blob: 207a45a00ca84445e030d5cd2082e81a44e43034 [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 }
ziga-lunarg5a76c442022-04-17 18:04:08 +0200605
606 if (IsExtEnabled(device_extensions.vk_khr_maintenance1)) {
607 // Track number of descriptorSets allowable in this pool
608 if (pool_state->GetAvailableSets() < pAllocateInfo->descriptorSetCount) {
609 skip |= LogWarning(pool_state->Handle(), kVUID_BestPractices_EmptyDescriptorPool,
610 "vkAllocateDescriptorSets(): Unable to allocate %" PRIu32 " descriptorSets from %s"
611 ". This pool only has %" PRIu32 " descriptorSets remaining.",
612 pAllocateInfo->descriptorSetCount, report_data->FormatHandle(pool_state->Handle()).c_str(),
613 pool_state->GetAvailableSets());
614 }
615 }
Sam Wallse746d522020-03-16 21:20:23 +0000616 }
617
618 return skip;
619}
620
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600621void BestPractices::ManualPostCallRecordAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
622 VkDescriptorSet* pDescriptorSets, VkResult result, void* ads_state) {
Sam Wallse746d522020-03-16 21:20:23 +0000623 if (result == VK_SUCCESS) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700624 auto pool_state = Get<bp_state::DescriptorPool>(pAllocateInfo->descriptorPool);
625 if (pool_state) {
Sam Wallse746d522020-03-16 21:20:23 +0000626 // we record successful allocations by subtracting the allocation count from the last recorded free count
627 const auto alloc_count = pAllocateInfo->descriptorSetCount;
628 // clamp the unsigned subtraction to the range [0, last_free_count]
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700629 if (pool_state->freed_count > alloc_count) {
630 pool_state->freed_count -= alloc_count;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700631 } else {
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700632 pool_state->freed_count = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700633 }
Sam Wallse746d522020-03-16 21:20:23 +0000634 }
635 }
636}
637
638void BestPractices::PostCallRecordFreeDescriptorSets(VkDevice device, VkDescriptorPool descriptorPool, uint32_t descriptorSetCount,
639 const VkDescriptorSet* pDescriptorSets, VkResult result) {
640 ValidationStateTracker::PostCallRecordFreeDescriptorSets(device, descriptorPool, descriptorSetCount, pDescriptorSets, result);
641 if (result == VK_SUCCESS) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700642 auto pool_state = Get<bp_state::DescriptorPool>(descriptorPool);
Sam Wallse746d522020-03-16 21:20:23 +0000643 // we want to track frees because we're interested in suggesting re-use
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700644 if (pool_state) {
645 pool_state->freed_count += descriptorSetCount;
Sam Wallse746d522020-03-16 21:20:23 +0000646 }
647 }
648}
649
Camden5b184be2019-08-13 07:50:19 -0600650bool BestPractices::PreCallValidateAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500651 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory) const {
Camden5b184be2019-08-13 07:50:19 -0600652 bool skip = false;
653
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700654 if ((Count<DEVICE_MEMORY_STATE>() + 1) > kMemoryObjectWarningLimit) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700655 skip |= LogPerformanceWarning(device, kVUID_BestPractices_AllocateMemory_TooManyObjects,
656 "Performance Warning: This app has > %" PRIu32 " memory objects.", kMemoryObjectWarningLimit);
Camden5b184be2019-08-13 07:50:19 -0600657 }
658
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000659 if (pAllocateInfo->allocationSize < kMinDeviceAllocationSize) {
660 skip |= LogPerformanceWarning(
661 device, kVUID_BestPractices_AllocateMemory_SmallAllocation,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600662 "vkAllocateMemory(): Allocating a VkDeviceMemory of size %" PRIu64 ". This is a very small allocation (current "
663 "threshold is %" PRIu64 " bytes). "
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000664 "You should make large allocations and sub-allocate from one large VkDeviceMemory.",
665 pAllocateInfo->allocationSize, kMinDeviceAllocationSize);
666 }
667
Camden83a9c372019-08-14 11:41:38 -0600668 // TODO: Insert get check for GetPhysicalDeviceMemoryProperties once the state is tracked in the StateTracker
669
670 return skip;
671}
672
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600673void BestPractices::ManualPostCallRecordAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
674 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory,
675 VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700676 if (result != VK_SUCCESS) {
677 static std::vector<VkResult> error_codes = {VK_ERROR_OUT_OF_HOST_MEMORY, VK_ERROR_OUT_OF_DEVICE_MEMORY,
678 VK_ERROR_TOO_MANY_OBJECTS, VK_ERROR_INVALID_EXTERNAL_HANDLE,
Mike Schuchardt2df08912020-12-15 16:28:09 -0800679 VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS};
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700680 static std::vector<VkResult> success_codes = {};
Nathaniel Cesariodb3f43f2021-05-12 09:08:23 -0600681 ValidateReturnCodes("vkAllocateMemory", result, error_codes, success_codes);
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700682 return;
683 }
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700684}
Camden Stocker9738af92019-10-16 13:54:03 -0700685
Mark Lobodzinskide15e582020-04-29 08:06:00 -0600686void BestPractices::ValidateReturnCodes(const char* api_name, VkResult result, const std::vector<VkResult>& error_codes,
687 const std::vector<VkResult>& success_codes) const {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700688 auto error = std::find(error_codes.begin(), error_codes.end(), result);
689 if (error != error_codes.end()) {
Gareth Webb586c46b2021-01-13 11:17:22 +0000690 static const std::vector<VkResult> common_failure_codes = {VK_ERROR_OUT_OF_DATE_KHR,
691 VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT};
692
693 auto common_failure = std::find(common_failure_codes.begin(), common_failure_codes.end(), result);
694 if (common_failure != common_failure_codes.end()) {
695 LogInfo(instance, kVUID_BestPractices_Failure_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
696 } else {
697 LogWarning(instance, kVUID_BestPractices_Error_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
698 }
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700699 return;
700 }
701 auto success = std::find(success_codes.begin(), success_codes.end(), result);
702 if (success != success_codes.end()) {
Mark Lobodzinskie7215152020-05-11 08:21:23 -0600703 LogInfo(instance, kVUID_BestPractices_NonSuccess_Result, "%s(): Returned non-success return code %s.", api_name,
704 string_VkResult(result));
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500705 }
706}
707
Jeff Bolz5c801d12019-10-09 10:38:45 -0500708bool BestPractices::PreCallValidateFreeMemory(VkDevice device, VkDeviceMemory memory,
709 const VkAllocationCallbacks* pAllocator) const {
Mark Lobodzinski91e50bf2020-01-14 09:55:11 -0700710 if (memory == VK_NULL_HANDLE) return false;
Camden83a9c372019-08-14 11:41:38 -0600711 bool skip = false;
712
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700713 auto mem_info = Get<DEVICE_MEMORY_STATE>(memory);
Camden83a9c372019-08-14 11:41:38 -0600714
Jeremy Gebben610d3a62022-01-01 12:53:17 -0700715 for (const auto& item : mem_info->ObjectBindings()) {
716 const auto& obj = item.first;
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600717 LogObjectList objlist(device);
718 objlist.add(obj);
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -0600719 objlist.add(mem_info->mem());
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600720 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 -0600721 report_data->FormatHandle(obj).c_str(), report_data->FormatHandle(mem_info->mem()).c_str());
Camden83a9c372019-08-14 11:41:38 -0600722 }
723
Camden5b184be2019-08-13 07:50:19 -0600724 return skip;
725}
726
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000727bool BestPractices::ValidateBindBufferMemory(VkBuffer buffer, VkDeviceMemory memory, const char* api_name) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600728 bool skip = false;
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700729 auto buffer_state = Get<BUFFER_STATE>(buffer);
Camden Stockerb603cc82019-09-03 10:09:02 -0600730
sfricke-samsunge2441192019-11-06 14:07:57 -0800731 if (!buffer_state->memory_requirements_checked && !buffer_state->external_memory_handle) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700732 skip |= LogWarning(device, kVUID_BestPractices_BufferMemReqNotCalled,
733 "%s: Binding memory to %s but vkGetBufferMemoryRequirements() has not been called on that buffer.",
734 api_name, report_data->FormatHandle(buffer).c_str());
Camden Stockerb603cc82019-09-03 10:09:02 -0600735 }
736
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700737 auto mem_state = Get<DEVICE_MEMORY_STATE>(memory);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000738
AndreyVK_D3D0416a332021-11-02 23:22:28 +0300739 if (mem_state && mem_state->alloc_info.allocationSize == buffer_state->createInfo.size &&
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000740 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
741 skip |= LogPerformanceWarning(
742 device, kVUID_BestPractices_SmallDedicatedAllocation,
743 "%s: Trying to bind %s to a memory block which is fully consumed by the buffer. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600744 "The required size of the allocation is %" PRIu64 ", but smaller buffers like this should be sub-allocated from "
745 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000746 api_name, report_data->FormatHandle(buffer).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
747 }
748
Camden Stockerb603cc82019-09-03 10:09:02 -0600749 return skip;
750}
751
752bool BestPractices::PreCallValidateBindBufferMemory(VkDevice device, VkBuffer buffer, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500753 VkDeviceSize memoryOffset) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600754 bool skip = false;
755 const char* api_name = "BindBufferMemory()";
756
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000757 skip |= ValidateBindBufferMemory(buffer, memory, api_name);
Camden Stockerb603cc82019-09-03 10:09:02 -0600758
759 return skip;
760}
761
762bool BestPractices::PreCallValidateBindBufferMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500763 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600764 char api_name[64];
765 bool skip = false;
766
767 for (uint32_t i = 0; i < bindInfoCount; i++) {
Frédéric Wangafb89862022-06-21 16:15:29 +0200768 snprintf(api_name, sizeof(api_name), "vkBindBufferMemory2() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000769 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600770 }
771
772 return skip;
773}
Camden Stockerb603cc82019-09-03 10:09:02 -0600774
775bool BestPractices::PreCallValidateBindBufferMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500776 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600777 char api_name[64];
778 bool skip = false;
Camden Stockerb603cc82019-09-03 10:09:02 -0600779
Camden Stocker8b798ab2019-09-03 10:33:28 -0600780 for (uint32_t i = 0; i < bindInfoCount; i++) {
Frédéric Wangafb89862022-06-21 16:15:29 +0200781 snprintf(api_name, sizeof(api_name), "vkBindBufferMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000782 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600783 }
784
785 return skip;
786}
787
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000788bool BestPractices::ValidateBindImageMemory(VkImage image, VkDeviceMemory memory, const char* api_name) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600789 bool skip = false;
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700790 auto image_state = Get<IMAGE_STATE>(image);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600791
sfricke-samsung71bc6572020-04-29 15:49:43 -0700792 if (image_state->disjoint == false) {
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600793 if (!image_state->memory_requirements_checked[0] && !image_state->external_memory_handle) {
sfricke-samsungd7ea5de2020-04-08 09:19:18 -0700794 skip |= LogWarning(device, kVUID_BestPractices_ImageMemReqNotCalled,
795 "%s: Binding memory to %s but vkGetImageMemoryRequirements() has not been called on that image.",
796 api_name, report_data->FormatHandle(image).c_str());
797 }
798 } else {
799 // TODO If binding disjoint image then this needs to check that VkImagePlaneMemoryRequirementsInfo was called for each
800 // plane.
Camden Stocker8b798ab2019-09-03 10:33:28 -0600801 }
802
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700803 auto mem_state = Get<DEVICE_MEMORY_STATE>(memory);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000804
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600805 if (mem_state->alloc_info.allocationSize == image_state->requirements[0].size &&
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000806 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
807 skip |= LogPerformanceWarning(
808 device, kVUID_BestPractices_SmallDedicatedAllocation,
809 "%s: Trying to bind %s to a memory block which is fully consumed by the image. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600810 "The required size of the allocation is %" PRIu64 ", but smaller images like this should be sub-allocated from "
811 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000812 api_name, report_data->FormatHandle(image).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
813 }
814
815 // If we're binding memory to a image which was created as TRANSIENT and the image supports LAZY allocation,
816 // make sure this type is actually used.
817 // This warning will only trigger if this layer is run on a platform that supports LAZILY_ALLOCATED_BIT
818 // (i.e.most tile - based renderers)
819 if (image_state->createInfo.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) {
820 bool supports_lazy = false;
821 uint32_t suggested_type = 0;
822
823 for (uint32_t i = 0; i < phys_dev_mem_props.memoryTypeCount; i++) {
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600824 if ((1u << i) & image_state->requirements[0].memoryTypeBits) {
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000825 if (phys_dev_mem_props.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
826 supports_lazy = true;
827 suggested_type = i;
828 break;
829 }
830 }
831 }
832
833 uint32_t allocated_properties = phys_dev_mem_props.memoryTypes[mem_state->alloc_info.memoryTypeIndex].propertyFlags;
834
835 if (supports_lazy && (allocated_properties & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) == 0) {
836 skip |= LogPerformanceWarning(
837 device, kVUID_BestPractices_NonLazyTransientImage,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600838 "%s: Attempting to bind memory type %u to VkImage which was created with TRANSIENT_ATTACHMENT_BIT,"
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000839 "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 -0600840 "%" PRIu64 " bytes of physical memory.",
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600841 api_name, mem_state->alloc_info.memoryTypeIndex, suggested_type, image_state->requirements[0].size);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000842 }
843 }
844
Camden Stocker8b798ab2019-09-03 10:33:28 -0600845 return skip;
846}
847
848bool BestPractices::PreCallValidateBindImageMemory(VkDevice device, VkImage image, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500849 VkDeviceSize memoryOffset) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600850 bool skip = false;
851 const char* api_name = "vkBindImageMemory()";
852
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000853 skip |= ValidateBindImageMemory(image, memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600854
855 return skip;
856}
857
858bool BestPractices::PreCallValidateBindImageMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500859 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600860 char api_name[64];
861 bool skip = false;
862
863 for (uint32_t i = 0; i < bindInfoCount; i++) {
Frédéric Wangafb89862022-06-21 16:15:29 +0200864 snprintf(api_name, sizeof(api_name), "vkBindImageMemory2() pBindInfos[%u]", i);
Mark Lobodzinski1f887d32020-12-30 15:31:33 -0700865 if (!LvlFindInChain<VkBindImageMemorySwapchainInfoKHR>(pBindInfos[i].pNext)) {
Tony-LunarG5e60b852020-04-27 11:27:54 -0600866 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
867 }
Camden Stocker8b798ab2019-09-03 10:33:28 -0600868 }
869
870 return skip;
871}
872
873bool BestPractices::PreCallValidateBindImageMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500874 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600875 char api_name[64];
876 bool skip = false;
877
878 for (uint32_t i = 0; i < bindInfoCount; i++) {
Frédéric Wangafb89862022-06-21 16:15:29 +0200879 snprintf(api_name, sizeof(api_name), "vkBindImageMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000880 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600881 }
882
883 return skip;
884}
Camden83a9c372019-08-14 11:41:38 -0600885
Attilio Provenzano02859b22020-02-27 14:17:28 +0000886static inline bool FormatHasFullThroughputBlendingArm(VkFormat format) {
887 switch (format) {
888 case VK_FORMAT_B10G11R11_UFLOAT_PACK32:
889 case VK_FORMAT_R16_SFLOAT:
890 case VK_FORMAT_R16G16_SFLOAT:
891 case VK_FORMAT_R16G16B16_SFLOAT:
892 case VK_FORMAT_R16G16B16A16_SFLOAT:
893 case VK_FORMAT_R32_SFLOAT:
894 case VK_FORMAT_R32G32_SFLOAT:
895 case VK_FORMAT_R32G32B32_SFLOAT:
896 case VK_FORMAT_R32G32B32A32_SFLOAT:
897 return false;
898
899 default:
900 return true;
901 }
902}
903
904bool BestPractices::ValidateMultisampledBlendingArm(uint32_t createInfoCount,
905 const VkGraphicsPipelineCreateInfo* pCreateInfos) const {
906 bool skip = false;
907
908 for (uint32_t i = 0; i < createInfoCount; i++) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700909 auto create_info = &pCreateInfos[i];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000910
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700911 if (!create_info->pColorBlendState || !create_info->pMultisampleState ||
912 create_info->pMultisampleState->rasterizationSamples == VK_SAMPLE_COUNT_1_BIT ||
913 create_info->pMultisampleState->sampleShadingEnable) {
Attilio Provenzano02859b22020-02-27 14:17:28 +0000914 return skip;
915 }
916
Jeremy Gebbenb20a8242021-11-05 15:14:43 -0600917 auto rp_state = Get<RENDER_PASS_STATE>(create_info->renderPass);
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200918 const auto& subpass = rp_state->createInfo.pSubpasses[create_info->subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000919
Hans-Kristian Arntzenc2742e72021-07-01 14:31:06 +0200920 // According to spec, pColorBlendState must be ignored if subpass does not have color attachments.
921 uint32_t num_color_attachments = std::min(subpass.colorAttachmentCount, create_info->pColorBlendState->attachmentCount);
922
923 for (uint32_t j = 0; j < num_color_attachments; j++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200924 const auto& blend_att = create_info->pColorBlendState->pAttachments[j];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000925 uint32_t att = subpass.pColorAttachments[j].attachment;
926
927 if (att != VK_ATTACHMENT_UNUSED && blend_att.blendEnable && blend_att.colorWriteMask) {
928 if (!FormatHasFullThroughputBlendingArm(rp_state->createInfo.pAttachments[att].format)) {
929 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultisampledBlending,
930 "%s vkCreateGraphicsPipelines() - createInfo #%u: Pipeline is multisampled and "
931 "color attachment #%u makes use "
932 "of a format which cannot be blended at full throughput when using MSAA.",
933 VendorSpecificTag(kBPVendorArm), i, j);
934 }
935 }
936 }
937 }
938
939 return skip;
940}
941
Nadav Gevaf0808442021-05-21 13:51:25 -0400942void BestPractices::ManualPostCallRecordCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
943 const VkComputePipelineCreateInfo* pCreateInfos,
944 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
945 VkResult result, void* pipe_state) {
946 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700947 pipeline_cache_ = pipelineCache;
Nadav Gevaf0808442021-05-21 13:51:25 -0400948}
949
Camden5b184be2019-08-13 07:50:19 -0600950bool BestPractices::PreCallValidateCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
951 const VkGraphicsPipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -0600952 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500953 void* cgpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -0600954 bool skip = StateTracker::PreCallValidateCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos,
955 pAllocator, pPipelines, cgpl_state_data);
ziga-lunarg08c81582022-03-08 17:33:45 +0100956 if (skip) {
957 return skip;
958 }
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600959 create_graphics_pipeline_api_state* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
Camden5b184be2019-08-13 07:50:19 -0600960
961 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700962 skip |= LogPerformanceWarning(
963 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
964 "Performance Warning: This vkCreateGraphicsPipelines call is creating multiple pipelines but is not using a "
965 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -0600966 }
967
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000968 for (uint32_t i = 0; i < createInfoCount; i++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200969 const auto& create_info = pCreateInfos[i];
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000970
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600971 if (!(cgpl_state->pipe_state[i]->active_shaders & VK_SHADER_STAGE_MESH_BIT_NV)) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200972 const auto& vertex_input = *create_info.pVertexInputState;
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600973 uint32_t count = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700974 for (uint32_t j = 0; j < vertex_input.vertexBindingDescriptionCount; j++) {
975 if (vertex_input.pVertexBindingDescriptions[j].inputRate == VK_VERTEX_INPUT_RATE_INSTANCE) {
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600976 count++;
977 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000978 }
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600979 if (count > kMaxInstancedVertexBuffers) {
980 skip |= LogPerformanceWarning(
981 device, kVUID_BestPractices_CreatePipelines_TooManyInstancedVertexBuffers,
982 "The pipeline is using %u instanced vertex buffers (current limit: %u), but this can be inefficient on the "
983 "GPU. If using instanced vertex attributes prefer interleaving them in a single buffer.",
984 count, kMaxInstancedVertexBuffers);
985 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000986 }
Attilio Provenzano02859b22020-02-27 14:17:28 +0000987
Szilard Pappaaf2da32020-06-22 10:37:35 +0100988 if ((pCreateInfos[i].pRasterizationState->depthBiasEnable) &&
989 (pCreateInfos[i].pRasterizationState->depthBiasConstantFactor == 0.0f) &&
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +0200990 (pCreateInfos[i].pRasterizationState->depthBiasSlopeFactor == 0.0f) &&
991 VendorCheckEnabled(kBPVendorArm)) {
992 skip |= LogPerformanceWarning(
993 device, kVUID_BestPractices_CreatePipelines_DepthBias_Zero,
994 "%s Performance Warning: This vkCreateGraphicsPipelines call is created with depthBiasEnable set to true "
995 "and both depthBiasConstantFactor and depthBiasSlopeFactor are set to 0. This can cause reduced "
996 "efficiency during rasterization. Consider disabling depthBias or increasing either "
997 "depthBiasConstantFactor or depthBiasSlopeFactor.",
998 VendorSpecificTag(kBPVendorArm));
Szilard Pappaaf2da32020-06-22 10:37:35 +0100999 }
1000
Attilio Provenzano02859b22020-02-27 14:17:28 +00001001 skip |= VendorCheckEnabled(kBPVendorArm) && ValidateMultisampledBlendingArm(createInfoCount, pCreateInfos);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001002 }
Nadav Gevaf0808442021-05-21 13:51:25 -04001003 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001004 auto prev_pipeline = pipeline_cache_.load();
1005 if (pipelineCache && prev_pipeline && pipelineCache != prev_pipeline) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001006 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultiplePipelineCaches,
1007 "%s Performance Warning: A second pipeline cache is in use. Consider using only one pipeline cache to "
1008 "improve cache hit rate", VendorSpecificTag(kBPVendorAMD));
1009 }
1010
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001011 if (num_pso_ > kMaxRecommendedNumberOfPSOAMD) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001012 skip |=
1013 LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_TooManyPipelines,
1014 "%s Performance warning: Too many pipelines created, consider consolidation",
1015 VendorSpecificTag(kBPVendorAMD));
1016 }
1017
Nathaniel Cesario1a7e1a92021-08-30 14:34:20 -06001018 if (pCreateInfos->pInputAssemblyState && pCreateInfos->pInputAssemblyState->primitiveRestartEnable) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001019 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_AvoidPrimitiveRestart,
1020 "%s Performance warning: Use of primitive restart is not recommended",
1021 VendorSpecificTag(kBPVendorAMD));
1022 }
1023
1024 // TODO: this might be too aggressive of a check
1025 if (pCreateInfos->pDynamicState && pCreateInfos->pDynamicState->dynamicStateCount > kDynamicStatesWarningLimitAMD) {
1026 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MinimizeNumDynamicStates,
1027 "%s Performance warning: Dynamic States usage incurs a performance cost. Ensure that they are truly needed",
1028 VendorSpecificTag(kBPVendorAMD));
1029 }
1030 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001031
Camden5b184be2019-08-13 07:50:19 -06001032 return skip;
1033}
1034
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001035static std::vector<bp_state::AttachmentInfo> GetAttachmentAccess(const safe_VkGraphicsPipelineCreateInfo& create_info,
1036 std::shared_ptr<const RENDER_PASS_STATE>& rp) {
1037 std::vector<bp_state::AttachmentInfo> result;
Tony-LunarG5e1dbcd2022-03-29 08:19:58 -06001038 if (!rp || rp->use_dynamic_rendering || rp->use_dynamic_rendering_inherited) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001039 return result;
Hans-Kristian Arntzenb033ab12021-06-16 11:16:59 +02001040 }
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001041
1042 const auto& subpass = rp->createInfo.pSubpasses[create_info.subpass];
1043
1044 // NOTE: see PIPELINE_LAYOUT and safe_VkGraphicsPipelineCreateInfo constructors. pColorBlendState and pDepthStencilState
1045 // are only non-null if they are enabled.
1046 if (create_info.pColorBlendState) {
1047 // According to spec, pColorBlendState must be ignored if subpass does not have color attachments.
1048 uint32_t num_color_attachments = std::min(subpass.colorAttachmentCount, create_info.pColorBlendState->attachmentCount);
1049 for (uint32_t j = 0; j < num_color_attachments; j++) {
1050 if (create_info.pColorBlendState->pAttachments[j].colorWriteMask != 0) {
1051 uint32_t attachment = subpass.pColorAttachments[j].attachment;
1052 if (attachment != VK_ATTACHMENT_UNUSED) {
1053 result.push_back({attachment, VK_IMAGE_ASPECT_COLOR_BIT});
1054 }
1055 }
1056 }
1057 }
1058
1059 if (create_info.pDepthStencilState &&
1060 (create_info.pDepthStencilState->depthTestEnable || create_info.pDepthStencilState->depthBoundsTestEnable ||
1061 create_info.pDepthStencilState->stencilTestEnable)) {
1062 uint32_t attachment = subpass.pDepthStencilAttachment ? subpass.pDepthStencilAttachment->attachment : VK_ATTACHMENT_UNUSED;
1063 if (attachment != VK_ATTACHMENT_UNUSED) {
1064 VkImageAspectFlags aspects = 0;
1065 if (create_info.pDepthStencilState->depthTestEnable || create_info.pDepthStencilState->depthBoundsTestEnable) {
1066 aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
1067 }
1068 if (create_info.pDepthStencilState->stencilTestEnable) {
1069 aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
1070 }
1071 result.push_back({attachment, aspects});
1072 }
1073 }
1074 return result;
1075}
1076
1077bp_state::Pipeline::Pipeline(const ValidationStateTracker* state_data, const VkGraphicsPipelineCreateInfo* pCreateInfo,
1078 std::shared_ptr<const RENDER_PASS_STATE>&& rpstate,
1079 std::shared_ptr<const PIPELINE_LAYOUT_STATE>&& layout)
1080 : PIPELINE_STATE(state_data, pCreateInfo, std::move(rpstate), std::move(layout)),
1081 access_framebuffer_attachments(GetAttachmentAccess(create_info.graphics, rp_state)) {}
1082
1083std::shared_ptr<PIPELINE_STATE> BestPractices::CreateGraphicsPipelineState(
1084 const VkGraphicsPipelineCreateInfo* pCreateInfo, std::shared_ptr<const RENDER_PASS_STATE>&& render_pass,
1085 std::shared_ptr<const PIPELINE_LAYOUT_STATE>&& layout) const {
1086 return std::static_pointer_cast<PIPELINE_STATE>(
1087 std::make_shared<bp_state::Pipeline>(this, pCreateInfo, std::move(render_pass), std::move(layout)));
Hans-Kristian Arntzenb033ab12021-06-16 11:16:59 +02001088}
1089
Sam Walls0961ec02020-03-31 16:39:15 +01001090void BestPractices::ManualPostCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t count,
1091 const VkGraphicsPipelineCreateInfo* pCreateInfos,
1092 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
1093 VkResult result, void* cgpl_state_data) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001094 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001095 pipeline_cache_ = pipelineCache;
Sam Walls0961ec02020-03-31 16:39:15 +01001096}
1097
Camden5b184be2019-08-13 07:50:19 -06001098bool BestPractices::PreCallValidateCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
1099 const VkComputePipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -06001100 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001101 void* ccpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -06001102 bool skip = StateTracker::PreCallValidateCreateComputePipelines(device, pipelineCache, createInfoCount, pCreateInfos,
1103 pAllocator, pPipelines, ccpl_state_data);
Camden5b184be2019-08-13 07:50:19 -06001104
1105 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001106 skip |= LogPerformanceWarning(
1107 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
1108 "Performance Warning: This vkCreateComputePipelines call is creating multiple pipelines but is not using a "
1109 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -06001110 }
1111
Nadav Gevaf0808442021-05-21 13:51:25 -04001112 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001113 auto prev_pipeline = pipeline_cache_.load();
1114 if (pipelineCache && prev_pipeline && pipelineCache != prev_pipeline) {
1115 skip |= LogPerformanceWarning(
1116 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
1117 "%s Performance Warning: A second pipeline cache is in use. Consider using only one pipeline cache to "
Nadav Gevaf0808442021-05-21 13:51:25 -04001118 "improve cache hit rate",
1119 VendorSpecificTag(kBPVendorAMD));
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001120 }
1121 }
Nadav Gevaf0808442021-05-21 13:51:25 -04001122
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001123 for (uint32_t i = 0; i < createInfoCount; i++) {
1124 const VkComputePipelineCreateInfo& createInfo = pCreateInfos[i];
1125 if (VendorCheckEnabled(kBPVendorArm)) {
1126 skip |= ValidateCreateComputePipelineArm(createInfo);
1127 }
sfricke-samsung86d055a2022-02-11 14:43:50 -08001128
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001129 if (IsExtEnabled(device_extensions.vk_khr_maintenance4)) {
1130 auto module_state = Get<SHADER_MODULE_STATE>(createInfo.stage.module);
1131 for (const auto& builtin : module_state->static_data_.builtin_decoration_list) {
1132 if (builtin.builtin == spv::BuiltInWorkgroupSize) {
1133 skip |= LogWarning(device, kVUID_BestPractices_SpirvDeprecated_WorkgroupSize,
1134 "vkCreateComputePipelines(): pCreateInfos[ %" PRIu32
1135 "] is using the Workgroup built-in which SPIR-V 1.6 deprecated. The VK_KHR_maintenance4 "
1136 "extension exposes a new LocalSizeId execution mode that should be used instead.",
1137 i);
sfricke-samsung86d055a2022-02-11 14:43:50 -08001138 }
1139 }
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001140 }
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001141 }
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001142
1143 return skip;
1144}
1145
1146bool BestPractices::ValidateCreateComputePipelineArm(const VkComputePipelineCreateInfo& createInfo) const {
1147 bool skip = false;
sfricke-samsungef15e482022-01-26 11:32:49 -08001148 auto module_state = Get<SHADER_MODULE_STATE>(createInfo.stage.module);
sfricke-samsung8a7341a2021-02-28 07:30:21 -08001149 // Generate warnings about work group sizes based on active resources.
sfricke-samsungef15e482022-01-26 11:32:49 -08001150 auto entrypoint = module_state->FindEntrypoint(createInfo.stage.pName, createInfo.stage.stage);
1151 if (entrypoint == module_state->end()) return false;
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001152
1153 uint32_t x = 1, y = 1, z = 1;
sfricke-samsungef15e482022-01-26 11:32:49 -08001154 module_state->FindLocalSize(entrypoint, x, y, z);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001155
1156 uint32_t thread_count = x * y * z;
1157
1158 // Generate a priori warnings about work group sizes.
1159 if (thread_count > kMaxEfficientWorkGroupThreadCountArm) {
1160 skip |= LogPerformanceWarning(
1161 device, kVUID_BestPractices_CreateComputePipelines_ComputeWorkGroupSize,
1162 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, %u, "
1163 "%u) (%u threads total), has more threads than advised in a single work group. It is advised to use work "
1164 "groups with less than %u threads, especially when using barrier() or shared memory.",
1165 VendorSpecificTag(kBPVendorArm), x, y, z, thread_count, kMaxEfficientWorkGroupThreadCountArm);
1166 }
1167
1168 if (thread_count == 1 || ((x > 1) && (x & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
1169 ((y > 1) && (y & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
1170 ((z > 1) && (z & (kThreadGroupDispatchCountAlignmentArm - 1)))) {
1171 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeThreadGroupAlignment,
1172 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, "
1173 "%u, %u) is not aligned to %u "
1174 "threads. On Arm Mali architectures, not aligning work group sizes to %u may "
1175 "leave threads idle on the shader "
1176 "core.",
1177 VendorSpecificTag(kBPVendorArm), x, y, z, kThreadGroupDispatchCountAlignmentArm,
1178 kThreadGroupDispatchCountAlignmentArm);
1179 }
1180
sfricke-samsungef15e482022-01-26 11:32:49 -08001181 auto accessible_ids = module_state->MarkAccessibleIds(entrypoint);
1182 auto descriptor_uses = module_state->CollectInterfaceByDescriptorSlot(accessible_ids);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001183
1184 unsigned dimensions = 0;
1185 if (x > 1) dimensions++;
1186 if (y > 1) dimensions++;
1187 if (z > 1) dimensions++;
1188 // Here the dimension will really depend on the dispatch grid, but assume it's 1D.
1189 dimensions = std::max(dimensions, 1u);
1190
1191 // If we're accessing images, we almost certainly want to have a 2D workgroup for cache reasons.
1192 // There are some false positives here. We could simply have a shader that does this within a 1D grid,
1193 // or we may have a linearly tiled image, but these cases are quite unlikely in practice.
1194 bool accesses_2d = false;
1195 for (const auto& usage : descriptor_uses) {
sfricke-samsungef15e482022-01-26 11:32:49 -08001196 auto dim = module_state->GetShaderResourceDimensionality(usage.second);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001197 if (dim < 0) continue;
1198 auto spvdim = spv::Dim(dim);
1199 if (spvdim != spv::Dim1D && spvdim != spv::DimBuffer) accesses_2d = true;
1200 }
1201
1202 if (accesses_2d && dimensions < 2) {
1203 LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeSpatialLocality,
1204 "%s vkCreateComputePipelines(): compute shader has work group dimensions (%u, %u, %u), which "
1205 "suggests a 1D dispatch, but the shader is accessing 2D or 3D images. The shader may be "
1206 "exhibiting poor spatial locality with respect to one or more shader resources.",
1207 VendorSpecificTag(kBPVendorArm), x, y, z);
1208 }
1209
Camden5b184be2019-08-13 07:50:19 -06001210 return skip;
1211}
1212
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001213bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags flags) const {
Camden5b184be2019-08-13 07:50:19 -06001214 bool skip = false;
1215
1216 if (flags & VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001217 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1218 "You are using VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001219 } else if (flags & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001220 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1221 "You are using VK_PIPELINE_STAGE_ALL_COMMANDS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001222 }
1223
1224 return skip;
1225}
1226
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001227bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags2KHR flags) const {
1228 bool skip = false;
1229
1230 if (flags & VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR) {
1231 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1232 "You are using VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR when %s is called\n", api_name.c_str());
1233 } else if (flags & VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR) {
1234 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1235 "You are using VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR when %s is called\n", api_name.c_str());
1236 }
1237
1238 return skip;
1239}
1240
1241bool BestPractices::CheckDependencyInfo(const std::string& api_name, const VkDependencyInfoKHR& dep_info) const {
1242 bool skip = false;
1243 auto stage_masks = sync_utils::GetGlobalStageMasks(dep_info);
1244
1245 skip |= CheckPipelineStageFlags(api_name, stage_masks.src);
1246 skip |= CheckPipelineStageFlags(api_name, stage_masks.dst);
1247
1248 return skip;
1249}
1250
Mark Lobodzinski84101d72020-04-24 09:43:48 -06001251void BestPractices::ManualPostCallRecordQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo, VkResult result) {
Mark Lobodzinski9b133c12020-03-10 10:42:56 -06001252 for (uint32_t i = 0; i < pPresentInfo->swapchainCount; ++i) {
1253 auto swapchains_result = pPresentInfo->pResults ? pPresentInfo->pResults[i] : result;
1254 if (swapchains_result == VK_SUBOPTIMAL_KHR) {
1255 LogPerformanceWarning(
1256 pPresentInfo->pSwapchains[i], kVUID_BestPractices_SuboptimalSwapchain,
1257 "vkQueuePresentKHR: %s :VK_SUBOPTIMAL_KHR was returned. VK_SUBOPTIMAL_KHR - Presentation will still succeed, "
1258 "subject to the window resize behavior, but the swapchain is no longer configured optimally for the surface it "
1259 "targets. Applications should query updated surface information and recreate their swapchain at the next "
1260 "convenient opportunity.",
1261 report_data->FormatHandle(pPresentInfo->pSwapchains[i]).c_str());
1262 }
1263 }
Nadav Gevaf0808442021-05-21 13:51:25 -04001264
1265 // AMD best practice
1266 // end-of-frame cleanup
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001267 num_queue_submissions_ = 0;
1268 num_barriers_objects_ = 0;
1269 ClearPipelinesUsedInFrame();
Mark Lobodzinski9b133c12020-03-10 10:42:56 -06001270}
1271
Jeff Bolz5c801d12019-10-09 10:38:45 -05001272bool BestPractices::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
1273 VkFence fence) const {
Camden5b184be2019-08-13 07:50:19 -06001274 bool skip = false;
1275
1276 for (uint32_t submit = 0; submit < submitCount; submit++) {
1277 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreCount; semaphore++) {
1278 skip |= CheckPipelineStageFlags("vkQueueSubmit", pSubmits[submit].pWaitDstStageMask[semaphore]);
1279 }
ziga-lunargc77f0c02022-04-18 00:15:16 +02001280 if (pSubmits[submit].signalSemaphoreCount == 0 && pSubmits[submit].pSignalSemaphores != nullptr) {
1281 skip |=
1282 LogWarning(device, kVUID_BestPractices_SemaphoreCount,
1283 "pSubmits[%" PRIu32 "].pSignalSemaphores is set, but pSubmits[%" PRIu32 "].signalSemaphoreCount is 0.",
1284 submit, submit);
1285 }
1286 if (pSubmits[submit].waitSemaphoreCount == 0 && pSubmits[submit].pWaitSemaphores != nullptr) {
1287 skip |= LogWarning(device, kVUID_BestPractices_SemaphoreCount,
1288 "pSubmits[%" PRIu32 "].pWaitSemaphores is set, but pSubmits[%" PRIu32 "].waitSemaphoreCount is 0.",
1289 submit, submit);
1290 }
Camden5b184be2019-08-13 07:50:19 -06001291 }
1292
1293 return skip;
1294}
1295
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001296bool BestPractices::PreCallValidateQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR* pSubmits,
1297 VkFence fence) const {
1298 bool skip = false;
1299
1300 for (uint32_t submit = 0; submit < submitCount; submit++) {
1301 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreInfoCount; semaphore++) {
1302 skip |= CheckPipelineStageFlags("vkQueueSubmit2KHR", pSubmits[submit].pWaitSemaphoreInfos[semaphore].stageMask);
1303 }
1304 }
1305
1306 return skip;
1307}
1308
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001309bool BestPractices::PreCallValidateQueueSubmit2(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2* pSubmits,
1310 VkFence fence) const {
1311 bool skip = false;
1312
1313 for (uint32_t submit = 0; submit < submitCount; submit++) {
1314 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreInfoCount; semaphore++) {
1315 skip |= CheckPipelineStageFlags("vkQueueSubmit2", pSubmits[submit].pWaitSemaphoreInfos[semaphore].stageMask);
1316 }
1317 }
1318
1319 return skip;
1320}
1321
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001322bool BestPractices::PreCallValidateCreateCommandPool(VkDevice device, const VkCommandPoolCreateInfo* pCreateInfo,
1323 const VkAllocationCallbacks* pAllocator, VkCommandPool* pCommandPool) const {
1324 bool skip = false;
1325
1326 if (pCreateInfo->flags & VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT) {
1327 skip |= LogPerformanceWarning(
1328 device, kVUID_BestPractices_CreateCommandPool_CommandBufferReset,
1329 "vkCreateCommandPool(): VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT is set. Consider resetting entire "
1330 "pool instead.");
1331 }
1332
1333 return skip;
1334}
1335
1336bool BestPractices::PreCallValidateBeginCommandBuffer(VkCommandBuffer commandBuffer,
1337 const VkCommandBufferBeginInfo* pBeginInfo) const {
1338 bool skip = false;
1339
1340 if (pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT) {
1341 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_SimultaneousUse,
1342 "vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT is set.");
1343 }
1344
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001345 if (!(pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT) && VendorCheckEnabled(kBPVendorArm)) {
1346 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_OneTimeSubmit,
Attilio Provenzano02859b22020-02-27 14:17:28 +00001347 "%s vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT is not set. "
1348 "For best performance on Mali GPUs, consider setting ONE_TIME_SUBMIT by default.",
1349 VendorSpecificTag(kBPVendorArm));
1350 }
1351
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001352 return skip;
1353}
1354
Jeff Bolz5c801d12019-10-09 10:38:45 -05001355bool BestPractices::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001356 bool skip = false;
1357
1358 skip |= CheckPipelineStageFlags("vkCmdSetEvent", stageMask);
1359
1360 return skip;
1361}
1362
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001363bool BestPractices::PreCallValidateCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1364 const VkDependencyInfoKHR* pDependencyInfo) const {
1365 return CheckDependencyInfo("vkCmdSetEvent2KHR", *pDependencyInfo);
1366}
1367
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001368bool BestPractices::PreCallValidateCmdSetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
1369 const VkDependencyInfo* pDependencyInfo) const {
1370 return CheckDependencyInfo("vkCmdSetEvent2", *pDependencyInfo);
1371}
1372
Jeff Bolz5c801d12019-10-09 10:38:45 -05001373bool BestPractices::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
1374 VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001375 bool skip = false;
1376
1377 skip |= CheckPipelineStageFlags("vkCmdResetEvent", stageMask);
1378
1379 return skip;
1380}
1381
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001382bool BestPractices::PreCallValidateCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1383 VkPipelineStageFlags2KHR stageMask) const {
1384 bool skip = false;
1385
1386 skip |= CheckPipelineStageFlags("vkCmdResetEvent2KHR", stageMask);
1387
1388 return skip;
1389}
1390
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001391bool BestPractices::PreCallValidateCmdResetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
1392 VkPipelineStageFlags2 stageMask) const {
1393 bool skip = false;
1394
1395 skip |= CheckPipelineStageFlags("vkCmdResetEvent2", stageMask);
1396
1397 return skip;
1398}
1399
Camden5b184be2019-08-13 07:50:19 -06001400bool BestPractices::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1401 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
1402 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1403 uint32_t bufferMemoryBarrierCount,
1404 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1405 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001406 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001407 bool skip = false;
1408
1409 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", srcStageMask);
1410 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", dstStageMask);
1411
1412 return skip;
1413}
1414
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001415bool BestPractices::PreCallValidateCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1416 const VkDependencyInfoKHR* pDependencyInfos) const {
1417 bool skip = false;
1418 for (uint32_t i = 0; i < eventCount; i++) {
1419 skip = CheckDependencyInfo("vkCmdWaitEvents2KHR", pDependencyInfos[i]);
1420 }
1421
1422 return skip;
1423}
1424
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001425bool BestPractices::PreCallValidateCmdWaitEvents2(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1426 const VkDependencyInfo* pDependencyInfos) const {
1427 bool skip = false;
1428 for (uint32_t i = 0; i < eventCount; i++) {
1429 skip = CheckDependencyInfo("vkCmdWaitEvents2", pDependencyInfos[i]);
1430 }
1431
1432 return skip;
1433}
1434
Camden5b184be2019-08-13 07:50:19 -06001435bool BestPractices::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
1436 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
1437 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1438 uint32_t bufferMemoryBarrierCount,
1439 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1440 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001441 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001442 bool skip = false;
1443
1444 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", srcStageMask);
1445 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", dstStageMask);
1446
ziga-lunargb65dbfb2022-03-19 18:45:09 +01001447 for (uint32_t i = 0; i < imageMemoryBarrierCount; ++i) {
1448 if (pImageMemoryBarriers[i].oldLayout == VK_IMAGE_LAYOUT_UNDEFINED &&
1449 IsImageLayoutReadOnly(pImageMemoryBarriers[i].newLayout)) {
1450 skip |= LogWarning(device, kVUID_BestPractices_TransitionUndefinedToReadOnly,
1451 "VkImageMemoryBarrier is being submitted with oldLayout VK_IMAGE_LAYOUT_UNDEFINED and the contents "
1452 "may be discarded, but the newLayout is %s, which is read only.",
1453 string_VkImageLayout(pImageMemoryBarriers[i].newLayout));
1454 }
1455 }
1456
Nadav Gevaf0808442021-05-21 13:51:25 -04001457 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001458 auto num = num_barriers_objects_.load();
1459 if (num + imageMemoryBarrierCount + bufferMemoryBarrierCount > kMaxRecommendedBarriersSizeAMD) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001460 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdBuffer_highBarrierCount,
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001461 "%s Performance warning: In this frame, %" PRIu32
1462 " barriers were already submitted. Barriers have a high cost and can "
1463 "stall the GPU. "
1464 "Consider consolidating and re-organizing the frame to use fewer barriers.",
1465 VendorSpecificTag(kBPVendorAMD), num);
Nadav Gevaf0808442021-05-21 13:51:25 -04001466 }
1467
1468 std::array<VkImageLayout, 3> read_layouts = {
1469 VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL,
1470 VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
1471 VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
1472 };
1473
1474 for (uint32_t i = 0; i < imageMemoryBarrierCount; i++) {
1475 // read to read barriers
1476 auto found = std::find(read_layouts.begin(), read_layouts.end(), pImageMemoryBarriers[i].oldLayout);
1477 bool old_is_read_layout = found != read_layouts.end();
1478 found = std::find(read_layouts.begin(), read_layouts.end(), pImageMemoryBarriers[i].newLayout);
1479 bool new_is_read_layout = found != read_layouts.end();
1480 if (old_is_read_layout && new_is_read_layout) {
1481 skip |= LogPerformanceWarning(device, kVUID_BestPractices_PipelineBarrier_readToReadBarrier,
1482 "%s Performance warning: Don't issue read-to-read barriers. Get the resource in the right state the first "
1483 "time you use it.",
1484 VendorSpecificTag(kBPVendorAMD));
1485 }
1486
1487 // general with no storage
1488 if (pImageMemoryBarriers[i].newLayout == VK_IMAGE_LAYOUT_GENERAL) {
1489 auto image_state = Get<IMAGE_STATE>(pImageMemoryBarriers[i].image);
1490 if (!(image_state->createInfo.usage & VK_IMAGE_USAGE_STORAGE_BIT)) {
1491 skip |= LogPerformanceWarning(device, kVUID_BestPractices_vkImage_AvoidGeneral,
1492 "%s Performance warning: VK_IMAGE_LAYOUT_GENERAL should only be used with "
1493 "VK_IMAGE_USAGE_STORAGE_BIT images.",
1494 VendorSpecificTag(kBPVendorAMD));
1495 }
1496 }
1497 }
1498 }
1499
Camden5b184be2019-08-13 07:50:19 -06001500 return skip;
1501}
1502
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001503bool BestPractices::PreCallValidateCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer,
1504 const VkDependencyInfoKHR* pDependencyInfo) const {
1505 return CheckDependencyInfo("vkCmdPipelineBarrier2KHR", *pDependencyInfo);
1506}
1507
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001508bool BestPractices::PreCallValidateCmdPipelineBarrier2(VkCommandBuffer commandBuffer,
1509 const VkDependencyInfo* pDependencyInfo) const {
1510 return CheckDependencyInfo("vkCmdPipelineBarrier2", *pDependencyInfo);
1511}
1512
Camden5b184be2019-08-13 07:50:19 -06001513bool BestPractices::PreCallValidateCmdWriteTimestamp(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001514 VkQueryPool queryPool, uint32_t query) const {
Camden5b184be2019-08-13 07:50:19 -06001515 bool skip = false;
1516
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001517 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp", static_cast<VkPipelineStageFlags>(pipelineStage));
1518
1519 return skip;
1520}
1521
1522bool BestPractices::PreCallValidateCmdWriteTimestamp2KHR(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
1523 VkQueryPool queryPool, uint32_t query) const {
1524 bool skip = false;
1525
1526 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp2KHR", pipelineStage);
Camden5b184be2019-08-13 07:50:19 -06001527
1528 return skip;
1529}
1530
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001531bool BestPractices::PreCallValidateCmdWriteTimestamp2(VkCommandBuffer commandBuffer, VkPipelineStageFlags2 pipelineStage,
1532 VkQueryPool queryPool, uint32_t query) const {
1533 bool skip = false;
1534
1535 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp2", pipelineStage);
1536
1537 return skip;
1538}
1539
Sam Walls0961ec02020-03-31 16:39:15 +01001540void BestPractices::PostCallRecordCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
1541 VkPipeline pipeline) {
1542 StateTracker::PostCallRecordCmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
1543
Nadav Gevaf0808442021-05-21 13:51:25 -04001544 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001545 PipelineUsedInFrame(pipeline);
Nadav Gevaf0808442021-05-21 13:51:25 -04001546
Sam Walls0961ec02020-03-31 16:39:15 +01001547 if (pipelineBindPoint == VK_PIPELINE_BIND_POINT_GRAPHICS) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001548 auto pipeline_state = Get<bp_state::Pipeline>(pipeline);
Sam Walls0961ec02020-03-31 16:39:15 +01001549 // check for depth/blend state tracking
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001550 if (pipeline_state) {
1551 auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06001552 assert(cb_node);
1553 auto& render_pass_state = cb_node->render_pass_state;
Sam Walls0961ec02020-03-31 16:39:15 +01001554
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001555 render_pass_state.nextDrawTouchesAttachments = pipeline_state->access_framebuffer_attachments;
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001556 render_pass_state.drawTouchAttachments = true;
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02001557
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07001558 const auto* blend_state = pipeline_state->ColorBlendState();
1559 const auto* stencil_state = pipeline_state->DepthStencilState();
Sam Walls0961ec02020-03-31 16:39:15 +01001560
1561 if (blend_state) {
1562 // assume the pipeline is depth-only unless any of the attachments have color writes enabled
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001563 render_pass_state.depthOnly = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001564 for (size_t i = 0; i < blend_state->attachmentCount; i++) {
1565 if (blend_state->pAttachments[i].colorWriteMask != 0) {
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001566 render_pass_state.depthOnly = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001567 }
1568 }
1569 }
1570
1571 // check for depth value usage
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001572 render_pass_state.depthEqualComparison = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001573
1574 if (stencil_state && stencil_state->depthTestEnable) {
1575 switch (stencil_state->depthCompareOp) {
1576 case VK_COMPARE_OP_EQUAL:
1577 case VK_COMPARE_OP_GREATER_OR_EQUAL:
1578 case VK_COMPARE_OP_LESS_OR_EQUAL:
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001579 render_pass_state.depthEqualComparison = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001580 break;
1581 default:
1582 break;
1583 }
1584 }
Sam Walls0961ec02020-03-31 16:39:15 +01001585 }
1586 }
1587}
1588
Hans-Kristian Arntzen237663c2021-07-01 14:36:40 +02001589static inline bool RenderPassUsesAttachmentAsResolve(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1590 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
1591 const auto& subpass_info = createInfo.pSubpasses[subpass];
1592 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
1599 return false;
1600}
1601
Attilio Provenzano02859b22020-02-27 14:17:28 +00001602static inline bool RenderPassUsesAttachmentOnTile(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1603 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001604 const auto& subpass_info = createInfo.pSubpasses[subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001605
1606 // If an attachment is ever used as a color attachment,
1607 // resolve attachment or depth stencil attachment,
1608 // it needs to exist on tile at some point.
1609
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001610 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1611 if (subpass_info.pColorAttachments[i].attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001612 }
1613
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001614 if (subpass_info.pResolveAttachments) {
1615 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1616 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
1617 }
1618 }
1619
1620 if (subpass_info.pDepthStencilAttachment && subpass_info.pDepthStencilAttachment->attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001621 }
1622
1623 return false;
1624}
1625
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001626static inline bool RenderPassUsesAttachmentAsImageOnly(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1627 if (RenderPassUsesAttachmentOnTile(createInfo, attachment)) {
1628 return false;
1629 }
1630
1631 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001632 const auto& subpassInfo = createInfo.pSubpasses[subpass];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001633
1634 for (uint32_t i = 0; i < subpassInfo.inputAttachmentCount; i++) {
1635 if (subpassInfo.pInputAttachments[i].attachment == attachment) {
1636 return true;
1637 }
1638 }
1639 }
1640
1641 return false;
1642}
1643
Attilio Provenzano02859b22020-02-27 14:17:28 +00001644bool BestPractices::ValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1645 const VkRenderPassBeginInfo* pRenderPassBegin) const {
1646 bool skip = false;
1647
1648 if (!pRenderPassBegin) {
1649 return skip;
1650 }
1651
Gareth Webbdc6549a2021-06-16 03:52:24 +01001652 if (pRenderPassBegin->renderArea.extent.width == 0 || pRenderPassBegin->renderArea.extent.height == 0) {
1653 skip |= LogWarning(device, kVUID_BestPractices_BeginRenderPass_ZeroSizeRenderArea,
1654 "This render pass has a zero-size render area. It cannot write to any attachments, "
1655 "and can only be used for side effects such as layout transitions.");
1656 }
1657
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001658 auto rp_state = Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001659 if (rp_state) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08001660 if (rp_state->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07001661 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
Tony-LunarG767180f2020-04-23 14:03:59 -06001662 if (rpabi) {
1663 skip = ValidateAttachments(rp_state->createInfo.ptr(), rpabi->attachmentCount, rpabi->pAttachments);
1664 }
1665 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001666 // Check if any attachments have LOAD operation on them
1667 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001668 const auto& attachment = rp_state->createInfo.pAttachments[att];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001669
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001670 bool attachment_has_readback = false;
Hans-Kristian Arntzen4afb59b2021-06-18 12:41:36 +02001671 if (!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001672 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001673 }
1674
1675 if (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001676 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001677 }
1678
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001679 bool attachment_needs_readback = false;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001680
1681 // Check if the attachment is actually used in any subpass on-tile
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001682 if (attachment_has_readback && RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1683 attachment_needs_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001684 }
1685
1686 // Using LOAD_OP_LOAD is expensive on tiled GPUs, so flag it as a potential improvement
LawG47747b322022-02-23 16:12:10 +00001687 if (attachment_needs_readback && (VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG))) {
1688 skip |=
1689 LogPerformanceWarning(device, kVUID_BestPractices_BeginRenderPass_AttachmentNeedsReadback,
LawG4015be1c2022-03-01 10:37:52 +00001690 "%s %s: Attachment #%u in render pass has begun with VK_ATTACHMENT_LOAD_OP_LOAD.\n"
LawG47747b322022-02-23 16:12:10 +00001691 "Submitting this renderpass will cause the driver to inject a readback of the attachment "
Nadav Gevaf0808442021-05-21 13:51:25 -04001692 "which will copy in total %u pixels (renderArea = "
LawG47747b322022-02-23 16:12:10 +00001693 "{ %" PRId32 ", %" PRId32 ", %" PRIu32 ", %" PRIu32 " }) to the tile buffer.",
1694 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), att,
1695 pRenderPassBegin->renderArea.extent.width * pRenderPassBegin->renderArea.extent.height,
1696 pRenderPassBegin->renderArea.offset.x, pRenderPassBegin->renderArea.offset.y,
1697 pRenderPassBegin->renderArea.extent.width, pRenderPassBegin->renderArea.extent.height);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001698 }
1699 }
paul-lunarg7089e272022-06-20 22:19:37 +02001700
1701 // Check if renderpass has at least one VK_ATTACHMENT_LOAD_OP_CLEAR
1702
1703 bool clearing = false;
1704
1705 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
1706 const auto& attachment = rp_state->createInfo.pAttachments[att];
1707
1708 if (attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) {
1709 clearing = true;
1710 break;
1711 }
1712 }
1713
1714 // Check if there are ClearValues passed to BeginRenderPass even though no attachments will be cleared
1715 if (!clearing && pRenderPassBegin->clearValueCount > 0) {
1716 // Flag as warning because nothing will happen per spec, and pClearValues will be ignored
1717 skip |= LogWarning(
1718 device, kVUID_BestPractices_ClearValueWithoutLoadOpClear,
1719 "This render pass does not have VkRenderPassCreateInfo.pAttachments->loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR "
1720 "but VkRenderPassBeginInfo.clearValueCount > 0. VkRenderPassBeginInfo.pClearValues will be ignored and no "
paul-lunarga0a149c2022-06-23 16:18:51 +02001721 "attachments will be cleared.");
paul-lunarg7089e272022-06-20 22:19:37 +02001722 }
paul-lunarga0a149c2022-06-23 16:18:51 +02001723
1724 // Check if there are more clearValues than attachments
1725 if(pRenderPassBegin->clearValueCount > rp_state->createInfo.attachmentCount) {
1726 // Flag as warning because the overflowing clearValues will be ignored and could even be undefined on certain platforms.
1727 // This could signal a bug and there seems to be no reason for this to happen on purpose.
1728 skip |= LogWarning(
1729 device, kVUID_BestPractices_ClearValueCountHigherThanAttachmentCount,
1730 "This render pass has VkRenderPassBeginInfo.clearValueCount > VkRenderPassCreateInfo.attachmentCount "
1731 "(%" PRIu32 " > %" PRIu32 ") and as such the clearValues that do not have a corresponding attachment will be ignored.",
1732 pRenderPassBegin->clearValueCount, rp_state->createInfo.attachmentCount);
1733 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001734 }
1735
1736 return skip;
1737}
1738
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001739void BestPractices::QueueValidateImageView(QueueCallbacks &funcs, const char* function_name,
1740 IMAGE_VIEW_STATE* view, IMAGE_SUBRESOURCE_USAGE_BP usage) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001741 if (view) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001742 auto image_state = std::static_pointer_cast<bp_state::Image>(view->image_state);
1743 QueueValidateImage(funcs, function_name, image_state, usage, view->normalized_subresource_range);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001744 }
1745}
1746
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001747void BestPractices::QueueValidateImage(QueueCallbacks& funcs, const char* function_name, std::shared_ptr<bp_state::Image>& state,
1748 IMAGE_SUBRESOURCE_USAGE_BP usage, const VkImageSubresourceRange& subresource_range) {
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02001749 // If we're viewing a 3D slice, ignore base array layer.
1750 // The entire 3D subresource is accessed as one atomic unit.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001751 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 +02001752
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001753 const uint32_t max_layers = state->createInfo.arrayLayers - base_array_layer;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001754 const uint32_t array_layers = std::min(subresource_range.layerCount, max_layers);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001755 const uint32_t max_levels = state->createInfo.mipLevels - subresource_range.baseMipLevel;
1756 const uint32_t mip_levels = std::min(state->createInfo.mipLevels, max_levels);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001757
1758 for (uint32_t layer = 0; layer < array_layers; layer++) {
1759 for (uint32_t level = 0; level < mip_levels; level++) {
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02001760 QueueValidateImage(funcs, function_name, state, usage, layer + base_array_layer,
1761 level + subresource_range.baseMipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001762 }
1763 }
1764}
1765
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001766void BestPractices::QueueValidateImage(QueueCallbacks& funcs, const char* function_name, std::shared_ptr<bp_state::Image>& state,
1767 IMAGE_SUBRESOURCE_USAGE_BP usage, const VkImageSubresourceLayers& subresource_layers) {
1768 const uint32_t max_layers = state->createInfo.arrayLayers - subresource_layers.baseArrayLayer;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001769 const uint32_t array_layers = std::min(subresource_layers.layerCount, max_layers);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001770
1771 for (uint32_t layer = 0; layer < array_layers; layer++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001772 QueueValidateImage(funcs, function_name, state, usage, layer + subresource_layers.baseArrayLayer, subresource_layers.mipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001773 }
1774}
1775
paul-lunarg5eb52062022-06-27 18:57:15 +02001776void BestPractices::QueueValidateImage(QueueCallbacks& funcs, const char* function_name, std::shared_ptr<bp_state::Image>& state,
1777 IMAGE_SUBRESOURCE_USAGE_BP usage, uint32_t array_layer, uint32_t mip_level) {
1778 funcs.push_back([this, function_name, state, usage, array_layer, mip_level](const ValidationStateTracker&, const QUEUE_STATE&,
1779 const CMD_BUFFER_STATE&) -> bool {
1780 ValidateImageInQueue(function_name, *state, usage, array_layer, mip_level);
1781 return false;
1782 });
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001783}
1784
LawG44d414ba2022-02-23 15:35:41 +00001785void BestPractices::ValidateImageInQueueArmImg(const char* function_name, const bp_state::Image& image,
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001786 IMAGE_SUBRESOURCE_USAGE_BP last_usage, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001787 uint32_t array_layer, uint32_t mip_level) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001788 // Swapchain images are implicitly read so clear after store is expected.
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001789 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 -07001790 !image.IsSwapchainImage()) {
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001791 LogPerformanceWarning(
1792 device, kVUID_BestPractices_RenderPass_RedundantStore,
LawG4015be1c2022-03-01 10:37:52 +00001793 "%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 +02001794 "image was used, it was written to with STORE_OP_STORE. "
1795 "Storing to the image is probably redundant in this case, and wastes bandwidth on tile-based "
1796 "architectures.",
LawG44d414ba2022-02-23 15:35:41 +00001797 function_name, VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), array_layer, mip_level);
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001798 } 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 +02001799 LogPerformanceWarning(
1800 device, kVUID_BestPractices_RenderPass_RedundantClear,
LawG4015be1c2022-03-01 10:37:52 +00001801 "%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 +02001802 "image was used, it was written to with vkCmdClear*Image(). "
1803 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
LawG44d414ba2022-02-23 15:35:41 +00001804 "tile-based architectures.",
1805 function_name, VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), array_layer, mip_level);
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01001806 } else if (usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE &&
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001807 (last_usage == IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE || last_usage == IMAGE_SUBRESOURCE_USAGE_BP::CLEARED ||
1808 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE || last_usage == IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE)) {
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01001809 const char *last_cmd = nullptr;
1810 const char *vuid = nullptr;
1811 const char *suggestion = nullptr;
1812
1813 switch (last_usage) {
1814 case IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE:
1815 vuid = kVUID_BestPractices_RenderPass_BlitImage_LoadOpLoad;
1816 last_cmd = "vkCmdBlitImage";
1817 suggestion =
1818 "The blit is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
1819 "Rather than blitting, just render the source image in a fragment shader in this render pass, "
1820 "which avoids the memory roundtrip.";
1821 break;
1822 case IMAGE_SUBRESOURCE_USAGE_BP::CLEARED:
1823 vuid = kVUID_BestPractices_RenderPass_InefficientClear;
1824 last_cmd = "vkCmdClear*Image";
1825 suggestion =
1826 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
1827 "tile-based architectures. "
1828 "Use LOAD_OP_CLEAR instead to clear the image for free.";
1829 break;
1830 case IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE:
1831 vuid = kVUID_BestPractices_RenderPass_CopyImage_LoadOpLoad;
1832 last_cmd = "vkCmdCopy*Image";
1833 suggestion =
1834 "The copy is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
1835 "Rather than copying, just render the source image in a fragment shader in this render pass, "
1836 "which avoids the memory roundtrip.";
1837 break;
1838 case IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE:
1839 vuid = kVUID_BestPractices_RenderPass_ResolveImage_LoadOpLoad;
1840 last_cmd = "vkCmdResolveImage";
1841 suggestion =
1842 "The resolve is probably redundant in this case, and wastes a lot of bandwidth on tile-based architectures. "
1843 "Rather than resolving, and then loading, try to keep rendering in the same render pass, "
1844 "which avoids the memory roundtrip.";
1845 break;
1846 default:
1847 break;
1848 }
1849
1850 LogPerformanceWarning(
1851 device, vuid,
LawG4015be1c2022-03-01 10:37:52 +00001852 "%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 +01001853 "time image was used, it was written to with %s. %s",
LawG44d414ba2022-02-23 15:35:41 +00001854 function_name, VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), array_layer, mip_level, last_cmd,
1855 suggestion);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001856 }
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001857}
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001858
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001859void BestPractices::ValidateImageInQueue(const char* function_name, bp_state::Image& state, IMAGE_SUBRESOURCE_USAGE_BP usage,
1860 uint32_t array_layer, uint32_t mip_level) {
1861 auto last_usage = state.UpdateUsage(array_layer, mip_level, usage);
paul-lunarg5eb52062022-06-27 18:57:15 +02001862
1863 // When image was discarded with StoreOpDontCare but is now being read with LoadOpLoad
1864 if (last_usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_DISCARDED &&
1865 usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE) {
1866 LogWarning(device, kVUID_BestPractices_StoreOpDontCareThenLoadOpLoad,
1867 "Trying to load an attachment with LOAD_OP_LOAD that was previously stored with STORE_OP_DONT_CARE. This may "
1868 "result in undefined behaviour.");
1869 }
1870
LawG44d414ba2022-02-23 15:35:41 +00001871 if (VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG)) {
1872 ValidateImageInQueueArmImg(function_name, state, last_usage, usage, array_layer, mip_level);
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001873 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001874}
1875
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001876void BestPractices::AddDeferredQueueOperations(bp_state::CommandBuffer& cb) {
1877 cb.queue_submit_functions.insert(cb.queue_submit_functions.end(), cb.queue_submit_functions_after_render_pass.begin(),
1878 cb.queue_submit_functions_after_render_pass.end());
1879 cb.queue_submit_functions_after_render_pass.clear();
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001880}
1881
1882void BestPractices::PreCallRecordCmdEndRenderPass(VkCommandBuffer commandBuffer) {
1883 ValidationStateTracker::PreCallRecordCmdEndRenderPass(commandBuffer);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001884 auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
1885 if (cb_node) {
1886 AddDeferredQueueOperations(*cb_node);
1887 }
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001888}
1889
1890void BestPractices::PreCallRecordCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassInfo) {
1891 ValidationStateTracker::PreCallRecordCmdEndRenderPass2(commandBuffer, pSubpassInfo);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001892 auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
1893 if (cb_node) {
1894 AddDeferredQueueOperations(*cb_node);
1895 }
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001896}
1897
1898void BestPractices::PreCallRecordCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfoKHR *pSubpassInfo) {
1899 ValidationStateTracker::PreCallRecordCmdEndRenderPass2KHR(commandBuffer, pSubpassInfo);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001900 auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
1901 if (cb_node) {
1902 AddDeferredQueueOperations(*cb_node);
1903 }
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001904}
1905
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02001906void BestPractices::PreCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer,
1907 const VkRenderPassBeginInfo* pRenderPassBegin,
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001908 VkSubpassContents contents) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001909 ValidationStateTracker::PreCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02001910 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1911}
1912
1913void BestPractices::PreCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer,
1914 const VkRenderPassBeginInfo* pRenderPassBegin,
1915 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1916 ValidationStateTracker::PreCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1917 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1918}
1919
1920void BestPractices::PreCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1921 const VkRenderPassBeginInfo* pRenderPassBegin,
1922 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1923 ValidationStateTracker::PreCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1924 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1925}
1926
1927void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001928
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001929 if (!pRenderPassBegin) {
1930 return;
1931 }
1932
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001933 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001934
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001935 auto rp_state = Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001936 if (rp_state) {
1937 // Check load ops
1938 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001939 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001940
1941 if (!RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att) &&
1942 !RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1943 continue;
1944 }
1945
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001946 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::UNDEFINED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001947
1948 if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) ||
1949 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001950 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02001951 } else if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) ||
1952 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_CLEAR)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001953 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_CLEARED;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02001954 } else if (RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att)) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001955 usage = IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001956 }
1957
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001958 auto framebuffer = Get<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer);
Jeremy Gebben9f537102021-10-05 16:37:12 -06001959 std::shared_ptr<IMAGE_VIEW_STATE> image_view = nullptr;
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001960
Tony-LunarGb3ab3572021-07-02 09:45:17 -06001961 if (framebuffer->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001962 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
1963 if (rpabi) {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001964 image_view = Get<IMAGE_VIEW_STATE>(rpabi->pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001965 }
1966 } else {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001967 image_view = Get<IMAGE_VIEW_STATE>(framebuffer->createInfo.pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001968 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001969
Jeremy Gebben9f537102021-10-05 16:37:12 -06001970 QueueValidateImageView(cb->queue_submit_functions, "vkCmdBeginRenderPass()", image_view.get(), usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001971 }
1972
1973 // Check store ops
1974 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001975 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001976
1977 if (!RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1978 continue;
1979 }
1980
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001981 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_DISCARDED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001982
1983 if ((!FormatIsStencilOnly(attachment.format) && attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE) ||
1984 (FormatHasStencil(attachment.format) && attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001985 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_STORED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001986 }
1987
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001988 auto framebuffer = Get<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001989
Jeremy Gebben9f537102021-10-05 16:37:12 -06001990 std::shared_ptr<IMAGE_VIEW_STATE> image_view;
Tony-LunarGb3ab3572021-07-02 09:45:17 -06001991 if (framebuffer->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001992 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
1993 if (rpabi) {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001994 image_view = Get<IMAGE_VIEW_STATE>(rpabi->pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001995 }
1996 } else {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001997 image_view = Get<IMAGE_VIEW_STATE>(framebuffer->createInfo.pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001998 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001999
Jeremy Gebben9f537102021-10-05 16:37:12 -06002000 QueueValidateImageView(cb->queue_submit_functions_after_render_pass, "vkCmdEndRenderPass()", image_view.get(), usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002001 }
2002 }
2003}
2004
Attilio Provenzano02859b22020-02-27 14:17:28 +00002005bool BestPractices::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
2006 VkSubpassContents contents) const {
Sam Walls0961ec02020-03-31 16:39:15 +01002007 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
2008 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002009 return skip;
2010}
2011
2012bool BestPractices::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
2013 const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08002014 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01002015 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
2016 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002017 return skip;
2018}
2019
2020bool BestPractices::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08002021 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01002022 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
2023 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002024 return skip;
2025}
2026
Sam Walls0961ec02020-03-31 16:39:15 +01002027void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
2028 const VkRenderPassBeginInfo* pRenderPassBegin) {
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002029 // Reset the renderpass state
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002030 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002031 cb->hasDrawCmd = false;
2032 assert(cb);
2033 auto& render_pass_state = cb->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002034 render_pass_state.touchesAttachments.clear();
2035 render_pass_state.earlyClearAttachments.clear();
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002036 render_pass_state.numDrawCallsDepthOnly = 0;
2037 render_pass_state.numDrawCallsDepthEqualCompare = 0;
2038 render_pass_state.colorAttachment = false;
2039 render_pass_state.depthAttachment = false;
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002040 render_pass_state.drawTouchAttachments = true;
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002041 // Don't reset state related to pipeline state.
Sam Walls0961ec02020-03-31 16:39:15 +01002042
Jeremy Gebbenf4449392022-01-28 10:09:10 -07002043 auto rp_state = Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
Sam Walls0961ec02020-03-31 16:39:15 +01002044
2045 // track depth / color attachment usage within the renderpass
2046 for (size_t i = 0; i < rp_state->createInfo.subpassCount; i++) {
2047 // record if depth/color attachments are in use for this renderpass
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002048 if (rp_state->createInfo.pSubpasses[i].pDepthStencilAttachment != nullptr) render_pass_state.depthAttachment = true;
Sam Walls0961ec02020-03-31 16:39:15 +01002049
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002050 if (rp_state->createInfo.pSubpasses[i].colorAttachmentCount > 0) render_pass_state.colorAttachment = true;
Sam Walls0961ec02020-03-31 16:39:15 +01002051 }
2052}
2053
2054void BestPractices::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
2055 VkSubpassContents contents) {
2056 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
2057 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
2058}
2059
2060void BestPractices::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
2061 const VkSubpassBeginInfo* pSubpassBeginInfo) {
2062 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
2063 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
2064}
2065
2066void BestPractices::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
2067 const VkRenderPassBeginInfo* pRenderPassBegin,
2068 const VkSubpassBeginInfo* pSubpassBeginInfo) {
2069 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
2070 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
2071}
2072
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002073// Generic function to handle validation for all CmdDraw* type functions
2074bool BestPractices::ValidateCmdDrawType(VkCommandBuffer cmd_buffer, const char* caller) const {
2075 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002076 const auto cb_state = GetRead<bp_state::CommandBuffer>(cmd_buffer);
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002077 if (cb_state) {
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002078 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
2079 const auto* pipeline_state = cb_state->lastBound[lv_bind_point].pipeline_state;
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002080 const auto& current_vtx_bfr_binding_info = cb_state->current_vertex_buffer_binding_info.vertex_buffer_bindings;
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002081
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002082 // Verify vertex binding
Tony-LunarG2ffe1f52022-04-11 15:13:30 -06002083 if (pipeline_state && pipeline_state->vertex_input_state &&
2084 pipeline_state->vertex_input_state->binding_descriptions.size() <= 0) {
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002085 if ((!current_vtx_bfr_binding_info.empty()) && (!cb_state->vertex_buffer_used)) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002086 skip |= LogPerformanceWarning(cb_state->commandBuffer(), kVUID_BestPractices_DrawState_VtxIndexOutOfBounds,
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07002087 "Vertex buffers are bound to %s but no vertex buffers are attached to %s.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002088 report_data->FormatHandle(cb_state->commandBuffer()).c_str(),
2089 report_data->FormatHandle(pipeline_state->pipeline()).c_str());
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002090 }
2091 }
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002092
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002093 const auto* pipe = cb_state->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002094 if (pipe) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002095 const auto& rp_state = pipe->RenderPassState();
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002096 if (rp_state) {
2097 for (uint32_t i = 0; i < rp_state->createInfo.subpassCount; ++i) {
2098 const auto& subpass = rp_state->createInfo.pSubpasses[i];
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002099 const auto* ds_state = pipe->DepthStencilState();
Jeremy Gebben11af9792021-08-20 10:20:09 -06002100 const uint32_t depth_stencil_attachment =
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002101 GetSubpassDepthStencilAttachmentIndex(ds_state, subpass.pDepthStencilAttachment);
2102 const auto* raster_state = pipe->RasterizationState();
2103 if ((depth_stencil_attachment == VK_ATTACHMENT_UNUSED) && raster_state &&
2104 raster_state->depthBiasEnable == VK_TRUE) {
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002105 skip |= LogWarning(cb_state->commandBuffer(), kVUID_BestPractices_DepthBiasNoAttachment,
2106 "%s: depthBiasEnable == VK_TRUE without a depth-stencil attachment.", caller);
2107 }
2108 }
2109 }
2110 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002111 }
2112 return skip;
2113}
2114
Sam Walls0961ec02020-03-31 16:39:15 +01002115void BestPractices::RecordCmdDrawType(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002116 auto cb_node = GetWrite<bp_state::CommandBuffer>(cmd_buffer);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002117 assert(cb_node);
Sam Walls0961ec02020-03-31 16:39:15 +01002118 if (VendorCheckEnabled(kBPVendorArm)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002119 RecordCmdDrawTypeArm(*cb_node, draw_count, caller);
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002120 }
2121
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002122 if (cb_node->render_pass_state.drawTouchAttachments) {
2123 for (auto& touch : cb_node->render_pass_state.nextDrawTouchesAttachments) {
2124 RecordAttachmentAccess(*cb_node, touch.framebufferAttachment, touch.aspects);
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002125 }
2126 // No need to touch the same attachments over and over.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002127 cb_node->render_pass_state.drawTouchAttachments = false;
Sam Walls0961ec02020-03-31 16:39:15 +01002128 }
2129}
2130
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002131void BestPractices::RecordCmdDrawTypeArm(bp_state::CommandBuffer& cb_node, uint32_t draw_count, const char* caller) {
2132 auto& render_pass_state = cb_node.render_pass_state;
LawG4b21485c2022-02-28 13:46:48 +00002133 // Each TBDR vendor requires a depth pre-pass draw call to have a minimum number of vertices/indices before it counts towards
2134 // depth prepass warnings First find the lowest enabled draw count
2135 uint32_t lowestEnabledMinDrawCount = 0;
2136 lowestEnabledMinDrawCount = VendorCheckEnabled(kBPVendorArm) * kDepthPrePassMinDrawCountArm;
2137 if (VendorCheckEnabled(kBPVendorIMG) && kDepthPrePassMinDrawCountIMG < lowestEnabledMinDrawCount)
2138 lowestEnabledMinDrawCount = kDepthPrePassMinDrawCountIMG;
2139
2140 if (draw_count >= lowestEnabledMinDrawCount) {
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002141 if (render_pass_state.depthOnly) render_pass_state.numDrawCallsDepthOnly++;
2142 if (render_pass_state.depthEqualComparison) render_pass_state.numDrawCallsDepthEqualCompare++;
Sam Walls0961ec02020-03-31 16:39:15 +01002143 }
2144}
2145
Camden5b184be2019-08-13 07:50:19 -06002146bool BestPractices::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002147 uint32_t firstVertex, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06002148 bool skip = false;
2149
2150 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002151 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
2152 "Warning: You are calling vkCmdDraw() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06002153 }
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002154 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDraw()");
Camden5b184be2019-08-13 07:50:19 -06002155
2156 return skip;
2157}
2158
Sam Walls0961ec02020-03-31 16:39:15 +01002159void BestPractices::PostCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
2160 uint32_t firstVertex, uint32_t firstInstance) {
2161 StateTracker::PostCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
2162 RecordCmdDrawType(commandBuffer, vertexCount * instanceCount, "vkCmdDraw()");
2163}
2164
Camden5b184be2019-08-13 07:50:19 -06002165bool BestPractices::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002166 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06002167 bool skip = false;
2168
2169 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002170 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
2171 "Warning: You are calling vkCmdDrawIndexed() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06002172 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002173 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexed()");
2174
Attilio Provenzano02859b22020-02-27 14:17:28 +00002175 // Check if we reached the limit for small indexed draw calls.
2176 // Note that we cannot update the draw call count here, so we do it in PreCallRecordCmdDrawIndexed.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002177 const auto cmd_state = GetRead<bp_state::CommandBuffer>(commandBuffer);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002178 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices &&
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02002179 (cmd_state->small_indexed_draw_call_count == kMaxSmallIndexedDrawcalls - 1) &&
LawG4ff42d722022-03-01 10:28:25 +00002180 (VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG))) {
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02002181 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_ManySmallIndexedDrawcalls,
LawG4ff42d722022-03-01 10:28:25 +00002182 "%s %s: The command buffer contains many small indexed drawcalls "
Attilio Provenzano02859b22020-02-27 14:17:28 +00002183 "(at least %u drawcalls with less than %u indices each). This may cause pipeline bubbles. "
2184 "You can try batching drawcalls or instancing when applicable.",
LawG4ff42d722022-03-01 10:28:25 +00002185 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), kMaxSmallIndexedDrawcalls,
2186 kSmallIndexedDrawcallIndices);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002187 }
2188
Sam Walls8e77e4f2020-03-16 20:47:40 +00002189 if (VendorCheckEnabled(kBPVendorArm)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002190 ValidateIndexBufferArm(*cmd_state, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002191 }
2192
2193 return skip;
2194}
2195
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002196bool BestPractices::ValidateIndexBufferArm(const bp_state::CommandBuffer& cmd_state, uint32_t indexCount, uint32_t instanceCount,
Sam Walls8e77e4f2020-03-16 20:47:40 +00002197 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
2198 bool skip = false;
2199
2200 // check for sparse/underutilised index buffer, and post-transform cache thrashing
Sam Walls8e77e4f2020-03-16 20:47:40 +00002201
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002202 const auto* ib_state = cmd_state.index_buffer_binding.buffer_state.get();
2203 if (ib_state == nullptr || cmd_state.index_buffer_binding.buffer_state->Destroyed()) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00002204
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002205 const VkIndexType ib_type = cmd_state.index_buffer_binding.index_type;
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06002206 const auto& ib_mem_state = *ib_state->MemState();
Sam Walls8e77e4f2020-03-16 20:47:40 +00002207 const VkDeviceSize ib_mem_offset = ib_mem_state.mapped_range.offset;
2208 const void* ib_mem = ib_mem_state.p_driver_data;
2209 bool primitive_restart_enable = false;
2210
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002211 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002212 const auto& pipeline_binding_iter = cmd_state.lastBound[lv_bind_point];
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002213 const auto* pipeline_state = pipeline_binding_iter.pipeline_state;
Sam Walls8e77e4f2020-03-16 20:47:40 +00002214
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002215 const auto* ia_state = pipeline_state ? pipeline_state->InputAssemblyState() : nullptr;
2216 if (ia_state) {
2217 primitive_restart_enable = ia_state->primitiveRestartEnable == VK_TRUE;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002218 }
Sam Walls8e77e4f2020-03-16 20:47:40 +00002219
2220 // 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 -06002221 if (ib_mem && pipeline_binding_iter.IsUsing()) {
Sam Walls8e77e4f2020-03-16 20:47:40 +00002222 uint32_t scan_stride;
2223 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
2224 scan_stride = sizeof(uint8_t);
2225 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
2226 scan_stride = sizeof(uint16_t);
2227 } else {
2228 scan_stride = sizeof(uint32_t);
2229 }
2230
2231 const uint8_t* scan_begin = static_cast<const uint8_t*>(ib_mem) + ib_mem_offset + firstIndex * scan_stride;
2232 const uint8_t* scan_end = scan_begin + indexCount * scan_stride;
2233
2234 // Min and max are important to track for some Mali architectures. In older Mali devices without IDVS, all
2235 // vertices corresponding to indices between the minimum and maximum may be loaded, and possibly shaded,
2236 // irrespective of whether or not they're part of the draw call.
2237
2238 // start with minimum as 0xFFFFFFFF and adjust to indices in the buffer
2239 uint32_t min_index = ~0u;
2240 // start with maximum as 0 and adjust to indices in the buffer
2241 uint32_t max_index = 0u;
2242
2243 // first scan-through, we're looking to simulate a model LRU post-transform cache, estimating the number of vertices shaded
2244 // for the given index buffer
2245 uint32_t vertex_shade_count = 0;
2246
2247 PostTransformLRUCacheModel post_transform_cache;
2248
2249 // The size of the cache being modelled positively correlates with how much behaviour it can capture about
2250 // arbitrary ground-truth hardware/architecture cache behaviour. I.e. it's a good solution when we don't know the
2251 // target architecture.
2252 // However, modelling a post-transform cache with more than 32 elements gives diminishing returns in practice.
2253 // http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
2254 post_transform_cache.resize(32);
2255
2256 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
2257 uint32_t scan_index;
2258 uint32_t primitive_restart_value;
2259 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
2260 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
2261 primitive_restart_value = 0xFF;
2262 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
2263 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
2264 primitive_restart_value = 0xFFFF;
2265 } else {
2266 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
2267 primitive_restart_value = 0xFFFFFFFF;
2268 }
2269
2270 max_index = std::max(max_index, scan_index);
2271 min_index = std::min(min_index, scan_index);
2272
2273 if (!primitive_restart_enable || scan_index != primitive_restart_value) {
2274 bool in_cache = post_transform_cache.query_cache(scan_index);
2275 // if the shaded vertex corresponding to the index is not in the PT-cache, we need to shade again
2276 if (!in_cache) vertex_shade_count++;
2277 }
2278 }
2279
2280 // 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 +01002281 // 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
2282 if (max_index < min_index || max_index == min_index) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00002283
2284 if (max_index - min_index >= indexCount) {
Mark Young0ec6b062020-11-19 15:32:17 -07002285 skip |=
2286 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
2287 "%s The indices which were specified for the draw call only utilise approximately %.02f%% of "
2288 "index buffer value range. Arm Mali architectures before G71 do not have IDVS (Index-Driven "
2289 "Vertex Shading), meaning all vertices corresponding to indices between the minimum and "
2290 "maximum would be loaded, and possibly shaded, whether or not they are used.",
2291 VendorSpecificTag(kBPVendorArm),
2292 (static_cast<float>(indexCount) / static_cast<float>(max_index - min_index)) * 100.0f);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002293 return skip;
2294 }
2295
2296 // use a dynamic vector of bitsets as a memory-compact representation of which indices are included in the draw call
2297 // 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 +01002298 const size_t refs_per_bucket = 64;
2299 std::vector<std::bitset<refs_per_bucket>> vertex_reference_buckets;
2300
2301 const uint32_t n_indices = max_index - min_index + 1;
2302 const uint32_t n_buckets = (n_indices / static_cast<uint32_t>(refs_per_bucket)) +
2303 ((n_indices % static_cast<uint32_t>(refs_per_bucket)) != 0 ? 1 : 0);
2304
2305 // there needs to be at least one bitset to store a set of indices smaller than n_buckets
2306 vertex_reference_buckets.resize(std::max(1u, n_buckets));
Sam Walls8e77e4f2020-03-16 20:47:40 +00002307
2308 // To avoid using too much memory, we run over the indices again.
2309 // Knowing the size from the last scan allows us to record index usage with bitsets
2310 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
2311 uint32_t scan_index;
2312 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
2313 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
2314 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
2315 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
2316 } else {
2317 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
2318 }
2319 // keep track of the set of all indices used to reference vertices in the draw call
2320 size_t index_offset = scan_index - min_index;
Sam Walls61b06892020-07-23 16:20:50 +01002321 size_t bitset_bucket_index = index_offset / refs_per_bucket;
2322 uint64_t used_indices = 1ull << ((index_offset % refs_per_bucket) & 0xFFFFFFFFu);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002323 vertex_reference_buckets[bitset_bucket_index] |= used_indices;
2324 }
2325
2326 uint32_t vertex_reference_count = 0;
2327 for (const auto& bitset : vertex_reference_buckets) {
2328 vertex_reference_count += static_cast<uint32_t>(bitset.count());
2329 }
2330
2331 // 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 -07002332 float utilization = static_cast<float>(vertex_reference_count) / static_cast<float>(max_index - min_index + 1);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002333 // 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 -07002334 float cache_hit_rate = static_cast<float>(vertex_reference_count) / static_cast<float>(vertex_shade_count);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002335
2336 if (utilization < 0.5f) {
2337 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
2338 "%s The indices which were specified for the draw call only utilise approximately "
2339 "%.02f%% of the bound vertex buffer.",
2340 VendorSpecificTag(kBPVendorArm), utilization);
2341 }
2342
2343 if (cache_hit_rate <= 0.5f) {
2344 skip |=
2345 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_PostTransformCacheThrashing,
2346 "%s The indices which were specified for the draw call are estimated to cause thrashing of "
2347 "the post-transform vertex cache, with a hit-rate of %.02f%%. "
2348 "I.e. the ordering of the index buffer may not make optimal use of indices associated with "
2349 "recently shaded vertices.",
2350 VendorSpecificTag(kBPVendorArm), cache_hit_rate * 100.0f);
2351 }
2352 }
2353
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002354 return skip;
2355}
2356
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002357bool BestPractices::PreCallValidateCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
2358 const VkCommandBuffer* pCommandBuffers) const {
2359 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002360 const auto primary = GetRead<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002361 for (uint32_t i = 0; i < commandBufferCount; i++) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002362 const auto secondary_cb = GetRead<bp_state::CommandBuffer>(pCommandBuffers[i]);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002363 if (secondary_cb == nullptr) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002364 continue;
2365 }
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002366 const auto& secondary = secondary_cb->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002367 for (auto& clear : secondary.earlyClearAttachments) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002368 if (ClearAttachmentsIsFullClear(*primary, uint32_t(clear.rects.size()), clear.rects.data())) {
2369 skip |= ValidateClearAttachment(*primary, clear.framebufferAttachment, clear.colorAttachment, clear.aspects, true);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002370 }
2371 }
2372 }
Nadav Gevaf0808442021-05-21 13:51:25 -04002373
2374 if (VendorCheckEnabled(kBPVendorAMD)) {
2375 if (commandBufferCount > 0) {
2376 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdBuffer_AvoidSecondaryCmdBuffers,
2377 "%s Performance warning: Use of secondary command buffers is not recommended. ",
2378 VendorSpecificTag(kBPVendorAMD));
2379 }
2380 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002381 return skip;
2382}
2383
2384void BestPractices::PreCallRecordCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
2385 const VkCommandBuffer* pCommandBuffers) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002386 ValidationStateTracker::PreCallRecordCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
2387
2388 auto primary = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2389 if (!primary) {
2390 return;
2391 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002392
2393 for (uint32_t i = 0; i < commandBufferCount; i++) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002394 auto secondary = GetWrite<bp_state::CommandBuffer>(pCommandBuffers[i]);
2395 if (!secondary) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002396 continue;
2397 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002398
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002399 for (auto& early_clear : secondary->render_pass_state.earlyClearAttachments) {
2400 if (ClearAttachmentsIsFullClear(*primary, uint32_t(early_clear.rects.size()), early_clear.rects.data())) {
2401 RecordAttachmentClearAttachments(*primary, early_clear.framebufferAttachment, early_clear.colorAttachment,
2402 early_clear.aspects, uint32_t(early_clear.rects.size()), early_clear.rects.data());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002403 } else {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002404 RecordAttachmentAccess(*primary, early_clear.framebufferAttachment, early_clear.aspects);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002405 }
2406 }
2407
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002408 for (auto& touch : secondary->render_pass_state.touchesAttachments) {
2409 RecordAttachmentAccess(*primary, touch.framebufferAttachment, touch.aspects);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002410 }
Hans-Kristian Arntzenc7eb82a2021-06-16 13:57:18 +02002411
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002412 primary->render_pass_state.numDrawCallsDepthEqualCompare += secondary->render_pass_state.numDrawCallsDepthEqualCompare;
2413 primary->render_pass_state.numDrawCallsDepthOnly += secondary->render_pass_state.numDrawCallsDepthOnly;
Hans-Kristian Arntzenaf81dca2021-06-18 11:14:28 +02002414
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002415 if (secondary->hasDrawCmd) {
Hans-Kristian Arntzenaf81dca2021-06-18 11:14:28 +02002416 primary->hasDrawCmd = true;
2417 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002418 }
2419
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002420}
2421
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002422void BestPractices::RecordAttachmentAccess(bp_state::CommandBuffer& cb_state, uint32_t fb_attachment, VkImageAspectFlags aspects) {
2423 auto& state = cb_state.render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002424 // Called when we have a partial clear attachment, or a normal draw call which accesses an attachment.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002425 auto itr =
2426 std::find_if(state.touchesAttachments.begin(), state.touchesAttachments.end(),
2427 [fb_attachment](const bp_state::AttachmentInfo& info) { return info.framebufferAttachment == fb_attachment; });
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002428
2429 if (itr != state.touchesAttachments.end()) {
2430 itr->aspects |= aspects;
2431 } else {
2432 state.touchesAttachments.push_back({ fb_attachment, aspects });
2433 }
2434}
2435
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002436void BestPractices::RecordAttachmentClearAttachments(bp_state::CommandBuffer& cmd_state, uint32_t fb_attachment,
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002437 uint32_t color_attachment, VkImageAspectFlags aspects, uint32_t rectCount,
2438 const VkClearRect* pRects) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002439 auto& state = cmd_state.render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002440 // If we observe a full clear before any other access to a frame buffer attachment,
2441 // we have candidate for redundant clear attachments.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002442 auto itr =
2443 std::find_if(state.touchesAttachments.begin(), state.touchesAttachments.end(),
2444 [fb_attachment](const bp_state::AttachmentInfo& info) { return info.framebufferAttachment == fb_attachment; });
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002445
2446 uint32_t new_aspects = aspects;
2447 if (itr != state.touchesAttachments.end()) {
2448 new_aspects = aspects & ~itr->aspects;
2449 itr->aspects |= aspects;
2450 } else {
2451 state.touchesAttachments.push_back({ fb_attachment, aspects });
2452 }
2453
2454 if (new_aspects == 0) {
2455 return;
2456 }
2457
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002458 if (cmd_state.createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002459 // The first command might be a clear, but might not be the first in the render pass, defer any checks until
2460 // CmdExecuteCommands.
2461 state.earlyClearAttachments.push_back({ fb_attachment, color_attachment, new_aspects,
2462 std::vector<VkClearRect>{pRects, pRects + rectCount} });
2463 }
2464}
2465
2466void BestPractices::PreCallRecordCmdClearAttachments(VkCommandBuffer commandBuffer,
2467 uint32_t attachmentCount, const VkClearAttachment* pClearAttachments,
2468 uint32_t rectCount, const VkClearRect* pRects) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002469 ValidationStateTracker::PreCallRecordCmdClearAttachments(commandBuffer, attachmentCount, pClearAttachments, rectCount, pRects);
2470
2471 auto cmd_state = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2472 auto* rp_state = cmd_state->activeRenderPass.get();
2473 auto* fb_state = cmd_state->activeFramebuffer.get();
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002474 bool is_secondary = cmd_state->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY;
2475
2476 if (rectCount == 0 || !rp_state) {
2477 return;
2478 }
2479
2480 if (!is_secondary && !fb_state) {
2481 return;
2482 }
2483
2484 // 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 -07002485 bool full_clear = ClearAttachmentsIsFullClear(*cmd_state, rectCount, pRects);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002486
ziga-lunarg885c6542022-03-07 01:08:25 +01002487 if (!rp_state->use_dynamic_rendering && !rp_state->use_dynamic_rendering_inherited) {
2488 auto& subpass = rp_state->createInfo.pSubpasses[cmd_state->activeSubpass];
2489 for (uint32_t i = 0; i < attachmentCount; i++) {
2490 auto& attachment = pClearAttachments[i];
2491 uint32_t fb_attachment = VK_ATTACHMENT_UNUSED;
2492 VkImageAspectFlags aspects = attachment.aspectMask;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002493
ziga-lunarg885c6542022-03-07 01:08:25 +01002494 if (aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) {
2495 if (subpass.pDepthStencilAttachment) {
2496 fb_attachment = subpass.pDepthStencilAttachment->attachment;
2497 }
2498 } else if (aspects & VK_IMAGE_ASPECT_COLOR_BIT) {
2499 fb_attachment = subpass.pColorAttachments[attachment.colorAttachment].attachment;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002500 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002501
ziga-lunarg885c6542022-03-07 01:08:25 +01002502 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2503 if (full_clear) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002504 RecordAttachmentClearAttachments(*cmd_state, fb_attachment, attachment.colorAttachment,
ziga-lunarg885c6542022-03-07 01:08:25 +01002505 aspects, rectCount, pRects);
2506 } else {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002507 RecordAttachmentAccess(*cmd_state, fb_attachment, aspects);
ziga-lunarg885c6542022-03-07 01:08:25 +01002508 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002509 }
2510 }
2511 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002512}
2513
Attilio Provenzano02859b22020-02-27 14:17:28 +00002514void BestPractices::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
2515 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
2516 ValidationStateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset,
2517 firstInstance);
2518
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002519 auto cmd_state = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002520 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices) {
2521 cmd_state->small_indexed_draw_call_count++;
2522 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002523
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002524 ValidateBoundDescriptorSets(*cmd_state, "vkCmdDrawIndexed()");
Attilio Provenzano02859b22020-02-27 14:17:28 +00002525}
2526
Sam Walls0961ec02020-03-31 16:39:15 +01002527void BestPractices::PostCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
2528 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
2529 StateTracker::PostCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
2530 RecordCmdDrawType(commandBuffer, indexCount * instanceCount, "vkCmdDrawIndexed()");
2531}
2532
sfricke-samsung681ab7b2020-10-29 01:53:35 -07002533bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2534 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
2535 uint32_t maxDrawCount, uint32_t stride) const {
2536 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCount()");
2537
2538 return skip;
2539}
2540
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002541bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
2542 VkDeviceSize offset, VkBuffer countBuffer,
2543 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
2544 uint32_t stride) const {
2545 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCountKHR()");
Camden5b184be2019-08-13 07:50:19 -06002546
2547 return skip;
2548}
2549
2550bool BestPractices::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002551 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06002552 bool skip = false;
2553
2554 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002555 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
2556 "Warning: You are calling vkCmdDrawIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002557 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirect()");
Camden5b184be2019-08-13 07:50:19 -06002558 }
2559
2560 return skip;
2561}
2562
Sam Walls0961ec02020-03-31 16:39:15 +01002563void BestPractices::PostCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2564 uint32_t count, uint32_t stride) {
2565 StateTracker::PostCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, count, stride);
2566 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndirect()");
2567}
2568
Camden5b184be2019-08-13 07:50:19 -06002569bool BestPractices::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002570 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06002571 bool skip = false;
2572
2573 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002574 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
2575 "Warning: You are calling vkCmdDrawIndexedIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002576 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirect()");
Camden5b184be2019-08-13 07:50:19 -06002577 }
2578
2579 return skip;
2580}
2581
Sam Walls0961ec02020-03-31 16:39:15 +01002582void BestPractices::PostCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2583 uint32_t count, uint32_t stride) {
2584 StateTracker::PostCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, count, stride);
2585 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndexedIndirect()");
2586}
2587
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002588void BestPractices::ValidateBoundDescriptorSets(bp_state::CommandBuffer& cb_state, const char* function_name) {
2589 for (auto descriptor_set : cb_state.validated_descriptor_sets) {
2590 const auto& layout = *descriptor_set->GetLayout();
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002591
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002592 for (uint32_t index = 0; index < descriptor_set->GetBindingCount(); ++index) {
2593 // For bindless scenarios, we should not attempt to track descriptor set state.
2594 // It is highly uncertain which resources are actually bound.
2595 // Resources which are written to such a descriptor should be marked as indeterminate w.r.t. state.
2596 VkDescriptorBindingFlags flags = layout.GetDescriptorBindingFlagsFromIndex(index);
2597 if (flags & (VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT | VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT |
2598 VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT)) {
2599 continue;
2600 }
Hans-Kristian Arntzena8199012021-03-22 12:10:07 +01002601
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002602 auto index_range = layout.GetGlobalIndexRangeFromIndex(index);
2603 for (uint32_t i = index_range.start; i < index_range.end; ++i) {
2604 VkImageView image_view{VK_NULL_HANDLE};
2605
2606 auto descriptor = descriptor_set->GetDescriptorFromGlobalIndex(i);
ziga-lunarg33d806c2022-05-05 17:00:52 +02002607 if (!descriptor) {
2608 continue;
2609 }
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002610 switch (descriptor->GetClass()) {
2611 case cvdescriptorset::DescriptorClass::Image: {
2612 if (const auto image_descriptor = static_cast<const cvdescriptorset::ImageDescriptor*>(descriptor)) {
2613 image_view = image_descriptor->GetImageView();
2614 }
2615 break;
2616 }
2617 case cvdescriptorset::DescriptorClass::ImageSampler: {
2618 if (const auto image_sampler_descriptor =
2619 static_cast<const cvdescriptorset::ImageSamplerDescriptor*>(descriptor)) {
2620 image_view = image_sampler_descriptor->GetImageView();
2621 }
2622 break;
2623 }
2624 default:
2625 break;
Hans-Kristian Arntzena8199012021-03-22 12:10:07 +01002626 }
2627
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002628 if (image_view) {
2629 auto image_view_state = Get<IMAGE_VIEW_STATE>(image_view);
2630 QueueValidateImageView(cb_state.queue_submit_functions, function_name, image_view_state.get(),
2631 IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002632 }
2633 }
2634 }
2635 }
2636}
2637
2638void BestPractices::PreCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
2639 uint32_t firstVertex, uint32_t firstInstance) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002640 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2641 ValidateBoundDescriptorSets(*cb_node, "vkCmdDraw()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002642}
2643
2644void BestPractices::PreCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2645 uint32_t drawCount, uint32_t stride) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002646 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2647 ValidateBoundDescriptorSets(*cb_node, "vkCmdDrawIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002648}
2649
2650void BestPractices::PreCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2651 uint32_t drawCount, uint32_t stride) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002652 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2653 ValidateBoundDescriptorSets(*cb_node, "vkCmdDrawIndexedIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002654}
2655
Camden5b184be2019-08-13 07:50:19 -06002656bool BestPractices::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t groupCountX, uint32_t groupCountY,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002657 uint32_t groupCountZ) const {
Camden5b184be2019-08-13 07:50:19 -06002658 bool skip = false;
2659
2660 if ((groupCountX == 0) || (groupCountY == 0) || (groupCountZ == 0)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002661 skip |= LogWarning(device, kVUID_BestPractices_CmdDispatch_GroupCountZero,
2662 "Warning: You are calling vkCmdDispatch() while one or more groupCounts are zero (groupCountX = %" PRIu32
2663 ", groupCountY = %" PRIu32 ", groupCountZ = %" PRIu32 ").",
2664 groupCountX, groupCountY, groupCountZ);
Camden5b184be2019-08-13 07:50:19 -06002665 }
2666
2667 return skip;
2668}
Camden83a9c372019-08-14 11:41:38 -06002669
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002670bool BestPractices::PreCallValidateCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo* pSubpassEndInfo) const {
2671 bool skip = false;
2672 skip |= StateTracker::PreCallValidateCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
2673 skip |= ValidateCmdEndRenderPass(commandBuffer);
2674 return skip;
2675}
2676
2677bool BestPractices::PreCallValidateCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfo* pSubpassEndInfo) const {
2678 bool skip = false;
2679 skip |= StateTracker::PreCallValidateCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
2680 skip |= ValidateCmdEndRenderPass(commandBuffer);
2681 return skip;
2682}
2683
Sam Walls0961ec02020-03-31 16:39:15 +01002684bool BestPractices::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
2685 bool skip = false;
Sam Walls0961ec02020-03-31 16:39:15 +01002686 skip |= StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002687 skip |= ValidateCmdEndRenderPass(commandBuffer);
2688 return skip;
2689}
2690
2691bool BestPractices::ValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
2692 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002693 const auto cmd = GetRead<bp_state::CommandBuffer>(commandBuffer);
Sam Walls0961ec02020-03-31 16:39:15 +01002694
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002695 if (cmd == nullptr) return skip;
2696 auto &render_pass_state = cmd->render_pass_state;
Sam Walls0961ec02020-03-31 16:39:15 +01002697
LawG4b21485c2022-02-28 13:46:48 +00002698 // Does the number of draw calls classified as depth only surpass the vendor limit for a specified vendor
2699 bool depth_only_arm = render_pass_state.numDrawCallsDepthEqualCompare >= kDepthPrePassNumDrawCallsArm &&
2700 render_pass_state.numDrawCallsDepthOnly >= kDepthPrePassNumDrawCallsArm;
2701 bool depth_only_img = render_pass_state.numDrawCallsDepthEqualCompare >= kDepthPrePassNumDrawCallsIMG &&
2702 render_pass_state.numDrawCallsDepthOnly >= kDepthPrePassNumDrawCallsIMG;
2703
2704 // Only send the warning when the vendor is enabled and a depth prepass is detected
LawG498ec4502022-04-05 09:08:25 +01002705 bool uses_depth =
2706 (render_pass_state.depthAttachment || render_pass_state.colorAttachment) &&
LawG45507e142022-04-08 09:36:54 +01002707 ((depth_only_arm && VendorCheckEnabled(kBPVendorArm)) || (depth_only_img && VendorCheckEnabled(kBPVendorIMG)));
LawG4b21485c2022-02-28 13:46:48 +00002708
Sam Walls0961ec02020-03-31 16:39:15 +01002709 if (uses_depth) {
2710 skip |= LogPerformanceWarning(
2711 device, kVUID_BestPractices_EndRenderPass_DepthPrePassUsage,
LawG4015be1c2022-03-01 10:37:52 +00002712 "%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 +00002713 "renderering architectures; such as those in Arm Mali or PowerVR GPUs. Since they can remove geometry "
2714 "hidden by other opaque geometry. Mali has Forward Pixel Killing (FPK), PowerVR has Hiden Surface "
2715 "Remover (HSR) in which case, using depth pre-passes for hidden surface removal may worsen performance.",
2716 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG));
Sam Walls0961ec02020-03-31 16:39:15 +01002717 }
2718
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002719 RENDER_PASS_STATE* rp = cmd->activeRenderPass.get();
2720
LawG40da9c3d2022-03-01 09:51:01 +00002721 if ((VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG)) && rp) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002722 // If we use an attachment on-tile, we should access it in some way. Otherwise,
2723 // it is redundant to have it be part of the render pass.
2724 // Only consider it redundant if it will actually consume bandwidth, i.e.
2725 // LOAD_OP_LOAD is used or STORE_OP_STORE. CLEAR -> DONT_CARE is benign,
2726 // as is using pure input attachments.
2727 // CLEAR -> STORE might be considered a "useful" thing to do, but
2728 // the optimal thing to do is to defer the clear until you're actually
2729 // going to render to the image.
2730
2731 uint32_t num_attachments = rp->createInfo.attachmentCount;
2732 for (uint32_t i = 0; i < num_attachments; i++) {
Hans-Kristian Arntzen237663c2021-07-01 14:36:40 +02002733 if (!RenderPassUsesAttachmentOnTile(rp->createInfo, i) ||
2734 RenderPassUsesAttachmentAsResolve(rp->createInfo, i)) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002735 continue;
2736 }
2737
2738 auto& attachment = rp->createInfo.pAttachments[i];
2739
2740 VkImageAspectFlags bandwidth_aspects = 0;
2741
2742 if (!FormatIsStencilOnly(attachment.format) &&
2743 (attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
2744 attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE)) {
2745 if (FormatHasDepth(attachment.format)) {
2746 bandwidth_aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
2747 } else {
2748 bandwidth_aspects |= VK_IMAGE_ASPECT_COLOR_BIT;
2749 }
2750 }
2751
2752 if (FormatHasStencil(attachment.format) &&
2753 (attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
2754 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE)) {
2755 bandwidth_aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
2756 }
2757
2758 if (!bandwidth_aspects) {
2759 continue;
2760 }
2761
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002762 auto itr = std::find_if(render_pass_state.touchesAttachments.begin(), render_pass_state.touchesAttachments.end(),
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002763 [i](const bp_state::AttachmentInfo& info) { return info.framebufferAttachment == i; });
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002764 uint32_t untouched_aspects = bandwidth_aspects;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002765 if (itr != render_pass_state.touchesAttachments.end()) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002766 untouched_aspects &= ~itr->aspects;
2767 }
2768
2769 if (untouched_aspects) {
2770 skip |= LogPerformanceWarning(
2771 device, kVUID_BestPractices_EndRenderPass_RedundantAttachmentOnTile,
LawG4015be1c2022-03-01 10:37:52 +00002772 "%s %s: Render pass was ended, but attachment #%u (format: %u, untouched aspects 0x%x) "
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002773 "was never accessed by a pipeline or clear command. "
LawG40da9c3d2022-03-01 09:51:01 +00002774 "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 +00002775 "render pass if the attachments are not intended to be accessed.",
LawG40da9c3d2022-03-01 09:51:01 +00002776 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), i, attachment.format, untouched_aspects);
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002777 }
2778 }
2779 }
2780
Sam Walls0961ec02020-03-31 16:39:15 +01002781 return skip;
2782}
2783
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002784void BestPractices::PreCallRecordCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002785 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2786 ValidateBoundDescriptorSets(*cb_node, "vkCmdDispatch()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002787}
2788
2789void BestPractices::PreCallRecordCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002790 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2791 ValidateBoundDescriptorSets(*cb_node, "vkCmdDispatchIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002792}
2793
Camden Stocker9c051442019-11-06 14:28:43 -08002794bool BestPractices::ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(VkPhysicalDevice physicalDevice,
2795 const char* api_name) const {
2796 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002797 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Camden Stocker9c051442019-11-06 14:28:43 -08002798
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002799 if (bp_pd_state) {
2800 if (bp_pd_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState == UNCALLED) {
2801 skip |= LogWarning(physicalDevice, kVUID_BestPractices_DisplayPlane_PropertiesNotCalled,
2802 "Potential problem with calling %s() without first retrieving properties from "
2803 "vkGetPhysicalDeviceDisplayPlanePropertiesKHR or vkGetPhysicalDeviceDisplayPlaneProperties2KHR.",
2804 api_name);
2805 }
Camden Stocker9c051442019-11-06 14:28:43 -08002806 }
2807
2808 return skip;
2809}
2810
Camden83a9c372019-08-14 11:41:38 -06002811bool BestPractices::PreCallValidateGetDisplayPlaneSupportedDisplaysKHR(VkPhysicalDevice physicalDevice, uint32_t planeIndex,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002812 uint32_t* pDisplayCount, VkDisplayKHR* pDisplays) const {
Camden83a9c372019-08-14 11:41:38 -06002813 bool skip = false;
2814
Camden Stocker9c051442019-11-06 14:28:43 -08002815 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneSupportedDisplaysKHR");
Camden83a9c372019-08-14 11:41:38 -06002816
Camden Stocker9c051442019-11-06 14:28:43 -08002817 return skip;
2818}
2819
2820bool BestPractices::PreCallValidateGetDisplayPlaneCapabilitiesKHR(VkPhysicalDevice physicalDevice, VkDisplayModeKHR mode,
2821 uint32_t planeIndex,
2822 VkDisplayPlaneCapabilitiesKHR* pCapabilities) const {
2823 bool skip = false;
2824
2825 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilitiesKHR");
2826
2827 return skip;
2828}
2829
2830bool BestPractices::PreCallValidateGetDisplayPlaneCapabilities2KHR(VkPhysicalDevice physicalDevice,
2831 const VkDisplayPlaneInfo2KHR* pDisplayPlaneInfo,
2832 VkDisplayPlaneCapabilities2KHR* pCapabilities) const {
2833 bool skip = false;
2834
2835 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilities2KHR");
Camden83a9c372019-08-14 11:41:38 -06002836
2837 return skip;
2838}
Camden05de2d42019-08-19 10:23:56 -06002839
2840bool BestPractices::PreCallValidateGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain, uint32_t* pSwapchainImageCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002841 VkImage* pSwapchainImages) const {
Camden05de2d42019-08-19 10:23:56 -06002842 bool skip = false;
2843
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002844 auto swapchain_state = Get<bp_state::Swapchain>(swapchain);
Camden05de2d42019-08-19 10:23:56 -06002845
Nathaniel Cesario39152e62021-07-02 13:04:16 -06002846 if (swapchain_state && pSwapchainImages) {
Camden05de2d42019-08-19 10:23:56 -06002847 // Compare the preliminary value of *pSwapchainImageCount with the value this time:
Nathaniel Cesario39152e62021-07-02 13:04:16 -06002848 if (swapchain_state->vkGetSwapchainImagesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002849 skip |=
2850 LogWarning(device, kVUID_Core_Swapchain_PriorCount,
2851 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImageCount; but no prior positive value has "
2852 "been seen for pSwapchainImages.");
Camden05de2d42019-08-19 10:23:56 -06002853 }
Camden05de2d42019-08-19 10:23:56 -06002854
Nathaniel Cesario4ce98382021-05-28 11:33:20 -06002855 if (*pSwapchainImageCount > swapchain_state->get_swapchain_image_count) {
2856 skip |= LogWarning(
2857 device, kVUID_BestPractices_Swapchain_InvalidCount,
2858 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImages, and with pSwapchainImageCount set to a "
Nadav Gevaf0808442021-05-21 13:51:25 -04002859 "value (%" PRId32 ") that is greater than the value (%" PRId32 ") that was returned when pSwapchainImages was NULL.",
Nathaniel Cesario4ce98382021-05-28 11:33:20 -06002860 *pSwapchainImageCount, swapchain_state->get_swapchain_image_count);
2861 }
2862 }
2863
Camden05de2d42019-08-19 10:23:56 -06002864 return skip;
2865}
2866
2867// Common function to handle validation for GetPhysicalDeviceQueueFamilyProperties & 2KHR version
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002868bool BestPractices::ValidateCommonGetPhysicalDeviceQueueFamilyProperties(const PHYSICAL_DEVICE_STATE* bp_pd_state,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002869 uint32_t requested_queue_family_property_count,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002870 const CALL_STATE call_state,
2871 const char* caller_name) const {
Camden05de2d42019-08-19 10:23:56 -06002872 bool skip = false;
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002873 // Verify that for each physical device, this command is called first with NULL pQueueFamilyProperties in order to get count
2874 if (UNCALLED == call_state) {
2875 skip |= LogWarning(
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002876 bp_pd_state->Handle(), kVUID_Core_DevLimit_MissingQueryCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002877 "%s is called with non-NULL pQueueFamilyProperties before obtaining pQueueFamilyPropertyCount. It is "
2878 "recommended "
2879 "to first call %s with NULL pQueueFamilyProperties in order to obtain the maximal pQueueFamilyPropertyCount.",
2880 caller_name, caller_name);
2881 // Then verify that pCount that is passed in on second call matches what was returned
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002882 } else if (bp_pd_state->queue_family_known_count != requested_queue_family_property_count) {
2883 skip |= LogWarning(bp_pd_state->Handle(), kVUID_Core_DevLimit_CountMismatch,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002884 "%s is called with non-NULL pQueueFamilyProperties and pQueueFamilyPropertyCount value %" PRIu32
2885 ", but the largest previously returned pQueueFamilyPropertyCount for this physicalDevice is %" PRIu32
2886 ". It is recommended to instead receive all the properties by calling %s with "
2887 "pQueueFamilyPropertyCount that was "
2888 "previously obtained by calling %s with NULL pQueueFamilyProperties.",
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002889 caller_name, requested_queue_family_property_count, bp_pd_state->queue_family_known_count, caller_name,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002890 caller_name);
Camden05de2d42019-08-19 10:23:56 -06002891 }
2892
2893 return skip;
2894}
2895
Jeff Bolz5c801d12019-10-09 10:38:45 -05002896bool BestPractices::PreCallValidateBindAccelerationStructureMemoryNV(
2897 VkDevice device, uint32_t bindInfoCount, const VkBindAccelerationStructureMemoryInfoNV* pBindInfos) const {
Camden Stocker82510582019-09-03 14:00:16 -06002898 bool skip = false;
2899
2900 for (uint32_t i = 0; i < bindInfoCount; i++) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07002901 auto as_state = Get<ACCELERATION_STRUCTURE_STATE>(pBindInfos[i].accelerationStructure);
Camden Stocker82510582019-09-03 14:00:16 -06002902 if (!as_state->memory_requirements_checked) {
2903 // There's not an explicit requirement in the spec to call vkGetImageMemoryRequirements() prior to calling
2904 // BindAccelerationStructureMemoryNV but it's implied in that memory being bound must conform with
2905 // VkAccelerationStructureMemoryRequirementsInfoNV from vkGetAccelerationStructureMemoryRequirementsNV
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002906 skip |= LogWarning(
2907 device, kVUID_BestPractices_BindAccelNV_NoMemReqQuery,
Camden Stocker82510582019-09-03 14:00:16 -06002908 "vkBindAccelerationStructureMemoryNV(): "
2909 "Binding memory to %s but vkGetAccelerationStructureMemoryRequirementsNV() has not been called on that structure.",
2910 report_data->FormatHandle(pBindInfos[i].accelerationStructure).c_str());
2911 }
2912 }
2913
2914 return skip;
2915}
2916
Camden05de2d42019-08-19 10:23:56 -06002917bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
2918 uint32_t* pQueueFamilyPropertyCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002919 VkQueueFamilyProperties* pQueueFamilyProperties) const {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002920 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002921 if (pQueueFamilyProperties && bp_pd_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002922 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(bp_pd_state.get(), *pQueueFamilyPropertyCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002923 bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
2924 "vkGetPhysicalDeviceQueueFamilyProperties()");
2925 }
2926 return false;
Camden05de2d42019-08-19 10:23:56 -06002927}
2928
Mike Schuchardt2df08912020-12-15 16:28:09 -08002929bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
2930 uint32_t* pQueueFamilyPropertyCount,
2931 VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002932 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002933 if (pQueueFamilyProperties && bp_pd_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002934 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(bp_pd_state.get(), *pQueueFamilyPropertyCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002935 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
2936 "vkGetPhysicalDeviceQueueFamilyProperties2()");
2937 }
2938 return false;
Camden05de2d42019-08-19 10:23:56 -06002939}
2940
Jeff Bolz5c801d12019-10-09 10:38:45 -05002941bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2KHR(
Mike Schuchardt2df08912020-12-15 16:28:09 -08002942 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount, VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002943 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002944 if (pQueueFamilyProperties && bp_pd_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002945 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(bp_pd_state.get(), *pQueueFamilyPropertyCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002946 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
2947 "vkGetPhysicalDeviceQueueFamilyProperties2KHR()");
2948 }
2949 return false;
Camden05de2d42019-08-19 10:23:56 -06002950}
2951
2952bool BestPractices::PreCallValidateGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
2953 uint32_t* pSurfaceFormatCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002954 VkSurfaceFormatKHR* pSurfaceFormats) const {
Camden05de2d42019-08-19 10:23:56 -06002955 if (!pSurfaceFormats) return false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002956 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002957 const auto& call_state = bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState;
Camden05de2d42019-08-19 10:23:56 -06002958 bool skip = false;
2959 if (call_state == UNCALLED) {
2960 // Since we haven't recorded a preliminary value of *pSurfaceFormatCount, that likely means that the application didn't
2961 // previously call this function with a NULL value of pSurfaceFormats:
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002962 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_MustQueryCount,
2963 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount; but no prior "
2964 "positive value has been seen for pSurfaceFormats.");
Camden05de2d42019-08-19 10:23:56 -06002965 } else {
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06002966 if (*pSurfaceFormatCount > bp_pd_state->surface_formats_count) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002967 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_CountMismatch,
2968 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount, and with "
2969 "pSurfaceFormats set to a value (%u) that is greater than the value (%u) that was returned "
2970 "when pSurfaceFormatCount was NULL.",
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06002971 *pSurfaceFormatCount, bp_pd_state->surface_formats_count);
Camden05de2d42019-08-19 10:23:56 -06002972 }
2973 }
2974 return skip;
2975}
Camden Stocker23cc47d2019-09-03 14:53:57 -06002976
2977bool BestPractices::PreCallValidateQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002978 VkFence fence) const {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002979 bool skip = false;
2980
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002981 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
2982 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
Camden Stocker23cc47d2019-09-03 14:53:57 -06002983 // 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 -07002984 layer_data::unordered_set<const IMAGE_STATE*> sparse_images;
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002985 // Track images getting metadata bound by this call in a set, it'll be recorded into the image_state
2986 // in RecordQueueBindSparse.
Jeremy Gebbencbf22862021-03-03 12:01:22 -07002987 layer_data::unordered_set<const IMAGE_STATE*> sparse_images_with_metadata;
Camden Stocker23cc47d2019-09-03 14:53:57 -06002988 // 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 -07002989 for (uint32_t i = 0; i < bind_info.imageBindCount; ++i) {
2990 const auto& image_bind = bind_info.pImageBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04002991 auto image_state = Get<IMAGE_STATE>(image_bind.image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002992 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002993 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002994 }
Jeremy Gebben9f537102021-10-05 16:37:12 -06002995 sparse_images.insert(image_state.get());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002996 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
2997 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
2998 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002999 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003000 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
3001 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003002 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06003003 }
3004 }
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06003005 if (!image_state->memory_requirements_checked[0]) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06003006 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003007 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003008 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
3009 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003010 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06003011 }
3012 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003013 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
3014 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04003015 auto image_state = Get<IMAGE_STATE>(bind_info.pImageOpaqueBinds[i].image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003016 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06003017 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003018 }
Jeremy Gebben9f537102021-10-05 16:37:12 -06003019 sparse_images.insert(image_state.get());
Camden Stocker23cc47d2019-09-03 14:53:57 -06003020 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
3021 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
3022 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003023 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003024 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
3025 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003026 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06003027 }
3028 }
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06003029 if (!image_state->memory_requirements_checked[0]) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06003030 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003031 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003032 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
3033 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003034 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06003035 }
3036 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
3037 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06003038 sparse_images_with_metadata.insert(image_state.get());
Camden Stocker23cc47d2019-09-03 14:53:57 -06003039 }
3040 }
3041 }
3042 for (const auto& sparse_image_state : sparse_images) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05003043 if (sparse_image_state->sparse_metadata_required && !sparse_image_state->sparse_metadata_bound &&
3044 sparse_images_with_metadata.find(sparse_image_state) == sparse_images_with_metadata.end()) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06003045 // Warn if sparse image binding metadata required for image with sparse binding, but metadata not bound
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003046 skip |= LogWarning(sparse_image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003047 "vkQueueBindSparse(): Binding sparse memory to %s which requires a metadata aspect but no "
3048 "binding with VK_SPARSE_MEMORY_BIND_METADATA_BIT set was made.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003049 report_data->FormatHandle(sparse_image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06003050 }
3051 }
3052 }
3053
3054 return skip;
3055}
Jeff Bolz46c0ea02019-10-09 13:06:29 -05003056
Mark Lobodzinski84101d72020-04-24 09:43:48 -06003057void BestPractices::ManualPostCallRecordQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
3058 VkFence fence, VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07003059 if (result != VK_SUCCESS) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07003060 return;
3061 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05003062
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003063 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
3064 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
3065 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
3066 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04003067 auto image_state = Get<IMAGE_STATE>(bind_info.pImageOpaqueBinds[i].image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003068 if (!image_state) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05003069 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003070 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05003071 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
3072 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
3073 image_state->sparse_metadata_bound = true;
3074 }
3075 }
3076 }
3077 }
3078}
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003079
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003080bool BestPractices::ClearAttachmentsIsFullClear(const bp_state::CommandBuffer& cmd, uint32_t rectCount,
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003081 const VkClearRect* pRects) const {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003082 if (cmd.createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003083 // We don't know the accurate render area in a secondary,
3084 // so assume we clear the entire frame buffer.
3085 // This is resolved in CmdExecuteCommands where we can check if the clear is a full clear.
3086 return true;
3087 }
3088
3089 // If we have a rect which covers the entire frame buffer, we have a LOAD_OP_CLEAR-like command.
3090 for (uint32_t i = 0; i < rectCount; i++) {
3091 auto& rect = pRects[i];
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003092 auto& render_area = cmd.activeRenderPassBeginInfo.renderArea;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003093 if (rect.rect.extent.width == render_area.extent.width && rect.rect.extent.height == render_area.extent.height) {
3094 return true;
3095 }
3096 }
3097
3098 return false;
3099}
3100
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003101bool BestPractices::ValidateClearAttachment(const bp_state::CommandBuffer& cmd, uint32_t fb_attachment, uint32_t color_attachment,
3102 VkImageAspectFlags aspects, bool secondary) const {
3103 const RENDER_PASS_STATE* rp = cmd.activeRenderPass.get();
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003104 bool skip = false;
3105
3106 if (!rp || fb_attachment == VK_ATTACHMENT_UNUSED) {
3107 return skip;
3108 }
3109
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003110 const auto& rp_state = cmd.render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003111
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003112 auto attachment_itr =
3113 std::find_if(rp_state.touchesAttachments.begin(), rp_state.touchesAttachments.end(),
3114 [fb_attachment](const bp_state::AttachmentInfo& info) { return info.framebufferAttachment == fb_attachment; });
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003115
3116 // Only report aspects which haven't been touched yet.
3117 VkImageAspectFlags new_aspects = aspects;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003118 if (attachment_itr != rp_state.touchesAttachments.end()) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003119 new_aspects &= ~attachment_itr->aspects;
3120 }
3121
3122 // Warn if this is issued prior to Draw Cmd and clearing the entire attachment
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003123 if (!cmd.hasDrawCmd) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003124 skip |= LogPerformanceWarning(
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003125 cmd.Handle(), kVUID_BestPractices_DrawState_ClearCmdBeforeDraw,
Hans-Kristian Arntzen4ddd6182021-06-18 12:16:33 +02003126 "vkCmdClearAttachments() issued on %s prior to any Draw Cmds in current render pass. It is recommended you "
3127 "use RenderPass LOAD_OP_CLEAR on attachments instead.",
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003128 report_data->FormatHandle(cmd.Handle()).c_str());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003129 }
3130
3131 if ((new_aspects & VK_IMAGE_ASPECT_COLOR_BIT) &&
3132 rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
3133 skip |= LogPerformanceWarning(
3134 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
3135 "%svkCmdClearAttachments() issued on %s for color attachment #%u in this subpass, "
3136 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
3137 "it is more efficient.",
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003138 secondary ? "vkCmdExecuteCommands(): " : "", report_data->FormatHandle(cmd.Handle()).c_str(), color_attachment);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003139 }
3140
3141 if ((new_aspects & VK_IMAGE_ASPECT_DEPTH_BIT) &&
3142 rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003143 skip |=
3144 LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
3145 "%svkCmdClearAttachments() issued on %s for the depth attachment in this subpass, "
3146 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
3147 "it is more efficient.",
3148 secondary ? "vkCmdExecuteCommands(): " : "", report_data->FormatHandle(cmd.Handle()).c_str());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003149 }
3150
3151 if ((new_aspects & VK_IMAGE_ASPECT_STENCIL_BIT) &&
3152 rp->createInfo.pAttachments[fb_attachment].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003153 skip |=
3154 LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
3155 "%svkCmdClearAttachments() issued on %s for the stencil attachment in this subpass, "
3156 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
3157 "it is more efficient.",
3158 secondary ? "vkCmdExecuteCommands(): " : "", report_data->FormatHandle(cmd.Handle()).c_str());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003159 }
3160
3161 return skip;
3162}
3163
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003164bool BestPractices::PreCallValidateCmdClearAttachments(VkCommandBuffer commandBuffer, uint32_t attachmentCount,
Camden Stockerf55721f2019-09-09 11:04:49 -06003165 const VkClearAttachment* pAttachments, uint32_t rectCount,
3166 const VkClearRect* pRects) const {
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003167 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003168 const auto cb_node = GetRead<bp_state::CommandBuffer>(commandBuffer);
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003169 if (!cb_node) return skip;
3170
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003171 if (cb_node->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
3172 // Defer checks to ExecuteCommands.
3173 return skip;
3174 }
3175
3176 // Only care about full clears, partial clears might have legitimate uses.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003177 if (!ClearAttachmentsIsFullClear(*cb_node, rectCount, pRects)) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003178 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003179 }
3180
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003181 // Check for uses of ClearAttachments along with LOAD_OP_LOAD,
3182 // as it can be more efficient to just use LOAD_OP_CLEAR
locke-lunargaecf2152020-05-12 17:15:41 -06003183 const RENDER_PASS_STATE* rp = cb_node->activeRenderPass.get();
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003184 if (rp) {
3185 const auto& subpass = rp->createInfo.pSubpasses[cb_node->activeSubpass];
3186
3187 for (uint32_t i = 0; i < attachmentCount; i++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02003188 const auto& attachment = pAttachments[i];
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003189
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003190 if (attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
3191 uint32_t color_attachment = attachment.colorAttachment;
3192 uint32_t fb_attachment = subpass.pColorAttachments[color_attachment].attachment;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003193 skip |= ValidateClearAttachment(*cb_node, fb_attachment, color_attachment, attachment.aspectMask, false);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003194 }
3195
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003196 if (subpass.pDepthStencilAttachment &&
3197 (attachment.aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT))) {
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003198 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003199 skip |= ValidateClearAttachment(*cb_node, fb_attachment, VK_ATTACHMENT_UNUSED, attachment.aspectMask, false);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003200 }
3201 }
3202 }
3203
Nadav Gevaf0808442021-05-21 13:51:25 -04003204 if (VendorCheckEnabled(kBPVendorAMD)) {
3205 for (uint32_t attachment_idx = 0; attachment_idx < attachmentCount; attachment_idx++) {
3206 if (pAttachments[attachment_idx].aspectMask == VK_IMAGE_ASPECT_COLOR_BIT) {
3207 bool black_check = false;
3208 black_check |= pAttachments[attachment_idx].clearValue.color.float32[0] != 0.0f;
3209 black_check |= pAttachments[attachment_idx].clearValue.color.float32[1] != 0.0f;
3210 black_check |= pAttachments[attachment_idx].clearValue.color.float32[2] != 0.0f;
3211 black_check |= pAttachments[attachment_idx].clearValue.color.float32[3] != 0.0f &&
3212 pAttachments[attachment_idx].clearValue.color.float32[3] != 1.0f;
3213
3214 bool white_check = false;
3215 white_check |= pAttachments[attachment_idx].clearValue.color.float32[0] != 1.0f;
3216 white_check |= pAttachments[attachment_idx].clearValue.color.float32[1] != 1.0f;
3217 white_check |= pAttachments[attachment_idx].clearValue.color.float32[2] != 1.0f;
3218 white_check |= pAttachments[attachment_idx].clearValue.color.float32[3] != 0.0f &&
3219 pAttachments[attachment_idx].clearValue.color.float32[3] != 1.0f;
3220
3221 if (black_check && white_check) {
3222 skip |= LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachment_FastClearValues,
3223 "%s Performance warning: vkCmdClearAttachments() clear value for color attachment %" PRId32 " is not a fast clear value."
3224 "Consider changing to one of the following:"
3225 "RGBA(0, 0, 0, 0) "
3226 "RGBA(0, 0, 0, 1) "
3227 "RGBA(1, 1, 1, 0) "
3228 "RGBA(1, 1, 1, 1)",
3229 VendorSpecificTag(kBPVendorAMD), attachment_idx);
3230 }
3231 } else {
3232 if ((pAttachments[attachment_idx].clearValue.depthStencil.depth != 0 &&
3233 pAttachments[attachment_idx].clearValue.depthStencil.depth != 1) &&
3234 pAttachments[attachment_idx].clearValue.depthStencil.stencil != 0) {
3235 skip |= LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachment_FastClearValues,
3236 "%s Performance warning: vkCmdClearAttachments() clear value for depth/stencil "
3237 "attachment %" PRId32 " is not a fast clear value."
3238 "Consider changing to one of the following:"
3239 "D=0.0f, S=0"
3240 "D=1.0f, S=0",
3241 VendorSpecificTag(kBPVendorAMD), attachment_idx);
3242 }
3243 }
3244 }
3245 }
3246
Camden Stockerf55721f2019-09-09 11:04:49 -06003247 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003248}
Attilio Provenzano02859b22020-02-27 14:17:28 +00003249
3250bool BestPractices::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3251 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3252 const VkImageResolve* pRegions) const {
3253 bool skip = false;
3254
3255 skip |= VendorCheckEnabled(kBPVendorArm) &&
3256 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage_ResolvingImage,
3257 "%s Attempting to use vkCmdResolveImage to resolve a multisampled image. "
3258 "This is a very slow and extremely bandwidth intensive path. "
3259 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
3260 VendorSpecificTag(kBPVendorArm));
3261
3262 return skip;
3263}
3264
Jeff Leger178b1e52020-10-05 12:22:23 -04003265bool BestPractices::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
3266 const VkResolveImageInfo2KHR* pResolveImageInfo) const {
3267 bool skip = false;
3268
3269 skip |= VendorCheckEnabled(kBPVendorArm) &&
3270 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2KHR_ResolvingImage,
3271 "%s Attempting to use vkCmdResolveImage2KHR to resolve a multisampled image. "
3272 "This is a very slow and extremely bandwidth intensive path. "
3273 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
3274 VendorSpecificTag(kBPVendorArm));
3275
3276 return skip;
3277}
3278
Tony-LunarGd36f5f32022-01-20 11:49:59 -07003279bool BestPractices::PreCallValidateCmdResolveImage2(VkCommandBuffer commandBuffer,
3280 const VkResolveImageInfo2* pResolveImageInfo) const {
3281 bool skip = false;
3282
3283 skip |= VendorCheckEnabled(kBPVendorArm) &&
3284 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2_ResolvingImage,
3285 "%s Attempting to use vkCmdResolveImage2 to resolve a multisampled image. "
3286 "This is a very slow and extremely bandwidth intensive path. "
3287 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
3288 VendorSpecificTag(kBPVendorArm));
3289
3290 return skip;
3291}
3292
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003293void BestPractices::PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3294 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3295 const VkImageResolve* pRegions) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003296 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003297 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003298 auto src = Get<bp_state::Image>(srcImage);
3299 auto dst = Get<bp_state::Image>(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003300
3301 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003302 QueueValidateImage(funcs, "vkCmdResolveImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pRegions[i].srcSubresource);
3303 QueueValidateImage(funcs, "vkCmdResolveImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003304 }
3305}
3306
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01003307void BestPractices::PreCallRecordCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
3308 const VkResolveImageInfo2KHR* pResolveImageInfo) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003309 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003310 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003311 auto src = Get<bp_state::Image>(pResolveImageInfo->srcImage);
3312 auto dst = Get<bp_state::Image>(pResolveImageInfo->dstImage);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01003313 uint32_t regionCount = pResolveImageInfo->regionCount;
3314
3315 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003316 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pResolveImageInfo->pRegions[i].srcSubresource);
3317 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pResolveImageInfo->pRegions[i].dstSubresource);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01003318 }
3319}
3320
Tony-LunarGd36f5f32022-01-20 11:49:59 -07003321void BestPractices::PreCallRecordCmdResolveImage2(VkCommandBuffer commandBuffer,
3322 const VkResolveImageInfo2* pResolveImageInfo) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003323 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Tony-LunarGd36f5f32022-01-20 11:49:59 -07003324 auto& funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003325 auto src = Get<bp_state::Image>(pResolveImageInfo->srcImage);
3326 auto dst = Get<bp_state::Image>(pResolveImageInfo->dstImage);
Tony-LunarGd36f5f32022-01-20 11:49:59 -07003327 uint32_t regionCount = pResolveImageInfo->regionCount;
3328
3329 for (uint32_t i = 0; i < regionCount; i++) {
3330 QueueValidateImage(funcs, "vkCmdResolveImage2()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ,
3331 pResolveImageInfo->pRegions[i].srcSubresource);
3332 QueueValidateImage(funcs, "vkCmdResolveImage2()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE,
3333 pResolveImageInfo->pRegions[i].dstSubresource);
3334 }
3335}
3336
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003337void BestPractices::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
3338 const VkClearColorValue* pColor, uint32_t rangeCount,
3339 const VkImageSubresourceRange* pRanges) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003340 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003341 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003342 auto dst = Get<bp_state::Image>(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003343
3344 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003345 QueueValidateImage(funcs, "vkCmdClearColorImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003346 }
3347}
3348
3349void BestPractices::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
3350 const VkClearDepthStencilValue* pDepthStencil, uint32_t rangeCount,
3351 const VkImageSubresourceRange* pRanges) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003352 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003353 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003354 auto dst = Get<bp_state::Image>(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003355
3356 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003357 QueueValidateImage(funcs, "vkCmdClearDepthStencilImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003358 }
3359}
3360
3361void BestPractices::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3362 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3363 const VkImageCopy* pRegions) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003364 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003365 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003366 auto src = Get<bp_state::Image>(srcImage);
3367 auto dst = Get<bp_state::Image>(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003368
3369 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003370 QueueValidateImage(funcs, "vkCmdCopyImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].srcSubresource);
3371 QueueValidateImage(funcs, "vkCmdCopyImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003372 }
3373}
3374
3375void BestPractices::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
3376 VkImageLayout dstImageLayout, uint32_t regionCount,
3377 const VkBufferImageCopy* pRegions) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003378 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003379 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003380 auto dst = Get<bp_state::Image>(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003381
3382 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003383 QueueValidateImage(funcs, "vkCmdCopyBufferToImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003384 }
3385}
3386
3387void BestPractices::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3388 VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy* pRegions) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003389 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003390 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003391 auto src = Get<bp_state::Image>(srcImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003392
3393 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003394 QueueValidateImage(funcs, "vkCmdCopyImageToBuffer()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003395 }
3396}
3397
3398void BestPractices::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3399 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3400 const VkImageBlit* pRegions, VkFilter filter) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003401 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003402 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003403 auto src = Get<bp_state::Image>(srcImage);
3404 auto dst = Get<bp_state::Image>(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003405
3406 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003407 QueueValidateImage(funcs, "vkCmdBlitImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_READ, pRegions[i].srcSubresource);
3408 QueueValidateImage(funcs, "vkCmdBlitImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003409 }
3410}
3411
Attilio Provenzano02859b22020-02-27 14:17:28 +00003412bool BestPractices::PreCallValidateCreateSampler(VkDevice device, const VkSamplerCreateInfo* pCreateInfo,
3413 const VkAllocationCallbacks* pAllocator, VkSampler* pSampler) const {
3414 bool skip = false;
3415
3416 if (VendorCheckEnabled(kBPVendorArm)) {
3417 if ((pCreateInfo->addressModeU != pCreateInfo->addressModeV) || (pCreateInfo->addressModeV != pCreateInfo->addressModeW)) {
3418 skip |= LogPerformanceWarning(
3419 device, kVUID_BestPractices_CreateSampler_DifferentWrappingModes,
3420 "%s Creating a sampler object with wrapping modes which do not match (U = %u, V = %u, W = %u). "
3421 "This may cause reduced performance even if only U (1D image) or U/V wrapping modes (2D "
3422 "image) are actually used. If you need different wrapping modes, disregard this warning.",
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -06003423 VendorSpecificTag(kBPVendorArm), pCreateInfo->addressModeU, pCreateInfo->addressModeV, pCreateInfo->addressModeW);
Attilio Provenzano02859b22020-02-27 14:17:28 +00003424 }
3425
3426 if ((pCreateInfo->minLod != 0.0f) || (pCreateInfo->maxLod < VK_LOD_CLAMP_NONE)) {
3427 skip |= LogPerformanceWarning(
3428 device, kVUID_BestPractices_CreateSampler_LodClamping,
3429 "%s Creating a sampler object with LOD clamping (minLod = %f, maxLod = %f). This may cause reduced performance. "
3430 "Instead of clamping LOD in the sampler, consider using an VkImageView which restricts the mip-levels, set minLod "
3431 "to 0.0, and maxLod to VK_LOD_CLAMP_NONE.",
3432 VendorSpecificTag(kBPVendorArm), pCreateInfo->minLod, pCreateInfo->maxLod);
3433 }
3434
3435 if (pCreateInfo->mipLodBias != 0.0f) {
3436 skip |=
3437 LogPerformanceWarning(device, kVUID_BestPractices_CreateSampler_LodBias,
3438 "%s Creating a sampler object with LOD bias != 0.0 (%f). This will lead to less efficient "
3439 "descriptors being created and may cause reduced performance.",
3440 VendorSpecificTag(kBPVendorArm), pCreateInfo->mipLodBias);
3441 }
3442
3443 if ((pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
3444 pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
3445 pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER) &&
3446 (pCreateInfo->borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK)) {
3447 skip |= LogPerformanceWarning(
3448 device, kVUID_BestPractices_CreateSampler_BorderClampColor,
3449 "%s Creating a sampler object with border clamping and borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK. "
3450 "This will lead to less efficient descriptors being created and may cause reduced performance. "
3451 "If possible, use VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK as the border color.",
3452 VendorSpecificTag(kBPVendorArm));
3453 }
3454
3455 if (pCreateInfo->unnormalizedCoordinates) {
3456 skip |= LogPerformanceWarning(
3457 device, kVUID_BestPractices_CreateSampler_UnnormalizedCoordinates,
3458 "%s Creating a sampler object with unnormalized coordinates. This will lead to less efficient "
3459 "descriptors being created and may cause reduced performance.",
3460 VendorSpecificTag(kBPVendorArm));
3461 }
3462
3463 if (pCreateInfo->anisotropyEnable) {
3464 skip |= LogPerformanceWarning(
3465 device, kVUID_BestPractices_CreateSampler_Anisotropy,
3466 "%s Creating a sampler object with anisotropy. This will lead to less efficient descriptors being created "
3467 "and may cause reduced performance.",
3468 VendorSpecificTag(kBPVendorArm));
3469 }
3470 }
3471
3472 return skip;
3473}
Sam Walls8e77e4f2020-03-16 20:47:40 +00003474
Nadav Gevaf0808442021-05-21 13:51:25 -04003475void BestPractices::PreCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
3476 const VkGraphicsPipelineCreateInfo* pCreateInfos,
3477 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
3478 void* cgpl_state) {
3479 ValidationStateTracker::PreCallRecordCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos, pAllocator,
3480 pPipelines);
3481 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003482 num_pso_ += createInfoCount;
Nadav Gevaf0808442021-05-21 13:51:25 -04003483}
3484
3485bool BestPractices::PreCallValidateUpdateDescriptorSets(VkDevice device, uint32_t descriptorWriteCount,
3486 const VkWriteDescriptorSet* pDescriptorWrites, uint32_t descriptorCopyCount,
3487 const VkCopyDescriptorSet* pDescriptorCopies) const {
3488 bool skip = false;
3489 if (VendorCheckEnabled(kBPVendorAMD)) {
3490 if (descriptorCopyCount > 0) {
3491 skip |= LogPerformanceWarning(device, kVUID_BestPractices_UpdateDescriptors_AvoidCopyingDescriptors,
3492 "%s Performance warning: copying descriptor sets is not recommended",
3493 VendorSpecificTag(kBPVendorAMD));
3494 }
3495 }
3496
3497 return skip;
3498}
3499
3500bool BestPractices::PreCallValidateCreateDescriptorUpdateTemplate(VkDevice device,
3501 const VkDescriptorUpdateTemplateCreateInfo* pCreateInfo,
3502 const VkAllocationCallbacks* pAllocator,
3503 VkDescriptorUpdateTemplate* pDescriptorUpdateTemplate) const {
3504 bool skip = false;
3505 if (VendorCheckEnabled(kBPVendorAMD)) {
3506 skip |= LogPerformanceWarning(device, kVUID_BestPractices_UpdateDescriptors_PreferNonTemplate,
3507 "%s Performance warning: using DescriptorSetWithTemplate is not recommended. Prefer using "
3508 "vkUpdateDescriptorSet instead",
3509 VendorSpecificTag(kBPVendorAMD));
3510 }
3511
3512 return skip;
3513}
3514
3515bool BestPractices::PreCallValidateCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
3516 const VkClearColorValue* pColor, uint32_t rangeCount,
3517 const VkImageSubresourceRange* pRanges) const {
3518 bool skip = false;
3519 if (VendorCheckEnabled(kBPVendorAMD)) {
sfricke-samsungef15e482022-01-26 11:32:49 -08003520 skip |= LogPerformanceWarning(
3521 device, kVUID_BestPractices_ClearAttachment_ClearImage,
Nadav Gevaf0808442021-05-21 13:51:25 -04003522 "%s Performance warning: using vkCmdClearColorImage is not recommended. Prefer using LOAD_OP_CLEAR or "
3523 "vkCmdClearAttachments instead",
3524 VendorSpecificTag(kBPVendorAMD));
3525 }
3526
3527 return skip;
3528}
3529
3530bool BestPractices::PreCallValidateCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image,
3531 VkImageLayout imageLayout,
3532 const VkClearDepthStencilValue* pDepthStencil, uint32_t rangeCount,
3533 const VkImageSubresourceRange* pRanges) const {
3534 bool skip = false;
3535 if (VendorCheckEnabled(kBPVendorAMD)) {
3536 skip |= LogPerformanceWarning(
3537 device, kVUID_BestPractices_ClearAttachment_ClearImage,
3538 "%s Performance warning: using vkCmdClearDepthStencilImage is not recommended. Prefer using LOAD_OP_CLEAR or "
3539 "vkCmdClearAttachments instead",
3540 VendorSpecificTag(kBPVendorAMD));
3541 }
3542
3543 return skip;
3544}
3545
3546bool BestPractices::PreCallValidateCreatePipelineLayout(VkDevice device, const VkPipelineLayoutCreateInfo* pCreateInfo,
3547 const VkAllocationCallbacks* pAllocator,
3548 VkPipelineLayout* pPipelineLayout) const {
3549 bool skip = false;
3550 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003551 uint32_t descriptor_size = enabled_features.core.robustBufferAccess ? 4 : 2;
Nadav Gevaf0808442021-05-21 13:51:25 -04003552 // Descriptor sets cost 1 DWORD each.
3553 // Dynamic buffers cost 2 DWORDs each when robust buffer access is OFF.
3554 // Dynamic buffers cost 4 DWORDs each when robust buffer access is ON.
3555 // Push constants cost 1 DWORD per 4 bytes in the Push constant range.
3556 uint32_t pipeline_size = pCreateInfo->setLayoutCount; // in DWORDS
3557 for (uint32_t i = 0; i < pCreateInfo->setLayoutCount; i++) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06003558 auto descriptor_set_layout_state = Get<cvdescriptorset::DescriptorSetLayout>(pCreateInfo->pSetLayouts[i]);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003559 pipeline_size += descriptor_set_layout_state->GetDynamicDescriptorCount() * descriptor_size;
Nadav Gevaf0808442021-05-21 13:51:25 -04003560 }
3561
3562 for (uint32_t i = 0; i < pCreateInfo->pushConstantRangeCount; i++) {
3563 pipeline_size += pCreateInfo->pPushConstantRanges[i].size / 4;
3564 }
3565
3566 if (pipeline_size > kPipelineLayoutSizeWarningLimitAMD) {
3567 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelinesLayout_KeepLayoutSmall,
3568 "%s Performance warning: pipeline layout size is too large. Prefer smaller pipeline layouts."
3569 "Descriptor sets cost 1 DWORD each. "
3570 "Dynamic buffers cost 2 DWORDs each when robust buffer access is OFF. "
3571 "Dynamic buffers cost 4 DWORDs each when robust buffer access is ON. "
3572 "Push constants cost 1 DWORD per 4 bytes in the Push constant range. ",
3573 VendorSpecificTag(kBPVendorAMD));
3574 }
3575 }
3576
3577 return skip;
3578}
3579
3580bool BestPractices::PreCallValidateCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3581 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3582 const VkImageCopy* pRegions) const {
3583 bool skip = false;
3584 std::stringstream src_image_hex;
3585 std::stringstream dst_image_hex;
3586 src_image_hex << "0x" << std::hex << HandleToUint64(srcImage);
3587 dst_image_hex << "0x" << std::hex << HandleToUint64(dstImage);
3588
3589 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07003590 auto src_state = Get<IMAGE_STATE>(srcImage);
3591 auto dst_state = Get<IMAGE_STATE>(dstImage);
Nadav Gevaf0808442021-05-21 13:51:25 -04003592
3593 if (src_state && dst_state) {
3594 VkImageTiling src_Tiling = src_state->createInfo.tiling;
3595 VkImageTiling dst_Tiling = dst_state->createInfo.tiling;
3596 if (src_Tiling != dst_Tiling && (src_Tiling == VK_IMAGE_TILING_LINEAR || dst_Tiling == VK_IMAGE_TILING_LINEAR)) {
3597 skip |=
3598 LogPerformanceWarning(device, kVUID_BestPractices_vkImage_AvoidImageToImageCopy,
3599 "%s Performance warning: image %s and image %s have differing tilings. Use buffer to "
3600 "image (vkCmdCopyImageToBuffer) "
3601 "and image to buffer (vkCmdCopyBufferToImage) copies instead of image to image "
3602 "copies when converting between linear and optimal images",
3603 VendorSpecificTag(kBPVendorAMD), src_image_hex.str().c_str(), dst_image_hex.str().c_str());
3604 }
3605 }
3606 }
3607
3608 return skip;
3609}
3610
3611bool BestPractices::PreCallValidateCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
3612 VkPipeline pipeline) const {
3613 bool skip = false;
3614
3615 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003616 if (IsPipelineUsedInFrame(pipeline)) {
Nadav Gevaf0808442021-05-21 13:51:25 -04003617 skip |= LogPerformanceWarning(device, kVUID_BestPractices_Pipeline_SortAndBind,
3618 "%s Performance warning: Pipeline %s was bound twice in the frame. Keep pipeline state changes to a minimum,"
3619 "for example, by sorting draw calls by pipeline.",
3620 VendorSpecificTag(kBPVendorAMD), report_data->FormatHandle(pipeline).c_str());
3621 }
3622 }
3623
3624 return skip;
3625}
3626
3627void BestPractices::ManualPostCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
3628 VkFence fence, VkResult result) {
3629 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003630 num_queue_submissions_ += submitCount;
Nadav Gevaf0808442021-05-21 13:51:25 -04003631}
3632
3633bool BestPractices::PreCallValidateQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo) const {
3634 bool skip = false;
3635
3636 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003637 auto num = num_queue_submissions_.load();
3638 if (num > kNumberOfSubmissionWarningLimitAMD) {
3639 skip |= LogPerformanceWarning(device, kVUID_BestPractices_Submission_ReduceNumberOfSubmissions,
3640 "%s Performance warning: command buffers submitted %" PRId32
3641 " times this frame. Submitting command buffers has a CPU "
3642 "and GPU overhead. Submit fewer times to incur less overhead.",
3643 VendorSpecificTag(kBPVendorAMD), num);
Nadav Gevaf0808442021-05-21 13:51:25 -04003644 }
3645 }
3646
3647 return skip;
3648}
3649
3650void BestPractices::PostCallRecordCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
3651 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
3652 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
3653 uint32_t bufferMemoryBarrierCount,
3654 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
3655 uint32_t imageMemoryBarrierCount,
3656 const VkImageMemoryBarrier* pImageMemoryBarriers) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003657 num_barriers_objects_ += (memoryBarrierCount + imageMemoryBarrierCount + bufferMemoryBarrierCount);
Nadav Gevaf0808442021-05-21 13:51:25 -04003658}
3659
3660bool BestPractices::PreCallValidateCreateSemaphore(VkDevice device, const VkSemaphoreCreateInfo* pCreateInfo,
3661 const VkAllocationCallbacks* pAllocator, VkSemaphore* pSemaphore) const {
3662 bool skip = false;
3663 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003664 if (Count<SEMAPHORE_STATE>() > kMaxRecommendedSemaphoreObjectsSizeAMD) {
Nadav Gevaf0808442021-05-21 13:51:25 -04003665 skip |= LogPerformanceWarning(device, kVUID_BestPractices_SyncObjects_HighNumberOfSemaphores,
3666 "%s Performance warning: High number of vkSemaphore objects created."
3667 "Minimize the amount of queue synchronization that is used. "
3668 "Semaphores and fences have overhead. Each fence has a CPU and GPU cost with it.",
3669 VendorSpecificTag(kBPVendorAMD));
3670 }
3671 }
3672
3673 return skip;
3674}
3675
3676bool BestPractices::PreCallValidateCreateFence(VkDevice device, const VkFenceCreateInfo* pCreateInfo,
3677 const VkAllocationCallbacks* pAllocator, VkFence* pFence) const {
3678 bool skip = false;
3679 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003680 if (Count<FENCE_STATE>() > kMaxRecommendedFenceObjectsSizeAMD) {
Nadav Gevaf0808442021-05-21 13:51:25 -04003681 skip |= LogPerformanceWarning(device, kVUID_BestPractices_SyncObjects_HighNumberOfFences,
3682 "%s Performance warning: High number of VkFence objects created."
3683 "Minimize the amount of CPU-GPU synchronization that is used. "
3684 "Semaphores and fences have overhead.Each fence has a CPU and GPU cost with it.",
3685 VendorSpecificTag(kBPVendorAMD));
3686 }
3687 }
3688
3689 return skip;
3690}
3691
Sam Walls8e77e4f2020-03-16 20:47:40 +00003692void BestPractices::PostTransformLRUCacheModel::resize(size_t size) { _entries.resize(size); }
3693
3694bool BestPractices::PostTransformLRUCacheModel::query_cache(uint32_t value) {
3695 // look for a cache hit
3696 auto hit = std::find_if(_entries.begin(), _entries.end(), [value](const CacheEntry& entry) { return entry.value == value; });
3697 if (hit != _entries.end()) {
3698 // mark the cache hit as being most recently used
3699 hit->age = iteration++;
3700 return true;
3701 }
3702
3703 // if there's no cache hit, we need to model the entry being inserted into the cache
3704 CacheEntry new_entry = {value, iteration};
3705 if (iteration < static_cast<uint32_t>(std::distance(_entries.begin(), _entries.end()))) {
3706 // if there is still space left in the cache, use the next available slot
3707 *(_entries.begin() + iteration) = new_entry;
3708 } else {
3709 // otherwise replace the least recently used cache entry
3710 auto lru = std::min_element(_entries.begin(), hit, [](const CacheEntry& a, const CacheEntry& b) { return a.age < b.age; });
3711 *lru = new_entry;
3712 }
3713 iteration++;
3714 return false;
3715}
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003716
3717bool BestPractices::PreCallValidateAcquireNextImageKHR(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout,
3718 VkSemaphore semaphore, VkFence fence, uint32_t* pImageIndex) const {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07003719 auto swapchain_data = Get<SWAPCHAIN_NODE>(swapchain);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003720 bool skip = false;
3721 if (swapchain_data && swapchain_data->images.size() == 0) {
3722 skip |= LogWarning(swapchain, kVUID_Core_DrawState_SwapchainImagesNotFound,
3723 "vkAcquireNextImageKHR: No images found to acquire from. Application probably did not call "
3724 "vkGetSwapchainImagesKHR after swapchain creation.");
3725 }
3726 return skip;
3727}
3728
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003729void BestPractices::CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(CALL_STATE& call_state, bool no_pointer) {
3730 if (no_pointer) {
3731 if (UNCALLED == call_state) {
3732 call_state = QUERY_COUNT;
3733 }
3734 } else { // Save queue family properties
3735 call_state = QUERY_DETAILS;
3736 }
3737}
3738
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003739void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
3740 uint32_t* pQueueFamilyPropertyCount,
3741 VkQueueFamilyProperties* pQueueFamilyProperties) {
3742 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(physicalDevice, pQueueFamilyPropertyCount,
3743 pQueueFamilyProperties);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003744 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003745 if (bp_pd_state) {
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003746 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
3747 nullptr == pQueueFamilyProperties);
3748 }
3749}
3750
3751void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
3752 uint32_t* pQueueFamilyPropertyCount,
3753 VkQueueFamilyProperties2* pQueueFamilyProperties) {
3754 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(physicalDevice, pQueueFamilyPropertyCount,
3755 pQueueFamilyProperties);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003756 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003757 if (bp_pd_state) {
3758 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
3759 nullptr == pQueueFamilyProperties);
3760 }
3761}
3762
3763void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(VkPhysicalDevice physicalDevice,
3764 uint32_t* pQueueFamilyPropertyCount,
3765 VkQueueFamilyProperties2* pQueueFamilyProperties) {
3766 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(physicalDevice, pQueueFamilyPropertyCount,
3767 pQueueFamilyProperties);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003768 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003769 if (bp_pd_state) {
3770 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
3771 nullptr == pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003772 }
3773}
3774
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003775void BestPractices::PostCallRecordGetPhysicalDeviceFeatures(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures* pFeatures) {
3776 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures(physicalDevice, pFeatures);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003777 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003778 if (bp_pd_state) {
3779 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3780 }
3781}
3782
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003783void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2(VkPhysicalDevice physicalDevice,
3784 VkPhysicalDeviceFeatures2* pFeatures) {
3785 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2(physicalDevice, pFeatures);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003786 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003787 if (bp_pd_state) {
3788 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3789 }
3790}
3791
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003792void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2KHR(VkPhysicalDevice physicalDevice,
3793 VkPhysicalDeviceFeatures2* pFeatures) {
3794 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2KHR(physicalDevice, pFeatures);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003795 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003796 if (bp_pd_state) {
3797 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3798 }
3799}
3800
3801void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilitiesKHR(VkPhysicalDevice physicalDevice,
3802 VkSurfaceKHR surface,
3803 VkSurfaceCapabilitiesKHR* pSurfaceCapabilities,
3804 VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003805 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003806 if (bp_pd_state) {
3807 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3808 }
3809}
3810
3811void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2KHR(
3812 VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
3813 VkSurfaceCapabilities2KHR* pSurfaceCapabilities, VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003814 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003815 if (bp_pd_state) {
3816 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3817 }
3818}
3819
3820void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2EXT(VkPhysicalDevice physicalDevice,
3821 VkSurfaceKHR surface,
3822 VkSurfaceCapabilities2EXT* pSurfaceCapabilities,
3823 VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003824 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003825 if (bp_pd_state) {
3826 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3827 }
3828}
3829
3830void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice physicalDevice,
3831 VkSurfaceKHR surface, uint32_t* pPresentModeCount,
3832 VkPresentModeKHR* pPresentModes, VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003833 auto bp_pd_data = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003834 if (bp_pd_data) {
3835 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfacePresentModesKHRState;
3836
3837 if (*pPresentModeCount) {
3838 if (call_state < QUERY_COUNT) {
3839 call_state = QUERY_COUNT;
3840 }
3841 }
3842 if (pPresentModes) {
3843 if (call_state < QUERY_DETAILS) {
3844 call_state = QUERY_DETAILS;
3845 }
3846 }
3847 }
3848}
3849
3850void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
3851 uint32_t* pSurfaceFormatCount,
3852 VkSurfaceFormatKHR* pSurfaceFormats, VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003853 auto bp_pd_data = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003854 if (bp_pd_data) {
3855 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState;
3856
3857 if (*pSurfaceFormatCount) {
3858 if (call_state < QUERY_COUNT) {
3859 call_state = QUERY_COUNT;
3860 }
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06003861 bp_pd_data->surface_formats_count = *pSurfaceFormatCount;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003862 }
3863 if (pSurfaceFormats) {
3864 if (call_state < QUERY_DETAILS) {
3865 call_state = QUERY_DETAILS;
3866 }
3867 }
3868 }
3869}
3870
3871void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormats2KHR(VkPhysicalDevice physicalDevice,
3872 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
3873 uint32_t* pSurfaceFormatCount,
3874 VkSurfaceFormat2KHR* pSurfaceFormats, VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003875 auto bp_pd_data = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003876 if (bp_pd_data) {
3877 if (*pSurfaceFormatCount) {
3878 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_COUNT) {
3879 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_COUNT;
3880 }
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06003881 bp_pd_data->surface_formats_count = *pSurfaceFormatCount;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003882 }
3883 if (pSurfaceFormats) {
3884 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_DETAILS) {
3885 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_DETAILS;
3886 }
3887 }
3888 }
3889}
3890
3891void BestPractices::ManualPostCallRecordGetPhysicalDeviceDisplayPlanePropertiesKHR(VkPhysicalDevice physicalDevice,
3892 uint32_t* pPropertyCount,
3893 VkDisplayPlanePropertiesKHR* pProperties,
3894 VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003895 auto bp_pd_data = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003896 if (bp_pd_data) {
3897 if (*pPropertyCount) {
3898 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_COUNT) {
3899 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_COUNT;
3900 }
3901 }
3902 if (pProperties) {
3903 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_DETAILS) {
3904 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_DETAILS;
3905 }
3906 }
3907 }
3908}
3909
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003910void BestPractices::ManualPostCallRecordGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain,
3911 uint32_t* pSwapchainImageCount, VkImage* pSwapchainImages,
3912 VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003913 auto swapchain_state = Get<bp_state::Swapchain>(swapchain);
Nathaniel Cesario39152e62021-07-02 13:04:16 -06003914 if (swapchain_state && (pSwapchainImages || *pSwapchainImageCount)) {
3915 if (swapchain_state->vkGetSwapchainImagesKHRState < QUERY_DETAILS) {
3916 swapchain_state->vkGetSwapchainImagesKHRState = QUERY_DETAILS;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003917 }
3918 }
3919}
3920
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003921void BestPractices::PreCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits, VkFence fence) {
3922 ValidationStateTracker::PreCallRecordQueueSubmit(queue, submitCount, pSubmits, fence);
3923
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06003924 auto queue_state = Get<QUEUE_STATE>(queue);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003925 for (uint32_t submit = 0; submit < submitCount; submit++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02003926 const auto& submit_info = pSubmits[submit];
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003927 for (uint32_t cb_index = 0; cb_index < submit_info.commandBufferCount; cb_index++) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003928 auto cb = GetWrite<bp_state::CommandBuffer>(submit_info.pCommandBuffers[cb_index]);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003929 for (auto &func : cb->queue_submit_functions) {
Jeremy Gebbene5361dd2021-11-18 14:23:56 -07003930 func(*this, *queue_state, *cb);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003931 }
3932 }
3933 }
3934}