blob: eea73c00110fb20b9d0fa30ab430a5c86290c8b7 [file] [log] [blame]
Gareth Webbdc6549a2021-06-16 03:52:24 +01001/* Copyright (c) 2015-2021 The Khronos Group Inc.
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002 * Copyright (c) 2015-2021 Valve Corporation
3 * Copyright (c) 2015-2021 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,
63 std::shared_ptr<COMMAND_POOL_STATE>& pool) {
64 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,
68 std::shared_ptr<COMMAND_POOL_STATE>& pool)
69 : 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)) ||
133 ((dep_info.target.compare("VK_VERSION_1_2") == 0) && (version >= VK_API_VERSION_1_2))) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700134 skip |=
135 LogWarning(instance, vuid, "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
136 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
Mark Lobodzinski6a149702020-05-14 12:21:34 -0600137 } else if (dep_info.target.find("VK_VERSION") == std::string::npos) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700138 if (dep_info.target.length() == 0) {
139 skip |= LogWarning(instance, vuid,
140 "%s(): Attempting to enable deprecated extension %s, but this extension has been deprecated "
141 "without replacement.",
142 api_name, extension_name);
143 } else {
144 skip |= LogWarning(instance, vuid,
145 "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
146 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
147 }
148 }
149 }
150 return skip;
151}
152
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200153bool BestPractices::ValidateSpecialUseExtensions(const char* api_name, const char* extension_name, const SpecialUseVUIDs& special_use_vuids) const
154{
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700155 bool skip = false;
156 auto dep_info_it = special_use_extensions.find(extension_name);
157
158 if (dep_info_it != special_use_extensions.end()) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200159 const char* const format = "%s(): Attempting to enable extension %s, but this extension is intended to support %s "
160 "and it is strongly recommended that it be otherwise avoided.";
161 auto& special_uses = dep_info_it->second;
162
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700163 if (special_uses.find("cadsupport") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200164 skip |= LogWarning(instance, special_use_vuids.cadsupport, format, api_name, extension_name,
165 "specialized functionality used by CAD/CAM applications");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700166 }
167 if (special_uses.find("d3demulation") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200168 skip |= LogWarning(instance, special_use_vuids.d3demulation, format, api_name, extension_name,
169 "D3D emulation layers, and applications ported from D3D, by adding functionality specific to D3D");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700170 }
171 if (special_uses.find("devtools") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200172 skip |= LogWarning(instance, special_use_vuids.devtools, format, api_name, extension_name,
173 "developer tools such as capture-replay libraries");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700174 }
175 if (special_uses.find("debugging") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200176 skip |= LogWarning(instance, special_use_vuids.debugging, format, api_name, extension_name,
177 "use by applications when debugging");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700178 }
179 if (special_uses.find("glemulation") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200180 skip |= LogWarning(instance, special_use_vuids.glemulation, format, api_name, extension_name,
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700181 "OpenGL and/or OpenGL ES emulation layers, and applications ported from those APIs, by adding functionality "
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200182 "specific to those APIs");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700183 }
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700184 }
185 return skip;
186}
187
Nadav Gevaf0808442021-05-21 13:51:25 -0400188void BestPractices::InitDeviceValidationObject(bool add_obj, ValidationObject* inst_obj, ValidationObject* dev_obj) {
189 if (add_obj) {
190 ValidationStateTracker::InitDeviceValidationObject(add_obj, inst_obj, dev_obj);
191 }
192}
193
194
Camden5b184be2019-08-13 07:50:19 -0600195bool BestPractices::PreCallValidateCreateInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500196 VkInstance* pInstance) const {
Camden5b184be2019-08-13 07:50:19 -0600197 bool skip = false;
198
199 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
200 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kDeviceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800201 skip |= LogWarning(instance, kVUID_BestPractices_CreateInstance_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700202 "vkCreateInstance(): Attempting to enable Device Extension %s at CreateInstance time.",
203 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600204 }
Mark Lobodzinski17d8dc62020-06-03 08:48:58 -0600205 uint32_t specified_version =
206 (pCreateInfo->pApplicationInfo ? pCreateInfo->pApplicationInfo->apiVersion : VK_API_VERSION_1_0);
207 skip |= ValidateDeprecatedExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i], specified_version,
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700208 kVUID_BestPractices_CreateInstance_DeprecatedExtension);
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200209 skip |= ValidateSpecialUseExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i], kSpecialUseInstanceVUIDs);
Camden5b184be2019-08-13 07:50:19 -0600210 }
211
212 return skip;
213}
214
215void BestPractices::PreCallRecordCreateInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator,
216 VkInstance* pInstance) {
Mark Lobodzinski97484d62020-03-03 11:57:41 -0700217 ValidationStateTracker::PreCallRecordCreateInstance(pCreateInfo, pAllocator, pInstance);
Sam Walls53bf7652020-04-21 17:35:15 +0100218
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700219 if (pCreateInfo != nullptr && pCreateInfo->pApplicationInfo != nullptr) {
Sam Walls53bf7652020-04-21 17:35:15 +0100220 instance_api_version = pCreateInfo->pApplicationInfo->apiVersion;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700221 } else {
Sam Walls53bf7652020-04-21 17:35:15 +0100222 instance_api_version = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700223 }
Camden5b184be2019-08-13 07:50:19 -0600224}
225
226bool BestPractices::PreCallValidateCreateDevice(VkPhysicalDevice physicalDevice, const VkDeviceCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500227 const VkAllocationCallbacks* pAllocator, VkDevice* pDevice) const {
Camden5b184be2019-08-13 07:50:19 -0600228 bool skip = false;
229
230 // get API version of physical device passed when creating device.
231 VkPhysicalDeviceProperties physical_device_properties{};
232 DispatchGetPhysicalDeviceProperties(physicalDevice, &physical_device_properties);
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500233 auto device_api_version = physical_device_properties.apiVersion;
Camden5b184be2019-08-13 07:50:19 -0600234
235 // check api versions and warn if instance api Version is higher than version on device.
236 if (instance_api_version > device_api_version) {
Mark Lobodzinski60880782020-08-11 08:02:07 -0600237 std::string inst_api_name = StringAPIVersion(instance_api_version);
238 std::string dev_api_name = StringAPIVersion(device_api_version);
Camden5b184be2019-08-13 07:50:19 -0600239
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700240 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_API_Mismatch,
241 "vkCreateDevice(): API Version of current instance, %s is higher than API Version on device, %s",
242 inst_api_name.c_str(), dev_api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -0600243 }
244
245 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
246 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kInstanceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800247 skip |= LogWarning(instance, kVUID_BestPractices_CreateDevice_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700248 "vkCreateDevice(): Attempting to enable Instance Extension %s at CreateDevice time.",
249 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600250 }
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700251 skip |= ValidateDeprecatedExtensions("CreateDevice", pCreateInfo->ppEnabledExtensionNames[i], instance_api_version,
252 kVUID_BestPractices_CreateDevice_DeprecatedExtension);
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200253 skip |= ValidateSpecialUseExtensions("CreateDevice", pCreateInfo->ppEnabledExtensionNames[i], kSpecialUseDeviceVUIDs);
Camden5b184be2019-08-13 07:50:19 -0600254 }
255
Jeremy Gebben383b9a32021-09-08 16:31:33 -0600256 const auto bp_pd_state = GetPhysicalDeviceState(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600257 if ((bp_pd_state->vkGetPhysicalDeviceFeaturesState == UNCALLED) && (pCreateInfo->pEnabledFeatures != NULL)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700258 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_PDFeaturesNotCalled,
259 "vkCreateDevice() called before getting physical device features from vkGetPhysicalDeviceFeatures().");
Camden83a9c372019-08-14 11:41:38 -0600260 }
261
Nadav Gevaf0808442021-05-21 13:51:25 -0400262 if ((VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorAMD)) && (pCreateInfo->pEnabledFeatures != nullptr) &&
Szilard Papp7d2c7952020-06-22 14:38:13 +0100263 (pCreateInfo->pEnabledFeatures->robustBufferAccess == VK_TRUE)) {
264 skip |= LogPerformanceWarning(
265 device, kVUID_BestPractices_CreateDevice_RobustBufferAccess,
Nadav Gevaf0808442021-05-21 13:51:25 -0400266 "%s %s vkCreateDevice() called with enabled robustBufferAccess. Use robustBufferAccess as a debugging tool during "
Szilard Papp7d2c7952020-06-22 14:38:13 +0100267 "development. Enabling it causes loss in performance for accesses to uniform buffers and shader storage "
268 "buffers. Disable robustBufferAccess in release builds. Only leave it enabled if the application use-case "
269 "requires the additional level of reliability due to the use of unverified user-supplied draw parameters.",
Nadav Gevaf0808442021-05-21 13:51:25 -0400270 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorAMD));
Szilard Papp7d2c7952020-06-22 14:38:13 +0100271 }
272
Camden5b184be2019-08-13 07:50:19 -0600273 return skip;
274}
275
276bool BestPractices::PreCallValidateCreateBuffer(VkDevice device, const VkBufferCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500277 const VkAllocationCallbacks* pAllocator, VkBuffer* pBuffer) const {
Camden5b184be2019-08-13 07:50:19 -0600278 bool skip = false;
279
280 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700281 std::stringstream buffer_hex;
282 buffer_hex << "0x" << std::hex << HandleToUint64(pBuffer);
Camden5b184be2019-08-13 07:50:19 -0600283
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700284 skip |= LogWarning(
285 device, kVUID_BestPractices_SharingModeExclusive,
286 "Warning: Buffer (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
287 "(queueFamilyIndexCount of %" PRIu32 ").",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700288 buffer_hex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600289 }
290
291 return skip;
292}
293
294bool BestPractices::PreCallValidateCreateImage(VkDevice device, const VkImageCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500295 const VkAllocationCallbacks* pAllocator, VkImage* pImage) const {
Camden5b184be2019-08-13 07:50:19 -0600296 bool skip = false;
297
298 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700299 std::stringstream image_hex;
300 image_hex << "0x" << std::hex << HandleToUint64(pImage);
Camden5b184be2019-08-13 07:50:19 -0600301
302 skip |=
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700303 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
304 "Warning: Image (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
305 "(queueFamilyIndexCount of %" PRIu32 ").",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700306 image_hex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600307 }
308
Attilio Provenzano02859b22020-02-27 14:17:28 +0000309 if (VendorCheckEnabled(kBPVendorArm)) {
310 if (pCreateInfo->samples > kMaxEfficientSamplesArm) {
311 skip |= LogPerformanceWarning(
312 device, kVUID_BestPractices_CreateImage_TooLargeSampleCount,
313 "%s vkCreateImage(): Trying to create an image with %u samples. "
314 "The hardware revision may not have full throughput for framebuffers with more than %u samples.",
315 VendorSpecificTag(kBPVendorArm), static_cast<uint32_t>(pCreateInfo->samples), kMaxEfficientSamplesArm);
316 }
317
318 if (pCreateInfo->samples > VK_SAMPLE_COUNT_1_BIT && !(pCreateInfo->usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT)) {
319 skip |= LogPerformanceWarning(
320 device, kVUID_BestPractices_CreateImage_NonTransientMSImage,
321 "%s vkCreateImage(): Trying to create a multisampled image, but createInfo.usage did not have "
322 "VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. Multisampled images may be resolved on-chip, "
323 "and do not need to be backed by physical storage. "
324 "TRANSIENT_ATTACHMENT allows tiled GPUs to not back the multisampled image with physical memory.",
325 VendorSpecificTag(kBPVendorArm));
326 }
327 }
328
Nadav Gevaf0808442021-05-21 13:51:25 -0400329 if (VendorCheckEnabled(kBPVendorAMD)) {
330 std::stringstream image_hex;
331 image_hex << "0x" << std::hex << HandleToUint64(pImage);
332
333 if ((pCreateInfo->usage & (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) &&
334 (pCreateInfo->sharingMode == VK_SHARING_MODE_CONCURRENT)) {
335 skip |= LogPerformanceWarning(device,
336 kVUID_BestPractices_vkImage_AvoidConcurrentRenderTargets,
337 "%s Performance warning: image (%s) is created as a render target with VK_SHARING_MODE_CONCURRENT. "
338 "Using a SHARING_MODE_CONCURRENT "
339 "is not recommended with color and depth targets",
340 VendorSpecificTag(kBPVendorAMD), image_hex.str().c_str());
341 }
342
343 if ((pCreateInfo->usage &
344 (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) &&
345 (pCreateInfo->flags & VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT)) {
346 skip |= LogPerformanceWarning(device, kVUID_BestPractices_vkImage_DontUseMutableRenderTargets,
347 "%s Performance warning: image (%s) is created as a render target with VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT. "
348 "Using a MUTABLE_FORMAT is not recommended with color, depth, and storage targets",
349 VendorSpecificTag(kBPVendorAMD), image_hex.str().c_str());
350 }
351
352 if ((pCreateInfo->usage & (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) &&
353 (pCreateInfo->usage & VK_IMAGE_USAGE_STORAGE_BIT)) {
354 skip |= LogPerformanceWarning(device, kVUID_BestPractices_vkImage_DontUseStorageRenderTargets,
355 "%s Performance warning: image (%s) is created as a render target with VK_IMAGE_USAGE_STORAGE_BIT. Using a "
356 "VK_IMAGE_USAGE_STORAGE_BIT is not recommended with color and depth targets",
357 VendorSpecificTag(kBPVendorAMD), image_hex.str().c_str());
358 }
359 }
360
Camden5b184be2019-08-13 07:50:19 -0600361 return skip;
362}
363
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +0100364void BestPractices::PreCallRecordDestroyImage(VkDevice device, VkImage image, const VkAllocationCallbacks *pAllocator) {
365 ValidationStateTracker::PreCallRecordDestroyImage(device, image, pAllocator);
366 ReleaseImageUsageState(image);
367}
368
Hans-Kristian Arntzen92664eb2021-03-29 12:19:48 +0200369void BestPractices::PreCallRecordDestroySwapchainKHR(VkDevice device, VkSwapchainKHR swapchain, const VkAllocationCallbacks* pAllocator) {
Tony-LunarG299187b2021-05-28 09:29:12 -0600370 if (VK_NULL_HANDLE != swapchain) {
371 SWAPCHAIN_NODE* chain = GetSwapchainState(swapchain);
372 for (auto& image : chain->images) {
373 if (image.image_state) {
374 ReleaseImageUsageState(image.image_state->image());
375 }
376 }
Hans-Kristian Arntzen92664eb2021-03-29 12:19:48 +0200377 }
378 ValidationStateTracker::PreCallRecordDestroySwapchainKHR(device, swapchain, pAllocator);
379}
380
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +0100381IMAGE_STATE_BP* BestPractices::GetImageUsageState(VkImage vk_image) {
382 auto itr = imageUsageMap.find(vk_image);
383 if (itr != imageUsageMap.end()) {
384 return &itr->second;
385 } else {
386 auto& state = imageUsageMap[vk_image];
Nadav Gevaf0808442021-05-21 13:51:25 -0400387 IMAGE_STATE* image = Get<IMAGE_STATE>(vk_image);
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +0100388 state.image = image;
389 state.usages.resize(image->createInfo.arrayLayers);
390 for (auto& mips : state.usages) {
391 mips.resize(image->createInfo.mipLevels, IMAGE_SUBRESOURCE_USAGE_BP::UNDEFINED);
392 }
393 return &state;
394 }
395}
396
397void BestPractices::ReleaseImageUsageState(VkImage image) {
398 auto itr = imageUsageMap.find(image);
399 if (itr != imageUsageMap.end()) {
400 imageUsageMap.erase(itr);
401 }
402}
403
Camden5b184be2019-08-13 07:50:19 -0600404bool BestPractices::PreCallValidateCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500405 const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain) const {
Camden5b184be2019-08-13 07:50:19 -0600406 bool skip = false;
407
Jeremy Gebben383b9a32021-09-08 16:31:33 -0600408 const auto* bp_pd_state = GetPhysicalDeviceState();
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600409 if (bp_pd_state) {
410 if (bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState == UNCALLED) {
411 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
412 "vkCreateSwapchainKHR() called before getting surface capabilities from "
413 "vkGetPhysicalDeviceSurfaceCapabilitiesKHR().");
414 }
Camden83a9c372019-08-14 11:41:38 -0600415
Shannon McPherson73e58c82021-03-05 17:14:26 -0700416 if ((pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR) &&
417 (bp_pd_state->vkGetPhysicalDeviceSurfacePresentModesKHRState != QUERY_DETAILS)) {
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600418 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
419 "vkCreateSwapchainKHR() called before getting surface present mode(s) from "
420 "vkGetPhysicalDeviceSurfacePresentModesKHR().");
421 }
Camden83a9c372019-08-14 11:41:38 -0600422
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600423 if (bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState != QUERY_DETAILS) {
424 skip |= LogWarning(
425 device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
426 "vkCreateSwapchainKHR() called before getting surface format(s) from vkGetPhysicalDeviceSurfaceFormatsKHR().");
427 }
Camden83a9c372019-08-14 11:41:38 -0600428 }
429
Camden5b184be2019-08-13 07:50:19 -0600430 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700431 skip |=
432 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
Mark Lobodzinski019f4e32020-04-13 11:01:35 -0600433 "Warning: A Swapchain is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while "
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700434 "specifying multiple queues (queueFamilyIndexCount of %" PRIu32 ").",
435 pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600436 }
437
Szilard Papp48a6da32020-06-10 14:41:59 +0100438 if (pCreateInfo->minImageCount == 2) {
439 skip |= LogPerformanceWarning(
440 device, kVUID_BestPractices_SuboptimalSwapchainImageCount,
441 "Warning: A Swapchain is being created with minImageCount set to %" PRIu32
442 ", which means double buffering is going "
443 "to be used. Using double buffering and vsync locks rendering to an integer fraction of the vsync rate. In turn, "
444 "reducing the performance of the application if rendering is slower than vsync. Consider setting minImageCount to "
445 "3 to use triple buffering to maximize performance in such cases.",
446 pCreateInfo->minImageCount);
447 }
448
Szilard Pappd5f0f812020-06-22 09:01:29 +0100449 if (VendorCheckEnabled(kBPVendorArm) && (pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR)) {
450 skip |= LogWarning(device, kVUID_BestPractices_CreateSwapchain_PresentMode,
451 "%s Warning: Swapchain is not being created with presentation mode \"VK_PRESENT_MODE_FIFO_KHR\". "
452 "Prefer using \"VK_PRESENT_MODE_FIFO_KHR\" to avoid unnecessary CPU and GPU load and save power. "
453 "Presentation modes which are not FIFO will present the latest available frame and discard other "
454 "frame(s) if any.",
455 VendorSpecificTag(kBPVendorArm));
456 }
457
Camden5b184be2019-08-13 07:50:19 -0600458 return skip;
459}
460
461bool BestPractices::PreCallValidateCreateSharedSwapchainsKHR(VkDevice device, uint32_t swapchainCount,
462 const VkSwapchainCreateInfoKHR* pCreateInfos,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500463 const VkAllocationCallbacks* pAllocator,
464 VkSwapchainKHR* pSwapchains) const {
Camden5b184be2019-08-13 07:50:19 -0600465 bool skip = false;
466
467 for (uint32_t i = 0; i < swapchainCount; i++) {
468 if ((pCreateInfos[i].queueFamilyIndexCount > 1) && (pCreateInfos[i].imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700469 skip |= LogWarning(
470 device, kVUID_BestPractices_SharingModeExclusive,
471 "Warning: A shared swapchain (index %" PRIu32
472 ") is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple "
473 "queues (queueFamilyIndexCount of %" PRIu32 ").",
474 i, pCreateInfos[i].queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600475 }
476 }
477
478 return skip;
479}
480
481bool BestPractices::PreCallValidateCreateRenderPass(VkDevice device, const VkRenderPassCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500482 const VkAllocationCallbacks* pAllocator, VkRenderPass* pRenderPass) const {
Camden5b184be2019-08-13 07:50:19 -0600483 bool skip = false;
484
485 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; ++i) {
486 VkFormat format = pCreateInfo->pAttachments[i].format;
487 if (pCreateInfo->pAttachments[i].initialLayout == VK_IMAGE_LAYOUT_UNDEFINED) {
488 if ((FormatIsColor(format) || FormatHasDepth(format)) &&
489 pCreateInfo->pAttachments[i].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700490 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
491 "Render pass has an attachment with loadOp == VK_ATTACHMENT_LOAD_OP_LOAD and "
492 "initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
493 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
494 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600495 }
496 if (FormatHasStencil(format) && pCreateInfo->pAttachments[i].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700497 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
498 "Render pass has an attachment with stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD "
499 "and initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
500 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
501 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600502 }
503 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000504
505 const auto& attachment = pCreateInfo->pAttachments[i];
506 if (attachment.samples > VK_SAMPLE_COUNT_1_BIT) {
507 bool access_requires_memory =
508 attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD || attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE;
509
510 if (FormatHasStencil(format)) {
511 access_requires_memory |= attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
512 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE;
513 }
514
515 if (access_requires_memory) {
516 skip |= LogPerformanceWarning(
517 device, kVUID_BestPractices_CreateRenderPass_ImageRequiresMemory,
518 "Attachment %u in the VkRenderPass is a multisampled image with %u samples, but it uses loadOp/storeOp "
519 "which requires accessing data from memory. Multisampled images should always be loadOp = CLEAR or DONT_CARE, "
520 "storeOp = DONT_CARE. This allows the implementation to use lazily allocated memory effectively.",
521 i, static_cast<uint32_t>(attachment.samples));
522 }
523 }
Camden5b184be2019-08-13 07:50:19 -0600524 }
525
526 for (uint32_t dependency = 0; dependency < pCreateInfo->dependencyCount; dependency++) {
527 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].srcStageMask);
528 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].dstStageMask);
529 }
530
531 return skip;
532}
533
Tony-LunarG767180f2020-04-23 14:03:59 -0600534bool BestPractices::ValidateAttachments(const VkRenderPassCreateInfo2* rpci, uint32_t attachmentCount,
535 const VkImageView* image_views) const {
536 bool skip = false;
537
538 // Check for non-transient attachments that should be transient and vice versa
539 for (uint32_t i = 0; i < attachmentCount; ++i) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200540 const auto& attachment = rpci->pAttachments[i];
Tony-LunarG767180f2020-04-23 14:03:59 -0600541 bool attachment_should_be_transient =
542 (attachment.loadOp != VK_ATTACHMENT_LOAD_OP_LOAD && attachment.storeOp != VK_ATTACHMENT_STORE_OP_STORE);
543
544 if (FormatHasStencil(attachment.format)) {
545 attachment_should_be_transient &= (attachment.stencilLoadOp != VK_ATTACHMENT_LOAD_OP_LOAD &&
546 attachment.stencilStoreOp != VK_ATTACHMENT_STORE_OP_STORE);
547 }
548
549 auto view_state = GetImageViewState(image_views[i]);
550 if (view_state) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200551 const auto& ivci = view_state->create_info;
Nadav Gevaf0808442021-05-21 13:51:25 -0400552 const auto& ici = Get<IMAGE_STATE>(ivci.image)->createInfo;
Tony-LunarG767180f2020-04-23 14:03:59 -0600553
554 bool image_is_transient = (ici.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) != 0;
555
556 // The check for an image that should not be transient applies to all GPUs
557 if (!attachment_should_be_transient && image_is_transient) {
558 skip |= LogPerformanceWarning(
559 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldNotBeTransient,
560 "Attachment %u in VkFramebuffer uses loadOp/storeOps which need to access physical memory, "
561 "but the image backing the image view has VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
562 "Physical memory will need to be backed lazily to this image, potentially causing stalls.",
563 i);
564 }
565
566 bool supports_lazy = false;
567 for (uint32_t j = 0; j < phys_dev_mem_props.memoryTypeCount; j++) {
568 if (phys_dev_mem_props.memoryTypes[j].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
569 supports_lazy = true;
570 }
571 }
572
573 // The check for an image that should be transient only applies to GPUs supporting
574 // lazily allocated memory
575 if (supports_lazy && attachment_should_be_transient && !image_is_transient) {
576 skip |= LogPerformanceWarning(
577 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldBeTransient,
578 "Attachment %u in VkFramebuffer uses loadOp/storeOps which never have to be backed by physical memory, "
579 "but the image backing the image view does not have VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
580 "You can save physical memory by using transient attachment backed by lazily allocated memory here.",
581 i);
582 }
583 }
584 }
585 return skip;
586}
587
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000588bool BestPractices::PreCallValidateCreateFramebuffer(VkDevice device, const VkFramebufferCreateInfo* pCreateInfo,
589 const VkAllocationCallbacks* pAllocator, VkFramebuffer* pFramebuffer) const {
590 bool skip = false;
591
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000592 auto rp_state = GetRenderPassState(pCreateInfo->renderPass);
Mike Schuchardt2df08912020-12-15 16:28:09 -0800593 if (rp_state && !(pCreateInfo->flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT)) {
Tony-LunarG767180f2020-04-23 14:03:59 -0600594 skip = ValidateAttachments(rp_state->createInfo.ptr(), pCreateInfo->attachmentCount, pCreateInfo->pAttachments);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000595 }
596
597 return skip;
598}
599
Sam Wallse746d522020-03-16 21:20:23 +0000600bool BestPractices::PreCallValidateAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
601 VkDescriptorSet* pDescriptorSets, void* ads_state_data) const {
602 bool skip = false;
603 skip |= ValidationStateTracker::PreCallValidateAllocateDescriptorSets(device, pAllocateInfo, pDescriptorSets, ads_state_data);
604
605 if (!skip) {
606 const auto& pool_handle = pAllocateInfo->descriptorPool;
607 auto iter = descriptor_pool_freed_count.find(pool_handle);
608 // if the number of freed sets > 0, it implies they could be recycled instead if desirable
609 // this warning is specific to Arm
610 if (VendorCheckEnabled(kBPVendorArm) && iter != descriptor_pool_freed_count.end() && iter->second > 0) {
611 skip |= LogPerformanceWarning(
612 device, kVUID_BestPractices_AllocateDescriptorSets_SuboptimalReuse,
613 "%s Descriptor set memory was allocated via vkAllocateDescriptorSets() for sets which were previously freed in the "
614 "same logical device. On some drivers or architectures it may be most optimal to re-use existing descriptor sets.",
615 VendorSpecificTag(kBPVendorArm));
616 }
617 }
618
619 return skip;
620}
621
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600622void BestPractices::ManualPostCallRecordAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
623 VkDescriptorSet* pDescriptorSets, VkResult result, void* ads_state) {
Sam Wallse746d522020-03-16 21:20:23 +0000624 if (result == VK_SUCCESS) {
625 // find the free count for the pool we allocated into
626 auto iter = descriptor_pool_freed_count.find(pAllocateInfo->descriptorPool);
627 if (iter != descriptor_pool_freed_count.end()) {
628 // we record successful allocations by subtracting the allocation count from the last recorded free count
629 const auto alloc_count = pAllocateInfo->descriptorSetCount;
630 // clamp the unsigned subtraction to the range [0, last_free_count]
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700631 if (iter->second > alloc_count) {
Sam Wallse746d522020-03-16 21:20:23 +0000632 iter->second -= alloc_count;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700633 } else {
Sam Wallse746d522020-03-16 21:20:23 +0000634 iter->second = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700635 }
Sam Wallse746d522020-03-16 21:20:23 +0000636 }
637 }
638}
639
640void BestPractices::PostCallRecordFreeDescriptorSets(VkDevice device, VkDescriptorPool descriptorPool, uint32_t descriptorSetCount,
641 const VkDescriptorSet* pDescriptorSets, VkResult result) {
642 ValidationStateTracker::PostCallRecordFreeDescriptorSets(device, descriptorPool, descriptorSetCount, pDescriptorSets, result);
643 if (result == VK_SUCCESS) {
644 // we want to track frees because we're interested in suggesting re-use
645 auto iter = descriptor_pool_freed_count.find(descriptorPool);
646 if (iter == descriptor_pool_freed_count.end()) {
Jeremy Gebbencbf22862021-03-03 12:01:22 -0700647 descriptor_pool_freed_count.emplace(descriptorPool, descriptorSetCount);
Sam Wallse746d522020-03-16 21:20:23 +0000648 } else {
649 iter->second += descriptorSetCount;
650 }
651 }
652}
653
Camden5b184be2019-08-13 07:50:19 -0600654bool BestPractices::PreCallValidateAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500655 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory) const {
Camden5b184be2019-08-13 07:50:19 -0600656 bool skip = false;
657
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500658 if (num_mem_objects + 1 > kMemoryObjectWarningLimit) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700659 skip |= LogPerformanceWarning(device, kVUID_BestPractices_AllocateMemory_TooManyObjects,
660 "Performance Warning: This app has > %" PRIu32 " memory objects.", kMemoryObjectWarningLimit);
Camden5b184be2019-08-13 07:50:19 -0600661 }
662
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000663 if (pAllocateInfo->allocationSize < kMinDeviceAllocationSize) {
664 skip |= LogPerformanceWarning(
665 device, kVUID_BestPractices_AllocateMemory_SmallAllocation,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600666 "vkAllocateMemory(): Allocating a VkDeviceMemory of size %" PRIu64 ". This is a very small allocation (current "
667 "threshold is %" PRIu64 " bytes). "
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000668 "You should make large allocations and sub-allocate from one large VkDeviceMemory.",
669 pAllocateInfo->allocationSize, kMinDeviceAllocationSize);
670 }
671
Camden83a9c372019-08-14 11:41:38 -0600672 // TODO: Insert get check for GetPhysicalDeviceMemoryProperties once the state is tracked in the StateTracker
673
674 return skip;
675}
676
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600677void BestPractices::ManualPostCallRecordAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
678 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory,
679 VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700680 if (result != VK_SUCCESS) {
681 static std::vector<VkResult> error_codes = {VK_ERROR_OUT_OF_HOST_MEMORY, VK_ERROR_OUT_OF_DEVICE_MEMORY,
682 VK_ERROR_TOO_MANY_OBJECTS, VK_ERROR_INVALID_EXTERNAL_HANDLE,
Mike Schuchardt2df08912020-12-15 16:28:09 -0800683 VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS};
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700684 static std::vector<VkResult> success_codes = {};
Nathaniel Cesariodb3f43f2021-05-12 09:08:23 -0600685 ValidateReturnCodes("vkAllocateMemory", result, error_codes, success_codes);
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700686 return;
687 }
688 num_mem_objects++;
689}
Camden Stocker9738af92019-10-16 13:54:03 -0700690
Mark Lobodzinskide15e582020-04-29 08:06:00 -0600691void BestPractices::ValidateReturnCodes(const char* api_name, VkResult result, const std::vector<VkResult>& error_codes,
692 const std::vector<VkResult>& success_codes) const {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700693 auto error = std::find(error_codes.begin(), error_codes.end(), result);
694 if (error != error_codes.end()) {
Gareth Webb586c46b2021-01-13 11:17:22 +0000695 static const std::vector<VkResult> common_failure_codes = {VK_ERROR_OUT_OF_DATE_KHR,
696 VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT};
697
698 auto common_failure = std::find(common_failure_codes.begin(), common_failure_codes.end(), result);
699 if (common_failure != common_failure_codes.end()) {
700 LogInfo(instance, kVUID_BestPractices_Failure_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
701 } else {
702 LogWarning(instance, kVUID_BestPractices_Error_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
703 }
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700704 return;
705 }
706 auto success = std::find(success_codes.begin(), success_codes.end(), result);
707 if (success != success_codes.end()) {
Mark Lobodzinskie7215152020-05-11 08:21:23 -0600708 LogInfo(instance, kVUID_BestPractices_NonSuccess_Result, "%s(): Returned non-success return code %s.", api_name,
709 string_VkResult(result));
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500710 }
711}
712
Jeff Bolz5c801d12019-10-09 10:38:45 -0500713bool BestPractices::PreCallValidateFreeMemory(VkDevice device, VkDeviceMemory memory,
714 const VkAllocationCallbacks* pAllocator) const {
Mark Lobodzinski91e50bf2020-01-14 09:55:11 -0700715 if (memory == VK_NULL_HANDLE) return false;
Camden83a9c372019-08-14 11:41:38 -0600716 bool skip = false;
717
Camden Stocker9738af92019-10-16 13:54:03 -0700718 const DEVICE_MEMORY_STATE* mem_info = ValidationStateTracker::GetDevMemState(memory);
Camden83a9c372019-08-14 11:41:38 -0600719
Jeremy Gebben5570abe2021-05-16 18:35:13 -0600720 for (const auto& node: mem_info->ObjectBindings()) {
721 const auto& obj = node->Handle();
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600722 LogObjectList objlist(device);
723 objlist.add(obj);
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -0600724 objlist.add(mem_info->mem());
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600725 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 -0600726 report_data->FormatHandle(obj).c_str(), report_data->FormatHandle(mem_info->mem()).c_str());
Camden83a9c372019-08-14 11:41:38 -0600727 }
728
Camden5b184be2019-08-13 07:50:19 -0600729 return skip;
730}
731
732void BestPractices::PreCallRecordFreeMemory(VkDevice device, VkDeviceMemory memory, const VkAllocationCallbacks* pAllocator) {
Mark Lobodzinski97484d62020-03-03 11:57:41 -0700733 ValidationStateTracker::PreCallRecordFreeMemory(device, memory, pAllocator);
Camden5b184be2019-08-13 07:50:19 -0600734 if (memory != VK_NULL_HANDLE) {
735 num_mem_objects--;
736 }
737}
738
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000739bool BestPractices::ValidateBindBufferMemory(VkBuffer buffer, VkDeviceMemory memory, const char* api_name) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600740 bool skip = false;
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500741 const BUFFER_STATE* buffer_state = GetBufferState(buffer);
Camden Stockerb603cc82019-09-03 10:09:02 -0600742
sfricke-samsunge2441192019-11-06 14:07:57 -0800743 if (!buffer_state->memory_requirements_checked && !buffer_state->external_memory_handle) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700744 skip |= LogWarning(device, kVUID_BestPractices_BufferMemReqNotCalled,
745 "%s: Binding memory to %s but vkGetBufferMemoryRequirements() has not been called on that buffer.",
746 api_name, report_data->FormatHandle(buffer).c_str());
Camden Stockerb603cc82019-09-03 10:09:02 -0600747 }
748
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000749 const DEVICE_MEMORY_STATE* mem_state = GetDevMemState(memory);
750
751 if (mem_state->alloc_info.allocationSize == buffer_state->createInfo.size &&
752 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
753 skip |= LogPerformanceWarning(
754 device, kVUID_BestPractices_SmallDedicatedAllocation,
755 "%s: Trying to bind %s to a memory block which is fully consumed by the buffer. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600756 "The required size of the allocation is %" PRIu64 ", but smaller buffers like this should be sub-allocated from "
757 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000758 api_name, report_data->FormatHandle(buffer).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
759 }
760
Camden Stockerb603cc82019-09-03 10:09:02 -0600761 return skip;
762}
763
764bool BestPractices::PreCallValidateBindBufferMemory(VkDevice device, VkBuffer buffer, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500765 VkDeviceSize memoryOffset) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600766 bool skip = false;
767 const char* api_name = "BindBufferMemory()";
768
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000769 skip |= ValidateBindBufferMemory(buffer, memory, api_name);
Camden Stockerb603cc82019-09-03 10:09:02 -0600770
771 return skip;
772}
773
774bool BestPractices::PreCallValidateBindBufferMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500775 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600776 char api_name[64];
777 bool skip = false;
778
779 for (uint32_t i = 0; i < bindInfoCount; i++) {
780 sprintf(api_name, "vkBindBufferMemory2() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000781 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600782 }
783
784 return skip;
785}
Camden Stockerb603cc82019-09-03 10:09:02 -0600786
787bool BestPractices::PreCallValidateBindBufferMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500788 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600789 char api_name[64];
790 bool skip = false;
Camden Stockerb603cc82019-09-03 10:09:02 -0600791
Camden Stocker8b798ab2019-09-03 10:33:28 -0600792 for (uint32_t i = 0; i < bindInfoCount; i++) {
793 sprintf(api_name, "vkBindBufferMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000794 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600795 }
796
797 return skip;
798}
799
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000800bool BestPractices::ValidateBindImageMemory(VkImage image, VkDeviceMemory memory, const char* api_name) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600801 bool skip = false;
Nadav Gevaf0808442021-05-21 13:51:25 -0400802 const IMAGE_STATE* image_state = Get<IMAGE_STATE>(image);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600803
sfricke-samsung71bc6572020-04-29 15:49:43 -0700804 if (image_state->disjoint == false) {
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600805 if (!image_state->memory_requirements_checked[0] && !image_state->external_memory_handle) {
sfricke-samsungd7ea5de2020-04-08 09:19:18 -0700806 skip |= LogWarning(device, kVUID_BestPractices_ImageMemReqNotCalled,
807 "%s: Binding memory to %s but vkGetImageMemoryRequirements() has not been called on that image.",
808 api_name, report_data->FormatHandle(image).c_str());
809 }
810 } else {
811 // TODO If binding disjoint image then this needs to check that VkImagePlaneMemoryRequirementsInfo was called for each
812 // plane.
Camden Stocker8b798ab2019-09-03 10:33:28 -0600813 }
814
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000815 const DEVICE_MEMORY_STATE* mem_state = GetDevMemState(memory);
816
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600817 if (mem_state->alloc_info.allocationSize == image_state->requirements[0].size &&
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000818 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
819 skip |= LogPerformanceWarning(
820 device, kVUID_BestPractices_SmallDedicatedAllocation,
821 "%s: Trying to bind %s to a memory block which is fully consumed by the image. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600822 "The required size of the allocation is %" PRIu64 ", but smaller images like this should be sub-allocated from "
823 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000824 api_name, report_data->FormatHandle(image).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
825 }
826
827 // If we're binding memory to a image which was created as TRANSIENT and the image supports LAZY allocation,
828 // make sure this type is actually used.
829 // This warning will only trigger if this layer is run on a platform that supports LAZILY_ALLOCATED_BIT
830 // (i.e.most tile - based renderers)
831 if (image_state->createInfo.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) {
832 bool supports_lazy = false;
833 uint32_t suggested_type = 0;
834
835 for (uint32_t i = 0; i < phys_dev_mem_props.memoryTypeCount; i++) {
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600836 if ((1u << i) & image_state->requirements[0].memoryTypeBits) {
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000837 if (phys_dev_mem_props.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
838 supports_lazy = true;
839 suggested_type = i;
840 break;
841 }
842 }
843 }
844
845 uint32_t allocated_properties = phys_dev_mem_props.memoryTypes[mem_state->alloc_info.memoryTypeIndex].propertyFlags;
846
847 if (supports_lazy && (allocated_properties & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) == 0) {
848 skip |= LogPerformanceWarning(
849 device, kVUID_BestPractices_NonLazyTransientImage,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600850 "%s: Attempting to bind memory type %u to VkImage which was created with TRANSIENT_ATTACHMENT_BIT,"
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000851 "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 -0600852 "%" PRIu64 " bytes of physical memory.",
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600853 api_name, mem_state->alloc_info.memoryTypeIndex, suggested_type, image_state->requirements[0].size);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000854 }
855 }
856
Camden Stocker8b798ab2019-09-03 10:33:28 -0600857 return skip;
858}
859
860bool BestPractices::PreCallValidateBindImageMemory(VkDevice device, VkImage image, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500861 VkDeviceSize memoryOffset) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600862 bool skip = false;
863 const char* api_name = "vkBindImageMemory()";
864
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000865 skip |= ValidateBindImageMemory(image, memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600866
867 return skip;
868}
869
870bool BestPractices::PreCallValidateBindImageMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500871 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600872 char api_name[64];
873 bool skip = false;
874
875 for (uint32_t i = 0; i < bindInfoCount; i++) {
876 sprintf(api_name, "vkBindImageMemory2() pBindInfos[%u]", i);
Mark Lobodzinski1f887d32020-12-30 15:31:33 -0700877 if (!LvlFindInChain<VkBindImageMemorySwapchainInfoKHR>(pBindInfos[i].pNext)) {
Tony-LunarG5e60b852020-04-27 11:27:54 -0600878 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
879 }
Camden Stocker8b798ab2019-09-03 10:33:28 -0600880 }
881
882 return skip;
883}
884
885bool BestPractices::PreCallValidateBindImageMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500886 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600887 char api_name[64];
888 bool skip = false;
889
890 for (uint32_t i = 0; i < bindInfoCount; i++) {
891 sprintf(api_name, "vkBindImageMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000892 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600893 }
894
895 return skip;
896}
Camden83a9c372019-08-14 11:41:38 -0600897
Attilio Provenzano02859b22020-02-27 14:17:28 +0000898static inline bool FormatHasFullThroughputBlendingArm(VkFormat format) {
899 switch (format) {
900 case VK_FORMAT_B10G11R11_UFLOAT_PACK32:
901 case VK_FORMAT_R16_SFLOAT:
902 case VK_FORMAT_R16G16_SFLOAT:
903 case VK_FORMAT_R16G16B16_SFLOAT:
904 case VK_FORMAT_R16G16B16A16_SFLOAT:
905 case VK_FORMAT_R32_SFLOAT:
906 case VK_FORMAT_R32G32_SFLOAT:
907 case VK_FORMAT_R32G32B32_SFLOAT:
908 case VK_FORMAT_R32G32B32A32_SFLOAT:
909 return false;
910
911 default:
912 return true;
913 }
914}
915
916bool BestPractices::ValidateMultisampledBlendingArm(uint32_t createInfoCount,
917 const VkGraphicsPipelineCreateInfo* pCreateInfos) const {
918 bool skip = false;
919
920 for (uint32_t i = 0; i < createInfoCount; i++) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700921 auto create_info = &pCreateInfos[i];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000922
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700923 if (!create_info->pColorBlendState || !create_info->pMultisampleState ||
924 create_info->pMultisampleState->rasterizationSamples == VK_SAMPLE_COUNT_1_BIT ||
925 create_info->pMultisampleState->sampleShadingEnable) {
Attilio Provenzano02859b22020-02-27 14:17:28 +0000926 return skip;
927 }
928
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700929 auto rp_state = GetRenderPassState(create_info->renderPass);
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200930 const auto& subpass = rp_state->createInfo.pSubpasses[create_info->subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000931
Hans-Kristian Arntzenc2742e72021-07-01 14:31:06 +0200932 // According to spec, pColorBlendState must be ignored if subpass does not have color attachments.
933 uint32_t num_color_attachments = std::min(subpass.colorAttachmentCount, create_info->pColorBlendState->attachmentCount);
934
935 for (uint32_t j = 0; j < num_color_attachments; j++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200936 const auto& blend_att = create_info->pColorBlendState->pAttachments[j];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000937 uint32_t att = subpass.pColorAttachments[j].attachment;
938
939 if (att != VK_ATTACHMENT_UNUSED && blend_att.blendEnable && blend_att.colorWriteMask) {
940 if (!FormatHasFullThroughputBlendingArm(rp_state->createInfo.pAttachments[att].format)) {
941 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultisampledBlending,
942 "%s vkCreateGraphicsPipelines() - createInfo #%u: Pipeline is multisampled and "
943 "color attachment #%u makes use "
944 "of a format which cannot be blended at full throughput when using MSAA.",
945 VendorSpecificTag(kBPVendorArm), i, j);
946 }
947 }
948 }
949 }
950
951 return skip;
952}
953
Nadav Gevaf0808442021-05-21 13:51:25 -0400954void BestPractices::ManualPostCallRecordCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
955 const VkComputePipelineCreateInfo* pCreateInfos,
956 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
957 VkResult result, void* pipe_state) {
958 // AMD best practice
959 pipeline_cache = pipelineCache;
960}
961
Camden5b184be2019-08-13 07:50:19 -0600962bool BestPractices::PreCallValidateCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
963 const VkGraphicsPipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -0600964 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500965 void* cgpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -0600966 bool skip = StateTracker::PreCallValidateCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos,
967 pAllocator, pPipelines, cgpl_state_data);
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600968 create_graphics_pipeline_api_state* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
Camden5b184be2019-08-13 07:50:19 -0600969
970 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700971 skip |= LogPerformanceWarning(
972 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
973 "Performance Warning: This vkCreateGraphicsPipelines call is creating multiple pipelines but is not using a "
974 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -0600975 }
976
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000977 for (uint32_t i = 0; i < createInfoCount; i++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200978 const auto& create_info = pCreateInfos[i];
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000979
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600980 if (!(cgpl_state->pipe_state[i]->active_shaders & VK_SHADER_STAGE_MESH_BIT_NV)) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200981 const auto& vertex_input = *create_info.pVertexInputState;
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600982 uint32_t count = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700983 for (uint32_t j = 0; j < vertex_input.vertexBindingDescriptionCount; j++) {
984 if (vertex_input.pVertexBindingDescriptions[j].inputRate == VK_VERTEX_INPUT_RATE_INSTANCE) {
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600985 count++;
986 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000987 }
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600988 if (count > kMaxInstancedVertexBuffers) {
989 skip |= LogPerformanceWarning(
990 device, kVUID_BestPractices_CreatePipelines_TooManyInstancedVertexBuffers,
991 "The pipeline is using %u instanced vertex buffers (current limit: %u), but this can be inefficient on the "
992 "GPU. If using instanced vertex attributes prefer interleaving them in a single buffer.",
993 count, kMaxInstancedVertexBuffers);
994 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000995 }
Attilio Provenzano02859b22020-02-27 14:17:28 +0000996
Szilard Pappaaf2da32020-06-22 10:37:35 +0100997 if ((pCreateInfos[i].pRasterizationState->depthBiasEnable) &&
998 (pCreateInfos[i].pRasterizationState->depthBiasConstantFactor == 0.0f) &&
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +0200999 (pCreateInfos[i].pRasterizationState->depthBiasSlopeFactor == 0.0f) &&
1000 VendorCheckEnabled(kBPVendorArm)) {
1001 skip |= LogPerformanceWarning(
1002 device, kVUID_BestPractices_CreatePipelines_DepthBias_Zero,
1003 "%s Performance Warning: This vkCreateGraphicsPipelines call is created with depthBiasEnable set to true "
1004 "and both depthBiasConstantFactor and depthBiasSlopeFactor are set to 0. This can cause reduced "
1005 "efficiency during rasterization. Consider disabling depthBias or increasing either "
1006 "depthBiasConstantFactor or depthBiasSlopeFactor.",
1007 VendorSpecificTag(kBPVendorArm));
Szilard Pappaaf2da32020-06-22 10:37:35 +01001008 }
1009
Attilio Provenzano02859b22020-02-27 14:17:28 +00001010 skip |= VendorCheckEnabled(kBPVendorArm) && ValidateMultisampledBlendingArm(createInfoCount, pCreateInfos);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001011 }
Nadav Gevaf0808442021-05-21 13:51:25 -04001012 if (VendorCheckEnabled(kBPVendorAMD)) {
1013 if (pipelineCache && pipeline_cache && pipelineCache != pipeline_cache) {
1014 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultiplePipelineCaches,
1015 "%s Performance Warning: A second pipeline cache is in use. Consider using only one pipeline cache to "
1016 "improve cache hit rate", VendorSpecificTag(kBPVendorAMD));
1017 }
1018
1019 if (num_pso > kMaxRecommendedNumberOfPSOAMD) {
1020 skip |=
1021 LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_TooManyPipelines,
1022 "%s Performance warning: Too many pipelines created, consider consolidation",
1023 VendorSpecificTag(kBPVendorAMD));
1024 }
1025
Nathaniel Cesario1a7e1a92021-08-30 14:34:20 -06001026 if (pCreateInfos->pInputAssemblyState && pCreateInfos->pInputAssemblyState->primitiveRestartEnable) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001027 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_AvoidPrimitiveRestart,
1028 "%s Performance warning: Use of primitive restart is not recommended",
1029 VendorSpecificTag(kBPVendorAMD));
1030 }
1031
1032 // TODO: this might be too aggressive of a check
1033 if (pCreateInfos->pDynamicState && pCreateInfos->pDynamicState->dynamicStateCount > kDynamicStatesWarningLimitAMD) {
1034 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MinimizeNumDynamicStates,
1035 "%s Performance warning: Dynamic States usage incurs a performance cost. Ensure that they are truly needed",
1036 VendorSpecificTag(kBPVendorAMD));
1037 }
1038 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001039
Camden5b184be2019-08-13 07:50:19 -06001040 return skip;
1041}
1042
Hans-Kristian Arntzenb033ab12021-06-16 11:16:59 +02001043void BestPractices::PreCallRecordDestroyPipeline(VkDevice device, VkPipeline pipeline, const VkAllocationCallbacks *pAllocator)
1044{
1045 auto itr = graphicsPipelineCIs.find(pipeline);
1046 if (itr != graphicsPipelineCIs.end()) {
1047 graphicsPipelineCIs.erase(itr);
1048 }
1049 ValidationStateTracker::PreCallRecordDestroyPipeline(device, pipeline, pAllocator);
1050}
1051
Sam Walls0961ec02020-03-31 16:39:15 +01001052void BestPractices::ManualPostCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t count,
1053 const VkGraphicsPipelineCreateInfo* pCreateInfos,
1054 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
1055 VkResult result, void* cgpl_state_data) {
1056 for (size_t i = 0; i < count; i++) {
1057 const auto* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
1058 const VkPipeline pipeline_handle = pPipelines[i];
1059
1060 // record depth stencil state and color blend states for depth pre-pass tracking purposes
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001061 GraphicsPipelineCIs& cis = graphicsPipelineCIs[pipeline_handle];
Sam Walls0961ec02020-03-31 16:39:15 +01001062
Hans-Kristian Arntzen42c0ef52021-06-14 14:46:25 +02001063 auto& create_info = cgpl_state->pCreateInfos[i];
Hans-Kristian Arntzen42c0ef52021-06-14 14:46:25 +02001064
Jeremy Gebben396d06a2021-08-12 11:03:04 -06001065 if (create_info.pColorBlendState) {
1066 cis.colorBlendStateCI.emplace(create_info.pColorBlendState);
1067 }
1068
1069 if (create_info.pDepthStencilState) {
1070 cis.depthStencilStateCI.emplace(create_info.pDepthStencilState);
1071 }
Hans-Kristian Arntzen42c0ef52021-06-14 14:46:25 +02001072
1073 // Record which frame buffer attachments we should consider to be accessed when a draw call is performed.
1074 RENDER_PASS_STATE* rp = GetRenderPassState(create_info.renderPass);
1075 auto& subpass = rp->createInfo.pSubpasses[create_info.subpass];
1076 cis.accessFramebufferAttachments.clear();
1077
1078 if (cis.colorBlendStateCI) {
Hans-Kristian Arntzenc2742e72021-07-01 14:31:06 +02001079 // According to spec, pColorBlendState must be ignored if subpass does not have color attachments.
1080 uint32_t num_color_attachments = std::min(subpass.colorAttachmentCount, cis.colorBlendStateCI->attachmentCount);
1081 for (uint32_t j = 0; j < num_color_attachments; j++) {
Hans-Kristian Arntzen42c0ef52021-06-14 14:46:25 +02001082 if (cis.colorBlendStateCI->pAttachments[j].colorWriteMask != 0) {
1083 uint32_t attachment = subpass.pColorAttachments[j].attachment;
1084 if (attachment != VK_ATTACHMENT_UNUSED) {
1085 cis.accessFramebufferAttachments.push_back({ attachment, VK_IMAGE_ASPECT_COLOR_BIT });
1086 }
1087 }
1088 }
1089 }
1090
1091 if (cis.depthStencilStateCI && (cis.depthStencilStateCI->depthTestEnable ||
1092 cis.depthStencilStateCI->depthBoundsTestEnable ||
1093 cis.depthStencilStateCI->stencilTestEnable)) {
1094 uint32_t attachment = subpass.pDepthStencilAttachment ?
1095 subpass.pDepthStencilAttachment->attachment :
1096 VK_ATTACHMENT_UNUSED;
1097 if (attachment != VK_ATTACHMENT_UNUSED) {
1098 VkImageAspectFlags aspects = 0;
1099 if (cis.depthStencilStateCI->depthTestEnable || cis.depthStencilStateCI->depthBoundsTestEnable) {
1100 aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
1101 }
1102 if (cis.depthStencilStateCI->stencilTestEnable) {
1103 aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
1104 }
1105 cis.accessFramebufferAttachments.push_back({ attachment, aspects });
1106 }
1107 }
Sam Walls0961ec02020-03-31 16:39:15 +01001108 }
Nadav Gevaf0808442021-05-21 13:51:25 -04001109
1110 // AMD best practice
1111 pipeline_cache = pipelineCache;
Sam Walls0961ec02020-03-31 16:39:15 +01001112}
1113
Camden5b184be2019-08-13 07:50:19 -06001114bool BestPractices::PreCallValidateCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
1115 const VkComputePipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -06001116 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001117 void* ccpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -06001118 bool skip = StateTracker::PreCallValidateCreateComputePipelines(device, pipelineCache, createInfoCount, pCreateInfos,
1119 pAllocator, pPipelines, ccpl_state_data);
Camden5b184be2019-08-13 07:50:19 -06001120
1121 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001122 skip |= LogPerformanceWarning(
1123 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
1124 "Performance Warning: This vkCreateComputePipelines call is creating multiple pipelines but is not using a "
1125 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -06001126 }
1127
Nadav Gevaf0808442021-05-21 13:51:25 -04001128 if (VendorCheckEnabled(kBPVendorAMD)) {
1129 if (pipelineCache && pipeline_cache && pipelineCache != pipeline_cache) {
1130 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
1131 "%s Performance Warning: A second pipeline cache is in use. Consider using only one pipeline cache to "
1132 "improve cache hit rate",
1133 VendorSpecificTag(kBPVendorAMD));
1134 }
1135 }
1136
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001137 if (VendorCheckEnabled(kBPVendorArm)) {
1138 for (size_t i = 0; i < createInfoCount; i++) {
1139 skip |= ValidateCreateComputePipelineArm(pCreateInfos[i]);
1140 }
1141 }
1142
1143 return skip;
1144}
1145
1146bool BestPractices::ValidateCreateComputePipelineArm(const VkComputePipelineCreateInfo& createInfo) const {
1147 bool skip = false;
1148 auto* module = GetShaderModuleState(createInfo.stage.module);
sfricke-samsung8a7341a2021-02-28 07:30:21 -08001149 // Generate warnings about work group sizes based on active resources.
sfricke-samsung962cad92021-04-13 00:46:29 -07001150 auto entrypoint = module->FindEntrypoint(createInfo.stage.pName, createInfo.stage.stage);
sfricke-samsung8a7341a2021-02-28 07:30:21 -08001151 if (entrypoint == module->end()) return false;
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001152
1153 uint32_t x = 1, y = 1, z = 1;
sfricke-samsung962cad92021-04-13 00:46:29 -07001154 module->FindLocalSize(entrypoint, x, y, z);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001155
1156 uint32_t thread_count = x * y * z;
1157
1158 // Generate a priori warnings about work group sizes.
1159 if (thread_count > kMaxEfficientWorkGroupThreadCountArm) {
1160 skip |= LogPerformanceWarning(
1161 device, kVUID_BestPractices_CreateComputePipelines_ComputeWorkGroupSize,
1162 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, %u, "
1163 "%u) (%u threads total), has more threads than advised in a single work group. It is advised to use work "
1164 "groups with less than %u threads, especially when using barrier() or shared memory.",
1165 VendorSpecificTag(kBPVendorArm), x, y, z, thread_count, kMaxEfficientWorkGroupThreadCountArm);
1166 }
1167
1168 if (thread_count == 1 || ((x > 1) && (x & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
1169 ((y > 1) && (y & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
1170 ((z > 1) && (z & (kThreadGroupDispatchCountAlignmentArm - 1)))) {
1171 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeThreadGroupAlignment,
1172 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, "
1173 "%u, %u) is not aligned to %u "
1174 "threads. On Arm Mali architectures, not aligning work group sizes to %u may "
1175 "leave threads idle on the shader "
1176 "core.",
1177 VendorSpecificTag(kBPVendorArm), x, y, z, kThreadGroupDispatchCountAlignmentArm,
1178 kThreadGroupDispatchCountAlignmentArm);
1179 }
1180
sfricke-samsung962cad92021-04-13 00:46:29 -07001181 auto accessible_ids = module->MarkAccessibleIds(entrypoint);
Jeremy Gebben84b838b2021-08-23 08:41:39 -06001182 auto descriptor_uses = module->CollectInterfaceByDescriptorSlot(accessible_ids);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001183
1184 unsigned dimensions = 0;
1185 if (x > 1) dimensions++;
1186 if (y > 1) dimensions++;
1187 if (z > 1) dimensions++;
1188 // Here the dimension will really depend on the dispatch grid, but assume it's 1D.
1189 dimensions = std::max(dimensions, 1u);
1190
1191 // If we're accessing images, we almost certainly want to have a 2D workgroup for cache reasons.
1192 // There are some false positives here. We could simply have a shader that does this within a 1D grid,
1193 // or we may have a linearly tiled image, but these cases are quite unlikely in practice.
1194 bool accesses_2d = false;
1195 for (const auto& usage : descriptor_uses) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001196 auto dim = module->GetShaderResourceDimensionality(usage.second);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001197 if (dim < 0) continue;
1198 auto spvdim = spv::Dim(dim);
1199 if (spvdim != spv::Dim1D && spvdim != spv::DimBuffer) accesses_2d = true;
1200 }
1201
1202 if (accesses_2d && dimensions < 2) {
1203 LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeSpatialLocality,
1204 "%s vkCreateComputePipelines(): compute shader has work group dimensions (%u, %u, %u), which "
1205 "suggests a 1D dispatch, but the shader is accessing 2D or 3D images. The shader may be "
1206 "exhibiting poor spatial locality with respect to one or more shader resources.",
1207 VendorSpecificTag(kBPVendorArm), x, y, z);
1208 }
1209
Camden5b184be2019-08-13 07:50:19 -06001210 return skip;
1211}
1212
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001213bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags flags) const {
Camden5b184be2019-08-13 07:50:19 -06001214 bool skip = false;
1215
1216 if (flags & VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001217 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1218 "You are using VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001219 } else if (flags & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001220 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1221 "You are using VK_PIPELINE_STAGE_ALL_COMMANDS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001222 }
1223
1224 return skip;
1225}
1226
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001227bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags2KHR flags) const {
1228 bool skip = false;
1229
1230 if (flags & VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR) {
1231 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1232 "You are using VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR when %s is called\n", api_name.c_str());
1233 } else if (flags & VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR) {
1234 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1235 "You are using VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR when %s is called\n", api_name.c_str());
1236 }
1237
1238 return skip;
1239}
1240
1241bool BestPractices::CheckDependencyInfo(const std::string& api_name, const VkDependencyInfoKHR& dep_info) const {
1242 bool skip = false;
1243 auto stage_masks = sync_utils::GetGlobalStageMasks(dep_info);
1244
1245 skip |= CheckPipelineStageFlags(api_name, stage_masks.src);
1246 skip |= CheckPipelineStageFlags(api_name, stage_masks.dst);
1247
1248 return skip;
1249}
1250
Mark Lobodzinski84101d72020-04-24 09:43:48 -06001251void BestPractices::ManualPostCallRecordQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo, VkResult result) {
Mark Lobodzinski9b133c12020-03-10 10:42:56 -06001252 for (uint32_t i = 0; i < pPresentInfo->swapchainCount; ++i) {
1253 auto swapchains_result = pPresentInfo->pResults ? pPresentInfo->pResults[i] : result;
1254 if (swapchains_result == VK_SUBOPTIMAL_KHR) {
1255 LogPerformanceWarning(
1256 pPresentInfo->pSwapchains[i], kVUID_BestPractices_SuboptimalSwapchain,
1257 "vkQueuePresentKHR: %s :VK_SUBOPTIMAL_KHR was returned. VK_SUBOPTIMAL_KHR - Presentation will still succeed, "
1258 "subject to the window resize behavior, but the swapchain is no longer configured optimally for the surface it "
1259 "targets. Applications should query updated surface information and recreate their swapchain at the next "
1260 "convenient opportunity.",
1261 report_data->FormatHandle(pPresentInfo->pSwapchains[i]).c_str());
1262 }
1263 }
Nadav Gevaf0808442021-05-21 13:51:25 -04001264
1265 // AMD best practice
1266 // end-of-frame cleanup
1267 num_queue_submissions = 0;
1268 num_barriers_objects = 0;
1269 pipelines_used_in_frame.clear();
Mark Lobodzinski9b133c12020-03-10 10:42:56 -06001270}
1271
Jeff Bolz5c801d12019-10-09 10:38:45 -05001272bool BestPractices::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
1273 VkFence fence) const {
Camden5b184be2019-08-13 07:50:19 -06001274 bool skip = false;
1275
1276 for (uint32_t submit = 0; submit < submitCount; submit++) {
1277 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreCount; semaphore++) {
1278 skip |= CheckPipelineStageFlags("vkQueueSubmit", pSubmits[submit].pWaitDstStageMask[semaphore]);
1279 }
1280 }
1281
1282 return skip;
1283}
1284
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001285bool BestPractices::PreCallValidateQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR* pSubmits,
1286 VkFence fence) const {
1287 bool skip = false;
1288
1289 for (uint32_t submit = 0; submit < submitCount; submit++) {
1290 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreInfoCount; semaphore++) {
1291 skip |= CheckPipelineStageFlags("vkQueueSubmit2KHR", pSubmits[submit].pWaitSemaphoreInfos[semaphore].stageMask);
1292 }
1293 }
1294
1295 return skip;
1296}
1297
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001298bool BestPractices::PreCallValidateCreateCommandPool(VkDevice device, const VkCommandPoolCreateInfo* pCreateInfo,
1299 const VkAllocationCallbacks* pAllocator, VkCommandPool* pCommandPool) const {
1300 bool skip = false;
1301
1302 if (pCreateInfo->flags & VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT) {
1303 skip |= LogPerformanceWarning(
1304 device, kVUID_BestPractices_CreateCommandPool_CommandBufferReset,
1305 "vkCreateCommandPool(): VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT is set. Consider resetting entire "
1306 "pool instead.");
1307 }
1308
1309 return skip;
1310}
1311
1312bool BestPractices::PreCallValidateBeginCommandBuffer(VkCommandBuffer commandBuffer,
1313 const VkCommandBufferBeginInfo* pBeginInfo) const {
1314 bool skip = false;
1315
1316 if (pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT) {
1317 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_SimultaneousUse,
1318 "vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT is set.");
1319 }
1320
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001321 if (!(pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT) && VendorCheckEnabled(kBPVendorArm)) {
1322 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_OneTimeSubmit,
Attilio Provenzano02859b22020-02-27 14:17:28 +00001323 "%s vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT is not set. "
1324 "For best performance on Mali GPUs, consider setting ONE_TIME_SUBMIT by default.",
1325 VendorSpecificTag(kBPVendorArm));
1326 }
1327
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001328 return skip;
1329}
1330
Jeff Bolz5c801d12019-10-09 10:38:45 -05001331bool BestPractices::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001332 bool skip = false;
1333
1334 skip |= CheckPipelineStageFlags("vkCmdSetEvent", stageMask);
1335
1336 return skip;
1337}
1338
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001339bool BestPractices::PreCallValidateCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1340 const VkDependencyInfoKHR* pDependencyInfo) const {
1341 return CheckDependencyInfo("vkCmdSetEvent2KHR", *pDependencyInfo);
1342}
1343
Jeff Bolz5c801d12019-10-09 10:38:45 -05001344bool BestPractices::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
1345 VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001346 bool skip = false;
1347
1348 skip |= CheckPipelineStageFlags("vkCmdResetEvent", stageMask);
1349
1350 return skip;
1351}
1352
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001353bool BestPractices::PreCallValidateCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1354 VkPipelineStageFlags2KHR stageMask) const {
1355 bool skip = false;
1356
1357 skip |= CheckPipelineStageFlags("vkCmdResetEvent2KHR", stageMask);
1358
1359 return skip;
1360}
1361
Camden5b184be2019-08-13 07:50:19 -06001362bool BestPractices::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1363 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
1364 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1365 uint32_t bufferMemoryBarrierCount,
1366 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1367 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001368 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001369 bool skip = false;
1370
1371 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", srcStageMask);
1372 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", dstStageMask);
1373
1374 return skip;
1375}
1376
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001377bool BestPractices::PreCallValidateCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1378 const VkDependencyInfoKHR* pDependencyInfos) const {
1379 bool skip = false;
1380 for (uint32_t i = 0; i < eventCount; i++) {
1381 skip = CheckDependencyInfo("vkCmdWaitEvents2KHR", pDependencyInfos[i]);
1382 }
1383
1384 return skip;
1385}
1386
Camden5b184be2019-08-13 07:50:19 -06001387bool BestPractices::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
1388 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
1389 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1390 uint32_t bufferMemoryBarrierCount,
1391 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1392 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001393 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001394 bool skip = false;
1395
1396 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", srcStageMask);
1397 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", dstStageMask);
1398
Nadav Gevaf0808442021-05-21 13:51:25 -04001399 if (VendorCheckEnabled(kBPVendorAMD)) {
1400 if (num_barriers_objects + imageMemoryBarrierCount + bufferMemoryBarrierCount > kMaxRecommendedBarriersSizeAMD) {
1401 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdBuffer_highBarrierCount,
1402 "%s Performance warning: In this frame, %" PRIu32 " barriers were already submitted. Barriers have a high cost and can "
1403 "stall the GPU. "
1404 "Consider consolidating and re-organizing the frame to use fewer barriers.",
1405 VendorSpecificTag(kBPVendorAMD), num_barriers_objects);
1406 }
1407
1408 std::array<VkImageLayout, 3> read_layouts = {
1409 VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL,
1410 VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
1411 VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
1412 };
1413
1414 for (uint32_t i = 0; i < imageMemoryBarrierCount; i++) {
1415 // read to read barriers
1416 auto found = std::find(read_layouts.begin(), read_layouts.end(), pImageMemoryBarriers[i].oldLayout);
1417 bool old_is_read_layout = found != read_layouts.end();
1418 found = std::find(read_layouts.begin(), read_layouts.end(), pImageMemoryBarriers[i].newLayout);
1419 bool new_is_read_layout = found != read_layouts.end();
1420 if (old_is_read_layout && new_is_read_layout) {
1421 skip |= LogPerformanceWarning(device, kVUID_BestPractices_PipelineBarrier_readToReadBarrier,
1422 "%s Performance warning: Don't issue read-to-read barriers. Get the resource in the right state the first "
1423 "time you use it.",
1424 VendorSpecificTag(kBPVendorAMD));
1425 }
1426
1427 // general with no storage
1428 if (pImageMemoryBarriers[i].newLayout == VK_IMAGE_LAYOUT_GENERAL) {
1429 auto image_state = Get<IMAGE_STATE>(pImageMemoryBarriers[i].image);
1430 if (!(image_state->createInfo.usage & VK_IMAGE_USAGE_STORAGE_BIT)) {
1431 skip |= LogPerformanceWarning(device, kVUID_BestPractices_vkImage_AvoidGeneral,
1432 "%s Performance warning: VK_IMAGE_LAYOUT_GENERAL should only be used with "
1433 "VK_IMAGE_USAGE_STORAGE_BIT images.",
1434 VendorSpecificTag(kBPVendorAMD));
1435 }
1436 }
1437 }
1438 }
1439
Camden5b184be2019-08-13 07:50:19 -06001440 return skip;
1441}
1442
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001443bool BestPractices::PreCallValidateCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer,
1444 const VkDependencyInfoKHR* pDependencyInfo) const {
1445 return CheckDependencyInfo("vkCmdPipelineBarrier2KHR", *pDependencyInfo);
1446}
1447
Camden5b184be2019-08-13 07:50:19 -06001448bool BestPractices::PreCallValidateCmdWriteTimestamp(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001449 VkQueryPool queryPool, uint32_t query) const {
Camden5b184be2019-08-13 07:50:19 -06001450 bool skip = false;
1451
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001452 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp", static_cast<VkPipelineStageFlags>(pipelineStage));
1453
1454 return skip;
1455}
1456
1457bool BestPractices::PreCallValidateCmdWriteTimestamp2KHR(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
1458 VkQueryPool queryPool, uint32_t query) const {
1459 bool skip = false;
1460
1461 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp2KHR", pipelineStage);
Camden5b184be2019-08-13 07:50:19 -06001462
1463 return skip;
1464}
1465
Sam Walls0961ec02020-03-31 16:39:15 +01001466void BestPractices::PostCallRecordCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
1467 VkPipeline pipeline) {
1468 StateTracker::PostCallRecordCmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
1469
Nadav Gevaf0808442021-05-21 13:51:25 -04001470 // AMD best practice
1471 pipelines_used_in_frame.emplace(pipeline);
1472
Sam Walls0961ec02020-03-31 16:39:15 +01001473 if (pipelineBindPoint == VK_PIPELINE_BIND_POINT_GRAPHICS) {
1474 // check for depth/blend state tracking
1475 auto gp_cis = graphicsPipelineCIs.find(pipeline);
1476 if (gp_cis != graphicsPipelineCIs.end()) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06001477 auto* cb_node = GetCBState(commandBuffer);
1478 assert(cb_node);
1479 auto& render_pass_state = cb_node->render_pass_state;
Sam Walls0961ec02020-03-31 16:39:15 +01001480
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001481 render_pass_state.nextDrawTouchesAttachments = gp_cis->second.accessFramebufferAttachments;
1482 render_pass_state.drawTouchAttachments = true;
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02001483
Jeremy Gebben396d06a2021-08-12 11:03:04 -06001484 const auto& blend_state = gp_cis->second.colorBlendStateCI;
1485 const auto& stencil_state = gp_cis->second.depthStencilStateCI;
Sam Walls0961ec02020-03-31 16:39:15 +01001486
1487 if (blend_state) {
1488 // assume the pipeline is depth-only unless any of the attachments have color writes enabled
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001489 render_pass_state.depthOnly = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001490 for (size_t i = 0; i < blend_state->attachmentCount; i++) {
1491 if (blend_state->pAttachments[i].colorWriteMask != 0) {
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001492 render_pass_state.depthOnly = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001493 }
1494 }
1495 }
1496
1497 // check for depth value usage
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001498 render_pass_state.depthEqualComparison = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001499
1500 if (stencil_state && stencil_state->depthTestEnable) {
1501 switch (stencil_state->depthCompareOp) {
1502 case VK_COMPARE_OP_EQUAL:
1503 case VK_COMPARE_OP_GREATER_OR_EQUAL:
1504 case VK_COMPARE_OP_LESS_OR_EQUAL:
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001505 render_pass_state.depthEqualComparison = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001506 break;
1507 default:
1508 break;
1509 }
1510 }
Sam Walls0961ec02020-03-31 16:39:15 +01001511 }
1512 }
1513}
1514
Hans-Kristian Arntzen237663c2021-07-01 14:36:40 +02001515static inline bool RenderPassUsesAttachmentAsResolve(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1516 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
1517 const auto& subpass_info = createInfo.pSubpasses[subpass];
1518 if (subpass_info.pResolveAttachments) {
1519 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1520 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
1521 }
1522 }
1523 }
1524
1525 return false;
1526}
1527
Attilio Provenzano02859b22020-02-27 14:17:28 +00001528static inline bool RenderPassUsesAttachmentOnTile(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1529 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001530 const auto& subpass_info = createInfo.pSubpasses[subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001531
1532 // If an attachment is ever used as a color attachment,
1533 // resolve attachment or depth stencil attachment,
1534 // it needs to exist on tile at some point.
1535
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001536 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1537 if (subpass_info.pColorAttachments[i].attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001538 }
1539
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001540 if (subpass_info.pResolveAttachments) {
1541 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1542 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
1543 }
1544 }
1545
1546 if (subpass_info.pDepthStencilAttachment && subpass_info.pDepthStencilAttachment->attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001547 }
1548
1549 return false;
1550}
1551
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001552static inline bool RenderPassUsesAttachmentAsImageOnly(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1553 if (RenderPassUsesAttachmentOnTile(createInfo, attachment)) {
1554 return false;
1555 }
1556
1557 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001558 const auto& subpassInfo = createInfo.pSubpasses[subpass];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001559
1560 for (uint32_t i = 0; i < subpassInfo.inputAttachmentCount; i++) {
1561 if (subpassInfo.pInputAttachments[i].attachment == attachment) {
1562 return true;
1563 }
1564 }
1565 }
1566
1567 return false;
1568}
1569
Attilio Provenzano02859b22020-02-27 14:17:28 +00001570bool BestPractices::ValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1571 const VkRenderPassBeginInfo* pRenderPassBegin) const {
1572 bool skip = false;
1573
1574 if (!pRenderPassBegin) {
1575 return skip;
1576 }
1577
Gareth Webbdc6549a2021-06-16 03:52:24 +01001578 if (pRenderPassBegin->renderArea.extent.width == 0 || pRenderPassBegin->renderArea.extent.height == 0) {
1579 skip |= LogWarning(device, kVUID_BestPractices_BeginRenderPass_ZeroSizeRenderArea,
1580 "This render pass has a zero-size render area. It cannot write to any attachments, "
1581 "and can only be used for side effects such as layout transitions.");
1582 }
1583
Attilio Provenzano02859b22020-02-27 14:17:28 +00001584 auto rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
1585 if (rp_state) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08001586 if (rp_state->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07001587 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
Tony-LunarG767180f2020-04-23 14:03:59 -06001588 if (rpabi) {
1589 skip = ValidateAttachments(rp_state->createInfo.ptr(), rpabi->attachmentCount, rpabi->pAttachments);
1590 }
1591 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001592 // Check if any attachments have LOAD operation on them
1593 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001594 const auto& attachment = rp_state->createInfo.pAttachments[att];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001595
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001596 bool attachment_has_readback = false;
Hans-Kristian Arntzen4afb59b2021-06-18 12:41:36 +02001597 if (!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001598 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001599 }
1600
1601 if (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001602 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001603 }
1604
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001605 bool attachment_needs_readback = false;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001606
1607 // Check if the attachment is actually used in any subpass on-tile
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001608 if (attachment_has_readback && RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1609 attachment_needs_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001610 }
1611
1612 // Using LOAD_OP_LOAD is expensive on tiled GPUs, so flag it as a potential improvement
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001613 if (attachment_needs_readback && VendorCheckEnabled(kBPVendorArm)) {
1614 skip |= LogPerformanceWarning(
1615 device, kVUID_BestPractices_BeginRenderPass_AttachmentNeedsReadback,
1616 "%s Attachment #%u in render pass has begun with VK_ATTACHMENT_LOAD_OP_LOAD.\n"
1617 "Submitting this renderpass will cause the driver to inject a readback of the attachment "
Nadav Gevaf0808442021-05-21 13:51:25 -04001618 "which will copy in total %u pixels (renderArea = "
1619 "{ %" PRId32 ", %" PRId32 ", %" PRIu32", %" PRIu32 " }) to the tile buffer.",
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001620 VendorSpecificTag(kBPVendorArm), att,
1621 pRenderPassBegin->renderArea.extent.width * pRenderPassBegin->renderArea.extent.height,
1622 pRenderPassBegin->renderArea.offset.x, pRenderPassBegin->renderArea.offset.y,
1623 pRenderPassBegin->renderArea.extent.width, pRenderPassBegin->renderArea.extent.height);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001624 }
1625 }
1626 }
1627
1628 return skip;
1629}
1630
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001631void BestPractices::QueueValidateImageView(QueueCallbacks &funcs, const char* function_name,
1632 IMAGE_VIEW_STATE* view, IMAGE_SUBRESOURCE_USAGE_BP usage) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001633 if (view) {
Jeremy Gebbenb4d17012021-07-08 13:18:15 -06001634 QueueValidateImage(funcs, function_name, GetImageUsageState(view->create_info.image), usage,
1635 view->normalized_subresource_range);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001636 }
1637}
1638
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001639void BestPractices::QueueValidateImage(QueueCallbacks &funcs, const char* function_name,
1640 IMAGE_STATE_BP* state, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001641 const VkImageSubresourceRange& subresource_range) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001642 IMAGE_STATE* image = state->image;
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02001643
1644 // If we're viewing a 3D slice, ignore base array layer.
1645 // The entire 3D subresource is accessed as one atomic unit.
1646 const uint32_t base_array_layer = image->createInfo.imageType == VK_IMAGE_TYPE_3D ? 0 : subresource_range.baseArrayLayer;
1647
1648 const uint32_t max_layers = image->createInfo.arrayLayers - base_array_layer;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001649 const uint32_t array_layers = std::min(subresource_range.layerCount, max_layers);
1650 const uint32_t max_levels = image->createInfo.mipLevels - subresource_range.baseMipLevel;
1651 const uint32_t mip_levels = std::min(image->createInfo.mipLevels, max_levels);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001652
1653 for (uint32_t layer = 0; layer < array_layers; layer++) {
1654 for (uint32_t level = 0; level < mip_levels; level++) {
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02001655 QueueValidateImage(funcs, function_name, state, usage, layer + base_array_layer,
1656 level + subresource_range.baseMipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001657 }
1658 }
1659}
1660
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001661void BestPractices::QueueValidateImage(QueueCallbacks &funcs, const char* function_name,
1662 IMAGE_STATE_BP* state, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001663 const VkImageSubresourceLayers& subresource_layers) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001664 IMAGE_STATE* image = state->image;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001665 const uint32_t max_layers = image->createInfo.arrayLayers - subresource_layers.baseArrayLayer;
1666 const uint32_t array_layers = std::min(subresource_layers.layerCount, max_layers);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001667
1668 for (uint32_t layer = 0; layer < array_layers; layer++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001669 QueueValidateImage(funcs, function_name, state, usage, layer + subresource_layers.baseArrayLayer, subresource_layers.mipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001670 }
1671}
1672
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001673void BestPractices::QueueValidateImage(QueueCallbacks &funcs, const char* function_name,
1674 IMAGE_STATE_BP* state, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001675 uint32_t array_layer, uint32_t mip_level) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001676 funcs.push_back([this, function_name, state, usage, array_layer, mip_level](const ValidationStateTracker*, const QUEUE_STATE*) -> bool {
1677 ValidateImageInQueue(function_name, state, usage, array_layer, mip_level);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001678 return false;
1679 });
1680}
1681
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001682void BestPractices::ValidateImageInQueueArm(const char* function_name, IMAGE_STATE* image,
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001683 IMAGE_SUBRESOURCE_USAGE_BP last_usage,
1684 IMAGE_SUBRESOURCE_USAGE_BP usage,
1685 uint32_t array_layer, uint32_t mip_level) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001686 // Swapchain images are implicitly read so clear after store is expected.
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001687 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 -06001688 !image->IsSwapchainImage()) {
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001689 LogPerformanceWarning(
1690 device, kVUID_BestPractices_RenderPass_RedundantStore,
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001691 "%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 +02001692 "image was used, it was written to with STORE_OP_STORE. "
1693 "Storing to the image is probably redundant in this case, and wastes bandwidth on tile-based "
1694 "architectures.",
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001695 function_name, VendorSpecificTag(kBPVendorArm), array_layer, mip_level);
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001696 } 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 +02001697 LogPerformanceWarning(
1698 device, kVUID_BestPractices_RenderPass_RedundantClear,
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001699 "%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 +02001700 "image was used, it was written to with vkCmdClear*Image(). "
1701 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
1702 "tile-based architectures."
1703 "architectures.",
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001704 function_name, VendorSpecificTag(kBPVendorArm), array_layer, mip_level);
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01001705 } else if (usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE &&
1706 (last_usage == IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE ||
1707 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::CLEARED ||
1708 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE ||
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001709 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE)) {
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01001710 const char *last_cmd = nullptr;
1711 const char *vuid = nullptr;
1712 const char *suggestion = nullptr;
1713
1714 switch (last_usage) {
1715 case IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE:
1716 vuid = kVUID_BestPractices_RenderPass_BlitImage_LoadOpLoad;
1717 last_cmd = "vkCmdBlitImage";
1718 suggestion =
1719 "The blit is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
1720 "Rather than blitting, just render the source image in a fragment shader in this render pass, "
1721 "which avoids the memory roundtrip.";
1722 break;
1723 case IMAGE_SUBRESOURCE_USAGE_BP::CLEARED:
1724 vuid = kVUID_BestPractices_RenderPass_InefficientClear;
1725 last_cmd = "vkCmdClear*Image";
1726 suggestion =
1727 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
1728 "tile-based architectures. "
1729 "Use LOAD_OP_CLEAR instead to clear the image for free.";
1730 break;
1731 case IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE:
1732 vuid = kVUID_BestPractices_RenderPass_CopyImage_LoadOpLoad;
1733 last_cmd = "vkCmdCopy*Image";
1734 suggestion =
1735 "The copy is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
1736 "Rather than copying, just render the source image in a fragment shader in this render pass, "
1737 "which avoids the memory roundtrip.";
1738 break;
1739 case IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE:
1740 vuid = kVUID_BestPractices_RenderPass_ResolveImage_LoadOpLoad;
1741 last_cmd = "vkCmdResolveImage";
1742 suggestion =
1743 "The resolve is probably redundant in this case, and wastes a lot of bandwidth on tile-based architectures. "
1744 "Rather than resolving, and then loading, try to keep rendering in the same render pass, "
1745 "which avoids the memory roundtrip.";
1746 break;
1747 default:
1748 break;
1749 }
1750
1751 LogPerformanceWarning(
1752 device, vuid,
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001753 "%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 +01001754 "time image was used, it was written to with %s. %s",
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001755 function_name, VendorSpecificTag(kBPVendorArm), array_layer, mip_level, last_cmd, suggestion);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001756 }
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001757}
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001758
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001759void BestPractices::ValidateImageInQueue(const char* function_name, IMAGE_STATE_BP* state,
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001760 IMAGE_SUBRESOURCE_USAGE_BP usage, uint32_t array_layer,
1761 uint32_t mip_level) {
1762 IMAGE_STATE* image = state->image;
1763 IMAGE_SUBRESOURCE_USAGE_BP last_usage = state->usages[array_layer][mip_level];
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001764 state->usages[array_layer][mip_level] = usage;
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001765 if (VendorCheckEnabled(kBPVendorArm)) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001766 ValidateImageInQueueArm(function_name, image, last_usage, usage, array_layer, mip_level);
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001767 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001768}
1769
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06001770void BestPractices::AddDeferredQueueOperations(CMD_BUFFER_STATE_BP* cb) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001771 cb->queue_submit_functions.insert(cb->queue_submit_functions.end(),
Hans-Kristian Arntzenf44df192021-06-14 11:42:08 +02001772 cb->queue_submit_functions_after_render_pass.begin(),
1773 cb->queue_submit_functions_after_render_pass.end());
1774 cb->queue_submit_functions_after_render_pass.clear();
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001775}
1776
1777void BestPractices::PreCallRecordCmdEndRenderPass(VkCommandBuffer commandBuffer) {
1778 ValidationStateTracker::PreCallRecordCmdEndRenderPass(commandBuffer);
Hans-Kristian Arntzenb8336ad2021-04-28 14:54:09 +02001779 AddDeferredQueueOperations(GetCBState(commandBuffer));
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001780}
1781
1782void BestPractices::PreCallRecordCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassInfo) {
1783 ValidationStateTracker::PreCallRecordCmdEndRenderPass2(commandBuffer, pSubpassInfo);
Hans-Kristian Arntzenb8336ad2021-04-28 14:54:09 +02001784 AddDeferredQueueOperations(GetCBState(commandBuffer));
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001785}
1786
1787void BestPractices::PreCallRecordCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfoKHR *pSubpassInfo) {
1788 ValidationStateTracker::PreCallRecordCmdEndRenderPass2KHR(commandBuffer, pSubpassInfo);
Hans-Kristian Arntzenb8336ad2021-04-28 14:54:09 +02001789 AddDeferredQueueOperations(GetCBState(commandBuffer));
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001790}
1791
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02001792void BestPractices::PreCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer,
1793 const VkRenderPassBeginInfo* pRenderPassBegin,
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001794 VkSubpassContents contents) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001795 ValidationStateTracker::PreCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02001796 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1797}
1798
1799void BestPractices::PreCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer,
1800 const VkRenderPassBeginInfo* pRenderPassBegin,
1801 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1802 ValidationStateTracker::PreCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1803 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1804}
1805
1806void BestPractices::PreCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1807 const VkRenderPassBeginInfo* pRenderPassBegin,
1808 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1809 ValidationStateTracker::PreCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1810 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1811}
1812
1813void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001814
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001815 if (!pRenderPassBegin) {
1816 return;
1817 }
1818
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06001819 auto* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001820
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06001821 auto* rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001822 if (rp_state) {
1823 // Check load ops
1824 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001825 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001826
1827 if (!RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att) &&
1828 !RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1829 continue;
1830 }
1831
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001832 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::UNDEFINED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001833
1834 if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) ||
1835 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001836 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02001837 } else if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) ||
1838 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_CLEAR)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001839 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_CLEARED;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02001840 } else if (RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att)) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001841 usage = IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001842 }
1843
1844 auto framebuffer = GetFramebufferState(pRenderPassBegin->framebuffer);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001845 IMAGE_VIEW_STATE* image_view = nullptr;
1846
Tony-LunarGb3ab3572021-07-02 09:45:17 -06001847 if (framebuffer->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001848 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
1849 if (rpabi) {
1850 image_view = GetImageViewState(rpabi->pAttachments[att]);
1851 }
1852 } else {
1853 image_view = GetImageViewState(framebuffer->createInfo.pAttachments[att]);
1854 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001855
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001856 QueueValidateImageView(cb->queue_submit_functions, "vkCmdBeginRenderPass()", image_view, usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001857 }
1858
1859 // Check store ops
1860 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001861 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001862
1863 if (!RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1864 continue;
1865 }
1866
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001867 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_DISCARDED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001868
1869 if ((!FormatIsStencilOnly(attachment.format) && attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE) ||
1870 (FormatHasStencil(attachment.format) && attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001871 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_STORED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001872 }
1873
1874 auto framebuffer = GetFramebufferState(pRenderPassBegin->framebuffer);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001875
1876 IMAGE_VIEW_STATE* image_view = nullptr;
Tony-LunarGb3ab3572021-07-02 09:45:17 -06001877 if (framebuffer->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001878 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
1879 if (rpabi) {
1880 image_view = GetImageViewState(rpabi->pAttachments[att]);
1881 }
1882 } else {
1883 image_view = GetImageViewState(framebuffer->createInfo.pAttachments[att]);
1884 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001885
Hans-Kristian Arntzenf44df192021-06-14 11:42:08 +02001886 QueueValidateImageView(cb->queue_submit_functions_after_render_pass, "vkCmdEndRenderPass()", image_view, usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001887 }
1888 }
1889}
1890
Attilio Provenzano02859b22020-02-27 14:17:28 +00001891bool BestPractices::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1892 VkSubpassContents contents) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001893 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1894 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001895 return skip;
1896}
1897
1898bool BestPractices::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1899 const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08001900 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001901 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1902 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001903 return skip;
1904}
1905
1906bool BestPractices::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08001907 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001908 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1909 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001910 return skip;
1911}
1912
Sam Walls0961ec02020-03-31 16:39:15 +01001913void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1914 const VkRenderPassBeginInfo* pRenderPassBegin) {
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001915 // Reset the renderpass state
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06001916 auto* cb = GetCBState(commandBuffer);
1917 cb->hasDrawCmd = false;
1918 assert(cb);
1919 auto& render_pass_state = cb->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02001920 render_pass_state.touchesAttachments.clear();
1921 render_pass_state.earlyClearAttachments.clear();
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001922 render_pass_state.numDrawCallsDepthOnly = 0;
1923 render_pass_state.numDrawCallsDepthEqualCompare = 0;
1924 render_pass_state.colorAttachment = false;
1925 render_pass_state.depthAttachment = false;
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02001926 render_pass_state.drawTouchAttachments = true;
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001927 // Don't reset state related to pipeline state.
Sam Walls0961ec02020-03-31 16:39:15 +01001928
Hans-Kristian Arntzena1a92cc2021-03-17 13:09:33 +01001929 const auto* rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
Sam Walls0961ec02020-03-31 16:39:15 +01001930
1931 // track depth / color attachment usage within the renderpass
1932 for (size_t i = 0; i < rp_state->createInfo.subpassCount; i++) {
1933 // record if depth/color attachments are in use for this renderpass
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001934 if (rp_state->createInfo.pSubpasses[i].pDepthStencilAttachment != nullptr) render_pass_state.depthAttachment = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001935
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001936 if (rp_state->createInfo.pSubpasses[i].colorAttachmentCount > 0) render_pass_state.colorAttachment = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001937 }
1938}
1939
1940void BestPractices::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1941 VkSubpassContents contents) {
1942 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1943 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
1944}
1945
1946void BestPractices::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1947 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1948 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1949 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1950}
1951
1952void BestPractices::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1953 const VkRenderPassBeginInfo* pRenderPassBegin,
1954 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1955 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1956 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1957}
1958
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001959// Generic function to handle validation for all CmdDraw* type functions
1960bool BestPractices::ValidateCmdDrawType(VkCommandBuffer cmd_buffer, const char* caller) const {
1961 bool skip = false;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06001962 const auto* cb_state = GetCBState(cmd_buffer);
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001963 if (cb_state) {
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001964 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
1965 const auto* pipeline_state = cb_state->lastBound[lv_bind_point].pipeline_state;
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001966 const auto& current_vtx_bfr_binding_info = cb_state->current_vertex_buffer_binding_info.vertex_buffer_bindings;
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001967
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001968 // Verify vertex binding
1969 if (pipeline_state->vertex_binding_descriptions_.size() <= 0) {
1970 if ((!current_vtx_bfr_binding_info.empty()) && (!cb_state->vertex_buffer_used)) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001971 skip |= LogPerformanceWarning(cb_state->commandBuffer(), kVUID_BestPractices_DrawState_VtxIndexOutOfBounds,
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001972 "Vertex buffers are bound to %s but no vertex buffers are attached to %s.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001973 report_data->FormatHandle(cb_state->commandBuffer()).c_str(),
1974 report_data->FormatHandle(pipeline_state->pipeline()).c_str());
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001975 }
1976 }
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06001977
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06001978 const auto* pipe = cb_state->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06001979 if (pipe) {
1980 const auto* rp_state = pipe->rp_state.get();
1981 if (rp_state) {
1982 for (uint32_t i = 0; i < rp_state->createInfo.subpassCount; ++i) {
1983 const auto& subpass = rp_state->createInfo.pSubpasses[i];
Jeremy Gebben11af9792021-08-20 10:20:09 -06001984 const auto& create_info = pipe->create_info.graphics;
1985 const uint32_t depth_stencil_attachment =
1986 GetSubpassDepthStencilAttachmentIndex(create_info.pDepthStencilState, subpass.pDepthStencilAttachment);
1987 if ((depth_stencil_attachment == VK_ATTACHMENT_UNUSED) && create_info.pRasterizationState &&
1988 create_info.pRasterizationState->depthBiasEnable == VK_TRUE) {
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06001989 skip |= LogWarning(cb_state->commandBuffer(), kVUID_BestPractices_DepthBiasNoAttachment,
1990 "%s: depthBiasEnable == VK_TRUE without a depth-stencil attachment.", caller);
1991 }
1992 }
1993 }
1994 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001995 }
1996 return skip;
1997}
1998
Sam Walls0961ec02020-03-31 16:39:15 +01001999void BestPractices::RecordCmdDrawType(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002000 auto* cb_node = GetCBState(cmd_buffer);
2001 assert(cb_node);
2002 auto& render_pass_state = cb_node->render_pass_state;
Sam Walls0961ec02020-03-31 16:39:15 +01002003 if (VendorCheckEnabled(kBPVendorArm)) {
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002004 RecordCmdDrawTypeArm(render_pass_state, draw_count, caller);
2005 }
2006
2007 if (render_pass_state.drawTouchAttachments) {
2008 for (auto& touch : render_pass_state.nextDrawTouchesAttachments) {
2009 RecordAttachmentAccess(render_pass_state, touch.framebufferAttachment, touch.aspects);
2010 }
2011 // No need to touch the same attachments over and over.
2012 render_pass_state.drawTouchAttachments = false;
Sam Walls0961ec02020-03-31 16:39:15 +01002013 }
2014}
2015
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002016void BestPractices::RecordCmdDrawTypeArm(RenderPassState& render_pass_state, uint32_t draw_count, const char* caller) {
2017 if (draw_count >= kDepthPrePassMinDrawCountArm) {
2018 if (render_pass_state.depthOnly) render_pass_state.numDrawCallsDepthOnly++;
2019 if (render_pass_state.depthEqualComparison) render_pass_state.numDrawCallsDepthEqualCompare++;
Sam Walls0961ec02020-03-31 16:39:15 +01002020 }
2021}
2022
Camden5b184be2019-08-13 07:50:19 -06002023bool BestPractices::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002024 uint32_t firstVertex, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06002025 bool skip = false;
2026
2027 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002028 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
2029 "Warning: You are calling vkCmdDraw() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06002030 }
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002031 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDraw()");
Camden5b184be2019-08-13 07:50:19 -06002032
2033 return skip;
2034}
2035
Sam Walls0961ec02020-03-31 16:39:15 +01002036void BestPractices::PostCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
2037 uint32_t firstVertex, uint32_t firstInstance) {
2038 StateTracker::PostCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
2039 RecordCmdDrawType(commandBuffer, vertexCount * instanceCount, "vkCmdDraw()");
2040}
2041
Camden5b184be2019-08-13 07:50:19 -06002042bool BestPractices::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002043 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06002044 bool skip = false;
2045
2046 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002047 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
2048 "Warning: You are calling vkCmdDrawIndexed() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06002049 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002050 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexed()");
2051
Attilio Provenzano02859b22020-02-27 14:17:28 +00002052 // Check if we reached the limit for small indexed draw calls.
2053 // Note that we cannot update the draw call count here, so we do it in PreCallRecordCmdDrawIndexed.
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002054 const auto* cmd_state = GetCBState(commandBuffer);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002055 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices &&
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02002056 (cmd_state->small_indexed_draw_call_count == kMaxSmallIndexedDrawcalls - 1) &&
2057 VendorCheckEnabled(kBPVendorArm)) {
2058 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_ManySmallIndexedDrawcalls,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -06002059 "%s: The command buffer contains many small indexed drawcalls "
Attilio Provenzano02859b22020-02-27 14:17:28 +00002060 "(at least %u drawcalls with less than %u indices each). This may cause pipeline bubbles. "
2061 "You can try batching drawcalls or instancing when applicable.",
2062 VendorSpecificTag(kBPVendorArm), kMaxSmallIndexedDrawcalls, kSmallIndexedDrawcallIndices);
2063 }
2064
Sam Walls8e77e4f2020-03-16 20:47:40 +00002065 if (VendorCheckEnabled(kBPVendorArm)) {
2066 ValidateIndexBufferArm(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
2067 }
2068
2069 return skip;
2070}
2071
2072bool BestPractices::ValidateIndexBufferArm(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
2073 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
2074 bool skip = false;
2075
2076 // check for sparse/underutilised index buffer, and post-transform cache thrashing
2077 const auto* cmd_state = GetCBState(commandBuffer);
2078 if (cmd_state == nullptr) return skip;
2079
locke-lunarg1ae57d62020-11-18 10:49:19 -07002080 const auto* ib_state = cmd_state->index_buffer_binding.buffer_state.get();
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002081 if (ib_state == nullptr || cmd_state->index_buffer_binding.buffer_state->Destroyed()) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00002082
2083 const VkIndexType ib_type = cmd_state->index_buffer_binding.index_type;
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06002084 const auto& ib_mem_state = *ib_state->MemState();
Sam Walls8e77e4f2020-03-16 20:47:40 +00002085 const VkDeviceSize ib_mem_offset = ib_mem_state.mapped_range.offset;
2086 const void* ib_mem = ib_mem_state.p_driver_data;
2087 bool primitive_restart_enable = false;
2088
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002089 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
2090 const auto& pipeline_binding_iter = cmd_state->lastBound[lv_bind_point];
2091 const auto* pipeline_state = pipeline_binding_iter.pipeline_state;
Sam Walls8e77e4f2020-03-16 20:47:40 +00002092
Jeremy Gebben11af9792021-08-20 10:20:09 -06002093 if (pipeline_state != nullptr && pipeline_state->create_info.graphics.pInputAssemblyState != nullptr) {
2094 primitive_restart_enable = pipeline_state->create_info.graphics.pInputAssemblyState->primitiveRestartEnable == VK_TRUE;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002095 }
Sam Walls8e77e4f2020-03-16 20:47:40 +00002096
2097 // 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 -06002098 if (ib_mem && pipeline_binding_iter.IsUsing()) {
Sam Walls8e77e4f2020-03-16 20:47:40 +00002099 uint32_t scan_stride;
2100 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
2101 scan_stride = sizeof(uint8_t);
2102 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
2103 scan_stride = sizeof(uint16_t);
2104 } else {
2105 scan_stride = sizeof(uint32_t);
2106 }
2107
2108 const uint8_t* scan_begin = static_cast<const uint8_t*>(ib_mem) + ib_mem_offset + firstIndex * scan_stride;
2109 const uint8_t* scan_end = scan_begin + indexCount * scan_stride;
2110
2111 // Min and max are important to track for some Mali architectures. In older Mali devices without IDVS, all
2112 // vertices corresponding to indices between the minimum and maximum may be loaded, and possibly shaded,
2113 // irrespective of whether or not they're part of the draw call.
2114
2115 // start with minimum as 0xFFFFFFFF and adjust to indices in the buffer
2116 uint32_t min_index = ~0u;
2117 // start with maximum as 0 and adjust to indices in the buffer
2118 uint32_t max_index = 0u;
2119
2120 // first scan-through, we're looking to simulate a model LRU post-transform cache, estimating the number of vertices shaded
2121 // for the given index buffer
2122 uint32_t vertex_shade_count = 0;
2123
2124 PostTransformLRUCacheModel post_transform_cache;
2125
2126 // The size of the cache being modelled positively correlates with how much behaviour it can capture about
2127 // arbitrary ground-truth hardware/architecture cache behaviour. I.e. it's a good solution when we don't know the
2128 // target architecture.
2129 // However, modelling a post-transform cache with more than 32 elements gives diminishing returns in practice.
2130 // http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
2131 post_transform_cache.resize(32);
2132
2133 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
2134 uint32_t scan_index;
2135 uint32_t primitive_restart_value;
2136 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
2137 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
2138 primitive_restart_value = 0xFF;
2139 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
2140 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
2141 primitive_restart_value = 0xFFFF;
2142 } else {
2143 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
2144 primitive_restart_value = 0xFFFFFFFF;
2145 }
2146
2147 max_index = std::max(max_index, scan_index);
2148 min_index = std::min(min_index, scan_index);
2149
2150 if (!primitive_restart_enable || scan_index != primitive_restart_value) {
2151 bool in_cache = post_transform_cache.query_cache(scan_index);
2152 // if the shaded vertex corresponding to the index is not in the PT-cache, we need to shade again
2153 if (!in_cache) vertex_shade_count++;
2154 }
2155 }
2156
2157 // 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 +01002158 // 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
2159 if (max_index < min_index || max_index == min_index) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00002160
2161 if (max_index - min_index >= indexCount) {
Mark Young0ec6b062020-11-19 15:32:17 -07002162 skip |=
2163 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
2164 "%s The indices which were specified for the draw call only utilise approximately %.02f%% of "
2165 "index buffer value range. Arm Mali architectures before G71 do not have IDVS (Index-Driven "
2166 "Vertex Shading), meaning all vertices corresponding to indices between the minimum and "
2167 "maximum would be loaded, and possibly shaded, whether or not they are used.",
2168 VendorSpecificTag(kBPVendorArm),
2169 (static_cast<float>(indexCount) / static_cast<float>(max_index - min_index)) * 100.0f);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002170 return skip;
2171 }
2172
2173 // use a dynamic vector of bitsets as a memory-compact representation of which indices are included in the draw call
2174 // 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 +01002175 const size_t refs_per_bucket = 64;
2176 std::vector<std::bitset<refs_per_bucket>> vertex_reference_buckets;
2177
2178 const uint32_t n_indices = max_index - min_index + 1;
2179 const uint32_t n_buckets = (n_indices / static_cast<uint32_t>(refs_per_bucket)) +
2180 ((n_indices % static_cast<uint32_t>(refs_per_bucket)) != 0 ? 1 : 0);
2181
2182 // there needs to be at least one bitset to store a set of indices smaller than n_buckets
2183 vertex_reference_buckets.resize(std::max(1u, n_buckets));
Sam Walls8e77e4f2020-03-16 20:47:40 +00002184
2185 // To avoid using too much memory, we run over the indices again.
2186 // Knowing the size from the last scan allows us to record index usage with bitsets
2187 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
2188 uint32_t scan_index;
2189 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
2190 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
2191 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
2192 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
2193 } else {
2194 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
2195 }
2196 // keep track of the set of all indices used to reference vertices in the draw call
2197 size_t index_offset = scan_index - min_index;
Sam Walls61b06892020-07-23 16:20:50 +01002198 size_t bitset_bucket_index = index_offset / refs_per_bucket;
2199 uint64_t used_indices = 1ull << ((index_offset % refs_per_bucket) & 0xFFFFFFFFu);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002200 vertex_reference_buckets[bitset_bucket_index] |= used_indices;
2201 }
2202
2203 uint32_t vertex_reference_count = 0;
2204 for (const auto& bitset : vertex_reference_buckets) {
2205 vertex_reference_count += static_cast<uint32_t>(bitset.count());
2206 }
2207
2208 // 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 -07002209 float utilization = static_cast<float>(vertex_reference_count) / static_cast<float>(max_index - min_index + 1);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002210 // 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 -07002211 float cache_hit_rate = static_cast<float>(vertex_reference_count) / static_cast<float>(vertex_shade_count);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002212
2213 if (utilization < 0.5f) {
2214 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
2215 "%s The indices which were specified for the draw call only utilise approximately "
2216 "%.02f%% of the bound vertex buffer.",
2217 VendorSpecificTag(kBPVendorArm), utilization);
2218 }
2219
2220 if (cache_hit_rate <= 0.5f) {
2221 skip |=
2222 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_PostTransformCacheThrashing,
2223 "%s The indices which were specified for the draw call are estimated to cause thrashing of "
2224 "the post-transform vertex cache, with a hit-rate of %.02f%%. "
2225 "I.e. the ordering of the index buffer may not make optimal use of indices associated with "
2226 "recently shaded vertices.",
2227 VendorSpecificTag(kBPVendorArm), cache_hit_rate * 100.0f);
2228 }
2229 }
2230
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002231 return skip;
2232}
2233
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002234bool BestPractices::PreCallValidateCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
2235 const VkCommandBuffer* pCommandBuffers) const {
2236 bool skip = false;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002237 const auto* primary = GetCBState(commandBuffer);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002238 for (uint32_t i = 0; i < commandBufferCount; i++) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002239 const auto* secondary_cb = GetCBState(pCommandBuffers[i]);
2240 if (secondary_cb == nullptr) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002241 continue;
2242 }
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002243 const auto& secondary = secondary_cb->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002244 for (auto& clear : secondary.earlyClearAttachments) {
Hans-Kristian Arntzenfa8ef9f2021-06-29 12:07:59 +02002245 if (ClearAttachmentsIsFullClear(primary, uint32_t(clear.rects.size()), clear.rects.data())) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002246 skip |= ValidateClearAttachment(commandBuffer, primary,
2247 clear.framebufferAttachment, clear.colorAttachment,
2248 clear.aspects, true);
2249 }
2250 }
2251 }
Nadav Gevaf0808442021-05-21 13:51:25 -04002252
2253 if (VendorCheckEnabled(kBPVendorAMD)) {
2254 if (commandBufferCount > 0) {
2255 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdBuffer_AvoidSecondaryCmdBuffers,
2256 "%s Performance warning: Use of secondary command buffers is not recommended. ",
2257 VendorSpecificTag(kBPVendorAMD));
2258 }
2259 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002260 return skip;
2261}
2262
2263void BestPractices::PreCallRecordCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
2264 const VkCommandBuffer* pCommandBuffers) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002265 auto* primary = GetCBState(commandBuffer);
2266 auto& primary_state = primary->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002267
2268 for (uint32_t i = 0; i < commandBufferCount; i++) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002269 auto* secondary_cb = GetCBState(pCommandBuffers[i]);
2270 if (secondary_cb == nullptr) {
2271 continue;
2272 }
2273 auto& secondary = secondary_cb->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002274
2275 for (auto& early_clear : secondary.earlyClearAttachments) {
Hans-Kristian Arntzenfa8ef9f2021-06-29 12:07:59 +02002276 if (ClearAttachmentsIsFullClear(primary, uint32_t(early_clear.rects.size()), early_clear.rects.data())) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002277 RecordAttachmentClearAttachments(primary, primary_state, early_clear.framebufferAttachment,
2278 early_clear.colorAttachment, early_clear.aspects,
Hans-Kristian Arntzenfa8ef9f2021-06-29 12:07:59 +02002279 uint32_t(early_clear.rects.size()), early_clear.rects.data());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002280 } else {
2281 RecordAttachmentAccess(primary_state, early_clear.framebufferAttachment,
2282 early_clear.aspects);
2283 }
2284 }
2285
2286 for (auto& touch : secondary.touchesAttachments) {
2287 RecordAttachmentAccess(primary_state, touch.framebufferAttachment,
2288 touch.aspects);
2289 }
Hans-Kristian Arntzenc7eb82a2021-06-16 13:57:18 +02002290
2291 primary_state.numDrawCallsDepthEqualCompare += secondary.numDrawCallsDepthEqualCompare;
2292 primary_state.numDrawCallsDepthOnly += secondary.numDrawCallsDepthOnly;
Hans-Kristian Arntzenaf81dca2021-06-18 11:14:28 +02002293
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002294 auto* second_state = GetCBState(pCommandBuffers[i]);
Hans-Kristian Arntzenaf81dca2021-06-18 11:14:28 +02002295 if (second_state->hasDrawCmd) {
2296 primary->hasDrawCmd = true;
2297 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002298 }
2299
2300 ValidationStateTracker::PreCallRecordCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
2301}
2302
2303void BestPractices::RecordAttachmentAccess(RenderPassState& state, uint32_t fb_attachment, VkImageAspectFlags aspects) {
2304 // Called when we have a partial clear attachment, or a normal draw call which accesses an attachment.
2305 auto itr = std::find_if(state.touchesAttachments.begin(), state.touchesAttachments.end(),
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002306 [&](const AttachmentInfo& info) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002307 return info.framebufferAttachment == fb_attachment;
2308 });
2309
2310 if (itr != state.touchesAttachments.end()) {
2311 itr->aspects |= aspects;
2312 } else {
2313 state.touchesAttachments.push_back({ fb_attachment, aspects });
2314 }
2315}
2316
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002317void BestPractices::RecordAttachmentClearAttachments(CMD_BUFFER_STATE_BP* cmd_state, RenderPassState& state, uint32_t fb_attachment,
2318 uint32_t color_attachment, VkImageAspectFlags aspects, uint32_t rectCount,
2319 const VkClearRect* pRects) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002320 // If we observe a full clear before any other access to a frame buffer attachment,
2321 // we have candidate for redundant clear attachments.
2322 auto itr = std::find_if(state.touchesAttachments.begin(), state.touchesAttachments.end(),
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002323 [&](const AttachmentInfo& info) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002324 return info.framebufferAttachment == fb_attachment;
2325 });
2326
2327 uint32_t new_aspects = aspects;
2328 if (itr != state.touchesAttachments.end()) {
2329 new_aspects = aspects & ~itr->aspects;
2330 itr->aspects |= aspects;
2331 } else {
2332 state.touchesAttachments.push_back({ fb_attachment, aspects });
2333 }
2334
2335 if (new_aspects == 0) {
2336 return;
2337 }
2338
2339 if (cmd_state->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
2340 // The first command might be a clear, but might not be the first in the render pass, defer any checks until
2341 // CmdExecuteCommands.
2342 state.earlyClearAttachments.push_back({ fb_attachment, color_attachment, new_aspects,
2343 std::vector<VkClearRect>{pRects, pRects + rectCount} });
2344 }
2345}
2346
2347void BestPractices::PreCallRecordCmdClearAttachments(VkCommandBuffer commandBuffer,
2348 uint32_t attachmentCount, const VkClearAttachment* pClearAttachments,
2349 uint32_t rectCount, const VkClearRect* pRects) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002350 auto* cmd_state = GetCBState(commandBuffer);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002351 RENDER_PASS_STATE* rp_state = cmd_state->activeRenderPass.get();
2352 FRAMEBUFFER_STATE* fb_state = cmd_state->activeFramebuffer.get();
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002353 RenderPassState& tracking_state = cmd_state->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002354 bool is_secondary = cmd_state->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY;
2355
2356 if (rectCount == 0 || !rp_state) {
2357 return;
2358 }
2359
2360 if (!is_secondary && !fb_state) {
2361 return;
2362 }
2363
2364 // If we have a rect which covers the entire frame buffer, we have a LOAD_OP_CLEAR-like command.
2365 bool full_clear = ClearAttachmentsIsFullClear(cmd_state, rectCount, pRects);
2366
2367 auto& subpass = rp_state->createInfo.pSubpasses[cmd_state->activeSubpass];
2368 for (uint32_t i = 0; i < attachmentCount; i++) {
2369 auto& attachment = pClearAttachments[i];
2370 uint32_t fb_attachment = VK_ATTACHMENT_UNUSED;
2371 VkImageAspectFlags aspects = attachment.aspectMask;
2372
2373 if (aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) {
2374 if (subpass.pDepthStencilAttachment) {
2375 fb_attachment = subpass.pDepthStencilAttachment->attachment;
2376 }
2377 } else if (aspects & VK_IMAGE_ASPECT_COLOR_BIT) {
2378 fb_attachment = subpass.pColorAttachments[attachment.colorAttachment].attachment;
2379 }
2380
2381 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2382 if (full_clear) {
2383 RecordAttachmentClearAttachments(cmd_state, tracking_state,
2384 fb_attachment, attachment.colorAttachment, aspects,
2385 rectCount, pRects);
2386 } else {
2387 RecordAttachmentAccess(tracking_state, fb_attachment, aspects);
2388 }
2389 }
2390 }
2391
2392 ValidationStateTracker::PreCallRecordCmdClearAttachments(commandBuffer, attachmentCount, pClearAttachments,
2393 rectCount, pRects);
2394}
2395
Attilio Provenzano02859b22020-02-27 14:17:28 +00002396void BestPractices::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
2397 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
2398 ValidationStateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset,
2399 firstInstance);
2400
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002401 auto* cmd_state = GetCBState(commandBuffer);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002402 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices) {
2403 cmd_state->small_indexed_draw_call_count++;
2404 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002405
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002406 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDrawIndexed()");
Attilio Provenzano02859b22020-02-27 14:17:28 +00002407}
2408
Sam Walls0961ec02020-03-31 16:39:15 +01002409void BestPractices::PostCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
2410 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
2411 StateTracker::PostCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
2412 RecordCmdDrawType(commandBuffer, indexCount * instanceCount, "vkCmdDrawIndexed()");
2413}
2414
sfricke-samsung681ab7b2020-10-29 01:53:35 -07002415bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2416 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
2417 uint32_t maxDrawCount, uint32_t stride) const {
2418 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCount()");
2419
2420 return skip;
2421}
2422
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002423bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
2424 VkDeviceSize offset, VkBuffer countBuffer,
2425 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
2426 uint32_t stride) const {
2427 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCountKHR()");
Camden5b184be2019-08-13 07:50:19 -06002428
2429 return skip;
2430}
2431
2432bool BestPractices::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002433 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06002434 bool skip = false;
2435
2436 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002437 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
2438 "Warning: You are calling vkCmdDrawIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002439 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirect()");
Camden5b184be2019-08-13 07:50:19 -06002440 }
2441
2442 return skip;
2443}
2444
Sam Walls0961ec02020-03-31 16:39:15 +01002445void BestPractices::PostCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2446 uint32_t count, uint32_t stride) {
2447 StateTracker::PostCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, count, stride);
2448 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndirect()");
2449}
2450
Camden5b184be2019-08-13 07:50:19 -06002451bool BestPractices::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002452 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06002453 bool skip = false;
2454
2455 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002456 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
2457 "Warning: You are calling vkCmdDrawIndexedIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002458 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirect()");
Camden5b184be2019-08-13 07:50:19 -06002459 }
2460
2461 return skip;
2462}
2463
Sam Walls0961ec02020-03-31 16:39:15 +01002464void BestPractices::PostCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2465 uint32_t count, uint32_t stride) {
2466 StateTracker::PostCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, count, stride);
2467 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndexedIndirect()");
2468}
2469
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002470void BestPractices::ValidateBoundDescriptorSets(VkCommandBuffer commandBuffer, const char* function_name) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002471 auto* cb_state = GetCBState(commandBuffer);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002472
2473 if (cb_state) {
2474 for (auto descriptor_set : cb_state->validated_descriptor_sets) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002475 const auto& layout = *descriptor_set->GetLayout();
Hans-Kristian Arntzena8199012021-03-22 12:10:07 +01002476
2477 for (uint32_t index = 0; index < descriptor_set->GetBindingCount(); ++index) {
2478 // For bindless scenarios, we should not attempt to track descriptor set state.
2479 // It is highly uncertain which resources are actually bound.
2480 // Resources which are written to such a descriptor should be marked as indeterminate w.r.t. state.
2481 VkDescriptorBindingFlags flags = layout.GetDescriptorBindingFlagsFromIndex(index);
2482 if (flags & (VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT |
2483 VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT |
2484 VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT)) {
2485 continue;
2486 }
2487
2488 auto index_range = layout.GetGlobalIndexRangeFromIndex(index);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002489 for (uint32_t i = index_range.start; i < index_range.end; ++i) {
ZandroFargnoliacf12f02020-06-18 16:50:00 +01002490 VkImageView image_view{VK_NULL_HANDLE};
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002491
2492 auto descriptor = descriptor_set->GetDescriptorFromGlobalIndex(i);
2493 switch (descriptor->GetClass()) {
2494 case cvdescriptorset::DescriptorClass::Image: {
2495 if (const auto image_descriptor = static_cast<const cvdescriptorset::ImageDescriptor*>(descriptor)) {
2496 image_view = image_descriptor->GetImageView();
2497 }
Hans-Kristian Arntzenbc3a6152021-03-22 13:05:43 +01002498 break;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002499 }
2500 case cvdescriptorset::DescriptorClass::ImageSampler: {
2501 if (const auto image_sampler_descriptor =
2502 static_cast<const cvdescriptorset::ImageSamplerDescriptor*>(descriptor)) {
2503 image_view = image_sampler_descriptor->GetImageView();
2504 }
Hans-Kristian Arntzenbc3a6152021-03-22 13:05:43 +01002505 break;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002506 }
ZandroFargnoliacf12f02020-06-18 16:50:00 +01002507 default:
Hans-Kristian Arntzenbc3a6152021-03-22 13:05:43 +01002508 break;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002509 }
2510
2511 if (image_view) {
2512 IMAGE_VIEW_STATE* image_view_state = GetImageViewState(image_view);
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002513 QueueValidateImageView(cb_state->queue_submit_functions, function_name,
2514 image_view_state, IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002515 }
2516 }
2517 }
2518 }
2519 }
2520}
2521
2522void BestPractices::PreCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
2523 uint32_t firstVertex, uint32_t firstInstance) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002524 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDraw()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002525}
2526
2527void BestPractices::PreCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2528 uint32_t drawCount, uint32_t stride) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002529 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDrawIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002530}
2531
2532void BestPractices::PreCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2533 uint32_t drawCount, uint32_t stride) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002534 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDrawIndexedIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002535}
2536
Camden5b184be2019-08-13 07:50:19 -06002537bool BestPractices::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t groupCountX, uint32_t groupCountY,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002538 uint32_t groupCountZ) const {
Camden5b184be2019-08-13 07:50:19 -06002539 bool skip = false;
2540
2541 if ((groupCountX == 0) || (groupCountY == 0) || (groupCountZ == 0)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002542 skip |= LogWarning(device, kVUID_BestPractices_CmdDispatch_GroupCountZero,
2543 "Warning: You are calling vkCmdDispatch() while one or more groupCounts are zero (groupCountX = %" PRIu32
2544 ", groupCountY = %" PRIu32 ", groupCountZ = %" PRIu32 ").",
2545 groupCountX, groupCountY, groupCountZ);
Camden5b184be2019-08-13 07:50:19 -06002546 }
2547
2548 return skip;
2549}
Camden83a9c372019-08-14 11:41:38 -06002550
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002551bool BestPractices::PreCallValidateCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo* pSubpassEndInfo) const {
2552 bool skip = false;
2553 skip |= StateTracker::PreCallValidateCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
2554 skip |= ValidateCmdEndRenderPass(commandBuffer);
2555 return skip;
2556}
2557
2558bool BestPractices::PreCallValidateCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfo* pSubpassEndInfo) const {
2559 bool skip = false;
2560 skip |= StateTracker::PreCallValidateCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
2561 skip |= ValidateCmdEndRenderPass(commandBuffer);
2562 return skip;
2563}
2564
Sam Walls0961ec02020-03-31 16:39:15 +01002565bool BestPractices::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
2566 bool skip = false;
Sam Walls0961ec02020-03-31 16:39:15 +01002567 skip |= StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002568 skip |= ValidateCmdEndRenderPass(commandBuffer);
2569 return skip;
2570}
2571
2572bool BestPractices::ValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
2573 bool skip = false;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002574 const auto* cmd = GetCBState(commandBuffer);
Sam Walls0961ec02020-03-31 16:39:15 +01002575
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002576 if (cmd == nullptr) return skip;
2577 auto &render_pass_state = cmd->render_pass_state;
Sam Walls0961ec02020-03-31 16:39:15 +01002578
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002579 bool uses_depth = (render_pass_state.depthAttachment || render_pass_state.colorAttachment) &&
2580 render_pass_state.numDrawCallsDepthEqualCompare >= kDepthPrePassNumDrawCallsArm &&
2581 render_pass_state.numDrawCallsDepthOnly >= kDepthPrePassNumDrawCallsArm;
Sam Walls0961ec02020-03-31 16:39:15 +01002582 if (uses_depth) {
2583 skip |= LogPerformanceWarning(
2584 device, kVUID_BestPractices_EndRenderPass_DepthPrePassUsage,
2585 "%s Depth pre-passes may be in use. In general, this is not recommended, as in Arm Mali GPUs since "
2586 "Mali-T620, Forward Pixel Killing (FPK) can already perform automatic hidden surface removal; in which "
2587 "case, using depth pre-passes for hidden surface removal may worsen performance.",
2588 VendorSpecificTag(kBPVendorArm));
2589 }
2590
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002591 RENDER_PASS_STATE* rp = cmd->activeRenderPass.get();
2592
2593 if (VendorCheckEnabled(kBPVendorArm) && rp) {
2594
2595 // If we use an attachment on-tile, we should access it in some way. Otherwise,
2596 // it is redundant to have it be part of the render pass.
2597 // Only consider it redundant if it will actually consume bandwidth, i.e.
2598 // LOAD_OP_LOAD is used or STORE_OP_STORE. CLEAR -> DONT_CARE is benign,
2599 // as is using pure input attachments.
2600 // CLEAR -> STORE might be considered a "useful" thing to do, but
2601 // the optimal thing to do is to defer the clear until you're actually
2602 // going to render to the image.
2603
2604 uint32_t num_attachments = rp->createInfo.attachmentCount;
2605 for (uint32_t i = 0; i < num_attachments; i++) {
Hans-Kristian Arntzen237663c2021-07-01 14:36:40 +02002606 if (!RenderPassUsesAttachmentOnTile(rp->createInfo, i) ||
2607 RenderPassUsesAttachmentAsResolve(rp->createInfo, i)) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002608 continue;
2609 }
2610
2611 auto& attachment = rp->createInfo.pAttachments[i];
2612
2613 VkImageAspectFlags bandwidth_aspects = 0;
2614
2615 if (!FormatIsStencilOnly(attachment.format) &&
2616 (attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
2617 attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE)) {
2618 if (FormatHasDepth(attachment.format)) {
2619 bandwidth_aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
2620 } else {
2621 bandwidth_aspects |= VK_IMAGE_ASPECT_COLOR_BIT;
2622 }
2623 }
2624
2625 if (FormatHasStencil(attachment.format) &&
2626 (attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
2627 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE)) {
2628 bandwidth_aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
2629 }
2630
2631 if (!bandwidth_aspects) {
2632 continue;
2633 }
2634
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002635 auto itr = std::find_if(render_pass_state.touchesAttachments.begin(), render_pass_state.touchesAttachments.end(),
2636 [&](const AttachmentInfo& info) { return info.framebufferAttachment == i; });
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002637 uint32_t untouched_aspects = bandwidth_aspects;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002638 if (itr != render_pass_state.touchesAttachments.end()) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002639 untouched_aspects &= ~itr->aspects;
2640 }
2641
2642 if (untouched_aspects) {
2643 skip |= LogPerformanceWarning(
2644 device, kVUID_BestPractices_EndRenderPass_RedundantAttachmentOnTile,
2645 "%s Render pass was ended, but attachment #%u (format: %u, untouched aspects 0x%x) "
2646 "was never accessed by a pipeline or clear command. "
2647 "On tile-based architectures, LOAD_OP_LOAD and STORE_OP_STORE consume bandwidth and should not be part of the render pass "
2648 "if the attachments are not intended to be accessed.",
2649 VendorSpecificTag(kBPVendorArm), i, attachment.format, untouched_aspects);
2650 }
2651 }
2652 }
2653
Sam Walls0961ec02020-03-31 16:39:15 +01002654 return skip;
2655}
2656
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002657void BestPractices::PreCallRecordCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002658 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDispatch()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002659}
2660
2661void BestPractices::PreCallRecordCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002662 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDispatchIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002663}
2664
Camden Stocker9c051442019-11-06 14:28:43 -08002665bool BestPractices::ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(VkPhysicalDevice physicalDevice,
2666 const char* api_name) const {
2667 bool skip = false;
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002668 const auto* bp_pd_state = GetPhysicalDeviceState(physicalDevice);
Camden Stocker9c051442019-11-06 14:28:43 -08002669
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002670 if (bp_pd_state) {
2671 if (bp_pd_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState == UNCALLED) {
2672 skip |= LogWarning(physicalDevice, kVUID_BestPractices_DisplayPlane_PropertiesNotCalled,
2673 "Potential problem with calling %s() without first retrieving properties from "
2674 "vkGetPhysicalDeviceDisplayPlanePropertiesKHR or vkGetPhysicalDeviceDisplayPlaneProperties2KHR.",
2675 api_name);
2676 }
Camden Stocker9c051442019-11-06 14:28:43 -08002677 }
2678
2679 return skip;
2680}
2681
Camden83a9c372019-08-14 11:41:38 -06002682bool BestPractices::PreCallValidateGetDisplayPlaneSupportedDisplaysKHR(VkPhysicalDevice physicalDevice, uint32_t planeIndex,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002683 uint32_t* pDisplayCount, VkDisplayKHR* pDisplays) const {
Camden83a9c372019-08-14 11:41:38 -06002684 bool skip = false;
2685
Camden Stocker9c051442019-11-06 14:28:43 -08002686 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneSupportedDisplaysKHR");
Camden83a9c372019-08-14 11:41:38 -06002687
Camden Stocker9c051442019-11-06 14:28:43 -08002688 return skip;
2689}
2690
2691bool BestPractices::PreCallValidateGetDisplayPlaneCapabilitiesKHR(VkPhysicalDevice physicalDevice, VkDisplayModeKHR mode,
2692 uint32_t planeIndex,
2693 VkDisplayPlaneCapabilitiesKHR* pCapabilities) const {
2694 bool skip = false;
2695
2696 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilitiesKHR");
2697
2698 return skip;
2699}
2700
2701bool BestPractices::PreCallValidateGetDisplayPlaneCapabilities2KHR(VkPhysicalDevice physicalDevice,
2702 const VkDisplayPlaneInfo2KHR* pDisplayPlaneInfo,
2703 VkDisplayPlaneCapabilities2KHR* pCapabilities) const {
2704 bool skip = false;
2705
2706 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilities2KHR");
Camden83a9c372019-08-14 11:41:38 -06002707
2708 return skip;
2709}
Camden05de2d42019-08-19 10:23:56 -06002710
2711bool BestPractices::PreCallValidateGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain, uint32_t* pSwapchainImageCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002712 VkImage* pSwapchainImages) const {
Camden05de2d42019-08-19 10:23:56 -06002713 bool skip = false;
2714
Nathaniel Cesario39152e62021-07-02 13:04:16 -06002715 const auto* swapchain_state = static_cast<SWAPCHAIN_STATE_BP*>(Get<SWAPCHAIN_NODE>(swapchain));
Camden05de2d42019-08-19 10:23:56 -06002716
Nathaniel Cesario39152e62021-07-02 13:04:16 -06002717 if (swapchain_state && pSwapchainImages) {
Camden05de2d42019-08-19 10:23:56 -06002718 // Compare the preliminary value of *pSwapchainImageCount with the value this time:
Nathaniel Cesario39152e62021-07-02 13:04:16 -06002719 if (swapchain_state->vkGetSwapchainImagesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002720 skip |=
2721 LogWarning(device, kVUID_Core_Swapchain_PriorCount,
2722 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImageCount; but no prior positive value has "
2723 "been seen for pSwapchainImages.");
Camden05de2d42019-08-19 10:23:56 -06002724 }
Camden05de2d42019-08-19 10:23:56 -06002725
Nathaniel Cesario4ce98382021-05-28 11:33:20 -06002726 if (*pSwapchainImageCount > swapchain_state->get_swapchain_image_count) {
2727 skip |= LogWarning(
2728 device, kVUID_BestPractices_Swapchain_InvalidCount,
2729 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImages, and with pSwapchainImageCount set to a "
Nadav Gevaf0808442021-05-21 13:51:25 -04002730 "value (%" PRId32 ") that is greater than the value (%" PRId32 ") that was returned when pSwapchainImages was NULL.",
Nathaniel Cesario4ce98382021-05-28 11:33:20 -06002731 *pSwapchainImageCount, swapchain_state->get_swapchain_image_count);
2732 }
2733 }
2734
Camden05de2d42019-08-19 10:23:56 -06002735 return skip;
2736}
2737
2738// Common function to handle validation for GetPhysicalDeviceQueueFamilyProperties & 2KHR version
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002739bool BestPractices::ValidateCommonGetPhysicalDeviceQueueFamilyProperties(const PHYSICAL_DEVICE_STATE* bp_pd_state,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002740 uint32_t requested_queue_family_property_count,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002741 const CALL_STATE call_state,
2742 const char* caller_name) const {
Camden05de2d42019-08-19 10:23:56 -06002743 bool skip = false;
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002744 // Verify that for each physical device, this command is called first with NULL pQueueFamilyProperties in order to get count
2745 if (UNCALLED == call_state) {
2746 skip |= LogWarning(
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002747 bp_pd_state->Handle(), kVUID_Core_DevLimit_MissingQueryCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002748 "%s is called with non-NULL pQueueFamilyProperties before obtaining pQueueFamilyPropertyCount. It is "
2749 "recommended "
2750 "to first call %s with NULL pQueueFamilyProperties in order to obtain the maximal pQueueFamilyPropertyCount.",
2751 caller_name, caller_name);
2752 // Then verify that pCount that is passed in on second call matches what was returned
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002753 } else if (bp_pd_state->queue_family_known_count != requested_queue_family_property_count) {
2754 skip |= LogWarning(bp_pd_state->Handle(), kVUID_Core_DevLimit_CountMismatch,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002755 "%s is called with non-NULL pQueueFamilyProperties and pQueueFamilyPropertyCount value %" PRIu32
2756 ", but the largest previously returned pQueueFamilyPropertyCount for this physicalDevice is %" PRIu32
2757 ". It is recommended to instead receive all the properties by calling %s with "
2758 "pQueueFamilyPropertyCount that was "
2759 "previously obtained by calling %s with NULL pQueueFamilyProperties.",
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002760 caller_name, requested_queue_family_property_count, bp_pd_state->queue_family_known_count, caller_name,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002761 caller_name);
Camden05de2d42019-08-19 10:23:56 -06002762 }
2763
2764 return skip;
2765}
2766
Jeff Bolz5c801d12019-10-09 10:38:45 -05002767bool BestPractices::PreCallValidateBindAccelerationStructureMemoryNV(
2768 VkDevice device, uint32_t bindInfoCount, const VkBindAccelerationStructureMemoryInfoNV* pBindInfos) const {
Camden Stocker82510582019-09-03 14:00:16 -06002769 bool skip = false;
2770
2771 for (uint32_t i = 0; i < bindInfoCount; i++) {
sourav parmarcd5fb182020-07-17 12:58:44 -07002772 const ACCELERATION_STRUCTURE_STATE* as_state = GetAccelerationStructureStateNV(pBindInfos[i].accelerationStructure);
Camden Stocker82510582019-09-03 14:00:16 -06002773 if (!as_state->memory_requirements_checked) {
2774 // There's not an explicit requirement in the spec to call vkGetImageMemoryRequirements() prior to calling
2775 // BindAccelerationStructureMemoryNV but it's implied in that memory being bound must conform with
2776 // VkAccelerationStructureMemoryRequirementsInfoNV from vkGetAccelerationStructureMemoryRequirementsNV
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002777 skip |= LogWarning(
2778 device, kVUID_BestPractices_BindAccelNV_NoMemReqQuery,
Camden Stocker82510582019-09-03 14:00:16 -06002779 "vkBindAccelerationStructureMemoryNV(): "
2780 "Binding memory to %s but vkGetAccelerationStructureMemoryRequirementsNV() has not been called on that structure.",
2781 report_data->FormatHandle(pBindInfos[i].accelerationStructure).c_str());
2782 }
2783 }
2784
2785 return skip;
2786}
2787
Camden05de2d42019-08-19 10:23:56 -06002788bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
2789 uint32_t* pQueueFamilyPropertyCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002790 VkQueueFamilyProperties* pQueueFamilyProperties) const {
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002791 const auto* bp_pd_state = GetPhysicalDeviceState(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002792 if (pQueueFamilyProperties && bp_pd_state) {
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002793 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(bp_pd_state, *pQueueFamilyPropertyCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002794 bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
2795 "vkGetPhysicalDeviceQueueFamilyProperties()");
2796 }
2797 return false;
Camden05de2d42019-08-19 10:23:56 -06002798}
2799
Mike Schuchardt2df08912020-12-15 16:28:09 -08002800bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
2801 uint32_t* pQueueFamilyPropertyCount,
2802 VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002803 const auto* bp_pd_state = GetPhysicalDeviceState(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002804 if (pQueueFamilyProperties && bp_pd_state) {
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002805 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(bp_pd_state, *pQueueFamilyPropertyCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002806 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
2807 "vkGetPhysicalDeviceQueueFamilyProperties2()");
2808 }
2809 return false;
Camden05de2d42019-08-19 10:23:56 -06002810}
2811
Jeff Bolz5c801d12019-10-09 10:38:45 -05002812bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2KHR(
Mike Schuchardt2df08912020-12-15 16:28:09 -08002813 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount, VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002814 const auto* bp_pd_state = GetPhysicalDeviceState(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002815 if (pQueueFamilyProperties && bp_pd_state) {
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002816 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(bp_pd_state, *pQueueFamilyPropertyCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002817 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
2818 "vkGetPhysicalDeviceQueueFamilyProperties2KHR()");
2819 }
2820 return false;
Camden05de2d42019-08-19 10:23:56 -06002821}
2822
2823bool BestPractices::PreCallValidateGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
2824 uint32_t* pSurfaceFormatCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002825 VkSurfaceFormatKHR* pSurfaceFormats) const {
Camden05de2d42019-08-19 10:23:56 -06002826 if (!pSurfaceFormats) return false;
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002827 const auto* bp_pd_state = GetPhysicalDeviceState(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002828 const auto& call_state = bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState;
Camden05de2d42019-08-19 10:23:56 -06002829 bool skip = false;
2830 if (call_state == UNCALLED) {
2831 // Since we haven't recorded a preliminary value of *pSurfaceFormatCount, that likely means that the application didn't
2832 // previously call this function with a NULL value of pSurfaceFormats:
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002833 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_MustQueryCount,
2834 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount; but no prior "
2835 "positive value has been seen for pSurfaceFormats.");
Camden05de2d42019-08-19 10:23:56 -06002836 } else {
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002837 auto prev_format_count = static_cast<uint32_t>(bp_pd_state->surface_formats.size());
Peter Chene191bd72019-09-16 13:04:37 -04002838 if (*pSurfaceFormatCount > prev_format_count) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002839 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_CountMismatch,
2840 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount, and with "
2841 "pSurfaceFormats set to a value (%u) that is greater than the value (%u) that was returned "
2842 "when pSurfaceFormatCount was NULL.",
2843 *pSurfaceFormatCount, prev_format_count);
Camden05de2d42019-08-19 10:23:56 -06002844 }
2845 }
2846 return skip;
2847}
Camden Stocker23cc47d2019-09-03 14:53:57 -06002848
2849bool BestPractices::PreCallValidateQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002850 VkFence fence) const {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002851 bool skip = false;
2852
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002853 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
2854 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
Camden Stocker23cc47d2019-09-03 14:53:57 -06002855 // 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 -07002856 layer_data::unordered_set<const IMAGE_STATE*> sparse_images;
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002857 // Track images getting metadata bound by this call in a set, it'll be recorded into the image_state
2858 // in RecordQueueBindSparse.
Jeremy Gebbencbf22862021-03-03 12:01:22 -07002859 layer_data::unordered_set<const IMAGE_STATE*> sparse_images_with_metadata;
Camden Stocker23cc47d2019-09-03 14:53:57 -06002860 // 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 -07002861 for (uint32_t i = 0; i < bind_info.imageBindCount; ++i) {
2862 const auto& image_bind = bind_info.pImageBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04002863 auto image_state = Get<IMAGE_STATE>(image_bind.image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002864 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002865 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002866 }
Camden Stocker23cc47d2019-09-03 14:53:57 -06002867 sparse_images.insert(image_state);
2868 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
2869 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
2870 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002871 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002872 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
2873 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002874 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002875 }
2876 }
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06002877 if (!image_state->memory_requirements_checked[0]) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002878 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002879 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002880 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
2881 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002882 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002883 }
2884 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002885 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
2886 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04002887 auto image_state = Get<IMAGE_STATE>(bind_info.pImageOpaqueBinds[i].image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002888 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002889 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002890 }
Camden Stocker23cc47d2019-09-03 14:53:57 -06002891 sparse_images.insert(image_state);
2892 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
2893 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
2894 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002895 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002896 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
2897 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002898 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002899 }
2900 }
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06002901 if (!image_state->memory_requirements_checked[0]) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002902 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002903 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002904 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
2905 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002906 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002907 }
2908 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
2909 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002910 sparse_images_with_metadata.insert(image_state);
Camden Stocker23cc47d2019-09-03 14:53:57 -06002911 }
2912 }
2913 }
2914 for (const auto& sparse_image_state : sparse_images) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002915 if (sparse_image_state->sparse_metadata_required && !sparse_image_state->sparse_metadata_bound &&
2916 sparse_images_with_metadata.find(sparse_image_state) == sparse_images_with_metadata.end()) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002917 // Warn if sparse image binding metadata required for image with sparse binding, but metadata not bound
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002918 skip |= LogWarning(sparse_image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002919 "vkQueueBindSparse(): Binding sparse memory to %s which requires a metadata aspect but no "
2920 "binding with VK_SPARSE_MEMORY_BIND_METADATA_BIT set was made.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002921 report_data->FormatHandle(sparse_image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002922 }
2923 }
2924 }
2925
2926 return skip;
2927}
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002928
Mark Lobodzinski84101d72020-04-24 09:43:48 -06002929void BestPractices::ManualPostCallRecordQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
2930 VkFence fence, VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07002931 if (result != VK_SUCCESS) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07002932 return;
2933 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002934
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002935 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
2936 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
2937 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
2938 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04002939 auto image_state = Get<IMAGE_STATE>(bind_info.pImageOpaqueBinds[i].image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002940 if (!image_state) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002941 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002942 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002943 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
2944 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
2945 image_state->sparse_metadata_bound = true;
2946 }
2947 }
2948 }
2949 }
2950}
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002951
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002952bool BestPractices::ClearAttachmentsIsFullClear(const CMD_BUFFER_STATE_BP* cmd, uint32_t rectCount,
2953 const VkClearRect* pRects) const {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002954 if (cmd->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
2955 // We don't know the accurate render area in a secondary,
2956 // so assume we clear the entire frame buffer.
2957 // This is resolved in CmdExecuteCommands where we can check if the clear is a full clear.
2958 return true;
2959 }
2960
2961 // If we have a rect which covers the entire frame buffer, we have a LOAD_OP_CLEAR-like command.
2962 for (uint32_t i = 0; i < rectCount; i++) {
2963 auto& rect = pRects[i];
2964 auto& render_area = cmd->activeRenderPassBeginInfo.renderArea;
2965 if (rect.rect.extent.width == render_area.extent.width && rect.rect.extent.height == render_area.extent.height) {
2966 return true;
2967 }
2968 }
2969
2970 return false;
2971}
2972
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002973bool BestPractices::ValidateClearAttachment(VkCommandBuffer commandBuffer, const CMD_BUFFER_STATE_BP* cmd, uint32_t fb_attachment,
2974 uint32_t color_attachment, VkImageAspectFlags aspects, bool secondary) const {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002975 const RENDER_PASS_STATE* rp = cmd->activeRenderPass.get();
2976 bool skip = false;
2977
2978 if (!rp || fb_attachment == VK_ATTACHMENT_UNUSED) {
2979 return skip;
2980 }
2981
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002982 const auto& rp_state = cmd->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002983
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002984 auto attachment_itr = std::find_if(rp_state.touchesAttachments.begin(), rp_state.touchesAttachments.end(),
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002985 [&](const AttachmentInfo& info) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002986 return info.framebufferAttachment == fb_attachment;
2987 });
2988
2989 // Only report aspects which haven't been touched yet.
2990 VkImageAspectFlags new_aspects = aspects;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002991 if (attachment_itr != rp_state.touchesAttachments.end()) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002992 new_aspects &= ~attachment_itr->aspects;
2993 }
2994
2995 // Warn if this is issued prior to Draw Cmd and clearing the entire attachment
2996 if (!cmd->hasDrawCmd) {
2997 skip |= LogPerformanceWarning(
2998 commandBuffer, kVUID_BestPractices_DrawState_ClearCmdBeforeDraw,
Hans-Kristian Arntzen4ddd6182021-06-18 12:16:33 +02002999 "vkCmdClearAttachments() issued on %s prior to any Draw Cmds in current render pass. It is recommended you "
3000 "use RenderPass LOAD_OP_CLEAR on attachments instead.",
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003001 report_data->FormatHandle(commandBuffer).c_str());
3002 }
3003
3004 if ((new_aspects & VK_IMAGE_ASPECT_COLOR_BIT) &&
3005 rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
3006 skip |= LogPerformanceWarning(
3007 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
3008 "%svkCmdClearAttachments() issued on %s for color attachment #%u in this subpass, "
3009 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
3010 "it is more efficient.",
3011 secondary ? "vkCmdExecuteCommands(): " : "",
3012 report_data->FormatHandle(commandBuffer).c_str(), color_attachment);
3013 }
3014
3015 if ((new_aspects & VK_IMAGE_ASPECT_DEPTH_BIT) &&
3016 rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
3017 skip |= LogPerformanceWarning(
3018 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
3019 "%svkCmdClearAttachments() issued on %s for the depth attachment in this subpass, "
3020 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
3021 "it is more efficient.",
3022 secondary ? "vkCmdExecuteCommands(): " : "",
3023 report_data->FormatHandle(commandBuffer).c_str());
3024 }
3025
3026 if ((new_aspects & VK_IMAGE_ASPECT_STENCIL_BIT) &&
3027 rp->createInfo.pAttachments[fb_attachment].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
3028 skip |= LogPerformanceWarning(
3029 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
3030 "%svkCmdClearAttachments() issued on %s for the stencil attachment in this subpass, "
3031 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
3032 "it is more efficient.",
3033 secondary ? "vkCmdExecuteCommands(): " : "",
3034 report_data->FormatHandle(commandBuffer).c_str());
3035 }
3036
3037 return skip;
3038}
3039
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003040bool BestPractices::PreCallValidateCmdClearAttachments(VkCommandBuffer commandBuffer, uint32_t attachmentCount,
Camden Stockerf55721f2019-09-09 11:04:49 -06003041 const VkClearAttachment* pAttachments, uint32_t rectCount,
3042 const VkClearRect* pRects) const {
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003043 bool skip = false;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003044 const auto* cb_node = GetCBState(commandBuffer);
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003045 if (!cb_node) return skip;
3046
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003047 if (cb_node->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
3048 // Defer checks to ExecuteCommands.
3049 return skip;
3050 }
3051
3052 // Only care about full clears, partial clears might have legitimate uses.
3053 if (!ClearAttachmentsIsFullClear(cb_node, rectCount, pRects)) {
3054 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003055 }
3056
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003057 // Check for uses of ClearAttachments along with LOAD_OP_LOAD,
3058 // as it can be more efficient to just use LOAD_OP_CLEAR
locke-lunargaecf2152020-05-12 17:15:41 -06003059 const RENDER_PASS_STATE* rp = cb_node->activeRenderPass.get();
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003060 if (rp) {
3061 const auto& subpass = rp->createInfo.pSubpasses[cb_node->activeSubpass];
3062
3063 for (uint32_t i = 0; i < attachmentCount; i++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02003064 const auto& attachment = pAttachments[i];
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003065
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003066 if (attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
3067 uint32_t color_attachment = attachment.colorAttachment;
3068 uint32_t fb_attachment = subpass.pColorAttachments[color_attachment].attachment;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003069 skip |= ValidateClearAttachment(commandBuffer, cb_node,
3070 fb_attachment, color_attachment,
3071 attachment.aspectMask, false);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003072 }
3073
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003074 if (subpass.pDepthStencilAttachment &&
3075 (attachment.aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT))) {
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003076 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003077 skip |= ValidateClearAttachment(commandBuffer, cb_node,
3078 fb_attachment, VK_ATTACHMENT_UNUSED,
3079 attachment.aspectMask, false);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003080 }
3081 }
3082 }
3083
Nadav Gevaf0808442021-05-21 13:51:25 -04003084 if (VendorCheckEnabled(kBPVendorAMD)) {
3085 for (uint32_t attachment_idx = 0; attachment_idx < attachmentCount; attachment_idx++) {
3086 if (pAttachments[attachment_idx].aspectMask == VK_IMAGE_ASPECT_COLOR_BIT) {
3087 bool black_check = false;
3088 black_check |= pAttachments[attachment_idx].clearValue.color.float32[0] != 0.0f;
3089 black_check |= pAttachments[attachment_idx].clearValue.color.float32[1] != 0.0f;
3090 black_check |= pAttachments[attachment_idx].clearValue.color.float32[2] != 0.0f;
3091 black_check |= pAttachments[attachment_idx].clearValue.color.float32[3] != 0.0f &&
3092 pAttachments[attachment_idx].clearValue.color.float32[3] != 1.0f;
3093
3094 bool white_check = false;
3095 white_check |= pAttachments[attachment_idx].clearValue.color.float32[0] != 1.0f;
3096 white_check |= pAttachments[attachment_idx].clearValue.color.float32[1] != 1.0f;
3097 white_check |= pAttachments[attachment_idx].clearValue.color.float32[2] != 1.0f;
3098 white_check |= pAttachments[attachment_idx].clearValue.color.float32[3] != 0.0f &&
3099 pAttachments[attachment_idx].clearValue.color.float32[3] != 1.0f;
3100
3101 if (black_check && white_check) {
3102 skip |= LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachment_FastClearValues,
3103 "%s Performance warning: vkCmdClearAttachments() clear value for color attachment %" PRId32 " is not a fast clear value."
3104 "Consider changing to one of the following:"
3105 "RGBA(0, 0, 0, 0) "
3106 "RGBA(0, 0, 0, 1) "
3107 "RGBA(1, 1, 1, 0) "
3108 "RGBA(1, 1, 1, 1)",
3109 VendorSpecificTag(kBPVendorAMD), attachment_idx);
3110 }
3111 } else {
3112 if ((pAttachments[attachment_idx].clearValue.depthStencil.depth != 0 &&
3113 pAttachments[attachment_idx].clearValue.depthStencil.depth != 1) &&
3114 pAttachments[attachment_idx].clearValue.depthStencil.stencil != 0) {
3115 skip |= LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachment_FastClearValues,
3116 "%s Performance warning: vkCmdClearAttachments() clear value for depth/stencil "
3117 "attachment %" PRId32 " is not a fast clear value."
3118 "Consider changing to one of the following:"
3119 "D=0.0f, S=0"
3120 "D=1.0f, S=0",
3121 VendorSpecificTag(kBPVendorAMD), attachment_idx);
3122 }
3123 }
3124 }
3125 }
3126
Camden Stockerf55721f2019-09-09 11:04:49 -06003127 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003128}
Attilio Provenzano02859b22020-02-27 14:17:28 +00003129
3130bool BestPractices::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3131 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3132 const VkImageResolve* pRegions) const {
3133 bool skip = false;
3134
3135 skip |= VendorCheckEnabled(kBPVendorArm) &&
3136 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage_ResolvingImage,
3137 "%s Attempting to use vkCmdResolveImage to resolve a multisampled image. "
3138 "This is a very slow and extremely bandwidth intensive path. "
3139 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
3140 VendorSpecificTag(kBPVendorArm));
3141
3142 return skip;
3143}
3144
Jeff Leger178b1e52020-10-05 12:22:23 -04003145bool BestPractices::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
3146 const VkResolveImageInfo2KHR* pResolveImageInfo) const {
3147 bool skip = false;
3148
3149 skip |= VendorCheckEnabled(kBPVendorArm) &&
3150 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2KHR_ResolvingImage,
3151 "%s Attempting to use vkCmdResolveImage2KHR to resolve a multisampled image. "
3152 "This is a very slow and extremely bandwidth intensive path. "
3153 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
3154 VendorSpecificTag(kBPVendorArm));
3155
3156 return skip;
3157}
3158
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003159void BestPractices::PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3160 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3161 const VkImageResolve* pRegions) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003162 auto* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003163 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003164 auto* src = GetImageUsageState(srcImage);
3165 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003166
3167 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003168 QueueValidateImage(funcs, "vkCmdResolveImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pRegions[i].srcSubresource);
3169 QueueValidateImage(funcs, "vkCmdResolveImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003170 }
3171}
3172
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01003173void BestPractices::PreCallRecordCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
3174 const VkResolveImageInfo2KHR* pResolveImageInfo) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003175 auto* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003176 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003177 auto* src = GetImageUsageState(pResolveImageInfo->srcImage);
3178 auto* dst = GetImageUsageState(pResolveImageInfo->dstImage);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01003179 uint32_t regionCount = pResolveImageInfo->regionCount;
3180
3181 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003182 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pResolveImageInfo->pRegions[i].srcSubresource);
3183 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pResolveImageInfo->pRegions[i].dstSubresource);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01003184 }
3185}
3186
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003187void BestPractices::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
3188 const VkClearColorValue* pColor, uint32_t rangeCount,
3189 const VkImageSubresourceRange* pRanges) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003190 auto* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003191 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003192 auto* dst = GetImageUsageState(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003193
3194 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003195 QueueValidateImage(funcs, "vkCmdClearColorImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003196 }
3197}
3198
3199void BestPractices::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
3200 const VkClearDepthStencilValue* pDepthStencil, uint32_t rangeCount,
3201 const VkImageSubresourceRange* pRanges) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003202 auto* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003203 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003204 auto* dst = GetImageUsageState(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003205
3206 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003207 QueueValidateImage(funcs, "vkCmdClearDepthStencilImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003208 }
3209}
3210
3211void BestPractices::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3212 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3213 const VkImageCopy* pRegions) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003214 auto* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003215 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003216 auto* src = GetImageUsageState(srcImage);
3217 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003218
3219 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003220 QueueValidateImage(funcs, "vkCmdCopyImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].srcSubresource);
3221 QueueValidateImage(funcs, "vkCmdCopyImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003222 }
3223}
3224
3225void BestPractices::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
3226 VkImageLayout dstImageLayout, uint32_t regionCount,
3227 const VkBufferImageCopy* pRegions) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003228 auto* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003229 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003230 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003231
3232 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003233 QueueValidateImage(funcs, "vkCmdCopyBufferToImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003234 }
3235}
3236
3237void BestPractices::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3238 VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy* pRegions) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003239 auto* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003240 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003241 auto* src = GetImageUsageState(srcImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003242
3243 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003244 QueueValidateImage(funcs, "vkCmdCopyImageToBuffer()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003245 }
3246}
3247
3248void BestPractices::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3249 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3250 const VkImageBlit* pRegions, VkFilter filter) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003251 auto* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003252 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003253 auto* src = GetImageUsageState(srcImage);
3254 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003255
3256 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003257 QueueValidateImage(funcs, "vkCmdBlitImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_READ, pRegions[i].srcSubresource);
3258 QueueValidateImage(funcs, "vkCmdBlitImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003259 }
3260}
3261
Attilio Provenzano02859b22020-02-27 14:17:28 +00003262bool BestPractices::PreCallValidateCreateSampler(VkDevice device, const VkSamplerCreateInfo* pCreateInfo,
3263 const VkAllocationCallbacks* pAllocator, VkSampler* pSampler) const {
3264 bool skip = false;
3265
3266 if (VendorCheckEnabled(kBPVendorArm)) {
3267 if ((pCreateInfo->addressModeU != pCreateInfo->addressModeV) || (pCreateInfo->addressModeV != pCreateInfo->addressModeW)) {
3268 skip |= LogPerformanceWarning(
3269 device, kVUID_BestPractices_CreateSampler_DifferentWrappingModes,
3270 "%s Creating a sampler object with wrapping modes which do not match (U = %u, V = %u, W = %u). "
3271 "This may cause reduced performance even if only U (1D image) or U/V wrapping modes (2D "
3272 "image) are actually used. If you need different wrapping modes, disregard this warning.",
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -06003273 VendorSpecificTag(kBPVendorArm), pCreateInfo->addressModeU, pCreateInfo->addressModeV, pCreateInfo->addressModeW);
Attilio Provenzano02859b22020-02-27 14:17:28 +00003274 }
3275
3276 if ((pCreateInfo->minLod != 0.0f) || (pCreateInfo->maxLod < VK_LOD_CLAMP_NONE)) {
3277 skip |= LogPerformanceWarning(
3278 device, kVUID_BestPractices_CreateSampler_LodClamping,
3279 "%s Creating a sampler object with LOD clamping (minLod = %f, maxLod = %f). This may cause reduced performance. "
3280 "Instead of clamping LOD in the sampler, consider using an VkImageView which restricts the mip-levels, set minLod "
3281 "to 0.0, and maxLod to VK_LOD_CLAMP_NONE.",
3282 VendorSpecificTag(kBPVendorArm), pCreateInfo->minLod, pCreateInfo->maxLod);
3283 }
3284
3285 if (pCreateInfo->mipLodBias != 0.0f) {
3286 skip |=
3287 LogPerformanceWarning(device, kVUID_BestPractices_CreateSampler_LodBias,
3288 "%s Creating a sampler object with LOD bias != 0.0 (%f). This will lead to less efficient "
3289 "descriptors being created and may cause reduced performance.",
3290 VendorSpecificTag(kBPVendorArm), pCreateInfo->mipLodBias);
3291 }
3292
3293 if ((pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
3294 pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
3295 pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER) &&
3296 (pCreateInfo->borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK)) {
3297 skip |= LogPerformanceWarning(
3298 device, kVUID_BestPractices_CreateSampler_BorderClampColor,
3299 "%s Creating a sampler object with border clamping and borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK. "
3300 "This will lead to less efficient descriptors being created and may cause reduced performance. "
3301 "If possible, use VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK as the border color.",
3302 VendorSpecificTag(kBPVendorArm));
3303 }
3304
3305 if (pCreateInfo->unnormalizedCoordinates) {
3306 skip |= LogPerformanceWarning(
3307 device, kVUID_BestPractices_CreateSampler_UnnormalizedCoordinates,
3308 "%s Creating a sampler object with unnormalized coordinates. This will lead to less efficient "
3309 "descriptors being created and may cause reduced performance.",
3310 VendorSpecificTag(kBPVendorArm));
3311 }
3312
3313 if (pCreateInfo->anisotropyEnable) {
3314 skip |= LogPerformanceWarning(
3315 device, kVUID_BestPractices_CreateSampler_Anisotropy,
3316 "%s Creating a sampler object with anisotropy. This will lead to less efficient descriptors being created "
3317 "and may cause reduced performance.",
3318 VendorSpecificTag(kBPVendorArm));
3319 }
3320 }
3321
3322 return skip;
3323}
Sam Walls8e77e4f2020-03-16 20:47:40 +00003324
Nadav Gevaf0808442021-05-21 13:51:25 -04003325void BestPractices::PreCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
3326 const VkGraphicsPipelineCreateInfo* pCreateInfos,
3327 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
3328 void* cgpl_state) {
3329 ValidationStateTracker::PreCallRecordCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos, pAllocator,
3330 pPipelines);
3331 // AMD best practice
3332 num_pso += createInfoCount;
3333}
3334
3335bool BestPractices::PreCallValidateUpdateDescriptorSets(VkDevice device, uint32_t descriptorWriteCount,
3336 const VkWriteDescriptorSet* pDescriptorWrites, uint32_t descriptorCopyCount,
3337 const VkCopyDescriptorSet* pDescriptorCopies) const {
3338 bool skip = false;
3339 if (VendorCheckEnabled(kBPVendorAMD)) {
3340 if (descriptorCopyCount > 0) {
3341 skip |= LogPerformanceWarning(device, kVUID_BestPractices_UpdateDescriptors_AvoidCopyingDescriptors,
3342 "%s Performance warning: copying descriptor sets is not recommended",
3343 VendorSpecificTag(kBPVendorAMD));
3344 }
3345 }
3346
3347 return skip;
3348}
3349
3350bool BestPractices::PreCallValidateCreateDescriptorUpdateTemplate(VkDevice device,
3351 const VkDescriptorUpdateTemplateCreateInfo* pCreateInfo,
3352 const VkAllocationCallbacks* pAllocator,
3353 VkDescriptorUpdateTemplate* pDescriptorUpdateTemplate) const {
3354 bool skip = false;
3355 if (VendorCheckEnabled(kBPVendorAMD)) {
3356 skip |= LogPerformanceWarning(device, kVUID_BestPractices_UpdateDescriptors_PreferNonTemplate,
3357 "%s Performance warning: using DescriptorSetWithTemplate is not recommended. Prefer using "
3358 "vkUpdateDescriptorSet instead",
3359 VendorSpecificTag(kBPVendorAMD));
3360 }
3361
3362 return skip;
3363}
3364
3365bool BestPractices::PreCallValidateCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
3366 const VkClearColorValue* pColor, uint32_t rangeCount,
3367 const VkImageSubresourceRange* pRanges) const {
3368 bool skip = false;
3369 if (VendorCheckEnabled(kBPVendorAMD)) {
3370 skip |= LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachment_ClearImage,
3371 "%s Performance warning: using vkCmdClearColorImage is not recommended. Prefer using LOAD_OP_CLEAR or "
3372 "vkCmdClearAttachments instead",
3373 VendorSpecificTag(kBPVendorAMD));
3374 }
3375
3376 return skip;
3377}
3378
3379bool BestPractices::PreCallValidateCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image,
3380 VkImageLayout imageLayout,
3381 const VkClearDepthStencilValue* pDepthStencil, uint32_t rangeCount,
3382 const VkImageSubresourceRange* pRanges) const {
3383 bool skip = false;
3384 if (VendorCheckEnabled(kBPVendorAMD)) {
3385 skip |= LogPerformanceWarning(
3386 device, kVUID_BestPractices_ClearAttachment_ClearImage,
3387 "%s Performance warning: using vkCmdClearDepthStencilImage is not recommended. Prefer using LOAD_OP_CLEAR or "
3388 "vkCmdClearAttachments instead",
3389 VendorSpecificTag(kBPVendorAMD));
3390 }
3391
3392 return skip;
3393}
3394
3395bool BestPractices::PreCallValidateCreatePipelineLayout(VkDevice device, const VkPipelineLayoutCreateInfo* pCreateInfo,
3396 const VkAllocationCallbacks* pAllocator,
3397 VkPipelineLayout* pPipelineLayout) const {
3398 bool skip = false;
3399 if (VendorCheckEnabled(kBPVendorAMD)) {
3400 // Descriptor sets cost 1 DWORD each.
3401 // Dynamic buffers cost 2 DWORDs each when robust buffer access is OFF.
3402 // Dynamic buffers cost 4 DWORDs each when robust buffer access is ON.
3403 // Push constants cost 1 DWORD per 4 bytes in the Push constant range.
3404 uint32_t pipeline_size = pCreateInfo->setLayoutCount; // in DWORDS
3405 for (uint32_t i = 0; i < pCreateInfo->setLayoutCount; i++) {
3406 std::shared_ptr<const cvdescriptorset::DescriptorSetLayout> descriptor_set_layout_state =
3407 GetDescriptorSetLayoutShared(pCreateInfo->pSetLayouts[i]);
3408 pipeline_size += descriptor_set_layout_state->GetDynamicDescriptorCount() * (robust_buffer_access ? 4 : 2);
3409 }
3410
3411 for (uint32_t i = 0; i < pCreateInfo->pushConstantRangeCount; i++) {
3412 pipeline_size += pCreateInfo->pPushConstantRanges[i].size / 4;
3413 }
3414
3415 if (pipeline_size > kPipelineLayoutSizeWarningLimitAMD) {
3416 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelinesLayout_KeepLayoutSmall,
3417 "%s Performance warning: pipeline layout size is too large. Prefer smaller pipeline layouts."
3418 "Descriptor sets cost 1 DWORD each. "
3419 "Dynamic buffers cost 2 DWORDs each when robust buffer access is OFF. "
3420 "Dynamic buffers cost 4 DWORDs each when robust buffer access is ON. "
3421 "Push constants cost 1 DWORD per 4 bytes in the Push constant range. ",
3422 VendorSpecificTag(kBPVendorAMD));
3423 }
3424 }
3425
3426 return skip;
3427}
3428
3429bool BestPractices::PreCallValidateCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3430 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3431 const VkImageCopy* pRegions) const {
3432 bool skip = false;
3433 std::stringstream src_image_hex;
3434 std::stringstream dst_image_hex;
3435 src_image_hex << "0x" << std::hex << HandleToUint64(srcImage);
3436 dst_image_hex << "0x" << std::hex << HandleToUint64(dstImage);
3437
3438 if (VendorCheckEnabled(kBPVendorAMD)) {
3439 const IMAGE_STATE* src_state = Get<IMAGE_STATE>(srcImage);
3440 const IMAGE_STATE* dst_state = Get<IMAGE_STATE>(dstImage);
3441
3442 if (src_state && dst_state) {
3443 VkImageTiling src_Tiling = src_state->createInfo.tiling;
3444 VkImageTiling dst_Tiling = dst_state->createInfo.tiling;
3445 if (src_Tiling != dst_Tiling && (src_Tiling == VK_IMAGE_TILING_LINEAR || dst_Tiling == VK_IMAGE_TILING_LINEAR)) {
3446 skip |=
3447 LogPerformanceWarning(device, kVUID_BestPractices_vkImage_AvoidImageToImageCopy,
3448 "%s Performance warning: image %s and image %s have differing tilings. Use buffer to "
3449 "image (vkCmdCopyImageToBuffer) "
3450 "and image to buffer (vkCmdCopyBufferToImage) copies instead of image to image "
3451 "copies when converting between linear and optimal images",
3452 VendorSpecificTag(kBPVendorAMD), src_image_hex.str().c_str(), dst_image_hex.str().c_str());
3453 }
3454 }
3455 }
3456
3457 return skip;
3458}
3459
3460bool BestPractices::PreCallValidateCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
3461 VkPipeline pipeline) const {
3462 bool skip = false;
3463
3464 if (VendorCheckEnabled(kBPVendorAMD)) {
3465 if (pipelines_used_in_frame.find(pipeline) != pipelines_used_in_frame.end()) {
3466 skip |= LogPerformanceWarning(device, kVUID_BestPractices_Pipeline_SortAndBind,
3467 "%s Performance warning: Pipeline %s was bound twice in the frame. Keep pipeline state changes to a minimum,"
3468 "for example, by sorting draw calls by pipeline.",
3469 VendorSpecificTag(kBPVendorAMD), report_data->FormatHandle(pipeline).c_str());
3470 }
3471 }
3472
3473 return skip;
3474}
3475
3476void BestPractices::ManualPostCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
3477 VkFence fence, VkResult result) {
3478 // AMD best practice
3479 num_queue_submissions += submitCount;
3480}
3481
3482bool BestPractices::PreCallValidateQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo) const {
3483 bool skip = false;
3484
3485 if (VendorCheckEnabled(kBPVendorAMD)) {
3486 if (num_queue_submissions > kNumberOfSubmissionWarningLimitAMD) {
3487 skip |= LogPerformanceWarning(
3488 device, kVUID_BestPractices_Submission_ReduceNumberOfSubmissions,
3489 "%s Performance warning: command buffers submitted %" PRId32 " times this frame. Submitting command buffers has a CPU "
3490 "and GPU overhead. Submit fewer times to incur less overhead.",
3491 VendorSpecificTag(kBPVendorAMD), num_queue_submissions);
3492 }
3493 }
3494
3495 return skip;
3496}
3497
3498void BestPractices::PostCallRecordCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
3499 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
3500 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
3501 uint32_t bufferMemoryBarrierCount,
3502 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
3503 uint32_t imageMemoryBarrierCount,
3504 const VkImageMemoryBarrier* pImageMemoryBarriers) {
3505 num_barriers_objects += memoryBarrierCount;
3506 num_barriers_objects += imageMemoryBarrierCount;
3507 num_barriers_objects += bufferMemoryBarrierCount;
3508}
3509
3510void BestPractices::ManualPostCallRecordCreateFence(VkDevice device, const VkFenceCreateInfo* pCreateInfo,
3511 const VkAllocationCallbacks* pAllocator, VkFence* pFence, VkResult result) {
3512 // AMD best practice
3513 if (result == VK_SUCCESS) {
3514 num_fence_objects++;
3515 }
3516}
3517
3518void BestPractices::ManualPostCallRecordCreateSemaphore(VkDevice device, const VkSemaphoreCreateInfo* pCreateInfo,
3519 const VkAllocationCallbacks* pAllocator, VkSemaphore* pSemaphore,
3520 VkResult result) {
3521 // AMD best practice
3522 if (result == VK_SUCCESS) {
3523 num_semaphore_objects++;
3524 }
3525}
3526
3527bool BestPractices::PreCallValidateCreateSemaphore(VkDevice device, const VkSemaphoreCreateInfo* pCreateInfo,
3528 const VkAllocationCallbacks* pAllocator, VkSemaphore* pSemaphore) const {
3529 bool skip = false;
3530 if (VendorCheckEnabled(kBPVendorAMD)) {
3531 if (num_semaphore_objects > kMaxRecommendedSemaphoreObjectsSizeAMD) {
3532 skip |= LogPerformanceWarning(device, kVUID_BestPractices_SyncObjects_HighNumberOfSemaphores,
3533 "%s Performance warning: High number of vkSemaphore objects created."
3534 "Minimize the amount of queue synchronization that is used. "
3535 "Semaphores and fences have overhead. Each fence has a CPU and GPU cost with it.",
3536 VendorSpecificTag(kBPVendorAMD));
3537 }
3538 }
3539
3540 return skip;
3541}
3542
3543bool BestPractices::PreCallValidateCreateFence(VkDevice device, const VkFenceCreateInfo* pCreateInfo,
3544 const VkAllocationCallbacks* pAllocator, VkFence* pFence) const {
3545 bool skip = false;
3546 if (VendorCheckEnabled(kBPVendorAMD)) {
3547 if (num_fence_objects > kMaxRecommendedFenceObjectsSizeAMD) {
3548 skip |= LogPerformanceWarning(device, kVUID_BestPractices_SyncObjects_HighNumberOfFences,
3549 "%s Performance warning: High number of VkFence objects created."
3550 "Minimize the amount of CPU-GPU synchronization that is used. "
3551 "Semaphores and fences have overhead.Each fence has a CPU and GPU cost with it.",
3552 VendorSpecificTag(kBPVendorAMD));
3553 }
3554 }
3555
3556 return skip;
3557}
3558
Sam Walls8e77e4f2020-03-16 20:47:40 +00003559void BestPractices::PostTransformLRUCacheModel::resize(size_t size) { _entries.resize(size); }
3560
3561bool BestPractices::PostTransformLRUCacheModel::query_cache(uint32_t value) {
3562 // look for a cache hit
3563 auto hit = std::find_if(_entries.begin(), _entries.end(), [value](const CacheEntry& entry) { return entry.value == value; });
3564 if (hit != _entries.end()) {
3565 // mark the cache hit as being most recently used
3566 hit->age = iteration++;
3567 return true;
3568 }
3569
3570 // if there's no cache hit, we need to model the entry being inserted into the cache
3571 CacheEntry new_entry = {value, iteration};
3572 if (iteration < static_cast<uint32_t>(std::distance(_entries.begin(), _entries.end()))) {
3573 // if there is still space left in the cache, use the next available slot
3574 *(_entries.begin() + iteration) = new_entry;
3575 } else {
3576 // otherwise replace the least recently used cache entry
3577 auto lru = std::min_element(_entries.begin(), hit, [](const CacheEntry& a, const CacheEntry& b) { return a.age < b.age; });
3578 *lru = new_entry;
3579 }
3580 iteration++;
3581 return false;
3582}
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003583
3584bool BestPractices::PreCallValidateAcquireNextImageKHR(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout,
3585 VkSemaphore semaphore, VkFence fence, uint32_t* pImageIndex) const {
3586 const auto swapchain_data = GetSwapchainState(swapchain);
3587 bool skip = false;
3588 if (swapchain_data && swapchain_data->images.size() == 0) {
3589 skip |= LogWarning(swapchain, kVUID_Core_DrawState_SwapchainImagesNotFound,
3590 "vkAcquireNextImageKHR: No images found to acquire from. Application probably did not call "
3591 "vkGetSwapchainImagesKHR after swapchain creation.");
3592 }
3593 return skip;
3594}
3595
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003596void BestPractices::CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(CALL_STATE& call_state, bool no_pointer) {
3597 if (no_pointer) {
3598 if (UNCALLED == call_state) {
3599 call_state = QUERY_COUNT;
3600 }
3601 } else { // Save queue family properties
3602 call_state = QUERY_DETAILS;
3603 }
3604}
3605
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003606void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
3607 uint32_t* pQueueFamilyPropertyCount,
3608 VkQueueFamilyProperties* pQueueFamilyProperties) {
3609 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(physicalDevice, pQueueFamilyPropertyCount,
3610 pQueueFamilyProperties);
Jeremy Gebben383b9a32021-09-08 16:31:33 -06003611 auto* bp_pd_state = GetPhysicalDeviceState(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003612 if (bp_pd_state) {
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003613 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
3614 nullptr == pQueueFamilyProperties);
3615 }
3616}
3617
3618void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
3619 uint32_t* pQueueFamilyPropertyCount,
3620 VkQueueFamilyProperties2* pQueueFamilyProperties) {
3621 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(physicalDevice, pQueueFamilyPropertyCount,
3622 pQueueFamilyProperties);
Jeremy Gebben383b9a32021-09-08 16:31:33 -06003623 auto* bp_pd_state = GetPhysicalDeviceState(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003624 if (bp_pd_state) {
3625 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
3626 nullptr == pQueueFamilyProperties);
3627 }
3628}
3629
3630void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(VkPhysicalDevice physicalDevice,
3631 uint32_t* pQueueFamilyPropertyCount,
3632 VkQueueFamilyProperties2* pQueueFamilyProperties) {
3633 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(physicalDevice, pQueueFamilyPropertyCount,
3634 pQueueFamilyProperties);
Jeremy Gebben383b9a32021-09-08 16:31:33 -06003635 auto* bp_pd_state = GetPhysicalDeviceState(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003636 if (bp_pd_state) {
3637 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
3638 nullptr == pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003639 }
3640}
3641
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003642void BestPractices::PostCallRecordGetPhysicalDeviceFeatures(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures* pFeatures) {
3643 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures(physicalDevice, pFeatures);
Jeremy Gebben383b9a32021-09-08 16:31:33 -06003644 auto* bp_pd_state = GetPhysicalDeviceState(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003645 if (bp_pd_state) {
3646 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3647 }
3648}
3649
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003650void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2(VkPhysicalDevice physicalDevice,
3651 VkPhysicalDeviceFeatures2* pFeatures) {
3652 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2(physicalDevice, pFeatures);
Jeremy Gebben383b9a32021-09-08 16:31:33 -06003653 auto* bp_pd_state = GetPhysicalDeviceState(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003654 if (bp_pd_state) {
3655 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3656 }
3657}
3658
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003659void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2KHR(VkPhysicalDevice physicalDevice,
3660 VkPhysicalDeviceFeatures2* pFeatures) {
3661 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2KHR(physicalDevice, pFeatures);
Jeremy Gebben383b9a32021-09-08 16:31:33 -06003662 auto* bp_pd_state = GetPhysicalDeviceState(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003663 if (bp_pd_state) {
3664 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3665 }
3666}
3667
3668void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilitiesKHR(VkPhysicalDevice physicalDevice,
3669 VkSurfaceKHR surface,
3670 VkSurfaceCapabilitiesKHR* pSurfaceCapabilities,
3671 VkResult result) {
Jeremy Gebben383b9a32021-09-08 16:31:33 -06003672 auto* bp_pd_state = GetPhysicalDeviceState(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003673 if (bp_pd_state) {
3674 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3675 }
3676}
3677
3678void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2KHR(
3679 VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
3680 VkSurfaceCapabilities2KHR* pSurfaceCapabilities, VkResult result) {
Jeremy Gebben383b9a32021-09-08 16:31:33 -06003681 auto* bp_pd_state = GetPhysicalDeviceState(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003682 if (bp_pd_state) {
3683 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3684 }
3685}
3686
3687void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2EXT(VkPhysicalDevice physicalDevice,
3688 VkSurfaceKHR surface,
3689 VkSurfaceCapabilities2EXT* pSurfaceCapabilities,
3690 VkResult result) {
Jeremy Gebben383b9a32021-09-08 16:31:33 -06003691 auto* bp_pd_state = GetPhysicalDeviceState(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003692 if (bp_pd_state) {
3693 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3694 }
3695}
3696
3697void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice physicalDevice,
3698 VkSurfaceKHR surface, uint32_t* pPresentModeCount,
3699 VkPresentModeKHR* pPresentModes, VkResult result) {
Jeremy Gebben383b9a32021-09-08 16:31:33 -06003700 auto* bp_pd_data = GetPhysicalDeviceState(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003701 if (bp_pd_data) {
3702 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfacePresentModesKHRState;
3703
3704 if (*pPresentModeCount) {
3705 if (call_state < QUERY_COUNT) {
3706 call_state = QUERY_COUNT;
3707 }
3708 }
3709 if (pPresentModes) {
3710 if (call_state < QUERY_DETAILS) {
3711 call_state = QUERY_DETAILS;
3712 }
3713 }
3714 }
3715}
3716
3717void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
3718 uint32_t* pSurfaceFormatCount,
3719 VkSurfaceFormatKHR* pSurfaceFormats, VkResult result) {
Jeremy Gebben383b9a32021-09-08 16:31:33 -06003720 auto* bp_pd_data = GetPhysicalDeviceState(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003721 if (bp_pd_data) {
3722 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState;
3723
3724 if (*pSurfaceFormatCount) {
3725 if (call_state < QUERY_COUNT) {
3726 call_state = QUERY_COUNT;
3727 }
3728 }
3729 if (pSurfaceFormats) {
3730 if (call_state < QUERY_DETAILS) {
3731 call_state = QUERY_DETAILS;
3732 }
3733 }
3734 }
3735}
3736
3737void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormats2KHR(VkPhysicalDevice physicalDevice,
3738 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
3739 uint32_t* pSurfaceFormatCount,
3740 VkSurfaceFormat2KHR* pSurfaceFormats, VkResult result) {
Jeremy Gebben383b9a32021-09-08 16:31:33 -06003741 auto* bp_pd_data = GetPhysicalDeviceState(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003742 if (bp_pd_data) {
3743 if (*pSurfaceFormatCount) {
3744 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_COUNT) {
3745 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_COUNT;
3746 }
3747 }
3748 if (pSurfaceFormats) {
3749 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_DETAILS) {
3750 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_DETAILS;
3751 }
3752 }
3753 }
3754}
3755
3756void BestPractices::ManualPostCallRecordGetPhysicalDeviceDisplayPlanePropertiesKHR(VkPhysicalDevice physicalDevice,
3757 uint32_t* pPropertyCount,
3758 VkDisplayPlanePropertiesKHR* pProperties,
3759 VkResult result) {
Jeremy Gebben383b9a32021-09-08 16:31:33 -06003760 auto* bp_pd_data = GetPhysicalDeviceState(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003761 if (bp_pd_data) {
3762 if (*pPropertyCount) {
3763 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_COUNT) {
3764 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_COUNT;
3765 }
3766 }
3767 if (pProperties) {
3768 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_DETAILS) {
3769 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_DETAILS;
3770 }
3771 }
3772 }
3773}
3774
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003775void BestPractices::ManualPostCallRecordGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain,
3776 uint32_t* pSwapchainImageCount, VkImage* pSwapchainImages,
3777 VkResult result) {
Nathaniel Cesario39152e62021-07-02 13:04:16 -06003778 auto* swapchain_state = static_cast<SWAPCHAIN_STATE_BP*>(Get<SWAPCHAIN_NODE>(swapchain));
3779 if (swapchain_state && (pSwapchainImages || *pSwapchainImageCount)) {
3780 if (swapchain_state->vkGetSwapchainImagesKHRState < QUERY_DETAILS) {
3781 swapchain_state->vkGetSwapchainImagesKHRState = QUERY_DETAILS;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003782 }
3783 }
3784}
3785
Nadav Gevaf0808442021-05-21 13:51:25 -04003786void BestPractices::ManualPostCallRecordCreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo* pCreateInfo,
3787 const VkAllocationCallbacks* pAllocator, VkDevice* pDevice, VkResult result) {
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003788 if (VK_SUCCESS == result) {
Nadav Gevaf0808442021-05-21 13:51:25 -04003789 if ((pCreateInfo->pEnabledFeatures != nullptr) && (pCreateInfo->pEnabledFeatures->robustBufferAccess == VK_TRUE)) {
3790 robust_buffer_access = true;
3791 }
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003792 }
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003793}
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003794
3795void BestPractices::PreCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits, VkFence fence) {
3796 ValidationStateTracker::PreCallRecordQueueSubmit(queue, submitCount, pSubmits, fence);
3797
3798 QUEUE_STATE* queue_state = GetQueueState(queue);
3799 for (uint32_t submit = 0; submit < submitCount; submit++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02003800 const auto& submit_info = pSubmits[submit];
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003801 for (uint32_t cb_index = 0; cb_index < submit_info.commandBufferCount; cb_index++) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003802 auto* cb = GetCBState(submit_info.pCommandBuffers[cb_index]);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003803 for (auto &func : cb->queue_submit_functions) {
3804 func(this, queue_state);
3805 }
3806 }
3807 }
3808}