blob: b459da396f295b1f034e64cb43bb0eda39995e47 [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
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600256 const auto bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
257 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
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600408 const auto* bp_pd_state = GetPhysicalDeviceStateBP();
409 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
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001181 bool has_writeable_descriptors = false;
locke-lunarg63e4daf2020-08-17 17:53:25 -06001182 bool has_atomic_descriptors = false;
sfricke-samsung962cad92021-04-13 00:46:29 -07001183 auto accessible_ids = module->MarkAccessibleIds(entrypoint);
locke-lunarg63e4daf2020-08-17 17:53:25 -06001184 auto descriptor_uses =
sfricke-samsung962cad92021-04-13 00:46:29 -07001185 module->CollectInterfaceByDescriptorSlot(accessible_ids, &has_writeable_descriptors, &has_atomic_descriptors);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001186
1187 unsigned dimensions = 0;
1188 if (x > 1) dimensions++;
1189 if (y > 1) dimensions++;
1190 if (z > 1) dimensions++;
1191 // Here the dimension will really depend on the dispatch grid, but assume it's 1D.
1192 dimensions = std::max(dimensions, 1u);
1193
1194 // If we're accessing images, we almost certainly want to have a 2D workgroup for cache reasons.
1195 // There are some false positives here. We could simply have a shader that does this within a 1D grid,
1196 // or we may have a linearly tiled image, but these cases are quite unlikely in practice.
1197 bool accesses_2d = false;
1198 for (const auto& usage : descriptor_uses) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001199 auto dim = module->GetShaderResourceDimensionality(usage.second);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001200 if (dim < 0) continue;
1201 auto spvdim = spv::Dim(dim);
1202 if (spvdim != spv::Dim1D && spvdim != spv::DimBuffer) accesses_2d = true;
1203 }
1204
1205 if (accesses_2d && dimensions < 2) {
1206 LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeSpatialLocality,
1207 "%s vkCreateComputePipelines(): compute shader has work group dimensions (%u, %u, %u), which "
1208 "suggests a 1D dispatch, but the shader is accessing 2D or 3D images. The shader may be "
1209 "exhibiting poor spatial locality with respect to one or more shader resources.",
1210 VendorSpecificTag(kBPVendorArm), x, y, z);
1211 }
1212
Camden5b184be2019-08-13 07:50:19 -06001213 return skip;
1214}
1215
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001216bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags flags) const {
Camden5b184be2019-08-13 07:50:19 -06001217 bool skip = false;
1218
1219 if (flags & VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001220 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1221 "You are using VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001222 } else if (flags & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001223 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1224 "You are using VK_PIPELINE_STAGE_ALL_COMMANDS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001225 }
1226
1227 return skip;
1228}
1229
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001230bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags2KHR flags) const {
1231 bool skip = false;
1232
1233 if (flags & VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR) {
1234 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1235 "You are using VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR when %s is called\n", api_name.c_str());
1236 } else if (flags & VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR) {
1237 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1238 "You are using VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR when %s is called\n", api_name.c_str());
1239 }
1240
1241 return skip;
1242}
1243
1244bool BestPractices::CheckDependencyInfo(const std::string& api_name, const VkDependencyInfoKHR& dep_info) const {
1245 bool skip = false;
1246 auto stage_masks = sync_utils::GetGlobalStageMasks(dep_info);
1247
1248 skip |= CheckPipelineStageFlags(api_name, stage_masks.src);
1249 skip |= CheckPipelineStageFlags(api_name, stage_masks.dst);
1250
1251 return skip;
1252}
1253
Mark Lobodzinski84101d72020-04-24 09:43:48 -06001254void BestPractices::ManualPostCallRecordQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo, VkResult result) {
Mark Lobodzinski9b133c12020-03-10 10:42:56 -06001255 for (uint32_t i = 0; i < pPresentInfo->swapchainCount; ++i) {
1256 auto swapchains_result = pPresentInfo->pResults ? pPresentInfo->pResults[i] : result;
1257 if (swapchains_result == VK_SUBOPTIMAL_KHR) {
1258 LogPerformanceWarning(
1259 pPresentInfo->pSwapchains[i], kVUID_BestPractices_SuboptimalSwapchain,
1260 "vkQueuePresentKHR: %s :VK_SUBOPTIMAL_KHR was returned. VK_SUBOPTIMAL_KHR - Presentation will still succeed, "
1261 "subject to the window resize behavior, but the swapchain is no longer configured optimally for the surface it "
1262 "targets. Applications should query updated surface information and recreate their swapchain at the next "
1263 "convenient opportunity.",
1264 report_data->FormatHandle(pPresentInfo->pSwapchains[i]).c_str());
1265 }
1266 }
Nadav Gevaf0808442021-05-21 13:51:25 -04001267
1268 // AMD best practice
1269 // end-of-frame cleanup
1270 num_queue_submissions = 0;
1271 num_barriers_objects = 0;
1272 pipelines_used_in_frame.clear();
Mark Lobodzinski9b133c12020-03-10 10:42:56 -06001273}
1274
Jeff Bolz5c801d12019-10-09 10:38:45 -05001275bool BestPractices::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
1276 VkFence fence) const {
Camden5b184be2019-08-13 07:50:19 -06001277 bool skip = false;
1278
1279 for (uint32_t submit = 0; submit < submitCount; submit++) {
1280 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreCount; semaphore++) {
1281 skip |= CheckPipelineStageFlags("vkQueueSubmit", pSubmits[submit].pWaitDstStageMask[semaphore]);
1282 }
1283 }
1284
1285 return skip;
1286}
1287
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001288bool BestPractices::PreCallValidateQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR* pSubmits,
1289 VkFence fence) const {
1290 bool skip = false;
1291
1292 for (uint32_t submit = 0; submit < submitCount; submit++) {
1293 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreInfoCount; semaphore++) {
1294 skip |= CheckPipelineStageFlags("vkQueueSubmit2KHR", pSubmits[submit].pWaitSemaphoreInfos[semaphore].stageMask);
1295 }
1296 }
1297
1298 return skip;
1299}
1300
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001301bool BestPractices::PreCallValidateCreateCommandPool(VkDevice device, const VkCommandPoolCreateInfo* pCreateInfo,
1302 const VkAllocationCallbacks* pAllocator, VkCommandPool* pCommandPool) const {
1303 bool skip = false;
1304
1305 if (pCreateInfo->flags & VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT) {
1306 skip |= LogPerformanceWarning(
1307 device, kVUID_BestPractices_CreateCommandPool_CommandBufferReset,
1308 "vkCreateCommandPool(): VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT is set. Consider resetting entire "
1309 "pool instead.");
1310 }
1311
1312 return skip;
1313}
1314
1315bool BestPractices::PreCallValidateBeginCommandBuffer(VkCommandBuffer commandBuffer,
1316 const VkCommandBufferBeginInfo* pBeginInfo) const {
1317 bool skip = false;
1318
1319 if (pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT) {
1320 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_SimultaneousUse,
1321 "vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT is set.");
1322 }
1323
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001324 if (!(pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT) && VendorCheckEnabled(kBPVendorArm)) {
1325 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_OneTimeSubmit,
Attilio Provenzano02859b22020-02-27 14:17:28 +00001326 "%s vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT is not set. "
1327 "For best performance on Mali GPUs, consider setting ONE_TIME_SUBMIT by default.",
1328 VendorSpecificTag(kBPVendorArm));
1329 }
1330
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001331 return skip;
1332}
1333
Jeff Bolz5c801d12019-10-09 10:38:45 -05001334bool BestPractices::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001335 bool skip = false;
1336
1337 skip |= CheckPipelineStageFlags("vkCmdSetEvent", stageMask);
1338
1339 return skip;
1340}
1341
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001342bool BestPractices::PreCallValidateCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1343 const VkDependencyInfoKHR* pDependencyInfo) const {
1344 return CheckDependencyInfo("vkCmdSetEvent2KHR", *pDependencyInfo);
1345}
1346
Jeff Bolz5c801d12019-10-09 10:38:45 -05001347bool BestPractices::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
1348 VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001349 bool skip = false;
1350
1351 skip |= CheckPipelineStageFlags("vkCmdResetEvent", stageMask);
1352
1353 return skip;
1354}
1355
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001356bool BestPractices::PreCallValidateCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1357 VkPipelineStageFlags2KHR stageMask) const {
1358 bool skip = false;
1359
1360 skip |= CheckPipelineStageFlags("vkCmdResetEvent2KHR", stageMask);
1361
1362 return skip;
1363}
1364
Camden5b184be2019-08-13 07:50:19 -06001365bool BestPractices::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1366 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
1367 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1368 uint32_t bufferMemoryBarrierCount,
1369 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1370 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001371 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001372 bool skip = false;
1373
1374 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", srcStageMask);
1375 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", dstStageMask);
1376
1377 return skip;
1378}
1379
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001380bool BestPractices::PreCallValidateCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1381 const VkDependencyInfoKHR* pDependencyInfos) const {
1382 bool skip = false;
1383 for (uint32_t i = 0; i < eventCount; i++) {
1384 skip = CheckDependencyInfo("vkCmdWaitEvents2KHR", pDependencyInfos[i]);
1385 }
1386
1387 return skip;
1388}
1389
Camden5b184be2019-08-13 07:50:19 -06001390bool BestPractices::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
1391 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
1392 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1393 uint32_t bufferMemoryBarrierCount,
1394 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1395 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001396 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001397 bool skip = false;
1398
1399 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", srcStageMask);
1400 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", dstStageMask);
1401
Nadav Gevaf0808442021-05-21 13:51:25 -04001402 if (VendorCheckEnabled(kBPVendorAMD)) {
1403 if (num_barriers_objects + imageMemoryBarrierCount + bufferMemoryBarrierCount > kMaxRecommendedBarriersSizeAMD) {
1404 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdBuffer_highBarrierCount,
1405 "%s Performance warning: In this frame, %" PRIu32 " barriers were already submitted. Barriers have a high cost and can "
1406 "stall the GPU. "
1407 "Consider consolidating and re-organizing the frame to use fewer barriers.",
1408 VendorSpecificTag(kBPVendorAMD), num_barriers_objects);
1409 }
1410
1411 std::array<VkImageLayout, 3> read_layouts = {
1412 VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL,
1413 VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
1414 VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
1415 };
1416
1417 for (uint32_t i = 0; i < imageMemoryBarrierCount; i++) {
1418 // read to read barriers
1419 auto found = std::find(read_layouts.begin(), read_layouts.end(), pImageMemoryBarriers[i].oldLayout);
1420 bool old_is_read_layout = found != read_layouts.end();
1421 found = std::find(read_layouts.begin(), read_layouts.end(), pImageMemoryBarriers[i].newLayout);
1422 bool new_is_read_layout = found != read_layouts.end();
1423 if (old_is_read_layout && new_is_read_layout) {
1424 skip |= LogPerformanceWarning(device, kVUID_BestPractices_PipelineBarrier_readToReadBarrier,
1425 "%s Performance warning: Don't issue read-to-read barriers. Get the resource in the right state the first "
1426 "time you use it.",
1427 VendorSpecificTag(kBPVendorAMD));
1428 }
1429
1430 // general with no storage
1431 if (pImageMemoryBarriers[i].newLayout == VK_IMAGE_LAYOUT_GENERAL) {
1432 auto image_state = Get<IMAGE_STATE>(pImageMemoryBarriers[i].image);
1433 if (!(image_state->createInfo.usage & VK_IMAGE_USAGE_STORAGE_BIT)) {
1434 skip |= LogPerformanceWarning(device, kVUID_BestPractices_vkImage_AvoidGeneral,
1435 "%s Performance warning: VK_IMAGE_LAYOUT_GENERAL should only be used with "
1436 "VK_IMAGE_USAGE_STORAGE_BIT images.",
1437 VendorSpecificTag(kBPVendorAMD));
1438 }
1439 }
1440 }
1441 }
1442
Camden5b184be2019-08-13 07:50:19 -06001443 return skip;
1444}
1445
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001446bool BestPractices::PreCallValidateCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer,
1447 const VkDependencyInfoKHR* pDependencyInfo) const {
1448 return CheckDependencyInfo("vkCmdPipelineBarrier2KHR", *pDependencyInfo);
1449}
1450
Camden5b184be2019-08-13 07:50:19 -06001451bool BestPractices::PreCallValidateCmdWriteTimestamp(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001452 VkQueryPool queryPool, uint32_t query) const {
Camden5b184be2019-08-13 07:50:19 -06001453 bool skip = false;
1454
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001455 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp", static_cast<VkPipelineStageFlags>(pipelineStage));
1456
1457 return skip;
1458}
1459
1460bool BestPractices::PreCallValidateCmdWriteTimestamp2KHR(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
1461 VkQueryPool queryPool, uint32_t query) const {
1462 bool skip = false;
1463
1464 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp2KHR", pipelineStage);
Camden5b184be2019-08-13 07:50:19 -06001465
1466 return skip;
1467}
1468
Sam Walls0961ec02020-03-31 16:39:15 +01001469void BestPractices::PostCallRecordCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
1470 VkPipeline pipeline) {
1471 StateTracker::PostCallRecordCmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
1472
Nadav Gevaf0808442021-05-21 13:51:25 -04001473 // AMD best practice
1474 pipelines_used_in_frame.emplace(pipeline);
1475
Sam Walls0961ec02020-03-31 16:39:15 +01001476 if (pipelineBindPoint == VK_PIPELINE_BIND_POINT_GRAPHICS) {
1477 // check for depth/blend state tracking
1478 auto gp_cis = graphicsPipelineCIs.find(pipeline);
1479 if (gp_cis != graphicsPipelineCIs.end()) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06001480 auto* cb_node = GetCBState(commandBuffer);
1481 assert(cb_node);
1482 auto& render_pass_state = cb_node->render_pass_state;
Sam Walls0961ec02020-03-31 16:39:15 +01001483
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001484 render_pass_state.nextDrawTouchesAttachments = gp_cis->second.accessFramebufferAttachments;
1485 render_pass_state.drawTouchAttachments = true;
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02001486
Jeremy Gebben396d06a2021-08-12 11:03:04 -06001487 const auto& blend_state = gp_cis->second.colorBlendStateCI;
1488 const auto& stencil_state = gp_cis->second.depthStencilStateCI;
Sam Walls0961ec02020-03-31 16:39:15 +01001489
1490 if (blend_state) {
1491 // assume the pipeline is depth-only unless any of the attachments have color writes enabled
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001492 render_pass_state.depthOnly = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001493 for (size_t i = 0; i < blend_state->attachmentCount; i++) {
1494 if (blend_state->pAttachments[i].colorWriteMask != 0) {
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001495 render_pass_state.depthOnly = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001496 }
1497 }
1498 }
1499
1500 // check for depth value usage
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001501 render_pass_state.depthEqualComparison = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001502
1503 if (stencil_state && stencil_state->depthTestEnable) {
1504 switch (stencil_state->depthCompareOp) {
1505 case VK_COMPARE_OP_EQUAL:
1506 case VK_COMPARE_OP_GREATER_OR_EQUAL:
1507 case VK_COMPARE_OP_LESS_OR_EQUAL:
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001508 render_pass_state.depthEqualComparison = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001509 break;
1510 default:
1511 break;
1512 }
1513 }
Sam Walls0961ec02020-03-31 16:39:15 +01001514 }
1515 }
1516}
1517
Hans-Kristian Arntzen237663c2021-07-01 14:36:40 +02001518static inline bool RenderPassUsesAttachmentAsResolve(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1519 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
1520 const auto& subpass_info = createInfo.pSubpasses[subpass];
1521 if (subpass_info.pResolveAttachments) {
1522 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1523 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
1524 }
1525 }
1526 }
1527
1528 return false;
1529}
1530
Attilio Provenzano02859b22020-02-27 14:17:28 +00001531static inline bool RenderPassUsesAttachmentOnTile(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1532 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001533 const auto& subpass_info = createInfo.pSubpasses[subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001534
1535 // If an attachment is ever used as a color attachment,
1536 // resolve attachment or depth stencil attachment,
1537 // it needs to exist on tile at some point.
1538
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001539 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1540 if (subpass_info.pColorAttachments[i].attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001541 }
1542
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001543 if (subpass_info.pResolveAttachments) {
1544 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1545 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
1546 }
1547 }
1548
1549 if (subpass_info.pDepthStencilAttachment && subpass_info.pDepthStencilAttachment->attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001550 }
1551
1552 return false;
1553}
1554
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001555static inline bool RenderPassUsesAttachmentAsImageOnly(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1556 if (RenderPassUsesAttachmentOnTile(createInfo, attachment)) {
1557 return false;
1558 }
1559
1560 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001561 const auto& subpassInfo = createInfo.pSubpasses[subpass];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001562
1563 for (uint32_t i = 0; i < subpassInfo.inputAttachmentCount; i++) {
1564 if (subpassInfo.pInputAttachments[i].attachment == attachment) {
1565 return true;
1566 }
1567 }
1568 }
1569
1570 return false;
1571}
1572
Attilio Provenzano02859b22020-02-27 14:17:28 +00001573bool BestPractices::ValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1574 const VkRenderPassBeginInfo* pRenderPassBegin) const {
1575 bool skip = false;
1576
1577 if (!pRenderPassBegin) {
1578 return skip;
1579 }
1580
Gareth Webbdc6549a2021-06-16 03:52:24 +01001581 if (pRenderPassBegin->renderArea.extent.width == 0 || pRenderPassBegin->renderArea.extent.height == 0) {
1582 skip |= LogWarning(device, kVUID_BestPractices_BeginRenderPass_ZeroSizeRenderArea,
1583 "This render pass has a zero-size render area. It cannot write to any attachments, "
1584 "and can only be used for side effects such as layout transitions.");
1585 }
1586
Attilio Provenzano02859b22020-02-27 14:17:28 +00001587 auto rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
1588 if (rp_state) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08001589 if (rp_state->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07001590 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
Tony-LunarG767180f2020-04-23 14:03:59 -06001591 if (rpabi) {
1592 skip = ValidateAttachments(rp_state->createInfo.ptr(), rpabi->attachmentCount, rpabi->pAttachments);
1593 }
1594 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001595 // Check if any attachments have LOAD operation on them
1596 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001597 const auto& attachment = rp_state->createInfo.pAttachments[att];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001598
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001599 bool attachment_has_readback = false;
Hans-Kristian Arntzen4afb59b2021-06-18 12:41:36 +02001600 if (!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001601 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001602 }
1603
1604 if (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001605 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001606 }
1607
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001608 bool attachment_needs_readback = false;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001609
1610 // Check if the attachment is actually used in any subpass on-tile
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001611 if (attachment_has_readback && RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1612 attachment_needs_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001613 }
1614
1615 // Using LOAD_OP_LOAD is expensive on tiled GPUs, so flag it as a potential improvement
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001616 if (attachment_needs_readback && VendorCheckEnabled(kBPVendorArm)) {
1617 skip |= LogPerformanceWarning(
1618 device, kVUID_BestPractices_BeginRenderPass_AttachmentNeedsReadback,
1619 "%s Attachment #%u in render pass has begun with VK_ATTACHMENT_LOAD_OP_LOAD.\n"
1620 "Submitting this renderpass will cause the driver to inject a readback of the attachment "
Nadav Gevaf0808442021-05-21 13:51:25 -04001621 "which will copy in total %u pixels (renderArea = "
1622 "{ %" PRId32 ", %" PRId32 ", %" PRIu32", %" PRIu32 " }) to the tile buffer.",
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001623 VendorSpecificTag(kBPVendorArm), att,
1624 pRenderPassBegin->renderArea.extent.width * pRenderPassBegin->renderArea.extent.height,
1625 pRenderPassBegin->renderArea.offset.x, pRenderPassBegin->renderArea.offset.y,
1626 pRenderPassBegin->renderArea.extent.width, pRenderPassBegin->renderArea.extent.height);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001627 }
1628 }
1629 }
1630
1631 return skip;
1632}
1633
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001634void BestPractices::QueueValidateImageView(QueueCallbacks &funcs, const char* function_name,
1635 IMAGE_VIEW_STATE* view, IMAGE_SUBRESOURCE_USAGE_BP usage) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001636 if (view) {
Jeremy Gebbenb4d17012021-07-08 13:18:15 -06001637 QueueValidateImage(funcs, function_name, GetImageUsageState(view->create_info.image), usage,
1638 view->normalized_subresource_range);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001639 }
1640}
1641
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001642void BestPractices::QueueValidateImage(QueueCallbacks &funcs, const char* function_name,
1643 IMAGE_STATE_BP* state, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001644 const VkImageSubresourceRange& subresource_range) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001645 IMAGE_STATE* image = state->image;
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02001646
1647 // If we're viewing a 3D slice, ignore base array layer.
1648 // The entire 3D subresource is accessed as one atomic unit.
1649 const uint32_t base_array_layer = image->createInfo.imageType == VK_IMAGE_TYPE_3D ? 0 : subresource_range.baseArrayLayer;
1650
1651 const uint32_t max_layers = image->createInfo.arrayLayers - base_array_layer;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001652 const uint32_t array_layers = std::min(subresource_range.layerCount, max_layers);
1653 const uint32_t max_levels = image->createInfo.mipLevels - subresource_range.baseMipLevel;
1654 const uint32_t mip_levels = std::min(image->createInfo.mipLevels, max_levels);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001655
1656 for (uint32_t layer = 0; layer < array_layers; layer++) {
1657 for (uint32_t level = 0; level < mip_levels; level++) {
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02001658 QueueValidateImage(funcs, function_name, state, usage, layer + base_array_layer,
1659 level + subresource_range.baseMipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001660 }
1661 }
1662}
1663
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001664void BestPractices::QueueValidateImage(QueueCallbacks &funcs, const char* function_name,
1665 IMAGE_STATE_BP* state, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001666 const VkImageSubresourceLayers& subresource_layers) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001667 IMAGE_STATE* image = state->image;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001668 const uint32_t max_layers = image->createInfo.arrayLayers - subresource_layers.baseArrayLayer;
1669 const uint32_t array_layers = std::min(subresource_layers.layerCount, max_layers);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001670
1671 for (uint32_t layer = 0; layer < array_layers; layer++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001672 QueueValidateImage(funcs, function_name, state, usage, layer + subresource_layers.baseArrayLayer, subresource_layers.mipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001673 }
1674}
1675
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001676void BestPractices::QueueValidateImage(QueueCallbacks &funcs, const char* function_name,
1677 IMAGE_STATE_BP* state, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001678 uint32_t array_layer, uint32_t mip_level) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001679 funcs.push_back([this, function_name, state, usage, array_layer, mip_level](const ValidationStateTracker*, const QUEUE_STATE*) -> bool {
1680 ValidateImageInQueue(function_name, state, usage, array_layer, mip_level);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001681 return false;
1682 });
1683}
1684
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001685void BestPractices::ValidateImageInQueueArm(const char* function_name, IMAGE_STATE* image,
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001686 IMAGE_SUBRESOURCE_USAGE_BP last_usage,
1687 IMAGE_SUBRESOURCE_USAGE_BP usage,
1688 uint32_t array_layer, uint32_t mip_level) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001689 // Swapchain images are implicitly read so clear after store is expected.
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001690 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 -06001691 !image->IsSwapchainImage()) {
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001692 LogPerformanceWarning(
1693 device, kVUID_BestPractices_RenderPass_RedundantStore,
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001694 "%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 +02001695 "image was used, it was written to with STORE_OP_STORE. "
1696 "Storing to the image is probably redundant in this case, and wastes bandwidth on tile-based "
1697 "architectures.",
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001698 function_name, VendorSpecificTag(kBPVendorArm), array_layer, mip_level);
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001699 } 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 +02001700 LogPerformanceWarning(
1701 device, kVUID_BestPractices_RenderPass_RedundantClear,
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001702 "%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 +02001703 "image was used, it was written to with vkCmdClear*Image(). "
1704 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
1705 "tile-based architectures."
1706 "architectures.",
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001707 function_name, VendorSpecificTag(kBPVendorArm), array_layer, mip_level);
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01001708 } else if (usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE &&
1709 (last_usage == IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE ||
1710 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::CLEARED ||
1711 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE ||
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001712 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE)) {
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01001713 const char *last_cmd = nullptr;
1714 const char *vuid = nullptr;
1715 const char *suggestion = nullptr;
1716
1717 switch (last_usage) {
1718 case IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE:
1719 vuid = kVUID_BestPractices_RenderPass_BlitImage_LoadOpLoad;
1720 last_cmd = "vkCmdBlitImage";
1721 suggestion =
1722 "The blit is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
1723 "Rather than blitting, just render the source image in a fragment shader in this render pass, "
1724 "which avoids the memory roundtrip.";
1725 break;
1726 case IMAGE_SUBRESOURCE_USAGE_BP::CLEARED:
1727 vuid = kVUID_BestPractices_RenderPass_InefficientClear;
1728 last_cmd = "vkCmdClear*Image";
1729 suggestion =
1730 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
1731 "tile-based architectures. "
1732 "Use LOAD_OP_CLEAR instead to clear the image for free.";
1733 break;
1734 case IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE:
1735 vuid = kVUID_BestPractices_RenderPass_CopyImage_LoadOpLoad;
1736 last_cmd = "vkCmdCopy*Image";
1737 suggestion =
1738 "The copy is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
1739 "Rather than copying, just render the source image in a fragment shader in this render pass, "
1740 "which avoids the memory roundtrip.";
1741 break;
1742 case IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE:
1743 vuid = kVUID_BestPractices_RenderPass_ResolveImage_LoadOpLoad;
1744 last_cmd = "vkCmdResolveImage";
1745 suggestion =
1746 "The resolve is probably redundant in this case, and wastes a lot of bandwidth on tile-based architectures. "
1747 "Rather than resolving, and then loading, try to keep rendering in the same render pass, "
1748 "which avoids the memory roundtrip.";
1749 break;
1750 default:
1751 break;
1752 }
1753
1754 LogPerformanceWarning(
1755 device, vuid,
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001756 "%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 +01001757 "time image was used, it was written to with %s. %s",
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001758 function_name, VendorSpecificTag(kBPVendorArm), array_layer, mip_level, last_cmd, suggestion);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001759 }
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001760}
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001761
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001762void BestPractices::ValidateImageInQueue(const char* function_name, IMAGE_STATE_BP* state,
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001763 IMAGE_SUBRESOURCE_USAGE_BP usage, uint32_t array_layer,
1764 uint32_t mip_level) {
1765 IMAGE_STATE* image = state->image;
1766 IMAGE_SUBRESOURCE_USAGE_BP last_usage = state->usages[array_layer][mip_level];
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001767 state->usages[array_layer][mip_level] = usage;
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001768 if (VendorCheckEnabled(kBPVendorArm)) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001769 ValidateImageInQueueArm(function_name, image, last_usage, usage, array_layer, mip_level);
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001770 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001771}
1772
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06001773void BestPractices::AddDeferredQueueOperations(CMD_BUFFER_STATE_BP* cb) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001774 cb->queue_submit_functions.insert(cb->queue_submit_functions.end(),
Hans-Kristian Arntzenf44df192021-06-14 11:42:08 +02001775 cb->queue_submit_functions_after_render_pass.begin(),
1776 cb->queue_submit_functions_after_render_pass.end());
1777 cb->queue_submit_functions_after_render_pass.clear();
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001778}
1779
1780void BestPractices::PreCallRecordCmdEndRenderPass(VkCommandBuffer commandBuffer) {
1781 ValidationStateTracker::PreCallRecordCmdEndRenderPass(commandBuffer);
Hans-Kristian Arntzenb8336ad2021-04-28 14:54:09 +02001782 AddDeferredQueueOperations(GetCBState(commandBuffer));
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001783}
1784
1785void BestPractices::PreCallRecordCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassInfo) {
1786 ValidationStateTracker::PreCallRecordCmdEndRenderPass2(commandBuffer, pSubpassInfo);
Hans-Kristian Arntzenb8336ad2021-04-28 14:54:09 +02001787 AddDeferredQueueOperations(GetCBState(commandBuffer));
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001788}
1789
1790void BestPractices::PreCallRecordCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfoKHR *pSubpassInfo) {
1791 ValidationStateTracker::PreCallRecordCmdEndRenderPass2KHR(commandBuffer, pSubpassInfo);
Hans-Kristian Arntzenb8336ad2021-04-28 14:54:09 +02001792 AddDeferredQueueOperations(GetCBState(commandBuffer));
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001793}
1794
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02001795void BestPractices::PreCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer,
1796 const VkRenderPassBeginInfo* pRenderPassBegin,
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001797 VkSubpassContents contents) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001798 ValidationStateTracker::PreCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02001799 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1800}
1801
1802void BestPractices::PreCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer,
1803 const VkRenderPassBeginInfo* pRenderPassBegin,
1804 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1805 ValidationStateTracker::PreCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1806 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1807}
1808
1809void BestPractices::PreCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1810 const VkRenderPassBeginInfo* pRenderPassBegin,
1811 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1812 ValidationStateTracker::PreCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1813 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1814}
1815
1816void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001817
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001818 if (!pRenderPassBegin) {
1819 return;
1820 }
1821
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06001822 auto* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001823
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06001824 auto* rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001825 if (rp_state) {
1826 // Check load ops
1827 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001828 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001829
1830 if (!RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att) &&
1831 !RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1832 continue;
1833 }
1834
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001835 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::UNDEFINED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001836
1837 if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) ||
1838 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001839 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02001840 } else if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) ||
1841 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_CLEAR)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001842 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_CLEARED;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02001843 } else if (RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att)) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001844 usage = IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001845 }
1846
1847 auto framebuffer = GetFramebufferState(pRenderPassBegin->framebuffer);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001848 IMAGE_VIEW_STATE* image_view = nullptr;
1849
Tony-LunarGb3ab3572021-07-02 09:45:17 -06001850 if (framebuffer->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001851 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
1852 if (rpabi) {
1853 image_view = GetImageViewState(rpabi->pAttachments[att]);
1854 }
1855 } else {
1856 image_view = GetImageViewState(framebuffer->createInfo.pAttachments[att]);
1857 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001858
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001859 QueueValidateImageView(cb->queue_submit_functions, "vkCmdBeginRenderPass()", image_view, usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001860 }
1861
1862 // Check store ops
1863 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001864 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001865
1866 if (!RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1867 continue;
1868 }
1869
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001870 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_DISCARDED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001871
1872 if ((!FormatIsStencilOnly(attachment.format) && attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE) ||
1873 (FormatHasStencil(attachment.format) && attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001874 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_STORED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001875 }
1876
1877 auto framebuffer = GetFramebufferState(pRenderPassBegin->framebuffer);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001878
1879 IMAGE_VIEW_STATE* image_view = nullptr;
Tony-LunarGb3ab3572021-07-02 09:45:17 -06001880 if (framebuffer->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001881 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
1882 if (rpabi) {
1883 image_view = GetImageViewState(rpabi->pAttachments[att]);
1884 }
1885 } else {
1886 image_view = GetImageViewState(framebuffer->createInfo.pAttachments[att]);
1887 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001888
Hans-Kristian Arntzenf44df192021-06-14 11:42:08 +02001889 QueueValidateImageView(cb->queue_submit_functions_after_render_pass, "vkCmdEndRenderPass()", image_view, usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001890 }
1891 }
1892}
1893
Attilio Provenzano02859b22020-02-27 14:17:28 +00001894bool BestPractices::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1895 VkSubpassContents contents) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001896 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1897 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001898 return skip;
1899}
1900
1901bool BestPractices::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1902 const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08001903 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001904 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1905 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001906 return skip;
1907}
1908
1909bool BestPractices::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08001910 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001911 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1912 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001913 return skip;
1914}
1915
Sam Walls0961ec02020-03-31 16:39:15 +01001916void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1917 const VkRenderPassBeginInfo* pRenderPassBegin) {
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001918 // Reset the renderpass state
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06001919 auto* cb = GetCBState(commandBuffer);
1920 cb->hasDrawCmd = false;
1921 assert(cb);
1922 auto& render_pass_state = cb->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02001923 render_pass_state.touchesAttachments.clear();
1924 render_pass_state.earlyClearAttachments.clear();
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001925 render_pass_state.numDrawCallsDepthOnly = 0;
1926 render_pass_state.numDrawCallsDepthEqualCompare = 0;
1927 render_pass_state.colorAttachment = false;
1928 render_pass_state.depthAttachment = false;
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02001929 render_pass_state.drawTouchAttachments = true;
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001930 // Don't reset state related to pipeline state.
Sam Walls0961ec02020-03-31 16:39:15 +01001931
Hans-Kristian Arntzena1a92cc2021-03-17 13:09:33 +01001932 const auto* rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
Sam Walls0961ec02020-03-31 16:39:15 +01001933
1934 // track depth / color attachment usage within the renderpass
1935 for (size_t i = 0; i < rp_state->createInfo.subpassCount; i++) {
1936 // record if depth/color attachments are in use for this renderpass
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001937 if (rp_state->createInfo.pSubpasses[i].pDepthStencilAttachment != nullptr) render_pass_state.depthAttachment = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001938
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001939 if (rp_state->createInfo.pSubpasses[i].colorAttachmentCount > 0) render_pass_state.colorAttachment = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001940 }
1941}
1942
1943void BestPractices::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1944 VkSubpassContents contents) {
1945 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1946 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
1947}
1948
1949void BestPractices::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1950 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1951 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1952 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1953}
1954
1955void BestPractices::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1956 const VkRenderPassBeginInfo* pRenderPassBegin,
1957 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1958 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1959 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1960}
1961
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001962// Generic function to handle validation for all CmdDraw* type functions
1963bool BestPractices::ValidateCmdDrawType(VkCommandBuffer cmd_buffer, const char* caller) const {
1964 bool skip = false;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06001965 const auto* cb_state = GetCBState(cmd_buffer);
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001966 if (cb_state) {
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001967 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
1968 const auto* pipeline_state = cb_state->lastBound[lv_bind_point].pipeline_state;
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001969 const auto& current_vtx_bfr_binding_info = cb_state->current_vertex_buffer_binding_info.vertex_buffer_bindings;
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001970
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001971 // Verify vertex binding
1972 if (pipeline_state->vertex_binding_descriptions_.size() <= 0) {
1973 if ((!current_vtx_bfr_binding_info.empty()) && (!cb_state->vertex_buffer_used)) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001974 skip |= LogPerformanceWarning(cb_state->commandBuffer(), kVUID_BestPractices_DrawState_VtxIndexOutOfBounds,
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001975 "Vertex buffers are bound to %s but no vertex buffers are attached to %s.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001976 report_data->FormatHandle(cb_state->commandBuffer()).c_str(),
1977 report_data->FormatHandle(pipeline_state->pipeline()).c_str());
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001978 }
1979 }
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06001980
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06001981 const auto* pipe = cb_state->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06001982 if (pipe) {
1983 const auto* rp_state = pipe->rp_state.get();
1984 if (rp_state) {
1985 for (uint32_t i = 0; i < rp_state->createInfo.subpassCount; ++i) {
1986 const auto& subpass = rp_state->createInfo.pSubpasses[i];
Jeremy Gebben11af9792021-08-20 10:20:09 -06001987 const auto& create_info = pipe->create_info.graphics;
1988 const uint32_t depth_stencil_attachment =
1989 GetSubpassDepthStencilAttachmentIndex(create_info.pDepthStencilState, subpass.pDepthStencilAttachment);
1990 if ((depth_stencil_attachment == VK_ATTACHMENT_UNUSED) && create_info.pRasterizationState &&
1991 create_info.pRasterizationState->depthBiasEnable == VK_TRUE) {
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06001992 skip |= LogWarning(cb_state->commandBuffer(), kVUID_BestPractices_DepthBiasNoAttachment,
1993 "%s: depthBiasEnable == VK_TRUE without a depth-stencil attachment.", caller);
1994 }
1995 }
1996 }
1997 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001998 }
1999 return skip;
2000}
2001
Sam Walls0961ec02020-03-31 16:39:15 +01002002void BestPractices::RecordCmdDrawType(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002003 auto* cb_node = GetCBState(cmd_buffer);
2004 assert(cb_node);
2005 auto& render_pass_state = cb_node->render_pass_state;
Sam Walls0961ec02020-03-31 16:39:15 +01002006 if (VendorCheckEnabled(kBPVendorArm)) {
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002007 RecordCmdDrawTypeArm(render_pass_state, draw_count, caller);
2008 }
2009
2010 if (render_pass_state.drawTouchAttachments) {
2011 for (auto& touch : render_pass_state.nextDrawTouchesAttachments) {
2012 RecordAttachmentAccess(render_pass_state, touch.framebufferAttachment, touch.aspects);
2013 }
2014 // No need to touch the same attachments over and over.
2015 render_pass_state.drawTouchAttachments = false;
Sam Walls0961ec02020-03-31 16:39:15 +01002016 }
2017}
2018
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002019void BestPractices::RecordCmdDrawTypeArm(RenderPassState& render_pass_state, uint32_t draw_count, const char* caller) {
2020 if (draw_count >= kDepthPrePassMinDrawCountArm) {
2021 if (render_pass_state.depthOnly) render_pass_state.numDrawCallsDepthOnly++;
2022 if (render_pass_state.depthEqualComparison) render_pass_state.numDrawCallsDepthEqualCompare++;
Sam Walls0961ec02020-03-31 16:39:15 +01002023 }
2024}
2025
Camden5b184be2019-08-13 07:50:19 -06002026bool BestPractices::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002027 uint32_t firstVertex, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06002028 bool skip = false;
2029
2030 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002031 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
2032 "Warning: You are calling vkCmdDraw() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06002033 }
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002034 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDraw()");
Camden5b184be2019-08-13 07:50:19 -06002035
2036 return skip;
2037}
2038
Sam Walls0961ec02020-03-31 16:39:15 +01002039void BestPractices::PostCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
2040 uint32_t firstVertex, uint32_t firstInstance) {
2041 StateTracker::PostCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
2042 RecordCmdDrawType(commandBuffer, vertexCount * instanceCount, "vkCmdDraw()");
2043}
2044
Camden5b184be2019-08-13 07:50:19 -06002045bool BestPractices::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002046 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06002047 bool skip = false;
2048
2049 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002050 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
2051 "Warning: You are calling vkCmdDrawIndexed() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06002052 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002053 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexed()");
2054
Attilio Provenzano02859b22020-02-27 14:17:28 +00002055 // Check if we reached the limit for small indexed draw calls.
2056 // Note that we cannot update the draw call count here, so we do it in PreCallRecordCmdDrawIndexed.
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002057 const auto* cmd_state = GetCBState(commandBuffer);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002058 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices &&
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02002059 (cmd_state->small_indexed_draw_call_count == kMaxSmallIndexedDrawcalls - 1) &&
2060 VendorCheckEnabled(kBPVendorArm)) {
2061 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_ManySmallIndexedDrawcalls,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -06002062 "%s: The command buffer contains many small indexed drawcalls "
Attilio Provenzano02859b22020-02-27 14:17:28 +00002063 "(at least %u drawcalls with less than %u indices each). This may cause pipeline bubbles. "
2064 "You can try batching drawcalls or instancing when applicable.",
2065 VendorSpecificTag(kBPVendorArm), kMaxSmallIndexedDrawcalls, kSmallIndexedDrawcallIndices);
2066 }
2067
Sam Walls8e77e4f2020-03-16 20:47:40 +00002068 if (VendorCheckEnabled(kBPVendorArm)) {
2069 ValidateIndexBufferArm(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
2070 }
2071
2072 return skip;
2073}
2074
2075bool BestPractices::ValidateIndexBufferArm(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
2076 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
2077 bool skip = false;
2078
2079 // check for sparse/underutilised index buffer, and post-transform cache thrashing
2080 const auto* cmd_state = GetCBState(commandBuffer);
2081 if (cmd_state == nullptr) return skip;
2082
locke-lunarg1ae57d62020-11-18 10:49:19 -07002083 const auto* ib_state = cmd_state->index_buffer_binding.buffer_state.get();
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002084 if (ib_state == nullptr || cmd_state->index_buffer_binding.buffer_state->Destroyed()) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00002085
2086 const VkIndexType ib_type = cmd_state->index_buffer_binding.index_type;
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06002087 const auto& ib_mem_state = *ib_state->MemState();
Sam Walls8e77e4f2020-03-16 20:47:40 +00002088 const VkDeviceSize ib_mem_offset = ib_mem_state.mapped_range.offset;
2089 const void* ib_mem = ib_mem_state.p_driver_data;
2090 bool primitive_restart_enable = false;
2091
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002092 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
2093 const auto& pipeline_binding_iter = cmd_state->lastBound[lv_bind_point];
2094 const auto* pipeline_state = pipeline_binding_iter.pipeline_state;
Sam Walls8e77e4f2020-03-16 20:47:40 +00002095
Jeremy Gebben11af9792021-08-20 10:20:09 -06002096 if (pipeline_state != nullptr && pipeline_state->create_info.graphics.pInputAssemblyState != nullptr) {
2097 primitive_restart_enable = pipeline_state->create_info.graphics.pInputAssemblyState->primitiveRestartEnable == VK_TRUE;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002098 }
Sam Walls8e77e4f2020-03-16 20:47:40 +00002099
2100 // 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 -06002101 if (ib_mem && pipeline_binding_iter.IsUsing()) {
Sam Walls8e77e4f2020-03-16 20:47:40 +00002102 uint32_t scan_stride;
2103 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
2104 scan_stride = sizeof(uint8_t);
2105 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
2106 scan_stride = sizeof(uint16_t);
2107 } else {
2108 scan_stride = sizeof(uint32_t);
2109 }
2110
2111 const uint8_t* scan_begin = static_cast<const uint8_t*>(ib_mem) + ib_mem_offset + firstIndex * scan_stride;
2112 const uint8_t* scan_end = scan_begin + indexCount * scan_stride;
2113
2114 // Min and max are important to track for some Mali architectures. In older Mali devices without IDVS, all
2115 // vertices corresponding to indices between the minimum and maximum may be loaded, and possibly shaded,
2116 // irrespective of whether or not they're part of the draw call.
2117
2118 // start with minimum as 0xFFFFFFFF and adjust to indices in the buffer
2119 uint32_t min_index = ~0u;
2120 // start with maximum as 0 and adjust to indices in the buffer
2121 uint32_t max_index = 0u;
2122
2123 // first scan-through, we're looking to simulate a model LRU post-transform cache, estimating the number of vertices shaded
2124 // for the given index buffer
2125 uint32_t vertex_shade_count = 0;
2126
2127 PostTransformLRUCacheModel post_transform_cache;
2128
2129 // The size of the cache being modelled positively correlates with how much behaviour it can capture about
2130 // arbitrary ground-truth hardware/architecture cache behaviour. I.e. it's a good solution when we don't know the
2131 // target architecture.
2132 // However, modelling a post-transform cache with more than 32 elements gives diminishing returns in practice.
2133 // http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
2134 post_transform_cache.resize(32);
2135
2136 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
2137 uint32_t scan_index;
2138 uint32_t primitive_restart_value;
2139 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
2140 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
2141 primitive_restart_value = 0xFF;
2142 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
2143 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
2144 primitive_restart_value = 0xFFFF;
2145 } else {
2146 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
2147 primitive_restart_value = 0xFFFFFFFF;
2148 }
2149
2150 max_index = std::max(max_index, scan_index);
2151 min_index = std::min(min_index, scan_index);
2152
2153 if (!primitive_restart_enable || scan_index != primitive_restart_value) {
2154 bool in_cache = post_transform_cache.query_cache(scan_index);
2155 // if the shaded vertex corresponding to the index is not in the PT-cache, we need to shade again
2156 if (!in_cache) vertex_shade_count++;
2157 }
2158 }
2159
2160 // 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 +01002161 // 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
2162 if (max_index < min_index || max_index == min_index) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00002163
2164 if (max_index - min_index >= indexCount) {
Mark Young0ec6b062020-11-19 15:32:17 -07002165 skip |=
2166 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
2167 "%s The indices which were specified for the draw call only utilise approximately %.02f%% of "
2168 "index buffer value range. Arm Mali architectures before G71 do not have IDVS (Index-Driven "
2169 "Vertex Shading), meaning all vertices corresponding to indices between the minimum and "
2170 "maximum would be loaded, and possibly shaded, whether or not they are used.",
2171 VendorSpecificTag(kBPVendorArm),
2172 (static_cast<float>(indexCount) / static_cast<float>(max_index - min_index)) * 100.0f);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002173 return skip;
2174 }
2175
2176 // use a dynamic vector of bitsets as a memory-compact representation of which indices are included in the draw call
2177 // 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 +01002178 const size_t refs_per_bucket = 64;
2179 std::vector<std::bitset<refs_per_bucket>> vertex_reference_buckets;
2180
2181 const uint32_t n_indices = max_index - min_index + 1;
2182 const uint32_t n_buckets = (n_indices / static_cast<uint32_t>(refs_per_bucket)) +
2183 ((n_indices % static_cast<uint32_t>(refs_per_bucket)) != 0 ? 1 : 0);
2184
2185 // there needs to be at least one bitset to store a set of indices smaller than n_buckets
2186 vertex_reference_buckets.resize(std::max(1u, n_buckets));
Sam Walls8e77e4f2020-03-16 20:47:40 +00002187
2188 // To avoid using too much memory, we run over the indices again.
2189 // Knowing the size from the last scan allows us to record index usage with bitsets
2190 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
2191 uint32_t scan_index;
2192 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
2193 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
2194 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
2195 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
2196 } else {
2197 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
2198 }
2199 // keep track of the set of all indices used to reference vertices in the draw call
2200 size_t index_offset = scan_index - min_index;
Sam Walls61b06892020-07-23 16:20:50 +01002201 size_t bitset_bucket_index = index_offset / refs_per_bucket;
2202 uint64_t used_indices = 1ull << ((index_offset % refs_per_bucket) & 0xFFFFFFFFu);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002203 vertex_reference_buckets[bitset_bucket_index] |= used_indices;
2204 }
2205
2206 uint32_t vertex_reference_count = 0;
2207 for (const auto& bitset : vertex_reference_buckets) {
2208 vertex_reference_count += static_cast<uint32_t>(bitset.count());
2209 }
2210
2211 // 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 -07002212 float utilization = static_cast<float>(vertex_reference_count) / static_cast<float>(max_index - min_index + 1);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002213 // 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 -07002214 float cache_hit_rate = static_cast<float>(vertex_reference_count) / static_cast<float>(vertex_shade_count);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002215
2216 if (utilization < 0.5f) {
2217 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
2218 "%s The indices which were specified for the draw call only utilise approximately "
2219 "%.02f%% of the bound vertex buffer.",
2220 VendorSpecificTag(kBPVendorArm), utilization);
2221 }
2222
2223 if (cache_hit_rate <= 0.5f) {
2224 skip |=
2225 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_PostTransformCacheThrashing,
2226 "%s The indices which were specified for the draw call are estimated to cause thrashing of "
2227 "the post-transform vertex cache, with a hit-rate of %.02f%%. "
2228 "I.e. the ordering of the index buffer may not make optimal use of indices associated with "
2229 "recently shaded vertices.",
2230 VendorSpecificTag(kBPVendorArm), cache_hit_rate * 100.0f);
2231 }
2232 }
2233
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002234 return skip;
2235}
2236
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002237bool BestPractices::PreCallValidateCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
2238 const VkCommandBuffer* pCommandBuffers) const {
2239 bool skip = false;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002240 const auto* primary = GetCBState(commandBuffer);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002241 for (uint32_t i = 0; i < commandBufferCount; i++) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002242 const auto* secondary_cb = GetCBState(pCommandBuffers[i]);
2243 if (secondary_cb == nullptr) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002244 continue;
2245 }
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002246 const auto& secondary = secondary_cb->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002247 for (auto& clear : secondary.earlyClearAttachments) {
Hans-Kristian Arntzenfa8ef9f2021-06-29 12:07:59 +02002248 if (ClearAttachmentsIsFullClear(primary, uint32_t(clear.rects.size()), clear.rects.data())) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002249 skip |= ValidateClearAttachment(commandBuffer, primary,
2250 clear.framebufferAttachment, clear.colorAttachment,
2251 clear.aspects, true);
2252 }
2253 }
2254 }
Nadav Gevaf0808442021-05-21 13:51:25 -04002255
2256 if (VendorCheckEnabled(kBPVendorAMD)) {
2257 if (commandBufferCount > 0) {
2258 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdBuffer_AvoidSecondaryCmdBuffers,
2259 "%s Performance warning: Use of secondary command buffers is not recommended. ",
2260 VendorSpecificTag(kBPVendorAMD));
2261 }
2262 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002263 return skip;
2264}
2265
2266void BestPractices::PreCallRecordCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
2267 const VkCommandBuffer* pCommandBuffers) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002268 auto* primary = GetCBState(commandBuffer);
2269 auto& primary_state = primary->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002270
2271 for (uint32_t i = 0; i < commandBufferCount; i++) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002272 auto* secondary_cb = GetCBState(pCommandBuffers[i]);
2273 if (secondary_cb == nullptr) {
2274 continue;
2275 }
2276 auto& secondary = secondary_cb->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002277
2278 for (auto& early_clear : secondary.earlyClearAttachments) {
Hans-Kristian Arntzenfa8ef9f2021-06-29 12:07:59 +02002279 if (ClearAttachmentsIsFullClear(primary, uint32_t(early_clear.rects.size()), early_clear.rects.data())) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002280 RecordAttachmentClearAttachments(primary, primary_state, early_clear.framebufferAttachment,
2281 early_clear.colorAttachment, early_clear.aspects,
Hans-Kristian Arntzenfa8ef9f2021-06-29 12:07:59 +02002282 uint32_t(early_clear.rects.size()), early_clear.rects.data());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002283 } else {
2284 RecordAttachmentAccess(primary_state, early_clear.framebufferAttachment,
2285 early_clear.aspects);
2286 }
2287 }
2288
2289 for (auto& touch : secondary.touchesAttachments) {
2290 RecordAttachmentAccess(primary_state, touch.framebufferAttachment,
2291 touch.aspects);
2292 }
Hans-Kristian Arntzenc7eb82a2021-06-16 13:57:18 +02002293
2294 primary_state.numDrawCallsDepthEqualCompare += secondary.numDrawCallsDepthEqualCompare;
2295 primary_state.numDrawCallsDepthOnly += secondary.numDrawCallsDepthOnly;
Hans-Kristian Arntzenaf81dca2021-06-18 11:14:28 +02002296
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002297 auto* second_state = GetCBState(pCommandBuffers[i]);
Hans-Kristian Arntzenaf81dca2021-06-18 11:14:28 +02002298 if (second_state->hasDrawCmd) {
2299 primary->hasDrawCmd = true;
2300 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002301 }
2302
2303 ValidationStateTracker::PreCallRecordCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
2304}
2305
2306void BestPractices::RecordAttachmentAccess(RenderPassState& state, uint32_t fb_attachment, VkImageAspectFlags aspects) {
2307 // Called when we have a partial clear attachment, or a normal draw call which accesses an attachment.
2308 auto itr = std::find_if(state.touchesAttachments.begin(), state.touchesAttachments.end(),
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002309 [&](const AttachmentInfo& info) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002310 return info.framebufferAttachment == fb_attachment;
2311 });
2312
2313 if (itr != state.touchesAttachments.end()) {
2314 itr->aspects |= aspects;
2315 } else {
2316 state.touchesAttachments.push_back({ fb_attachment, aspects });
2317 }
2318}
2319
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002320void BestPractices::RecordAttachmentClearAttachments(CMD_BUFFER_STATE_BP* cmd_state, RenderPassState& state, uint32_t fb_attachment,
2321 uint32_t color_attachment, VkImageAspectFlags aspects, uint32_t rectCount,
2322 const VkClearRect* pRects) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002323 // If we observe a full clear before any other access to a frame buffer attachment,
2324 // we have candidate for redundant clear attachments.
2325 auto itr = std::find_if(state.touchesAttachments.begin(), state.touchesAttachments.end(),
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002326 [&](const AttachmentInfo& info) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002327 return info.framebufferAttachment == fb_attachment;
2328 });
2329
2330 uint32_t new_aspects = aspects;
2331 if (itr != state.touchesAttachments.end()) {
2332 new_aspects = aspects & ~itr->aspects;
2333 itr->aspects |= aspects;
2334 } else {
2335 state.touchesAttachments.push_back({ fb_attachment, aspects });
2336 }
2337
2338 if (new_aspects == 0) {
2339 return;
2340 }
2341
2342 if (cmd_state->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
2343 // The first command might be a clear, but might not be the first in the render pass, defer any checks until
2344 // CmdExecuteCommands.
2345 state.earlyClearAttachments.push_back({ fb_attachment, color_attachment, new_aspects,
2346 std::vector<VkClearRect>{pRects, pRects + rectCount} });
2347 }
2348}
2349
2350void BestPractices::PreCallRecordCmdClearAttachments(VkCommandBuffer commandBuffer,
2351 uint32_t attachmentCount, const VkClearAttachment* pClearAttachments,
2352 uint32_t rectCount, const VkClearRect* pRects) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002353 auto* cmd_state = GetCBState(commandBuffer);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002354 RENDER_PASS_STATE* rp_state = cmd_state->activeRenderPass.get();
2355 FRAMEBUFFER_STATE* fb_state = cmd_state->activeFramebuffer.get();
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002356 RenderPassState& tracking_state = cmd_state->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002357 bool is_secondary = cmd_state->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY;
2358
2359 if (rectCount == 0 || !rp_state) {
2360 return;
2361 }
2362
2363 if (!is_secondary && !fb_state) {
2364 return;
2365 }
2366
2367 // If we have a rect which covers the entire frame buffer, we have a LOAD_OP_CLEAR-like command.
2368 bool full_clear = ClearAttachmentsIsFullClear(cmd_state, rectCount, pRects);
2369
2370 auto& subpass = rp_state->createInfo.pSubpasses[cmd_state->activeSubpass];
2371 for (uint32_t i = 0; i < attachmentCount; i++) {
2372 auto& attachment = pClearAttachments[i];
2373 uint32_t fb_attachment = VK_ATTACHMENT_UNUSED;
2374 VkImageAspectFlags aspects = attachment.aspectMask;
2375
2376 if (aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) {
2377 if (subpass.pDepthStencilAttachment) {
2378 fb_attachment = subpass.pDepthStencilAttachment->attachment;
2379 }
2380 } else if (aspects & VK_IMAGE_ASPECT_COLOR_BIT) {
2381 fb_attachment = subpass.pColorAttachments[attachment.colorAttachment].attachment;
2382 }
2383
2384 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2385 if (full_clear) {
2386 RecordAttachmentClearAttachments(cmd_state, tracking_state,
2387 fb_attachment, attachment.colorAttachment, aspects,
2388 rectCount, pRects);
2389 } else {
2390 RecordAttachmentAccess(tracking_state, fb_attachment, aspects);
2391 }
2392 }
2393 }
2394
2395 ValidationStateTracker::PreCallRecordCmdClearAttachments(commandBuffer, attachmentCount, pClearAttachments,
2396 rectCount, pRects);
2397}
2398
Attilio Provenzano02859b22020-02-27 14:17:28 +00002399void BestPractices::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
2400 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
2401 ValidationStateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset,
2402 firstInstance);
2403
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002404 auto* cmd_state = GetCBState(commandBuffer);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002405 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices) {
2406 cmd_state->small_indexed_draw_call_count++;
2407 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002408
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002409 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDrawIndexed()");
Attilio Provenzano02859b22020-02-27 14:17:28 +00002410}
2411
Sam Walls0961ec02020-03-31 16:39:15 +01002412void BestPractices::PostCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
2413 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
2414 StateTracker::PostCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
2415 RecordCmdDrawType(commandBuffer, indexCount * instanceCount, "vkCmdDrawIndexed()");
2416}
2417
sfricke-samsung681ab7b2020-10-29 01:53:35 -07002418bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2419 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
2420 uint32_t maxDrawCount, uint32_t stride) const {
2421 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCount()");
2422
2423 return skip;
2424}
2425
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002426bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
2427 VkDeviceSize offset, VkBuffer countBuffer,
2428 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
2429 uint32_t stride) const {
2430 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCountKHR()");
Camden5b184be2019-08-13 07:50:19 -06002431
2432 return skip;
2433}
2434
2435bool BestPractices::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002436 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06002437 bool skip = false;
2438
2439 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002440 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
2441 "Warning: You are calling vkCmdDrawIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002442 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirect()");
Camden5b184be2019-08-13 07:50:19 -06002443 }
2444
2445 return skip;
2446}
2447
Sam Walls0961ec02020-03-31 16:39:15 +01002448void BestPractices::PostCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2449 uint32_t count, uint32_t stride) {
2450 StateTracker::PostCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, count, stride);
2451 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndirect()");
2452}
2453
Camden5b184be2019-08-13 07:50:19 -06002454bool BestPractices::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002455 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06002456 bool skip = false;
2457
2458 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002459 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
2460 "Warning: You are calling vkCmdDrawIndexedIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002461 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirect()");
Camden5b184be2019-08-13 07:50:19 -06002462 }
2463
2464 return skip;
2465}
2466
Sam Walls0961ec02020-03-31 16:39:15 +01002467void BestPractices::PostCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2468 uint32_t count, uint32_t stride) {
2469 StateTracker::PostCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, count, stride);
2470 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndexedIndirect()");
2471}
2472
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002473void BestPractices::ValidateBoundDescriptorSets(VkCommandBuffer commandBuffer, const char* function_name) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002474 auto* cb_state = GetCBState(commandBuffer);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002475
2476 if (cb_state) {
2477 for (auto descriptor_set : cb_state->validated_descriptor_sets) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002478 const auto& layout = *descriptor_set->GetLayout();
Hans-Kristian Arntzena8199012021-03-22 12:10:07 +01002479
2480 for (uint32_t index = 0; index < descriptor_set->GetBindingCount(); ++index) {
2481 // For bindless scenarios, we should not attempt to track descriptor set state.
2482 // It is highly uncertain which resources are actually bound.
2483 // Resources which are written to such a descriptor should be marked as indeterminate w.r.t. state.
2484 VkDescriptorBindingFlags flags = layout.GetDescriptorBindingFlagsFromIndex(index);
2485 if (flags & (VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT |
2486 VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT |
2487 VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT)) {
2488 continue;
2489 }
2490
2491 auto index_range = layout.GetGlobalIndexRangeFromIndex(index);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002492 for (uint32_t i = index_range.start; i < index_range.end; ++i) {
ZandroFargnoliacf12f02020-06-18 16:50:00 +01002493 VkImageView image_view{VK_NULL_HANDLE};
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002494
2495 auto descriptor = descriptor_set->GetDescriptorFromGlobalIndex(i);
2496 switch (descriptor->GetClass()) {
2497 case cvdescriptorset::DescriptorClass::Image: {
2498 if (const auto image_descriptor = static_cast<const cvdescriptorset::ImageDescriptor*>(descriptor)) {
2499 image_view = image_descriptor->GetImageView();
2500 }
Hans-Kristian Arntzenbc3a6152021-03-22 13:05:43 +01002501 break;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002502 }
2503 case cvdescriptorset::DescriptorClass::ImageSampler: {
2504 if (const auto image_sampler_descriptor =
2505 static_cast<const cvdescriptorset::ImageSamplerDescriptor*>(descriptor)) {
2506 image_view = image_sampler_descriptor->GetImageView();
2507 }
Hans-Kristian Arntzenbc3a6152021-03-22 13:05:43 +01002508 break;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002509 }
ZandroFargnoliacf12f02020-06-18 16:50:00 +01002510 default:
Hans-Kristian Arntzenbc3a6152021-03-22 13:05:43 +01002511 break;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002512 }
2513
2514 if (image_view) {
2515 IMAGE_VIEW_STATE* image_view_state = GetImageViewState(image_view);
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002516 QueueValidateImageView(cb_state->queue_submit_functions, function_name,
2517 image_view_state, IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002518 }
2519 }
2520 }
2521 }
2522 }
2523}
2524
2525void BestPractices::PreCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
2526 uint32_t firstVertex, uint32_t firstInstance) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002527 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDraw()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002528}
2529
2530void BestPractices::PreCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2531 uint32_t drawCount, uint32_t stride) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002532 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDrawIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002533}
2534
2535void BestPractices::PreCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2536 uint32_t drawCount, uint32_t stride) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002537 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDrawIndexedIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002538}
2539
Camden5b184be2019-08-13 07:50:19 -06002540bool BestPractices::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t groupCountX, uint32_t groupCountY,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002541 uint32_t groupCountZ) const {
Camden5b184be2019-08-13 07:50:19 -06002542 bool skip = false;
2543
2544 if ((groupCountX == 0) || (groupCountY == 0) || (groupCountZ == 0)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002545 skip |= LogWarning(device, kVUID_BestPractices_CmdDispatch_GroupCountZero,
2546 "Warning: You are calling vkCmdDispatch() while one or more groupCounts are zero (groupCountX = %" PRIu32
2547 ", groupCountY = %" PRIu32 ", groupCountZ = %" PRIu32 ").",
2548 groupCountX, groupCountY, groupCountZ);
Camden5b184be2019-08-13 07:50:19 -06002549 }
2550
2551 return skip;
2552}
Camden83a9c372019-08-14 11:41:38 -06002553
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002554bool BestPractices::PreCallValidateCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo* pSubpassEndInfo) const {
2555 bool skip = false;
2556 skip |= StateTracker::PreCallValidateCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
2557 skip |= ValidateCmdEndRenderPass(commandBuffer);
2558 return skip;
2559}
2560
2561bool BestPractices::PreCallValidateCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfo* pSubpassEndInfo) const {
2562 bool skip = false;
2563 skip |= StateTracker::PreCallValidateCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
2564 skip |= ValidateCmdEndRenderPass(commandBuffer);
2565 return skip;
2566}
2567
Sam Walls0961ec02020-03-31 16:39:15 +01002568bool BestPractices::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
2569 bool skip = false;
Sam Walls0961ec02020-03-31 16:39:15 +01002570 skip |= StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002571 skip |= ValidateCmdEndRenderPass(commandBuffer);
2572 return skip;
2573}
2574
2575bool BestPractices::ValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
2576 bool skip = false;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002577 const auto* cmd = GetCBState(commandBuffer);
Sam Walls0961ec02020-03-31 16:39:15 +01002578
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002579 if (cmd == nullptr) return skip;
2580 auto &render_pass_state = cmd->render_pass_state;
Sam Walls0961ec02020-03-31 16:39:15 +01002581
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002582 bool uses_depth = (render_pass_state.depthAttachment || render_pass_state.colorAttachment) &&
2583 render_pass_state.numDrawCallsDepthEqualCompare >= kDepthPrePassNumDrawCallsArm &&
2584 render_pass_state.numDrawCallsDepthOnly >= kDepthPrePassNumDrawCallsArm;
Sam Walls0961ec02020-03-31 16:39:15 +01002585 if (uses_depth) {
2586 skip |= LogPerformanceWarning(
2587 device, kVUID_BestPractices_EndRenderPass_DepthPrePassUsage,
2588 "%s Depth pre-passes may be in use. In general, this is not recommended, as in Arm Mali GPUs since "
2589 "Mali-T620, Forward Pixel Killing (FPK) can already perform automatic hidden surface removal; in which "
2590 "case, using depth pre-passes for hidden surface removal may worsen performance.",
2591 VendorSpecificTag(kBPVendorArm));
2592 }
2593
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002594 RENDER_PASS_STATE* rp = cmd->activeRenderPass.get();
2595
2596 if (VendorCheckEnabled(kBPVendorArm) && rp) {
2597
2598 // If we use an attachment on-tile, we should access it in some way. Otherwise,
2599 // it is redundant to have it be part of the render pass.
2600 // Only consider it redundant if it will actually consume bandwidth, i.e.
2601 // LOAD_OP_LOAD is used or STORE_OP_STORE. CLEAR -> DONT_CARE is benign,
2602 // as is using pure input attachments.
2603 // CLEAR -> STORE might be considered a "useful" thing to do, but
2604 // the optimal thing to do is to defer the clear until you're actually
2605 // going to render to the image.
2606
2607 uint32_t num_attachments = rp->createInfo.attachmentCount;
2608 for (uint32_t i = 0; i < num_attachments; i++) {
Hans-Kristian Arntzen237663c2021-07-01 14:36:40 +02002609 if (!RenderPassUsesAttachmentOnTile(rp->createInfo, i) ||
2610 RenderPassUsesAttachmentAsResolve(rp->createInfo, i)) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002611 continue;
2612 }
2613
2614 auto& attachment = rp->createInfo.pAttachments[i];
2615
2616 VkImageAspectFlags bandwidth_aspects = 0;
2617
2618 if (!FormatIsStencilOnly(attachment.format) &&
2619 (attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
2620 attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE)) {
2621 if (FormatHasDepth(attachment.format)) {
2622 bandwidth_aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
2623 } else {
2624 bandwidth_aspects |= VK_IMAGE_ASPECT_COLOR_BIT;
2625 }
2626 }
2627
2628 if (FormatHasStencil(attachment.format) &&
2629 (attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
2630 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE)) {
2631 bandwidth_aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
2632 }
2633
2634 if (!bandwidth_aspects) {
2635 continue;
2636 }
2637
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002638 auto itr = std::find_if(render_pass_state.touchesAttachments.begin(), render_pass_state.touchesAttachments.end(),
2639 [&](const AttachmentInfo& info) { return info.framebufferAttachment == i; });
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002640 uint32_t untouched_aspects = bandwidth_aspects;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002641 if (itr != render_pass_state.touchesAttachments.end()) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002642 untouched_aspects &= ~itr->aspects;
2643 }
2644
2645 if (untouched_aspects) {
2646 skip |= LogPerformanceWarning(
2647 device, kVUID_BestPractices_EndRenderPass_RedundantAttachmentOnTile,
2648 "%s Render pass was ended, but attachment #%u (format: %u, untouched aspects 0x%x) "
2649 "was never accessed by a pipeline or clear command. "
2650 "On tile-based architectures, LOAD_OP_LOAD and STORE_OP_STORE consume bandwidth and should not be part of the render pass "
2651 "if the attachments are not intended to be accessed.",
2652 VendorSpecificTag(kBPVendorArm), i, attachment.format, untouched_aspects);
2653 }
2654 }
2655 }
2656
Sam Walls0961ec02020-03-31 16:39:15 +01002657 return skip;
2658}
2659
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002660void BestPractices::PreCallRecordCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002661 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDispatch()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002662}
2663
2664void BestPractices::PreCallRecordCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002665 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDispatchIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002666}
2667
Camden Stocker9c051442019-11-06 14:28:43 -08002668bool BestPractices::ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(VkPhysicalDevice physicalDevice,
2669 const char* api_name) const {
2670 bool skip = false;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002671 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
Camden Stocker9c051442019-11-06 14:28:43 -08002672
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002673 if (bp_pd_state) {
2674 if (bp_pd_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState == UNCALLED) {
2675 skip |= LogWarning(physicalDevice, kVUID_BestPractices_DisplayPlane_PropertiesNotCalled,
2676 "Potential problem with calling %s() without first retrieving properties from "
2677 "vkGetPhysicalDeviceDisplayPlanePropertiesKHR or vkGetPhysicalDeviceDisplayPlaneProperties2KHR.",
2678 api_name);
2679 }
Camden Stocker9c051442019-11-06 14:28:43 -08002680 }
2681
2682 return skip;
2683}
2684
Camden83a9c372019-08-14 11:41:38 -06002685bool BestPractices::PreCallValidateGetDisplayPlaneSupportedDisplaysKHR(VkPhysicalDevice physicalDevice, uint32_t planeIndex,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002686 uint32_t* pDisplayCount, VkDisplayKHR* pDisplays) const {
Camden83a9c372019-08-14 11:41:38 -06002687 bool skip = false;
2688
Camden Stocker9c051442019-11-06 14:28:43 -08002689 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneSupportedDisplaysKHR");
Camden83a9c372019-08-14 11:41:38 -06002690
Camden Stocker9c051442019-11-06 14:28:43 -08002691 return skip;
2692}
2693
2694bool BestPractices::PreCallValidateGetDisplayPlaneCapabilitiesKHR(VkPhysicalDevice physicalDevice, VkDisplayModeKHR mode,
2695 uint32_t planeIndex,
2696 VkDisplayPlaneCapabilitiesKHR* pCapabilities) const {
2697 bool skip = false;
2698
2699 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilitiesKHR");
2700
2701 return skip;
2702}
2703
2704bool BestPractices::PreCallValidateGetDisplayPlaneCapabilities2KHR(VkPhysicalDevice physicalDevice,
2705 const VkDisplayPlaneInfo2KHR* pDisplayPlaneInfo,
2706 VkDisplayPlaneCapabilities2KHR* pCapabilities) const {
2707 bool skip = false;
2708
2709 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilities2KHR");
Camden83a9c372019-08-14 11:41:38 -06002710
2711 return skip;
2712}
Camden05de2d42019-08-19 10:23:56 -06002713
2714bool BestPractices::PreCallValidateGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain, uint32_t* pSwapchainImageCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002715 VkImage* pSwapchainImages) const {
Camden05de2d42019-08-19 10:23:56 -06002716 bool skip = false;
2717
Nathaniel Cesario39152e62021-07-02 13:04:16 -06002718 const auto* swapchain_state = static_cast<SWAPCHAIN_STATE_BP*>(Get<SWAPCHAIN_NODE>(swapchain));
Camden05de2d42019-08-19 10:23:56 -06002719
Nathaniel Cesario39152e62021-07-02 13:04:16 -06002720 if (swapchain_state && pSwapchainImages) {
Camden05de2d42019-08-19 10:23:56 -06002721 // Compare the preliminary value of *pSwapchainImageCount with the value this time:
Nathaniel Cesario39152e62021-07-02 13:04:16 -06002722 if (swapchain_state->vkGetSwapchainImagesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002723 skip |=
2724 LogWarning(device, kVUID_Core_Swapchain_PriorCount,
2725 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImageCount; but no prior positive value has "
2726 "been seen for pSwapchainImages.");
Camden05de2d42019-08-19 10:23:56 -06002727 }
Camden05de2d42019-08-19 10:23:56 -06002728
Nathaniel Cesario4ce98382021-05-28 11:33:20 -06002729 if (*pSwapchainImageCount > swapchain_state->get_swapchain_image_count) {
2730 skip |= LogWarning(
2731 device, kVUID_BestPractices_Swapchain_InvalidCount,
2732 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImages, and with pSwapchainImageCount set to a "
Nadav Gevaf0808442021-05-21 13:51:25 -04002733 "value (%" PRId32 ") that is greater than the value (%" PRId32 ") that was returned when pSwapchainImages was NULL.",
Nathaniel Cesario4ce98382021-05-28 11:33:20 -06002734 *pSwapchainImageCount, swapchain_state->get_swapchain_image_count);
2735 }
2736 }
2737
Camden05de2d42019-08-19 10:23:56 -06002738 return skip;
2739}
2740
2741// Common function to handle validation for GetPhysicalDeviceQueueFamilyProperties & 2KHR version
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002742bool BestPractices::ValidateCommonGetPhysicalDeviceQueueFamilyProperties(const PHYSICAL_DEVICE_STATE* pd_state,
2743 uint32_t requested_queue_family_property_count,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002744 const CALL_STATE call_state,
2745 const char* caller_name) const {
Camden05de2d42019-08-19 10:23:56 -06002746 bool skip = false;
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002747 // Verify that for each physical device, this command is called first with NULL pQueueFamilyProperties in order to get count
2748 if (UNCALLED == call_state) {
2749 skip |= LogWarning(
2750 pd_state->phys_device, kVUID_Core_DevLimit_MissingQueryCount,
2751 "%s is called with non-NULL pQueueFamilyProperties before obtaining pQueueFamilyPropertyCount. It is "
2752 "recommended "
2753 "to first call %s with NULL pQueueFamilyProperties in order to obtain the maximal pQueueFamilyPropertyCount.",
2754 caller_name, caller_name);
2755 // Then verify that pCount that is passed in on second call matches what was returned
2756 } else if (pd_state->queue_family_known_count != requested_queue_family_property_count) {
2757 skip |= LogWarning(pd_state->phys_device, kVUID_Core_DevLimit_CountMismatch,
2758 "%s is called with non-NULL pQueueFamilyProperties and pQueueFamilyPropertyCount value %" PRIu32
2759 ", but the largest previously returned pQueueFamilyPropertyCount for this physicalDevice is %" PRIu32
2760 ". It is recommended to instead receive all the properties by calling %s with "
2761 "pQueueFamilyPropertyCount that was "
2762 "previously obtained by calling %s with NULL pQueueFamilyProperties.",
2763 caller_name, requested_queue_family_property_count, pd_state->queue_family_known_count, caller_name,
2764 caller_name);
Camden05de2d42019-08-19 10:23:56 -06002765 }
2766
2767 return skip;
2768}
2769
Jeff Bolz5c801d12019-10-09 10:38:45 -05002770bool BestPractices::PreCallValidateBindAccelerationStructureMemoryNV(
2771 VkDevice device, uint32_t bindInfoCount, const VkBindAccelerationStructureMemoryInfoNV* pBindInfos) const {
Camden Stocker82510582019-09-03 14:00:16 -06002772 bool skip = false;
2773
2774 for (uint32_t i = 0; i < bindInfoCount; i++) {
sourav parmarcd5fb182020-07-17 12:58:44 -07002775 const ACCELERATION_STRUCTURE_STATE* as_state = GetAccelerationStructureStateNV(pBindInfos[i].accelerationStructure);
Camden Stocker82510582019-09-03 14:00:16 -06002776 if (!as_state->memory_requirements_checked) {
2777 // There's not an explicit requirement in the spec to call vkGetImageMemoryRequirements() prior to calling
2778 // BindAccelerationStructureMemoryNV but it's implied in that memory being bound must conform with
2779 // VkAccelerationStructureMemoryRequirementsInfoNV from vkGetAccelerationStructureMemoryRequirementsNV
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002780 skip |= LogWarning(
2781 device, kVUID_BestPractices_BindAccelNV_NoMemReqQuery,
Camden Stocker82510582019-09-03 14:00:16 -06002782 "vkBindAccelerationStructureMemoryNV(): "
2783 "Binding memory to %s but vkGetAccelerationStructureMemoryRequirementsNV() has not been called on that structure.",
2784 report_data->FormatHandle(pBindInfos[i].accelerationStructure).c_str());
2785 }
2786 }
2787
2788 return skip;
2789}
2790
Camden05de2d42019-08-19 10:23:56 -06002791bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
2792 uint32_t* pQueueFamilyPropertyCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002793 VkQueueFamilyProperties* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06002794 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
2795 assert(physical_device_state);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002796 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physical_device_state->phys_device);
2797 if (pQueueFamilyProperties && bp_pd_state) {
2798 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
2799 bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
2800 "vkGetPhysicalDeviceQueueFamilyProperties()");
2801 }
2802 return false;
Camden05de2d42019-08-19 10:23:56 -06002803}
2804
Mike Schuchardt2df08912020-12-15 16:28:09 -08002805bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
2806 uint32_t* pQueueFamilyPropertyCount,
2807 VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06002808 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
2809 assert(physical_device_state);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002810 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physical_device_state->phys_device);
2811 if (pQueueFamilyProperties && bp_pd_state) {
2812 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
2813 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
2814 "vkGetPhysicalDeviceQueueFamilyProperties2()");
2815 }
2816 return false;
Camden05de2d42019-08-19 10:23:56 -06002817}
2818
Jeff Bolz5c801d12019-10-09 10:38:45 -05002819bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2KHR(
Mike Schuchardt2df08912020-12-15 16:28:09 -08002820 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount, VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06002821 auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
2822 assert(physical_device_state);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002823 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physical_device_state->phys_device);
2824 if (pQueueFamilyProperties && bp_pd_state) {
2825 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
2826 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
2827 "vkGetPhysicalDeviceQueueFamilyProperties2KHR()");
2828 }
2829 return false;
Camden05de2d42019-08-19 10:23:56 -06002830}
2831
2832bool BestPractices::PreCallValidateGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
2833 uint32_t* pSurfaceFormatCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002834 VkSurfaceFormatKHR* pSurfaceFormats) const {
Camden05de2d42019-08-19 10:23:56 -06002835 if (!pSurfaceFormats) return false;
2836 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002837 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2838 const auto& call_state = bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState;
Camden05de2d42019-08-19 10:23:56 -06002839 bool skip = false;
2840 if (call_state == UNCALLED) {
2841 // Since we haven't recorded a preliminary value of *pSurfaceFormatCount, that likely means that the application didn't
2842 // previously call this function with a NULL value of pSurfaceFormats:
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002843 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_MustQueryCount,
2844 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount; but no prior "
2845 "positive value has been seen for pSurfaceFormats.");
Camden05de2d42019-08-19 10:23:56 -06002846 } else {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002847 auto prev_format_count = static_cast<uint32_t>(physical_device_state->surface_formats.size());
Peter Chene191bd72019-09-16 13:04:37 -04002848 if (*pSurfaceFormatCount > prev_format_count) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002849 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_CountMismatch,
2850 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount, and with "
2851 "pSurfaceFormats set to a value (%u) that is greater than the value (%u) that was returned "
2852 "when pSurfaceFormatCount was NULL.",
2853 *pSurfaceFormatCount, prev_format_count);
Camden05de2d42019-08-19 10:23:56 -06002854 }
2855 }
2856 return skip;
2857}
Camden Stocker23cc47d2019-09-03 14:53:57 -06002858
2859bool BestPractices::PreCallValidateQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002860 VkFence fence) const {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002861 bool skip = false;
2862
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002863 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
2864 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
Camden Stocker23cc47d2019-09-03 14:53:57 -06002865 // 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 -07002866 layer_data::unordered_set<const IMAGE_STATE*> sparse_images;
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002867 // Track images getting metadata bound by this call in a set, it'll be recorded into the image_state
2868 // in RecordQueueBindSparse.
Jeremy Gebbencbf22862021-03-03 12:01:22 -07002869 layer_data::unordered_set<const IMAGE_STATE*> sparse_images_with_metadata;
Camden Stocker23cc47d2019-09-03 14:53:57 -06002870 // 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 -07002871 for (uint32_t i = 0; i < bind_info.imageBindCount; ++i) {
2872 const auto& image_bind = bind_info.pImageBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04002873 auto image_state = Get<IMAGE_STATE>(image_bind.image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002874 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002875 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002876 }
Camden Stocker23cc47d2019-09-03 14:53:57 -06002877 sparse_images.insert(image_state);
2878 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
2879 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
2880 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002881 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002882 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
2883 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002884 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002885 }
2886 }
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06002887 if (!image_state->memory_requirements_checked[0]) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002888 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002889 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002890 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
2891 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002892 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002893 }
2894 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002895 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
2896 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04002897 auto image_state = Get<IMAGE_STATE>(bind_info.pImageOpaqueBinds[i].image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002898 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002899 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002900 }
Camden Stocker23cc47d2019-09-03 14:53:57 -06002901 sparse_images.insert(image_state);
2902 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
2903 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
2904 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002905 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002906 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
2907 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002908 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002909 }
2910 }
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06002911 if (!image_state->memory_requirements_checked[0]) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002912 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002913 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002914 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
2915 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002916 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002917 }
2918 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
2919 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002920 sparse_images_with_metadata.insert(image_state);
Camden Stocker23cc47d2019-09-03 14:53:57 -06002921 }
2922 }
2923 }
2924 for (const auto& sparse_image_state : sparse_images) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002925 if (sparse_image_state->sparse_metadata_required && !sparse_image_state->sparse_metadata_bound &&
2926 sparse_images_with_metadata.find(sparse_image_state) == sparse_images_with_metadata.end()) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002927 // Warn if sparse image binding metadata required for image with sparse binding, but metadata not bound
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002928 skip |= LogWarning(sparse_image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002929 "vkQueueBindSparse(): Binding sparse memory to %s which requires a metadata aspect but no "
2930 "binding with VK_SPARSE_MEMORY_BIND_METADATA_BIT set was made.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002931 report_data->FormatHandle(sparse_image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002932 }
2933 }
2934 }
2935
2936 return skip;
2937}
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002938
Mark Lobodzinski84101d72020-04-24 09:43:48 -06002939void BestPractices::ManualPostCallRecordQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
2940 VkFence fence, VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07002941 if (result != VK_SUCCESS) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07002942 return;
2943 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002944
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002945 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
2946 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
2947 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
2948 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04002949 auto image_state = Get<IMAGE_STATE>(bind_info.pImageOpaqueBinds[i].image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002950 if (!image_state) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002951 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002952 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002953 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
2954 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
2955 image_state->sparse_metadata_bound = true;
2956 }
2957 }
2958 }
2959 }
2960}
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002961
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002962bool BestPractices::ClearAttachmentsIsFullClear(const CMD_BUFFER_STATE_BP* cmd, uint32_t rectCount,
2963 const VkClearRect* pRects) const {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002964 if (cmd->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
2965 // We don't know the accurate render area in a secondary,
2966 // so assume we clear the entire frame buffer.
2967 // This is resolved in CmdExecuteCommands where we can check if the clear is a full clear.
2968 return true;
2969 }
2970
2971 // If we have a rect which covers the entire frame buffer, we have a LOAD_OP_CLEAR-like command.
2972 for (uint32_t i = 0; i < rectCount; i++) {
2973 auto& rect = pRects[i];
2974 auto& render_area = cmd->activeRenderPassBeginInfo.renderArea;
2975 if (rect.rect.extent.width == render_area.extent.width && rect.rect.extent.height == render_area.extent.height) {
2976 return true;
2977 }
2978 }
2979
2980 return false;
2981}
2982
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002983bool BestPractices::ValidateClearAttachment(VkCommandBuffer commandBuffer, const CMD_BUFFER_STATE_BP* cmd, uint32_t fb_attachment,
2984 uint32_t color_attachment, VkImageAspectFlags aspects, bool secondary) const {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002985 const RENDER_PASS_STATE* rp = cmd->activeRenderPass.get();
2986 bool skip = false;
2987
2988 if (!rp || fb_attachment == VK_ATTACHMENT_UNUSED) {
2989 return skip;
2990 }
2991
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002992 const auto& rp_state = cmd->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002993
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002994 auto attachment_itr = std::find_if(rp_state.touchesAttachments.begin(), rp_state.touchesAttachments.end(),
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002995 [&](const AttachmentInfo& info) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002996 return info.framebufferAttachment == fb_attachment;
2997 });
2998
2999 // Only report aspects which haven't been touched yet.
3000 VkImageAspectFlags new_aspects = aspects;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003001 if (attachment_itr != rp_state.touchesAttachments.end()) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003002 new_aspects &= ~attachment_itr->aspects;
3003 }
3004
3005 // Warn if this is issued prior to Draw Cmd and clearing the entire attachment
3006 if (!cmd->hasDrawCmd) {
3007 skip |= LogPerformanceWarning(
3008 commandBuffer, kVUID_BestPractices_DrawState_ClearCmdBeforeDraw,
Hans-Kristian Arntzen4ddd6182021-06-18 12:16:33 +02003009 "vkCmdClearAttachments() issued on %s prior to any Draw Cmds in current render pass. It is recommended you "
3010 "use RenderPass LOAD_OP_CLEAR on attachments instead.",
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003011 report_data->FormatHandle(commandBuffer).c_str());
3012 }
3013
3014 if ((new_aspects & VK_IMAGE_ASPECT_COLOR_BIT) &&
3015 rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
3016 skip |= LogPerformanceWarning(
3017 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
3018 "%svkCmdClearAttachments() issued on %s for color attachment #%u in this subpass, "
3019 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
3020 "it is more efficient.",
3021 secondary ? "vkCmdExecuteCommands(): " : "",
3022 report_data->FormatHandle(commandBuffer).c_str(), color_attachment);
3023 }
3024
3025 if ((new_aspects & VK_IMAGE_ASPECT_DEPTH_BIT) &&
3026 rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
3027 skip |= LogPerformanceWarning(
3028 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
3029 "%svkCmdClearAttachments() issued on %s for the depth attachment in this subpass, "
3030 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
3031 "it is more efficient.",
3032 secondary ? "vkCmdExecuteCommands(): " : "",
3033 report_data->FormatHandle(commandBuffer).c_str());
3034 }
3035
3036 if ((new_aspects & VK_IMAGE_ASPECT_STENCIL_BIT) &&
3037 rp->createInfo.pAttachments[fb_attachment].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
3038 skip |= LogPerformanceWarning(
3039 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
3040 "%svkCmdClearAttachments() issued on %s for the stencil attachment in this subpass, "
3041 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
3042 "it is more efficient.",
3043 secondary ? "vkCmdExecuteCommands(): " : "",
3044 report_data->FormatHandle(commandBuffer).c_str());
3045 }
3046
3047 return skip;
3048}
3049
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003050bool BestPractices::PreCallValidateCmdClearAttachments(VkCommandBuffer commandBuffer, uint32_t attachmentCount,
Camden Stockerf55721f2019-09-09 11:04:49 -06003051 const VkClearAttachment* pAttachments, uint32_t rectCount,
3052 const VkClearRect* pRects) const {
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003053 bool skip = false;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003054 const auto* cb_node = GetCBState(commandBuffer);
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003055 if (!cb_node) return skip;
3056
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003057 if (cb_node->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
3058 // Defer checks to ExecuteCommands.
3059 return skip;
3060 }
3061
3062 // Only care about full clears, partial clears might have legitimate uses.
3063 if (!ClearAttachmentsIsFullClear(cb_node, rectCount, pRects)) {
3064 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003065 }
3066
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003067 // Check for uses of ClearAttachments along with LOAD_OP_LOAD,
3068 // as it can be more efficient to just use LOAD_OP_CLEAR
locke-lunargaecf2152020-05-12 17:15:41 -06003069 const RENDER_PASS_STATE* rp = cb_node->activeRenderPass.get();
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003070 if (rp) {
3071 const auto& subpass = rp->createInfo.pSubpasses[cb_node->activeSubpass];
3072
3073 for (uint32_t i = 0; i < attachmentCount; i++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02003074 const auto& attachment = pAttachments[i];
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003075
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003076 if (attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
3077 uint32_t color_attachment = attachment.colorAttachment;
3078 uint32_t fb_attachment = subpass.pColorAttachments[color_attachment].attachment;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003079 skip |= ValidateClearAttachment(commandBuffer, cb_node,
3080 fb_attachment, color_attachment,
3081 attachment.aspectMask, false);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003082 }
3083
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003084 if (subpass.pDepthStencilAttachment &&
3085 (attachment.aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT))) {
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003086 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003087 skip |= ValidateClearAttachment(commandBuffer, cb_node,
3088 fb_attachment, VK_ATTACHMENT_UNUSED,
3089 attachment.aspectMask, false);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003090 }
3091 }
3092 }
3093
Nadav Gevaf0808442021-05-21 13:51:25 -04003094 if (VendorCheckEnabled(kBPVendorAMD)) {
3095 for (uint32_t attachment_idx = 0; attachment_idx < attachmentCount; attachment_idx++) {
3096 if (pAttachments[attachment_idx].aspectMask == VK_IMAGE_ASPECT_COLOR_BIT) {
3097 bool black_check = false;
3098 black_check |= pAttachments[attachment_idx].clearValue.color.float32[0] != 0.0f;
3099 black_check |= pAttachments[attachment_idx].clearValue.color.float32[1] != 0.0f;
3100 black_check |= pAttachments[attachment_idx].clearValue.color.float32[2] != 0.0f;
3101 black_check |= pAttachments[attachment_idx].clearValue.color.float32[3] != 0.0f &&
3102 pAttachments[attachment_idx].clearValue.color.float32[3] != 1.0f;
3103
3104 bool white_check = false;
3105 white_check |= pAttachments[attachment_idx].clearValue.color.float32[0] != 1.0f;
3106 white_check |= pAttachments[attachment_idx].clearValue.color.float32[1] != 1.0f;
3107 white_check |= pAttachments[attachment_idx].clearValue.color.float32[2] != 1.0f;
3108 white_check |= pAttachments[attachment_idx].clearValue.color.float32[3] != 0.0f &&
3109 pAttachments[attachment_idx].clearValue.color.float32[3] != 1.0f;
3110
3111 if (black_check && white_check) {
3112 skip |= LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachment_FastClearValues,
3113 "%s Performance warning: vkCmdClearAttachments() clear value for color attachment %" PRId32 " is not a fast clear value."
3114 "Consider changing to one of the following:"
3115 "RGBA(0, 0, 0, 0) "
3116 "RGBA(0, 0, 0, 1) "
3117 "RGBA(1, 1, 1, 0) "
3118 "RGBA(1, 1, 1, 1)",
3119 VendorSpecificTag(kBPVendorAMD), attachment_idx);
3120 }
3121 } else {
3122 if ((pAttachments[attachment_idx].clearValue.depthStencil.depth != 0 &&
3123 pAttachments[attachment_idx].clearValue.depthStencil.depth != 1) &&
3124 pAttachments[attachment_idx].clearValue.depthStencil.stencil != 0) {
3125 skip |= LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachment_FastClearValues,
3126 "%s Performance warning: vkCmdClearAttachments() clear value for depth/stencil "
3127 "attachment %" PRId32 " is not a fast clear value."
3128 "Consider changing to one of the following:"
3129 "D=0.0f, S=0"
3130 "D=1.0f, S=0",
3131 VendorSpecificTag(kBPVendorAMD), attachment_idx);
3132 }
3133 }
3134 }
3135 }
3136
Camden Stockerf55721f2019-09-09 11:04:49 -06003137 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003138}
Attilio Provenzano02859b22020-02-27 14:17:28 +00003139
3140bool BestPractices::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3141 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3142 const VkImageResolve* pRegions) const {
3143 bool skip = false;
3144
3145 skip |= VendorCheckEnabled(kBPVendorArm) &&
3146 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage_ResolvingImage,
3147 "%s Attempting to use vkCmdResolveImage to resolve a multisampled image. "
3148 "This is a very slow and extremely bandwidth intensive path. "
3149 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
3150 VendorSpecificTag(kBPVendorArm));
3151
3152 return skip;
3153}
3154
Jeff Leger178b1e52020-10-05 12:22:23 -04003155bool BestPractices::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
3156 const VkResolveImageInfo2KHR* pResolveImageInfo) const {
3157 bool skip = false;
3158
3159 skip |= VendorCheckEnabled(kBPVendorArm) &&
3160 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2KHR_ResolvingImage,
3161 "%s Attempting to use vkCmdResolveImage2KHR to resolve a multisampled image. "
3162 "This is a very slow and extremely bandwidth intensive path. "
3163 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
3164 VendorSpecificTag(kBPVendorArm));
3165
3166 return skip;
3167}
3168
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003169void BestPractices::PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3170 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3171 const VkImageResolve* pRegions) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003172 auto* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003173 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003174 auto* src = GetImageUsageState(srcImage);
3175 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003176
3177 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003178 QueueValidateImage(funcs, "vkCmdResolveImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pRegions[i].srcSubresource);
3179 QueueValidateImage(funcs, "vkCmdResolveImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003180 }
3181}
3182
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01003183void BestPractices::PreCallRecordCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
3184 const VkResolveImageInfo2KHR* pResolveImageInfo) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003185 auto* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003186 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003187 auto* src = GetImageUsageState(pResolveImageInfo->srcImage);
3188 auto* dst = GetImageUsageState(pResolveImageInfo->dstImage);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01003189 uint32_t regionCount = pResolveImageInfo->regionCount;
3190
3191 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003192 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pResolveImageInfo->pRegions[i].srcSubresource);
3193 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pResolveImageInfo->pRegions[i].dstSubresource);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01003194 }
3195}
3196
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003197void BestPractices::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
3198 const VkClearColorValue* pColor, uint32_t rangeCount,
3199 const VkImageSubresourceRange* pRanges) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003200 auto* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003201 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003202 auto* dst = GetImageUsageState(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003203
3204 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003205 QueueValidateImage(funcs, "vkCmdClearColorImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003206 }
3207}
3208
3209void BestPractices::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
3210 const VkClearDepthStencilValue* pDepthStencil, uint32_t rangeCount,
3211 const VkImageSubresourceRange* pRanges) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003212 auto* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003213 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003214 auto* dst = GetImageUsageState(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003215
3216 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003217 QueueValidateImage(funcs, "vkCmdClearDepthStencilImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003218 }
3219}
3220
3221void BestPractices::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3222 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3223 const VkImageCopy* pRegions) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003224 auto* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003225 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003226 auto* src = GetImageUsageState(srcImage);
3227 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003228
3229 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003230 QueueValidateImage(funcs, "vkCmdCopyImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].srcSubresource);
3231 QueueValidateImage(funcs, "vkCmdCopyImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003232 }
3233}
3234
3235void BestPractices::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
3236 VkImageLayout dstImageLayout, uint32_t regionCount,
3237 const VkBufferImageCopy* pRegions) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003238 auto* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003239 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003240 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003241
3242 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003243 QueueValidateImage(funcs, "vkCmdCopyBufferToImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003244 }
3245}
3246
3247void BestPractices::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3248 VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy* pRegions) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003249 auto* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003250 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003251 auto* src = GetImageUsageState(srcImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003252
3253 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003254 QueueValidateImage(funcs, "vkCmdCopyImageToBuffer()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003255 }
3256}
3257
3258void BestPractices::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3259 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3260 const VkImageBlit* pRegions, VkFilter filter) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003261 auto* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003262 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003263 auto* src = GetImageUsageState(srcImage);
3264 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003265
3266 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003267 QueueValidateImage(funcs, "vkCmdBlitImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_READ, pRegions[i].srcSubresource);
3268 QueueValidateImage(funcs, "vkCmdBlitImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003269 }
3270}
3271
Attilio Provenzano02859b22020-02-27 14:17:28 +00003272bool BestPractices::PreCallValidateCreateSampler(VkDevice device, const VkSamplerCreateInfo* pCreateInfo,
3273 const VkAllocationCallbacks* pAllocator, VkSampler* pSampler) const {
3274 bool skip = false;
3275
3276 if (VendorCheckEnabled(kBPVendorArm)) {
3277 if ((pCreateInfo->addressModeU != pCreateInfo->addressModeV) || (pCreateInfo->addressModeV != pCreateInfo->addressModeW)) {
3278 skip |= LogPerformanceWarning(
3279 device, kVUID_BestPractices_CreateSampler_DifferentWrappingModes,
3280 "%s Creating a sampler object with wrapping modes which do not match (U = %u, V = %u, W = %u). "
3281 "This may cause reduced performance even if only U (1D image) or U/V wrapping modes (2D "
3282 "image) are actually used. If you need different wrapping modes, disregard this warning.",
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -06003283 VendorSpecificTag(kBPVendorArm), pCreateInfo->addressModeU, pCreateInfo->addressModeV, pCreateInfo->addressModeW);
Attilio Provenzano02859b22020-02-27 14:17:28 +00003284 }
3285
3286 if ((pCreateInfo->minLod != 0.0f) || (pCreateInfo->maxLod < VK_LOD_CLAMP_NONE)) {
3287 skip |= LogPerformanceWarning(
3288 device, kVUID_BestPractices_CreateSampler_LodClamping,
3289 "%s Creating a sampler object with LOD clamping (minLod = %f, maxLod = %f). This may cause reduced performance. "
3290 "Instead of clamping LOD in the sampler, consider using an VkImageView which restricts the mip-levels, set minLod "
3291 "to 0.0, and maxLod to VK_LOD_CLAMP_NONE.",
3292 VendorSpecificTag(kBPVendorArm), pCreateInfo->minLod, pCreateInfo->maxLod);
3293 }
3294
3295 if (pCreateInfo->mipLodBias != 0.0f) {
3296 skip |=
3297 LogPerformanceWarning(device, kVUID_BestPractices_CreateSampler_LodBias,
3298 "%s Creating a sampler object with LOD bias != 0.0 (%f). This will lead to less efficient "
3299 "descriptors being created and may cause reduced performance.",
3300 VendorSpecificTag(kBPVendorArm), pCreateInfo->mipLodBias);
3301 }
3302
3303 if ((pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
3304 pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
3305 pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER) &&
3306 (pCreateInfo->borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK)) {
3307 skip |= LogPerformanceWarning(
3308 device, kVUID_BestPractices_CreateSampler_BorderClampColor,
3309 "%s Creating a sampler object with border clamping and borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK. "
3310 "This will lead to less efficient descriptors being created and may cause reduced performance. "
3311 "If possible, use VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK as the border color.",
3312 VendorSpecificTag(kBPVendorArm));
3313 }
3314
3315 if (pCreateInfo->unnormalizedCoordinates) {
3316 skip |= LogPerformanceWarning(
3317 device, kVUID_BestPractices_CreateSampler_UnnormalizedCoordinates,
3318 "%s Creating a sampler object with unnormalized coordinates. This will lead to less efficient "
3319 "descriptors being created and may cause reduced performance.",
3320 VendorSpecificTag(kBPVendorArm));
3321 }
3322
3323 if (pCreateInfo->anisotropyEnable) {
3324 skip |= LogPerformanceWarning(
3325 device, kVUID_BestPractices_CreateSampler_Anisotropy,
3326 "%s Creating a sampler object with anisotropy. This will lead to less efficient descriptors being created "
3327 "and may cause reduced performance.",
3328 VendorSpecificTag(kBPVendorArm));
3329 }
3330 }
3331
3332 return skip;
3333}
Sam Walls8e77e4f2020-03-16 20:47:40 +00003334
Nadav Gevaf0808442021-05-21 13:51:25 -04003335void BestPractices::PreCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
3336 const VkGraphicsPipelineCreateInfo* pCreateInfos,
3337 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
3338 void* cgpl_state) {
3339 ValidationStateTracker::PreCallRecordCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos, pAllocator,
3340 pPipelines);
3341 // AMD best practice
3342 num_pso += createInfoCount;
3343}
3344
3345bool BestPractices::PreCallValidateUpdateDescriptorSets(VkDevice device, uint32_t descriptorWriteCount,
3346 const VkWriteDescriptorSet* pDescriptorWrites, uint32_t descriptorCopyCount,
3347 const VkCopyDescriptorSet* pDescriptorCopies) const {
3348 bool skip = false;
3349 if (VendorCheckEnabled(kBPVendorAMD)) {
3350 if (descriptorCopyCount > 0) {
3351 skip |= LogPerformanceWarning(device, kVUID_BestPractices_UpdateDescriptors_AvoidCopyingDescriptors,
3352 "%s Performance warning: copying descriptor sets is not recommended",
3353 VendorSpecificTag(kBPVendorAMD));
3354 }
3355 }
3356
3357 return skip;
3358}
3359
3360bool BestPractices::PreCallValidateCreateDescriptorUpdateTemplate(VkDevice device,
3361 const VkDescriptorUpdateTemplateCreateInfo* pCreateInfo,
3362 const VkAllocationCallbacks* pAllocator,
3363 VkDescriptorUpdateTemplate* pDescriptorUpdateTemplate) const {
3364 bool skip = false;
3365 if (VendorCheckEnabled(kBPVendorAMD)) {
3366 skip |= LogPerformanceWarning(device, kVUID_BestPractices_UpdateDescriptors_PreferNonTemplate,
3367 "%s Performance warning: using DescriptorSetWithTemplate is not recommended. Prefer using "
3368 "vkUpdateDescriptorSet instead",
3369 VendorSpecificTag(kBPVendorAMD));
3370 }
3371
3372 return skip;
3373}
3374
3375bool BestPractices::PreCallValidateCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
3376 const VkClearColorValue* pColor, uint32_t rangeCount,
3377 const VkImageSubresourceRange* pRanges) const {
3378 bool skip = false;
3379 if (VendorCheckEnabled(kBPVendorAMD)) {
3380 skip |= LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachment_ClearImage,
3381 "%s Performance warning: using vkCmdClearColorImage is not recommended. Prefer using LOAD_OP_CLEAR or "
3382 "vkCmdClearAttachments instead",
3383 VendorSpecificTag(kBPVendorAMD));
3384 }
3385
3386 return skip;
3387}
3388
3389bool BestPractices::PreCallValidateCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image,
3390 VkImageLayout imageLayout,
3391 const VkClearDepthStencilValue* pDepthStencil, uint32_t rangeCount,
3392 const VkImageSubresourceRange* pRanges) const {
3393 bool skip = false;
3394 if (VendorCheckEnabled(kBPVendorAMD)) {
3395 skip |= LogPerformanceWarning(
3396 device, kVUID_BestPractices_ClearAttachment_ClearImage,
3397 "%s Performance warning: using vkCmdClearDepthStencilImage is not recommended. Prefer using LOAD_OP_CLEAR or "
3398 "vkCmdClearAttachments instead",
3399 VendorSpecificTag(kBPVendorAMD));
3400 }
3401
3402 return skip;
3403}
3404
3405bool BestPractices::PreCallValidateCreatePipelineLayout(VkDevice device, const VkPipelineLayoutCreateInfo* pCreateInfo,
3406 const VkAllocationCallbacks* pAllocator,
3407 VkPipelineLayout* pPipelineLayout) const {
3408 bool skip = false;
3409 if (VendorCheckEnabled(kBPVendorAMD)) {
3410 // Descriptor sets cost 1 DWORD each.
3411 // Dynamic buffers cost 2 DWORDs each when robust buffer access is OFF.
3412 // Dynamic buffers cost 4 DWORDs each when robust buffer access is ON.
3413 // Push constants cost 1 DWORD per 4 bytes in the Push constant range.
3414 uint32_t pipeline_size = pCreateInfo->setLayoutCount; // in DWORDS
3415 for (uint32_t i = 0; i < pCreateInfo->setLayoutCount; i++) {
3416 std::shared_ptr<const cvdescriptorset::DescriptorSetLayout> descriptor_set_layout_state =
3417 GetDescriptorSetLayoutShared(pCreateInfo->pSetLayouts[i]);
3418 pipeline_size += descriptor_set_layout_state->GetDynamicDescriptorCount() * (robust_buffer_access ? 4 : 2);
3419 }
3420
3421 for (uint32_t i = 0; i < pCreateInfo->pushConstantRangeCount; i++) {
3422 pipeline_size += pCreateInfo->pPushConstantRanges[i].size / 4;
3423 }
3424
3425 if (pipeline_size > kPipelineLayoutSizeWarningLimitAMD) {
3426 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelinesLayout_KeepLayoutSmall,
3427 "%s Performance warning: pipeline layout size is too large. Prefer smaller pipeline layouts."
3428 "Descriptor sets cost 1 DWORD each. "
3429 "Dynamic buffers cost 2 DWORDs each when robust buffer access is OFF. "
3430 "Dynamic buffers cost 4 DWORDs each when robust buffer access is ON. "
3431 "Push constants cost 1 DWORD per 4 bytes in the Push constant range. ",
3432 VendorSpecificTag(kBPVendorAMD));
3433 }
3434 }
3435
3436 return skip;
3437}
3438
3439bool BestPractices::PreCallValidateCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3440 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3441 const VkImageCopy* pRegions) const {
3442 bool skip = false;
3443 std::stringstream src_image_hex;
3444 std::stringstream dst_image_hex;
3445 src_image_hex << "0x" << std::hex << HandleToUint64(srcImage);
3446 dst_image_hex << "0x" << std::hex << HandleToUint64(dstImage);
3447
3448 if (VendorCheckEnabled(kBPVendorAMD)) {
3449 const IMAGE_STATE* src_state = Get<IMAGE_STATE>(srcImage);
3450 const IMAGE_STATE* dst_state = Get<IMAGE_STATE>(dstImage);
3451
3452 if (src_state && dst_state) {
3453 VkImageTiling src_Tiling = src_state->createInfo.tiling;
3454 VkImageTiling dst_Tiling = dst_state->createInfo.tiling;
3455 if (src_Tiling != dst_Tiling && (src_Tiling == VK_IMAGE_TILING_LINEAR || dst_Tiling == VK_IMAGE_TILING_LINEAR)) {
3456 skip |=
3457 LogPerformanceWarning(device, kVUID_BestPractices_vkImage_AvoidImageToImageCopy,
3458 "%s Performance warning: image %s and image %s have differing tilings. Use buffer to "
3459 "image (vkCmdCopyImageToBuffer) "
3460 "and image to buffer (vkCmdCopyBufferToImage) copies instead of image to image "
3461 "copies when converting between linear and optimal images",
3462 VendorSpecificTag(kBPVendorAMD), src_image_hex.str().c_str(), dst_image_hex.str().c_str());
3463 }
3464 }
3465 }
3466
3467 return skip;
3468}
3469
3470bool BestPractices::PreCallValidateCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
3471 VkPipeline pipeline) const {
3472 bool skip = false;
3473
3474 if (VendorCheckEnabled(kBPVendorAMD)) {
3475 if (pipelines_used_in_frame.find(pipeline) != pipelines_used_in_frame.end()) {
3476 skip |= LogPerformanceWarning(device, kVUID_BestPractices_Pipeline_SortAndBind,
3477 "%s Performance warning: Pipeline %s was bound twice in the frame. Keep pipeline state changes to a minimum,"
3478 "for example, by sorting draw calls by pipeline.",
3479 VendorSpecificTag(kBPVendorAMD), report_data->FormatHandle(pipeline).c_str());
3480 }
3481 }
3482
3483 return skip;
3484}
3485
3486void BestPractices::ManualPostCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
3487 VkFence fence, VkResult result) {
3488 // AMD best practice
3489 num_queue_submissions += submitCount;
3490}
3491
3492bool BestPractices::PreCallValidateQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo) const {
3493 bool skip = false;
3494
3495 if (VendorCheckEnabled(kBPVendorAMD)) {
3496 if (num_queue_submissions > kNumberOfSubmissionWarningLimitAMD) {
3497 skip |= LogPerformanceWarning(
3498 device, kVUID_BestPractices_Submission_ReduceNumberOfSubmissions,
3499 "%s Performance warning: command buffers submitted %" PRId32 " times this frame. Submitting command buffers has a CPU "
3500 "and GPU overhead. Submit fewer times to incur less overhead.",
3501 VendorSpecificTag(kBPVendorAMD), num_queue_submissions);
3502 }
3503 }
3504
3505 return skip;
3506}
3507
3508void BestPractices::PostCallRecordCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
3509 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
3510 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
3511 uint32_t bufferMemoryBarrierCount,
3512 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
3513 uint32_t imageMemoryBarrierCount,
3514 const VkImageMemoryBarrier* pImageMemoryBarriers) {
3515 num_barriers_objects += memoryBarrierCount;
3516 num_barriers_objects += imageMemoryBarrierCount;
3517 num_barriers_objects += bufferMemoryBarrierCount;
3518}
3519
3520void BestPractices::ManualPostCallRecordCreateFence(VkDevice device, const VkFenceCreateInfo* pCreateInfo,
3521 const VkAllocationCallbacks* pAllocator, VkFence* pFence, VkResult result) {
3522 // AMD best practice
3523 if (result == VK_SUCCESS) {
3524 num_fence_objects++;
3525 }
3526}
3527
3528void BestPractices::ManualPostCallRecordCreateSemaphore(VkDevice device, const VkSemaphoreCreateInfo* pCreateInfo,
3529 const VkAllocationCallbacks* pAllocator, VkSemaphore* pSemaphore,
3530 VkResult result) {
3531 // AMD best practice
3532 if (result == VK_SUCCESS) {
3533 num_semaphore_objects++;
3534 }
3535}
3536
3537bool BestPractices::PreCallValidateCreateSemaphore(VkDevice device, const VkSemaphoreCreateInfo* pCreateInfo,
3538 const VkAllocationCallbacks* pAllocator, VkSemaphore* pSemaphore) const {
3539 bool skip = false;
3540 if (VendorCheckEnabled(kBPVendorAMD)) {
3541 if (num_semaphore_objects > kMaxRecommendedSemaphoreObjectsSizeAMD) {
3542 skip |= LogPerformanceWarning(device, kVUID_BestPractices_SyncObjects_HighNumberOfSemaphores,
3543 "%s Performance warning: High number of vkSemaphore objects created."
3544 "Minimize the amount of queue synchronization that is used. "
3545 "Semaphores and fences have overhead. Each fence has a CPU and GPU cost with it.",
3546 VendorSpecificTag(kBPVendorAMD));
3547 }
3548 }
3549
3550 return skip;
3551}
3552
3553bool BestPractices::PreCallValidateCreateFence(VkDevice device, const VkFenceCreateInfo* pCreateInfo,
3554 const VkAllocationCallbacks* pAllocator, VkFence* pFence) const {
3555 bool skip = false;
3556 if (VendorCheckEnabled(kBPVendorAMD)) {
3557 if (num_fence_objects > kMaxRecommendedFenceObjectsSizeAMD) {
3558 skip |= LogPerformanceWarning(device, kVUID_BestPractices_SyncObjects_HighNumberOfFences,
3559 "%s Performance warning: High number of VkFence objects created."
3560 "Minimize the amount of CPU-GPU synchronization that is used. "
3561 "Semaphores and fences have overhead.Each fence has a CPU and GPU cost with it.",
3562 VendorSpecificTag(kBPVendorAMD));
3563 }
3564 }
3565
3566 return skip;
3567}
3568
Sam Walls8e77e4f2020-03-16 20:47:40 +00003569void BestPractices::PostTransformLRUCacheModel::resize(size_t size) { _entries.resize(size); }
3570
3571bool BestPractices::PostTransformLRUCacheModel::query_cache(uint32_t value) {
3572 // look for a cache hit
3573 auto hit = std::find_if(_entries.begin(), _entries.end(), [value](const CacheEntry& entry) { return entry.value == value; });
3574 if (hit != _entries.end()) {
3575 // mark the cache hit as being most recently used
3576 hit->age = iteration++;
3577 return true;
3578 }
3579
3580 // if there's no cache hit, we need to model the entry being inserted into the cache
3581 CacheEntry new_entry = {value, iteration};
3582 if (iteration < static_cast<uint32_t>(std::distance(_entries.begin(), _entries.end()))) {
3583 // if there is still space left in the cache, use the next available slot
3584 *(_entries.begin() + iteration) = new_entry;
3585 } else {
3586 // otherwise replace the least recently used cache entry
3587 auto lru = std::min_element(_entries.begin(), hit, [](const CacheEntry& a, const CacheEntry& b) { return a.age < b.age; });
3588 *lru = new_entry;
3589 }
3590 iteration++;
3591 return false;
3592}
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003593
3594bool BestPractices::PreCallValidateAcquireNextImageKHR(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout,
3595 VkSemaphore semaphore, VkFence fence, uint32_t* pImageIndex) const {
3596 const auto swapchain_data = GetSwapchainState(swapchain);
3597 bool skip = false;
3598 if (swapchain_data && swapchain_data->images.size() == 0) {
3599 skip |= LogWarning(swapchain, kVUID_Core_DrawState_SwapchainImagesNotFound,
3600 "vkAcquireNextImageKHR: No images found to acquire from. Application probably did not call "
3601 "vkGetSwapchainImagesKHR after swapchain creation.");
3602 }
3603 return skip;
3604}
3605
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003606void BestPractices::CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(CALL_STATE& call_state, bool no_pointer) {
3607 if (no_pointer) {
3608 if (UNCALLED == call_state) {
3609 call_state = QUERY_COUNT;
3610 }
3611 } else { // Save queue family properties
3612 call_state = QUERY_DETAILS;
3613 }
3614}
3615
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003616void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
3617 uint32_t* pQueueFamilyPropertyCount,
3618 VkQueueFamilyProperties* pQueueFamilyProperties) {
3619 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(physicalDevice, pQueueFamilyPropertyCount,
3620 pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003621 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003622 if (bp_pd_state) {
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003623 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
3624 nullptr == pQueueFamilyProperties);
3625 }
3626}
3627
3628void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
3629 uint32_t* pQueueFamilyPropertyCount,
3630 VkQueueFamilyProperties2* pQueueFamilyProperties) {
3631 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(physicalDevice, pQueueFamilyPropertyCount,
3632 pQueueFamilyProperties);
3633 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3634 if (bp_pd_state) {
3635 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
3636 nullptr == pQueueFamilyProperties);
3637 }
3638}
3639
3640void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(VkPhysicalDevice physicalDevice,
3641 uint32_t* pQueueFamilyPropertyCount,
3642 VkQueueFamilyProperties2* pQueueFamilyProperties) {
3643 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(physicalDevice, pQueueFamilyPropertyCount,
3644 pQueueFamilyProperties);
3645 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3646 if (bp_pd_state) {
3647 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
3648 nullptr == pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003649 }
3650}
3651
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003652void BestPractices::PostCallRecordGetPhysicalDeviceFeatures(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures* pFeatures) {
3653 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003654 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3655 if (bp_pd_state) {
3656 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3657 }
3658}
3659
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003660void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2(VkPhysicalDevice physicalDevice,
3661 VkPhysicalDeviceFeatures2* pFeatures) {
3662 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003663 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3664 if (bp_pd_state) {
3665 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3666 }
3667}
3668
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003669void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2KHR(VkPhysicalDevice physicalDevice,
3670 VkPhysicalDeviceFeatures2* pFeatures) {
3671 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2KHR(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003672 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3673 if (bp_pd_state) {
3674 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3675 }
3676}
3677
3678void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilitiesKHR(VkPhysicalDevice physicalDevice,
3679 VkSurfaceKHR surface,
3680 VkSurfaceCapabilitiesKHR* pSurfaceCapabilities,
3681 VkResult result) {
3682 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3683 if (bp_pd_state) {
3684 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3685 }
3686}
3687
3688void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2KHR(
3689 VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
3690 VkSurfaceCapabilities2KHR* pSurfaceCapabilities, VkResult result) {
3691 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3692 if (bp_pd_state) {
3693 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3694 }
3695}
3696
3697void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2EXT(VkPhysicalDevice physicalDevice,
3698 VkSurfaceKHR surface,
3699 VkSurfaceCapabilities2EXT* pSurfaceCapabilities,
3700 VkResult result) {
3701 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3702 if (bp_pd_state) {
3703 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3704 }
3705}
3706
3707void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice physicalDevice,
3708 VkSurfaceKHR surface, uint32_t* pPresentModeCount,
3709 VkPresentModeKHR* pPresentModes, VkResult result) {
3710 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
3711 if (bp_pd_data) {
3712 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfacePresentModesKHRState;
3713
3714 if (*pPresentModeCount) {
3715 if (call_state < QUERY_COUNT) {
3716 call_state = QUERY_COUNT;
3717 }
3718 }
3719 if (pPresentModes) {
3720 if (call_state < QUERY_DETAILS) {
3721 call_state = QUERY_DETAILS;
3722 }
3723 }
3724 }
3725}
3726
3727void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
3728 uint32_t* pSurfaceFormatCount,
3729 VkSurfaceFormatKHR* pSurfaceFormats, VkResult result) {
3730 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
3731 if (bp_pd_data) {
3732 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState;
3733
3734 if (*pSurfaceFormatCount) {
3735 if (call_state < QUERY_COUNT) {
3736 call_state = QUERY_COUNT;
3737 }
3738 }
3739 if (pSurfaceFormats) {
3740 if (call_state < QUERY_DETAILS) {
3741 call_state = QUERY_DETAILS;
3742 }
3743 }
3744 }
3745}
3746
3747void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormats2KHR(VkPhysicalDevice physicalDevice,
3748 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
3749 uint32_t* pSurfaceFormatCount,
3750 VkSurfaceFormat2KHR* pSurfaceFormats, VkResult result) {
3751 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
3752 if (bp_pd_data) {
3753 if (*pSurfaceFormatCount) {
3754 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_COUNT) {
3755 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_COUNT;
3756 }
3757 }
3758 if (pSurfaceFormats) {
3759 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_DETAILS) {
3760 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_DETAILS;
3761 }
3762 }
3763 }
3764}
3765
3766void BestPractices::ManualPostCallRecordGetPhysicalDeviceDisplayPlanePropertiesKHR(VkPhysicalDevice physicalDevice,
3767 uint32_t* pPropertyCount,
3768 VkDisplayPlanePropertiesKHR* pProperties,
3769 VkResult result) {
3770 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
3771 if (bp_pd_data) {
3772 if (*pPropertyCount) {
3773 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_COUNT) {
3774 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_COUNT;
3775 }
3776 }
3777 if (pProperties) {
3778 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_DETAILS) {
3779 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_DETAILS;
3780 }
3781 }
3782 }
3783}
3784
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003785void BestPractices::ManualPostCallRecordGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain,
3786 uint32_t* pSwapchainImageCount, VkImage* pSwapchainImages,
3787 VkResult result) {
Nathaniel Cesario39152e62021-07-02 13:04:16 -06003788 auto* swapchain_state = static_cast<SWAPCHAIN_STATE_BP*>(Get<SWAPCHAIN_NODE>(swapchain));
3789 if (swapchain_state && (pSwapchainImages || *pSwapchainImageCount)) {
3790 if (swapchain_state->vkGetSwapchainImagesKHRState < QUERY_DETAILS) {
3791 swapchain_state->vkGetSwapchainImagesKHRState = QUERY_DETAILS;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003792 }
3793 }
3794}
3795
3796void BestPractices::ManualPostCallRecordEnumeratePhysicalDevices(VkInstance instance, uint32_t* pPhysicalDeviceCount,
3797 VkPhysicalDevice* pPhysicalDevices, VkResult result) {
3798 if ((nullptr != pPhysicalDevices) && ((result == VK_SUCCESS || result == VK_INCOMPLETE))) {
3799 for (uint32_t i = 0; i < *pPhysicalDeviceCount; i++) {
3800 phys_device_bp_state_map.emplace(pPhysicalDevices[i], PHYSICAL_DEVICE_STATE_BP{});
3801 }
3802 }
3803}
3804
Nadav Gevaf0808442021-05-21 13:51:25 -04003805void BestPractices::ManualPostCallRecordCreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo* pCreateInfo,
3806 const VkAllocationCallbacks* pAllocator, VkDevice* pDevice, VkResult result) {
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003807 if (VK_SUCCESS == result) {
3808 instance_device_bp_state = &phys_device_bp_state_map[gpu];
Nadav Gevaf0808442021-05-21 13:51:25 -04003809
3810 if ((pCreateInfo->pEnabledFeatures != nullptr) && (pCreateInfo->pEnabledFeatures->robustBufferAccess == VK_TRUE)) {
3811 robust_buffer_access = true;
3812 }
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003813 }
Nadav Gevaf0808442021-05-21 13:51:25 -04003814
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003815}
3816
3817PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP(const VkPhysicalDevice& phys_device) {
3818 if (phys_device_bp_state_map.count(phys_device) > 0) {
3819 return &phys_device_bp_state_map.at(phys_device);
3820 } else {
3821 return nullptr;
3822 }
3823}
3824
3825const PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP(const VkPhysicalDevice& phys_device) const {
3826 if (phys_device_bp_state_map.count(phys_device) > 0) {
3827 return &phys_device_bp_state_map.at(phys_device);
3828 } else {
3829 return nullptr;
3830 }
3831}
3832
3833PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP() {
3834 auto bp_state = (reinterpret_cast<BestPractices*>(instance_state))->instance_device_bp_state;
3835 if (bp_state) {
3836 return bp_state;
3837 } else if (!bp_state && phys_device_bp_state_map.count(physical_device_state->phys_device) > 0) {
3838 return &phys_device_bp_state_map.at(physical_device_state->phys_device);
3839 } else {
3840 return nullptr;
3841 }
3842}
3843
3844const PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP() const {
3845 auto bp_state = (reinterpret_cast<BestPractices*>(instance_state))->instance_device_bp_state;
3846 if (bp_state) {
3847 return bp_state;
3848 } else if (!bp_state && phys_device_bp_state_map.count(physical_device_state->phys_device) > 0) {
3849 return &phys_device_bp_state_map.at(physical_device_state->phys_device);
3850 } else {
3851 return nullptr;
3852 }
3853}
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003854
3855void BestPractices::PreCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits, VkFence fence) {
3856 ValidationStateTracker::PreCallRecordQueueSubmit(queue, submitCount, pSubmits, fence);
3857
3858 QUEUE_STATE* queue_state = GetQueueState(queue);
3859 for (uint32_t submit = 0; submit < submitCount; submit++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02003860 const auto& submit_info = pSubmits[submit];
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003861 for (uint32_t cb_index = 0; cb_index < submit_info.commandBufferCount; cb_index++) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003862 auto* cb = GetCBState(submit_info.pCommandBuffers[cb_index]);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003863 for (auto &func : cb->queue_submit_functions) {
3864 func(this, queue_state);
3865 }
3866 }
3867 }
3868}