blob: a811a23c6381a8f17b2bc232ab251733dd24b28b [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"}},
42 {kBPVendorIMG, {vendor_specific_img, "IMG"}}};
Attilio Provenzano19d6a982020-02-27 12:41:41 +000043
Hannes Harnisch607d1d92021-07-10 18:44:56 +020044const SpecialUseVUIDs kSpecialUseInstanceVUIDs {
45 kVUID_BestPractices_CreateInstance_SpecialUseExtension_CADSupport,
46 kVUID_BestPractices_CreateInstance_SpecialUseExtension_D3DEmulation,
47 kVUID_BestPractices_CreateInstance_SpecialUseExtension_DevTools,
48 kVUID_BestPractices_CreateInstance_SpecialUseExtension_Debugging,
49 kVUID_BestPractices_CreateInstance_SpecialUseExtension_GLEmulation,
50};
51
52const SpecialUseVUIDs kSpecialUseDeviceVUIDs {
53 kVUID_BestPractices_CreateDevice_SpecialUseExtension_CADSupport,
54 kVUID_BestPractices_CreateDevice_SpecialUseExtension_D3DEmulation,
55 kVUID_BestPractices_CreateDevice_SpecialUseExtension_DevTools,
56 kVUID_BestPractices_CreateDevice_SpecialUseExtension_Debugging,
57 kVUID_BestPractices_CreateDevice_SpecialUseExtension_GLEmulation,
58};
59
Jeremy Gebben20da7a12022-02-25 14:07:46 -070060ReadLockGuard BestPractices::ReadLock() {
61 if (fine_grained_locking) {
62 return ReadLockGuard(validation_object_mutex, std::defer_lock);
63 } else {
64 return ReadLockGuard(validation_object_mutex);
65 }
66}
67
68WriteLockGuard BestPractices::WriteLock() {
69 if (fine_grained_locking) {
70 return WriteLockGuard(validation_object_mutex, std::defer_lock);
71 } else {
72 return WriteLockGuard(validation_object_mutex);
73 }
74}
75
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -060076std::shared_ptr<CMD_BUFFER_STATE> BestPractices::CreateCmdBufferState(VkCommandBuffer cb,
77 const VkCommandBufferAllocateInfo* pCreateInfo,
Jeremy Gebbencd7fa282021-10-27 10:25:32 -060078 const COMMAND_POOL_STATE* pool) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -070079 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 -060080}
81
Jeremy Gebben20da7a12022-02-25 14:07:46 -070082bp_state::CommandBuffer::CommandBuffer(BestPractices* bp, VkCommandBuffer cb, const VkCommandBufferAllocateInfo* pCreateInfo,
83 const COMMAND_POOL_STATE* pool)
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -060084 : CMD_BUFFER_STATE(bp, cb, pCreateInfo, pool) {}
85
Attilio Provenzano19d6a982020-02-27 12:41:41 +000086bool BestPractices::VendorCheckEnabled(BPVendorFlags vendors) const {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -070087 for (const auto& vendor : kVendorInfo) {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060088 if (vendors & vendor.first && enabled[vendor.second.vendor_id]) {
Attilio Provenzano19d6a982020-02-27 12:41:41 +000089 return true;
90 }
91 }
92 return false;
93}
94
95const char* VendorSpecificTag(BPVendorFlags vendors) {
96 // Cache built vendor tags in a map
Jeremy Gebbencbf22862021-03-03 12:01:22 -070097 static layer_data::unordered_map<BPVendorFlags, std::string> tag_map;
Attilio Provenzano19d6a982020-02-27 12:41:41 +000098
99 auto res = tag_map.find(vendors);
100 if (res == tag_map.end()) {
101 // Build the vendor tag string
102 std::stringstream vendor_tag;
103
104 vendor_tag << "[";
105 bool first_vendor = true;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700106 for (const auto& vendor : kVendorInfo) {
Attilio Provenzano19d6a982020-02-27 12:41:41 +0000107 if (vendors & vendor.first) {
108 if (!first_vendor) {
109 vendor_tag << ", ";
110 }
111 vendor_tag << vendor.second.name;
112 first_vendor = false;
113 }
114 }
115 vendor_tag << "]";
116
117 tag_map[vendors] = vendor_tag.str();
118 res = tag_map.find(vendors);
119 }
120
121 return res->second.c_str();
122}
123
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700124const char* DepReasonToString(ExtDeprecationReason reason) {
125 switch (reason) {
126 case kExtPromoted:
127 return "promoted to";
128 break;
129 case kExtObsoleted:
130 return "obsoleted by";
131 break;
132 case kExtDeprecated:
133 return "deprecated by";
134 break;
135 default:
136 return "";
137 break;
138 }
139}
140
141bool BestPractices::ValidateDeprecatedExtensions(const char* api_name, const char* extension_name, uint32_t version,
142 const char* vuid) const {
143 bool skip = false;
144 auto dep_info_it = deprecated_extensions.find(extension_name);
145 if (dep_info_it != deprecated_extensions.end()) {
146 auto dep_info = dep_info_it->second;
Mark Lobodzinski6a149702020-05-14 12:21:34 -0600147 if (((dep_info.target.compare("VK_VERSION_1_1") == 0) && (version >= VK_API_VERSION_1_1)) ||
Tony-LunarGc30b59f2022-02-15 11:02:36 -0700148 ((dep_info.target.compare("VK_VERSION_1_2") == 0) && (version >= VK_API_VERSION_1_2)) ||
149 ((dep_info.target.compare("VK_VERSION_1_3") == 0) && (version >= VK_API_VERSION_1_3))) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700150 skip |=
151 LogWarning(instance, vuid, "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
152 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
Mark Lobodzinski6a149702020-05-14 12:21:34 -0600153 } else if (dep_info.target.find("VK_VERSION") == std::string::npos) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700154 if (dep_info.target.length() == 0) {
155 skip |= LogWarning(instance, vuid,
156 "%s(): Attempting to enable deprecated extension %s, but this extension has been deprecated "
157 "without replacement.",
158 api_name, extension_name);
159 } else {
160 skip |= LogWarning(instance, vuid,
161 "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
162 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
163 }
164 }
165 }
166 return skip;
167}
168
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200169bool BestPractices::ValidateSpecialUseExtensions(const char* api_name, const char* extension_name, const SpecialUseVUIDs& special_use_vuids) const
170{
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700171 bool skip = false;
172 auto dep_info_it = special_use_extensions.find(extension_name);
173
174 if (dep_info_it != special_use_extensions.end()) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200175 const char* const format = "%s(): Attempting to enable extension %s, but this extension is intended to support %s "
176 "and it is strongly recommended that it be otherwise avoided.";
177 auto& special_uses = dep_info_it->second;
sfricke-samsungef15e482022-01-26 11:32:49 -0800178
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700179 if (special_uses.find("cadsupport") != std::string::npos) {
sfricke-samsungef15e482022-01-26 11:32:49 -0800180 skip |= LogWarning(instance, special_use_vuids.cadsupport, format, api_name, extension_name,
181 "specialized functionality used by CAD/CAM applications");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700182 }
183 if (special_uses.find("d3demulation") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200184 skip |= LogWarning(instance, special_use_vuids.d3demulation, format, api_name, extension_name,
185 "D3D emulation layers, and applications ported from D3D, by adding functionality specific to D3D");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700186 }
187 if (special_uses.find("devtools") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200188 skip |= LogWarning(instance, special_use_vuids.devtools, format, api_name, extension_name,
189 "developer tools such as capture-replay libraries");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700190 }
191 if (special_uses.find("debugging") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200192 skip |= LogWarning(instance, special_use_vuids.debugging, format, api_name, extension_name,
193 "use by applications when debugging");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700194 }
195 if (special_uses.find("glemulation") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200196 skip |= LogWarning(instance, special_use_vuids.glemulation, format, api_name, extension_name,
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700197 "OpenGL and/or OpenGL ES emulation layers, and applications ported from those APIs, by adding functionality "
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200198 "specific to those APIs");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700199 }
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700200 }
201 return skip;
202}
203
Camden5b184be2019-08-13 07:50:19 -0600204bool BestPractices::PreCallValidateCreateInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500205 VkInstance* pInstance) const {
Camden5b184be2019-08-13 07:50:19 -0600206 bool skip = false;
207
208 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
209 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kDeviceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800210 skip |= LogWarning(instance, kVUID_BestPractices_CreateInstance_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700211 "vkCreateInstance(): Attempting to enable Device Extension %s at CreateInstance time.",
212 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600213 }
Mark Lobodzinski17d8dc62020-06-03 08:48:58 -0600214 uint32_t specified_version =
215 (pCreateInfo->pApplicationInfo ? pCreateInfo->pApplicationInfo->apiVersion : VK_API_VERSION_1_0);
216 skip |= ValidateDeprecatedExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i], specified_version,
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700217 kVUID_BestPractices_CreateInstance_DeprecatedExtension);
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200218 skip |= ValidateSpecialUseExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i], kSpecialUseInstanceVUIDs);
Camden5b184be2019-08-13 07:50:19 -0600219 }
220
221 return skip;
222}
223
Camden5b184be2019-08-13 07:50:19 -0600224bool BestPractices::PreCallValidateCreateDevice(VkPhysicalDevice physicalDevice, const VkDeviceCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500225 const VkAllocationCallbacks* pAllocator, VkDevice* pDevice) const {
Camden5b184be2019-08-13 07:50:19 -0600226 bool skip = false;
227
228 // get API version of physical device passed when creating device.
229 VkPhysicalDeviceProperties physical_device_properties{};
230 DispatchGetPhysicalDeviceProperties(physicalDevice, &physical_device_properties);
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500231 auto device_api_version = physical_device_properties.apiVersion;
Camden5b184be2019-08-13 07:50:19 -0600232
233 // check api versions and warn if instance api Version is higher than version on device.
Jeremy Gebben404f6ac2021-10-28 12:33:28 -0600234 if (api_version > device_api_version) {
235 std::string inst_api_name = StringAPIVersion(api_version);
Mark Lobodzinski60880782020-08-11 08:02:07 -0600236 std::string dev_api_name = StringAPIVersion(device_api_version);
Camden5b184be2019-08-13 07:50:19 -0600237
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700238 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_API_Mismatch,
239 "vkCreateDevice(): API Version of current instance, %s is higher than API Version on device, %s",
240 inst_api_name.c_str(), dev_api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -0600241 }
242
243 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
244 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kInstanceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800245 skip |= LogWarning(instance, kVUID_BestPractices_CreateDevice_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700246 "vkCreateDevice(): Attempting to enable Instance Extension %s at CreateDevice time.",
247 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600248 }
Jeremy Gebben404f6ac2021-10-28 12:33:28 -0600249 skip |= ValidateDeprecatedExtensions("CreateDevice", pCreateInfo->ppEnabledExtensionNames[i], api_version,
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700250 kVUID_BestPractices_CreateDevice_DeprecatedExtension);
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200251 skip |= ValidateSpecialUseExtensions("CreateDevice", pCreateInfo->ppEnabledExtensionNames[i], kSpecialUseDeviceVUIDs);
Camden5b184be2019-08-13 07:50:19 -0600252 }
253
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700254 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600255 if ((bp_pd_state->vkGetPhysicalDeviceFeaturesState == UNCALLED) && (pCreateInfo->pEnabledFeatures != NULL)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700256 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_PDFeaturesNotCalled,
257 "vkCreateDevice() called before getting physical device features from vkGetPhysicalDeviceFeatures().");
Camden83a9c372019-08-14 11:41:38 -0600258 }
259
LawG43f848c72022-02-23 09:35:21 +0000260 if ((VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorAMD) || VendorCheckEnabled(kBPVendorIMG)) &&
261 (pCreateInfo->pEnabledFeatures != nullptr) && (pCreateInfo->pEnabledFeatures->robustBufferAccess == VK_TRUE)) {
Szilard Papp7d2c7952020-06-22 14:38:13 +0100262 skip |= LogPerformanceWarning(
263 device, kVUID_BestPractices_CreateDevice_RobustBufferAccess,
LawG4015be1c2022-03-01 10:37:52 +0000264 "%s %s %s: vkCreateDevice() called with enabled robustBufferAccess. Use robustBufferAccess as a debugging tool during "
Szilard Papp7d2c7952020-06-22 14:38:13 +0100265 "development. Enabling it causes loss in performance for accesses to uniform buffers and shader storage "
266 "buffers. Disable robustBufferAccess in release builds. Only leave it enabled if the application use-case "
267 "requires the additional level of reliability due to the use of unverified user-supplied draw parameters.",
LawG43f848c72022-02-23 09:35:21 +0000268 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorAMD), VendorSpecificTag(kBPVendorIMG));
Szilard Papp7d2c7952020-06-22 14:38:13 +0100269 }
270
Camden5b184be2019-08-13 07:50:19 -0600271 return skip;
272}
273
274bool BestPractices::PreCallValidateCreateBuffer(VkDevice device, const VkBufferCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500275 const VkAllocationCallbacks* pAllocator, VkBuffer* pBuffer) const {
Camden5b184be2019-08-13 07:50:19 -0600276 bool skip = false;
277
278 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700279 std::stringstream buffer_hex;
280 buffer_hex << "0x" << std::hex << HandleToUint64(pBuffer);
Camden5b184be2019-08-13 07:50:19 -0600281
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700282 skip |= LogWarning(
283 device, kVUID_BestPractices_SharingModeExclusive,
284 "Warning: Buffer (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
285 "(queueFamilyIndexCount of %" PRIu32 ").",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700286 buffer_hex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600287 }
288
289 return skip;
290}
291
292bool BestPractices::PreCallValidateCreateImage(VkDevice device, const VkImageCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500293 const VkAllocationCallbacks* pAllocator, VkImage* pImage) const {
Camden5b184be2019-08-13 07:50:19 -0600294 bool skip = false;
295
296 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700297 std::stringstream image_hex;
298 image_hex << "0x" << std::hex << HandleToUint64(pImage);
Camden5b184be2019-08-13 07:50:19 -0600299
300 skip |=
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700301 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
302 "Warning: Image (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
303 "(queueFamilyIndexCount of %" PRIu32 ").",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700304 image_hex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600305 }
306
ziga-lunarg6df3d102022-03-18 17:02:14 +0100307 if ((pCreateInfo->flags & VK_IMAGE_CREATE_EXTENDED_USAGE_BIT) && !(pCreateInfo->flags & VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT)) {
308 skip |= LogWarning(device, kVUID_BestPractices_ImageCreateFlags,
309 "vkCreateImage(): pCreateInfo->flags has VK_IMAGE_CREATE_EXTENDED_USAGE_BIT set, but not "
310 "VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT, therefore image views created from this image will have to use the "
311 "same format and VK_IMAGE_CREATE_EXTENDED_USAGE_BIT will not have any effect.");
312 }
313
LawG4655f59c2022-02-23 13:55:55 +0000314 if (VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG)) {
Attilio Provenzano02859b22020-02-27 14:17:28 +0000315 if (pCreateInfo->samples > VK_SAMPLE_COUNT_1_BIT && !(pCreateInfo->usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT)) {
316 skip |= LogPerformanceWarning(
317 device, kVUID_BestPractices_CreateImage_NonTransientMSImage,
LawG4655f59c2022-02-23 13:55:55 +0000318 "%s %s vkCreateImage(): Trying to create a multisampled image, but createInfo.usage did not have "
Attilio Provenzano02859b22020-02-27 14:17:28 +0000319 "VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. Multisampled images may be resolved on-chip, "
320 "and do not need to be backed by physical storage. "
321 "TRANSIENT_ATTACHMENT allows tiled GPUs to not back the multisampled image with physical memory.",
LawG4655f59c2022-02-23 13:55:55 +0000322 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG));
Attilio Provenzano02859b22020-02-27 14:17:28 +0000323 }
324 }
325
LawG4ba113892022-02-23 14:39:02 +0000326 if (VendorCheckEnabled(kBPVendorArm) && pCreateInfo->samples > kMaxEfficientSamplesArm) {
327 skip |= LogPerformanceWarning(
328 device, kVUID_BestPractices_CreateImage_TooLargeSampleCount,
329 "%s vkCreateImage(): Trying to create an image with %u samples. "
330 "The hardware revision may not have full throughput for framebuffers with more than %u samples.",
331 VendorSpecificTag(kBPVendorArm), static_cast<uint32_t>(pCreateInfo->samples), kMaxEfficientSamplesArm);
332 }
333
334 if (VendorCheckEnabled(kBPVendorIMG) && pCreateInfo->samples > kMaxEfficientSamplesImg) {
335 skip |= LogPerformanceWarning(
336 device, kVUID_BestPractices_CreateImage_TooLargeSampleCount,
337 "%s vkCreateImage(): Trying to create an image with %u samples. "
338 "The device may not have full support for true multisampling for images with more than %u samples. "
339 "XT devices support up to 8 samples, XE up to 4 samples.",
340 VendorSpecificTag(kBPVendorIMG), static_cast<uint32_t>(pCreateInfo->samples), kMaxEfficientSamplesImg);
341 }
342
LawG4db16f802022-03-21 17:33:39 +0000343 if (VendorCheckEnabled(kBPVendorIMG) && (pCreateInfo->format == VK_FORMAT_PVRTC1_2BPP_SRGB_BLOCK_IMG ||
344 pCreateInfo->format == VK_FORMAT_PVRTC1_2BPP_UNORM_BLOCK_IMG ||
345 pCreateInfo->format == VK_FORMAT_PVRTC1_4BPP_SRGB_BLOCK_IMG ||
346 pCreateInfo->format == VK_FORMAT_PVRTC1_4BPP_UNORM_BLOCK_IMG ||
347 pCreateInfo->format == VK_FORMAT_PVRTC2_2BPP_SRGB_BLOCK_IMG ||
348 pCreateInfo->format == VK_FORMAT_PVRTC2_2BPP_UNORM_BLOCK_IMG ||
349 pCreateInfo->format == VK_FORMAT_PVRTC2_4BPP_SRGB_BLOCK_IMG ||
350 pCreateInfo->format == VK_FORMAT_PVRTC2_4BPP_UNORM_BLOCK_IMG)) {
351 skip |= LogPerformanceWarning(device, kVUID_BestPractices_Texture_Format_PVRTC_Outdated,
352 "%s vkCreateImage(): Trying to create an image with a PVRTC format. Both PVRTC1 and PVRTC2 "
353 "are slower than standard image formats on PowerVR GPUs, prefer ETC, BC, ASTC, etc.",
354 VendorSpecificTag(kBPVendorIMG));
355 }
356
Nadav Gevaf0808442021-05-21 13:51:25 -0400357 if (VendorCheckEnabled(kBPVendorAMD)) {
358 std::stringstream image_hex;
359 image_hex << "0x" << std::hex << HandleToUint64(pImage);
360
361 if ((pCreateInfo->usage & (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) &&
362 (pCreateInfo->sharingMode == VK_SHARING_MODE_CONCURRENT)) {
363 skip |= LogPerformanceWarning(device,
364 kVUID_BestPractices_vkImage_AvoidConcurrentRenderTargets,
365 "%s Performance warning: image (%s) is created as a render target with VK_SHARING_MODE_CONCURRENT. "
366 "Using a SHARING_MODE_CONCURRENT "
367 "is not recommended with color and depth targets",
368 VendorSpecificTag(kBPVendorAMD), image_hex.str().c_str());
369 }
370
371 if ((pCreateInfo->usage &
372 (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) &&
373 (pCreateInfo->flags & VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT)) {
374 skip |= LogPerformanceWarning(device, kVUID_BestPractices_vkImage_DontUseMutableRenderTargets,
375 "%s Performance warning: image (%s) is created as a render target with VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT. "
376 "Using a MUTABLE_FORMAT is not recommended with color, depth, and storage targets",
377 VendorSpecificTag(kBPVendorAMD), image_hex.str().c_str());
378 }
379
380 if ((pCreateInfo->usage & (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) &&
381 (pCreateInfo->usage & VK_IMAGE_USAGE_STORAGE_BIT)) {
382 skip |= LogPerformanceWarning(device, kVUID_BestPractices_vkImage_DontUseStorageRenderTargets,
383 "%s Performance warning: image (%s) is created as a render target with VK_IMAGE_USAGE_STORAGE_BIT. Using a "
384 "VK_IMAGE_USAGE_STORAGE_BIT is not recommended with color and depth targets",
385 VendorSpecificTag(kBPVendorAMD), image_hex.str().c_str());
386 }
387 }
388
Camden5b184be2019-08-13 07:50:19 -0600389 return skip;
390}
391
392bool BestPractices::PreCallValidateCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500393 const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain) const {
Camden5b184be2019-08-13 07:50:19 -0600394 bool skip = false;
395
Jeremy Gebben383b9a32021-09-08 16:31:33 -0600396 const auto* bp_pd_state = GetPhysicalDeviceState();
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600397 if (bp_pd_state) {
398 if (bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState == UNCALLED) {
399 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
400 "vkCreateSwapchainKHR() called before getting surface capabilities from "
401 "vkGetPhysicalDeviceSurfaceCapabilitiesKHR().");
402 }
Camden83a9c372019-08-14 11:41:38 -0600403
Shannon McPherson73e58c82021-03-05 17:14:26 -0700404 if ((pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR) &&
405 (bp_pd_state->vkGetPhysicalDeviceSurfacePresentModesKHRState != QUERY_DETAILS)) {
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600406 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
407 "vkCreateSwapchainKHR() called before getting surface present mode(s) from "
408 "vkGetPhysicalDeviceSurfacePresentModesKHR().");
409 }
Camden83a9c372019-08-14 11:41:38 -0600410
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600411 if (bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState != QUERY_DETAILS) {
412 skip |= LogWarning(
413 device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
414 "vkCreateSwapchainKHR() called before getting surface format(s) from vkGetPhysicalDeviceSurfaceFormatsKHR().");
415 }
Camden83a9c372019-08-14 11:41:38 -0600416 }
417
Camden5b184be2019-08-13 07:50:19 -0600418 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700419 skip |=
420 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
Mark Lobodzinski019f4e32020-04-13 11:01:35 -0600421 "Warning: A Swapchain is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while "
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700422 "specifying multiple queues (queueFamilyIndexCount of %" PRIu32 ").",
423 pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600424 }
425
ziga-lunarg79beba62022-03-30 01:17:30 +0200426 const auto present_mode = pCreateInfo->presentMode;
427 if (((present_mode == VK_PRESENT_MODE_MAILBOX_KHR) || (present_mode == VK_PRESENT_MODE_FIFO_KHR)) &&
428 (pCreateInfo->minImageCount == 2)) {
Szilard Papp48a6da32020-06-10 14:41:59 +0100429 skip |= LogPerformanceWarning(
430 device, kVUID_BestPractices_SuboptimalSwapchainImageCount,
431 "Warning: A Swapchain is being created with minImageCount set to %" PRIu32
432 ", which means double buffering is going "
433 "to be used. Using double buffering and vsync locks rendering to an integer fraction of the vsync rate. In turn, "
434 "reducing the performance of the application if rendering is slower than vsync. Consider setting minImageCount to "
435 "3 to use triple buffering to maximize performance in such cases.",
436 pCreateInfo->minImageCount);
437 }
438
Szilard Pappd5f0f812020-06-22 09:01:29 +0100439 if (VendorCheckEnabled(kBPVendorArm) && (pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR)) {
440 skip |= LogWarning(device, kVUID_BestPractices_CreateSwapchain_PresentMode,
441 "%s Warning: Swapchain is not being created with presentation mode \"VK_PRESENT_MODE_FIFO_KHR\". "
442 "Prefer using \"VK_PRESENT_MODE_FIFO_KHR\" to avoid unnecessary CPU and GPU load and save power. "
443 "Presentation modes which are not FIFO will present the latest available frame and discard other "
444 "frame(s) if any.",
445 VendorSpecificTag(kBPVendorArm));
446 }
447
Camden5b184be2019-08-13 07:50:19 -0600448 return skip;
449}
450
451bool BestPractices::PreCallValidateCreateSharedSwapchainsKHR(VkDevice device, uint32_t swapchainCount,
452 const VkSwapchainCreateInfoKHR* pCreateInfos,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500453 const VkAllocationCallbacks* pAllocator,
454 VkSwapchainKHR* pSwapchains) const {
Camden5b184be2019-08-13 07:50:19 -0600455 bool skip = false;
456
457 for (uint32_t i = 0; i < swapchainCount; i++) {
458 if ((pCreateInfos[i].queueFamilyIndexCount > 1) && (pCreateInfos[i].imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700459 skip |= LogWarning(
460 device, kVUID_BestPractices_SharingModeExclusive,
461 "Warning: A shared swapchain (index %" PRIu32
462 ") is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple "
463 "queues (queueFamilyIndexCount of %" PRIu32 ").",
464 i, pCreateInfos[i].queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600465 }
466 }
467
468 return skip;
469}
470
471bool BestPractices::PreCallValidateCreateRenderPass(VkDevice device, const VkRenderPassCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500472 const VkAllocationCallbacks* pAllocator, VkRenderPass* pRenderPass) const {
Camden5b184be2019-08-13 07:50:19 -0600473 bool skip = false;
474
475 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; ++i) {
476 VkFormat format = pCreateInfo->pAttachments[i].format;
477 if (pCreateInfo->pAttachments[i].initialLayout == VK_IMAGE_LAYOUT_UNDEFINED) {
478 if ((FormatIsColor(format) || FormatHasDepth(format)) &&
479 pCreateInfo->pAttachments[i].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700480 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
481 "Render pass has an attachment with loadOp == VK_ATTACHMENT_LOAD_OP_LOAD and "
482 "initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
483 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
484 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600485 }
486 if (FormatHasStencil(format) && pCreateInfo->pAttachments[i].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700487 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
488 "Render pass has an attachment with stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD "
489 "and initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
490 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
491 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600492 }
493 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000494
495 const auto& attachment = pCreateInfo->pAttachments[i];
496 if (attachment.samples > VK_SAMPLE_COUNT_1_BIT) {
497 bool access_requires_memory =
498 attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD || attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE;
499
500 if (FormatHasStencil(format)) {
501 access_requires_memory |= attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
502 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE;
503 }
504
505 if (access_requires_memory) {
506 skip |= LogPerformanceWarning(
507 device, kVUID_BestPractices_CreateRenderPass_ImageRequiresMemory,
508 "Attachment %u in the VkRenderPass is a multisampled image with %u samples, but it uses loadOp/storeOp "
509 "which requires accessing data from memory. Multisampled images should always be loadOp = CLEAR or DONT_CARE, "
510 "storeOp = DONT_CARE. This allows the implementation to use lazily allocated memory effectively.",
511 i, static_cast<uint32_t>(attachment.samples));
512 }
513 }
Camden5b184be2019-08-13 07:50:19 -0600514 }
515
516 for (uint32_t dependency = 0; dependency < pCreateInfo->dependencyCount; dependency++) {
517 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].srcStageMask);
518 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].dstStageMask);
519 }
520
521 return skip;
522}
523
Tony-LunarG767180f2020-04-23 14:03:59 -0600524bool BestPractices::ValidateAttachments(const VkRenderPassCreateInfo2* rpci, uint32_t attachmentCount,
525 const VkImageView* image_views) const {
526 bool skip = false;
527
528 // Check for non-transient attachments that should be transient and vice versa
529 for (uint32_t i = 0; i < attachmentCount; ++i) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200530 const auto& attachment = rpci->pAttachments[i];
Tony-LunarG767180f2020-04-23 14:03:59 -0600531 bool attachment_should_be_transient =
532 (attachment.loadOp != VK_ATTACHMENT_LOAD_OP_LOAD && attachment.storeOp != VK_ATTACHMENT_STORE_OP_STORE);
533
534 if (FormatHasStencil(attachment.format)) {
535 attachment_should_be_transient &= (attachment.stencilLoadOp != VK_ATTACHMENT_LOAD_OP_LOAD &&
536 attachment.stencilStoreOp != VK_ATTACHMENT_STORE_OP_STORE);
537 }
538
Jeremy Gebbenb20a8242021-11-05 15:14:43 -0600539 auto view_state = Get<IMAGE_VIEW_STATE>(image_views[i]);
Tony-LunarG767180f2020-04-23 14:03:59 -0600540 if (view_state) {
Jeremy Gebben057f9d52021-11-05 14:12:31 -0600541 const auto& ici = view_state->image_state->createInfo;
Tony-LunarG767180f2020-04-23 14:03:59 -0600542
543 bool image_is_transient = (ici.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) != 0;
544
545 // The check for an image that should not be transient applies to all GPUs
546 if (!attachment_should_be_transient && image_is_transient) {
547 skip |= LogPerformanceWarning(
548 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldNotBeTransient,
549 "Attachment %u in VkFramebuffer uses loadOp/storeOps which need to access physical memory, "
550 "but the image backing the image view has VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
551 "Physical memory will need to be backed lazily to this image, potentially causing stalls.",
552 i);
553 }
554
555 bool supports_lazy = false;
556 for (uint32_t j = 0; j < phys_dev_mem_props.memoryTypeCount; j++) {
557 if (phys_dev_mem_props.memoryTypes[j].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
558 supports_lazy = true;
559 }
560 }
561
562 // The check for an image that should be transient only applies to GPUs supporting
563 // lazily allocated memory
564 if (supports_lazy && attachment_should_be_transient && !image_is_transient) {
565 skip |= LogPerformanceWarning(
566 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldBeTransient,
567 "Attachment %u in VkFramebuffer uses loadOp/storeOps which never have to be backed by physical memory, "
568 "but the image backing the image view does not have VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
569 "You can save physical memory by using transient attachment backed by lazily allocated memory here.",
570 i);
571 }
572 }
573 }
574 return skip;
575}
576
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000577bool BestPractices::PreCallValidateCreateFramebuffer(VkDevice device, const VkFramebufferCreateInfo* pCreateInfo,
578 const VkAllocationCallbacks* pAllocator, VkFramebuffer* pFramebuffer) const {
579 bool skip = false;
580
Jeremy Gebbenb20a8242021-11-05 15:14:43 -0600581 auto rp_state = Get<RENDER_PASS_STATE>(pCreateInfo->renderPass);
Mike Schuchardt2df08912020-12-15 16:28:09 -0800582 if (rp_state && !(pCreateInfo->flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT)) {
Tony-LunarG767180f2020-04-23 14:03:59 -0600583 skip = ValidateAttachments(rp_state->createInfo.ptr(), pCreateInfo->attachmentCount, pCreateInfo->pAttachments);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000584 }
585
586 return skip;
587}
588
Sam Wallse746d522020-03-16 21:20:23 +0000589bool BestPractices::PreCallValidateAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
590 VkDescriptorSet* pDescriptorSets, void* ads_state_data) const {
591 bool skip = false;
592 skip |= ValidationStateTracker::PreCallValidateAllocateDescriptorSets(device, pAllocateInfo, pDescriptorSets, ads_state_data);
593
594 if (!skip) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700595 const auto pool_state = Get<bp_state::DescriptorPool>(pAllocateInfo->descriptorPool);
Sam Wallse746d522020-03-16 21:20:23 +0000596 // if the number of freed sets > 0, it implies they could be recycled instead if desirable
597 // this warning is specific to Arm
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700598 if (VendorCheckEnabled(kBPVendorArm) && pool_state && (pool_state->freed_count > 0)) {
Sam Wallse746d522020-03-16 21:20:23 +0000599 skip |= LogPerformanceWarning(
600 device, kVUID_BestPractices_AllocateDescriptorSets_SuboptimalReuse,
601 "%s Descriptor set memory was allocated via vkAllocateDescriptorSets() for sets which were previously freed in the "
602 "same logical device. On some drivers or architectures it may be most optimal to re-use existing descriptor sets.",
603 VendorSpecificTag(kBPVendorArm));
604 }
605 }
606
607 return skip;
608}
609
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600610void BestPractices::ManualPostCallRecordAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
611 VkDescriptorSet* pDescriptorSets, VkResult result, void* ads_state) {
Sam Wallse746d522020-03-16 21:20:23 +0000612 if (result == VK_SUCCESS) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700613 auto pool_state = Get<bp_state::DescriptorPool>(pAllocateInfo->descriptorPool);
614 if (pool_state) {
Sam Wallse746d522020-03-16 21:20:23 +0000615 // we record successful allocations by subtracting the allocation count from the last recorded free count
616 const auto alloc_count = pAllocateInfo->descriptorSetCount;
617 // clamp the unsigned subtraction to the range [0, last_free_count]
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700618 if (pool_state->freed_count > alloc_count) {
619 pool_state->freed_count -= alloc_count;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700620 } else {
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700621 pool_state->freed_count = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700622 }
Sam Wallse746d522020-03-16 21:20:23 +0000623 }
624 }
625}
626
627void BestPractices::PostCallRecordFreeDescriptorSets(VkDevice device, VkDescriptorPool descriptorPool, uint32_t descriptorSetCount,
628 const VkDescriptorSet* pDescriptorSets, VkResult result) {
629 ValidationStateTracker::PostCallRecordFreeDescriptorSets(device, descriptorPool, descriptorSetCount, pDescriptorSets, result);
630 if (result == VK_SUCCESS) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700631 auto pool_state = Get<bp_state::DescriptorPool>(descriptorPool);
Sam Wallse746d522020-03-16 21:20:23 +0000632 // we want to track frees because we're interested in suggesting re-use
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700633 if (pool_state) {
634 pool_state->freed_count += descriptorSetCount;
Sam Wallse746d522020-03-16 21:20:23 +0000635 }
636 }
637}
638
Camden5b184be2019-08-13 07:50:19 -0600639bool BestPractices::PreCallValidateAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500640 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory) const {
Camden5b184be2019-08-13 07:50:19 -0600641 bool skip = false;
642
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700643 if ((Count<DEVICE_MEMORY_STATE>() + 1) > kMemoryObjectWarningLimit) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700644 skip |= LogPerformanceWarning(device, kVUID_BestPractices_AllocateMemory_TooManyObjects,
645 "Performance Warning: This app has > %" PRIu32 " memory objects.", kMemoryObjectWarningLimit);
Camden5b184be2019-08-13 07:50:19 -0600646 }
647
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000648 if (pAllocateInfo->allocationSize < kMinDeviceAllocationSize) {
649 skip |= LogPerformanceWarning(
650 device, kVUID_BestPractices_AllocateMemory_SmallAllocation,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600651 "vkAllocateMemory(): Allocating a VkDeviceMemory of size %" PRIu64 ". This is a very small allocation (current "
652 "threshold is %" PRIu64 " bytes). "
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000653 "You should make large allocations and sub-allocate from one large VkDeviceMemory.",
654 pAllocateInfo->allocationSize, kMinDeviceAllocationSize);
655 }
656
Camden83a9c372019-08-14 11:41:38 -0600657 // TODO: Insert get check for GetPhysicalDeviceMemoryProperties once the state is tracked in the StateTracker
658
659 return skip;
660}
661
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600662void BestPractices::ManualPostCallRecordAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
663 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory,
664 VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700665 if (result != VK_SUCCESS) {
666 static std::vector<VkResult> error_codes = {VK_ERROR_OUT_OF_HOST_MEMORY, VK_ERROR_OUT_OF_DEVICE_MEMORY,
667 VK_ERROR_TOO_MANY_OBJECTS, VK_ERROR_INVALID_EXTERNAL_HANDLE,
Mike Schuchardt2df08912020-12-15 16:28:09 -0800668 VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS};
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700669 static std::vector<VkResult> success_codes = {};
Nathaniel Cesariodb3f43f2021-05-12 09:08:23 -0600670 ValidateReturnCodes("vkAllocateMemory", result, error_codes, success_codes);
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700671 return;
672 }
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700673}
Camden Stocker9738af92019-10-16 13:54:03 -0700674
Mark Lobodzinskide15e582020-04-29 08:06:00 -0600675void BestPractices::ValidateReturnCodes(const char* api_name, VkResult result, const std::vector<VkResult>& error_codes,
676 const std::vector<VkResult>& success_codes) const {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700677 auto error = std::find(error_codes.begin(), error_codes.end(), result);
678 if (error != error_codes.end()) {
Gareth Webb586c46b2021-01-13 11:17:22 +0000679 static const std::vector<VkResult> common_failure_codes = {VK_ERROR_OUT_OF_DATE_KHR,
680 VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT};
681
682 auto common_failure = std::find(common_failure_codes.begin(), common_failure_codes.end(), result);
683 if (common_failure != common_failure_codes.end()) {
684 LogInfo(instance, kVUID_BestPractices_Failure_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
685 } else {
686 LogWarning(instance, kVUID_BestPractices_Error_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
687 }
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700688 return;
689 }
690 auto success = std::find(success_codes.begin(), success_codes.end(), result);
691 if (success != success_codes.end()) {
Mark Lobodzinskie7215152020-05-11 08:21:23 -0600692 LogInfo(instance, kVUID_BestPractices_NonSuccess_Result, "%s(): Returned non-success return code %s.", api_name,
693 string_VkResult(result));
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500694 }
695}
696
Jeff Bolz5c801d12019-10-09 10:38:45 -0500697bool BestPractices::PreCallValidateFreeMemory(VkDevice device, VkDeviceMemory memory,
698 const VkAllocationCallbacks* pAllocator) const {
Mark Lobodzinski91e50bf2020-01-14 09:55:11 -0700699 if (memory == VK_NULL_HANDLE) return false;
Camden83a9c372019-08-14 11:41:38 -0600700 bool skip = false;
701
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700702 auto mem_info = Get<DEVICE_MEMORY_STATE>(memory);
Camden83a9c372019-08-14 11:41:38 -0600703
Jeremy Gebben610d3a62022-01-01 12:53:17 -0700704 for (const auto& item : mem_info->ObjectBindings()) {
705 const auto& obj = item.first;
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600706 LogObjectList objlist(device);
707 objlist.add(obj);
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -0600708 objlist.add(mem_info->mem());
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600709 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 -0600710 report_data->FormatHandle(obj).c_str(), report_data->FormatHandle(mem_info->mem()).c_str());
Camden83a9c372019-08-14 11:41:38 -0600711 }
712
Camden5b184be2019-08-13 07:50:19 -0600713 return skip;
714}
715
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000716bool BestPractices::ValidateBindBufferMemory(VkBuffer buffer, VkDeviceMemory memory, const char* api_name) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600717 bool skip = false;
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700718 auto buffer_state = Get<BUFFER_STATE>(buffer);
Camden Stockerb603cc82019-09-03 10:09:02 -0600719
sfricke-samsunge2441192019-11-06 14:07:57 -0800720 if (!buffer_state->memory_requirements_checked && !buffer_state->external_memory_handle) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700721 skip |= LogWarning(device, kVUID_BestPractices_BufferMemReqNotCalled,
722 "%s: Binding memory to %s but vkGetBufferMemoryRequirements() has not been called on that buffer.",
723 api_name, report_data->FormatHandle(buffer).c_str());
Camden Stockerb603cc82019-09-03 10:09:02 -0600724 }
725
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700726 auto mem_state = Get<DEVICE_MEMORY_STATE>(memory);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000727
AndreyVK_D3D0416a332021-11-02 23:22:28 +0300728 if (mem_state && mem_state->alloc_info.allocationSize == buffer_state->createInfo.size &&
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000729 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
730 skip |= LogPerformanceWarning(
731 device, kVUID_BestPractices_SmallDedicatedAllocation,
732 "%s: Trying to bind %s to a memory block which is fully consumed by the buffer. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600733 "The required size of the allocation is %" PRIu64 ", but smaller buffers like this should be sub-allocated from "
734 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000735 api_name, report_data->FormatHandle(buffer).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
736 }
737
Camden Stockerb603cc82019-09-03 10:09:02 -0600738 return skip;
739}
740
741bool BestPractices::PreCallValidateBindBufferMemory(VkDevice device, VkBuffer buffer, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500742 VkDeviceSize memoryOffset) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600743 bool skip = false;
744 const char* api_name = "BindBufferMemory()";
745
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000746 skip |= ValidateBindBufferMemory(buffer, memory, api_name);
Camden Stockerb603cc82019-09-03 10:09:02 -0600747
748 return skip;
749}
750
751bool BestPractices::PreCallValidateBindBufferMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500752 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600753 char api_name[64];
754 bool skip = false;
755
756 for (uint32_t i = 0; i < bindInfoCount; i++) {
757 sprintf(api_name, "vkBindBufferMemory2() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000758 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600759 }
760
761 return skip;
762}
Camden Stockerb603cc82019-09-03 10:09:02 -0600763
764bool BestPractices::PreCallValidateBindBufferMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500765 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600766 char api_name[64];
767 bool skip = false;
Camden Stockerb603cc82019-09-03 10:09:02 -0600768
Camden Stocker8b798ab2019-09-03 10:33:28 -0600769 for (uint32_t i = 0; i < bindInfoCount; i++) {
770 sprintf(api_name, "vkBindBufferMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000771 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600772 }
773
774 return skip;
775}
776
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000777bool BestPractices::ValidateBindImageMemory(VkImage image, VkDeviceMemory memory, const char* api_name) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600778 bool skip = false;
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700779 auto image_state = Get<IMAGE_STATE>(image);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600780
sfricke-samsung71bc6572020-04-29 15:49:43 -0700781 if (image_state->disjoint == false) {
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600782 if (!image_state->memory_requirements_checked[0] && !image_state->external_memory_handle) {
sfricke-samsungd7ea5de2020-04-08 09:19:18 -0700783 skip |= LogWarning(device, kVUID_BestPractices_ImageMemReqNotCalled,
784 "%s: Binding memory to %s but vkGetImageMemoryRequirements() has not been called on that image.",
785 api_name, report_data->FormatHandle(image).c_str());
786 }
787 } else {
788 // TODO If binding disjoint image then this needs to check that VkImagePlaneMemoryRequirementsInfo was called for each
789 // plane.
Camden Stocker8b798ab2019-09-03 10:33:28 -0600790 }
791
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700792 auto mem_state = Get<DEVICE_MEMORY_STATE>(memory);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000793
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600794 if (mem_state->alloc_info.allocationSize == image_state->requirements[0].size &&
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000795 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
796 skip |= LogPerformanceWarning(
797 device, kVUID_BestPractices_SmallDedicatedAllocation,
798 "%s: Trying to bind %s to a memory block which is fully consumed by the image. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600799 "The required size of the allocation is %" PRIu64 ", but smaller images like this should be sub-allocated from "
800 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000801 api_name, report_data->FormatHandle(image).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
802 }
803
804 // If we're binding memory to a image which was created as TRANSIENT and the image supports LAZY allocation,
805 // make sure this type is actually used.
806 // This warning will only trigger if this layer is run on a platform that supports LAZILY_ALLOCATED_BIT
807 // (i.e.most tile - based renderers)
808 if (image_state->createInfo.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) {
809 bool supports_lazy = false;
810 uint32_t suggested_type = 0;
811
812 for (uint32_t i = 0; i < phys_dev_mem_props.memoryTypeCount; i++) {
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600813 if ((1u << i) & image_state->requirements[0].memoryTypeBits) {
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000814 if (phys_dev_mem_props.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
815 supports_lazy = true;
816 suggested_type = i;
817 break;
818 }
819 }
820 }
821
822 uint32_t allocated_properties = phys_dev_mem_props.memoryTypes[mem_state->alloc_info.memoryTypeIndex].propertyFlags;
823
824 if (supports_lazy && (allocated_properties & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) == 0) {
825 skip |= LogPerformanceWarning(
826 device, kVUID_BestPractices_NonLazyTransientImage,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600827 "%s: Attempting to bind memory type %u to VkImage which was created with TRANSIENT_ATTACHMENT_BIT,"
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000828 "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 -0600829 "%" PRIu64 " bytes of physical memory.",
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600830 api_name, mem_state->alloc_info.memoryTypeIndex, suggested_type, image_state->requirements[0].size);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000831 }
832 }
833
Camden Stocker8b798ab2019-09-03 10:33:28 -0600834 return skip;
835}
836
837bool BestPractices::PreCallValidateBindImageMemory(VkDevice device, VkImage image, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500838 VkDeviceSize memoryOffset) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600839 bool skip = false;
840 const char* api_name = "vkBindImageMemory()";
841
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000842 skip |= ValidateBindImageMemory(image, memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600843
844 return skip;
845}
846
847bool BestPractices::PreCallValidateBindImageMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500848 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600849 char api_name[64];
850 bool skip = false;
851
852 for (uint32_t i = 0; i < bindInfoCount; i++) {
853 sprintf(api_name, "vkBindImageMemory2() pBindInfos[%u]", i);
Mark Lobodzinski1f887d32020-12-30 15:31:33 -0700854 if (!LvlFindInChain<VkBindImageMemorySwapchainInfoKHR>(pBindInfos[i].pNext)) {
Tony-LunarG5e60b852020-04-27 11:27:54 -0600855 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
856 }
Camden Stocker8b798ab2019-09-03 10:33:28 -0600857 }
858
859 return skip;
860}
861
862bool BestPractices::PreCallValidateBindImageMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500863 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600864 char api_name[64];
865 bool skip = false;
866
867 for (uint32_t i = 0; i < bindInfoCount; i++) {
868 sprintf(api_name, "vkBindImageMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000869 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600870 }
871
872 return skip;
873}
Camden83a9c372019-08-14 11:41:38 -0600874
Attilio Provenzano02859b22020-02-27 14:17:28 +0000875static inline bool FormatHasFullThroughputBlendingArm(VkFormat format) {
876 switch (format) {
877 case VK_FORMAT_B10G11R11_UFLOAT_PACK32:
878 case VK_FORMAT_R16_SFLOAT:
879 case VK_FORMAT_R16G16_SFLOAT:
880 case VK_FORMAT_R16G16B16_SFLOAT:
881 case VK_FORMAT_R16G16B16A16_SFLOAT:
882 case VK_FORMAT_R32_SFLOAT:
883 case VK_FORMAT_R32G32_SFLOAT:
884 case VK_FORMAT_R32G32B32_SFLOAT:
885 case VK_FORMAT_R32G32B32A32_SFLOAT:
886 return false;
887
888 default:
889 return true;
890 }
891}
892
893bool BestPractices::ValidateMultisampledBlendingArm(uint32_t createInfoCount,
894 const VkGraphicsPipelineCreateInfo* pCreateInfos) const {
895 bool skip = false;
896
897 for (uint32_t i = 0; i < createInfoCount; i++) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700898 auto create_info = &pCreateInfos[i];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000899
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700900 if (!create_info->pColorBlendState || !create_info->pMultisampleState ||
901 create_info->pMultisampleState->rasterizationSamples == VK_SAMPLE_COUNT_1_BIT ||
902 create_info->pMultisampleState->sampleShadingEnable) {
Attilio Provenzano02859b22020-02-27 14:17:28 +0000903 return skip;
904 }
905
Jeremy Gebbenb20a8242021-11-05 15:14:43 -0600906 auto rp_state = Get<RENDER_PASS_STATE>(create_info->renderPass);
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200907 const auto& subpass = rp_state->createInfo.pSubpasses[create_info->subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000908
Hans-Kristian Arntzenc2742e72021-07-01 14:31:06 +0200909 // According to spec, pColorBlendState must be ignored if subpass does not have color attachments.
910 uint32_t num_color_attachments = std::min(subpass.colorAttachmentCount, create_info->pColorBlendState->attachmentCount);
911
912 for (uint32_t j = 0; j < num_color_attachments; j++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200913 const auto& blend_att = create_info->pColorBlendState->pAttachments[j];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000914 uint32_t att = subpass.pColorAttachments[j].attachment;
915
916 if (att != VK_ATTACHMENT_UNUSED && blend_att.blendEnable && blend_att.colorWriteMask) {
917 if (!FormatHasFullThroughputBlendingArm(rp_state->createInfo.pAttachments[att].format)) {
918 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultisampledBlending,
919 "%s vkCreateGraphicsPipelines() - createInfo #%u: Pipeline is multisampled and "
920 "color attachment #%u makes use "
921 "of a format which cannot be blended at full throughput when using MSAA.",
922 VendorSpecificTag(kBPVendorArm), i, j);
923 }
924 }
925 }
926 }
927
928 return skip;
929}
930
Nadav Gevaf0808442021-05-21 13:51:25 -0400931void BestPractices::ManualPostCallRecordCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
932 const VkComputePipelineCreateInfo* pCreateInfos,
933 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
934 VkResult result, void* pipe_state) {
935 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700936 pipeline_cache_ = pipelineCache;
Nadav Gevaf0808442021-05-21 13:51:25 -0400937}
938
Camden5b184be2019-08-13 07:50:19 -0600939bool BestPractices::PreCallValidateCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
940 const VkGraphicsPipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -0600941 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500942 void* cgpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -0600943 bool skip = StateTracker::PreCallValidateCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos,
944 pAllocator, pPipelines, cgpl_state_data);
ziga-lunarg08c81582022-03-08 17:33:45 +0100945 if (skip) {
946 return skip;
947 }
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600948 create_graphics_pipeline_api_state* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
Camden5b184be2019-08-13 07:50:19 -0600949
950 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700951 skip |= LogPerformanceWarning(
952 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
953 "Performance Warning: This vkCreateGraphicsPipelines call is creating multiple pipelines but is not using a "
954 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -0600955 }
956
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000957 for (uint32_t i = 0; i < createInfoCount; i++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200958 const auto& create_info = pCreateInfos[i];
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000959
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600960 if (!(cgpl_state->pipe_state[i]->active_shaders & VK_SHADER_STAGE_MESH_BIT_NV)) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200961 const auto& vertex_input = *create_info.pVertexInputState;
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600962 uint32_t count = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700963 for (uint32_t j = 0; j < vertex_input.vertexBindingDescriptionCount; j++) {
964 if (vertex_input.pVertexBindingDescriptions[j].inputRate == VK_VERTEX_INPUT_RATE_INSTANCE) {
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600965 count++;
966 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000967 }
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600968 if (count > kMaxInstancedVertexBuffers) {
969 skip |= LogPerformanceWarning(
970 device, kVUID_BestPractices_CreatePipelines_TooManyInstancedVertexBuffers,
971 "The pipeline is using %u instanced vertex buffers (current limit: %u), but this can be inefficient on the "
972 "GPU. If using instanced vertex attributes prefer interleaving them in a single buffer.",
973 count, kMaxInstancedVertexBuffers);
974 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000975 }
Attilio Provenzano02859b22020-02-27 14:17:28 +0000976
Szilard Pappaaf2da32020-06-22 10:37:35 +0100977 if ((pCreateInfos[i].pRasterizationState->depthBiasEnable) &&
978 (pCreateInfos[i].pRasterizationState->depthBiasConstantFactor == 0.0f) &&
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +0200979 (pCreateInfos[i].pRasterizationState->depthBiasSlopeFactor == 0.0f) &&
980 VendorCheckEnabled(kBPVendorArm)) {
981 skip |= LogPerformanceWarning(
982 device, kVUID_BestPractices_CreatePipelines_DepthBias_Zero,
983 "%s Performance Warning: This vkCreateGraphicsPipelines call is created with depthBiasEnable set to true "
984 "and both depthBiasConstantFactor and depthBiasSlopeFactor are set to 0. This can cause reduced "
985 "efficiency during rasterization. Consider disabling depthBias or increasing either "
986 "depthBiasConstantFactor or depthBiasSlopeFactor.",
987 VendorSpecificTag(kBPVendorArm));
Szilard Pappaaf2da32020-06-22 10:37:35 +0100988 }
989
Attilio Provenzano02859b22020-02-27 14:17:28 +0000990 skip |= VendorCheckEnabled(kBPVendorArm) && ValidateMultisampledBlendingArm(createInfoCount, pCreateInfos);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000991 }
Nadav Gevaf0808442021-05-21 13:51:25 -0400992 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700993 auto prev_pipeline = pipeline_cache_.load();
994 if (pipelineCache && prev_pipeline && pipelineCache != prev_pipeline) {
Nadav Gevaf0808442021-05-21 13:51:25 -0400995 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultiplePipelineCaches,
996 "%s Performance Warning: A second pipeline cache is in use. Consider using only one pipeline cache to "
997 "improve cache hit rate", VendorSpecificTag(kBPVendorAMD));
998 }
999
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001000 if (num_pso_ > kMaxRecommendedNumberOfPSOAMD) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001001 skip |=
1002 LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_TooManyPipelines,
1003 "%s Performance warning: Too many pipelines created, consider consolidation",
1004 VendorSpecificTag(kBPVendorAMD));
1005 }
1006
Nathaniel Cesario1a7e1a92021-08-30 14:34:20 -06001007 if (pCreateInfos->pInputAssemblyState && pCreateInfos->pInputAssemblyState->primitiveRestartEnable) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001008 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_AvoidPrimitiveRestart,
1009 "%s Performance warning: Use of primitive restart is not recommended",
1010 VendorSpecificTag(kBPVendorAMD));
1011 }
1012
1013 // TODO: this might be too aggressive of a check
1014 if (pCreateInfos->pDynamicState && pCreateInfos->pDynamicState->dynamicStateCount > kDynamicStatesWarningLimitAMD) {
1015 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MinimizeNumDynamicStates,
1016 "%s Performance warning: Dynamic States usage incurs a performance cost. Ensure that they are truly needed",
1017 VendorSpecificTag(kBPVendorAMD));
1018 }
1019 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001020
Camden5b184be2019-08-13 07:50:19 -06001021 return skip;
1022}
1023
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001024static std::vector<bp_state::AttachmentInfo> GetAttachmentAccess(const safe_VkGraphicsPipelineCreateInfo& create_info,
1025 std::shared_ptr<const RENDER_PASS_STATE>& rp) {
1026 std::vector<bp_state::AttachmentInfo> result;
Tony-LunarG5e1dbcd2022-03-29 08:19:58 -06001027 if (!rp || rp->use_dynamic_rendering || rp->use_dynamic_rendering_inherited) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001028 return result;
Hans-Kristian Arntzenb033ab12021-06-16 11:16:59 +02001029 }
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001030
1031 const auto& subpass = rp->createInfo.pSubpasses[create_info.subpass];
1032
1033 // NOTE: see PIPELINE_LAYOUT and safe_VkGraphicsPipelineCreateInfo constructors. pColorBlendState and pDepthStencilState
1034 // are only non-null if they are enabled.
1035 if (create_info.pColorBlendState) {
1036 // According to spec, pColorBlendState must be ignored if subpass does not have color attachments.
1037 uint32_t num_color_attachments = std::min(subpass.colorAttachmentCount, create_info.pColorBlendState->attachmentCount);
1038 for (uint32_t j = 0; j < num_color_attachments; j++) {
1039 if (create_info.pColorBlendState->pAttachments[j].colorWriteMask != 0) {
1040 uint32_t attachment = subpass.pColorAttachments[j].attachment;
1041 if (attachment != VK_ATTACHMENT_UNUSED) {
1042 result.push_back({attachment, VK_IMAGE_ASPECT_COLOR_BIT});
1043 }
1044 }
1045 }
1046 }
1047
1048 if (create_info.pDepthStencilState &&
1049 (create_info.pDepthStencilState->depthTestEnable || create_info.pDepthStencilState->depthBoundsTestEnable ||
1050 create_info.pDepthStencilState->stencilTestEnable)) {
1051 uint32_t attachment = subpass.pDepthStencilAttachment ? subpass.pDepthStencilAttachment->attachment : VK_ATTACHMENT_UNUSED;
1052 if (attachment != VK_ATTACHMENT_UNUSED) {
1053 VkImageAspectFlags aspects = 0;
1054 if (create_info.pDepthStencilState->depthTestEnable || create_info.pDepthStencilState->depthBoundsTestEnable) {
1055 aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
1056 }
1057 if (create_info.pDepthStencilState->stencilTestEnable) {
1058 aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
1059 }
1060 result.push_back({attachment, aspects});
1061 }
1062 }
1063 return result;
1064}
1065
1066bp_state::Pipeline::Pipeline(const ValidationStateTracker* state_data, const VkGraphicsPipelineCreateInfo* pCreateInfo,
1067 std::shared_ptr<const RENDER_PASS_STATE>&& rpstate,
1068 std::shared_ptr<const PIPELINE_LAYOUT_STATE>&& layout)
1069 : PIPELINE_STATE(state_data, pCreateInfo, std::move(rpstate), std::move(layout)),
1070 access_framebuffer_attachments(GetAttachmentAccess(create_info.graphics, rp_state)) {}
1071
1072std::shared_ptr<PIPELINE_STATE> BestPractices::CreateGraphicsPipelineState(
1073 const VkGraphicsPipelineCreateInfo* pCreateInfo, std::shared_ptr<const RENDER_PASS_STATE>&& render_pass,
1074 std::shared_ptr<const PIPELINE_LAYOUT_STATE>&& layout) const {
1075 return std::static_pointer_cast<PIPELINE_STATE>(
1076 std::make_shared<bp_state::Pipeline>(this, pCreateInfo, std::move(render_pass), std::move(layout)));
Hans-Kristian Arntzenb033ab12021-06-16 11:16:59 +02001077}
1078
Sam Walls0961ec02020-03-31 16:39:15 +01001079void BestPractices::ManualPostCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t count,
1080 const VkGraphicsPipelineCreateInfo* pCreateInfos,
1081 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
1082 VkResult result, void* cgpl_state_data) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001083 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001084 pipeline_cache_ = pipelineCache;
Sam Walls0961ec02020-03-31 16:39:15 +01001085}
1086
Camden5b184be2019-08-13 07:50:19 -06001087bool BestPractices::PreCallValidateCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
1088 const VkComputePipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -06001089 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001090 void* ccpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -06001091 bool skip = StateTracker::PreCallValidateCreateComputePipelines(device, pipelineCache, createInfoCount, pCreateInfos,
1092 pAllocator, pPipelines, ccpl_state_data);
Camden5b184be2019-08-13 07:50:19 -06001093
1094 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001095 skip |= LogPerformanceWarning(
1096 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
1097 "Performance Warning: This vkCreateComputePipelines call is creating multiple pipelines but is not using a "
1098 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -06001099 }
1100
Nadav Gevaf0808442021-05-21 13:51:25 -04001101 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001102 auto prev_pipeline = pipeline_cache_.load();
1103 if (pipelineCache && prev_pipeline && pipelineCache != prev_pipeline) {
1104 skip |= LogPerformanceWarning(
1105 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
1106 "%s Performance Warning: A second pipeline cache is in use. Consider using only one pipeline cache to "
Nadav Gevaf0808442021-05-21 13:51:25 -04001107 "improve cache hit rate",
1108 VendorSpecificTag(kBPVendorAMD));
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001109 }
1110 }
Nadav Gevaf0808442021-05-21 13:51:25 -04001111
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001112 for (uint32_t i = 0; i < createInfoCount; i++) {
1113 const VkComputePipelineCreateInfo& createInfo = pCreateInfos[i];
1114 if (VendorCheckEnabled(kBPVendorArm)) {
1115 skip |= ValidateCreateComputePipelineArm(createInfo);
1116 }
sfricke-samsung86d055a2022-02-11 14:43:50 -08001117
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001118 if (IsExtEnabled(device_extensions.vk_khr_maintenance4)) {
1119 auto module_state = Get<SHADER_MODULE_STATE>(createInfo.stage.module);
1120 for (const auto& builtin : module_state->static_data_.builtin_decoration_list) {
1121 if (builtin.builtin == spv::BuiltInWorkgroupSize) {
1122 skip |= LogWarning(device, kVUID_BestPractices_SpirvDeprecated_WorkgroupSize,
1123 "vkCreateComputePipelines(): pCreateInfos[ %" PRIu32
1124 "] is using the Workgroup built-in which SPIR-V 1.6 deprecated. The VK_KHR_maintenance4 "
1125 "extension exposes a new LocalSizeId execution mode that should be used instead.",
1126 i);
sfricke-samsung86d055a2022-02-11 14:43:50 -08001127 }
1128 }
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001129 }
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001130 }
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001131
1132 return skip;
1133}
1134
1135bool BestPractices::ValidateCreateComputePipelineArm(const VkComputePipelineCreateInfo& createInfo) const {
1136 bool skip = false;
sfricke-samsungef15e482022-01-26 11:32:49 -08001137 auto module_state = Get<SHADER_MODULE_STATE>(createInfo.stage.module);
sfricke-samsung8a7341a2021-02-28 07:30:21 -08001138 // Generate warnings about work group sizes based on active resources.
sfricke-samsungef15e482022-01-26 11:32:49 -08001139 auto entrypoint = module_state->FindEntrypoint(createInfo.stage.pName, createInfo.stage.stage);
1140 if (entrypoint == module_state->end()) return false;
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001141
1142 uint32_t x = 1, y = 1, z = 1;
sfricke-samsungef15e482022-01-26 11:32:49 -08001143 module_state->FindLocalSize(entrypoint, x, y, z);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001144
1145 uint32_t thread_count = x * y * z;
1146
1147 // Generate a priori warnings about work group sizes.
1148 if (thread_count > kMaxEfficientWorkGroupThreadCountArm) {
1149 skip |= LogPerformanceWarning(
1150 device, kVUID_BestPractices_CreateComputePipelines_ComputeWorkGroupSize,
1151 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, %u, "
1152 "%u) (%u threads total), has more threads than advised in a single work group. It is advised to use work "
1153 "groups with less than %u threads, especially when using barrier() or shared memory.",
1154 VendorSpecificTag(kBPVendorArm), x, y, z, thread_count, kMaxEfficientWorkGroupThreadCountArm);
1155 }
1156
1157 if (thread_count == 1 || ((x > 1) && (x & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
1158 ((y > 1) && (y & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
1159 ((z > 1) && (z & (kThreadGroupDispatchCountAlignmentArm - 1)))) {
1160 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeThreadGroupAlignment,
1161 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, "
1162 "%u, %u) is not aligned to %u "
1163 "threads. On Arm Mali architectures, not aligning work group sizes to %u may "
1164 "leave threads idle on the shader "
1165 "core.",
1166 VendorSpecificTag(kBPVendorArm), x, y, z, kThreadGroupDispatchCountAlignmentArm,
1167 kThreadGroupDispatchCountAlignmentArm);
1168 }
1169
sfricke-samsungef15e482022-01-26 11:32:49 -08001170 auto accessible_ids = module_state->MarkAccessibleIds(entrypoint);
1171 auto descriptor_uses = module_state->CollectInterfaceByDescriptorSlot(accessible_ids);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001172
1173 unsigned dimensions = 0;
1174 if (x > 1) dimensions++;
1175 if (y > 1) dimensions++;
1176 if (z > 1) dimensions++;
1177 // Here the dimension will really depend on the dispatch grid, but assume it's 1D.
1178 dimensions = std::max(dimensions, 1u);
1179
1180 // If we're accessing images, we almost certainly want to have a 2D workgroup for cache reasons.
1181 // There are some false positives here. We could simply have a shader that does this within a 1D grid,
1182 // or we may have a linearly tiled image, but these cases are quite unlikely in practice.
1183 bool accesses_2d = false;
1184 for (const auto& usage : descriptor_uses) {
sfricke-samsungef15e482022-01-26 11:32:49 -08001185 auto dim = module_state->GetShaderResourceDimensionality(usage.second);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001186 if (dim < 0) continue;
1187 auto spvdim = spv::Dim(dim);
1188 if (spvdim != spv::Dim1D && spvdim != spv::DimBuffer) accesses_2d = true;
1189 }
1190
1191 if (accesses_2d && dimensions < 2) {
1192 LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeSpatialLocality,
1193 "%s vkCreateComputePipelines(): compute shader has work group dimensions (%u, %u, %u), which "
1194 "suggests a 1D dispatch, but the shader is accessing 2D or 3D images. The shader may be "
1195 "exhibiting poor spatial locality with respect to one or more shader resources.",
1196 VendorSpecificTag(kBPVendorArm), x, y, z);
1197 }
1198
Camden5b184be2019-08-13 07:50:19 -06001199 return skip;
1200}
1201
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001202bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags flags) const {
Camden5b184be2019-08-13 07:50:19 -06001203 bool skip = false;
1204
1205 if (flags & VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001206 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1207 "You are using VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001208 } else if (flags & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001209 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1210 "You are using VK_PIPELINE_STAGE_ALL_COMMANDS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001211 }
1212
1213 return skip;
1214}
1215
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001216bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags2KHR flags) const {
1217 bool skip = false;
1218
1219 if (flags & VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR) {
1220 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1221 "You are using VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR when %s is called\n", api_name.c_str());
1222 } else if (flags & VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR) {
1223 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1224 "You are using VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR when %s is called\n", api_name.c_str());
1225 }
1226
1227 return skip;
1228}
1229
1230bool BestPractices::CheckDependencyInfo(const std::string& api_name, const VkDependencyInfoKHR& dep_info) const {
1231 bool skip = false;
1232 auto stage_masks = sync_utils::GetGlobalStageMasks(dep_info);
1233
1234 skip |= CheckPipelineStageFlags(api_name, stage_masks.src);
1235 skip |= CheckPipelineStageFlags(api_name, stage_masks.dst);
1236
1237 return skip;
1238}
1239
Mark Lobodzinski84101d72020-04-24 09:43:48 -06001240void BestPractices::ManualPostCallRecordQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo, VkResult result) {
Mark Lobodzinski9b133c12020-03-10 10:42:56 -06001241 for (uint32_t i = 0; i < pPresentInfo->swapchainCount; ++i) {
1242 auto swapchains_result = pPresentInfo->pResults ? pPresentInfo->pResults[i] : result;
1243 if (swapchains_result == VK_SUBOPTIMAL_KHR) {
1244 LogPerformanceWarning(
1245 pPresentInfo->pSwapchains[i], kVUID_BestPractices_SuboptimalSwapchain,
1246 "vkQueuePresentKHR: %s :VK_SUBOPTIMAL_KHR was returned. VK_SUBOPTIMAL_KHR - Presentation will still succeed, "
1247 "subject to the window resize behavior, but the swapchain is no longer configured optimally for the surface it "
1248 "targets. Applications should query updated surface information and recreate their swapchain at the next "
1249 "convenient opportunity.",
1250 report_data->FormatHandle(pPresentInfo->pSwapchains[i]).c_str());
1251 }
1252 }
Nadav Gevaf0808442021-05-21 13:51:25 -04001253
1254 // AMD best practice
1255 // end-of-frame cleanup
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001256 num_queue_submissions_ = 0;
1257 num_barriers_objects_ = 0;
1258 ClearPipelinesUsedInFrame();
Mark Lobodzinski9b133c12020-03-10 10:42:56 -06001259}
1260
Jeff Bolz5c801d12019-10-09 10:38:45 -05001261bool BestPractices::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
1262 VkFence fence) const {
Camden5b184be2019-08-13 07:50:19 -06001263 bool skip = false;
1264
1265 for (uint32_t submit = 0; submit < submitCount; submit++) {
1266 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreCount; semaphore++) {
1267 skip |= CheckPipelineStageFlags("vkQueueSubmit", pSubmits[submit].pWaitDstStageMask[semaphore]);
1268 }
1269 }
1270
1271 return skip;
1272}
1273
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001274bool BestPractices::PreCallValidateQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR* pSubmits,
1275 VkFence fence) const {
1276 bool skip = false;
1277
1278 for (uint32_t submit = 0; submit < submitCount; submit++) {
1279 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreInfoCount; semaphore++) {
1280 skip |= CheckPipelineStageFlags("vkQueueSubmit2KHR", pSubmits[submit].pWaitSemaphoreInfos[semaphore].stageMask);
1281 }
1282 }
1283
1284 return skip;
1285}
1286
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001287bool BestPractices::PreCallValidateQueueSubmit2(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2* pSubmits,
1288 VkFence fence) const {
1289 bool skip = false;
1290
1291 for (uint32_t submit = 0; submit < submitCount; submit++) {
1292 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreInfoCount; semaphore++) {
1293 skip |= CheckPipelineStageFlags("vkQueueSubmit2", pSubmits[submit].pWaitSemaphoreInfos[semaphore].stageMask);
1294 }
1295 }
1296
1297 return skip;
1298}
1299
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001300bool BestPractices::PreCallValidateCreateCommandPool(VkDevice device, const VkCommandPoolCreateInfo* pCreateInfo,
1301 const VkAllocationCallbacks* pAllocator, VkCommandPool* pCommandPool) const {
1302 bool skip = false;
1303
1304 if (pCreateInfo->flags & VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT) {
1305 skip |= LogPerformanceWarning(
1306 device, kVUID_BestPractices_CreateCommandPool_CommandBufferReset,
1307 "vkCreateCommandPool(): VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT is set. Consider resetting entire "
1308 "pool instead.");
1309 }
1310
1311 return skip;
1312}
1313
1314bool BestPractices::PreCallValidateBeginCommandBuffer(VkCommandBuffer commandBuffer,
1315 const VkCommandBufferBeginInfo* pBeginInfo) const {
1316 bool skip = false;
1317
1318 if (pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT) {
1319 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_SimultaneousUse,
1320 "vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT is set.");
1321 }
1322
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001323 if (!(pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT) && VendorCheckEnabled(kBPVendorArm)) {
1324 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_OneTimeSubmit,
Attilio Provenzano02859b22020-02-27 14:17:28 +00001325 "%s vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT is not set. "
1326 "For best performance on Mali GPUs, consider setting ONE_TIME_SUBMIT by default.",
1327 VendorSpecificTag(kBPVendorArm));
1328 }
1329
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001330 return skip;
1331}
1332
Jeff Bolz5c801d12019-10-09 10:38:45 -05001333bool BestPractices::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001334 bool skip = false;
1335
1336 skip |= CheckPipelineStageFlags("vkCmdSetEvent", stageMask);
1337
1338 return skip;
1339}
1340
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001341bool BestPractices::PreCallValidateCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1342 const VkDependencyInfoKHR* pDependencyInfo) const {
1343 return CheckDependencyInfo("vkCmdSetEvent2KHR", *pDependencyInfo);
1344}
1345
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001346bool BestPractices::PreCallValidateCmdSetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
1347 const VkDependencyInfo* pDependencyInfo) const {
1348 return CheckDependencyInfo("vkCmdSetEvent2", *pDependencyInfo);
1349}
1350
Jeff Bolz5c801d12019-10-09 10:38:45 -05001351bool BestPractices::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
1352 VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001353 bool skip = false;
1354
1355 skip |= CheckPipelineStageFlags("vkCmdResetEvent", stageMask);
1356
1357 return skip;
1358}
1359
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001360bool BestPractices::PreCallValidateCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1361 VkPipelineStageFlags2KHR stageMask) const {
1362 bool skip = false;
1363
1364 skip |= CheckPipelineStageFlags("vkCmdResetEvent2KHR", stageMask);
1365
1366 return skip;
1367}
1368
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001369bool BestPractices::PreCallValidateCmdResetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
1370 VkPipelineStageFlags2 stageMask) const {
1371 bool skip = false;
1372
1373 skip |= CheckPipelineStageFlags("vkCmdResetEvent2", stageMask);
1374
1375 return skip;
1376}
1377
Camden5b184be2019-08-13 07:50:19 -06001378bool BestPractices::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1379 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
1380 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1381 uint32_t bufferMemoryBarrierCount,
1382 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1383 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001384 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001385 bool skip = false;
1386
1387 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", srcStageMask);
1388 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", dstStageMask);
1389
1390 return skip;
1391}
1392
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001393bool BestPractices::PreCallValidateCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1394 const VkDependencyInfoKHR* pDependencyInfos) const {
1395 bool skip = false;
1396 for (uint32_t i = 0; i < eventCount; i++) {
1397 skip = CheckDependencyInfo("vkCmdWaitEvents2KHR", pDependencyInfos[i]);
1398 }
1399
1400 return skip;
1401}
1402
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001403bool BestPractices::PreCallValidateCmdWaitEvents2(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1404 const VkDependencyInfo* pDependencyInfos) const {
1405 bool skip = false;
1406 for (uint32_t i = 0; i < eventCount; i++) {
1407 skip = CheckDependencyInfo("vkCmdWaitEvents2", pDependencyInfos[i]);
1408 }
1409
1410 return skip;
1411}
1412
Camden5b184be2019-08-13 07:50:19 -06001413bool BestPractices::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
1414 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
1415 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1416 uint32_t bufferMemoryBarrierCount,
1417 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1418 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001419 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001420 bool skip = false;
1421
1422 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", srcStageMask);
1423 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", dstStageMask);
1424
ziga-lunargb65dbfb2022-03-19 18:45:09 +01001425 for (uint32_t i = 0; i < imageMemoryBarrierCount; ++i) {
1426 if (pImageMemoryBarriers[i].oldLayout == VK_IMAGE_LAYOUT_UNDEFINED &&
1427 IsImageLayoutReadOnly(pImageMemoryBarriers[i].newLayout)) {
1428 skip |= LogWarning(device, kVUID_BestPractices_TransitionUndefinedToReadOnly,
1429 "VkImageMemoryBarrier is being submitted with oldLayout VK_IMAGE_LAYOUT_UNDEFINED and the contents "
1430 "may be discarded, but the newLayout is %s, which is read only.",
1431 string_VkImageLayout(pImageMemoryBarriers[i].newLayout));
1432 }
1433 }
1434
Nadav Gevaf0808442021-05-21 13:51:25 -04001435 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001436 auto num = num_barriers_objects_.load();
1437 if (num + imageMemoryBarrierCount + bufferMemoryBarrierCount > kMaxRecommendedBarriersSizeAMD) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001438 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdBuffer_highBarrierCount,
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001439 "%s Performance warning: In this frame, %" PRIu32
1440 " barriers were already submitted. Barriers have a high cost and can "
1441 "stall the GPU. "
1442 "Consider consolidating and re-organizing the frame to use fewer barriers.",
1443 VendorSpecificTag(kBPVendorAMD), num);
Nadav Gevaf0808442021-05-21 13:51:25 -04001444 }
1445
1446 std::array<VkImageLayout, 3> read_layouts = {
1447 VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL,
1448 VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
1449 VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
1450 };
1451
1452 for (uint32_t i = 0; i < imageMemoryBarrierCount; i++) {
1453 // read to read barriers
1454 auto found = std::find(read_layouts.begin(), read_layouts.end(), pImageMemoryBarriers[i].oldLayout);
1455 bool old_is_read_layout = found != read_layouts.end();
1456 found = std::find(read_layouts.begin(), read_layouts.end(), pImageMemoryBarriers[i].newLayout);
1457 bool new_is_read_layout = found != read_layouts.end();
1458 if (old_is_read_layout && new_is_read_layout) {
1459 skip |= LogPerformanceWarning(device, kVUID_BestPractices_PipelineBarrier_readToReadBarrier,
1460 "%s Performance warning: Don't issue read-to-read barriers. Get the resource in the right state the first "
1461 "time you use it.",
1462 VendorSpecificTag(kBPVendorAMD));
1463 }
1464
1465 // general with no storage
1466 if (pImageMemoryBarriers[i].newLayout == VK_IMAGE_LAYOUT_GENERAL) {
1467 auto image_state = Get<IMAGE_STATE>(pImageMemoryBarriers[i].image);
1468 if (!(image_state->createInfo.usage & VK_IMAGE_USAGE_STORAGE_BIT)) {
1469 skip |= LogPerformanceWarning(device, kVUID_BestPractices_vkImage_AvoidGeneral,
1470 "%s Performance warning: VK_IMAGE_LAYOUT_GENERAL should only be used with "
1471 "VK_IMAGE_USAGE_STORAGE_BIT images.",
1472 VendorSpecificTag(kBPVendorAMD));
1473 }
1474 }
1475 }
1476 }
1477
Camden5b184be2019-08-13 07:50:19 -06001478 return skip;
1479}
1480
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001481bool BestPractices::PreCallValidateCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer,
1482 const VkDependencyInfoKHR* pDependencyInfo) const {
1483 return CheckDependencyInfo("vkCmdPipelineBarrier2KHR", *pDependencyInfo);
1484}
1485
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001486bool BestPractices::PreCallValidateCmdPipelineBarrier2(VkCommandBuffer commandBuffer,
1487 const VkDependencyInfo* pDependencyInfo) const {
1488 return CheckDependencyInfo("vkCmdPipelineBarrier2", *pDependencyInfo);
1489}
1490
Camden5b184be2019-08-13 07:50:19 -06001491bool BestPractices::PreCallValidateCmdWriteTimestamp(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001492 VkQueryPool queryPool, uint32_t query) const {
Camden5b184be2019-08-13 07:50:19 -06001493 bool skip = false;
1494
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001495 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp", static_cast<VkPipelineStageFlags>(pipelineStage));
1496
1497 return skip;
1498}
1499
1500bool BestPractices::PreCallValidateCmdWriteTimestamp2KHR(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
1501 VkQueryPool queryPool, uint32_t query) const {
1502 bool skip = false;
1503
1504 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp2KHR", pipelineStage);
Camden5b184be2019-08-13 07:50:19 -06001505
1506 return skip;
1507}
1508
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001509bool BestPractices::PreCallValidateCmdWriteTimestamp2(VkCommandBuffer commandBuffer, VkPipelineStageFlags2 pipelineStage,
1510 VkQueryPool queryPool, uint32_t query) const {
1511 bool skip = false;
1512
1513 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp2", pipelineStage);
1514
1515 return skip;
1516}
1517
Sam Walls0961ec02020-03-31 16:39:15 +01001518void BestPractices::PostCallRecordCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
1519 VkPipeline pipeline) {
1520 StateTracker::PostCallRecordCmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
1521
Nadav Gevaf0808442021-05-21 13:51:25 -04001522 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001523 PipelineUsedInFrame(pipeline);
Nadav Gevaf0808442021-05-21 13:51:25 -04001524
Sam Walls0961ec02020-03-31 16:39:15 +01001525 if (pipelineBindPoint == VK_PIPELINE_BIND_POINT_GRAPHICS) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001526 auto pipeline_state = Get<bp_state::Pipeline>(pipeline);
Sam Walls0961ec02020-03-31 16:39:15 +01001527 // check for depth/blend state tracking
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001528 if (pipeline_state) {
1529 auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06001530 assert(cb_node);
1531 auto& render_pass_state = cb_node->render_pass_state;
Sam Walls0961ec02020-03-31 16:39:15 +01001532
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001533 render_pass_state.nextDrawTouchesAttachments = pipeline_state->access_framebuffer_attachments;
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001534 render_pass_state.drawTouchAttachments = true;
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02001535
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07001536 const auto* blend_state = pipeline_state->ColorBlendState();
1537 const auto* stencil_state = pipeline_state->DepthStencilState();
Sam Walls0961ec02020-03-31 16:39:15 +01001538
1539 if (blend_state) {
1540 // assume the pipeline is depth-only unless any of the attachments have color writes enabled
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001541 render_pass_state.depthOnly = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001542 for (size_t i = 0; i < blend_state->attachmentCount; i++) {
1543 if (blend_state->pAttachments[i].colorWriteMask != 0) {
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001544 render_pass_state.depthOnly = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001545 }
1546 }
1547 }
1548
1549 // check for depth value usage
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001550 render_pass_state.depthEqualComparison = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001551
1552 if (stencil_state && stencil_state->depthTestEnable) {
1553 switch (stencil_state->depthCompareOp) {
1554 case VK_COMPARE_OP_EQUAL:
1555 case VK_COMPARE_OP_GREATER_OR_EQUAL:
1556 case VK_COMPARE_OP_LESS_OR_EQUAL:
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001557 render_pass_state.depthEqualComparison = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001558 break;
1559 default:
1560 break;
1561 }
1562 }
Sam Walls0961ec02020-03-31 16:39:15 +01001563 }
1564 }
1565}
1566
Hans-Kristian Arntzen237663c2021-07-01 14:36:40 +02001567static inline bool RenderPassUsesAttachmentAsResolve(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1568 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
1569 const auto& subpass_info = createInfo.pSubpasses[subpass];
1570 if (subpass_info.pResolveAttachments) {
1571 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1572 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
1573 }
1574 }
1575 }
1576
1577 return false;
1578}
1579
Attilio Provenzano02859b22020-02-27 14:17:28 +00001580static inline bool RenderPassUsesAttachmentOnTile(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1581 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001582 const auto& subpass_info = createInfo.pSubpasses[subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001583
1584 // If an attachment is ever used as a color attachment,
1585 // resolve attachment or depth stencil attachment,
1586 // it needs to exist on tile at some point.
1587
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001588 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1589 if (subpass_info.pColorAttachments[i].attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001590 }
1591
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001592 if (subpass_info.pResolveAttachments) {
1593 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1594 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
1595 }
1596 }
1597
1598 if (subpass_info.pDepthStencilAttachment && subpass_info.pDepthStencilAttachment->attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001599 }
1600
1601 return false;
1602}
1603
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001604static inline bool RenderPassUsesAttachmentAsImageOnly(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1605 if (RenderPassUsesAttachmentOnTile(createInfo, attachment)) {
1606 return false;
1607 }
1608
1609 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001610 const auto& subpassInfo = createInfo.pSubpasses[subpass];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001611
1612 for (uint32_t i = 0; i < subpassInfo.inputAttachmentCount; i++) {
1613 if (subpassInfo.pInputAttachments[i].attachment == attachment) {
1614 return true;
1615 }
1616 }
1617 }
1618
1619 return false;
1620}
1621
Attilio Provenzano02859b22020-02-27 14:17:28 +00001622bool BestPractices::ValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1623 const VkRenderPassBeginInfo* pRenderPassBegin) const {
1624 bool skip = false;
1625
1626 if (!pRenderPassBegin) {
1627 return skip;
1628 }
1629
Gareth Webbdc6549a2021-06-16 03:52:24 +01001630 if (pRenderPassBegin->renderArea.extent.width == 0 || pRenderPassBegin->renderArea.extent.height == 0) {
1631 skip |= LogWarning(device, kVUID_BestPractices_BeginRenderPass_ZeroSizeRenderArea,
1632 "This render pass has a zero-size render area. It cannot write to any attachments, "
1633 "and can only be used for side effects such as layout transitions.");
1634 }
1635
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001636 auto rp_state = Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001637 if (rp_state) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08001638 if (rp_state->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07001639 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
Tony-LunarG767180f2020-04-23 14:03:59 -06001640 if (rpabi) {
1641 skip = ValidateAttachments(rp_state->createInfo.ptr(), rpabi->attachmentCount, rpabi->pAttachments);
1642 }
1643 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001644 // Check if any attachments have LOAD operation on them
1645 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001646 const auto& attachment = rp_state->createInfo.pAttachments[att];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001647
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001648 bool attachment_has_readback = false;
Hans-Kristian Arntzen4afb59b2021-06-18 12:41:36 +02001649 if (!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001650 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001651 }
1652
1653 if (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001654 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001655 }
1656
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001657 bool attachment_needs_readback = false;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001658
1659 // Check if the attachment is actually used in any subpass on-tile
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001660 if (attachment_has_readback && RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1661 attachment_needs_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001662 }
1663
1664 // Using LOAD_OP_LOAD is expensive on tiled GPUs, so flag it as a potential improvement
LawG47747b322022-02-23 16:12:10 +00001665 if (attachment_needs_readback && (VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG))) {
1666 skip |=
1667 LogPerformanceWarning(device, kVUID_BestPractices_BeginRenderPass_AttachmentNeedsReadback,
LawG4015be1c2022-03-01 10:37:52 +00001668 "%s %s: Attachment #%u in render pass has begun with VK_ATTACHMENT_LOAD_OP_LOAD.\n"
LawG47747b322022-02-23 16:12:10 +00001669 "Submitting this renderpass will cause the driver to inject a readback of the attachment "
Nadav Gevaf0808442021-05-21 13:51:25 -04001670 "which will copy in total %u pixels (renderArea = "
LawG47747b322022-02-23 16:12:10 +00001671 "{ %" PRId32 ", %" PRId32 ", %" PRIu32 ", %" PRIu32 " }) to the tile buffer.",
1672 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), att,
1673 pRenderPassBegin->renderArea.extent.width * pRenderPassBegin->renderArea.extent.height,
1674 pRenderPassBegin->renderArea.offset.x, pRenderPassBegin->renderArea.offset.y,
1675 pRenderPassBegin->renderArea.extent.width, pRenderPassBegin->renderArea.extent.height);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001676 }
1677 }
1678 }
1679
1680 return skip;
1681}
1682
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001683void BestPractices::QueueValidateImageView(QueueCallbacks &funcs, const char* function_name,
1684 IMAGE_VIEW_STATE* view, IMAGE_SUBRESOURCE_USAGE_BP usage) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001685 if (view) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001686 auto image_state = std::static_pointer_cast<bp_state::Image>(view->image_state);
1687 QueueValidateImage(funcs, function_name, image_state, usage, view->normalized_subresource_range);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001688 }
1689}
1690
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001691void BestPractices::QueueValidateImage(QueueCallbacks& funcs, const char* function_name, std::shared_ptr<bp_state::Image>& state,
1692 IMAGE_SUBRESOURCE_USAGE_BP usage, const VkImageSubresourceRange& subresource_range) {
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02001693 // If we're viewing a 3D slice, ignore base array layer.
1694 // The entire 3D subresource is accessed as one atomic unit.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001695 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 +02001696
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001697 const uint32_t max_layers = state->createInfo.arrayLayers - base_array_layer;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001698 const uint32_t array_layers = std::min(subresource_range.layerCount, max_layers);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001699 const uint32_t max_levels = state->createInfo.mipLevels - subresource_range.baseMipLevel;
1700 const uint32_t mip_levels = std::min(state->createInfo.mipLevels, max_levels);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001701
1702 for (uint32_t layer = 0; layer < array_layers; layer++) {
1703 for (uint32_t level = 0; level < mip_levels; level++) {
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02001704 QueueValidateImage(funcs, function_name, state, usage, layer + base_array_layer,
1705 level + subresource_range.baseMipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001706 }
1707 }
1708}
1709
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001710void BestPractices::QueueValidateImage(QueueCallbacks& funcs, const char* function_name, std::shared_ptr<bp_state::Image>& state,
1711 IMAGE_SUBRESOURCE_USAGE_BP usage, const VkImageSubresourceLayers& subresource_layers) {
1712 const uint32_t max_layers = state->createInfo.arrayLayers - subresource_layers.baseArrayLayer;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001713 const uint32_t array_layers = std::min(subresource_layers.layerCount, max_layers);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001714
1715 for (uint32_t layer = 0; layer < array_layers; layer++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001716 QueueValidateImage(funcs, function_name, state, usage, layer + subresource_layers.baseArrayLayer, subresource_layers.mipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001717 }
1718}
1719
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001720void BestPractices::QueueValidateImage(QueueCallbacks &funcs, const char* function_name,
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001721 std::shared_ptr<bp_state::Image> &state, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001722 uint32_t array_layer, uint32_t mip_level) {
Jeremy Gebben7fd238f2022-03-04 10:32:24 -07001723 if (VendorCheckEnabled(kBPVendorArm)) {
1724 funcs.push_back([this, function_name, state, usage, array_layer, mip_level](
1725 const ValidationStateTracker&, const QUEUE_STATE&, const CMD_BUFFER_STATE&) -> bool {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001726 ValidateImageInQueue(function_name, *state, usage, array_layer, mip_level);
Jeremy Gebben7fd238f2022-03-04 10:32:24 -07001727 return false;
1728 });
1729 }
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001730}
1731
LawG44d414ba2022-02-23 15:35:41 +00001732void BestPractices::ValidateImageInQueueArmImg(const char* function_name, const bp_state::Image& image,
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001733 IMAGE_SUBRESOURCE_USAGE_BP last_usage, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001734 uint32_t array_layer, uint32_t mip_level) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001735 // Swapchain images are implicitly read so clear after store is expected.
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001736 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 -07001737 !image.IsSwapchainImage()) {
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001738 LogPerformanceWarning(
1739 device, kVUID_BestPractices_RenderPass_RedundantStore,
LawG4015be1c2022-03-01 10:37:52 +00001740 "%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 +02001741 "image was used, it was written to with STORE_OP_STORE. "
1742 "Storing to the image is probably redundant in this case, and wastes bandwidth on tile-based "
1743 "architectures.",
LawG44d414ba2022-02-23 15:35:41 +00001744 function_name, VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), array_layer, mip_level);
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001745 } 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 +02001746 LogPerformanceWarning(
1747 device, kVUID_BestPractices_RenderPass_RedundantClear,
LawG4015be1c2022-03-01 10:37:52 +00001748 "%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 +02001749 "image was used, it was written to with vkCmdClear*Image(). "
1750 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
LawG44d414ba2022-02-23 15:35:41 +00001751 "tile-based architectures.",
1752 function_name, VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), array_layer, mip_level);
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01001753 } else if (usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE &&
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001754 (last_usage == IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE || last_usage == IMAGE_SUBRESOURCE_USAGE_BP::CLEARED ||
1755 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE || last_usage == IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE)) {
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01001756 const char *last_cmd = nullptr;
1757 const char *vuid = nullptr;
1758 const char *suggestion = nullptr;
1759
1760 switch (last_usage) {
1761 case IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE:
1762 vuid = kVUID_BestPractices_RenderPass_BlitImage_LoadOpLoad;
1763 last_cmd = "vkCmdBlitImage";
1764 suggestion =
1765 "The blit is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
1766 "Rather than blitting, just render the source image in a fragment shader in this render pass, "
1767 "which avoids the memory roundtrip.";
1768 break;
1769 case IMAGE_SUBRESOURCE_USAGE_BP::CLEARED:
1770 vuid = kVUID_BestPractices_RenderPass_InefficientClear;
1771 last_cmd = "vkCmdClear*Image";
1772 suggestion =
1773 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
1774 "tile-based architectures. "
1775 "Use LOAD_OP_CLEAR instead to clear the image for free.";
1776 break;
1777 case IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE:
1778 vuid = kVUID_BestPractices_RenderPass_CopyImage_LoadOpLoad;
1779 last_cmd = "vkCmdCopy*Image";
1780 suggestion =
1781 "The copy is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
1782 "Rather than copying, just render the source image in a fragment shader in this render pass, "
1783 "which avoids the memory roundtrip.";
1784 break;
1785 case IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE:
1786 vuid = kVUID_BestPractices_RenderPass_ResolveImage_LoadOpLoad;
1787 last_cmd = "vkCmdResolveImage";
1788 suggestion =
1789 "The resolve is probably redundant in this case, and wastes a lot of bandwidth on tile-based architectures. "
1790 "Rather than resolving, and then loading, try to keep rendering in the same render pass, "
1791 "which avoids the memory roundtrip.";
1792 break;
1793 default:
1794 break;
1795 }
1796
1797 LogPerformanceWarning(
1798 device, vuid,
LawG4015be1c2022-03-01 10:37:52 +00001799 "%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 +01001800 "time image was used, it was written to with %s. %s",
LawG44d414ba2022-02-23 15:35:41 +00001801 function_name, VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), array_layer, mip_level, last_cmd,
1802 suggestion);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001803 }
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001804}
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001805
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001806void BestPractices::ValidateImageInQueue(const char* function_name, bp_state::Image& state, IMAGE_SUBRESOURCE_USAGE_BP usage,
1807 uint32_t array_layer, uint32_t mip_level) {
1808 auto last_usage = state.UpdateUsage(array_layer, mip_level, usage);
LawG44d414ba2022-02-23 15:35:41 +00001809 if (VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG)) {
1810 ValidateImageInQueueArmImg(function_name, state, last_usage, usage, array_layer, mip_level);
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001811 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001812}
1813
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001814void BestPractices::AddDeferredQueueOperations(bp_state::CommandBuffer& cb) {
1815 cb.queue_submit_functions.insert(cb.queue_submit_functions.end(), cb.queue_submit_functions_after_render_pass.begin(),
1816 cb.queue_submit_functions_after_render_pass.end());
1817 cb.queue_submit_functions_after_render_pass.clear();
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001818}
1819
1820void BestPractices::PreCallRecordCmdEndRenderPass(VkCommandBuffer commandBuffer) {
1821 ValidationStateTracker::PreCallRecordCmdEndRenderPass(commandBuffer);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001822 auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
1823 if (cb_node) {
1824 AddDeferredQueueOperations(*cb_node);
1825 }
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001826}
1827
1828void BestPractices::PreCallRecordCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassInfo) {
1829 ValidationStateTracker::PreCallRecordCmdEndRenderPass2(commandBuffer, pSubpassInfo);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001830 auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
1831 if (cb_node) {
1832 AddDeferredQueueOperations(*cb_node);
1833 }
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001834}
1835
1836void BestPractices::PreCallRecordCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfoKHR *pSubpassInfo) {
1837 ValidationStateTracker::PreCallRecordCmdEndRenderPass2KHR(commandBuffer, pSubpassInfo);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001838 auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
1839 if (cb_node) {
1840 AddDeferredQueueOperations(*cb_node);
1841 }
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001842}
1843
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02001844void BestPractices::PreCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer,
1845 const VkRenderPassBeginInfo* pRenderPassBegin,
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001846 VkSubpassContents contents) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001847 ValidationStateTracker::PreCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02001848 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1849}
1850
1851void BestPractices::PreCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer,
1852 const VkRenderPassBeginInfo* pRenderPassBegin,
1853 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1854 ValidationStateTracker::PreCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1855 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1856}
1857
1858void BestPractices::PreCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1859 const VkRenderPassBeginInfo* pRenderPassBegin,
1860 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1861 ValidationStateTracker::PreCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1862 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1863}
1864
1865void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001866
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001867 if (!pRenderPassBegin) {
1868 return;
1869 }
1870
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001871 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001872
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001873 auto rp_state = Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001874 if (rp_state) {
1875 // Check load ops
1876 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001877 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001878
1879 if (!RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att) &&
1880 !RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1881 continue;
1882 }
1883
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001884 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::UNDEFINED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001885
1886 if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) ||
1887 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001888 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02001889 } else if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) ||
1890 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_CLEAR)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001891 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_CLEARED;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02001892 } else if (RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att)) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001893 usage = IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001894 }
1895
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001896 auto framebuffer = Get<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer);
Jeremy Gebben9f537102021-10-05 16:37:12 -06001897 std::shared_ptr<IMAGE_VIEW_STATE> image_view = nullptr;
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001898
Tony-LunarGb3ab3572021-07-02 09:45:17 -06001899 if (framebuffer->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001900 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
1901 if (rpabi) {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001902 image_view = Get<IMAGE_VIEW_STATE>(rpabi->pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001903 }
1904 } else {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001905 image_view = Get<IMAGE_VIEW_STATE>(framebuffer->createInfo.pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001906 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001907
Jeremy Gebben9f537102021-10-05 16:37:12 -06001908 QueueValidateImageView(cb->queue_submit_functions, "vkCmdBeginRenderPass()", image_view.get(), usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001909 }
1910
1911 // Check store ops
1912 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001913 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001914
1915 if (!RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1916 continue;
1917 }
1918
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001919 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_DISCARDED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001920
1921 if ((!FormatIsStencilOnly(attachment.format) && attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE) ||
1922 (FormatHasStencil(attachment.format) && attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001923 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_STORED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001924 }
1925
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001926 auto framebuffer = Get<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001927
Jeremy Gebben9f537102021-10-05 16:37:12 -06001928 std::shared_ptr<IMAGE_VIEW_STATE> image_view;
Tony-LunarGb3ab3572021-07-02 09:45:17 -06001929 if (framebuffer->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001930 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
1931 if (rpabi) {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001932 image_view = Get<IMAGE_VIEW_STATE>(rpabi->pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001933 }
1934 } else {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001935 image_view = Get<IMAGE_VIEW_STATE>(framebuffer->createInfo.pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001936 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001937
Jeremy Gebben9f537102021-10-05 16:37:12 -06001938 QueueValidateImageView(cb->queue_submit_functions_after_render_pass, "vkCmdEndRenderPass()", image_view.get(), usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001939 }
1940 }
1941}
1942
Attilio Provenzano02859b22020-02-27 14:17:28 +00001943bool BestPractices::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1944 VkSubpassContents contents) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001945 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1946 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001947 return skip;
1948}
1949
1950bool BestPractices::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1951 const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08001952 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001953 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1954 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001955 return skip;
1956}
1957
1958bool BestPractices::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08001959 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001960 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1961 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001962 return skip;
1963}
1964
Sam Walls0961ec02020-03-31 16:39:15 +01001965void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1966 const VkRenderPassBeginInfo* pRenderPassBegin) {
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001967 // Reset the renderpass state
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001968 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06001969 cb->hasDrawCmd = false;
1970 assert(cb);
1971 auto& render_pass_state = cb->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02001972 render_pass_state.touchesAttachments.clear();
1973 render_pass_state.earlyClearAttachments.clear();
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001974 render_pass_state.numDrawCallsDepthOnly = 0;
1975 render_pass_state.numDrawCallsDepthEqualCompare = 0;
1976 render_pass_state.colorAttachment = false;
1977 render_pass_state.depthAttachment = false;
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02001978 render_pass_state.drawTouchAttachments = true;
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001979 // Don't reset state related to pipeline state.
Sam Walls0961ec02020-03-31 16:39:15 +01001980
Jeremy Gebbenf4449392022-01-28 10:09:10 -07001981 auto rp_state = Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
Sam Walls0961ec02020-03-31 16:39:15 +01001982
1983 // track depth / color attachment usage within the renderpass
1984 for (size_t i = 0; i < rp_state->createInfo.subpassCount; i++) {
1985 // record if depth/color attachments are in use for this renderpass
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001986 if (rp_state->createInfo.pSubpasses[i].pDepthStencilAttachment != nullptr) render_pass_state.depthAttachment = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001987
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001988 if (rp_state->createInfo.pSubpasses[i].colorAttachmentCount > 0) render_pass_state.colorAttachment = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001989 }
1990}
1991
1992void BestPractices::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1993 VkSubpassContents contents) {
1994 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1995 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
1996}
1997
1998void BestPractices::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1999 const VkSubpassBeginInfo* pSubpassBeginInfo) {
2000 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
2001 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
2002}
2003
2004void BestPractices::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
2005 const VkRenderPassBeginInfo* pRenderPassBegin,
2006 const VkSubpassBeginInfo* pSubpassBeginInfo) {
2007 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
2008 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
2009}
2010
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002011// Generic function to handle validation for all CmdDraw* type functions
2012bool BestPractices::ValidateCmdDrawType(VkCommandBuffer cmd_buffer, const char* caller) const {
2013 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002014 const auto cb_state = GetRead<bp_state::CommandBuffer>(cmd_buffer);
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002015 if (cb_state) {
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002016 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
2017 const auto* pipeline_state = cb_state->lastBound[lv_bind_point].pipeline_state;
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002018 const auto& current_vtx_bfr_binding_info = cb_state->current_vertex_buffer_binding_info.vertex_buffer_bindings;
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002019
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002020 // Verify vertex binding
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002021 if (pipeline_state->vertex_input_state && pipeline_state->vertex_input_state->binding_descriptions.size() <= 0) {
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002022 if ((!current_vtx_bfr_binding_info.empty()) && (!cb_state->vertex_buffer_used)) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002023 skip |= LogPerformanceWarning(cb_state->commandBuffer(), kVUID_BestPractices_DrawState_VtxIndexOutOfBounds,
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07002024 "Vertex buffers are bound to %s but no vertex buffers are attached to %s.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002025 report_data->FormatHandle(cb_state->commandBuffer()).c_str(),
2026 report_data->FormatHandle(pipeline_state->pipeline()).c_str());
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002027 }
2028 }
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002029
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002030 const auto* pipe = cb_state->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002031 if (pipe) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002032 const auto& rp_state = pipe->RenderPassState();
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002033 if (rp_state) {
2034 for (uint32_t i = 0; i < rp_state->createInfo.subpassCount; ++i) {
2035 const auto& subpass = rp_state->createInfo.pSubpasses[i];
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002036 const auto* ds_state = pipe->DepthStencilState();
Jeremy Gebben11af9792021-08-20 10:20:09 -06002037 const uint32_t depth_stencil_attachment =
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002038 GetSubpassDepthStencilAttachmentIndex(ds_state, subpass.pDepthStencilAttachment);
2039 const auto* raster_state = pipe->RasterizationState();
2040 if ((depth_stencil_attachment == VK_ATTACHMENT_UNUSED) && raster_state &&
2041 raster_state->depthBiasEnable == VK_TRUE) {
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002042 skip |= LogWarning(cb_state->commandBuffer(), kVUID_BestPractices_DepthBiasNoAttachment,
2043 "%s: depthBiasEnable == VK_TRUE without a depth-stencil attachment.", caller);
2044 }
2045 }
2046 }
2047 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002048 }
2049 return skip;
2050}
2051
Sam Walls0961ec02020-03-31 16:39:15 +01002052void BestPractices::RecordCmdDrawType(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002053 auto cb_node = GetWrite<bp_state::CommandBuffer>(cmd_buffer);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002054 assert(cb_node);
Sam Walls0961ec02020-03-31 16:39:15 +01002055 if (VendorCheckEnabled(kBPVendorArm)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002056 RecordCmdDrawTypeArm(*cb_node, draw_count, caller);
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002057 }
2058
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002059 if (cb_node->render_pass_state.drawTouchAttachments) {
2060 for (auto& touch : cb_node->render_pass_state.nextDrawTouchesAttachments) {
2061 RecordAttachmentAccess(*cb_node, touch.framebufferAttachment, touch.aspects);
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002062 }
2063 // No need to touch the same attachments over and over.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002064 cb_node->render_pass_state.drawTouchAttachments = false;
Sam Walls0961ec02020-03-31 16:39:15 +01002065 }
2066}
2067
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002068void BestPractices::RecordCmdDrawTypeArm(bp_state::CommandBuffer& cb_node, uint32_t draw_count, const char* caller) {
2069 auto& render_pass_state = cb_node.render_pass_state;
LawG4b21485c2022-02-28 13:46:48 +00002070 // Each TBDR vendor requires a depth pre-pass draw call to have a minimum number of vertices/indices before it counts towards
2071 // depth prepass warnings First find the lowest enabled draw count
2072 uint32_t lowestEnabledMinDrawCount = 0;
2073 lowestEnabledMinDrawCount = VendorCheckEnabled(kBPVendorArm) * kDepthPrePassMinDrawCountArm;
2074 if (VendorCheckEnabled(kBPVendorIMG) && kDepthPrePassMinDrawCountIMG < lowestEnabledMinDrawCount)
2075 lowestEnabledMinDrawCount = kDepthPrePassMinDrawCountIMG;
2076
2077 if (draw_count >= lowestEnabledMinDrawCount) {
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002078 if (render_pass_state.depthOnly) render_pass_state.numDrawCallsDepthOnly++;
2079 if (render_pass_state.depthEqualComparison) render_pass_state.numDrawCallsDepthEqualCompare++;
Sam Walls0961ec02020-03-31 16:39:15 +01002080 }
2081}
2082
Camden5b184be2019-08-13 07:50:19 -06002083bool BestPractices::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002084 uint32_t firstVertex, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06002085 bool skip = false;
2086
2087 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002088 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
2089 "Warning: You are calling vkCmdDraw() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06002090 }
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002091 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDraw()");
Camden5b184be2019-08-13 07:50:19 -06002092
2093 return skip;
2094}
2095
Sam Walls0961ec02020-03-31 16:39:15 +01002096void BestPractices::PostCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
2097 uint32_t firstVertex, uint32_t firstInstance) {
2098 StateTracker::PostCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
2099 RecordCmdDrawType(commandBuffer, vertexCount * instanceCount, "vkCmdDraw()");
2100}
2101
Camden5b184be2019-08-13 07:50:19 -06002102bool BestPractices::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002103 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06002104 bool skip = false;
2105
2106 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002107 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
2108 "Warning: You are calling vkCmdDrawIndexed() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06002109 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002110 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexed()");
2111
Attilio Provenzano02859b22020-02-27 14:17:28 +00002112 // Check if we reached the limit for small indexed draw calls.
2113 // Note that we cannot update the draw call count here, so we do it in PreCallRecordCmdDrawIndexed.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002114 const auto cmd_state = GetRead<bp_state::CommandBuffer>(commandBuffer);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002115 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices &&
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02002116 (cmd_state->small_indexed_draw_call_count == kMaxSmallIndexedDrawcalls - 1) &&
LawG4ff42d722022-03-01 10:28:25 +00002117 (VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG))) {
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02002118 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_ManySmallIndexedDrawcalls,
LawG4ff42d722022-03-01 10:28:25 +00002119 "%s %s: The command buffer contains many small indexed drawcalls "
Attilio Provenzano02859b22020-02-27 14:17:28 +00002120 "(at least %u drawcalls with less than %u indices each). This may cause pipeline bubbles. "
2121 "You can try batching drawcalls or instancing when applicable.",
LawG4ff42d722022-03-01 10:28:25 +00002122 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), kMaxSmallIndexedDrawcalls,
2123 kSmallIndexedDrawcallIndices);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002124 }
2125
Sam Walls8e77e4f2020-03-16 20:47:40 +00002126 if (VendorCheckEnabled(kBPVendorArm)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002127 ValidateIndexBufferArm(*cmd_state, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002128 }
2129
2130 return skip;
2131}
2132
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002133bool BestPractices::ValidateIndexBufferArm(const bp_state::CommandBuffer& cmd_state, uint32_t indexCount, uint32_t instanceCount,
Sam Walls8e77e4f2020-03-16 20:47:40 +00002134 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
2135 bool skip = false;
2136
2137 // check for sparse/underutilised index buffer, and post-transform cache thrashing
Sam Walls8e77e4f2020-03-16 20:47:40 +00002138
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002139 const auto* ib_state = cmd_state.index_buffer_binding.buffer_state.get();
2140 if (ib_state == nullptr || cmd_state.index_buffer_binding.buffer_state->Destroyed()) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00002141
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002142 const VkIndexType ib_type = cmd_state.index_buffer_binding.index_type;
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06002143 const auto& ib_mem_state = *ib_state->MemState();
Sam Walls8e77e4f2020-03-16 20:47:40 +00002144 const VkDeviceSize ib_mem_offset = ib_mem_state.mapped_range.offset;
2145 const void* ib_mem = ib_mem_state.p_driver_data;
2146 bool primitive_restart_enable = false;
2147
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002148 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002149 const auto& pipeline_binding_iter = cmd_state.lastBound[lv_bind_point];
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002150 const auto* pipeline_state = pipeline_binding_iter.pipeline_state;
Sam Walls8e77e4f2020-03-16 20:47:40 +00002151
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002152 const auto* ia_state = pipeline_state ? pipeline_state->InputAssemblyState() : nullptr;
2153 if (ia_state) {
2154 primitive_restart_enable = ia_state->primitiveRestartEnable == VK_TRUE;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002155 }
Sam Walls8e77e4f2020-03-16 20:47:40 +00002156
2157 // 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 -06002158 if (ib_mem && pipeline_binding_iter.IsUsing()) {
Sam Walls8e77e4f2020-03-16 20:47:40 +00002159 uint32_t scan_stride;
2160 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
2161 scan_stride = sizeof(uint8_t);
2162 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
2163 scan_stride = sizeof(uint16_t);
2164 } else {
2165 scan_stride = sizeof(uint32_t);
2166 }
2167
2168 const uint8_t* scan_begin = static_cast<const uint8_t*>(ib_mem) + ib_mem_offset + firstIndex * scan_stride;
2169 const uint8_t* scan_end = scan_begin + indexCount * scan_stride;
2170
2171 // Min and max are important to track for some Mali architectures. In older Mali devices without IDVS, all
2172 // vertices corresponding to indices between the minimum and maximum may be loaded, and possibly shaded,
2173 // irrespective of whether or not they're part of the draw call.
2174
2175 // start with minimum as 0xFFFFFFFF and adjust to indices in the buffer
2176 uint32_t min_index = ~0u;
2177 // start with maximum as 0 and adjust to indices in the buffer
2178 uint32_t max_index = 0u;
2179
2180 // first scan-through, we're looking to simulate a model LRU post-transform cache, estimating the number of vertices shaded
2181 // for the given index buffer
2182 uint32_t vertex_shade_count = 0;
2183
2184 PostTransformLRUCacheModel post_transform_cache;
2185
2186 // The size of the cache being modelled positively correlates with how much behaviour it can capture about
2187 // arbitrary ground-truth hardware/architecture cache behaviour. I.e. it's a good solution when we don't know the
2188 // target architecture.
2189 // However, modelling a post-transform cache with more than 32 elements gives diminishing returns in practice.
2190 // http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
2191 post_transform_cache.resize(32);
2192
2193 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
2194 uint32_t scan_index;
2195 uint32_t primitive_restart_value;
2196 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
2197 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
2198 primitive_restart_value = 0xFF;
2199 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
2200 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
2201 primitive_restart_value = 0xFFFF;
2202 } else {
2203 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
2204 primitive_restart_value = 0xFFFFFFFF;
2205 }
2206
2207 max_index = std::max(max_index, scan_index);
2208 min_index = std::min(min_index, scan_index);
2209
2210 if (!primitive_restart_enable || scan_index != primitive_restart_value) {
2211 bool in_cache = post_transform_cache.query_cache(scan_index);
2212 // if the shaded vertex corresponding to the index is not in the PT-cache, we need to shade again
2213 if (!in_cache) vertex_shade_count++;
2214 }
2215 }
2216
2217 // 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 +01002218 // 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
2219 if (max_index < min_index || max_index == min_index) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00002220
2221 if (max_index - min_index >= indexCount) {
Mark Young0ec6b062020-11-19 15:32:17 -07002222 skip |=
2223 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
2224 "%s The indices which were specified for the draw call only utilise approximately %.02f%% of "
2225 "index buffer value range. Arm Mali architectures before G71 do not have IDVS (Index-Driven "
2226 "Vertex Shading), meaning all vertices corresponding to indices between the minimum and "
2227 "maximum would be loaded, and possibly shaded, whether or not they are used.",
2228 VendorSpecificTag(kBPVendorArm),
2229 (static_cast<float>(indexCount) / static_cast<float>(max_index - min_index)) * 100.0f);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002230 return skip;
2231 }
2232
2233 // use a dynamic vector of bitsets as a memory-compact representation of which indices are included in the draw call
2234 // 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 +01002235 const size_t refs_per_bucket = 64;
2236 std::vector<std::bitset<refs_per_bucket>> vertex_reference_buckets;
2237
2238 const uint32_t n_indices = max_index - min_index + 1;
2239 const uint32_t n_buckets = (n_indices / static_cast<uint32_t>(refs_per_bucket)) +
2240 ((n_indices % static_cast<uint32_t>(refs_per_bucket)) != 0 ? 1 : 0);
2241
2242 // there needs to be at least one bitset to store a set of indices smaller than n_buckets
2243 vertex_reference_buckets.resize(std::max(1u, n_buckets));
Sam Walls8e77e4f2020-03-16 20:47:40 +00002244
2245 // To avoid using too much memory, we run over the indices again.
2246 // Knowing the size from the last scan allows us to record index usage with bitsets
2247 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
2248 uint32_t scan_index;
2249 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
2250 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
2251 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
2252 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
2253 } else {
2254 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
2255 }
2256 // keep track of the set of all indices used to reference vertices in the draw call
2257 size_t index_offset = scan_index - min_index;
Sam Walls61b06892020-07-23 16:20:50 +01002258 size_t bitset_bucket_index = index_offset / refs_per_bucket;
2259 uint64_t used_indices = 1ull << ((index_offset % refs_per_bucket) & 0xFFFFFFFFu);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002260 vertex_reference_buckets[bitset_bucket_index] |= used_indices;
2261 }
2262
2263 uint32_t vertex_reference_count = 0;
2264 for (const auto& bitset : vertex_reference_buckets) {
2265 vertex_reference_count += static_cast<uint32_t>(bitset.count());
2266 }
2267
2268 // 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 -07002269 float utilization = static_cast<float>(vertex_reference_count) / static_cast<float>(max_index - min_index + 1);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002270 // 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 -07002271 float cache_hit_rate = static_cast<float>(vertex_reference_count) / static_cast<float>(vertex_shade_count);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002272
2273 if (utilization < 0.5f) {
2274 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
2275 "%s The indices which were specified for the draw call only utilise approximately "
2276 "%.02f%% of the bound vertex buffer.",
2277 VendorSpecificTag(kBPVendorArm), utilization);
2278 }
2279
2280 if (cache_hit_rate <= 0.5f) {
2281 skip |=
2282 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_PostTransformCacheThrashing,
2283 "%s The indices which were specified for the draw call are estimated to cause thrashing of "
2284 "the post-transform vertex cache, with a hit-rate of %.02f%%. "
2285 "I.e. the ordering of the index buffer may not make optimal use of indices associated with "
2286 "recently shaded vertices.",
2287 VendorSpecificTag(kBPVendorArm), cache_hit_rate * 100.0f);
2288 }
2289 }
2290
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002291 return skip;
2292}
2293
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002294bool BestPractices::PreCallValidateCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
2295 const VkCommandBuffer* pCommandBuffers) const {
2296 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002297 const auto primary = GetRead<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002298 for (uint32_t i = 0; i < commandBufferCount; i++) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002299 const auto secondary_cb = GetRead<bp_state::CommandBuffer>(pCommandBuffers[i]);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002300 if (secondary_cb == nullptr) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002301 continue;
2302 }
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002303 const auto& secondary = secondary_cb->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002304 for (auto& clear : secondary.earlyClearAttachments) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002305 if (ClearAttachmentsIsFullClear(*primary, uint32_t(clear.rects.size()), clear.rects.data())) {
2306 skip |= ValidateClearAttachment(*primary, clear.framebufferAttachment, clear.colorAttachment, clear.aspects, true);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002307 }
2308 }
2309 }
Nadav Gevaf0808442021-05-21 13:51:25 -04002310
2311 if (VendorCheckEnabled(kBPVendorAMD)) {
2312 if (commandBufferCount > 0) {
2313 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdBuffer_AvoidSecondaryCmdBuffers,
2314 "%s Performance warning: Use of secondary command buffers is not recommended. ",
2315 VendorSpecificTag(kBPVendorAMD));
2316 }
2317 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002318 return skip;
2319}
2320
2321void BestPractices::PreCallRecordCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
2322 const VkCommandBuffer* pCommandBuffers) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002323 ValidationStateTracker::PreCallRecordCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
2324
2325 auto primary = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2326 if (!primary) {
2327 return;
2328 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002329
2330 for (uint32_t i = 0; i < commandBufferCount; i++) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002331 auto secondary = GetWrite<bp_state::CommandBuffer>(pCommandBuffers[i]);
2332 if (!secondary) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002333 continue;
2334 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002335
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002336 for (auto& early_clear : secondary->render_pass_state.earlyClearAttachments) {
2337 if (ClearAttachmentsIsFullClear(*primary, uint32_t(early_clear.rects.size()), early_clear.rects.data())) {
2338 RecordAttachmentClearAttachments(*primary, early_clear.framebufferAttachment, early_clear.colorAttachment,
2339 early_clear.aspects, uint32_t(early_clear.rects.size()), early_clear.rects.data());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002340 } else {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002341 RecordAttachmentAccess(*primary, early_clear.framebufferAttachment, early_clear.aspects);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002342 }
2343 }
2344
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002345 for (auto& touch : secondary->render_pass_state.touchesAttachments) {
2346 RecordAttachmentAccess(*primary, touch.framebufferAttachment, touch.aspects);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002347 }
Hans-Kristian Arntzenc7eb82a2021-06-16 13:57:18 +02002348
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002349 primary->render_pass_state.numDrawCallsDepthEqualCompare += secondary->render_pass_state.numDrawCallsDepthEqualCompare;
2350 primary->render_pass_state.numDrawCallsDepthOnly += secondary->render_pass_state.numDrawCallsDepthOnly;
Hans-Kristian Arntzenaf81dca2021-06-18 11:14:28 +02002351
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002352 if (secondary->hasDrawCmd) {
Hans-Kristian Arntzenaf81dca2021-06-18 11:14:28 +02002353 primary->hasDrawCmd = true;
2354 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002355 }
2356
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002357}
2358
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002359void BestPractices::RecordAttachmentAccess(bp_state::CommandBuffer& cb_state, uint32_t fb_attachment, VkImageAspectFlags aspects) {
2360 auto& state = cb_state.render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002361 // Called when we have a partial clear attachment, or a normal draw call which accesses an attachment.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002362 auto itr =
2363 std::find_if(state.touchesAttachments.begin(), state.touchesAttachments.end(),
2364 [fb_attachment](const bp_state::AttachmentInfo& info) { return info.framebufferAttachment == fb_attachment; });
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002365
2366 if (itr != state.touchesAttachments.end()) {
2367 itr->aspects |= aspects;
2368 } else {
2369 state.touchesAttachments.push_back({ fb_attachment, aspects });
2370 }
2371}
2372
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002373void BestPractices::RecordAttachmentClearAttachments(bp_state::CommandBuffer& cmd_state, uint32_t fb_attachment,
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002374 uint32_t color_attachment, VkImageAspectFlags aspects, uint32_t rectCount,
2375 const VkClearRect* pRects) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002376 auto& state = cmd_state.render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002377 // If we observe a full clear before any other access to a frame buffer attachment,
2378 // we have candidate for redundant clear attachments.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002379 auto itr =
2380 std::find_if(state.touchesAttachments.begin(), state.touchesAttachments.end(),
2381 [fb_attachment](const bp_state::AttachmentInfo& info) { return info.framebufferAttachment == fb_attachment; });
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002382
2383 uint32_t new_aspects = aspects;
2384 if (itr != state.touchesAttachments.end()) {
2385 new_aspects = aspects & ~itr->aspects;
2386 itr->aspects |= aspects;
2387 } else {
2388 state.touchesAttachments.push_back({ fb_attachment, aspects });
2389 }
2390
2391 if (new_aspects == 0) {
2392 return;
2393 }
2394
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002395 if (cmd_state.createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002396 // The first command might be a clear, but might not be the first in the render pass, defer any checks until
2397 // CmdExecuteCommands.
2398 state.earlyClearAttachments.push_back({ fb_attachment, color_attachment, new_aspects,
2399 std::vector<VkClearRect>{pRects, pRects + rectCount} });
2400 }
2401}
2402
2403void BestPractices::PreCallRecordCmdClearAttachments(VkCommandBuffer commandBuffer,
2404 uint32_t attachmentCount, const VkClearAttachment* pClearAttachments,
2405 uint32_t rectCount, const VkClearRect* pRects) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002406 ValidationStateTracker::PreCallRecordCmdClearAttachments(commandBuffer, attachmentCount, pClearAttachments, rectCount, pRects);
2407
2408 auto cmd_state = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2409 auto* rp_state = cmd_state->activeRenderPass.get();
2410 auto* fb_state = cmd_state->activeFramebuffer.get();
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002411 bool is_secondary = cmd_state->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY;
2412
2413 if (rectCount == 0 || !rp_state) {
2414 return;
2415 }
2416
2417 if (!is_secondary && !fb_state) {
2418 return;
2419 }
2420
2421 // 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 -07002422 bool full_clear = ClearAttachmentsIsFullClear(*cmd_state, rectCount, pRects);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002423
ziga-lunarg885c6542022-03-07 01:08:25 +01002424 if (!rp_state->use_dynamic_rendering && !rp_state->use_dynamic_rendering_inherited) {
2425 auto& subpass = rp_state->createInfo.pSubpasses[cmd_state->activeSubpass];
2426 for (uint32_t i = 0; i < attachmentCount; i++) {
2427 auto& attachment = pClearAttachments[i];
2428 uint32_t fb_attachment = VK_ATTACHMENT_UNUSED;
2429 VkImageAspectFlags aspects = attachment.aspectMask;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002430
ziga-lunarg885c6542022-03-07 01:08:25 +01002431 if (aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) {
2432 if (subpass.pDepthStencilAttachment) {
2433 fb_attachment = subpass.pDepthStencilAttachment->attachment;
2434 }
2435 } else if (aspects & VK_IMAGE_ASPECT_COLOR_BIT) {
2436 fb_attachment = subpass.pColorAttachments[attachment.colorAttachment].attachment;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002437 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002438
ziga-lunarg885c6542022-03-07 01:08:25 +01002439 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2440 if (full_clear) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002441 RecordAttachmentClearAttachments(*cmd_state, fb_attachment, attachment.colorAttachment,
ziga-lunarg885c6542022-03-07 01:08:25 +01002442 aspects, rectCount, pRects);
2443 } else {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002444 RecordAttachmentAccess(*cmd_state, fb_attachment, aspects);
ziga-lunarg885c6542022-03-07 01:08:25 +01002445 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002446 }
2447 }
2448 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002449}
2450
Attilio Provenzano02859b22020-02-27 14:17:28 +00002451void BestPractices::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
2452 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
2453 ValidationStateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset,
2454 firstInstance);
2455
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002456 auto cmd_state = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002457 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices) {
2458 cmd_state->small_indexed_draw_call_count++;
2459 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002460
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002461 ValidateBoundDescriptorSets(*cmd_state, "vkCmdDrawIndexed()");
Attilio Provenzano02859b22020-02-27 14:17:28 +00002462}
2463
Sam Walls0961ec02020-03-31 16:39:15 +01002464void BestPractices::PostCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
2465 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
2466 StateTracker::PostCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
2467 RecordCmdDrawType(commandBuffer, indexCount * instanceCount, "vkCmdDrawIndexed()");
2468}
2469
sfricke-samsung681ab7b2020-10-29 01:53:35 -07002470bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2471 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
2472 uint32_t maxDrawCount, uint32_t stride) const {
2473 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCount()");
2474
2475 return skip;
2476}
2477
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002478bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
2479 VkDeviceSize offset, VkBuffer countBuffer,
2480 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
2481 uint32_t stride) const {
2482 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCountKHR()");
Camden5b184be2019-08-13 07:50:19 -06002483
2484 return skip;
2485}
2486
2487bool BestPractices::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002488 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06002489 bool skip = false;
2490
2491 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002492 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
2493 "Warning: You are calling vkCmdDrawIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002494 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirect()");
Camden5b184be2019-08-13 07:50:19 -06002495 }
2496
2497 return skip;
2498}
2499
Sam Walls0961ec02020-03-31 16:39:15 +01002500void BestPractices::PostCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2501 uint32_t count, uint32_t stride) {
2502 StateTracker::PostCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, count, stride);
2503 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndirect()");
2504}
2505
Camden5b184be2019-08-13 07:50:19 -06002506bool BestPractices::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002507 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06002508 bool skip = false;
2509
2510 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002511 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
2512 "Warning: You are calling vkCmdDrawIndexedIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002513 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirect()");
Camden5b184be2019-08-13 07:50:19 -06002514 }
2515
2516 return skip;
2517}
2518
Sam Walls0961ec02020-03-31 16:39:15 +01002519void BestPractices::PostCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2520 uint32_t count, uint32_t stride) {
2521 StateTracker::PostCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, count, stride);
2522 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndexedIndirect()");
2523}
2524
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002525void BestPractices::ValidateBoundDescriptorSets(bp_state::CommandBuffer& cb_state, const char* function_name) {
2526 for (auto descriptor_set : cb_state.validated_descriptor_sets) {
2527 const auto& layout = *descriptor_set->GetLayout();
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002528
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002529 for (uint32_t index = 0; index < descriptor_set->GetBindingCount(); ++index) {
2530 // For bindless scenarios, we should not attempt to track descriptor set state.
2531 // It is highly uncertain which resources are actually bound.
2532 // Resources which are written to such a descriptor should be marked as indeterminate w.r.t. state.
2533 VkDescriptorBindingFlags flags = layout.GetDescriptorBindingFlagsFromIndex(index);
2534 if (flags & (VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT | VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT |
2535 VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT)) {
2536 continue;
2537 }
Hans-Kristian Arntzena8199012021-03-22 12:10:07 +01002538
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002539 auto index_range = layout.GetGlobalIndexRangeFromIndex(index);
2540 for (uint32_t i = index_range.start; i < index_range.end; ++i) {
2541 VkImageView image_view{VK_NULL_HANDLE};
2542
2543 auto descriptor = descriptor_set->GetDescriptorFromGlobalIndex(i);
2544 switch (descriptor->GetClass()) {
2545 case cvdescriptorset::DescriptorClass::Image: {
2546 if (const auto image_descriptor = static_cast<const cvdescriptorset::ImageDescriptor*>(descriptor)) {
2547 image_view = image_descriptor->GetImageView();
2548 }
2549 break;
2550 }
2551 case cvdescriptorset::DescriptorClass::ImageSampler: {
2552 if (const auto image_sampler_descriptor =
2553 static_cast<const cvdescriptorset::ImageSamplerDescriptor*>(descriptor)) {
2554 image_view = image_sampler_descriptor->GetImageView();
2555 }
2556 break;
2557 }
2558 default:
2559 break;
Hans-Kristian Arntzena8199012021-03-22 12:10:07 +01002560 }
2561
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002562 if (image_view) {
2563 auto image_view_state = Get<IMAGE_VIEW_STATE>(image_view);
2564 QueueValidateImageView(cb_state.queue_submit_functions, function_name, image_view_state.get(),
2565 IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002566 }
2567 }
2568 }
2569 }
2570}
2571
2572void BestPractices::PreCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
2573 uint32_t firstVertex, uint32_t firstInstance) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002574 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2575 ValidateBoundDescriptorSets(*cb_node, "vkCmdDraw()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002576}
2577
2578void BestPractices::PreCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2579 uint32_t drawCount, uint32_t stride) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002580 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2581 ValidateBoundDescriptorSets(*cb_node, "vkCmdDrawIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002582}
2583
2584void BestPractices::PreCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2585 uint32_t drawCount, uint32_t stride) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002586 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2587 ValidateBoundDescriptorSets(*cb_node, "vkCmdDrawIndexedIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002588}
2589
Camden5b184be2019-08-13 07:50:19 -06002590bool BestPractices::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t groupCountX, uint32_t groupCountY,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002591 uint32_t groupCountZ) const {
Camden5b184be2019-08-13 07:50:19 -06002592 bool skip = false;
2593
2594 if ((groupCountX == 0) || (groupCountY == 0) || (groupCountZ == 0)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002595 skip |= LogWarning(device, kVUID_BestPractices_CmdDispatch_GroupCountZero,
2596 "Warning: You are calling vkCmdDispatch() while one or more groupCounts are zero (groupCountX = %" PRIu32
2597 ", groupCountY = %" PRIu32 ", groupCountZ = %" PRIu32 ").",
2598 groupCountX, groupCountY, groupCountZ);
Camden5b184be2019-08-13 07:50:19 -06002599 }
2600
2601 return skip;
2602}
Camden83a9c372019-08-14 11:41:38 -06002603
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002604bool BestPractices::PreCallValidateCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo* pSubpassEndInfo) const {
2605 bool skip = false;
2606 skip |= StateTracker::PreCallValidateCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
2607 skip |= ValidateCmdEndRenderPass(commandBuffer);
2608 return skip;
2609}
2610
2611bool BestPractices::PreCallValidateCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfo* pSubpassEndInfo) const {
2612 bool skip = false;
2613 skip |= StateTracker::PreCallValidateCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
2614 skip |= ValidateCmdEndRenderPass(commandBuffer);
2615 return skip;
2616}
2617
Sam Walls0961ec02020-03-31 16:39:15 +01002618bool BestPractices::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
2619 bool skip = false;
Sam Walls0961ec02020-03-31 16:39:15 +01002620 skip |= StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002621 skip |= ValidateCmdEndRenderPass(commandBuffer);
2622 return skip;
2623}
2624
2625bool BestPractices::ValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
2626 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002627 const auto cmd = GetRead<bp_state::CommandBuffer>(commandBuffer);
Sam Walls0961ec02020-03-31 16:39:15 +01002628
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002629 if (cmd == nullptr) return skip;
2630 auto &render_pass_state = cmd->render_pass_state;
Sam Walls0961ec02020-03-31 16:39:15 +01002631
LawG4b21485c2022-02-28 13:46:48 +00002632 // Does the number of draw calls classified as depth only surpass the vendor limit for a specified vendor
2633 bool depth_only_arm = render_pass_state.numDrawCallsDepthEqualCompare >= kDepthPrePassNumDrawCallsArm &&
2634 render_pass_state.numDrawCallsDepthOnly >= kDepthPrePassNumDrawCallsArm;
2635 bool depth_only_img = render_pass_state.numDrawCallsDepthEqualCompare >= kDepthPrePassNumDrawCallsIMG &&
2636 render_pass_state.numDrawCallsDepthOnly >= kDepthPrePassNumDrawCallsIMG;
2637
2638 // Only send the warning when the vendor is enabled and a depth prepass is detected
LawG498ec4502022-04-05 09:08:25 +01002639 bool uses_depth =
2640 (render_pass_state.depthAttachment || render_pass_state.colorAttachment) &&
LawG45507e142022-04-08 09:36:54 +01002641 ((depth_only_arm && VendorCheckEnabled(kBPVendorArm)) || (depth_only_img && VendorCheckEnabled(kBPVendorIMG)));
LawG4b21485c2022-02-28 13:46:48 +00002642
Sam Walls0961ec02020-03-31 16:39:15 +01002643 if (uses_depth) {
2644 skip |= LogPerformanceWarning(
2645 device, kVUID_BestPractices_EndRenderPass_DepthPrePassUsage,
LawG4015be1c2022-03-01 10:37:52 +00002646 "%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 +00002647 "renderering architectures; such as those in Arm Mali or PowerVR GPUs. Since they can remove geometry "
2648 "hidden by other opaque geometry. Mali has Forward Pixel Killing (FPK), PowerVR has Hiden Surface "
2649 "Remover (HSR) in which case, using depth pre-passes for hidden surface removal may worsen performance.",
2650 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG));
Sam Walls0961ec02020-03-31 16:39:15 +01002651 }
2652
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002653 RENDER_PASS_STATE* rp = cmd->activeRenderPass.get();
2654
LawG40da9c3d2022-03-01 09:51:01 +00002655 if ((VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG)) && rp) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002656 // If we use an attachment on-tile, we should access it in some way. Otherwise,
2657 // it is redundant to have it be part of the render pass.
2658 // Only consider it redundant if it will actually consume bandwidth, i.e.
2659 // LOAD_OP_LOAD is used or STORE_OP_STORE. CLEAR -> DONT_CARE is benign,
2660 // as is using pure input attachments.
2661 // CLEAR -> STORE might be considered a "useful" thing to do, but
2662 // the optimal thing to do is to defer the clear until you're actually
2663 // going to render to the image.
2664
2665 uint32_t num_attachments = rp->createInfo.attachmentCount;
2666 for (uint32_t i = 0; i < num_attachments; i++) {
Hans-Kristian Arntzen237663c2021-07-01 14:36:40 +02002667 if (!RenderPassUsesAttachmentOnTile(rp->createInfo, i) ||
2668 RenderPassUsesAttachmentAsResolve(rp->createInfo, i)) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002669 continue;
2670 }
2671
2672 auto& attachment = rp->createInfo.pAttachments[i];
2673
2674 VkImageAspectFlags bandwidth_aspects = 0;
2675
2676 if (!FormatIsStencilOnly(attachment.format) &&
2677 (attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
2678 attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE)) {
2679 if (FormatHasDepth(attachment.format)) {
2680 bandwidth_aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
2681 } else {
2682 bandwidth_aspects |= VK_IMAGE_ASPECT_COLOR_BIT;
2683 }
2684 }
2685
2686 if (FormatHasStencil(attachment.format) &&
2687 (attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
2688 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE)) {
2689 bandwidth_aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
2690 }
2691
2692 if (!bandwidth_aspects) {
2693 continue;
2694 }
2695
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002696 auto itr = std::find_if(render_pass_state.touchesAttachments.begin(), render_pass_state.touchesAttachments.end(),
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002697 [i](const bp_state::AttachmentInfo& info) { return info.framebufferAttachment == i; });
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002698 uint32_t untouched_aspects = bandwidth_aspects;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002699 if (itr != render_pass_state.touchesAttachments.end()) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002700 untouched_aspects &= ~itr->aspects;
2701 }
2702
2703 if (untouched_aspects) {
2704 skip |= LogPerformanceWarning(
2705 device, kVUID_BestPractices_EndRenderPass_RedundantAttachmentOnTile,
LawG4015be1c2022-03-01 10:37:52 +00002706 "%s %s: Render pass was ended, but attachment #%u (format: %u, untouched aspects 0x%x) "
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002707 "was never accessed by a pipeline or clear command. "
LawG40da9c3d2022-03-01 09:51:01 +00002708 "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 +00002709 "render pass if the attachments are not intended to be accessed.",
LawG40da9c3d2022-03-01 09:51:01 +00002710 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), i, attachment.format, untouched_aspects);
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002711 }
2712 }
2713 }
2714
Sam Walls0961ec02020-03-31 16:39:15 +01002715 return skip;
2716}
2717
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002718void BestPractices::PreCallRecordCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002719 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2720 ValidateBoundDescriptorSets(*cb_node, "vkCmdDispatch()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002721}
2722
2723void BestPractices::PreCallRecordCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002724 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2725 ValidateBoundDescriptorSets(*cb_node, "vkCmdDispatchIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002726}
2727
Camden Stocker9c051442019-11-06 14:28:43 -08002728bool BestPractices::ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(VkPhysicalDevice physicalDevice,
2729 const char* api_name) const {
2730 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002731 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Camden Stocker9c051442019-11-06 14:28:43 -08002732
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002733 if (bp_pd_state) {
2734 if (bp_pd_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState == UNCALLED) {
2735 skip |= LogWarning(physicalDevice, kVUID_BestPractices_DisplayPlane_PropertiesNotCalled,
2736 "Potential problem with calling %s() without first retrieving properties from "
2737 "vkGetPhysicalDeviceDisplayPlanePropertiesKHR or vkGetPhysicalDeviceDisplayPlaneProperties2KHR.",
2738 api_name);
2739 }
Camden Stocker9c051442019-11-06 14:28:43 -08002740 }
2741
2742 return skip;
2743}
2744
Camden83a9c372019-08-14 11:41:38 -06002745bool BestPractices::PreCallValidateGetDisplayPlaneSupportedDisplaysKHR(VkPhysicalDevice physicalDevice, uint32_t planeIndex,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002746 uint32_t* pDisplayCount, VkDisplayKHR* pDisplays) const {
Camden83a9c372019-08-14 11:41:38 -06002747 bool skip = false;
2748
Camden Stocker9c051442019-11-06 14:28:43 -08002749 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneSupportedDisplaysKHR");
Camden83a9c372019-08-14 11:41:38 -06002750
Camden Stocker9c051442019-11-06 14:28:43 -08002751 return skip;
2752}
2753
2754bool BestPractices::PreCallValidateGetDisplayPlaneCapabilitiesKHR(VkPhysicalDevice physicalDevice, VkDisplayModeKHR mode,
2755 uint32_t planeIndex,
2756 VkDisplayPlaneCapabilitiesKHR* pCapabilities) const {
2757 bool skip = false;
2758
2759 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilitiesKHR");
2760
2761 return skip;
2762}
2763
2764bool BestPractices::PreCallValidateGetDisplayPlaneCapabilities2KHR(VkPhysicalDevice physicalDevice,
2765 const VkDisplayPlaneInfo2KHR* pDisplayPlaneInfo,
2766 VkDisplayPlaneCapabilities2KHR* pCapabilities) const {
2767 bool skip = false;
2768
2769 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilities2KHR");
Camden83a9c372019-08-14 11:41:38 -06002770
2771 return skip;
2772}
Camden05de2d42019-08-19 10:23:56 -06002773
2774bool BestPractices::PreCallValidateGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain, uint32_t* pSwapchainImageCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002775 VkImage* pSwapchainImages) const {
Camden05de2d42019-08-19 10:23:56 -06002776 bool skip = false;
2777
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002778 auto swapchain_state = Get<bp_state::Swapchain>(swapchain);
Camden05de2d42019-08-19 10:23:56 -06002779
Nathaniel Cesario39152e62021-07-02 13:04:16 -06002780 if (swapchain_state && pSwapchainImages) {
Camden05de2d42019-08-19 10:23:56 -06002781 // Compare the preliminary value of *pSwapchainImageCount with the value this time:
Nathaniel Cesario39152e62021-07-02 13:04:16 -06002782 if (swapchain_state->vkGetSwapchainImagesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002783 skip |=
2784 LogWarning(device, kVUID_Core_Swapchain_PriorCount,
2785 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImageCount; but no prior positive value has "
2786 "been seen for pSwapchainImages.");
Camden05de2d42019-08-19 10:23:56 -06002787 }
Camden05de2d42019-08-19 10:23:56 -06002788
Nathaniel Cesario4ce98382021-05-28 11:33:20 -06002789 if (*pSwapchainImageCount > swapchain_state->get_swapchain_image_count) {
2790 skip |= LogWarning(
2791 device, kVUID_BestPractices_Swapchain_InvalidCount,
2792 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImages, and with pSwapchainImageCount set to a "
Nadav Gevaf0808442021-05-21 13:51:25 -04002793 "value (%" PRId32 ") that is greater than the value (%" PRId32 ") that was returned when pSwapchainImages was NULL.",
Nathaniel Cesario4ce98382021-05-28 11:33:20 -06002794 *pSwapchainImageCount, swapchain_state->get_swapchain_image_count);
2795 }
2796 }
2797
Camden05de2d42019-08-19 10:23:56 -06002798 return skip;
2799}
2800
2801// Common function to handle validation for GetPhysicalDeviceQueueFamilyProperties & 2KHR version
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002802bool BestPractices::ValidateCommonGetPhysicalDeviceQueueFamilyProperties(const PHYSICAL_DEVICE_STATE* bp_pd_state,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002803 uint32_t requested_queue_family_property_count,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002804 const CALL_STATE call_state,
2805 const char* caller_name) const {
Camden05de2d42019-08-19 10:23:56 -06002806 bool skip = false;
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002807 // Verify that for each physical device, this command is called first with NULL pQueueFamilyProperties in order to get count
2808 if (UNCALLED == call_state) {
2809 skip |= LogWarning(
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002810 bp_pd_state->Handle(), kVUID_Core_DevLimit_MissingQueryCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002811 "%s is called with non-NULL pQueueFamilyProperties before obtaining pQueueFamilyPropertyCount. It is "
2812 "recommended "
2813 "to first call %s with NULL pQueueFamilyProperties in order to obtain the maximal pQueueFamilyPropertyCount.",
2814 caller_name, caller_name);
2815 // Then verify that pCount that is passed in on second call matches what was returned
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002816 } else if (bp_pd_state->queue_family_known_count != requested_queue_family_property_count) {
2817 skip |= LogWarning(bp_pd_state->Handle(), kVUID_Core_DevLimit_CountMismatch,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002818 "%s is called with non-NULL pQueueFamilyProperties and pQueueFamilyPropertyCount value %" PRIu32
2819 ", but the largest previously returned pQueueFamilyPropertyCount for this physicalDevice is %" PRIu32
2820 ". It is recommended to instead receive all the properties by calling %s with "
2821 "pQueueFamilyPropertyCount that was "
2822 "previously obtained by calling %s with NULL pQueueFamilyProperties.",
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002823 caller_name, requested_queue_family_property_count, bp_pd_state->queue_family_known_count, caller_name,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002824 caller_name);
Camden05de2d42019-08-19 10:23:56 -06002825 }
2826
2827 return skip;
2828}
2829
Jeff Bolz5c801d12019-10-09 10:38:45 -05002830bool BestPractices::PreCallValidateBindAccelerationStructureMemoryNV(
2831 VkDevice device, uint32_t bindInfoCount, const VkBindAccelerationStructureMemoryInfoNV* pBindInfos) const {
Camden Stocker82510582019-09-03 14:00:16 -06002832 bool skip = false;
2833
2834 for (uint32_t i = 0; i < bindInfoCount; i++) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07002835 auto as_state = Get<ACCELERATION_STRUCTURE_STATE>(pBindInfos[i].accelerationStructure);
Camden Stocker82510582019-09-03 14:00:16 -06002836 if (!as_state->memory_requirements_checked) {
2837 // There's not an explicit requirement in the spec to call vkGetImageMemoryRequirements() prior to calling
2838 // BindAccelerationStructureMemoryNV but it's implied in that memory being bound must conform with
2839 // VkAccelerationStructureMemoryRequirementsInfoNV from vkGetAccelerationStructureMemoryRequirementsNV
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002840 skip |= LogWarning(
2841 device, kVUID_BestPractices_BindAccelNV_NoMemReqQuery,
Camden Stocker82510582019-09-03 14:00:16 -06002842 "vkBindAccelerationStructureMemoryNV(): "
2843 "Binding memory to %s but vkGetAccelerationStructureMemoryRequirementsNV() has not been called on that structure.",
2844 report_data->FormatHandle(pBindInfos[i].accelerationStructure).c_str());
2845 }
2846 }
2847
2848 return skip;
2849}
2850
Camden05de2d42019-08-19 10:23:56 -06002851bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
2852 uint32_t* pQueueFamilyPropertyCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002853 VkQueueFamilyProperties* pQueueFamilyProperties) const {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002854 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002855 if (pQueueFamilyProperties && bp_pd_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002856 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(bp_pd_state.get(), *pQueueFamilyPropertyCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002857 bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
2858 "vkGetPhysicalDeviceQueueFamilyProperties()");
2859 }
2860 return false;
Camden05de2d42019-08-19 10:23:56 -06002861}
2862
Mike Schuchardt2df08912020-12-15 16:28:09 -08002863bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
2864 uint32_t* pQueueFamilyPropertyCount,
2865 VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002866 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002867 if (pQueueFamilyProperties && bp_pd_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002868 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(bp_pd_state.get(), *pQueueFamilyPropertyCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002869 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
2870 "vkGetPhysicalDeviceQueueFamilyProperties2()");
2871 }
2872 return false;
Camden05de2d42019-08-19 10:23:56 -06002873}
2874
Jeff Bolz5c801d12019-10-09 10:38:45 -05002875bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2KHR(
Mike Schuchardt2df08912020-12-15 16:28:09 -08002876 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount, VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002877 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002878 if (pQueueFamilyProperties && bp_pd_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002879 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(bp_pd_state.get(), *pQueueFamilyPropertyCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002880 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
2881 "vkGetPhysicalDeviceQueueFamilyProperties2KHR()");
2882 }
2883 return false;
Camden05de2d42019-08-19 10:23:56 -06002884}
2885
2886bool BestPractices::PreCallValidateGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
2887 uint32_t* pSurfaceFormatCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002888 VkSurfaceFormatKHR* pSurfaceFormats) const {
Camden05de2d42019-08-19 10:23:56 -06002889 if (!pSurfaceFormats) return false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002890 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002891 const auto& call_state = bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState;
Camden05de2d42019-08-19 10:23:56 -06002892 bool skip = false;
2893 if (call_state == UNCALLED) {
2894 // Since we haven't recorded a preliminary value of *pSurfaceFormatCount, that likely means that the application didn't
2895 // previously call this function with a NULL value of pSurfaceFormats:
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002896 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_MustQueryCount,
2897 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount; but no prior "
2898 "positive value has been seen for pSurfaceFormats.");
Camden05de2d42019-08-19 10:23:56 -06002899 } else {
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06002900 if (*pSurfaceFormatCount > bp_pd_state->surface_formats_count) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002901 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_CountMismatch,
2902 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount, and with "
2903 "pSurfaceFormats set to a value (%u) that is greater than the value (%u) that was returned "
2904 "when pSurfaceFormatCount was NULL.",
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06002905 *pSurfaceFormatCount, bp_pd_state->surface_formats_count);
Camden05de2d42019-08-19 10:23:56 -06002906 }
2907 }
2908 return skip;
2909}
Camden Stocker23cc47d2019-09-03 14:53:57 -06002910
2911bool BestPractices::PreCallValidateQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002912 VkFence fence) const {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002913 bool skip = false;
2914
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002915 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
2916 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
Camden Stocker23cc47d2019-09-03 14:53:57 -06002917 // 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 -07002918 layer_data::unordered_set<const IMAGE_STATE*> sparse_images;
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002919 // Track images getting metadata bound by this call in a set, it'll be recorded into the image_state
2920 // in RecordQueueBindSparse.
Jeremy Gebbencbf22862021-03-03 12:01:22 -07002921 layer_data::unordered_set<const IMAGE_STATE*> sparse_images_with_metadata;
Camden Stocker23cc47d2019-09-03 14:53:57 -06002922 // 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 -07002923 for (uint32_t i = 0; i < bind_info.imageBindCount; ++i) {
2924 const auto& image_bind = bind_info.pImageBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04002925 auto image_state = Get<IMAGE_STATE>(image_bind.image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002926 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002927 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002928 }
Jeremy Gebben9f537102021-10-05 16:37:12 -06002929 sparse_images.insert(image_state.get());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002930 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
2931 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
2932 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002933 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002934 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
2935 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002936 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002937 }
2938 }
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06002939 if (!image_state->memory_requirements_checked[0]) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002940 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002941 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002942 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
2943 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002944 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002945 }
2946 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002947 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
2948 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04002949 auto image_state = Get<IMAGE_STATE>(bind_info.pImageOpaqueBinds[i].image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002950 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002951 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002952 }
Jeremy Gebben9f537102021-10-05 16:37:12 -06002953 sparse_images.insert(image_state.get());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002954 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
2955 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
2956 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002957 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002958 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
2959 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002960 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002961 }
2962 }
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06002963 if (!image_state->memory_requirements_checked[0]) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002964 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002965 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002966 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
2967 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002968 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002969 }
2970 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
2971 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002972 sparse_images_with_metadata.insert(image_state.get());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002973 }
2974 }
2975 }
2976 for (const auto& sparse_image_state : sparse_images) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002977 if (sparse_image_state->sparse_metadata_required && !sparse_image_state->sparse_metadata_bound &&
2978 sparse_images_with_metadata.find(sparse_image_state) == sparse_images_with_metadata.end()) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002979 // Warn if sparse image binding metadata required for image with sparse binding, but metadata not bound
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002980 skip |= LogWarning(sparse_image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002981 "vkQueueBindSparse(): Binding sparse memory to %s which requires a metadata aspect but no "
2982 "binding with VK_SPARSE_MEMORY_BIND_METADATA_BIT set was made.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002983 report_data->FormatHandle(sparse_image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002984 }
2985 }
2986 }
2987
2988 return skip;
2989}
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002990
Mark Lobodzinski84101d72020-04-24 09:43:48 -06002991void BestPractices::ManualPostCallRecordQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
2992 VkFence fence, VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07002993 if (result != VK_SUCCESS) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07002994 return;
2995 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002996
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002997 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
2998 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
2999 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
3000 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04003001 auto image_state = Get<IMAGE_STATE>(bind_info.pImageOpaqueBinds[i].image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003002 if (!image_state) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05003003 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003004 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05003005 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
3006 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
3007 image_state->sparse_metadata_bound = true;
3008 }
3009 }
3010 }
3011 }
3012}
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003013
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003014bool BestPractices::ClearAttachmentsIsFullClear(const bp_state::CommandBuffer& cmd, uint32_t rectCount,
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003015 const VkClearRect* pRects) const {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003016 if (cmd.createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003017 // We don't know the accurate render area in a secondary,
3018 // so assume we clear the entire frame buffer.
3019 // This is resolved in CmdExecuteCommands where we can check if the clear is a full clear.
3020 return true;
3021 }
3022
3023 // If we have a rect which covers the entire frame buffer, we have a LOAD_OP_CLEAR-like command.
3024 for (uint32_t i = 0; i < rectCount; i++) {
3025 auto& rect = pRects[i];
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003026 auto& render_area = cmd.activeRenderPassBeginInfo.renderArea;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003027 if (rect.rect.extent.width == render_area.extent.width && rect.rect.extent.height == render_area.extent.height) {
3028 return true;
3029 }
3030 }
3031
3032 return false;
3033}
3034
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003035bool BestPractices::ValidateClearAttachment(const bp_state::CommandBuffer& cmd, uint32_t fb_attachment, uint32_t color_attachment,
3036 VkImageAspectFlags aspects, bool secondary) const {
3037 const RENDER_PASS_STATE* rp = cmd.activeRenderPass.get();
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003038 bool skip = false;
3039
3040 if (!rp || fb_attachment == VK_ATTACHMENT_UNUSED) {
3041 return skip;
3042 }
3043
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003044 const auto& rp_state = cmd.render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003045
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003046 auto attachment_itr =
3047 std::find_if(rp_state.touchesAttachments.begin(), rp_state.touchesAttachments.end(),
3048 [fb_attachment](const bp_state::AttachmentInfo& info) { return info.framebufferAttachment == fb_attachment; });
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003049
3050 // Only report aspects which haven't been touched yet.
3051 VkImageAspectFlags new_aspects = aspects;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003052 if (attachment_itr != rp_state.touchesAttachments.end()) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003053 new_aspects &= ~attachment_itr->aspects;
3054 }
3055
3056 // Warn if this is issued prior to Draw Cmd and clearing the entire attachment
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003057 if (!cmd.hasDrawCmd) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003058 skip |= LogPerformanceWarning(
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003059 cmd.Handle(), kVUID_BestPractices_DrawState_ClearCmdBeforeDraw,
Hans-Kristian Arntzen4ddd6182021-06-18 12:16:33 +02003060 "vkCmdClearAttachments() issued on %s prior to any Draw Cmds in current render pass. It is recommended you "
3061 "use RenderPass LOAD_OP_CLEAR on attachments instead.",
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003062 report_data->FormatHandle(cmd.Handle()).c_str());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003063 }
3064
3065 if ((new_aspects & VK_IMAGE_ASPECT_COLOR_BIT) &&
3066 rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
3067 skip |= LogPerformanceWarning(
3068 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
3069 "%svkCmdClearAttachments() issued on %s for color attachment #%u in this subpass, "
3070 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
3071 "it is more efficient.",
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003072 secondary ? "vkCmdExecuteCommands(): " : "", report_data->FormatHandle(cmd.Handle()).c_str(), color_attachment);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003073 }
3074
3075 if ((new_aspects & VK_IMAGE_ASPECT_DEPTH_BIT) &&
3076 rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003077 skip |=
3078 LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
3079 "%svkCmdClearAttachments() issued on %s for the depth attachment in this subpass, "
3080 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
3081 "it is more efficient.",
3082 secondary ? "vkCmdExecuteCommands(): " : "", report_data->FormatHandle(cmd.Handle()).c_str());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003083 }
3084
3085 if ((new_aspects & VK_IMAGE_ASPECT_STENCIL_BIT) &&
3086 rp->createInfo.pAttachments[fb_attachment].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003087 skip |=
3088 LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
3089 "%svkCmdClearAttachments() issued on %s for the stencil attachment in this subpass, "
3090 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
3091 "it is more efficient.",
3092 secondary ? "vkCmdExecuteCommands(): " : "", report_data->FormatHandle(cmd.Handle()).c_str());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003093 }
3094
3095 return skip;
3096}
3097
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003098bool BestPractices::PreCallValidateCmdClearAttachments(VkCommandBuffer commandBuffer, uint32_t attachmentCount,
Camden Stockerf55721f2019-09-09 11:04:49 -06003099 const VkClearAttachment* pAttachments, uint32_t rectCount,
3100 const VkClearRect* pRects) const {
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003101 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003102 const auto cb_node = GetRead<bp_state::CommandBuffer>(commandBuffer);
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003103 if (!cb_node) return skip;
3104
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003105 if (cb_node->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
3106 // Defer checks to ExecuteCommands.
3107 return skip;
3108 }
3109
3110 // Only care about full clears, partial clears might have legitimate uses.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003111 if (!ClearAttachmentsIsFullClear(*cb_node, rectCount, pRects)) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003112 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003113 }
3114
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003115 // Check for uses of ClearAttachments along with LOAD_OP_LOAD,
3116 // as it can be more efficient to just use LOAD_OP_CLEAR
locke-lunargaecf2152020-05-12 17:15:41 -06003117 const RENDER_PASS_STATE* rp = cb_node->activeRenderPass.get();
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003118 if (rp) {
3119 const auto& subpass = rp->createInfo.pSubpasses[cb_node->activeSubpass];
3120
3121 for (uint32_t i = 0; i < attachmentCount; i++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02003122 const auto& attachment = pAttachments[i];
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003123
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003124 if (attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
3125 uint32_t color_attachment = attachment.colorAttachment;
3126 uint32_t fb_attachment = subpass.pColorAttachments[color_attachment].attachment;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003127 skip |= ValidateClearAttachment(*cb_node, fb_attachment, color_attachment, attachment.aspectMask, false);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003128 }
3129
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003130 if (subpass.pDepthStencilAttachment &&
3131 (attachment.aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT))) {
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003132 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003133 skip |= ValidateClearAttachment(*cb_node, fb_attachment, VK_ATTACHMENT_UNUSED, attachment.aspectMask, false);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003134 }
3135 }
3136 }
3137
Nadav Gevaf0808442021-05-21 13:51:25 -04003138 if (VendorCheckEnabled(kBPVendorAMD)) {
3139 for (uint32_t attachment_idx = 0; attachment_idx < attachmentCount; attachment_idx++) {
3140 if (pAttachments[attachment_idx].aspectMask == VK_IMAGE_ASPECT_COLOR_BIT) {
3141 bool black_check = false;
3142 black_check |= pAttachments[attachment_idx].clearValue.color.float32[0] != 0.0f;
3143 black_check |= pAttachments[attachment_idx].clearValue.color.float32[1] != 0.0f;
3144 black_check |= pAttachments[attachment_idx].clearValue.color.float32[2] != 0.0f;
3145 black_check |= pAttachments[attachment_idx].clearValue.color.float32[3] != 0.0f &&
3146 pAttachments[attachment_idx].clearValue.color.float32[3] != 1.0f;
3147
3148 bool white_check = false;
3149 white_check |= pAttachments[attachment_idx].clearValue.color.float32[0] != 1.0f;
3150 white_check |= pAttachments[attachment_idx].clearValue.color.float32[1] != 1.0f;
3151 white_check |= pAttachments[attachment_idx].clearValue.color.float32[2] != 1.0f;
3152 white_check |= pAttachments[attachment_idx].clearValue.color.float32[3] != 0.0f &&
3153 pAttachments[attachment_idx].clearValue.color.float32[3] != 1.0f;
3154
3155 if (black_check && white_check) {
3156 skip |= LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachment_FastClearValues,
3157 "%s Performance warning: vkCmdClearAttachments() clear value for color attachment %" PRId32 " is not a fast clear value."
3158 "Consider changing to one of the following:"
3159 "RGBA(0, 0, 0, 0) "
3160 "RGBA(0, 0, 0, 1) "
3161 "RGBA(1, 1, 1, 0) "
3162 "RGBA(1, 1, 1, 1)",
3163 VendorSpecificTag(kBPVendorAMD), attachment_idx);
3164 }
3165 } else {
3166 if ((pAttachments[attachment_idx].clearValue.depthStencil.depth != 0 &&
3167 pAttachments[attachment_idx].clearValue.depthStencil.depth != 1) &&
3168 pAttachments[attachment_idx].clearValue.depthStencil.stencil != 0) {
3169 skip |= LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachment_FastClearValues,
3170 "%s Performance warning: vkCmdClearAttachments() clear value for depth/stencil "
3171 "attachment %" PRId32 " is not a fast clear value."
3172 "Consider changing to one of the following:"
3173 "D=0.0f, S=0"
3174 "D=1.0f, S=0",
3175 VendorSpecificTag(kBPVendorAMD), attachment_idx);
3176 }
3177 }
3178 }
3179 }
3180
Camden Stockerf55721f2019-09-09 11:04:49 -06003181 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003182}
Attilio Provenzano02859b22020-02-27 14:17:28 +00003183
3184bool BestPractices::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3185 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3186 const VkImageResolve* pRegions) const {
3187 bool skip = false;
3188
3189 skip |= VendorCheckEnabled(kBPVendorArm) &&
3190 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage_ResolvingImage,
3191 "%s Attempting to use vkCmdResolveImage to resolve a multisampled image. "
3192 "This is a very slow and extremely bandwidth intensive path. "
3193 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
3194 VendorSpecificTag(kBPVendorArm));
3195
3196 return skip;
3197}
3198
Jeff Leger178b1e52020-10-05 12:22:23 -04003199bool BestPractices::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
3200 const VkResolveImageInfo2KHR* pResolveImageInfo) const {
3201 bool skip = false;
3202
3203 skip |= VendorCheckEnabled(kBPVendorArm) &&
3204 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2KHR_ResolvingImage,
3205 "%s Attempting to use vkCmdResolveImage2KHR to resolve a multisampled image. "
3206 "This is a very slow and extremely bandwidth intensive path. "
3207 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
3208 VendorSpecificTag(kBPVendorArm));
3209
3210 return skip;
3211}
3212
Tony-LunarGd36f5f32022-01-20 11:49:59 -07003213bool BestPractices::PreCallValidateCmdResolveImage2(VkCommandBuffer commandBuffer,
3214 const VkResolveImageInfo2* pResolveImageInfo) const {
3215 bool skip = false;
3216
3217 skip |= VendorCheckEnabled(kBPVendorArm) &&
3218 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2_ResolvingImage,
3219 "%s Attempting to use vkCmdResolveImage2 to resolve a multisampled image. "
3220 "This is a very slow and extremely bandwidth intensive path. "
3221 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
3222 VendorSpecificTag(kBPVendorArm));
3223
3224 return skip;
3225}
3226
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003227void BestPractices::PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3228 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3229 const VkImageResolve* pRegions) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003230 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003231 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003232 auto src = Get<bp_state::Image>(srcImage);
3233 auto dst = Get<bp_state::Image>(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003234
3235 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003236 QueueValidateImage(funcs, "vkCmdResolveImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pRegions[i].srcSubresource);
3237 QueueValidateImage(funcs, "vkCmdResolveImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003238 }
3239}
3240
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01003241void BestPractices::PreCallRecordCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
3242 const VkResolveImageInfo2KHR* pResolveImageInfo) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003243 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003244 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003245 auto src = Get<bp_state::Image>(pResolveImageInfo->srcImage);
3246 auto dst = Get<bp_state::Image>(pResolveImageInfo->dstImage);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01003247 uint32_t regionCount = pResolveImageInfo->regionCount;
3248
3249 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003250 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pResolveImageInfo->pRegions[i].srcSubresource);
3251 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pResolveImageInfo->pRegions[i].dstSubresource);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01003252 }
3253}
3254
Tony-LunarGd36f5f32022-01-20 11:49:59 -07003255void BestPractices::PreCallRecordCmdResolveImage2(VkCommandBuffer commandBuffer,
3256 const VkResolveImageInfo2* pResolveImageInfo) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003257 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Tony-LunarGd36f5f32022-01-20 11:49:59 -07003258 auto& funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003259 auto src = Get<bp_state::Image>(pResolveImageInfo->srcImage);
3260 auto dst = Get<bp_state::Image>(pResolveImageInfo->dstImage);
Tony-LunarGd36f5f32022-01-20 11:49:59 -07003261 uint32_t regionCount = pResolveImageInfo->regionCount;
3262
3263 for (uint32_t i = 0; i < regionCount; i++) {
3264 QueueValidateImage(funcs, "vkCmdResolveImage2()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ,
3265 pResolveImageInfo->pRegions[i].srcSubresource);
3266 QueueValidateImage(funcs, "vkCmdResolveImage2()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE,
3267 pResolveImageInfo->pRegions[i].dstSubresource);
3268 }
3269}
3270
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003271void BestPractices::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
3272 const VkClearColorValue* pColor, uint32_t rangeCount,
3273 const VkImageSubresourceRange* pRanges) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003274 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003275 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003276 auto dst = Get<bp_state::Image>(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003277
3278 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003279 QueueValidateImage(funcs, "vkCmdClearColorImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003280 }
3281}
3282
3283void BestPractices::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
3284 const VkClearDepthStencilValue* pDepthStencil, uint32_t rangeCount,
3285 const VkImageSubresourceRange* pRanges) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003286 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003287 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003288 auto dst = Get<bp_state::Image>(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003289
3290 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003291 QueueValidateImage(funcs, "vkCmdClearDepthStencilImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003292 }
3293}
3294
3295void BestPractices::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3296 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3297 const VkImageCopy* pRegions) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003298 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003299 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003300 auto src = Get<bp_state::Image>(srcImage);
3301 auto dst = Get<bp_state::Image>(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003302
3303 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003304 QueueValidateImage(funcs, "vkCmdCopyImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].srcSubresource);
3305 QueueValidateImage(funcs, "vkCmdCopyImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003306 }
3307}
3308
3309void BestPractices::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
3310 VkImageLayout dstImageLayout, uint32_t regionCount,
3311 const VkBufferImageCopy* pRegions) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003312 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003313 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003314 auto dst = Get<bp_state::Image>(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003315
3316 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003317 QueueValidateImage(funcs, "vkCmdCopyBufferToImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003318 }
3319}
3320
3321void BestPractices::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3322 VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy* pRegions) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003323 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003324 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003325 auto src = Get<bp_state::Image>(srcImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003326
3327 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003328 QueueValidateImage(funcs, "vkCmdCopyImageToBuffer()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003329 }
3330}
3331
3332void BestPractices::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3333 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3334 const VkImageBlit* pRegions, VkFilter filter) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003335 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003336 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003337 auto src = Get<bp_state::Image>(srcImage);
3338 auto dst = Get<bp_state::Image>(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003339
3340 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003341 QueueValidateImage(funcs, "vkCmdBlitImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_READ, pRegions[i].srcSubresource);
3342 QueueValidateImage(funcs, "vkCmdBlitImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003343 }
3344}
3345
Attilio Provenzano02859b22020-02-27 14:17:28 +00003346bool BestPractices::PreCallValidateCreateSampler(VkDevice device, const VkSamplerCreateInfo* pCreateInfo,
3347 const VkAllocationCallbacks* pAllocator, VkSampler* pSampler) const {
3348 bool skip = false;
3349
3350 if (VendorCheckEnabled(kBPVendorArm)) {
3351 if ((pCreateInfo->addressModeU != pCreateInfo->addressModeV) || (pCreateInfo->addressModeV != pCreateInfo->addressModeW)) {
3352 skip |= LogPerformanceWarning(
3353 device, kVUID_BestPractices_CreateSampler_DifferentWrappingModes,
3354 "%s Creating a sampler object with wrapping modes which do not match (U = %u, V = %u, W = %u). "
3355 "This may cause reduced performance even if only U (1D image) or U/V wrapping modes (2D "
3356 "image) are actually used. If you need different wrapping modes, disregard this warning.",
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -06003357 VendorSpecificTag(kBPVendorArm), pCreateInfo->addressModeU, pCreateInfo->addressModeV, pCreateInfo->addressModeW);
Attilio Provenzano02859b22020-02-27 14:17:28 +00003358 }
3359
3360 if ((pCreateInfo->minLod != 0.0f) || (pCreateInfo->maxLod < VK_LOD_CLAMP_NONE)) {
3361 skip |= LogPerformanceWarning(
3362 device, kVUID_BestPractices_CreateSampler_LodClamping,
3363 "%s Creating a sampler object with LOD clamping (minLod = %f, maxLod = %f). This may cause reduced performance. "
3364 "Instead of clamping LOD in the sampler, consider using an VkImageView which restricts the mip-levels, set minLod "
3365 "to 0.0, and maxLod to VK_LOD_CLAMP_NONE.",
3366 VendorSpecificTag(kBPVendorArm), pCreateInfo->minLod, pCreateInfo->maxLod);
3367 }
3368
3369 if (pCreateInfo->mipLodBias != 0.0f) {
3370 skip |=
3371 LogPerformanceWarning(device, kVUID_BestPractices_CreateSampler_LodBias,
3372 "%s Creating a sampler object with LOD bias != 0.0 (%f). This will lead to less efficient "
3373 "descriptors being created and may cause reduced performance.",
3374 VendorSpecificTag(kBPVendorArm), pCreateInfo->mipLodBias);
3375 }
3376
3377 if ((pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
3378 pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
3379 pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER) &&
3380 (pCreateInfo->borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK)) {
3381 skip |= LogPerformanceWarning(
3382 device, kVUID_BestPractices_CreateSampler_BorderClampColor,
3383 "%s Creating a sampler object with border clamping and borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK. "
3384 "This will lead to less efficient descriptors being created and may cause reduced performance. "
3385 "If possible, use VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK as the border color.",
3386 VendorSpecificTag(kBPVendorArm));
3387 }
3388
3389 if (pCreateInfo->unnormalizedCoordinates) {
3390 skip |= LogPerformanceWarning(
3391 device, kVUID_BestPractices_CreateSampler_UnnormalizedCoordinates,
3392 "%s Creating a sampler object with unnormalized coordinates. This will lead to less efficient "
3393 "descriptors being created and may cause reduced performance.",
3394 VendorSpecificTag(kBPVendorArm));
3395 }
3396
3397 if (pCreateInfo->anisotropyEnable) {
3398 skip |= LogPerformanceWarning(
3399 device, kVUID_BestPractices_CreateSampler_Anisotropy,
3400 "%s Creating a sampler object with anisotropy. This will lead to less efficient descriptors being created "
3401 "and may cause reduced performance.",
3402 VendorSpecificTag(kBPVendorArm));
3403 }
3404 }
3405
3406 return skip;
3407}
Sam Walls8e77e4f2020-03-16 20:47:40 +00003408
Nadav Gevaf0808442021-05-21 13:51:25 -04003409void BestPractices::PreCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
3410 const VkGraphicsPipelineCreateInfo* pCreateInfos,
3411 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
3412 void* cgpl_state) {
3413 ValidationStateTracker::PreCallRecordCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos, pAllocator,
3414 pPipelines);
3415 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003416 num_pso_ += createInfoCount;
Nadav Gevaf0808442021-05-21 13:51:25 -04003417}
3418
3419bool BestPractices::PreCallValidateUpdateDescriptorSets(VkDevice device, uint32_t descriptorWriteCount,
3420 const VkWriteDescriptorSet* pDescriptorWrites, uint32_t descriptorCopyCount,
3421 const VkCopyDescriptorSet* pDescriptorCopies) const {
3422 bool skip = false;
3423 if (VendorCheckEnabled(kBPVendorAMD)) {
3424 if (descriptorCopyCount > 0) {
3425 skip |= LogPerformanceWarning(device, kVUID_BestPractices_UpdateDescriptors_AvoidCopyingDescriptors,
3426 "%s Performance warning: copying descriptor sets is not recommended",
3427 VendorSpecificTag(kBPVendorAMD));
3428 }
3429 }
3430
3431 return skip;
3432}
3433
3434bool BestPractices::PreCallValidateCreateDescriptorUpdateTemplate(VkDevice device,
3435 const VkDescriptorUpdateTemplateCreateInfo* pCreateInfo,
3436 const VkAllocationCallbacks* pAllocator,
3437 VkDescriptorUpdateTemplate* pDescriptorUpdateTemplate) const {
3438 bool skip = false;
3439 if (VendorCheckEnabled(kBPVendorAMD)) {
3440 skip |= LogPerformanceWarning(device, kVUID_BestPractices_UpdateDescriptors_PreferNonTemplate,
3441 "%s Performance warning: using DescriptorSetWithTemplate is not recommended. Prefer using "
3442 "vkUpdateDescriptorSet instead",
3443 VendorSpecificTag(kBPVendorAMD));
3444 }
3445
3446 return skip;
3447}
3448
3449bool BestPractices::PreCallValidateCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
3450 const VkClearColorValue* pColor, uint32_t rangeCount,
3451 const VkImageSubresourceRange* pRanges) const {
3452 bool skip = false;
3453 if (VendorCheckEnabled(kBPVendorAMD)) {
sfricke-samsungef15e482022-01-26 11:32:49 -08003454 skip |= LogPerformanceWarning(
3455 device, kVUID_BestPractices_ClearAttachment_ClearImage,
Nadav Gevaf0808442021-05-21 13:51:25 -04003456 "%s Performance warning: using vkCmdClearColorImage is not recommended. Prefer using LOAD_OP_CLEAR or "
3457 "vkCmdClearAttachments instead",
3458 VendorSpecificTag(kBPVendorAMD));
3459 }
3460
3461 return skip;
3462}
3463
3464bool BestPractices::PreCallValidateCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image,
3465 VkImageLayout imageLayout,
3466 const VkClearDepthStencilValue* pDepthStencil, uint32_t rangeCount,
3467 const VkImageSubresourceRange* pRanges) const {
3468 bool skip = false;
3469 if (VendorCheckEnabled(kBPVendorAMD)) {
3470 skip |= LogPerformanceWarning(
3471 device, kVUID_BestPractices_ClearAttachment_ClearImage,
3472 "%s Performance warning: using vkCmdClearDepthStencilImage is not recommended. Prefer using LOAD_OP_CLEAR or "
3473 "vkCmdClearAttachments instead",
3474 VendorSpecificTag(kBPVendorAMD));
3475 }
3476
3477 return skip;
3478}
3479
3480bool BestPractices::PreCallValidateCreatePipelineLayout(VkDevice device, const VkPipelineLayoutCreateInfo* pCreateInfo,
3481 const VkAllocationCallbacks* pAllocator,
3482 VkPipelineLayout* pPipelineLayout) const {
3483 bool skip = false;
3484 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003485 uint32_t descriptor_size = enabled_features.core.robustBufferAccess ? 4 : 2;
Nadav Gevaf0808442021-05-21 13:51:25 -04003486 // Descriptor sets cost 1 DWORD each.
3487 // Dynamic buffers cost 2 DWORDs each when robust buffer access is OFF.
3488 // Dynamic buffers cost 4 DWORDs each when robust buffer access is ON.
3489 // Push constants cost 1 DWORD per 4 bytes in the Push constant range.
3490 uint32_t pipeline_size = pCreateInfo->setLayoutCount; // in DWORDS
3491 for (uint32_t i = 0; i < pCreateInfo->setLayoutCount; i++) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06003492 auto descriptor_set_layout_state = Get<cvdescriptorset::DescriptorSetLayout>(pCreateInfo->pSetLayouts[i]);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003493 pipeline_size += descriptor_set_layout_state->GetDynamicDescriptorCount() * descriptor_size;
Nadav Gevaf0808442021-05-21 13:51:25 -04003494 }
3495
3496 for (uint32_t i = 0; i < pCreateInfo->pushConstantRangeCount; i++) {
3497 pipeline_size += pCreateInfo->pPushConstantRanges[i].size / 4;
3498 }
3499
3500 if (pipeline_size > kPipelineLayoutSizeWarningLimitAMD) {
3501 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelinesLayout_KeepLayoutSmall,
3502 "%s Performance warning: pipeline layout size is too large. Prefer smaller pipeline layouts."
3503 "Descriptor sets cost 1 DWORD each. "
3504 "Dynamic buffers cost 2 DWORDs each when robust buffer access is OFF. "
3505 "Dynamic buffers cost 4 DWORDs each when robust buffer access is ON. "
3506 "Push constants cost 1 DWORD per 4 bytes in the Push constant range. ",
3507 VendorSpecificTag(kBPVendorAMD));
3508 }
3509 }
3510
3511 return skip;
3512}
3513
3514bool BestPractices::PreCallValidateCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3515 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3516 const VkImageCopy* pRegions) const {
3517 bool skip = false;
3518 std::stringstream src_image_hex;
3519 std::stringstream dst_image_hex;
3520 src_image_hex << "0x" << std::hex << HandleToUint64(srcImage);
3521 dst_image_hex << "0x" << std::hex << HandleToUint64(dstImage);
3522
3523 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07003524 auto src_state = Get<IMAGE_STATE>(srcImage);
3525 auto dst_state = Get<IMAGE_STATE>(dstImage);
Nadav Gevaf0808442021-05-21 13:51:25 -04003526
3527 if (src_state && dst_state) {
3528 VkImageTiling src_Tiling = src_state->createInfo.tiling;
3529 VkImageTiling dst_Tiling = dst_state->createInfo.tiling;
3530 if (src_Tiling != dst_Tiling && (src_Tiling == VK_IMAGE_TILING_LINEAR || dst_Tiling == VK_IMAGE_TILING_LINEAR)) {
3531 skip |=
3532 LogPerformanceWarning(device, kVUID_BestPractices_vkImage_AvoidImageToImageCopy,
3533 "%s Performance warning: image %s and image %s have differing tilings. Use buffer to "
3534 "image (vkCmdCopyImageToBuffer) "
3535 "and image to buffer (vkCmdCopyBufferToImage) copies instead of image to image "
3536 "copies when converting between linear and optimal images",
3537 VendorSpecificTag(kBPVendorAMD), src_image_hex.str().c_str(), dst_image_hex.str().c_str());
3538 }
3539 }
3540 }
3541
3542 return skip;
3543}
3544
3545bool BestPractices::PreCallValidateCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
3546 VkPipeline pipeline) const {
3547 bool skip = false;
3548
3549 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003550 if (IsPipelineUsedInFrame(pipeline)) {
Nadav Gevaf0808442021-05-21 13:51:25 -04003551 skip |= LogPerformanceWarning(device, kVUID_BestPractices_Pipeline_SortAndBind,
3552 "%s Performance warning: Pipeline %s was bound twice in the frame. Keep pipeline state changes to a minimum,"
3553 "for example, by sorting draw calls by pipeline.",
3554 VendorSpecificTag(kBPVendorAMD), report_data->FormatHandle(pipeline).c_str());
3555 }
3556 }
3557
3558 return skip;
3559}
3560
3561void BestPractices::ManualPostCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
3562 VkFence fence, VkResult result) {
3563 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003564 num_queue_submissions_ += submitCount;
Nadav Gevaf0808442021-05-21 13:51:25 -04003565}
3566
3567bool BestPractices::PreCallValidateQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo) const {
3568 bool skip = false;
3569
3570 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003571 auto num = num_queue_submissions_.load();
3572 if (num > kNumberOfSubmissionWarningLimitAMD) {
3573 skip |= LogPerformanceWarning(device, kVUID_BestPractices_Submission_ReduceNumberOfSubmissions,
3574 "%s Performance warning: command buffers submitted %" PRId32
3575 " times this frame. Submitting command buffers has a CPU "
3576 "and GPU overhead. Submit fewer times to incur less overhead.",
3577 VendorSpecificTag(kBPVendorAMD), num);
Nadav Gevaf0808442021-05-21 13:51:25 -04003578 }
3579 }
3580
3581 return skip;
3582}
3583
3584void BestPractices::PostCallRecordCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
3585 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
3586 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
3587 uint32_t bufferMemoryBarrierCount,
3588 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
3589 uint32_t imageMemoryBarrierCount,
3590 const VkImageMemoryBarrier* pImageMemoryBarriers) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003591 num_barriers_objects_ += (memoryBarrierCount + imageMemoryBarrierCount + bufferMemoryBarrierCount);
Nadav Gevaf0808442021-05-21 13:51:25 -04003592}
3593
3594bool BestPractices::PreCallValidateCreateSemaphore(VkDevice device, const VkSemaphoreCreateInfo* pCreateInfo,
3595 const VkAllocationCallbacks* pAllocator, VkSemaphore* pSemaphore) const {
3596 bool skip = false;
3597 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003598 if (Count<SEMAPHORE_STATE>() > kMaxRecommendedSemaphoreObjectsSizeAMD) {
Nadav Gevaf0808442021-05-21 13:51:25 -04003599 skip |= LogPerformanceWarning(device, kVUID_BestPractices_SyncObjects_HighNumberOfSemaphores,
3600 "%s Performance warning: High number of vkSemaphore objects created."
3601 "Minimize the amount of queue synchronization that is used. "
3602 "Semaphores and fences have overhead. Each fence has a CPU and GPU cost with it.",
3603 VendorSpecificTag(kBPVendorAMD));
3604 }
3605 }
3606
3607 return skip;
3608}
3609
3610bool BestPractices::PreCallValidateCreateFence(VkDevice device, const VkFenceCreateInfo* pCreateInfo,
3611 const VkAllocationCallbacks* pAllocator, VkFence* pFence) const {
3612 bool skip = false;
3613 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003614 if (Count<FENCE_STATE>() > kMaxRecommendedFenceObjectsSizeAMD) {
Nadav Gevaf0808442021-05-21 13:51:25 -04003615 skip |= LogPerformanceWarning(device, kVUID_BestPractices_SyncObjects_HighNumberOfFences,
3616 "%s Performance warning: High number of VkFence objects created."
3617 "Minimize the amount of CPU-GPU synchronization that is used. "
3618 "Semaphores and fences have overhead.Each fence has a CPU and GPU cost with it.",
3619 VendorSpecificTag(kBPVendorAMD));
3620 }
3621 }
3622
3623 return skip;
3624}
3625
Sam Walls8e77e4f2020-03-16 20:47:40 +00003626void BestPractices::PostTransformLRUCacheModel::resize(size_t size) { _entries.resize(size); }
3627
3628bool BestPractices::PostTransformLRUCacheModel::query_cache(uint32_t value) {
3629 // look for a cache hit
3630 auto hit = std::find_if(_entries.begin(), _entries.end(), [value](const CacheEntry& entry) { return entry.value == value; });
3631 if (hit != _entries.end()) {
3632 // mark the cache hit as being most recently used
3633 hit->age = iteration++;
3634 return true;
3635 }
3636
3637 // if there's no cache hit, we need to model the entry being inserted into the cache
3638 CacheEntry new_entry = {value, iteration};
3639 if (iteration < static_cast<uint32_t>(std::distance(_entries.begin(), _entries.end()))) {
3640 // if there is still space left in the cache, use the next available slot
3641 *(_entries.begin() + iteration) = new_entry;
3642 } else {
3643 // otherwise replace the least recently used cache entry
3644 auto lru = std::min_element(_entries.begin(), hit, [](const CacheEntry& a, const CacheEntry& b) { return a.age < b.age; });
3645 *lru = new_entry;
3646 }
3647 iteration++;
3648 return false;
3649}
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003650
3651bool BestPractices::PreCallValidateAcquireNextImageKHR(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout,
3652 VkSemaphore semaphore, VkFence fence, uint32_t* pImageIndex) const {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07003653 auto swapchain_data = Get<SWAPCHAIN_NODE>(swapchain);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003654 bool skip = false;
3655 if (swapchain_data && swapchain_data->images.size() == 0) {
3656 skip |= LogWarning(swapchain, kVUID_Core_DrawState_SwapchainImagesNotFound,
3657 "vkAcquireNextImageKHR: No images found to acquire from. Application probably did not call "
3658 "vkGetSwapchainImagesKHR after swapchain creation.");
3659 }
3660 return skip;
3661}
3662
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003663void BestPractices::CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(CALL_STATE& call_state, bool no_pointer) {
3664 if (no_pointer) {
3665 if (UNCALLED == call_state) {
3666 call_state = QUERY_COUNT;
3667 }
3668 } else { // Save queue family properties
3669 call_state = QUERY_DETAILS;
3670 }
3671}
3672
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003673void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
3674 uint32_t* pQueueFamilyPropertyCount,
3675 VkQueueFamilyProperties* pQueueFamilyProperties) {
3676 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(physicalDevice, pQueueFamilyPropertyCount,
3677 pQueueFamilyProperties);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003678 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003679 if (bp_pd_state) {
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003680 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
3681 nullptr == pQueueFamilyProperties);
3682 }
3683}
3684
3685void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
3686 uint32_t* pQueueFamilyPropertyCount,
3687 VkQueueFamilyProperties2* pQueueFamilyProperties) {
3688 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(physicalDevice, pQueueFamilyPropertyCount,
3689 pQueueFamilyProperties);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003690 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003691 if (bp_pd_state) {
3692 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
3693 nullptr == pQueueFamilyProperties);
3694 }
3695}
3696
3697void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(VkPhysicalDevice physicalDevice,
3698 uint32_t* pQueueFamilyPropertyCount,
3699 VkQueueFamilyProperties2* pQueueFamilyProperties) {
3700 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(physicalDevice, pQueueFamilyPropertyCount,
3701 pQueueFamilyProperties);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003702 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003703 if (bp_pd_state) {
3704 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
3705 nullptr == pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003706 }
3707}
3708
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003709void BestPractices::PostCallRecordGetPhysicalDeviceFeatures(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures* pFeatures) {
3710 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures(physicalDevice, pFeatures);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003711 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003712 if (bp_pd_state) {
3713 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3714 }
3715}
3716
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003717void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2(VkPhysicalDevice physicalDevice,
3718 VkPhysicalDeviceFeatures2* pFeatures) {
3719 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2(physicalDevice, pFeatures);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003720 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003721 if (bp_pd_state) {
3722 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3723 }
3724}
3725
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003726void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2KHR(VkPhysicalDevice physicalDevice,
3727 VkPhysicalDeviceFeatures2* pFeatures) {
3728 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2KHR(physicalDevice, pFeatures);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003729 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003730 if (bp_pd_state) {
3731 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3732 }
3733}
3734
3735void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilitiesKHR(VkPhysicalDevice physicalDevice,
3736 VkSurfaceKHR surface,
3737 VkSurfaceCapabilitiesKHR* pSurfaceCapabilities,
3738 VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003739 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003740 if (bp_pd_state) {
3741 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3742 }
3743}
3744
3745void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2KHR(
3746 VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
3747 VkSurfaceCapabilities2KHR* pSurfaceCapabilities, VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003748 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003749 if (bp_pd_state) {
3750 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3751 }
3752}
3753
3754void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2EXT(VkPhysicalDevice physicalDevice,
3755 VkSurfaceKHR surface,
3756 VkSurfaceCapabilities2EXT* pSurfaceCapabilities,
3757 VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003758 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003759 if (bp_pd_state) {
3760 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3761 }
3762}
3763
3764void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice physicalDevice,
3765 VkSurfaceKHR surface, uint32_t* pPresentModeCount,
3766 VkPresentModeKHR* pPresentModes, VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003767 auto bp_pd_data = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003768 if (bp_pd_data) {
3769 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfacePresentModesKHRState;
3770
3771 if (*pPresentModeCount) {
3772 if (call_state < QUERY_COUNT) {
3773 call_state = QUERY_COUNT;
3774 }
3775 }
3776 if (pPresentModes) {
3777 if (call_state < QUERY_DETAILS) {
3778 call_state = QUERY_DETAILS;
3779 }
3780 }
3781 }
3782}
3783
3784void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
3785 uint32_t* pSurfaceFormatCount,
3786 VkSurfaceFormatKHR* pSurfaceFormats, VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003787 auto bp_pd_data = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003788 if (bp_pd_data) {
3789 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState;
3790
3791 if (*pSurfaceFormatCount) {
3792 if (call_state < QUERY_COUNT) {
3793 call_state = QUERY_COUNT;
3794 }
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06003795 bp_pd_data->surface_formats_count = *pSurfaceFormatCount;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003796 }
3797 if (pSurfaceFormats) {
3798 if (call_state < QUERY_DETAILS) {
3799 call_state = QUERY_DETAILS;
3800 }
3801 }
3802 }
3803}
3804
3805void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormats2KHR(VkPhysicalDevice physicalDevice,
3806 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
3807 uint32_t* pSurfaceFormatCount,
3808 VkSurfaceFormat2KHR* pSurfaceFormats, VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003809 auto bp_pd_data = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003810 if (bp_pd_data) {
3811 if (*pSurfaceFormatCount) {
3812 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_COUNT) {
3813 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_COUNT;
3814 }
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06003815 bp_pd_data->surface_formats_count = *pSurfaceFormatCount;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003816 }
3817 if (pSurfaceFormats) {
3818 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_DETAILS) {
3819 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_DETAILS;
3820 }
3821 }
3822 }
3823}
3824
3825void BestPractices::ManualPostCallRecordGetPhysicalDeviceDisplayPlanePropertiesKHR(VkPhysicalDevice physicalDevice,
3826 uint32_t* pPropertyCount,
3827 VkDisplayPlanePropertiesKHR* pProperties,
3828 VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003829 auto bp_pd_data = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003830 if (bp_pd_data) {
3831 if (*pPropertyCount) {
3832 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_COUNT) {
3833 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_COUNT;
3834 }
3835 }
3836 if (pProperties) {
3837 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_DETAILS) {
3838 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_DETAILS;
3839 }
3840 }
3841 }
3842}
3843
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003844void BestPractices::ManualPostCallRecordGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain,
3845 uint32_t* pSwapchainImageCount, VkImage* pSwapchainImages,
3846 VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003847 auto swapchain_state = Get<bp_state::Swapchain>(swapchain);
Nathaniel Cesario39152e62021-07-02 13:04:16 -06003848 if (swapchain_state && (pSwapchainImages || *pSwapchainImageCount)) {
3849 if (swapchain_state->vkGetSwapchainImagesKHRState < QUERY_DETAILS) {
3850 swapchain_state->vkGetSwapchainImagesKHRState = QUERY_DETAILS;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003851 }
3852 }
3853}
3854
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003855void BestPractices::PreCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits, VkFence fence) {
3856 ValidationStateTracker::PreCallRecordQueueSubmit(queue, submitCount, pSubmits, fence);
3857
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06003858 auto queue_state = Get<QUEUE_STATE>(queue);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003859 for (uint32_t submit = 0; submit < submitCount; submit++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02003860 const auto& submit_info = pSubmits[submit];
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003861 for (uint32_t cb_index = 0; cb_index < submit_info.commandBufferCount; cb_index++) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003862 auto cb = GetWrite<bp_state::CommandBuffer>(submit_info.pCommandBuffers[cb_index]);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003863 for (auto &func : cb->queue_submit_functions) {
Jeremy Gebbene5361dd2021-11-18 14:23:56 -07003864 func(*this, *queue_state, *cb);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003865 }
3866 }
3867 }
3868}