blob: 62409e0ce27cc0348ab8a1c5704e302b9ae882f2 [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
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -070040const std::map<BPVendorFlagBits, VendorSpecificInfo> kVendorInfo = {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060041 {kBPVendorArm, {vendor_specific_arm, "Arm"}},
Nadav Geva41c12a22021-05-21 13:14:05 -040042 {kBPVendorAMD, {vendor_specific_amd, "AMD"}},
Attilio Provenzano19d6a982020-02-27 12:41:41 +000043};
44
Hannes Harnisch607d1d92021-07-10 18:44:56 +020045const SpecialUseVUIDs kSpecialUseInstanceVUIDs {
46 kVUID_BestPractices_CreateInstance_SpecialUseExtension_CADSupport,
47 kVUID_BestPractices_CreateInstance_SpecialUseExtension_D3DEmulation,
48 kVUID_BestPractices_CreateInstance_SpecialUseExtension_DevTools,
49 kVUID_BestPractices_CreateInstance_SpecialUseExtension_Debugging,
50 kVUID_BestPractices_CreateInstance_SpecialUseExtension_GLEmulation,
51};
52
53const SpecialUseVUIDs kSpecialUseDeviceVUIDs {
54 kVUID_BestPractices_CreateDevice_SpecialUseExtension_CADSupport,
55 kVUID_BestPractices_CreateDevice_SpecialUseExtension_D3DEmulation,
56 kVUID_BestPractices_CreateDevice_SpecialUseExtension_DevTools,
57 kVUID_BestPractices_CreateDevice_SpecialUseExtension_Debugging,
58 kVUID_BestPractices_CreateDevice_SpecialUseExtension_GLEmulation,
59};
60
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -060061std::shared_ptr<CMD_BUFFER_STATE> BestPractices::CreateCmdBufferState(VkCommandBuffer cb,
62 const VkCommandBufferAllocateInfo* pCreateInfo,
Jeremy Gebbencd7fa282021-10-27 10:25:32 -060063 const COMMAND_POOL_STATE* pool) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -060064 return std::static_pointer_cast<CMD_BUFFER_STATE>(std::make_shared<CMD_BUFFER_STATE_BP>(this, cb, pCreateInfo, pool));
65}
66
67CMD_BUFFER_STATE_BP::CMD_BUFFER_STATE_BP(BestPractices* bp, VkCommandBuffer cb, const VkCommandBufferAllocateInfo* pCreateInfo,
Jeremy Gebbencd7fa282021-10-27 10:25:32 -060068 const COMMAND_POOL_STATE* pool)
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -060069 : CMD_BUFFER_STATE(bp, cb, pCreateInfo, pool) {}
70
Attilio Provenzano19d6a982020-02-27 12:41:41 +000071bool BestPractices::VendorCheckEnabled(BPVendorFlags vendors) const {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -070072 for (const auto& vendor : kVendorInfo) {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060073 if (vendors & vendor.first && enabled[vendor.second.vendor_id]) {
Attilio Provenzano19d6a982020-02-27 12:41:41 +000074 return true;
75 }
76 }
77 return false;
78}
79
80const char* VendorSpecificTag(BPVendorFlags vendors) {
81 // Cache built vendor tags in a map
Jeremy Gebbencbf22862021-03-03 12:01:22 -070082 static layer_data::unordered_map<BPVendorFlags, std::string> tag_map;
Attilio Provenzano19d6a982020-02-27 12:41:41 +000083
84 auto res = tag_map.find(vendors);
85 if (res == tag_map.end()) {
86 // Build the vendor tag string
87 std::stringstream vendor_tag;
88
89 vendor_tag << "[";
90 bool first_vendor = true;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -070091 for (const auto& vendor : kVendorInfo) {
Attilio Provenzano19d6a982020-02-27 12:41:41 +000092 if (vendors & vendor.first) {
93 if (!first_vendor) {
94 vendor_tag << ", ";
95 }
96 vendor_tag << vendor.second.name;
97 first_vendor = false;
98 }
99 }
100 vendor_tag << "]";
101
102 tag_map[vendors] = vendor_tag.str();
103 res = tag_map.find(vendors);
104 }
105
106 return res->second.c_str();
107}
108
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700109const char* DepReasonToString(ExtDeprecationReason reason) {
110 switch (reason) {
111 case kExtPromoted:
112 return "promoted to";
113 break;
114 case kExtObsoleted:
115 return "obsoleted by";
116 break;
117 case kExtDeprecated:
118 return "deprecated by";
119 break;
120 default:
121 return "";
122 break;
123 }
124}
125
126bool BestPractices::ValidateDeprecatedExtensions(const char* api_name, const char* extension_name, uint32_t version,
127 const char* vuid) const {
128 bool skip = false;
129 auto dep_info_it = deprecated_extensions.find(extension_name);
130 if (dep_info_it != deprecated_extensions.end()) {
131 auto dep_info = dep_info_it->second;
Mark Lobodzinski6a149702020-05-14 12:21:34 -0600132 if (((dep_info.target.compare("VK_VERSION_1_1") == 0) && (version >= VK_API_VERSION_1_1)) ||
Tony-LunarGc30b59f2022-02-15 11:02:36 -0700133 ((dep_info.target.compare("VK_VERSION_1_2") == 0) && (version >= VK_API_VERSION_1_2)) ||
134 ((dep_info.target.compare("VK_VERSION_1_3") == 0) && (version >= VK_API_VERSION_1_3))) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700135 skip |=
136 LogWarning(instance, vuid, "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
137 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
Mark Lobodzinski6a149702020-05-14 12:21:34 -0600138 } else if (dep_info.target.find("VK_VERSION") == std::string::npos) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700139 if (dep_info.target.length() == 0) {
140 skip |= LogWarning(instance, vuid,
141 "%s(): Attempting to enable deprecated extension %s, but this extension has been deprecated "
142 "without replacement.",
143 api_name, extension_name);
144 } else {
145 skip |= LogWarning(instance, vuid,
146 "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
147 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
148 }
149 }
150 }
151 return skip;
152}
153
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200154bool BestPractices::ValidateSpecialUseExtensions(const char* api_name, const char* extension_name, const SpecialUseVUIDs& special_use_vuids) const
155{
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700156 bool skip = false;
157 auto dep_info_it = special_use_extensions.find(extension_name);
158
159 if (dep_info_it != special_use_extensions.end()) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200160 const char* const format = "%s(): Attempting to enable extension %s, but this extension is intended to support %s "
161 "and it is strongly recommended that it be otherwise avoided.";
162 auto& special_uses = dep_info_it->second;
sfricke-samsungef15e482022-01-26 11:32:49 -0800163
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700164 if (special_uses.find("cadsupport") != std::string::npos) {
sfricke-samsungef15e482022-01-26 11:32:49 -0800165 skip |= LogWarning(instance, special_use_vuids.cadsupport, format, api_name, extension_name,
166 "specialized functionality used by CAD/CAM applications");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700167 }
168 if (special_uses.find("d3demulation") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200169 skip |= LogWarning(instance, special_use_vuids.d3demulation, format, api_name, extension_name,
170 "D3D emulation layers, and applications ported from D3D, by adding functionality specific to D3D");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700171 }
172 if (special_uses.find("devtools") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200173 skip |= LogWarning(instance, special_use_vuids.devtools, format, api_name, extension_name,
174 "developer tools such as capture-replay libraries");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700175 }
176 if (special_uses.find("debugging") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200177 skip |= LogWarning(instance, special_use_vuids.debugging, format, api_name, extension_name,
178 "use by applications when debugging");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700179 }
180 if (special_uses.find("glemulation") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200181 skip |= LogWarning(instance, special_use_vuids.glemulation, format, api_name, extension_name,
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700182 "OpenGL and/or OpenGL ES emulation layers, and applications ported from those APIs, by adding functionality "
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200183 "specific to those APIs");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700184 }
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700185 }
186 return skip;
187}
188
Nadav Gevaf0808442021-05-21 13:51:25 -0400189void BestPractices::InitDeviceValidationObject(bool add_obj, ValidationObject* inst_obj, ValidationObject* dev_obj) {
190 if (add_obj) {
191 ValidationStateTracker::InitDeviceValidationObject(add_obj, inst_obj, dev_obj);
192 }
193}
194
195
Camden5b184be2019-08-13 07:50:19 -0600196bool BestPractices::PreCallValidateCreateInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500197 VkInstance* pInstance) const {
Camden5b184be2019-08-13 07:50:19 -0600198 bool skip = false;
199
200 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
201 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kDeviceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800202 skip |= LogWarning(instance, kVUID_BestPractices_CreateInstance_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700203 "vkCreateInstance(): Attempting to enable Device Extension %s at CreateInstance time.",
204 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600205 }
Mark Lobodzinski17d8dc62020-06-03 08:48:58 -0600206 uint32_t specified_version =
207 (pCreateInfo->pApplicationInfo ? pCreateInfo->pApplicationInfo->apiVersion : VK_API_VERSION_1_0);
208 skip |= ValidateDeprecatedExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i], specified_version,
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700209 kVUID_BestPractices_CreateInstance_DeprecatedExtension);
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200210 skip |= ValidateSpecialUseExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i], kSpecialUseInstanceVUIDs);
Camden5b184be2019-08-13 07:50:19 -0600211 }
212
213 return skip;
214}
215
Camden5b184be2019-08-13 07:50:19 -0600216bool BestPractices::PreCallValidateCreateDevice(VkPhysicalDevice physicalDevice, const VkDeviceCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500217 const VkAllocationCallbacks* pAllocator, VkDevice* pDevice) const {
Camden5b184be2019-08-13 07:50:19 -0600218 bool skip = false;
219
220 // get API version of physical device passed when creating device.
221 VkPhysicalDeviceProperties physical_device_properties{};
222 DispatchGetPhysicalDeviceProperties(physicalDevice, &physical_device_properties);
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500223 auto device_api_version = physical_device_properties.apiVersion;
Camden5b184be2019-08-13 07:50:19 -0600224
225 // check api versions and warn if instance api Version is higher than version on device.
Jeremy Gebben404f6ac2021-10-28 12:33:28 -0600226 if (api_version > device_api_version) {
227 std::string inst_api_name = StringAPIVersion(api_version);
Mark Lobodzinski60880782020-08-11 08:02:07 -0600228 std::string dev_api_name = StringAPIVersion(device_api_version);
Camden5b184be2019-08-13 07:50:19 -0600229
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700230 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_API_Mismatch,
231 "vkCreateDevice(): API Version of current instance, %s is higher than API Version on device, %s",
232 inst_api_name.c_str(), dev_api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -0600233 }
234
235 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
236 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kInstanceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800237 skip |= LogWarning(instance, kVUID_BestPractices_CreateDevice_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700238 "vkCreateDevice(): Attempting to enable Instance Extension %s at CreateDevice time.",
239 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600240 }
Jeremy Gebben404f6ac2021-10-28 12:33:28 -0600241 skip |= ValidateDeprecatedExtensions("CreateDevice", pCreateInfo->ppEnabledExtensionNames[i], api_version,
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700242 kVUID_BestPractices_CreateDevice_DeprecatedExtension);
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200243 skip |= ValidateSpecialUseExtensions("CreateDevice", pCreateInfo->ppEnabledExtensionNames[i], kSpecialUseDeviceVUIDs);
Camden5b184be2019-08-13 07:50:19 -0600244 }
245
Jeremy Gebben78684b12022-02-23 17:31:56 -0700246 const auto bp_pd_state = Get<PHYSICAL_DEVICE_STATE_BP>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600247 if ((bp_pd_state->vkGetPhysicalDeviceFeaturesState == UNCALLED) && (pCreateInfo->pEnabledFeatures != NULL)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700248 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_PDFeaturesNotCalled,
249 "vkCreateDevice() called before getting physical device features from vkGetPhysicalDeviceFeatures().");
Camden83a9c372019-08-14 11:41:38 -0600250 }
251
Nadav Gevaf0808442021-05-21 13:51:25 -0400252 if ((VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorAMD)) && (pCreateInfo->pEnabledFeatures != nullptr) &&
Szilard Papp7d2c7952020-06-22 14:38:13 +0100253 (pCreateInfo->pEnabledFeatures->robustBufferAccess == VK_TRUE)) {
254 skip |= LogPerformanceWarning(
255 device, kVUID_BestPractices_CreateDevice_RobustBufferAccess,
Nadav Gevaf0808442021-05-21 13:51:25 -0400256 "%s %s vkCreateDevice() called with enabled robustBufferAccess. Use robustBufferAccess as a debugging tool during "
Szilard Papp7d2c7952020-06-22 14:38:13 +0100257 "development. Enabling it causes loss in performance for accesses to uniform buffers and shader storage "
258 "buffers. Disable robustBufferAccess in release builds. Only leave it enabled if the application use-case "
259 "requires the additional level of reliability due to the use of unverified user-supplied draw parameters.",
Nadav Gevaf0808442021-05-21 13:51:25 -0400260 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorAMD));
Szilard Papp7d2c7952020-06-22 14:38:13 +0100261 }
262
Camden5b184be2019-08-13 07:50:19 -0600263 return skip;
264}
265
266bool BestPractices::PreCallValidateCreateBuffer(VkDevice device, const VkBufferCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500267 const VkAllocationCallbacks* pAllocator, VkBuffer* pBuffer) const {
Camden5b184be2019-08-13 07:50:19 -0600268 bool skip = false;
269
270 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700271 std::stringstream buffer_hex;
272 buffer_hex << "0x" << std::hex << HandleToUint64(pBuffer);
Camden5b184be2019-08-13 07:50:19 -0600273
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700274 skip |= LogWarning(
275 device, kVUID_BestPractices_SharingModeExclusive,
276 "Warning: Buffer (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
277 "(queueFamilyIndexCount of %" PRIu32 ").",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700278 buffer_hex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600279 }
280
281 return skip;
282}
283
284bool BestPractices::PreCallValidateCreateImage(VkDevice device, const VkImageCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500285 const VkAllocationCallbacks* pAllocator, VkImage* pImage) const {
Camden5b184be2019-08-13 07:50:19 -0600286 bool skip = false;
287
288 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700289 std::stringstream image_hex;
290 image_hex << "0x" << std::hex << HandleToUint64(pImage);
Camden5b184be2019-08-13 07:50:19 -0600291
292 skip |=
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700293 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
294 "Warning: Image (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
295 "(queueFamilyIndexCount of %" PRIu32 ").",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700296 image_hex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600297 }
298
Attilio Provenzano02859b22020-02-27 14:17:28 +0000299 if (VendorCheckEnabled(kBPVendorArm)) {
300 if (pCreateInfo->samples > kMaxEfficientSamplesArm) {
301 skip |= LogPerformanceWarning(
302 device, kVUID_BestPractices_CreateImage_TooLargeSampleCount,
303 "%s vkCreateImage(): Trying to create an image with %u samples. "
304 "The hardware revision may not have full throughput for framebuffers with more than %u samples.",
305 VendorSpecificTag(kBPVendorArm), static_cast<uint32_t>(pCreateInfo->samples), kMaxEfficientSamplesArm);
306 }
307
308 if (pCreateInfo->samples > VK_SAMPLE_COUNT_1_BIT && !(pCreateInfo->usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT)) {
309 skip |= LogPerformanceWarning(
310 device, kVUID_BestPractices_CreateImage_NonTransientMSImage,
311 "%s vkCreateImage(): Trying to create a multisampled image, but createInfo.usage did not have "
312 "VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. Multisampled images may be resolved on-chip, "
313 "and do not need to be backed by physical storage. "
314 "TRANSIENT_ATTACHMENT allows tiled GPUs to not back the multisampled image with physical memory.",
315 VendorSpecificTag(kBPVendorArm));
316 }
317 }
318
Nadav Gevaf0808442021-05-21 13:51:25 -0400319 if (VendorCheckEnabled(kBPVendorAMD)) {
320 std::stringstream image_hex;
321 image_hex << "0x" << std::hex << HandleToUint64(pImage);
322
323 if ((pCreateInfo->usage & (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) &&
324 (pCreateInfo->sharingMode == VK_SHARING_MODE_CONCURRENT)) {
325 skip |= LogPerformanceWarning(device,
326 kVUID_BestPractices_vkImage_AvoidConcurrentRenderTargets,
327 "%s Performance warning: image (%s) is created as a render target with VK_SHARING_MODE_CONCURRENT. "
328 "Using a SHARING_MODE_CONCURRENT "
329 "is not recommended with color and depth targets",
330 VendorSpecificTag(kBPVendorAMD), image_hex.str().c_str());
331 }
332
333 if ((pCreateInfo->usage &
334 (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) &&
335 (pCreateInfo->flags & VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT)) {
336 skip |= LogPerformanceWarning(device, kVUID_BestPractices_vkImage_DontUseMutableRenderTargets,
337 "%s Performance warning: image (%s) is created as a render target with VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT. "
338 "Using a MUTABLE_FORMAT is not recommended with color, depth, and storage targets",
339 VendorSpecificTag(kBPVendorAMD), image_hex.str().c_str());
340 }
341
342 if ((pCreateInfo->usage & (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) &&
343 (pCreateInfo->usage & VK_IMAGE_USAGE_STORAGE_BIT)) {
344 skip |= LogPerformanceWarning(device, kVUID_BestPractices_vkImage_DontUseStorageRenderTargets,
345 "%s Performance warning: image (%s) is created as a render target with VK_IMAGE_USAGE_STORAGE_BIT. Using a "
346 "VK_IMAGE_USAGE_STORAGE_BIT is not recommended with color and depth targets",
347 VendorSpecificTag(kBPVendorAMD), image_hex.str().c_str());
348 }
349 }
350
Camden5b184be2019-08-13 07:50:19 -0600351 return skip;
352}
353
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +0100354void BestPractices::PreCallRecordDestroyImage(VkDevice device, VkImage image, const VkAllocationCallbacks *pAllocator) {
355 ValidationStateTracker::PreCallRecordDestroyImage(device, image, pAllocator);
356 ReleaseImageUsageState(image);
357}
358
Hans-Kristian Arntzen92664eb2021-03-29 12:19:48 +0200359void BestPractices::PreCallRecordDestroySwapchainKHR(VkDevice device, VkSwapchainKHR swapchain, const VkAllocationCallbacks* pAllocator) {
Tony-LunarG299187b2021-05-28 09:29:12 -0600360 if (VK_NULL_HANDLE != swapchain) {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -0600361 auto chain = Get<SWAPCHAIN_NODE>(swapchain);
Tony-LunarG299187b2021-05-28 09:29:12 -0600362 for (auto& image : chain->images) {
363 if (image.image_state) {
364 ReleaseImageUsageState(image.image_state->image());
365 }
366 }
Hans-Kristian Arntzen92664eb2021-03-29 12:19:48 +0200367 }
368 ValidationStateTracker::PreCallRecordDestroySwapchainKHR(device, swapchain, pAllocator);
369}
370
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +0100371IMAGE_STATE_BP* BestPractices::GetImageUsageState(VkImage vk_image) {
372 auto itr = imageUsageMap.find(vk_image);
373 if (itr != imageUsageMap.end()) {
374 return &itr->second;
375 } else {
376 auto& state = imageUsageMap[vk_image];
Jeremy Gebbenb20a8242021-11-05 15:14:43 -0600377 auto image = Get<IMAGE_STATE>(vk_image);
Jeremy Gebben9f537102021-10-05 16:37:12 -0600378 state.image = image.get();
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +0100379 state.usages.resize(image->createInfo.arrayLayers);
380 for (auto& mips : state.usages) {
381 mips.resize(image->createInfo.mipLevels, IMAGE_SUBRESOURCE_USAGE_BP::UNDEFINED);
382 }
383 return &state;
384 }
385}
386
387void BestPractices::ReleaseImageUsageState(VkImage image) {
388 auto itr = imageUsageMap.find(image);
389 if (itr != imageUsageMap.end()) {
390 imageUsageMap.erase(itr);
391 }
392}
393
Camden5b184be2019-08-13 07:50:19 -0600394bool BestPractices::PreCallValidateCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500395 const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain) const {
Camden5b184be2019-08-13 07:50:19 -0600396 bool skip = false;
397
Jeremy Gebben383b9a32021-09-08 16:31:33 -0600398 const auto* bp_pd_state = GetPhysicalDeviceState();
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600399 if (bp_pd_state) {
400 if (bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState == UNCALLED) {
401 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
402 "vkCreateSwapchainKHR() called before getting surface capabilities from "
403 "vkGetPhysicalDeviceSurfaceCapabilitiesKHR().");
404 }
Camden83a9c372019-08-14 11:41:38 -0600405
Shannon McPherson73e58c82021-03-05 17:14:26 -0700406 if ((pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR) &&
407 (bp_pd_state->vkGetPhysicalDeviceSurfacePresentModesKHRState != QUERY_DETAILS)) {
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600408 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
409 "vkCreateSwapchainKHR() called before getting surface present mode(s) from "
410 "vkGetPhysicalDeviceSurfacePresentModesKHR().");
411 }
Camden83a9c372019-08-14 11:41:38 -0600412
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600413 if (bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState != QUERY_DETAILS) {
414 skip |= LogWarning(
415 device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
416 "vkCreateSwapchainKHR() called before getting surface format(s) from vkGetPhysicalDeviceSurfaceFormatsKHR().");
417 }
Camden83a9c372019-08-14 11:41:38 -0600418 }
419
Camden5b184be2019-08-13 07:50:19 -0600420 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700421 skip |=
422 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
Mark Lobodzinski019f4e32020-04-13 11:01:35 -0600423 "Warning: A Swapchain is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while "
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700424 "specifying multiple queues (queueFamilyIndexCount of %" PRIu32 ").",
425 pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600426 }
427
Szilard Papp48a6da32020-06-10 14:41:59 +0100428 if (pCreateInfo->minImageCount == 2) {
429 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) {
595 const auto& pool_handle = pAllocateInfo->descriptorPool;
596 auto iter = descriptor_pool_freed_count.find(pool_handle);
597 // if the number of freed sets > 0, it implies they could be recycled instead if desirable
598 // this warning is specific to Arm
599 if (VendorCheckEnabled(kBPVendorArm) && iter != descriptor_pool_freed_count.end() && iter->second > 0) {
600 skip |= LogPerformanceWarning(
601 device, kVUID_BestPractices_AllocateDescriptorSets_SuboptimalReuse,
602 "%s Descriptor set memory was allocated via vkAllocateDescriptorSets() for sets which were previously freed in the "
603 "same logical device. On some drivers or architectures it may be most optimal to re-use existing descriptor sets.",
604 VendorSpecificTag(kBPVendorArm));
605 }
606 }
607
608 return skip;
609}
610
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600611void BestPractices::ManualPostCallRecordAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
612 VkDescriptorSet* pDescriptorSets, VkResult result, void* ads_state) {
Sam Wallse746d522020-03-16 21:20:23 +0000613 if (result == VK_SUCCESS) {
614 // find the free count for the pool we allocated into
615 auto iter = descriptor_pool_freed_count.find(pAllocateInfo->descriptorPool);
616 if (iter != descriptor_pool_freed_count.end()) {
617 // we record successful allocations by subtracting the allocation count from the last recorded free count
618 const auto alloc_count = pAllocateInfo->descriptorSetCount;
619 // clamp the unsigned subtraction to the range [0, last_free_count]
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700620 if (iter->second > alloc_count) {
Sam Wallse746d522020-03-16 21:20:23 +0000621 iter->second -= alloc_count;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700622 } else {
Sam Wallse746d522020-03-16 21:20:23 +0000623 iter->second = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700624 }
Sam Wallse746d522020-03-16 21:20:23 +0000625 }
626 }
627}
628
629void BestPractices::PostCallRecordFreeDescriptorSets(VkDevice device, VkDescriptorPool descriptorPool, uint32_t descriptorSetCount,
630 const VkDescriptorSet* pDescriptorSets, VkResult result) {
631 ValidationStateTracker::PostCallRecordFreeDescriptorSets(device, descriptorPool, descriptorSetCount, pDescriptorSets, result);
632 if (result == VK_SUCCESS) {
633 // we want to track frees because we're interested in suggesting re-use
634 auto iter = descriptor_pool_freed_count.find(descriptorPool);
635 if (iter == descriptor_pool_freed_count.end()) {
Jeremy Gebbencbf22862021-03-03 12:01:22 -0700636 descriptor_pool_freed_count.emplace(descriptorPool, descriptorSetCount);
Sam Wallse746d522020-03-16 21:20:23 +0000637 } else {
638 iter->second += descriptorSetCount;
639 }
640 }
641}
642
Camden5b184be2019-08-13 07:50:19 -0600643bool BestPractices::PreCallValidateAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500644 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory) const {
Camden5b184be2019-08-13 07:50:19 -0600645 bool skip = false;
646
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500647 if (num_mem_objects + 1 > kMemoryObjectWarningLimit) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700648 skip |= LogPerformanceWarning(device, kVUID_BestPractices_AllocateMemory_TooManyObjects,
649 "Performance Warning: This app has > %" PRIu32 " memory objects.", kMemoryObjectWarningLimit);
Camden5b184be2019-08-13 07:50:19 -0600650 }
651
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000652 if (pAllocateInfo->allocationSize < kMinDeviceAllocationSize) {
653 skip |= LogPerformanceWarning(
654 device, kVUID_BestPractices_AllocateMemory_SmallAllocation,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600655 "vkAllocateMemory(): Allocating a VkDeviceMemory of size %" PRIu64 ". This is a very small allocation (current "
656 "threshold is %" PRIu64 " bytes). "
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000657 "You should make large allocations and sub-allocate from one large VkDeviceMemory.",
658 pAllocateInfo->allocationSize, kMinDeviceAllocationSize);
659 }
660
Camden83a9c372019-08-14 11:41:38 -0600661 // TODO: Insert get check for GetPhysicalDeviceMemoryProperties once the state is tracked in the StateTracker
662
663 return skip;
664}
665
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600666void BestPractices::ManualPostCallRecordAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
667 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory,
668 VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700669 if (result != VK_SUCCESS) {
670 static std::vector<VkResult> error_codes = {VK_ERROR_OUT_OF_HOST_MEMORY, VK_ERROR_OUT_OF_DEVICE_MEMORY,
671 VK_ERROR_TOO_MANY_OBJECTS, VK_ERROR_INVALID_EXTERNAL_HANDLE,
Mike Schuchardt2df08912020-12-15 16:28:09 -0800672 VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS};
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700673 static std::vector<VkResult> success_codes = {};
Nathaniel Cesariodb3f43f2021-05-12 09:08:23 -0600674 ValidateReturnCodes("vkAllocateMemory", result, error_codes, success_codes);
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700675 return;
676 }
677 num_mem_objects++;
678}
Camden Stocker9738af92019-10-16 13:54:03 -0700679
Mark Lobodzinskide15e582020-04-29 08:06:00 -0600680void BestPractices::ValidateReturnCodes(const char* api_name, VkResult result, const std::vector<VkResult>& error_codes,
681 const std::vector<VkResult>& success_codes) const {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700682 auto error = std::find(error_codes.begin(), error_codes.end(), result);
683 if (error != error_codes.end()) {
Gareth Webb586c46b2021-01-13 11:17:22 +0000684 static const std::vector<VkResult> common_failure_codes = {VK_ERROR_OUT_OF_DATE_KHR,
685 VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT};
686
687 auto common_failure = std::find(common_failure_codes.begin(), common_failure_codes.end(), result);
688 if (common_failure != common_failure_codes.end()) {
689 LogInfo(instance, kVUID_BestPractices_Failure_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
690 } else {
691 LogWarning(instance, kVUID_BestPractices_Error_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
692 }
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700693 return;
694 }
695 auto success = std::find(success_codes.begin(), success_codes.end(), result);
696 if (success != success_codes.end()) {
Mark Lobodzinskie7215152020-05-11 08:21:23 -0600697 LogInfo(instance, kVUID_BestPractices_NonSuccess_Result, "%s(): Returned non-success return code %s.", api_name,
698 string_VkResult(result));
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500699 }
700}
701
Jeff Bolz5c801d12019-10-09 10:38:45 -0500702bool BestPractices::PreCallValidateFreeMemory(VkDevice device, VkDeviceMemory memory,
703 const VkAllocationCallbacks* pAllocator) const {
Mark Lobodzinski91e50bf2020-01-14 09:55:11 -0700704 if (memory == VK_NULL_HANDLE) return false;
Camden83a9c372019-08-14 11:41:38 -0600705 bool skip = false;
706
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700707 auto mem_info = Get<DEVICE_MEMORY_STATE>(memory);
Camden83a9c372019-08-14 11:41:38 -0600708
Jeremy Gebben610d3a62022-01-01 12:53:17 -0700709 for (const auto& item : mem_info->ObjectBindings()) {
710 const auto& obj = item.first;
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600711 LogObjectList objlist(device);
712 objlist.add(obj);
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -0600713 objlist.add(mem_info->mem());
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600714 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 -0600715 report_data->FormatHandle(obj).c_str(), report_data->FormatHandle(mem_info->mem()).c_str());
Camden83a9c372019-08-14 11:41:38 -0600716 }
717
Camden5b184be2019-08-13 07:50:19 -0600718 return skip;
719}
720
721void BestPractices::PreCallRecordFreeMemory(VkDevice device, VkDeviceMemory memory, const VkAllocationCallbacks* pAllocator) {
Mark Lobodzinski97484d62020-03-03 11:57:41 -0700722 ValidationStateTracker::PreCallRecordFreeMemory(device, memory, pAllocator);
Camden5b184be2019-08-13 07:50:19 -0600723 if (memory != VK_NULL_HANDLE) {
724 num_mem_objects--;
725 }
726}
727
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000728bool BestPractices::ValidateBindBufferMemory(VkBuffer buffer, VkDeviceMemory memory, const char* api_name) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600729 bool skip = false;
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700730 auto buffer_state = Get<BUFFER_STATE>(buffer);
Camden Stockerb603cc82019-09-03 10:09:02 -0600731
sfricke-samsunge2441192019-11-06 14:07:57 -0800732 if (!buffer_state->memory_requirements_checked && !buffer_state->external_memory_handle) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700733 skip |= LogWarning(device, kVUID_BestPractices_BufferMemReqNotCalled,
734 "%s: Binding memory to %s but vkGetBufferMemoryRequirements() has not been called on that buffer.",
735 api_name, report_data->FormatHandle(buffer).c_str());
Camden Stockerb603cc82019-09-03 10:09:02 -0600736 }
737
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700738 auto mem_state = Get<DEVICE_MEMORY_STATE>(memory);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000739
AndreyVK_D3D0416a332021-11-02 23:22:28 +0300740 if (mem_state && mem_state->alloc_info.allocationSize == buffer_state->createInfo.size &&
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000741 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
742 skip |= LogPerformanceWarning(
743 device, kVUID_BestPractices_SmallDedicatedAllocation,
744 "%s: Trying to bind %s to a memory block which is fully consumed by the buffer. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600745 "The required size of the allocation is %" PRIu64 ", but smaller buffers like this should be sub-allocated from "
746 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000747 api_name, report_data->FormatHandle(buffer).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
748 }
749
Camden Stockerb603cc82019-09-03 10:09:02 -0600750 return skip;
751}
752
753bool BestPractices::PreCallValidateBindBufferMemory(VkDevice device, VkBuffer buffer, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500754 VkDeviceSize memoryOffset) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600755 bool skip = false;
756 const char* api_name = "BindBufferMemory()";
757
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000758 skip |= ValidateBindBufferMemory(buffer, memory, api_name);
Camden Stockerb603cc82019-09-03 10:09:02 -0600759
760 return skip;
761}
762
763bool BestPractices::PreCallValidateBindBufferMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500764 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600765 char api_name[64];
766 bool skip = false;
767
768 for (uint32_t i = 0; i < bindInfoCount; i++) {
769 sprintf(api_name, "vkBindBufferMemory2() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000770 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600771 }
772
773 return skip;
774}
Camden Stockerb603cc82019-09-03 10:09:02 -0600775
776bool BestPractices::PreCallValidateBindBufferMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500777 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600778 char api_name[64];
779 bool skip = false;
Camden Stockerb603cc82019-09-03 10:09:02 -0600780
Camden Stocker8b798ab2019-09-03 10:33:28 -0600781 for (uint32_t i = 0; i < bindInfoCount; i++) {
782 sprintf(api_name, "vkBindBufferMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000783 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600784 }
785
786 return skip;
787}
788
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000789bool BestPractices::ValidateBindImageMemory(VkImage image, VkDeviceMemory memory, const char* api_name) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600790 bool skip = false;
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700791 auto image_state = Get<IMAGE_STATE>(image);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600792
sfricke-samsung71bc6572020-04-29 15:49:43 -0700793 if (image_state->disjoint == false) {
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600794 if (!image_state->memory_requirements_checked[0] && !image_state->external_memory_handle) {
sfricke-samsungd7ea5de2020-04-08 09:19:18 -0700795 skip |= LogWarning(device, kVUID_BestPractices_ImageMemReqNotCalled,
796 "%s: Binding memory to %s but vkGetImageMemoryRequirements() has not been called on that image.",
797 api_name, report_data->FormatHandle(image).c_str());
798 }
799 } else {
800 // TODO If binding disjoint image then this needs to check that VkImagePlaneMemoryRequirementsInfo was called for each
801 // plane.
Camden Stocker8b798ab2019-09-03 10:33:28 -0600802 }
803
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700804 auto mem_state = Get<DEVICE_MEMORY_STATE>(memory);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000805
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600806 if (mem_state->alloc_info.allocationSize == image_state->requirements[0].size &&
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000807 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
808 skip |= LogPerformanceWarning(
809 device, kVUID_BestPractices_SmallDedicatedAllocation,
810 "%s: Trying to bind %s to a memory block which is fully consumed by the image. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600811 "The required size of the allocation is %" PRIu64 ", but smaller images like this should be sub-allocated from "
812 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000813 api_name, report_data->FormatHandle(image).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
814 }
815
816 // If we're binding memory to a image which was created as TRANSIENT and the image supports LAZY allocation,
817 // make sure this type is actually used.
818 // This warning will only trigger if this layer is run on a platform that supports LAZILY_ALLOCATED_BIT
819 // (i.e.most tile - based renderers)
820 if (image_state->createInfo.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) {
821 bool supports_lazy = false;
822 uint32_t suggested_type = 0;
823
824 for (uint32_t i = 0; i < phys_dev_mem_props.memoryTypeCount; i++) {
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600825 if ((1u << i) & image_state->requirements[0].memoryTypeBits) {
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000826 if (phys_dev_mem_props.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
827 supports_lazy = true;
828 suggested_type = i;
829 break;
830 }
831 }
832 }
833
834 uint32_t allocated_properties = phys_dev_mem_props.memoryTypes[mem_state->alloc_info.memoryTypeIndex].propertyFlags;
835
836 if (supports_lazy && (allocated_properties & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) == 0) {
837 skip |= LogPerformanceWarning(
838 device, kVUID_BestPractices_NonLazyTransientImage,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600839 "%s: Attempting to bind memory type %u to VkImage which was created with TRANSIENT_ATTACHMENT_BIT,"
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000840 "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 -0600841 "%" PRIu64 " bytes of physical memory.",
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600842 api_name, mem_state->alloc_info.memoryTypeIndex, suggested_type, image_state->requirements[0].size);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000843 }
844 }
845
Camden Stocker8b798ab2019-09-03 10:33:28 -0600846 return skip;
847}
848
849bool BestPractices::PreCallValidateBindImageMemory(VkDevice device, VkImage image, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500850 VkDeviceSize memoryOffset) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600851 bool skip = false;
852 const char* api_name = "vkBindImageMemory()";
853
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000854 skip |= ValidateBindImageMemory(image, memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600855
856 return skip;
857}
858
859bool BestPractices::PreCallValidateBindImageMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500860 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600861 char api_name[64];
862 bool skip = false;
863
864 for (uint32_t i = 0; i < bindInfoCount; i++) {
865 sprintf(api_name, "vkBindImageMemory2() pBindInfos[%u]", i);
Mark Lobodzinski1f887d32020-12-30 15:31:33 -0700866 if (!LvlFindInChain<VkBindImageMemorySwapchainInfoKHR>(pBindInfos[i].pNext)) {
Tony-LunarG5e60b852020-04-27 11:27:54 -0600867 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
868 }
Camden Stocker8b798ab2019-09-03 10:33:28 -0600869 }
870
871 return skip;
872}
873
874bool BestPractices::PreCallValidateBindImageMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500875 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600876 char api_name[64];
877 bool skip = false;
878
879 for (uint32_t i = 0; i < bindInfoCount; i++) {
880 sprintf(api_name, "vkBindImageMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000881 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600882 }
883
884 return skip;
885}
Camden83a9c372019-08-14 11:41:38 -0600886
Attilio Provenzano02859b22020-02-27 14:17:28 +0000887static inline bool FormatHasFullThroughputBlendingArm(VkFormat format) {
888 switch (format) {
889 case VK_FORMAT_B10G11R11_UFLOAT_PACK32:
890 case VK_FORMAT_R16_SFLOAT:
891 case VK_FORMAT_R16G16_SFLOAT:
892 case VK_FORMAT_R16G16B16_SFLOAT:
893 case VK_FORMAT_R16G16B16A16_SFLOAT:
894 case VK_FORMAT_R32_SFLOAT:
895 case VK_FORMAT_R32G32_SFLOAT:
896 case VK_FORMAT_R32G32B32_SFLOAT:
897 case VK_FORMAT_R32G32B32A32_SFLOAT:
898 return false;
899
900 default:
901 return true;
902 }
903}
904
905bool BestPractices::ValidateMultisampledBlendingArm(uint32_t createInfoCount,
906 const VkGraphicsPipelineCreateInfo* pCreateInfos) const {
907 bool skip = false;
908
909 for (uint32_t i = 0; i < createInfoCount; i++) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700910 auto create_info = &pCreateInfos[i];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000911
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700912 if (!create_info->pColorBlendState || !create_info->pMultisampleState ||
913 create_info->pMultisampleState->rasterizationSamples == VK_SAMPLE_COUNT_1_BIT ||
914 create_info->pMultisampleState->sampleShadingEnable) {
Attilio Provenzano02859b22020-02-27 14:17:28 +0000915 return skip;
916 }
917
Jeremy Gebbenb20a8242021-11-05 15:14:43 -0600918 auto rp_state = Get<RENDER_PASS_STATE>(create_info->renderPass);
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200919 const auto& subpass = rp_state->createInfo.pSubpasses[create_info->subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000920
Hans-Kristian Arntzenc2742e72021-07-01 14:31:06 +0200921 // According to spec, pColorBlendState must be ignored if subpass does not have color attachments.
922 uint32_t num_color_attachments = std::min(subpass.colorAttachmentCount, create_info->pColorBlendState->attachmentCount);
923
924 for (uint32_t j = 0; j < num_color_attachments; j++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200925 const auto& blend_att = create_info->pColorBlendState->pAttachments[j];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000926 uint32_t att = subpass.pColorAttachments[j].attachment;
927
928 if (att != VK_ATTACHMENT_UNUSED && blend_att.blendEnable && blend_att.colorWriteMask) {
929 if (!FormatHasFullThroughputBlendingArm(rp_state->createInfo.pAttachments[att].format)) {
930 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultisampledBlending,
931 "%s vkCreateGraphicsPipelines() - createInfo #%u: Pipeline is multisampled and "
932 "color attachment #%u makes use "
933 "of a format which cannot be blended at full throughput when using MSAA.",
934 VendorSpecificTag(kBPVendorArm), i, j);
935 }
936 }
937 }
938 }
939
940 return skip;
941}
942
Nadav Gevaf0808442021-05-21 13:51:25 -0400943void BestPractices::ManualPostCallRecordCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
944 const VkComputePipelineCreateInfo* pCreateInfos,
945 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
946 VkResult result, void* pipe_state) {
947 // AMD best practice
948 pipeline_cache = pipelineCache;
949}
950
Camden5b184be2019-08-13 07:50:19 -0600951bool BestPractices::PreCallValidateCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
952 const VkGraphicsPipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -0600953 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500954 void* cgpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -0600955 bool skip = StateTracker::PreCallValidateCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos,
956 pAllocator, pPipelines, cgpl_state_data);
ziga-lunarg08c81582022-03-08 17:33:45 +0100957 if (skip) {
958 return skip;
959 }
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600960 create_graphics_pipeline_api_state* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
Camden5b184be2019-08-13 07:50:19 -0600961
962 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700963 skip |= LogPerformanceWarning(
964 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
965 "Performance Warning: This vkCreateGraphicsPipelines call is creating multiple pipelines but is not using a "
966 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -0600967 }
968
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000969 for (uint32_t i = 0; i < createInfoCount; i++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200970 const auto& create_info = pCreateInfos[i];
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000971
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600972 if (!(cgpl_state->pipe_state[i]->active_shaders & VK_SHADER_STAGE_MESH_BIT_NV)) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200973 const auto& vertex_input = *create_info.pVertexInputState;
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600974 uint32_t count = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700975 for (uint32_t j = 0; j < vertex_input.vertexBindingDescriptionCount; j++) {
976 if (vertex_input.pVertexBindingDescriptions[j].inputRate == VK_VERTEX_INPUT_RATE_INSTANCE) {
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600977 count++;
978 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000979 }
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600980 if (count > kMaxInstancedVertexBuffers) {
981 skip |= LogPerformanceWarning(
982 device, kVUID_BestPractices_CreatePipelines_TooManyInstancedVertexBuffers,
983 "The pipeline is using %u instanced vertex buffers (current limit: %u), but this can be inefficient on the "
984 "GPU. If using instanced vertex attributes prefer interleaving them in a single buffer.",
985 count, kMaxInstancedVertexBuffers);
986 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000987 }
Attilio Provenzano02859b22020-02-27 14:17:28 +0000988
Szilard Pappaaf2da32020-06-22 10:37:35 +0100989 if ((pCreateInfos[i].pRasterizationState->depthBiasEnable) &&
990 (pCreateInfos[i].pRasterizationState->depthBiasConstantFactor == 0.0f) &&
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +0200991 (pCreateInfos[i].pRasterizationState->depthBiasSlopeFactor == 0.0f) &&
992 VendorCheckEnabled(kBPVendorArm)) {
993 skip |= LogPerformanceWarning(
994 device, kVUID_BestPractices_CreatePipelines_DepthBias_Zero,
995 "%s Performance Warning: This vkCreateGraphicsPipelines call is created with depthBiasEnable set to true "
996 "and both depthBiasConstantFactor and depthBiasSlopeFactor are set to 0. This can cause reduced "
997 "efficiency during rasterization. Consider disabling depthBias or increasing either "
998 "depthBiasConstantFactor or depthBiasSlopeFactor.",
999 VendorSpecificTag(kBPVendorArm));
Szilard Pappaaf2da32020-06-22 10:37:35 +01001000 }
1001
Attilio Provenzano02859b22020-02-27 14:17:28 +00001002 skip |= VendorCheckEnabled(kBPVendorArm) && ValidateMultisampledBlendingArm(createInfoCount, pCreateInfos);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001003 }
Nadav Gevaf0808442021-05-21 13:51:25 -04001004 if (VendorCheckEnabled(kBPVendorAMD)) {
1005 if (pipelineCache && pipeline_cache && pipelineCache != pipeline_cache) {
1006 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
1011 if (num_pso > kMaxRecommendedNumberOfPSOAMD) {
1012 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
Hans-Kristian Arntzenb033ab12021-06-16 11:16:59 +02001035void BestPractices::PreCallRecordDestroyPipeline(VkDevice device, VkPipeline pipeline, const VkAllocationCallbacks *pAllocator)
1036{
1037 auto itr = graphicsPipelineCIs.find(pipeline);
1038 if (itr != graphicsPipelineCIs.end()) {
1039 graphicsPipelineCIs.erase(itr);
1040 }
1041 ValidationStateTracker::PreCallRecordDestroyPipeline(device, pipeline, pAllocator);
1042}
1043
Sam Walls0961ec02020-03-31 16:39:15 +01001044void BestPractices::ManualPostCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t count,
1045 const VkGraphicsPipelineCreateInfo* pCreateInfos,
1046 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
1047 VkResult result, void* cgpl_state_data) {
1048 for (size_t i = 0; i < count; i++) {
1049 const auto* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
1050 const VkPipeline pipeline_handle = pPipelines[i];
1051
1052 // record depth stencil state and color blend states for depth pre-pass tracking purposes
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001053 GraphicsPipelineCIs& cis = graphicsPipelineCIs[pipeline_handle];
Sam Walls0961ec02020-03-31 16:39:15 +01001054
Hans-Kristian Arntzen42c0ef52021-06-14 14:46:25 +02001055 auto& create_info = cgpl_state->pCreateInfos[i];
Andrej Redeky0d513072022-02-13 14:38:20 +01001056
1057 if (create_info.renderPass == VK_NULL_HANDLE) {
1058 // TODO: this is necessary to avoid crashing
1059 LogWarning(device, kVUID_BestPractices_DynamicRendering_NotSupported,
1060 "vkCreateGraphicsPipelines: pCreateInfos[%" PRIu32
1061 "].renderPass is VK_NULL_HANDLE, VK_KHR_dynamic_rendering is not supported.\n",
1062 static_cast<uint32_t>(i));
1063 continue;
1064 }
1065
Tony-LunarGf9b894b2022-02-08 15:01:37 -07001066 auto rp = Get<RENDER_PASS_STATE>(create_info.renderPass);
Hans-Kristian Arntzen42c0ef52021-06-14 14:46:25 +02001067
Jeremy Gebben396d06a2021-08-12 11:03:04 -06001068 if (create_info.pColorBlendState) {
Tony-LunarGf9b894b2022-02-08 15:01:37 -07001069 // pColorBlendState is ignored if the pipeline has rasterization disabled or if no color attachments are used
1070 bool uses_color_attachments = false;
1071 for (uint32_t j = 0; j < rp->createInfo.subpassCount; j++) {
1072 uses_color_attachments |= rp->UsesColorAttachment(j);
1073 }
1074 if (uses_color_attachments && !create_info.pRasterizationState->rasterizerDiscardEnable) {
1075 cis.colorBlendStateCI.emplace(create_info.pColorBlendState);
1076 }
Jeremy Gebben396d06a2021-08-12 11:03:04 -06001077 }
1078
1079 if (create_info.pDepthStencilState) {
Tony-LunarGf9b894b2022-02-08 15:01:37 -07001080 // pDepthStencilState is ignored if the pipeline has rasterization disabled or if no depth/stencil attachment is used
1081 bool uses_depth_stencil = false;
1082 for (uint32_t j = 0; j < rp->createInfo.subpassCount; j++) {
1083 uses_depth_stencil |= rp->UsesDepthStencilAttachment(j);
1084 }
1085 if (uses_depth_stencil && !create_info.pRasterizationState->rasterizerDiscardEnable) {
1086 cis.depthStencilStateCI.emplace(create_info.pDepthStencilState);
1087 }
Jeremy Gebben396d06a2021-08-12 11:03:04 -06001088 }
Hans-Kristian Arntzen42c0ef52021-06-14 14:46:25 +02001089 // Record which frame buffer attachments we should consider to be accessed when a draw call is performed.
Hans-Kristian Arntzen42c0ef52021-06-14 14:46:25 +02001090 auto& subpass = rp->createInfo.pSubpasses[create_info.subpass];
1091 cis.accessFramebufferAttachments.clear();
1092
1093 if (cis.colorBlendStateCI) {
Hans-Kristian Arntzenc2742e72021-07-01 14:31:06 +02001094 // According to spec, pColorBlendState must be ignored if subpass does not have color attachments.
1095 uint32_t num_color_attachments = std::min(subpass.colorAttachmentCount, cis.colorBlendStateCI->attachmentCount);
1096 for (uint32_t j = 0; j < num_color_attachments; j++) {
Hans-Kristian Arntzen42c0ef52021-06-14 14:46:25 +02001097 if (cis.colorBlendStateCI->pAttachments[j].colorWriteMask != 0) {
1098 uint32_t attachment = subpass.pColorAttachments[j].attachment;
1099 if (attachment != VK_ATTACHMENT_UNUSED) {
1100 cis.accessFramebufferAttachments.push_back({ attachment, VK_IMAGE_ASPECT_COLOR_BIT });
1101 }
1102 }
1103 }
1104 }
1105
1106 if (cis.depthStencilStateCI && (cis.depthStencilStateCI->depthTestEnable ||
1107 cis.depthStencilStateCI->depthBoundsTestEnable ||
1108 cis.depthStencilStateCI->stencilTestEnable)) {
1109 uint32_t attachment = subpass.pDepthStencilAttachment ?
1110 subpass.pDepthStencilAttachment->attachment :
1111 VK_ATTACHMENT_UNUSED;
1112 if (attachment != VK_ATTACHMENT_UNUSED) {
1113 VkImageAspectFlags aspects = 0;
1114 if (cis.depthStencilStateCI->depthTestEnable || cis.depthStencilStateCI->depthBoundsTestEnable) {
1115 aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
1116 }
1117 if (cis.depthStencilStateCI->stencilTestEnable) {
1118 aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
1119 }
1120 cis.accessFramebufferAttachments.push_back({ attachment, aspects });
1121 }
1122 }
Sam Walls0961ec02020-03-31 16:39:15 +01001123 }
Nadav Gevaf0808442021-05-21 13:51:25 -04001124
1125 // AMD best practice
1126 pipeline_cache = pipelineCache;
Sam Walls0961ec02020-03-31 16:39:15 +01001127}
1128
Camden5b184be2019-08-13 07:50:19 -06001129bool BestPractices::PreCallValidateCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
1130 const VkComputePipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -06001131 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001132 void* ccpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -06001133 bool skip = StateTracker::PreCallValidateCreateComputePipelines(device, pipelineCache, createInfoCount, pCreateInfos,
1134 pAllocator, pPipelines, ccpl_state_data);
Camden5b184be2019-08-13 07:50:19 -06001135
1136 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001137 skip |= LogPerformanceWarning(
1138 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
1139 "Performance Warning: This vkCreateComputePipelines call is creating multiple pipelines but is not using a "
1140 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -06001141 }
1142
Nadav Gevaf0808442021-05-21 13:51:25 -04001143 if (VendorCheckEnabled(kBPVendorAMD)) {
1144 if (pipelineCache && pipeline_cache && pipelineCache != pipeline_cache) {
1145 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
1146 "%s Performance Warning: A second pipeline cache is in use. Consider using only one pipeline cache to "
1147 "improve cache hit rate",
1148 VendorSpecificTag(kBPVendorAMD));
1149 }
1150 }
1151
sfricke-samsung86d055a2022-02-11 14:43:50 -08001152 for (uint32_t i = 0; i < createInfoCount; i++) {
1153 const VkComputePipelineCreateInfo& createInfo = pCreateInfos[i];
1154 if (VendorCheckEnabled(kBPVendorArm)) {
1155 skip |= ValidateCreateComputePipelineArm(createInfo);
1156 }
1157
1158 if (IsExtEnabled(device_extensions.vk_khr_maintenance4)) {
1159 auto module_state = Get<SHADER_MODULE_STATE>(createInfo.stage.module);
1160 for (const auto& builtin : module_state->static_data_.builtin_decoration_list) {
1161 if (builtin.builtin == spv::BuiltInWorkgroupSize) {
1162 skip |= LogWarning(device, kVUID_BestPractices_SpirvDeprecated_WorkgroupSize,
1163 "vkCreateComputePipelines(): pCreateInfos[ %" PRIu32
1164 "] is using the Workgroup built-in which SPIR-V 1.6 deprecated. The VK_KHR_maintenance4 "
1165 "extension exposes a new LocalSizeId execution mode that should be used instead.",
1166 i);
1167 }
1168 }
1169 }
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001170 }
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001171
1172 return skip;
1173}
1174
1175bool BestPractices::ValidateCreateComputePipelineArm(const VkComputePipelineCreateInfo& createInfo) const {
1176 bool skip = false;
sfricke-samsungef15e482022-01-26 11:32:49 -08001177 auto module_state = Get<SHADER_MODULE_STATE>(createInfo.stage.module);
sfricke-samsung8a7341a2021-02-28 07:30:21 -08001178 // Generate warnings about work group sizes based on active resources.
sfricke-samsungef15e482022-01-26 11:32:49 -08001179 auto entrypoint = module_state->FindEntrypoint(createInfo.stage.pName, createInfo.stage.stage);
1180 if (entrypoint == module_state->end()) return false;
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001181
1182 uint32_t x = 1, y = 1, z = 1;
sfricke-samsungef15e482022-01-26 11:32:49 -08001183 module_state->FindLocalSize(entrypoint, x, y, z);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001184
1185 uint32_t thread_count = x * y * z;
1186
1187 // Generate a priori warnings about work group sizes.
1188 if (thread_count > kMaxEfficientWorkGroupThreadCountArm) {
1189 skip |= LogPerformanceWarning(
1190 device, kVUID_BestPractices_CreateComputePipelines_ComputeWorkGroupSize,
1191 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, %u, "
1192 "%u) (%u threads total), has more threads than advised in a single work group. It is advised to use work "
1193 "groups with less than %u threads, especially when using barrier() or shared memory.",
1194 VendorSpecificTag(kBPVendorArm), x, y, z, thread_count, kMaxEfficientWorkGroupThreadCountArm);
1195 }
1196
1197 if (thread_count == 1 || ((x > 1) && (x & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
1198 ((y > 1) && (y & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
1199 ((z > 1) && (z & (kThreadGroupDispatchCountAlignmentArm - 1)))) {
1200 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeThreadGroupAlignment,
1201 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, "
1202 "%u, %u) is not aligned to %u "
1203 "threads. On Arm Mali architectures, not aligning work group sizes to %u may "
1204 "leave threads idle on the shader "
1205 "core.",
1206 VendorSpecificTag(kBPVendorArm), x, y, z, kThreadGroupDispatchCountAlignmentArm,
1207 kThreadGroupDispatchCountAlignmentArm);
1208 }
1209
sfricke-samsungef15e482022-01-26 11:32:49 -08001210 auto accessible_ids = module_state->MarkAccessibleIds(entrypoint);
1211 auto descriptor_uses = module_state->CollectInterfaceByDescriptorSlot(accessible_ids);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001212
1213 unsigned dimensions = 0;
1214 if (x > 1) dimensions++;
1215 if (y > 1) dimensions++;
1216 if (z > 1) dimensions++;
1217 // Here the dimension will really depend on the dispatch grid, but assume it's 1D.
1218 dimensions = std::max(dimensions, 1u);
1219
1220 // If we're accessing images, we almost certainly want to have a 2D workgroup for cache reasons.
1221 // There are some false positives here. We could simply have a shader that does this within a 1D grid,
1222 // or we may have a linearly tiled image, but these cases are quite unlikely in practice.
1223 bool accesses_2d = false;
1224 for (const auto& usage : descriptor_uses) {
sfricke-samsungef15e482022-01-26 11:32:49 -08001225 auto dim = module_state->GetShaderResourceDimensionality(usage.second);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001226 if (dim < 0) continue;
1227 auto spvdim = spv::Dim(dim);
1228 if (spvdim != spv::Dim1D && spvdim != spv::DimBuffer) accesses_2d = true;
1229 }
1230
1231 if (accesses_2d && dimensions < 2) {
1232 LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeSpatialLocality,
1233 "%s vkCreateComputePipelines(): compute shader has work group dimensions (%u, %u, %u), which "
1234 "suggests a 1D dispatch, but the shader is accessing 2D or 3D images. The shader may be "
1235 "exhibiting poor spatial locality with respect to one or more shader resources.",
1236 VendorSpecificTag(kBPVendorArm), x, y, z);
1237 }
1238
Camden5b184be2019-08-13 07:50:19 -06001239 return skip;
1240}
1241
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001242bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags flags) const {
Camden5b184be2019-08-13 07:50:19 -06001243 bool skip = false;
1244
1245 if (flags & VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001246 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1247 "You are using VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001248 } else if (flags & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001249 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1250 "You are using VK_PIPELINE_STAGE_ALL_COMMANDS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001251 }
1252
1253 return skip;
1254}
1255
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001256bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags2KHR flags) const {
1257 bool skip = false;
1258
1259 if (flags & VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR) {
1260 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1261 "You are using VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR when %s is called\n", api_name.c_str());
1262 } else if (flags & VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR) {
1263 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1264 "You are using VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR when %s is called\n", api_name.c_str());
1265 }
1266
1267 return skip;
1268}
1269
1270bool BestPractices::CheckDependencyInfo(const std::string& api_name, const VkDependencyInfoKHR& dep_info) const {
1271 bool skip = false;
1272 auto stage_masks = sync_utils::GetGlobalStageMasks(dep_info);
1273
1274 skip |= CheckPipelineStageFlags(api_name, stage_masks.src);
1275 skip |= CheckPipelineStageFlags(api_name, stage_masks.dst);
1276
1277 return skip;
1278}
1279
Mark Lobodzinski84101d72020-04-24 09:43:48 -06001280void BestPractices::ManualPostCallRecordQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo, VkResult result) {
Mark Lobodzinski9b133c12020-03-10 10:42:56 -06001281 for (uint32_t i = 0; i < pPresentInfo->swapchainCount; ++i) {
1282 auto swapchains_result = pPresentInfo->pResults ? pPresentInfo->pResults[i] : result;
1283 if (swapchains_result == VK_SUBOPTIMAL_KHR) {
1284 LogPerformanceWarning(
1285 pPresentInfo->pSwapchains[i], kVUID_BestPractices_SuboptimalSwapchain,
1286 "vkQueuePresentKHR: %s :VK_SUBOPTIMAL_KHR was returned. VK_SUBOPTIMAL_KHR - Presentation will still succeed, "
1287 "subject to the window resize behavior, but the swapchain is no longer configured optimally for the surface it "
1288 "targets. Applications should query updated surface information and recreate their swapchain at the next "
1289 "convenient opportunity.",
1290 report_data->FormatHandle(pPresentInfo->pSwapchains[i]).c_str());
1291 }
1292 }
Nadav Gevaf0808442021-05-21 13:51:25 -04001293
1294 // AMD best practice
1295 // end-of-frame cleanup
1296 num_queue_submissions = 0;
1297 num_barriers_objects = 0;
1298 pipelines_used_in_frame.clear();
Mark Lobodzinski9b133c12020-03-10 10:42:56 -06001299}
1300
Jeff Bolz5c801d12019-10-09 10:38:45 -05001301bool BestPractices::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
1302 VkFence fence) const {
Camden5b184be2019-08-13 07:50:19 -06001303 bool skip = false;
1304
1305 for (uint32_t submit = 0; submit < submitCount; submit++) {
1306 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreCount; semaphore++) {
1307 skip |= CheckPipelineStageFlags("vkQueueSubmit", pSubmits[submit].pWaitDstStageMask[semaphore]);
1308 }
1309 }
1310
1311 return skip;
1312}
1313
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001314bool BestPractices::PreCallValidateQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR* pSubmits,
1315 VkFence fence) const {
1316 bool skip = false;
1317
1318 for (uint32_t submit = 0; submit < submitCount; submit++) {
1319 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreInfoCount; semaphore++) {
1320 skip |= CheckPipelineStageFlags("vkQueueSubmit2KHR", pSubmits[submit].pWaitSemaphoreInfos[semaphore].stageMask);
1321 }
1322 }
1323
1324 return skip;
1325}
1326
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001327bool BestPractices::PreCallValidateQueueSubmit2(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2* pSubmits,
1328 VkFence fence) const {
1329 bool skip = false;
1330
1331 for (uint32_t submit = 0; submit < submitCount; submit++) {
1332 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreInfoCount; semaphore++) {
1333 skip |= CheckPipelineStageFlags("vkQueueSubmit2", pSubmits[submit].pWaitSemaphoreInfos[semaphore].stageMask);
1334 }
1335 }
1336
1337 return skip;
1338}
1339
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001340bool BestPractices::PreCallValidateCreateCommandPool(VkDevice device, const VkCommandPoolCreateInfo* pCreateInfo,
1341 const VkAllocationCallbacks* pAllocator, VkCommandPool* pCommandPool) const {
1342 bool skip = false;
1343
1344 if (pCreateInfo->flags & VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT) {
1345 skip |= LogPerformanceWarning(
1346 device, kVUID_BestPractices_CreateCommandPool_CommandBufferReset,
1347 "vkCreateCommandPool(): VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT is set. Consider resetting entire "
1348 "pool instead.");
1349 }
1350
1351 return skip;
1352}
1353
1354bool BestPractices::PreCallValidateBeginCommandBuffer(VkCommandBuffer commandBuffer,
1355 const VkCommandBufferBeginInfo* pBeginInfo) const {
1356 bool skip = false;
1357
1358 if (pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT) {
1359 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_SimultaneousUse,
1360 "vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT is set.");
1361 }
1362
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001363 if (!(pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT) && VendorCheckEnabled(kBPVendorArm)) {
1364 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_OneTimeSubmit,
Attilio Provenzano02859b22020-02-27 14:17:28 +00001365 "%s vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT is not set. "
1366 "For best performance on Mali GPUs, consider setting ONE_TIME_SUBMIT by default.",
1367 VendorSpecificTag(kBPVendorArm));
1368 }
1369
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001370 return skip;
1371}
1372
Jeff Bolz5c801d12019-10-09 10:38:45 -05001373bool BestPractices::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001374 bool skip = false;
1375
1376 skip |= CheckPipelineStageFlags("vkCmdSetEvent", stageMask);
1377
1378 return skip;
1379}
1380
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001381bool BestPractices::PreCallValidateCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1382 const VkDependencyInfoKHR* pDependencyInfo) const {
1383 return CheckDependencyInfo("vkCmdSetEvent2KHR", *pDependencyInfo);
1384}
1385
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001386bool BestPractices::PreCallValidateCmdSetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
1387 const VkDependencyInfo* pDependencyInfo) const {
1388 return CheckDependencyInfo("vkCmdSetEvent2", *pDependencyInfo);
1389}
1390
Jeff Bolz5c801d12019-10-09 10:38:45 -05001391bool BestPractices::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
1392 VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001393 bool skip = false;
1394
1395 skip |= CheckPipelineStageFlags("vkCmdResetEvent", stageMask);
1396
1397 return skip;
1398}
1399
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001400bool BestPractices::PreCallValidateCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1401 VkPipelineStageFlags2KHR stageMask) const {
1402 bool skip = false;
1403
1404 skip |= CheckPipelineStageFlags("vkCmdResetEvent2KHR", stageMask);
1405
1406 return skip;
1407}
1408
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001409bool BestPractices::PreCallValidateCmdResetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
1410 VkPipelineStageFlags2 stageMask) const {
1411 bool skip = false;
1412
1413 skip |= CheckPipelineStageFlags("vkCmdResetEvent2", stageMask);
1414
1415 return skip;
1416}
1417
Camden5b184be2019-08-13 07:50:19 -06001418bool BestPractices::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1419 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
1420 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1421 uint32_t bufferMemoryBarrierCount,
1422 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1423 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001424 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001425 bool skip = false;
1426
1427 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", srcStageMask);
1428 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", dstStageMask);
1429
1430 return skip;
1431}
1432
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001433bool BestPractices::PreCallValidateCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1434 const VkDependencyInfoKHR* pDependencyInfos) const {
1435 bool skip = false;
1436 for (uint32_t i = 0; i < eventCount; i++) {
1437 skip = CheckDependencyInfo("vkCmdWaitEvents2KHR", pDependencyInfos[i]);
1438 }
1439
1440 return skip;
1441}
1442
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001443bool BestPractices::PreCallValidateCmdWaitEvents2(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1444 const VkDependencyInfo* pDependencyInfos) const {
1445 bool skip = false;
1446 for (uint32_t i = 0; i < eventCount; i++) {
1447 skip = CheckDependencyInfo("vkCmdWaitEvents2", pDependencyInfos[i]);
1448 }
1449
1450 return skip;
1451}
1452
Camden5b184be2019-08-13 07:50:19 -06001453bool BestPractices::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
1454 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
1455 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1456 uint32_t bufferMemoryBarrierCount,
1457 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1458 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001459 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001460 bool skip = false;
1461
1462 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", srcStageMask);
1463 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", dstStageMask);
1464
Nadav Gevaf0808442021-05-21 13:51:25 -04001465 if (VendorCheckEnabled(kBPVendorAMD)) {
1466 if (num_barriers_objects + imageMemoryBarrierCount + bufferMemoryBarrierCount > kMaxRecommendedBarriersSizeAMD) {
1467 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdBuffer_highBarrierCount,
1468 "%s Performance warning: In this frame, %" PRIu32 " barriers were already submitted. Barriers have a high cost and can "
1469 "stall the GPU. "
1470 "Consider consolidating and re-organizing the frame to use fewer barriers.",
1471 VendorSpecificTag(kBPVendorAMD), num_barriers_objects);
1472 }
1473
1474 std::array<VkImageLayout, 3> read_layouts = {
1475 VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL,
1476 VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
1477 VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
1478 };
1479
1480 for (uint32_t i = 0; i < imageMemoryBarrierCount; i++) {
1481 // read to read barriers
1482 auto found = std::find(read_layouts.begin(), read_layouts.end(), pImageMemoryBarriers[i].oldLayout);
1483 bool old_is_read_layout = found != read_layouts.end();
1484 found = std::find(read_layouts.begin(), read_layouts.end(), pImageMemoryBarriers[i].newLayout);
1485 bool new_is_read_layout = found != read_layouts.end();
1486 if (old_is_read_layout && new_is_read_layout) {
1487 skip |= LogPerformanceWarning(device, kVUID_BestPractices_PipelineBarrier_readToReadBarrier,
1488 "%s Performance warning: Don't issue read-to-read barriers. Get the resource in the right state the first "
1489 "time you use it.",
1490 VendorSpecificTag(kBPVendorAMD));
1491 }
1492
1493 // general with no storage
1494 if (pImageMemoryBarriers[i].newLayout == VK_IMAGE_LAYOUT_GENERAL) {
1495 auto image_state = Get<IMAGE_STATE>(pImageMemoryBarriers[i].image);
1496 if (!(image_state->createInfo.usage & VK_IMAGE_USAGE_STORAGE_BIT)) {
1497 skip |= LogPerformanceWarning(device, kVUID_BestPractices_vkImage_AvoidGeneral,
1498 "%s Performance warning: VK_IMAGE_LAYOUT_GENERAL should only be used with "
1499 "VK_IMAGE_USAGE_STORAGE_BIT images.",
1500 VendorSpecificTag(kBPVendorAMD));
1501 }
1502 }
1503 }
1504 }
1505
Camden5b184be2019-08-13 07:50:19 -06001506 return skip;
1507}
1508
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001509bool BestPractices::PreCallValidateCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer,
1510 const VkDependencyInfoKHR* pDependencyInfo) const {
1511 return CheckDependencyInfo("vkCmdPipelineBarrier2KHR", *pDependencyInfo);
1512}
1513
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001514bool BestPractices::PreCallValidateCmdPipelineBarrier2(VkCommandBuffer commandBuffer,
1515 const VkDependencyInfo* pDependencyInfo) const {
1516 return CheckDependencyInfo("vkCmdPipelineBarrier2", *pDependencyInfo);
1517}
1518
Camden5b184be2019-08-13 07:50:19 -06001519bool BestPractices::PreCallValidateCmdWriteTimestamp(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001520 VkQueryPool queryPool, uint32_t query) const {
Camden5b184be2019-08-13 07:50:19 -06001521 bool skip = false;
1522
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001523 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp", static_cast<VkPipelineStageFlags>(pipelineStage));
1524
1525 return skip;
1526}
1527
1528bool BestPractices::PreCallValidateCmdWriteTimestamp2KHR(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
1529 VkQueryPool queryPool, uint32_t query) const {
1530 bool skip = false;
1531
1532 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp2KHR", pipelineStage);
Camden5b184be2019-08-13 07:50:19 -06001533
1534 return skip;
1535}
1536
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001537bool BestPractices::PreCallValidateCmdWriteTimestamp2(VkCommandBuffer commandBuffer, VkPipelineStageFlags2 pipelineStage,
1538 VkQueryPool queryPool, uint32_t query) const {
1539 bool skip = false;
1540
1541 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp2", pipelineStage);
1542
1543 return skip;
1544}
1545
Sam Walls0961ec02020-03-31 16:39:15 +01001546void BestPractices::PostCallRecordCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
1547 VkPipeline pipeline) {
1548 StateTracker::PostCallRecordCmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
1549
Nadav Gevaf0808442021-05-21 13:51:25 -04001550 // AMD best practice
1551 pipelines_used_in_frame.emplace(pipeline);
1552
Sam Walls0961ec02020-03-31 16:39:15 +01001553 if (pipelineBindPoint == VK_PIPELINE_BIND_POINT_GRAPHICS) {
1554 // check for depth/blend state tracking
1555 auto gp_cis = graphicsPipelineCIs.find(pipeline);
1556 if (gp_cis != graphicsPipelineCIs.end()) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07001557 auto cb_node = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06001558 assert(cb_node);
1559 auto& render_pass_state = cb_node->render_pass_state;
Sam Walls0961ec02020-03-31 16:39:15 +01001560
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001561 render_pass_state.nextDrawTouchesAttachments = gp_cis->second.accessFramebufferAttachments;
1562 render_pass_state.drawTouchAttachments = true;
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02001563
Jeremy Gebben396d06a2021-08-12 11:03:04 -06001564 const auto& blend_state = gp_cis->second.colorBlendStateCI;
1565 const auto& stencil_state = gp_cis->second.depthStencilStateCI;
Sam Walls0961ec02020-03-31 16:39:15 +01001566
1567 if (blend_state) {
1568 // assume the pipeline is depth-only unless any of the attachments have color writes enabled
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001569 render_pass_state.depthOnly = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001570 for (size_t i = 0; i < blend_state->attachmentCount; i++) {
1571 if (blend_state->pAttachments[i].colorWriteMask != 0) {
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001572 render_pass_state.depthOnly = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001573 }
1574 }
1575 }
1576
1577 // check for depth value usage
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001578 render_pass_state.depthEqualComparison = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001579
1580 if (stencil_state && stencil_state->depthTestEnable) {
1581 switch (stencil_state->depthCompareOp) {
1582 case VK_COMPARE_OP_EQUAL:
1583 case VK_COMPARE_OP_GREATER_OR_EQUAL:
1584 case VK_COMPARE_OP_LESS_OR_EQUAL:
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001585 render_pass_state.depthEqualComparison = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001586 break;
1587 default:
1588 break;
1589 }
1590 }
Sam Walls0961ec02020-03-31 16:39:15 +01001591 }
1592 }
1593}
1594
Hans-Kristian Arntzen237663c2021-07-01 14:36:40 +02001595static inline bool RenderPassUsesAttachmentAsResolve(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1596 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
1597 const auto& subpass_info = createInfo.pSubpasses[subpass];
1598 if (subpass_info.pResolveAttachments) {
1599 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1600 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
1601 }
1602 }
1603 }
1604
1605 return false;
1606}
1607
Attilio Provenzano02859b22020-02-27 14:17:28 +00001608static inline bool RenderPassUsesAttachmentOnTile(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1609 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001610 const auto& subpass_info = createInfo.pSubpasses[subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001611
1612 // If an attachment is ever used as a color attachment,
1613 // resolve attachment or depth stencil attachment,
1614 // it needs to exist on tile at some point.
1615
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001616 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1617 if (subpass_info.pColorAttachments[i].attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001618 }
1619
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001620 if (subpass_info.pResolveAttachments) {
1621 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1622 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
1623 }
1624 }
1625
1626 if (subpass_info.pDepthStencilAttachment && subpass_info.pDepthStencilAttachment->attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001627 }
1628
1629 return false;
1630}
1631
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001632static inline bool RenderPassUsesAttachmentAsImageOnly(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1633 if (RenderPassUsesAttachmentOnTile(createInfo, attachment)) {
1634 return false;
1635 }
1636
1637 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001638 const auto& subpassInfo = createInfo.pSubpasses[subpass];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001639
1640 for (uint32_t i = 0; i < subpassInfo.inputAttachmentCount; i++) {
1641 if (subpassInfo.pInputAttachments[i].attachment == attachment) {
1642 return true;
1643 }
1644 }
1645 }
1646
1647 return false;
1648}
1649
Attilio Provenzano02859b22020-02-27 14:17:28 +00001650bool BestPractices::ValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1651 const VkRenderPassBeginInfo* pRenderPassBegin) const {
1652 bool skip = false;
1653
1654 if (!pRenderPassBegin) {
1655 return skip;
1656 }
1657
Gareth Webbdc6549a2021-06-16 03:52:24 +01001658 if (pRenderPassBegin->renderArea.extent.width == 0 || pRenderPassBegin->renderArea.extent.height == 0) {
1659 skip |= LogWarning(device, kVUID_BestPractices_BeginRenderPass_ZeroSizeRenderArea,
1660 "This render pass has a zero-size render area. It cannot write to any attachments, "
1661 "and can only be used for side effects such as layout transitions.");
1662 }
1663
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001664 auto rp_state = Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001665 if (rp_state) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08001666 if (rp_state->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07001667 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
Tony-LunarG767180f2020-04-23 14:03:59 -06001668 if (rpabi) {
1669 skip = ValidateAttachments(rp_state->createInfo.ptr(), rpabi->attachmentCount, rpabi->pAttachments);
1670 }
1671 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001672 // Check if any attachments have LOAD operation on them
1673 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001674 const auto& attachment = rp_state->createInfo.pAttachments[att];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001675
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001676 bool attachment_has_readback = false;
Hans-Kristian Arntzen4afb59b2021-06-18 12:41:36 +02001677 if (!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001678 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001679 }
1680
1681 if (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001682 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001683 }
1684
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001685 bool attachment_needs_readback = false;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001686
1687 // Check if the attachment is actually used in any subpass on-tile
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001688 if (attachment_has_readback && RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1689 attachment_needs_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001690 }
1691
1692 // Using LOAD_OP_LOAD is expensive on tiled GPUs, so flag it as a potential improvement
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001693 if (attachment_needs_readback && VendorCheckEnabled(kBPVendorArm)) {
1694 skip |= LogPerformanceWarning(
1695 device, kVUID_BestPractices_BeginRenderPass_AttachmentNeedsReadback,
1696 "%s Attachment #%u in render pass has begun with VK_ATTACHMENT_LOAD_OP_LOAD.\n"
1697 "Submitting this renderpass will cause the driver to inject a readback of the attachment "
Nadav Gevaf0808442021-05-21 13:51:25 -04001698 "which will copy in total %u pixels (renderArea = "
1699 "{ %" PRId32 ", %" PRId32 ", %" PRIu32", %" PRIu32 " }) to the tile buffer.",
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001700 VendorSpecificTag(kBPVendorArm), att,
1701 pRenderPassBegin->renderArea.extent.width * pRenderPassBegin->renderArea.extent.height,
1702 pRenderPassBegin->renderArea.offset.x, pRenderPassBegin->renderArea.offset.y,
1703 pRenderPassBegin->renderArea.extent.width, pRenderPassBegin->renderArea.extent.height);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001704 }
1705 }
1706 }
1707
1708 return skip;
1709}
1710
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001711void BestPractices::QueueValidateImageView(QueueCallbacks &funcs, const char* function_name,
1712 IMAGE_VIEW_STATE* view, IMAGE_SUBRESOURCE_USAGE_BP usage) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001713 if (view) {
Jeremy Gebbenb4d17012021-07-08 13:18:15 -06001714 QueueValidateImage(funcs, function_name, GetImageUsageState(view->create_info.image), usage,
1715 view->normalized_subresource_range);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001716 }
1717}
1718
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001719void BestPractices::QueueValidateImage(QueueCallbacks &funcs, const char* function_name,
1720 IMAGE_STATE_BP* state, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001721 const VkImageSubresourceRange& subresource_range) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001722 IMAGE_STATE* image = state->image;
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02001723
1724 // If we're viewing a 3D slice, ignore base array layer.
1725 // The entire 3D subresource is accessed as one atomic unit.
1726 const uint32_t base_array_layer = image->createInfo.imageType == VK_IMAGE_TYPE_3D ? 0 : subresource_range.baseArrayLayer;
1727
1728 const uint32_t max_layers = image->createInfo.arrayLayers - base_array_layer;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001729 const uint32_t array_layers = std::min(subresource_range.layerCount, max_layers);
1730 const uint32_t max_levels = image->createInfo.mipLevels - subresource_range.baseMipLevel;
1731 const uint32_t mip_levels = std::min(image->createInfo.mipLevels, max_levels);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001732
1733 for (uint32_t layer = 0; layer < array_layers; layer++) {
1734 for (uint32_t level = 0; level < mip_levels; level++) {
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02001735 QueueValidateImage(funcs, function_name, state, usage, layer + base_array_layer,
1736 level + subresource_range.baseMipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001737 }
1738 }
1739}
1740
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001741void BestPractices::QueueValidateImage(QueueCallbacks &funcs, const char* function_name,
1742 IMAGE_STATE_BP* state, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001743 const VkImageSubresourceLayers& subresource_layers) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001744 IMAGE_STATE* image = state->image;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001745 const uint32_t max_layers = image->createInfo.arrayLayers - subresource_layers.baseArrayLayer;
1746 const uint32_t array_layers = std::min(subresource_layers.layerCount, max_layers);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001747
1748 for (uint32_t layer = 0; layer < array_layers; layer++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001749 QueueValidateImage(funcs, function_name, state, usage, layer + subresource_layers.baseArrayLayer, subresource_layers.mipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001750 }
1751}
1752
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001753void BestPractices::QueueValidateImage(QueueCallbacks &funcs, const char* function_name,
1754 IMAGE_STATE_BP* state, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001755 uint32_t array_layer, uint32_t mip_level) {
Jeremy Gebben7fd238f2022-03-04 10:32:24 -07001756 if (VendorCheckEnabled(kBPVendorArm)) {
1757 funcs.push_back([this, function_name, state, usage, array_layer, mip_level](
1758 const ValidationStateTracker&, const QUEUE_STATE&, const CMD_BUFFER_STATE&) -> bool {
1759 ValidateImageInQueue(function_name, state, usage, array_layer, mip_level);
1760 return false;
1761 });
1762 }
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001763}
1764
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001765void BestPractices::ValidateImageInQueueArm(const char* function_name, IMAGE_STATE* image,
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001766 IMAGE_SUBRESOURCE_USAGE_BP last_usage,
1767 IMAGE_SUBRESOURCE_USAGE_BP usage,
1768 uint32_t array_layer, uint32_t mip_level) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001769 // Swapchain images are implicitly read so clear after store is expected.
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001770 if (usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_CLEARED && last_usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_STORED &&
Jeremy Gebben82e11d52021-07-26 09:19:37 -06001771 !image->IsSwapchainImage()) {
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001772 LogPerformanceWarning(
1773 device, kVUID_BestPractices_RenderPass_RedundantStore,
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001774 "%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 +02001775 "image was used, it was written to with STORE_OP_STORE. "
1776 "Storing to the image is probably redundant in this case, and wastes bandwidth on tile-based "
1777 "architectures.",
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001778 function_name, VendorSpecificTag(kBPVendorArm), array_layer, mip_level);
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001779 } 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 +02001780 LogPerformanceWarning(
1781 device, kVUID_BestPractices_RenderPass_RedundantClear,
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001782 "%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 +02001783 "image was used, it was written to with vkCmdClear*Image(). "
1784 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
1785 "tile-based architectures."
1786 "architectures.",
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001787 function_name, VendorSpecificTag(kBPVendorArm), array_layer, mip_level);
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01001788 } else if (usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE &&
1789 (last_usage == IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE ||
1790 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::CLEARED ||
1791 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE ||
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001792 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE)) {
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01001793 const char *last_cmd = nullptr;
1794 const char *vuid = nullptr;
1795 const char *suggestion = nullptr;
1796
1797 switch (last_usage) {
1798 case IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE:
1799 vuid = kVUID_BestPractices_RenderPass_BlitImage_LoadOpLoad;
1800 last_cmd = "vkCmdBlitImage";
1801 suggestion =
1802 "The blit is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
1803 "Rather than blitting, just render the source image in a fragment shader in this render pass, "
1804 "which avoids the memory roundtrip.";
1805 break;
1806 case IMAGE_SUBRESOURCE_USAGE_BP::CLEARED:
1807 vuid = kVUID_BestPractices_RenderPass_InefficientClear;
1808 last_cmd = "vkCmdClear*Image";
1809 suggestion =
1810 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
1811 "tile-based architectures. "
1812 "Use LOAD_OP_CLEAR instead to clear the image for free.";
1813 break;
1814 case IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE:
1815 vuid = kVUID_BestPractices_RenderPass_CopyImage_LoadOpLoad;
1816 last_cmd = "vkCmdCopy*Image";
1817 suggestion =
1818 "The copy is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
1819 "Rather than copying, 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::RESOLVE_WRITE:
1823 vuid = kVUID_BestPractices_RenderPass_ResolveImage_LoadOpLoad;
1824 last_cmd = "vkCmdResolveImage";
1825 suggestion =
1826 "The resolve is probably redundant in this case, and wastes a lot of bandwidth on tile-based architectures. "
1827 "Rather than resolving, and then loading, try to keep rendering in the same render pass, "
1828 "which avoids the memory roundtrip.";
1829 break;
1830 default:
1831 break;
1832 }
1833
1834 LogPerformanceWarning(
1835 device, vuid,
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001836 "%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 +01001837 "time image was used, it was written to with %s. %s",
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001838 function_name, VendorSpecificTag(kBPVendorArm), array_layer, mip_level, last_cmd, suggestion);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001839 }
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001840}
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001841
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001842void BestPractices::ValidateImageInQueue(const char* function_name, IMAGE_STATE_BP* state,
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001843 IMAGE_SUBRESOURCE_USAGE_BP usage, uint32_t array_layer,
1844 uint32_t mip_level) {
1845 IMAGE_STATE* image = state->image;
1846 IMAGE_SUBRESOURCE_USAGE_BP last_usage = state->usages[array_layer][mip_level];
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001847 state->usages[array_layer][mip_level] = usage;
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001848 if (VendorCheckEnabled(kBPVendorArm)) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001849 ValidateImageInQueueArm(function_name, image, last_usage, usage, array_layer, mip_level);
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001850 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001851}
1852
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06001853void BestPractices::AddDeferredQueueOperations(CMD_BUFFER_STATE_BP* cb) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001854 cb->queue_submit_functions.insert(cb->queue_submit_functions.end(),
Hans-Kristian Arntzenf44df192021-06-14 11:42:08 +02001855 cb->queue_submit_functions_after_render_pass.begin(),
1856 cb->queue_submit_functions_after_render_pass.end());
1857 cb->queue_submit_functions_after_render_pass.clear();
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001858}
1859
1860void BestPractices::PreCallRecordCmdEndRenderPass(VkCommandBuffer commandBuffer) {
1861 ValidationStateTracker::PreCallRecordCmdEndRenderPass(commandBuffer);
Jeremy Gebben78684b12022-02-23 17:31:56 -07001862 auto cb_node = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Jeremy Gebben9f537102021-10-05 16:37:12 -06001863 AddDeferredQueueOperations(cb_node.get());
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001864}
1865
1866void BestPractices::PreCallRecordCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassInfo) {
1867 ValidationStateTracker::PreCallRecordCmdEndRenderPass2(commandBuffer, pSubpassInfo);
Jeremy Gebben78684b12022-02-23 17:31:56 -07001868 auto cb_node = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Jeremy Gebben9f537102021-10-05 16:37:12 -06001869 AddDeferredQueueOperations(cb_node.get());
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001870}
1871
1872void BestPractices::PreCallRecordCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfoKHR *pSubpassInfo) {
1873 ValidationStateTracker::PreCallRecordCmdEndRenderPass2KHR(commandBuffer, pSubpassInfo);
Jeremy Gebben78684b12022-02-23 17:31:56 -07001874 auto cb_node = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Jeremy Gebben9f537102021-10-05 16:37:12 -06001875 AddDeferredQueueOperations(cb_node.get());
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001876}
1877
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02001878void BestPractices::PreCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer,
1879 const VkRenderPassBeginInfo* pRenderPassBegin,
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001880 VkSubpassContents contents) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001881 ValidationStateTracker::PreCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02001882 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1883}
1884
1885void BestPractices::PreCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer,
1886 const VkRenderPassBeginInfo* pRenderPassBegin,
1887 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1888 ValidationStateTracker::PreCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1889 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1890}
1891
1892void BestPractices::PreCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1893 const VkRenderPassBeginInfo* pRenderPassBegin,
1894 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1895 ValidationStateTracker::PreCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1896 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1897}
1898
1899void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001900
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001901 if (!pRenderPassBegin) {
1902 return;
1903 }
1904
Jeremy Gebben78684b12022-02-23 17:31:56 -07001905 auto cb = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001906
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001907 auto rp_state = Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001908 if (rp_state) {
1909 // Check load ops
1910 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001911 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001912
1913 if (!RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att) &&
1914 !RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1915 continue;
1916 }
1917
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001918 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::UNDEFINED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001919
1920 if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) ||
1921 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001922 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02001923 } else if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) ||
1924 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_CLEAR)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001925 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_CLEARED;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02001926 } else if (RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att)) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001927 usage = IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001928 }
1929
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001930 auto framebuffer = Get<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer);
Jeremy Gebben9f537102021-10-05 16:37:12 -06001931 std::shared_ptr<IMAGE_VIEW_STATE> image_view = nullptr;
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001932
Tony-LunarGb3ab3572021-07-02 09:45:17 -06001933 if (framebuffer->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001934 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
1935 if (rpabi) {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001936 image_view = Get<IMAGE_VIEW_STATE>(rpabi->pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001937 }
1938 } else {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001939 image_view = Get<IMAGE_VIEW_STATE>(framebuffer->createInfo.pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001940 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001941
Jeremy Gebben9f537102021-10-05 16:37:12 -06001942 QueueValidateImageView(cb->queue_submit_functions, "vkCmdBeginRenderPass()", image_view.get(), usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001943 }
1944
1945 // Check store ops
1946 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001947 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001948
1949 if (!RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1950 continue;
1951 }
1952
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001953 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_DISCARDED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001954
1955 if ((!FormatIsStencilOnly(attachment.format) && attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE) ||
1956 (FormatHasStencil(attachment.format) && attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001957 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_STORED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001958 }
1959
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001960 auto framebuffer = Get<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001961
Jeremy Gebben9f537102021-10-05 16:37:12 -06001962 std::shared_ptr<IMAGE_VIEW_STATE> image_view;
Tony-LunarGb3ab3572021-07-02 09:45:17 -06001963 if (framebuffer->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001964 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
1965 if (rpabi) {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001966 image_view = Get<IMAGE_VIEW_STATE>(rpabi->pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001967 }
1968 } else {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001969 image_view = Get<IMAGE_VIEW_STATE>(framebuffer->createInfo.pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001970 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001971
Jeremy Gebben9f537102021-10-05 16:37:12 -06001972 QueueValidateImageView(cb->queue_submit_functions_after_render_pass, "vkCmdEndRenderPass()", image_view.get(), usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001973 }
1974 }
1975}
1976
Attilio Provenzano02859b22020-02-27 14:17:28 +00001977bool BestPractices::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1978 VkSubpassContents contents) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001979 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1980 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001981 return skip;
1982}
1983
1984bool BestPractices::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1985 const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08001986 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001987 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1988 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001989 return skip;
1990}
1991
1992bool BestPractices::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08001993 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001994 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1995 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001996 return skip;
1997}
1998
Sam Walls0961ec02020-03-31 16:39:15 +01001999void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
2000 const VkRenderPassBeginInfo* pRenderPassBegin) {
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002001 // Reset the renderpass state
Jeremy Gebben78684b12022-02-23 17:31:56 -07002002 auto cb = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002003 cb->hasDrawCmd = false;
2004 assert(cb);
2005 auto& render_pass_state = cb->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002006 render_pass_state.touchesAttachments.clear();
2007 render_pass_state.earlyClearAttachments.clear();
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002008 render_pass_state.numDrawCallsDepthOnly = 0;
2009 render_pass_state.numDrawCallsDepthEqualCompare = 0;
2010 render_pass_state.colorAttachment = false;
2011 render_pass_state.depthAttachment = false;
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002012 render_pass_state.drawTouchAttachments = true;
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002013 // Don't reset state related to pipeline state.
Sam Walls0961ec02020-03-31 16:39:15 +01002014
Jeremy Gebbenf4449392022-01-28 10:09:10 -07002015 auto rp_state = Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
Sam Walls0961ec02020-03-31 16:39:15 +01002016
2017 // track depth / color attachment usage within the renderpass
2018 for (size_t i = 0; i < rp_state->createInfo.subpassCount; i++) {
2019 // record if depth/color attachments are in use for this renderpass
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002020 if (rp_state->createInfo.pSubpasses[i].pDepthStencilAttachment != nullptr) render_pass_state.depthAttachment = true;
Sam Walls0961ec02020-03-31 16:39:15 +01002021
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002022 if (rp_state->createInfo.pSubpasses[i].colorAttachmentCount > 0) render_pass_state.colorAttachment = true;
Sam Walls0961ec02020-03-31 16:39:15 +01002023 }
2024}
2025
2026void BestPractices::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
2027 VkSubpassContents contents) {
2028 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
2029 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
2030}
2031
2032void BestPractices::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
2033 const VkSubpassBeginInfo* pSubpassBeginInfo) {
2034 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
2035 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
2036}
2037
2038void BestPractices::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
2039 const VkRenderPassBeginInfo* pRenderPassBegin,
2040 const VkSubpassBeginInfo* pSubpassBeginInfo) {
2041 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
2042 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
2043}
2044
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002045// Generic function to handle validation for all CmdDraw* type functions
2046bool BestPractices::ValidateCmdDrawType(VkCommandBuffer cmd_buffer, const char* caller) const {
2047 bool skip = false;
Jeremy Gebben78684b12022-02-23 17:31:56 -07002048 const auto cb_state = Get<CMD_BUFFER_STATE_BP>(cmd_buffer);
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002049 if (cb_state) {
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002050 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
2051 const auto* pipeline_state = cb_state->lastBound[lv_bind_point].pipeline_state;
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002052 const auto& current_vtx_bfr_binding_info = cb_state->current_vertex_buffer_binding_info.vertex_buffer_bindings;
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002053
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002054 // Verify vertex binding
2055 if (pipeline_state->vertex_binding_descriptions_.size() <= 0) {
2056 if ((!current_vtx_bfr_binding_info.empty()) && (!cb_state->vertex_buffer_used)) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002057 skip |= LogPerformanceWarning(cb_state->commandBuffer(), kVUID_BestPractices_DrawState_VtxIndexOutOfBounds,
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07002058 "Vertex buffers are bound to %s but no vertex buffers are attached to %s.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002059 report_data->FormatHandle(cb_state->commandBuffer()).c_str(),
2060 report_data->FormatHandle(pipeline_state->pipeline()).c_str());
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002061 }
2062 }
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002063
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002064 const auto* pipe = cb_state->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002065 if (pipe) {
2066 const auto* rp_state = pipe->rp_state.get();
2067 if (rp_state) {
2068 for (uint32_t i = 0; i < rp_state->createInfo.subpassCount; ++i) {
2069 const auto& subpass = rp_state->createInfo.pSubpasses[i];
Jeremy Gebben11af9792021-08-20 10:20:09 -06002070 const auto& create_info = pipe->create_info.graphics;
2071 const uint32_t depth_stencil_attachment =
2072 GetSubpassDepthStencilAttachmentIndex(create_info.pDepthStencilState, subpass.pDepthStencilAttachment);
2073 if ((depth_stencil_attachment == VK_ATTACHMENT_UNUSED) && create_info.pRasterizationState &&
2074 create_info.pRasterizationState->depthBiasEnable == VK_TRUE) {
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002075 skip |= LogWarning(cb_state->commandBuffer(), kVUID_BestPractices_DepthBiasNoAttachment,
2076 "%s: depthBiasEnable == VK_TRUE without a depth-stencil attachment.", caller);
2077 }
2078 }
2079 }
2080 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002081 }
2082 return skip;
2083}
2084
Sam Walls0961ec02020-03-31 16:39:15 +01002085void BestPractices::RecordCmdDrawType(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07002086 auto cb_node = Get<CMD_BUFFER_STATE_BP>(cmd_buffer);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002087 assert(cb_node);
2088 auto& render_pass_state = cb_node->render_pass_state;
Sam Walls0961ec02020-03-31 16:39:15 +01002089 if (VendorCheckEnabled(kBPVendorArm)) {
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002090 RecordCmdDrawTypeArm(render_pass_state, draw_count, caller);
2091 }
2092
2093 if (render_pass_state.drawTouchAttachments) {
2094 for (auto& touch : render_pass_state.nextDrawTouchesAttachments) {
2095 RecordAttachmentAccess(render_pass_state, touch.framebufferAttachment, touch.aspects);
2096 }
2097 // No need to touch the same attachments over and over.
2098 render_pass_state.drawTouchAttachments = false;
Sam Walls0961ec02020-03-31 16:39:15 +01002099 }
2100}
2101
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002102void BestPractices::RecordCmdDrawTypeArm(RenderPassState& render_pass_state, uint32_t draw_count, const char* caller) {
2103 if (draw_count >= kDepthPrePassMinDrawCountArm) {
2104 if (render_pass_state.depthOnly) render_pass_state.numDrawCallsDepthOnly++;
2105 if (render_pass_state.depthEqualComparison) render_pass_state.numDrawCallsDepthEqualCompare++;
Sam Walls0961ec02020-03-31 16:39:15 +01002106 }
2107}
2108
Camden5b184be2019-08-13 07:50:19 -06002109bool BestPractices::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002110 uint32_t firstVertex, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06002111 bool skip = false;
2112
2113 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002114 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
2115 "Warning: You are calling vkCmdDraw() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06002116 }
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002117 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDraw()");
Camden5b184be2019-08-13 07:50:19 -06002118
2119 return skip;
2120}
2121
Sam Walls0961ec02020-03-31 16:39:15 +01002122void BestPractices::PostCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
2123 uint32_t firstVertex, uint32_t firstInstance) {
2124 StateTracker::PostCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
2125 RecordCmdDrawType(commandBuffer, vertexCount * instanceCount, "vkCmdDraw()");
2126}
2127
Camden5b184be2019-08-13 07:50:19 -06002128bool BestPractices::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002129 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06002130 bool skip = false;
2131
2132 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002133 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
2134 "Warning: You are calling vkCmdDrawIndexed() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06002135 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002136 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexed()");
2137
Attilio Provenzano02859b22020-02-27 14:17:28 +00002138 // Check if we reached the limit for small indexed draw calls.
2139 // Note that we cannot update the draw call count here, so we do it in PreCallRecordCmdDrawIndexed.
Jeremy Gebben78684b12022-02-23 17:31:56 -07002140 const auto cmd_state = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002141 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices &&
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02002142 (cmd_state->small_indexed_draw_call_count == kMaxSmallIndexedDrawcalls - 1) &&
2143 VendorCheckEnabled(kBPVendorArm)) {
2144 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_ManySmallIndexedDrawcalls,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -06002145 "%s: The command buffer contains many small indexed drawcalls "
Attilio Provenzano02859b22020-02-27 14:17:28 +00002146 "(at least %u drawcalls with less than %u indices each). This may cause pipeline bubbles. "
2147 "You can try batching drawcalls or instancing when applicable.",
2148 VendorSpecificTag(kBPVendorArm), kMaxSmallIndexedDrawcalls, kSmallIndexedDrawcallIndices);
2149 }
2150
Sam Walls8e77e4f2020-03-16 20:47:40 +00002151 if (VendorCheckEnabled(kBPVendorArm)) {
2152 ValidateIndexBufferArm(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
2153 }
2154
2155 return skip;
2156}
2157
2158bool BestPractices::ValidateIndexBufferArm(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
2159 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
2160 bool skip = false;
2161
2162 // check for sparse/underutilised index buffer, and post-transform cache thrashing
Jeremy Gebben78684b12022-02-23 17:31:56 -07002163 const auto cmd_state = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002164 if (cmd_state == nullptr) return skip;
2165
locke-lunarg1ae57d62020-11-18 10:49:19 -07002166 const auto* ib_state = cmd_state->index_buffer_binding.buffer_state.get();
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002167 if (ib_state == nullptr || cmd_state->index_buffer_binding.buffer_state->Destroyed()) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00002168
2169 const VkIndexType ib_type = cmd_state->index_buffer_binding.index_type;
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06002170 const auto& ib_mem_state = *ib_state->MemState();
Sam Walls8e77e4f2020-03-16 20:47:40 +00002171 const VkDeviceSize ib_mem_offset = ib_mem_state.mapped_range.offset;
2172 const void* ib_mem = ib_mem_state.p_driver_data;
2173 bool primitive_restart_enable = false;
2174
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002175 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
2176 const auto& pipeline_binding_iter = cmd_state->lastBound[lv_bind_point];
2177 const auto* pipeline_state = pipeline_binding_iter.pipeline_state;
Sam Walls8e77e4f2020-03-16 20:47:40 +00002178
Jeremy Gebben11af9792021-08-20 10:20:09 -06002179 if (pipeline_state != nullptr && pipeline_state->create_info.graphics.pInputAssemblyState != nullptr) {
2180 primitive_restart_enable = pipeline_state->create_info.graphics.pInputAssemblyState->primitiveRestartEnable == VK_TRUE;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002181 }
Sam Walls8e77e4f2020-03-16 20:47:40 +00002182
2183 // 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 -06002184 if (ib_mem && pipeline_binding_iter.IsUsing()) {
Sam Walls8e77e4f2020-03-16 20:47:40 +00002185 uint32_t scan_stride;
2186 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
2187 scan_stride = sizeof(uint8_t);
2188 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
2189 scan_stride = sizeof(uint16_t);
2190 } else {
2191 scan_stride = sizeof(uint32_t);
2192 }
2193
2194 const uint8_t* scan_begin = static_cast<const uint8_t*>(ib_mem) + ib_mem_offset + firstIndex * scan_stride;
2195 const uint8_t* scan_end = scan_begin + indexCount * scan_stride;
2196
2197 // Min and max are important to track for some Mali architectures. In older Mali devices without IDVS, all
2198 // vertices corresponding to indices between the minimum and maximum may be loaded, and possibly shaded,
2199 // irrespective of whether or not they're part of the draw call.
2200
2201 // start with minimum as 0xFFFFFFFF and adjust to indices in the buffer
2202 uint32_t min_index = ~0u;
2203 // start with maximum as 0 and adjust to indices in the buffer
2204 uint32_t max_index = 0u;
2205
2206 // first scan-through, we're looking to simulate a model LRU post-transform cache, estimating the number of vertices shaded
2207 // for the given index buffer
2208 uint32_t vertex_shade_count = 0;
2209
2210 PostTransformLRUCacheModel post_transform_cache;
2211
2212 // The size of the cache being modelled positively correlates with how much behaviour it can capture about
2213 // arbitrary ground-truth hardware/architecture cache behaviour. I.e. it's a good solution when we don't know the
2214 // target architecture.
2215 // However, modelling a post-transform cache with more than 32 elements gives diminishing returns in practice.
2216 // http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
2217 post_transform_cache.resize(32);
2218
2219 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
2220 uint32_t scan_index;
2221 uint32_t primitive_restart_value;
2222 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
2223 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
2224 primitive_restart_value = 0xFF;
2225 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
2226 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
2227 primitive_restart_value = 0xFFFF;
2228 } else {
2229 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
2230 primitive_restart_value = 0xFFFFFFFF;
2231 }
2232
2233 max_index = std::max(max_index, scan_index);
2234 min_index = std::min(min_index, scan_index);
2235
2236 if (!primitive_restart_enable || scan_index != primitive_restart_value) {
2237 bool in_cache = post_transform_cache.query_cache(scan_index);
2238 // if the shaded vertex corresponding to the index is not in the PT-cache, we need to shade again
2239 if (!in_cache) vertex_shade_count++;
2240 }
2241 }
2242
2243 // 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 +01002244 // 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
2245 if (max_index < min_index || max_index == min_index) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00002246
2247 if (max_index - min_index >= indexCount) {
Mark Young0ec6b062020-11-19 15:32:17 -07002248 skip |=
2249 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
2250 "%s The indices which were specified for the draw call only utilise approximately %.02f%% of "
2251 "index buffer value range. Arm Mali architectures before G71 do not have IDVS (Index-Driven "
2252 "Vertex Shading), meaning all vertices corresponding to indices between the minimum and "
2253 "maximum would be loaded, and possibly shaded, whether or not they are used.",
2254 VendorSpecificTag(kBPVendorArm),
2255 (static_cast<float>(indexCount) / static_cast<float>(max_index - min_index)) * 100.0f);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002256 return skip;
2257 }
2258
2259 // use a dynamic vector of bitsets as a memory-compact representation of which indices are included in the draw call
2260 // 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 +01002261 const size_t refs_per_bucket = 64;
2262 std::vector<std::bitset<refs_per_bucket>> vertex_reference_buckets;
2263
2264 const uint32_t n_indices = max_index - min_index + 1;
2265 const uint32_t n_buckets = (n_indices / static_cast<uint32_t>(refs_per_bucket)) +
2266 ((n_indices % static_cast<uint32_t>(refs_per_bucket)) != 0 ? 1 : 0);
2267
2268 // there needs to be at least one bitset to store a set of indices smaller than n_buckets
2269 vertex_reference_buckets.resize(std::max(1u, n_buckets));
Sam Walls8e77e4f2020-03-16 20:47:40 +00002270
2271 // To avoid using too much memory, we run over the indices again.
2272 // Knowing the size from the last scan allows us to record index usage with bitsets
2273 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
2274 uint32_t scan_index;
2275 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
2276 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
2277 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
2278 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
2279 } else {
2280 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
2281 }
2282 // keep track of the set of all indices used to reference vertices in the draw call
2283 size_t index_offset = scan_index - min_index;
Sam Walls61b06892020-07-23 16:20:50 +01002284 size_t bitset_bucket_index = index_offset / refs_per_bucket;
2285 uint64_t used_indices = 1ull << ((index_offset % refs_per_bucket) & 0xFFFFFFFFu);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002286 vertex_reference_buckets[bitset_bucket_index] |= used_indices;
2287 }
2288
2289 uint32_t vertex_reference_count = 0;
2290 for (const auto& bitset : vertex_reference_buckets) {
2291 vertex_reference_count += static_cast<uint32_t>(bitset.count());
2292 }
2293
2294 // 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 -07002295 float utilization = static_cast<float>(vertex_reference_count) / static_cast<float>(max_index - min_index + 1);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002296 // 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 -07002297 float cache_hit_rate = static_cast<float>(vertex_reference_count) / static_cast<float>(vertex_shade_count);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002298
2299 if (utilization < 0.5f) {
2300 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
2301 "%s The indices which were specified for the draw call only utilise approximately "
2302 "%.02f%% of the bound vertex buffer.",
2303 VendorSpecificTag(kBPVendorArm), utilization);
2304 }
2305
2306 if (cache_hit_rate <= 0.5f) {
2307 skip |=
2308 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_PostTransformCacheThrashing,
2309 "%s The indices which were specified for the draw call are estimated to cause thrashing of "
2310 "the post-transform vertex cache, with a hit-rate of %.02f%%. "
2311 "I.e. the ordering of the index buffer may not make optimal use of indices associated with "
2312 "recently shaded vertices.",
2313 VendorSpecificTag(kBPVendorArm), cache_hit_rate * 100.0f);
2314 }
2315 }
2316
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002317 return skip;
2318}
2319
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002320bool BestPractices::PreCallValidateCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
2321 const VkCommandBuffer* pCommandBuffers) const {
2322 bool skip = false;
Jeremy Gebben78684b12022-02-23 17:31:56 -07002323 const auto primary = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002324 for (uint32_t i = 0; i < commandBufferCount; i++) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07002325 const auto secondary_cb = Get<CMD_BUFFER_STATE_BP>(pCommandBuffers[i]);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002326 if (secondary_cb == nullptr) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002327 continue;
2328 }
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002329 const auto& secondary = secondary_cb->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002330 for (auto& clear : secondary.earlyClearAttachments) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002331 if (ClearAttachmentsIsFullClear(primary.get(), uint32_t(clear.rects.size()), clear.rects.data())) {
2332 skip |= ValidateClearAttachment(commandBuffer, primary.get(), clear.framebufferAttachment, clear.colorAttachment,
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002333 clear.aspects, true);
2334 }
2335 }
2336 }
Nadav Gevaf0808442021-05-21 13:51:25 -04002337
2338 if (VendorCheckEnabled(kBPVendorAMD)) {
2339 if (commandBufferCount > 0) {
2340 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdBuffer_AvoidSecondaryCmdBuffers,
2341 "%s Performance warning: Use of secondary command buffers is not recommended. ",
2342 VendorSpecificTag(kBPVendorAMD));
2343 }
2344 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002345 return skip;
2346}
2347
2348void BestPractices::PreCallRecordCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
2349 const VkCommandBuffer* pCommandBuffers) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07002350 auto primary = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002351 auto& primary_state = primary->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002352
2353 for (uint32_t i = 0; i < commandBufferCount; i++) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07002354 auto secondary_cb = Get<CMD_BUFFER_STATE_BP>(pCommandBuffers[i]);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002355 if (secondary_cb == nullptr) {
2356 continue;
2357 }
2358 auto& secondary = secondary_cb->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002359
2360 for (auto& early_clear : secondary.earlyClearAttachments) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002361 if (ClearAttachmentsIsFullClear(primary.get(), uint32_t(early_clear.rects.size()), early_clear.rects.data())) {
2362 RecordAttachmentClearAttachments(primary.get(), primary_state, early_clear.framebufferAttachment,
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002363 early_clear.colorAttachment, early_clear.aspects,
Hans-Kristian Arntzenfa8ef9f2021-06-29 12:07:59 +02002364 uint32_t(early_clear.rects.size()), early_clear.rects.data());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002365 } else {
2366 RecordAttachmentAccess(primary_state, early_clear.framebufferAttachment,
2367 early_clear.aspects);
2368 }
2369 }
2370
2371 for (auto& touch : secondary.touchesAttachments) {
2372 RecordAttachmentAccess(primary_state, touch.framebufferAttachment,
2373 touch.aspects);
2374 }
Hans-Kristian Arntzenc7eb82a2021-06-16 13:57:18 +02002375
2376 primary_state.numDrawCallsDepthEqualCompare += secondary.numDrawCallsDepthEqualCompare;
2377 primary_state.numDrawCallsDepthOnly += secondary.numDrawCallsDepthOnly;
Hans-Kristian Arntzenaf81dca2021-06-18 11:14:28 +02002378
Jeremy Gebben78684b12022-02-23 17:31:56 -07002379 auto second_state = Get<CMD_BUFFER_STATE_BP>(pCommandBuffers[i]);
Hans-Kristian Arntzenaf81dca2021-06-18 11:14:28 +02002380 if (second_state->hasDrawCmd) {
2381 primary->hasDrawCmd = true;
2382 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002383 }
2384
2385 ValidationStateTracker::PreCallRecordCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
2386}
2387
2388void BestPractices::RecordAttachmentAccess(RenderPassState& state, uint32_t fb_attachment, VkImageAspectFlags aspects) {
2389 // Called when we have a partial clear attachment, or a normal draw call which accesses an attachment.
2390 auto itr = std::find_if(state.touchesAttachments.begin(), state.touchesAttachments.end(),
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002391 [&](const AttachmentInfo& info) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002392 return info.framebufferAttachment == fb_attachment;
2393 });
2394
2395 if (itr != state.touchesAttachments.end()) {
2396 itr->aspects |= aspects;
2397 } else {
2398 state.touchesAttachments.push_back({ fb_attachment, aspects });
2399 }
2400}
2401
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002402void BestPractices::RecordAttachmentClearAttachments(CMD_BUFFER_STATE_BP* cmd_state, RenderPassState& state, uint32_t fb_attachment,
2403 uint32_t color_attachment, VkImageAspectFlags aspects, uint32_t rectCount,
2404 const VkClearRect* pRects) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002405 // If we observe a full clear before any other access to a frame buffer attachment,
2406 // we have candidate for redundant clear attachments.
2407 auto itr = std::find_if(state.touchesAttachments.begin(), state.touchesAttachments.end(),
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002408 [&](const AttachmentInfo& info) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002409 return info.framebufferAttachment == fb_attachment;
2410 });
2411
2412 uint32_t new_aspects = aspects;
2413 if (itr != state.touchesAttachments.end()) {
2414 new_aspects = aspects & ~itr->aspects;
2415 itr->aspects |= aspects;
2416 } else {
2417 state.touchesAttachments.push_back({ fb_attachment, aspects });
2418 }
2419
2420 if (new_aspects == 0) {
2421 return;
2422 }
2423
2424 if (cmd_state->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
2425 // The first command might be a clear, but might not be the first in the render pass, defer any checks until
2426 // CmdExecuteCommands.
2427 state.earlyClearAttachments.push_back({ fb_attachment, color_attachment, new_aspects,
2428 std::vector<VkClearRect>{pRects, pRects + rectCount} });
2429 }
2430}
2431
2432void BestPractices::PreCallRecordCmdClearAttachments(VkCommandBuffer commandBuffer,
2433 uint32_t attachmentCount, const VkClearAttachment* pClearAttachments,
2434 uint32_t rectCount, const VkClearRect* pRects) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07002435 auto cmd_state = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002436 RENDER_PASS_STATE* rp_state = cmd_state->activeRenderPass.get();
2437 FRAMEBUFFER_STATE* fb_state = cmd_state->activeFramebuffer.get();
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002438 RenderPassState& tracking_state = cmd_state->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002439 bool is_secondary = cmd_state->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY;
2440
2441 if (rectCount == 0 || !rp_state) {
2442 return;
2443 }
2444
2445 if (!is_secondary && !fb_state) {
2446 return;
2447 }
2448
2449 // If we have a rect which covers the entire frame buffer, we have a LOAD_OP_CLEAR-like command.
Jeremy Gebben9f537102021-10-05 16:37:12 -06002450 bool full_clear = ClearAttachmentsIsFullClear(cmd_state.get(), rectCount, pRects);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002451
ziga-lunarg885c6542022-03-07 01:08:25 +01002452 if (!rp_state->use_dynamic_rendering && !rp_state->use_dynamic_rendering_inherited) {
2453 auto& subpass = rp_state->createInfo.pSubpasses[cmd_state->activeSubpass];
2454 for (uint32_t i = 0; i < attachmentCount; i++) {
2455 auto& attachment = pClearAttachments[i];
2456 uint32_t fb_attachment = VK_ATTACHMENT_UNUSED;
2457 VkImageAspectFlags aspects = attachment.aspectMask;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002458
ziga-lunarg885c6542022-03-07 01:08:25 +01002459 if (aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) {
2460 if (subpass.pDepthStencilAttachment) {
2461 fb_attachment = subpass.pDepthStencilAttachment->attachment;
2462 }
2463 } else if (aspects & VK_IMAGE_ASPECT_COLOR_BIT) {
2464 fb_attachment = subpass.pColorAttachments[attachment.colorAttachment].attachment;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002465 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002466
ziga-lunarg885c6542022-03-07 01:08:25 +01002467 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2468 if (full_clear) {
2469 RecordAttachmentClearAttachments(cmd_state.get(), tracking_state, fb_attachment, attachment.colorAttachment,
2470 aspects, rectCount, pRects);
2471 } else {
2472 RecordAttachmentAccess(tracking_state, fb_attachment, aspects);
2473 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002474 }
2475 }
2476 }
2477
2478 ValidationStateTracker::PreCallRecordCmdClearAttachments(commandBuffer, attachmentCount, pClearAttachments,
2479 rectCount, pRects);
2480}
2481
Attilio Provenzano02859b22020-02-27 14:17:28 +00002482void BestPractices::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
2483 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
2484 ValidationStateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset,
2485 firstInstance);
2486
Jeremy Gebben78684b12022-02-23 17:31:56 -07002487 auto cmd_state = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002488 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices) {
2489 cmd_state->small_indexed_draw_call_count++;
2490 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002491
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002492 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDrawIndexed()");
Attilio Provenzano02859b22020-02-27 14:17:28 +00002493}
2494
Sam Walls0961ec02020-03-31 16:39:15 +01002495void BestPractices::PostCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
2496 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
2497 StateTracker::PostCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
2498 RecordCmdDrawType(commandBuffer, indexCount * instanceCount, "vkCmdDrawIndexed()");
2499}
2500
sfricke-samsung681ab7b2020-10-29 01:53:35 -07002501bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2502 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
2503 uint32_t maxDrawCount, uint32_t stride) const {
2504 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCount()");
2505
2506 return skip;
2507}
2508
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002509bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
2510 VkDeviceSize offset, VkBuffer countBuffer,
2511 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
2512 uint32_t stride) const {
2513 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCountKHR()");
Camden5b184be2019-08-13 07:50:19 -06002514
2515 return skip;
2516}
2517
2518bool BestPractices::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002519 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06002520 bool skip = false;
2521
2522 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002523 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
2524 "Warning: You are calling vkCmdDrawIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002525 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirect()");
Camden5b184be2019-08-13 07:50:19 -06002526 }
2527
2528 return skip;
2529}
2530
Sam Walls0961ec02020-03-31 16:39:15 +01002531void BestPractices::PostCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2532 uint32_t count, uint32_t stride) {
2533 StateTracker::PostCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, count, stride);
2534 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndirect()");
2535}
2536
Camden5b184be2019-08-13 07:50:19 -06002537bool BestPractices::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002538 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06002539 bool skip = false;
2540
2541 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002542 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
2543 "Warning: You are calling vkCmdDrawIndexedIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002544 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirect()");
Camden5b184be2019-08-13 07:50:19 -06002545 }
2546
2547 return skip;
2548}
2549
Sam Walls0961ec02020-03-31 16:39:15 +01002550void BestPractices::PostCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2551 uint32_t count, uint32_t stride) {
2552 StateTracker::PostCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, count, stride);
2553 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndexedIndirect()");
2554}
2555
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002556void BestPractices::ValidateBoundDescriptorSets(VkCommandBuffer commandBuffer, const char* function_name) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07002557 auto cb_state = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002558
2559 if (cb_state) {
2560 for (auto descriptor_set : cb_state->validated_descriptor_sets) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002561 const auto& layout = *descriptor_set->GetLayout();
Hans-Kristian Arntzena8199012021-03-22 12:10:07 +01002562
2563 for (uint32_t index = 0; index < descriptor_set->GetBindingCount(); ++index) {
2564 // For bindless scenarios, we should not attempt to track descriptor set state.
2565 // It is highly uncertain which resources are actually bound.
2566 // Resources which are written to such a descriptor should be marked as indeterminate w.r.t. state.
2567 VkDescriptorBindingFlags flags = layout.GetDescriptorBindingFlagsFromIndex(index);
2568 if (flags & (VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT |
2569 VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT |
2570 VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT)) {
2571 continue;
2572 }
2573
2574 auto index_range = layout.GetGlobalIndexRangeFromIndex(index);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002575 for (uint32_t i = index_range.start; i < index_range.end; ++i) {
ZandroFargnoliacf12f02020-06-18 16:50:00 +01002576 VkImageView image_view{VK_NULL_HANDLE};
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002577
2578 auto descriptor = descriptor_set->GetDescriptorFromGlobalIndex(i);
2579 switch (descriptor->GetClass()) {
2580 case cvdescriptorset::DescriptorClass::Image: {
2581 if (const auto image_descriptor = static_cast<const cvdescriptorset::ImageDescriptor*>(descriptor)) {
2582 image_view = image_descriptor->GetImageView();
2583 }
Hans-Kristian Arntzenbc3a6152021-03-22 13:05:43 +01002584 break;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002585 }
2586 case cvdescriptorset::DescriptorClass::ImageSampler: {
2587 if (const auto image_sampler_descriptor =
2588 static_cast<const cvdescriptorset::ImageSamplerDescriptor*>(descriptor)) {
2589 image_view = image_sampler_descriptor->GetImageView();
2590 }
Hans-Kristian Arntzenbc3a6152021-03-22 13:05:43 +01002591 break;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002592 }
ZandroFargnoliacf12f02020-06-18 16:50:00 +01002593 default:
Hans-Kristian Arntzenbc3a6152021-03-22 13:05:43 +01002594 break;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002595 }
2596
2597 if (image_view) {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002598 auto image_view_state = Get<IMAGE_VIEW_STATE>(image_view);
Jeremy Gebben9f537102021-10-05 16:37:12 -06002599 QueueValidateImageView(cb_state->queue_submit_functions, function_name, image_view_state.get(),
2600 IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002601 }
2602 }
2603 }
2604 }
2605 }
2606}
2607
2608void BestPractices::PreCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
2609 uint32_t firstVertex, uint32_t firstInstance) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002610 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDraw()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002611}
2612
2613void BestPractices::PreCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2614 uint32_t drawCount, uint32_t stride) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002615 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDrawIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002616}
2617
2618void BestPractices::PreCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2619 uint32_t drawCount, uint32_t stride) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002620 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDrawIndexedIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002621}
2622
Camden5b184be2019-08-13 07:50:19 -06002623bool BestPractices::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t groupCountX, uint32_t groupCountY,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002624 uint32_t groupCountZ) const {
Camden5b184be2019-08-13 07:50:19 -06002625 bool skip = false;
2626
2627 if ((groupCountX == 0) || (groupCountY == 0) || (groupCountZ == 0)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002628 skip |= LogWarning(device, kVUID_BestPractices_CmdDispatch_GroupCountZero,
2629 "Warning: You are calling vkCmdDispatch() while one or more groupCounts are zero (groupCountX = %" PRIu32
2630 ", groupCountY = %" PRIu32 ", groupCountZ = %" PRIu32 ").",
2631 groupCountX, groupCountY, groupCountZ);
Camden5b184be2019-08-13 07:50:19 -06002632 }
2633
2634 return skip;
2635}
Camden83a9c372019-08-14 11:41:38 -06002636
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002637bool BestPractices::PreCallValidateCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo* pSubpassEndInfo) const {
2638 bool skip = false;
2639 skip |= StateTracker::PreCallValidateCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
2640 skip |= ValidateCmdEndRenderPass(commandBuffer);
2641 return skip;
2642}
2643
2644bool BestPractices::PreCallValidateCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfo* pSubpassEndInfo) const {
2645 bool skip = false;
2646 skip |= StateTracker::PreCallValidateCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
2647 skip |= ValidateCmdEndRenderPass(commandBuffer);
2648 return skip;
2649}
2650
Sam Walls0961ec02020-03-31 16:39:15 +01002651bool BestPractices::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
2652 bool skip = false;
Sam Walls0961ec02020-03-31 16:39:15 +01002653 skip |= StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002654 skip |= ValidateCmdEndRenderPass(commandBuffer);
2655 return skip;
2656}
2657
2658bool BestPractices::ValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
2659 bool skip = false;
Jeremy Gebben78684b12022-02-23 17:31:56 -07002660 const auto cmd = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Sam Walls0961ec02020-03-31 16:39:15 +01002661
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002662 if (cmd == nullptr) return skip;
2663 auto &render_pass_state = cmd->render_pass_state;
Sam Walls0961ec02020-03-31 16:39:15 +01002664
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002665 bool uses_depth = (render_pass_state.depthAttachment || render_pass_state.colorAttachment) &&
2666 render_pass_state.numDrawCallsDepthEqualCompare >= kDepthPrePassNumDrawCallsArm &&
2667 render_pass_state.numDrawCallsDepthOnly >= kDepthPrePassNumDrawCallsArm;
Sam Walls0961ec02020-03-31 16:39:15 +01002668 if (uses_depth) {
2669 skip |= LogPerformanceWarning(
2670 device, kVUID_BestPractices_EndRenderPass_DepthPrePassUsage,
2671 "%s Depth pre-passes may be in use. In general, this is not recommended, as in Arm Mali GPUs since "
2672 "Mali-T620, Forward Pixel Killing (FPK) can already perform automatic hidden surface removal; in which "
2673 "case, using depth pre-passes for hidden surface removal may worsen performance.",
2674 VendorSpecificTag(kBPVendorArm));
2675 }
2676
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002677 RENDER_PASS_STATE* rp = cmd->activeRenderPass.get();
2678
2679 if (VendorCheckEnabled(kBPVendorArm) && rp) {
2680
2681 // If we use an attachment on-tile, we should access it in some way. Otherwise,
2682 // it is redundant to have it be part of the render pass.
2683 // Only consider it redundant if it will actually consume bandwidth, i.e.
2684 // LOAD_OP_LOAD is used or STORE_OP_STORE. CLEAR -> DONT_CARE is benign,
2685 // as is using pure input attachments.
2686 // CLEAR -> STORE might be considered a "useful" thing to do, but
2687 // the optimal thing to do is to defer the clear until you're actually
2688 // going to render to the image.
2689
2690 uint32_t num_attachments = rp->createInfo.attachmentCount;
2691 for (uint32_t i = 0; i < num_attachments; i++) {
Hans-Kristian Arntzen237663c2021-07-01 14:36:40 +02002692 if (!RenderPassUsesAttachmentOnTile(rp->createInfo, i) ||
2693 RenderPassUsesAttachmentAsResolve(rp->createInfo, i)) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002694 continue;
2695 }
2696
2697 auto& attachment = rp->createInfo.pAttachments[i];
2698
2699 VkImageAspectFlags bandwidth_aspects = 0;
2700
2701 if (!FormatIsStencilOnly(attachment.format) &&
2702 (attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
2703 attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE)) {
2704 if (FormatHasDepth(attachment.format)) {
2705 bandwidth_aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
2706 } else {
2707 bandwidth_aspects |= VK_IMAGE_ASPECT_COLOR_BIT;
2708 }
2709 }
2710
2711 if (FormatHasStencil(attachment.format) &&
2712 (attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
2713 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE)) {
2714 bandwidth_aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
2715 }
2716
2717 if (!bandwidth_aspects) {
2718 continue;
2719 }
2720
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002721 auto itr = std::find_if(render_pass_state.touchesAttachments.begin(), render_pass_state.touchesAttachments.end(),
2722 [&](const AttachmentInfo& info) { return info.framebufferAttachment == i; });
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002723 uint32_t untouched_aspects = bandwidth_aspects;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002724 if (itr != render_pass_state.touchesAttachments.end()) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002725 untouched_aspects &= ~itr->aspects;
2726 }
2727
2728 if (untouched_aspects) {
2729 skip |= LogPerformanceWarning(
2730 device, kVUID_BestPractices_EndRenderPass_RedundantAttachmentOnTile,
2731 "%s Render pass was ended, but attachment #%u (format: %u, untouched aspects 0x%x) "
2732 "was never accessed by a pipeline or clear command. "
2733 "On tile-based architectures, LOAD_OP_LOAD and STORE_OP_STORE consume bandwidth and should not be part of the render pass "
2734 "if the attachments are not intended to be accessed.",
2735 VendorSpecificTag(kBPVendorArm), i, attachment.format, untouched_aspects);
2736 }
2737 }
2738 }
2739
Sam Walls0961ec02020-03-31 16:39:15 +01002740 return skip;
2741}
2742
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002743void BestPractices::PreCallRecordCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002744 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDispatch()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002745}
2746
2747void BestPractices::PreCallRecordCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002748 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDispatchIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002749}
2750
Camden Stocker9c051442019-11-06 14:28:43 -08002751bool BestPractices::ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(VkPhysicalDevice physicalDevice,
2752 const char* api_name) const {
2753 bool skip = false;
Jeremy Gebben78684b12022-02-23 17:31:56 -07002754 const auto bp_pd_state = Get<PHYSICAL_DEVICE_STATE_BP>(physicalDevice);
Camden Stocker9c051442019-11-06 14:28:43 -08002755
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002756 if (bp_pd_state) {
2757 if (bp_pd_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState == UNCALLED) {
2758 skip |= LogWarning(physicalDevice, kVUID_BestPractices_DisplayPlane_PropertiesNotCalled,
2759 "Potential problem with calling %s() without first retrieving properties from "
2760 "vkGetPhysicalDeviceDisplayPlanePropertiesKHR or vkGetPhysicalDeviceDisplayPlaneProperties2KHR.",
2761 api_name);
2762 }
Camden Stocker9c051442019-11-06 14:28:43 -08002763 }
2764
2765 return skip;
2766}
2767
Camden83a9c372019-08-14 11:41:38 -06002768bool BestPractices::PreCallValidateGetDisplayPlaneSupportedDisplaysKHR(VkPhysicalDevice physicalDevice, uint32_t planeIndex,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002769 uint32_t* pDisplayCount, VkDisplayKHR* pDisplays) const {
Camden83a9c372019-08-14 11:41:38 -06002770 bool skip = false;
2771
Camden Stocker9c051442019-11-06 14:28:43 -08002772 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneSupportedDisplaysKHR");
Camden83a9c372019-08-14 11:41:38 -06002773
Camden Stocker9c051442019-11-06 14:28:43 -08002774 return skip;
2775}
2776
2777bool BestPractices::PreCallValidateGetDisplayPlaneCapabilitiesKHR(VkPhysicalDevice physicalDevice, VkDisplayModeKHR mode,
2778 uint32_t planeIndex,
2779 VkDisplayPlaneCapabilitiesKHR* pCapabilities) const {
2780 bool skip = false;
2781
2782 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilitiesKHR");
2783
2784 return skip;
2785}
2786
2787bool BestPractices::PreCallValidateGetDisplayPlaneCapabilities2KHR(VkPhysicalDevice physicalDevice,
2788 const VkDisplayPlaneInfo2KHR* pDisplayPlaneInfo,
2789 VkDisplayPlaneCapabilities2KHR* pCapabilities) const {
2790 bool skip = false;
2791
2792 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilities2KHR");
Camden83a9c372019-08-14 11:41:38 -06002793
2794 return skip;
2795}
Camden05de2d42019-08-19 10:23:56 -06002796
2797bool BestPractices::PreCallValidateGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain, uint32_t* pSwapchainImageCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002798 VkImage* pSwapchainImages) const {
Camden05de2d42019-08-19 10:23:56 -06002799 bool skip = false;
2800
Jeremy Gebben78684b12022-02-23 17:31:56 -07002801 auto swapchain_state = Get<SWAPCHAIN_STATE_BP>(swapchain);
Camden05de2d42019-08-19 10:23:56 -06002802
Nathaniel Cesario39152e62021-07-02 13:04:16 -06002803 if (swapchain_state && pSwapchainImages) {
Camden05de2d42019-08-19 10:23:56 -06002804 // Compare the preliminary value of *pSwapchainImageCount with the value this time:
Nathaniel Cesario39152e62021-07-02 13:04:16 -06002805 if (swapchain_state->vkGetSwapchainImagesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002806 skip |=
2807 LogWarning(device, kVUID_Core_Swapchain_PriorCount,
2808 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImageCount; but no prior positive value has "
2809 "been seen for pSwapchainImages.");
Camden05de2d42019-08-19 10:23:56 -06002810 }
Camden05de2d42019-08-19 10:23:56 -06002811
Nathaniel Cesario4ce98382021-05-28 11:33:20 -06002812 if (*pSwapchainImageCount > swapchain_state->get_swapchain_image_count) {
2813 skip |= LogWarning(
2814 device, kVUID_BestPractices_Swapchain_InvalidCount,
2815 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImages, and with pSwapchainImageCount set to a "
Nadav Gevaf0808442021-05-21 13:51:25 -04002816 "value (%" PRId32 ") that is greater than the value (%" PRId32 ") that was returned when pSwapchainImages was NULL.",
Nathaniel Cesario4ce98382021-05-28 11:33:20 -06002817 *pSwapchainImageCount, swapchain_state->get_swapchain_image_count);
2818 }
2819 }
2820
Camden05de2d42019-08-19 10:23:56 -06002821 return skip;
2822}
2823
2824// Common function to handle validation for GetPhysicalDeviceQueueFamilyProperties & 2KHR version
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002825bool BestPractices::ValidateCommonGetPhysicalDeviceQueueFamilyProperties(const PHYSICAL_DEVICE_STATE* bp_pd_state,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002826 uint32_t requested_queue_family_property_count,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002827 const CALL_STATE call_state,
2828 const char* caller_name) const {
Camden05de2d42019-08-19 10:23:56 -06002829 bool skip = false;
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002830 // Verify that for each physical device, this command is called first with NULL pQueueFamilyProperties in order to get count
2831 if (UNCALLED == call_state) {
2832 skip |= LogWarning(
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002833 bp_pd_state->Handle(), kVUID_Core_DevLimit_MissingQueryCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002834 "%s is called with non-NULL pQueueFamilyProperties before obtaining pQueueFamilyPropertyCount. It is "
2835 "recommended "
2836 "to first call %s with NULL pQueueFamilyProperties in order to obtain the maximal pQueueFamilyPropertyCount.",
2837 caller_name, caller_name);
2838 // Then verify that pCount that is passed in on second call matches what was returned
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002839 } else if (bp_pd_state->queue_family_known_count != requested_queue_family_property_count) {
2840 skip |= LogWarning(bp_pd_state->Handle(), kVUID_Core_DevLimit_CountMismatch,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002841 "%s is called with non-NULL pQueueFamilyProperties and pQueueFamilyPropertyCount value %" PRIu32
2842 ", but the largest previously returned pQueueFamilyPropertyCount for this physicalDevice is %" PRIu32
2843 ". It is recommended to instead receive all the properties by calling %s with "
2844 "pQueueFamilyPropertyCount that was "
2845 "previously obtained by calling %s with NULL pQueueFamilyProperties.",
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002846 caller_name, requested_queue_family_property_count, bp_pd_state->queue_family_known_count, caller_name,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002847 caller_name);
Camden05de2d42019-08-19 10:23:56 -06002848 }
2849
2850 return skip;
2851}
2852
Jeff Bolz5c801d12019-10-09 10:38:45 -05002853bool BestPractices::PreCallValidateBindAccelerationStructureMemoryNV(
2854 VkDevice device, uint32_t bindInfoCount, const VkBindAccelerationStructureMemoryInfoNV* pBindInfos) const {
Camden Stocker82510582019-09-03 14:00:16 -06002855 bool skip = false;
2856
2857 for (uint32_t i = 0; i < bindInfoCount; i++) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07002858 auto as_state = Get<ACCELERATION_STRUCTURE_STATE>(pBindInfos[i].accelerationStructure);
Camden Stocker82510582019-09-03 14:00:16 -06002859 if (!as_state->memory_requirements_checked) {
2860 // There's not an explicit requirement in the spec to call vkGetImageMemoryRequirements() prior to calling
2861 // BindAccelerationStructureMemoryNV but it's implied in that memory being bound must conform with
2862 // VkAccelerationStructureMemoryRequirementsInfoNV from vkGetAccelerationStructureMemoryRequirementsNV
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002863 skip |= LogWarning(
2864 device, kVUID_BestPractices_BindAccelNV_NoMemReqQuery,
Camden Stocker82510582019-09-03 14:00:16 -06002865 "vkBindAccelerationStructureMemoryNV(): "
2866 "Binding memory to %s but vkGetAccelerationStructureMemoryRequirementsNV() has not been called on that structure.",
2867 report_data->FormatHandle(pBindInfos[i].accelerationStructure).c_str());
2868 }
2869 }
2870
2871 return skip;
2872}
2873
Camden05de2d42019-08-19 10:23:56 -06002874bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
2875 uint32_t* pQueueFamilyPropertyCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002876 VkQueueFamilyProperties* pQueueFamilyProperties) const {
Jeremy Gebben78684b12022-02-23 17:31:56 -07002877 const auto bp_pd_state = Get<PHYSICAL_DEVICE_STATE_BP>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002878 if (pQueueFamilyProperties && bp_pd_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002879 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(bp_pd_state.get(), *pQueueFamilyPropertyCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002880 bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
2881 "vkGetPhysicalDeviceQueueFamilyProperties()");
2882 }
2883 return false;
Camden05de2d42019-08-19 10:23:56 -06002884}
2885
Mike Schuchardt2df08912020-12-15 16:28:09 -08002886bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
2887 uint32_t* pQueueFamilyPropertyCount,
2888 VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Jeremy Gebben78684b12022-02-23 17:31:56 -07002889 const auto bp_pd_state = Get<PHYSICAL_DEVICE_STATE_BP>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002890 if (pQueueFamilyProperties && bp_pd_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002891 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(bp_pd_state.get(), *pQueueFamilyPropertyCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002892 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
2893 "vkGetPhysicalDeviceQueueFamilyProperties2()");
2894 }
2895 return false;
Camden05de2d42019-08-19 10:23:56 -06002896}
2897
Jeff Bolz5c801d12019-10-09 10:38:45 -05002898bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2KHR(
Mike Schuchardt2df08912020-12-15 16:28:09 -08002899 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount, VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Jeremy Gebben78684b12022-02-23 17:31:56 -07002900 const auto bp_pd_state = Get<PHYSICAL_DEVICE_STATE_BP>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002901 if (pQueueFamilyProperties && bp_pd_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002902 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(bp_pd_state.get(), *pQueueFamilyPropertyCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002903 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
2904 "vkGetPhysicalDeviceQueueFamilyProperties2KHR()");
2905 }
2906 return false;
Camden05de2d42019-08-19 10:23:56 -06002907}
2908
2909bool BestPractices::PreCallValidateGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
2910 uint32_t* pSurfaceFormatCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002911 VkSurfaceFormatKHR* pSurfaceFormats) const {
Camden05de2d42019-08-19 10:23:56 -06002912 if (!pSurfaceFormats) return false;
Jeremy Gebben78684b12022-02-23 17:31:56 -07002913 const auto bp_pd_state = Get<PHYSICAL_DEVICE_STATE_BP>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002914 const auto& call_state = bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState;
Camden05de2d42019-08-19 10:23:56 -06002915 bool skip = false;
2916 if (call_state == UNCALLED) {
2917 // Since we haven't recorded a preliminary value of *pSurfaceFormatCount, that likely means that the application didn't
2918 // previously call this function with a NULL value of pSurfaceFormats:
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002919 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_MustQueryCount,
2920 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount; but no prior "
2921 "positive value has been seen for pSurfaceFormats.");
Camden05de2d42019-08-19 10:23:56 -06002922 } else {
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06002923 if (*pSurfaceFormatCount > bp_pd_state->surface_formats_count) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002924 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_CountMismatch,
2925 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount, and with "
2926 "pSurfaceFormats set to a value (%u) that is greater than the value (%u) that was returned "
2927 "when pSurfaceFormatCount was NULL.",
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06002928 *pSurfaceFormatCount, bp_pd_state->surface_formats_count);
Camden05de2d42019-08-19 10:23:56 -06002929 }
2930 }
2931 return skip;
2932}
Camden Stocker23cc47d2019-09-03 14:53:57 -06002933
2934bool BestPractices::PreCallValidateQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002935 VkFence fence) const {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002936 bool skip = false;
2937
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002938 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
2939 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
Camden Stocker23cc47d2019-09-03 14:53:57 -06002940 // 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 -07002941 layer_data::unordered_set<const IMAGE_STATE*> sparse_images;
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002942 // Track images getting metadata bound by this call in a set, it'll be recorded into the image_state
2943 // in RecordQueueBindSparse.
Jeremy Gebbencbf22862021-03-03 12:01:22 -07002944 layer_data::unordered_set<const IMAGE_STATE*> sparse_images_with_metadata;
Camden Stocker23cc47d2019-09-03 14:53:57 -06002945 // 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 -07002946 for (uint32_t i = 0; i < bind_info.imageBindCount; ++i) {
2947 const auto& image_bind = bind_info.pImageBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04002948 auto image_state = Get<IMAGE_STATE>(image_bind.image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002949 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002950 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002951 }
Jeremy Gebben9f537102021-10-05 16:37:12 -06002952 sparse_images.insert(image_state.get());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002953 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
2954 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
2955 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002956 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002957 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
2958 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002959 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002960 }
2961 }
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06002962 if (!image_state->memory_requirements_checked[0]) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002963 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002964 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002965 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
2966 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002967 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002968 }
2969 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002970 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
2971 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04002972 auto image_state = Get<IMAGE_STATE>(bind_info.pImageOpaqueBinds[i].image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002973 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002974 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002975 }
Jeremy Gebben9f537102021-10-05 16:37:12 -06002976 sparse_images.insert(image_state.get());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002977 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
2978 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
2979 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002980 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002981 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
2982 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002983 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002984 }
2985 }
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06002986 if (!image_state->memory_requirements_checked[0]) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002987 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002988 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002989 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
2990 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002991 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002992 }
2993 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
2994 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002995 sparse_images_with_metadata.insert(image_state.get());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002996 }
2997 }
2998 }
2999 for (const auto& sparse_image_state : sparse_images) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05003000 if (sparse_image_state->sparse_metadata_required && !sparse_image_state->sparse_metadata_bound &&
3001 sparse_images_with_metadata.find(sparse_image_state) == sparse_images_with_metadata.end()) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06003002 // Warn if sparse image binding metadata required for image with sparse binding, but metadata not bound
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003003 skip |= LogWarning(sparse_image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003004 "vkQueueBindSparse(): Binding sparse memory to %s which requires a metadata aspect but no "
3005 "binding with VK_SPARSE_MEMORY_BIND_METADATA_BIT set was made.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003006 report_data->FormatHandle(sparse_image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06003007 }
3008 }
3009 }
3010
3011 return skip;
3012}
Jeff Bolz46c0ea02019-10-09 13:06:29 -05003013
Mark Lobodzinski84101d72020-04-24 09:43:48 -06003014void BestPractices::ManualPostCallRecordQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
3015 VkFence fence, VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07003016 if (result != VK_SUCCESS) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07003017 return;
3018 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05003019
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003020 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
3021 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
3022 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
3023 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04003024 auto image_state = Get<IMAGE_STATE>(bind_info.pImageOpaqueBinds[i].image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003025 if (!image_state) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05003026 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003027 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05003028 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
3029 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
3030 image_state->sparse_metadata_bound = true;
3031 }
3032 }
3033 }
3034 }
3035}
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003036
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003037bool BestPractices::ClearAttachmentsIsFullClear(const CMD_BUFFER_STATE_BP* cmd, uint32_t rectCount,
3038 const VkClearRect* pRects) const {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003039 if (cmd->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
3040 // We don't know the accurate render area in a secondary,
3041 // so assume we clear the entire frame buffer.
3042 // This is resolved in CmdExecuteCommands where we can check if the clear is a full clear.
3043 return true;
3044 }
3045
3046 // If we have a rect which covers the entire frame buffer, we have a LOAD_OP_CLEAR-like command.
3047 for (uint32_t i = 0; i < rectCount; i++) {
3048 auto& rect = pRects[i];
3049 auto& render_area = cmd->activeRenderPassBeginInfo.renderArea;
3050 if (rect.rect.extent.width == render_area.extent.width && rect.rect.extent.height == render_area.extent.height) {
3051 return true;
3052 }
3053 }
3054
3055 return false;
3056}
3057
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003058bool BestPractices::ValidateClearAttachment(VkCommandBuffer commandBuffer, const CMD_BUFFER_STATE_BP* cmd, uint32_t fb_attachment,
3059 uint32_t color_attachment, VkImageAspectFlags aspects, bool secondary) const {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003060 const RENDER_PASS_STATE* rp = cmd->activeRenderPass.get();
3061 bool skip = false;
3062
3063 if (!rp || fb_attachment == VK_ATTACHMENT_UNUSED) {
3064 return skip;
3065 }
3066
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003067 const auto& rp_state = cmd->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003068
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003069 auto attachment_itr = std::find_if(rp_state.touchesAttachments.begin(), rp_state.touchesAttachments.end(),
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02003070 [&](const AttachmentInfo& info) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003071 return info.framebufferAttachment == fb_attachment;
3072 });
3073
3074 // Only report aspects which haven't been touched yet.
3075 VkImageAspectFlags new_aspects = aspects;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003076 if (attachment_itr != rp_state.touchesAttachments.end()) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003077 new_aspects &= ~attachment_itr->aspects;
3078 }
3079
3080 // Warn if this is issued prior to Draw Cmd and clearing the entire attachment
3081 if (!cmd->hasDrawCmd) {
3082 skip |= LogPerformanceWarning(
3083 commandBuffer, kVUID_BestPractices_DrawState_ClearCmdBeforeDraw,
Hans-Kristian Arntzen4ddd6182021-06-18 12:16:33 +02003084 "vkCmdClearAttachments() issued on %s prior to any Draw Cmds in current render pass. It is recommended you "
3085 "use RenderPass LOAD_OP_CLEAR on attachments instead.",
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003086 report_data->FormatHandle(commandBuffer).c_str());
3087 }
3088
3089 if ((new_aspects & VK_IMAGE_ASPECT_COLOR_BIT) &&
3090 rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
3091 skip |= LogPerformanceWarning(
3092 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
3093 "%svkCmdClearAttachments() issued on %s for color attachment #%u in this subpass, "
3094 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
3095 "it is more efficient.",
3096 secondary ? "vkCmdExecuteCommands(): " : "",
3097 report_data->FormatHandle(commandBuffer).c_str(), color_attachment);
3098 }
3099
3100 if ((new_aspects & VK_IMAGE_ASPECT_DEPTH_BIT) &&
3101 rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
3102 skip |= LogPerformanceWarning(
3103 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
3104 "%svkCmdClearAttachments() issued on %s for the depth attachment in this subpass, "
3105 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
3106 "it is more efficient.",
3107 secondary ? "vkCmdExecuteCommands(): " : "",
3108 report_data->FormatHandle(commandBuffer).c_str());
3109 }
3110
3111 if ((new_aspects & VK_IMAGE_ASPECT_STENCIL_BIT) &&
3112 rp->createInfo.pAttachments[fb_attachment].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
3113 skip |= LogPerformanceWarning(
3114 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
3115 "%svkCmdClearAttachments() issued on %s for the stencil attachment in this subpass, "
3116 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
3117 "it is more efficient.",
3118 secondary ? "vkCmdExecuteCommands(): " : "",
3119 report_data->FormatHandle(commandBuffer).c_str());
3120 }
3121
3122 return skip;
3123}
3124
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003125bool BestPractices::PreCallValidateCmdClearAttachments(VkCommandBuffer commandBuffer, uint32_t attachmentCount,
Camden Stockerf55721f2019-09-09 11:04:49 -06003126 const VkClearAttachment* pAttachments, uint32_t rectCount,
3127 const VkClearRect* pRects) const {
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003128 bool skip = false;
Jeremy Gebben78684b12022-02-23 17:31:56 -07003129 const auto cb_node = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003130 if (!cb_node) return skip;
3131
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003132 if (cb_node->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
3133 // Defer checks to ExecuteCommands.
3134 return skip;
3135 }
3136
3137 // Only care about full clears, partial clears might have legitimate uses.
Jeremy Gebben9f537102021-10-05 16:37:12 -06003138 if (!ClearAttachmentsIsFullClear(cb_node.get(), rectCount, pRects)) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003139 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003140 }
3141
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003142 // Check for uses of ClearAttachments along with LOAD_OP_LOAD,
3143 // as it can be more efficient to just use LOAD_OP_CLEAR
locke-lunargaecf2152020-05-12 17:15:41 -06003144 const RENDER_PASS_STATE* rp = cb_node->activeRenderPass.get();
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003145 if (rp) {
3146 const auto& subpass = rp->createInfo.pSubpasses[cb_node->activeSubpass];
3147
3148 for (uint32_t i = 0; i < attachmentCount; i++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02003149 const auto& attachment = pAttachments[i];
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003150
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003151 if (attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
3152 uint32_t color_attachment = attachment.colorAttachment;
3153 uint32_t fb_attachment = subpass.pColorAttachments[color_attachment].attachment;
Jeremy Gebben9f537102021-10-05 16:37:12 -06003154 skip |= ValidateClearAttachment(commandBuffer, cb_node.get(), fb_attachment, color_attachment,
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003155 attachment.aspectMask, false);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003156 }
3157
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003158 if (subpass.pDepthStencilAttachment &&
3159 (attachment.aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT))) {
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003160 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
Jeremy Gebben9f537102021-10-05 16:37:12 -06003161 skip |= ValidateClearAttachment(commandBuffer, cb_node.get(), fb_attachment, VK_ATTACHMENT_UNUSED,
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003162 attachment.aspectMask, false);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003163 }
3164 }
3165 }
3166
Nadav Gevaf0808442021-05-21 13:51:25 -04003167 if (VendorCheckEnabled(kBPVendorAMD)) {
3168 for (uint32_t attachment_idx = 0; attachment_idx < attachmentCount; attachment_idx++) {
3169 if (pAttachments[attachment_idx].aspectMask == VK_IMAGE_ASPECT_COLOR_BIT) {
3170 bool black_check = false;
3171 black_check |= pAttachments[attachment_idx].clearValue.color.float32[0] != 0.0f;
3172 black_check |= pAttachments[attachment_idx].clearValue.color.float32[1] != 0.0f;
3173 black_check |= pAttachments[attachment_idx].clearValue.color.float32[2] != 0.0f;
3174 black_check |= pAttachments[attachment_idx].clearValue.color.float32[3] != 0.0f &&
3175 pAttachments[attachment_idx].clearValue.color.float32[3] != 1.0f;
3176
3177 bool white_check = false;
3178 white_check |= pAttachments[attachment_idx].clearValue.color.float32[0] != 1.0f;
3179 white_check |= pAttachments[attachment_idx].clearValue.color.float32[1] != 1.0f;
3180 white_check |= pAttachments[attachment_idx].clearValue.color.float32[2] != 1.0f;
3181 white_check |= pAttachments[attachment_idx].clearValue.color.float32[3] != 0.0f &&
3182 pAttachments[attachment_idx].clearValue.color.float32[3] != 1.0f;
3183
3184 if (black_check && white_check) {
3185 skip |= LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachment_FastClearValues,
3186 "%s Performance warning: vkCmdClearAttachments() clear value for color attachment %" PRId32 " is not a fast clear value."
3187 "Consider changing to one of the following:"
3188 "RGBA(0, 0, 0, 0) "
3189 "RGBA(0, 0, 0, 1) "
3190 "RGBA(1, 1, 1, 0) "
3191 "RGBA(1, 1, 1, 1)",
3192 VendorSpecificTag(kBPVendorAMD), attachment_idx);
3193 }
3194 } else {
3195 if ((pAttachments[attachment_idx].clearValue.depthStencil.depth != 0 &&
3196 pAttachments[attachment_idx].clearValue.depthStencil.depth != 1) &&
3197 pAttachments[attachment_idx].clearValue.depthStencil.stencil != 0) {
3198 skip |= LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachment_FastClearValues,
3199 "%s Performance warning: vkCmdClearAttachments() clear value for depth/stencil "
3200 "attachment %" PRId32 " is not a fast clear value."
3201 "Consider changing to one of the following:"
3202 "D=0.0f, S=0"
3203 "D=1.0f, S=0",
3204 VendorSpecificTag(kBPVendorAMD), attachment_idx);
3205 }
3206 }
3207 }
3208 }
3209
Camden Stockerf55721f2019-09-09 11:04:49 -06003210 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003211}
Attilio Provenzano02859b22020-02-27 14:17:28 +00003212
3213bool BestPractices::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3214 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3215 const VkImageResolve* pRegions) const {
3216 bool skip = false;
3217
3218 skip |= VendorCheckEnabled(kBPVendorArm) &&
3219 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage_ResolvingImage,
3220 "%s Attempting to use vkCmdResolveImage to resolve a multisampled image. "
3221 "This is a very slow and extremely bandwidth intensive path. "
3222 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
3223 VendorSpecificTag(kBPVendorArm));
3224
3225 return skip;
3226}
3227
Jeff Leger178b1e52020-10-05 12:22:23 -04003228bool BestPractices::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
3229 const VkResolveImageInfo2KHR* pResolveImageInfo) const {
3230 bool skip = false;
3231
3232 skip |= VendorCheckEnabled(kBPVendorArm) &&
3233 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2KHR_ResolvingImage,
3234 "%s Attempting to use vkCmdResolveImage2KHR to resolve a multisampled image. "
3235 "This is a very slow and extremely bandwidth intensive path. "
3236 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
3237 VendorSpecificTag(kBPVendorArm));
3238
3239 return skip;
3240}
3241
Tony-LunarGd36f5f32022-01-20 11:49:59 -07003242bool BestPractices::PreCallValidateCmdResolveImage2(VkCommandBuffer commandBuffer,
3243 const VkResolveImageInfo2* pResolveImageInfo) const {
3244 bool skip = false;
3245
3246 skip |= VendorCheckEnabled(kBPVendorArm) &&
3247 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2_ResolvingImage,
3248 "%s Attempting to use vkCmdResolveImage2 to resolve a multisampled image. "
3249 "This is a very slow and extremely bandwidth intensive path. "
3250 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
3251 VendorSpecificTag(kBPVendorArm));
3252
3253 return skip;
3254}
3255
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003256void BestPractices::PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3257 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3258 const VkImageResolve* pRegions) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07003259 auto cb = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003260 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003261 auto* src = GetImageUsageState(srcImage);
3262 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003263
3264 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003265 QueueValidateImage(funcs, "vkCmdResolveImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pRegions[i].srcSubresource);
3266 QueueValidateImage(funcs, "vkCmdResolveImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003267 }
3268}
3269
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01003270void BestPractices::PreCallRecordCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
3271 const VkResolveImageInfo2KHR* pResolveImageInfo) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07003272 auto cb = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003273 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003274 auto* src = GetImageUsageState(pResolveImageInfo->srcImage);
3275 auto* dst = GetImageUsageState(pResolveImageInfo->dstImage);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01003276 uint32_t regionCount = pResolveImageInfo->regionCount;
3277
3278 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003279 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pResolveImageInfo->pRegions[i].srcSubresource);
3280 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pResolveImageInfo->pRegions[i].dstSubresource);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01003281 }
3282}
3283
Tony-LunarGd36f5f32022-01-20 11:49:59 -07003284void BestPractices::PreCallRecordCmdResolveImage2(VkCommandBuffer commandBuffer,
3285 const VkResolveImageInfo2* pResolveImageInfo) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07003286 auto cb = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Tony-LunarGd36f5f32022-01-20 11:49:59 -07003287 auto& funcs = cb->queue_submit_functions;
3288 auto* src = GetImageUsageState(pResolveImageInfo->srcImage);
3289 auto* dst = GetImageUsageState(pResolveImageInfo->dstImage);
3290 uint32_t regionCount = pResolveImageInfo->regionCount;
3291
3292 for (uint32_t i = 0; i < regionCount; i++) {
3293 QueueValidateImage(funcs, "vkCmdResolveImage2()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ,
3294 pResolveImageInfo->pRegions[i].srcSubresource);
3295 QueueValidateImage(funcs, "vkCmdResolveImage2()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE,
3296 pResolveImageInfo->pRegions[i].dstSubresource);
3297 }
3298}
3299
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003300void BestPractices::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
3301 const VkClearColorValue* pColor, uint32_t rangeCount,
3302 const VkImageSubresourceRange* pRanges) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07003303 auto cb = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003304 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003305 auto* dst = GetImageUsageState(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003306
3307 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003308 QueueValidateImage(funcs, "vkCmdClearColorImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003309 }
3310}
3311
3312void BestPractices::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
3313 const VkClearDepthStencilValue* pDepthStencil, uint32_t rangeCount,
3314 const VkImageSubresourceRange* pRanges) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07003315 auto cb = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003316 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003317 auto* dst = GetImageUsageState(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003318
3319 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003320 QueueValidateImage(funcs, "vkCmdClearDepthStencilImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003321 }
3322}
3323
3324void BestPractices::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3325 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3326 const VkImageCopy* pRegions) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07003327 auto cb = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003328 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003329 auto* src = GetImageUsageState(srcImage);
3330 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003331
3332 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003333 QueueValidateImage(funcs, "vkCmdCopyImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].srcSubresource);
3334 QueueValidateImage(funcs, "vkCmdCopyImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003335 }
3336}
3337
3338void BestPractices::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
3339 VkImageLayout dstImageLayout, uint32_t regionCount,
3340 const VkBufferImageCopy* pRegions) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07003341 auto cb = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003342 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003343 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003344
3345 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003346 QueueValidateImage(funcs, "vkCmdCopyBufferToImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003347 }
3348}
3349
3350void BestPractices::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3351 VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy* pRegions) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07003352 auto cb = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003353 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003354 auto* src = GetImageUsageState(srcImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003355
3356 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003357 QueueValidateImage(funcs, "vkCmdCopyImageToBuffer()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003358 }
3359}
3360
3361void BestPractices::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3362 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3363 const VkImageBlit* pRegions, VkFilter filter) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07003364 auto cb = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003365 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003366 auto* src = GetImageUsageState(srcImage);
3367 auto* dst = GetImageUsageState(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, "vkCmdBlitImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_READ, pRegions[i].srcSubresource);
3371 QueueValidateImage(funcs, "vkCmdBlitImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003372 }
3373}
3374
Attilio Provenzano02859b22020-02-27 14:17:28 +00003375bool BestPractices::PreCallValidateCreateSampler(VkDevice device, const VkSamplerCreateInfo* pCreateInfo,
3376 const VkAllocationCallbacks* pAllocator, VkSampler* pSampler) const {
3377 bool skip = false;
3378
3379 if (VendorCheckEnabled(kBPVendorArm)) {
3380 if ((pCreateInfo->addressModeU != pCreateInfo->addressModeV) || (pCreateInfo->addressModeV != pCreateInfo->addressModeW)) {
3381 skip |= LogPerformanceWarning(
3382 device, kVUID_BestPractices_CreateSampler_DifferentWrappingModes,
3383 "%s Creating a sampler object with wrapping modes which do not match (U = %u, V = %u, W = %u). "
3384 "This may cause reduced performance even if only U (1D image) or U/V wrapping modes (2D "
3385 "image) are actually used. If you need different wrapping modes, disregard this warning.",
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -06003386 VendorSpecificTag(kBPVendorArm), pCreateInfo->addressModeU, pCreateInfo->addressModeV, pCreateInfo->addressModeW);
Attilio Provenzano02859b22020-02-27 14:17:28 +00003387 }
3388
3389 if ((pCreateInfo->minLod != 0.0f) || (pCreateInfo->maxLod < VK_LOD_CLAMP_NONE)) {
3390 skip |= LogPerformanceWarning(
3391 device, kVUID_BestPractices_CreateSampler_LodClamping,
3392 "%s Creating a sampler object with LOD clamping (minLod = %f, maxLod = %f). This may cause reduced performance. "
3393 "Instead of clamping LOD in the sampler, consider using an VkImageView which restricts the mip-levels, set minLod "
3394 "to 0.0, and maxLod to VK_LOD_CLAMP_NONE.",
3395 VendorSpecificTag(kBPVendorArm), pCreateInfo->minLod, pCreateInfo->maxLod);
3396 }
3397
3398 if (pCreateInfo->mipLodBias != 0.0f) {
3399 skip |=
3400 LogPerformanceWarning(device, kVUID_BestPractices_CreateSampler_LodBias,
3401 "%s Creating a sampler object with LOD bias != 0.0 (%f). This will lead to less efficient "
3402 "descriptors being created and may cause reduced performance.",
3403 VendorSpecificTag(kBPVendorArm), pCreateInfo->mipLodBias);
3404 }
3405
3406 if ((pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
3407 pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
3408 pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER) &&
3409 (pCreateInfo->borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK)) {
3410 skip |= LogPerformanceWarning(
3411 device, kVUID_BestPractices_CreateSampler_BorderClampColor,
3412 "%s Creating a sampler object with border clamping and borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK. "
3413 "This will lead to less efficient descriptors being created and may cause reduced performance. "
3414 "If possible, use VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK as the border color.",
3415 VendorSpecificTag(kBPVendorArm));
3416 }
3417
3418 if (pCreateInfo->unnormalizedCoordinates) {
3419 skip |= LogPerformanceWarning(
3420 device, kVUID_BestPractices_CreateSampler_UnnormalizedCoordinates,
3421 "%s Creating a sampler object with unnormalized coordinates. This will lead to less efficient "
3422 "descriptors being created and may cause reduced performance.",
3423 VendorSpecificTag(kBPVendorArm));
3424 }
3425
3426 if (pCreateInfo->anisotropyEnable) {
3427 skip |= LogPerformanceWarning(
3428 device, kVUID_BestPractices_CreateSampler_Anisotropy,
3429 "%s Creating a sampler object with anisotropy. This will lead to less efficient descriptors being created "
3430 "and may cause reduced performance.",
3431 VendorSpecificTag(kBPVendorArm));
3432 }
3433 }
3434
3435 return skip;
3436}
Sam Walls8e77e4f2020-03-16 20:47:40 +00003437
Nadav Gevaf0808442021-05-21 13:51:25 -04003438void BestPractices::PreCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
3439 const VkGraphicsPipelineCreateInfo* pCreateInfos,
3440 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
3441 void* cgpl_state) {
3442 ValidationStateTracker::PreCallRecordCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos, pAllocator,
3443 pPipelines);
3444 // AMD best practice
3445 num_pso += createInfoCount;
3446}
3447
3448bool BestPractices::PreCallValidateUpdateDescriptorSets(VkDevice device, uint32_t descriptorWriteCount,
3449 const VkWriteDescriptorSet* pDescriptorWrites, uint32_t descriptorCopyCount,
3450 const VkCopyDescriptorSet* pDescriptorCopies) const {
3451 bool skip = false;
3452 if (VendorCheckEnabled(kBPVendorAMD)) {
3453 if (descriptorCopyCount > 0) {
3454 skip |= LogPerformanceWarning(device, kVUID_BestPractices_UpdateDescriptors_AvoidCopyingDescriptors,
3455 "%s Performance warning: copying descriptor sets is not recommended",
3456 VendorSpecificTag(kBPVendorAMD));
3457 }
3458 }
3459
3460 return skip;
3461}
3462
3463bool BestPractices::PreCallValidateCreateDescriptorUpdateTemplate(VkDevice device,
3464 const VkDescriptorUpdateTemplateCreateInfo* pCreateInfo,
3465 const VkAllocationCallbacks* pAllocator,
3466 VkDescriptorUpdateTemplate* pDescriptorUpdateTemplate) const {
3467 bool skip = false;
3468 if (VendorCheckEnabled(kBPVendorAMD)) {
3469 skip |= LogPerformanceWarning(device, kVUID_BestPractices_UpdateDescriptors_PreferNonTemplate,
3470 "%s Performance warning: using DescriptorSetWithTemplate is not recommended. Prefer using "
3471 "vkUpdateDescriptorSet instead",
3472 VendorSpecificTag(kBPVendorAMD));
3473 }
3474
3475 return skip;
3476}
3477
3478bool BestPractices::PreCallValidateCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
3479 const VkClearColorValue* pColor, uint32_t rangeCount,
3480 const VkImageSubresourceRange* pRanges) const {
3481 bool skip = false;
3482 if (VendorCheckEnabled(kBPVendorAMD)) {
sfricke-samsungef15e482022-01-26 11:32:49 -08003483 skip |= LogPerformanceWarning(
3484 device, kVUID_BestPractices_ClearAttachment_ClearImage,
Nadav Gevaf0808442021-05-21 13:51:25 -04003485 "%s Performance warning: using vkCmdClearColorImage is not recommended. Prefer using LOAD_OP_CLEAR or "
3486 "vkCmdClearAttachments instead",
3487 VendorSpecificTag(kBPVendorAMD));
3488 }
3489
3490 return skip;
3491}
3492
3493bool BestPractices::PreCallValidateCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image,
3494 VkImageLayout imageLayout,
3495 const VkClearDepthStencilValue* pDepthStencil, uint32_t rangeCount,
3496 const VkImageSubresourceRange* pRanges) const {
3497 bool skip = false;
3498 if (VendorCheckEnabled(kBPVendorAMD)) {
3499 skip |= LogPerformanceWarning(
3500 device, kVUID_BestPractices_ClearAttachment_ClearImage,
3501 "%s Performance warning: using vkCmdClearDepthStencilImage is not recommended. Prefer using LOAD_OP_CLEAR or "
3502 "vkCmdClearAttachments instead",
3503 VendorSpecificTag(kBPVendorAMD));
3504 }
3505
3506 return skip;
3507}
3508
3509bool BestPractices::PreCallValidateCreatePipelineLayout(VkDevice device, const VkPipelineLayoutCreateInfo* pCreateInfo,
3510 const VkAllocationCallbacks* pAllocator,
3511 VkPipelineLayout* pPipelineLayout) const {
3512 bool skip = false;
3513 if (VendorCheckEnabled(kBPVendorAMD)) {
3514 // Descriptor sets cost 1 DWORD each.
3515 // Dynamic buffers cost 2 DWORDs each when robust buffer access is OFF.
3516 // Dynamic buffers cost 4 DWORDs each when robust buffer access is ON.
3517 // Push constants cost 1 DWORD per 4 bytes in the Push constant range.
3518 uint32_t pipeline_size = pCreateInfo->setLayoutCount; // in DWORDS
3519 for (uint32_t i = 0; i < pCreateInfo->setLayoutCount; i++) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06003520 auto descriptor_set_layout_state = Get<cvdescriptorset::DescriptorSetLayout>(pCreateInfo->pSetLayouts[i]);
Nadav Gevaf0808442021-05-21 13:51:25 -04003521 pipeline_size += descriptor_set_layout_state->GetDynamicDescriptorCount() * (robust_buffer_access ? 4 : 2);
3522 }
3523
3524 for (uint32_t i = 0; i < pCreateInfo->pushConstantRangeCount; i++) {
3525 pipeline_size += pCreateInfo->pPushConstantRanges[i].size / 4;
3526 }
3527
3528 if (pipeline_size > kPipelineLayoutSizeWarningLimitAMD) {
3529 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelinesLayout_KeepLayoutSmall,
3530 "%s Performance warning: pipeline layout size is too large. Prefer smaller pipeline layouts."
3531 "Descriptor sets cost 1 DWORD each. "
3532 "Dynamic buffers cost 2 DWORDs each when robust buffer access is OFF. "
3533 "Dynamic buffers cost 4 DWORDs each when robust buffer access is ON. "
3534 "Push constants cost 1 DWORD per 4 bytes in the Push constant range. ",
3535 VendorSpecificTag(kBPVendorAMD));
3536 }
3537 }
3538
3539 return skip;
3540}
3541
3542bool BestPractices::PreCallValidateCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3543 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3544 const VkImageCopy* pRegions) const {
3545 bool skip = false;
3546 std::stringstream src_image_hex;
3547 std::stringstream dst_image_hex;
3548 src_image_hex << "0x" << std::hex << HandleToUint64(srcImage);
3549 dst_image_hex << "0x" << std::hex << HandleToUint64(dstImage);
3550
3551 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07003552 auto src_state = Get<IMAGE_STATE>(srcImage);
3553 auto dst_state = Get<IMAGE_STATE>(dstImage);
Nadav Gevaf0808442021-05-21 13:51:25 -04003554
3555 if (src_state && dst_state) {
3556 VkImageTiling src_Tiling = src_state->createInfo.tiling;
3557 VkImageTiling dst_Tiling = dst_state->createInfo.tiling;
3558 if (src_Tiling != dst_Tiling && (src_Tiling == VK_IMAGE_TILING_LINEAR || dst_Tiling == VK_IMAGE_TILING_LINEAR)) {
3559 skip |=
3560 LogPerformanceWarning(device, kVUID_BestPractices_vkImage_AvoidImageToImageCopy,
3561 "%s Performance warning: image %s and image %s have differing tilings. Use buffer to "
3562 "image (vkCmdCopyImageToBuffer) "
3563 "and image to buffer (vkCmdCopyBufferToImage) copies instead of image to image "
3564 "copies when converting between linear and optimal images",
3565 VendorSpecificTag(kBPVendorAMD), src_image_hex.str().c_str(), dst_image_hex.str().c_str());
3566 }
3567 }
3568 }
3569
3570 return skip;
3571}
3572
3573bool BestPractices::PreCallValidateCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
3574 VkPipeline pipeline) const {
3575 bool skip = false;
3576
3577 if (VendorCheckEnabled(kBPVendorAMD)) {
3578 if (pipelines_used_in_frame.find(pipeline) != pipelines_used_in_frame.end()) {
3579 skip |= LogPerformanceWarning(device, kVUID_BestPractices_Pipeline_SortAndBind,
3580 "%s Performance warning: Pipeline %s was bound twice in the frame. Keep pipeline state changes to a minimum,"
3581 "for example, by sorting draw calls by pipeline.",
3582 VendorSpecificTag(kBPVendorAMD), report_data->FormatHandle(pipeline).c_str());
3583 }
3584 }
3585
3586 return skip;
3587}
3588
3589void BestPractices::ManualPostCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
3590 VkFence fence, VkResult result) {
3591 // AMD best practice
3592 num_queue_submissions += submitCount;
3593}
3594
3595bool BestPractices::PreCallValidateQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo) const {
3596 bool skip = false;
3597
3598 if (VendorCheckEnabled(kBPVendorAMD)) {
3599 if (num_queue_submissions > kNumberOfSubmissionWarningLimitAMD) {
3600 skip |= LogPerformanceWarning(
3601 device, kVUID_BestPractices_Submission_ReduceNumberOfSubmissions,
3602 "%s Performance warning: command buffers submitted %" PRId32 " times this frame. Submitting command buffers has a CPU "
3603 "and GPU overhead. Submit fewer times to incur less overhead.",
3604 VendorSpecificTag(kBPVendorAMD), num_queue_submissions);
3605 }
3606 }
3607
3608 return skip;
3609}
3610
3611void BestPractices::PostCallRecordCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
3612 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
3613 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
3614 uint32_t bufferMemoryBarrierCount,
3615 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
3616 uint32_t imageMemoryBarrierCount,
3617 const VkImageMemoryBarrier* pImageMemoryBarriers) {
3618 num_barriers_objects += memoryBarrierCount;
3619 num_barriers_objects += imageMemoryBarrierCount;
3620 num_barriers_objects += bufferMemoryBarrierCount;
3621}
3622
3623void BestPractices::ManualPostCallRecordCreateFence(VkDevice device, const VkFenceCreateInfo* pCreateInfo,
3624 const VkAllocationCallbacks* pAllocator, VkFence* pFence, VkResult result) {
3625 // AMD best practice
3626 if (result == VK_SUCCESS) {
3627 num_fence_objects++;
3628 }
3629}
3630
3631void BestPractices::ManualPostCallRecordCreateSemaphore(VkDevice device, const VkSemaphoreCreateInfo* pCreateInfo,
3632 const VkAllocationCallbacks* pAllocator, VkSemaphore* pSemaphore,
3633 VkResult result) {
3634 // AMD best practice
3635 if (result == VK_SUCCESS) {
3636 num_semaphore_objects++;
3637 }
3638}
3639
3640bool BestPractices::PreCallValidateCreateSemaphore(VkDevice device, const VkSemaphoreCreateInfo* pCreateInfo,
3641 const VkAllocationCallbacks* pAllocator, VkSemaphore* pSemaphore) const {
3642 bool skip = false;
3643 if (VendorCheckEnabled(kBPVendorAMD)) {
3644 if (num_semaphore_objects > kMaxRecommendedSemaphoreObjectsSizeAMD) {
3645 skip |= LogPerformanceWarning(device, kVUID_BestPractices_SyncObjects_HighNumberOfSemaphores,
3646 "%s Performance warning: High number of vkSemaphore objects created."
3647 "Minimize the amount of queue synchronization that is used. "
3648 "Semaphores and fences have overhead. Each fence has a CPU and GPU cost with it.",
3649 VendorSpecificTag(kBPVendorAMD));
3650 }
3651 }
3652
3653 return skip;
3654}
3655
3656bool BestPractices::PreCallValidateCreateFence(VkDevice device, const VkFenceCreateInfo* pCreateInfo,
3657 const VkAllocationCallbacks* pAllocator, VkFence* pFence) const {
3658 bool skip = false;
3659 if (VendorCheckEnabled(kBPVendorAMD)) {
3660 if (num_fence_objects > kMaxRecommendedFenceObjectsSizeAMD) {
3661 skip |= LogPerformanceWarning(device, kVUID_BestPractices_SyncObjects_HighNumberOfFences,
3662 "%s Performance warning: High number of VkFence objects created."
3663 "Minimize the amount of CPU-GPU synchronization that is used. "
3664 "Semaphores and fences have overhead.Each fence has a CPU and GPU cost with it.",
3665 VendorSpecificTag(kBPVendorAMD));
3666 }
3667 }
3668
3669 return skip;
3670}
3671
Sam Walls8e77e4f2020-03-16 20:47:40 +00003672void BestPractices::PostTransformLRUCacheModel::resize(size_t size) { _entries.resize(size); }
3673
3674bool BestPractices::PostTransformLRUCacheModel::query_cache(uint32_t value) {
3675 // look for a cache hit
3676 auto hit = std::find_if(_entries.begin(), _entries.end(), [value](const CacheEntry& entry) { return entry.value == value; });
3677 if (hit != _entries.end()) {
3678 // mark the cache hit as being most recently used
3679 hit->age = iteration++;
3680 return true;
3681 }
3682
3683 // if there's no cache hit, we need to model the entry being inserted into the cache
3684 CacheEntry new_entry = {value, iteration};
3685 if (iteration < static_cast<uint32_t>(std::distance(_entries.begin(), _entries.end()))) {
3686 // if there is still space left in the cache, use the next available slot
3687 *(_entries.begin() + iteration) = new_entry;
3688 } else {
3689 // otherwise replace the least recently used cache entry
3690 auto lru = std::min_element(_entries.begin(), hit, [](const CacheEntry& a, const CacheEntry& b) { return a.age < b.age; });
3691 *lru = new_entry;
3692 }
3693 iteration++;
3694 return false;
3695}
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003696
3697bool BestPractices::PreCallValidateAcquireNextImageKHR(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout,
3698 VkSemaphore semaphore, VkFence fence, uint32_t* pImageIndex) const {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07003699 auto swapchain_data = Get<SWAPCHAIN_NODE>(swapchain);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003700 bool skip = false;
3701 if (swapchain_data && swapchain_data->images.size() == 0) {
3702 skip |= LogWarning(swapchain, kVUID_Core_DrawState_SwapchainImagesNotFound,
3703 "vkAcquireNextImageKHR: No images found to acquire from. Application probably did not call "
3704 "vkGetSwapchainImagesKHR after swapchain creation.");
3705 }
3706 return skip;
3707}
3708
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003709void BestPractices::CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(CALL_STATE& call_state, bool no_pointer) {
3710 if (no_pointer) {
3711 if (UNCALLED == call_state) {
3712 call_state = QUERY_COUNT;
3713 }
3714 } else { // Save queue family properties
3715 call_state = QUERY_DETAILS;
3716 }
3717}
3718
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003719void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
3720 uint32_t* pQueueFamilyPropertyCount,
3721 VkQueueFamilyProperties* pQueueFamilyProperties) {
3722 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(physicalDevice, pQueueFamilyPropertyCount,
3723 pQueueFamilyProperties);
Jeremy Gebben78684b12022-02-23 17:31:56 -07003724 auto bp_pd_state = Get<PHYSICAL_DEVICE_STATE_BP>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003725 if (bp_pd_state) {
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003726 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
3727 nullptr == pQueueFamilyProperties);
3728 }
3729}
3730
3731void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
3732 uint32_t* pQueueFamilyPropertyCount,
3733 VkQueueFamilyProperties2* pQueueFamilyProperties) {
3734 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(physicalDevice, pQueueFamilyPropertyCount,
3735 pQueueFamilyProperties);
Jeremy Gebben78684b12022-02-23 17:31:56 -07003736 auto bp_pd_state = Get<PHYSICAL_DEVICE_STATE_BP>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003737 if (bp_pd_state) {
3738 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
3739 nullptr == pQueueFamilyProperties);
3740 }
3741}
3742
3743void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(VkPhysicalDevice physicalDevice,
3744 uint32_t* pQueueFamilyPropertyCount,
3745 VkQueueFamilyProperties2* pQueueFamilyProperties) {
3746 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(physicalDevice, pQueueFamilyPropertyCount,
3747 pQueueFamilyProperties);
Jeremy Gebben78684b12022-02-23 17:31:56 -07003748 auto bp_pd_state = Get<PHYSICAL_DEVICE_STATE_BP>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003749 if (bp_pd_state) {
3750 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
3751 nullptr == pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003752 }
3753}
3754
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003755void BestPractices::PostCallRecordGetPhysicalDeviceFeatures(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures* pFeatures) {
3756 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures(physicalDevice, pFeatures);
Jeremy Gebben78684b12022-02-23 17:31:56 -07003757 auto bp_pd_state = Get<PHYSICAL_DEVICE_STATE_BP>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003758 if (bp_pd_state) {
3759 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3760 }
3761}
3762
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003763void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2(VkPhysicalDevice physicalDevice,
3764 VkPhysicalDeviceFeatures2* pFeatures) {
3765 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2(physicalDevice, pFeatures);
Jeremy Gebben78684b12022-02-23 17:31:56 -07003766 auto bp_pd_state = Get<PHYSICAL_DEVICE_STATE_BP>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003767 if (bp_pd_state) {
3768 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3769 }
3770}
3771
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003772void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2KHR(VkPhysicalDevice physicalDevice,
3773 VkPhysicalDeviceFeatures2* pFeatures) {
3774 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2KHR(physicalDevice, pFeatures);
Jeremy Gebben78684b12022-02-23 17:31:56 -07003775 auto bp_pd_state = Get<PHYSICAL_DEVICE_STATE_BP>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003776 if (bp_pd_state) {
3777 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3778 }
3779}
3780
3781void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilitiesKHR(VkPhysicalDevice physicalDevice,
3782 VkSurfaceKHR surface,
3783 VkSurfaceCapabilitiesKHR* pSurfaceCapabilities,
3784 VkResult result) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07003785 auto bp_pd_state = Get<PHYSICAL_DEVICE_STATE_BP>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003786 if (bp_pd_state) {
3787 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3788 }
3789}
3790
3791void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2KHR(
3792 VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
3793 VkSurfaceCapabilities2KHR* pSurfaceCapabilities, VkResult result) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07003794 auto bp_pd_state = Get<PHYSICAL_DEVICE_STATE_BP>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003795 if (bp_pd_state) {
3796 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3797 }
3798}
3799
3800void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2EXT(VkPhysicalDevice physicalDevice,
3801 VkSurfaceKHR surface,
3802 VkSurfaceCapabilities2EXT* pSurfaceCapabilities,
3803 VkResult result) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07003804 auto bp_pd_state = Get<PHYSICAL_DEVICE_STATE_BP>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003805 if (bp_pd_state) {
3806 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3807 }
3808}
3809
3810void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice physicalDevice,
3811 VkSurfaceKHR surface, uint32_t* pPresentModeCount,
3812 VkPresentModeKHR* pPresentModes, VkResult result) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07003813 auto bp_pd_data = Get<PHYSICAL_DEVICE_STATE_BP>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003814 if (bp_pd_data) {
3815 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfacePresentModesKHRState;
3816
3817 if (*pPresentModeCount) {
3818 if (call_state < QUERY_COUNT) {
3819 call_state = QUERY_COUNT;
3820 }
3821 }
3822 if (pPresentModes) {
3823 if (call_state < QUERY_DETAILS) {
3824 call_state = QUERY_DETAILS;
3825 }
3826 }
3827 }
3828}
3829
3830void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
3831 uint32_t* pSurfaceFormatCount,
3832 VkSurfaceFormatKHR* pSurfaceFormats, VkResult result) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07003833 auto bp_pd_data = Get<PHYSICAL_DEVICE_STATE_BP>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003834 if (bp_pd_data) {
3835 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState;
3836
3837 if (*pSurfaceFormatCount) {
3838 if (call_state < QUERY_COUNT) {
3839 call_state = QUERY_COUNT;
3840 }
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06003841 bp_pd_data->surface_formats_count = *pSurfaceFormatCount;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003842 }
3843 if (pSurfaceFormats) {
3844 if (call_state < QUERY_DETAILS) {
3845 call_state = QUERY_DETAILS;
3846 }
3847 }
3848 }
3849}
3850
3851void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormats2KHR(VkPhysicalDevice physicalDevice,
3852 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
3853 uint32_t* pSurfaceFormatCount,
3854 VkSurfaceFormat2KHR* pSurfaceFormats, VkResult result) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07003855 auto bp_pd_data = Get<PHYSICAL_DEVICE_STATE_BP>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003856 if (bp_pd_data) {
3857 if (*pSurfaceFormatCount) {
3858 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_COUNT) {
3859 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = 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 (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_DETAILS) {
3865 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_DETAILS;
3866 }
3867 }
3868 }
3869}
3870
3871void BestPractices::ManualPostCallRecordGetPhysicalDeviceDisplayPlanePropertiesKHR(VkPhysicalDevice physicalDevice,
3872 uint32_t* pPropertyCount,
3873 VkDisplayPlanePropertiesKHR* pProperties,
3874 VkResult result) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07003875 auto bp_pd_data = Get<PHYSICAL_DEVICE_STATE_BP>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003876 if (bp_pd_data) {
3877 if (*pPropertyCount) {
3878 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_COUNT) {
3879 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_COUNT;
3880 }
3881 }
3882 if (pProperties) {
3883 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_DETAILS) {
3884 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_DETAILS;
3885 }
3886 }
3887 }
3888}
3889
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003890void BestPractices::ManualPostCallRecordGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain,
3891 uint32_t* pSwapchainImageCount, VkImage* pSwapchainImages,
3892 VkResult result) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07003893 auto swapchain_state = Get<SWAPCHAIN_STATE_BP>(swapchain);
Nathaniel Cesario39152e62021-07-02 13:04:16 -06003894 if (swapchain_state && (pSwapchainImages || *pSwapchainImageCount)) {
3895 if (swapchain_state->vkGetSwapchainImagesKHRState < QUERY_DETAILS) {
3896 swapchain_state->vkGetSwapchainImagesKHRState = QUERY_DETAILS;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003897 }
3898 }
3899}
3900
Nadav Gevaf0808442021-05-21 13:51:25 -04003901void BestPractices::ManualPostCallRecordCreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo* pCreateInfo,
3902 const VkAllocationCallbacks* pAllocator, VkDevice* pDevice, VkResult result) {
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003903 if (VK_SUCCESS == result) {
Nadav Gevaf0808442021-05-21 13:51:25 -04003904 if ((pCreateInfo->pEnabledFeatures != nullptr) && (pCreateInfo->pEnabledFeatures->robustBufferAccess == VK_TRUE)) {
3905 robust_buffer_access = true;
3906 }
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003907 }
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003908}
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003909
3910void BestPractices::PreCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits, VkFence fence) {
3911 ValidationStateTracker::PreCallRecordQueueSubmit(queue, submitCount, pSubmits, fence);
3912
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06003913 auto queue_state = Get<QUEUE_STATE>(queue);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003914 for (uint32_t submit = 0; submit < submitCount; submit++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02003915 const auto& submit_info = pSubmits[submit];
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003916 for (uint32_t cb_index = 0; cb_index < submit_info.commandBufferCount; cb_index++) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07003917 auto cb = Get<CMD_BUFFER_STATE_BP>(submit_info.pCommandBuffers[cb_index]);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003918 for (auto &func : cb->queue_submit_functions) {
Jeremy Gebbene5361dd2021-11-18 14:23:56 -07003919 func(*this, *queue_state, *cb);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003920 }
3921 }
3922 }
3923}