blob: 388bf4b10598e6cdd782514539e69f42a9d6d71c [file] [log] [blame]
Hannes Harnisch607d1d92021-07-10 18:44:56 +02001/* 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.
Camdeneaa86ea2019-07-26 11:00:09 -06004 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 * Author: Camden Stocker <camden@lunarg.com>
18 */
19
Mark Lobodzinski57b8ae82020-02-20 16:37:14 -070020#include "best_practices_validation.h"
Camden5b184be2019-08-13 07:50:19 -060021#include "layer_chassis_dispatch.h"
Camden Stocker0a660ce2019-08-27 15:30:40 -060022#include "best_practices_error_enums.h"
Sam Wallsd7ab6db2020-06-19 20:41:54 +010023#include "shader_validation.h"
Jeremy Gebbena3705f42021-01-19 16:47:43 -070024#include "sync_utils.h"
Jeremy Gebben159b3cc2021-06-03 09:09:03 -060025#include "cmd_buffer_state.h"
26#include "device_state.h"
27#include "render_pass_state.h"
Camden5b184be2019-08-13 07:50:19 -060028
29#include <string>
Sam Walls8e77e4f2020-03-16 20:47:40 +000030#include <bitset>
Sam Wallsd7ab6db2020-06-19 20:41:54 +010031#include <memory>
Camden5b184be2019-08-13 07:50:19 -060032
Attilio Provenzano19d6a982020-02-27 12:41:41 +000033struct VendorSpecificInfo {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060034 EnableFlags vendor_id;
Attilio Provenzano19d6a982020-02-27 12:41:41 +000035 std::string name;
36};
37
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -070038const std::map<BPVendorFlagBits, VendorSpecificInfo> kVendorInfo = {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060039 {kBPVendorArm, {vendor_specific_arm, "Arm"}},
Attilio Provenzano19d6a982020-02-27 12:41:41 +000040};
41
Hannes Harnisch607d1d92021-07-10 18:44:56 +020042const SpecialUseVUIDs kSpecialUseInstanceVUIDs {
43 kVUID_BestPractices_CreateInstance_SpecialUseExtension_CADSupport,
44 kVUID_BestPractices_CreateInstance_SpecialUseExtension_D3DEmulation,
45 kVUID_BestPractices_CreateInstance_SpecialUseExtension_DevTools,
46 kVUID_BestPractices_CreateInstance_SpecialUseExtension_Debugging,
47 kVUID_BestPractices_CreateInstance_SpecialUseExtension_GLEmulation,
48};
49
50const SpecialUseVUIDs kSpecialUseDeviceVUIDs {
51 kVUID_BestPractices_CreateDevice_SpecialUseExtension_CADSupport,
52 kVUID_BestPractices_CreateDevice_SpecialUseExtension_D3DEmulation,
53 kVUID_BestPractices_CreateDevice_SpecialUseExtension_DevTools,
54 kVUID_BestPractices_CreateDevice_SpecialUseExtension_Debugging,
55 kVUID_BestPractices_CreateDevice_SpecialUseExtension_GLEmulation,
56};
57
Attilio Provenzano19d6a982020-02-27 12:41:41 +000058bool BestPractices::VendorCheckEnabled(BPVendorFlags vendors) const {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -070059 for (const auto& vendor : kVendorInfo) {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060060 if (vendors & vendor.first && enabled[vendor.second.vendor_id]) {
Attilio Provenzano19d6a982020-02-27 12:41:41 +000061 return true;
62 }
63 }
64 return false;
65}
66
67const char* VendorSpecificTag(BPVendorFlags vendors) {
68 // Cache built vendor tags in a map
Jeremy Gebbencbf22862021-03-03 12:01:22 -070069 static layer_data::unordered_map<BPVendorFlags, std::string> tag_map;
Attilio Provenzano19d6a982020-02-27 12:41:41 +000070
71 auto res = tag_map.find(vendors);
72 if (res == tag_map.end()) {
73 // Build the vendor tag string
74 std::stringstream vendor_tag;
75
76 vendor_tag << "[";
77 bool first_vendor = true;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -070078 for (const auto& vendor : kVendorInfo) {
Attilio Provenzano19d6a982020-02-27 12:41:41 +000079 if (vendors & vendor.first) {
80 if (!first_vendor) {
81 vendor_tag << ", ";
82 }
83 vendor_tag << vendor.second.name;
84 first_vendor = false;
85 }
86 }
87 vendor_tag << "]";
88
89 tag_map[vendors] = vendor_tag.str();
90 res = tag_map.find(vendors);
91 }
92
93 return res->second.c_str();
94}
95
Mark Lobodzinski6167e102020-02-24 17:03:55 -070096const char* DepReasonToString(ExtDeprecationReason reason) {
97 switch (reason) {
98 case kExtPromoted:
99 return "promoted to";
100 break;
101 case kExtObsoleted:
102 return "obsoleted by";
103 break;
104 case kExtDeprecated:
105 return "deprecated by";
106 break;
107 default:
108 return "";
109 break;
110 }
111}
112
113bool BestPractices::ValidateDeprecatedExtensions(const char* api_name, const char* extension_name, uint32_t version,
114 const char* vuid) const {
115 bool skip = false;
116 auto dep_info_it = deprecated_extensions.find(extension_name);
117 if (dep_info_it != deprecated_extensions.end()) {
118 auto dep_info = dep_info_it->second;
Mark Lobodzinski6a149702020-05-14 12:21:34 -0600119 if (((dep_info.target.compare("VK_VERSION_1_1") == 0) && (version >= VK_API_VERSION_1_1)) ||
120 ((dep_info.target.compare("VK_VERSION_1_2") == 0) && (version >= VK_API_VERSION_1_2))) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700121 skip |=
122 LogWarning(instance, vuid, "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
123 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
Mark Lobodzinski6a149702020-05-14 12:21:34 -0600124 } else if (dep_info.target.find("VK_VERSION") == std::string::npos) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700125 if (dep_info.target.length() == 0) {
126 skip |= LogWarning(instance, vuid,
127 "%s(): Attempting to enable deprecated extension %s, but this extension has been deprecated "
128 "without replacement.",
129 api_name, extension_name);
130 } else {
131 skip |= LogWarning(instance, vuid,
132 "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
133 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
134 }
135 }
136 }
137 return skip;
138}
139
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200140bool BestPractices::ValidateSpecialUseExtensions(const char* api_name, const char* extension_name, const SpecialUseVUIDs& special_use_vuids) const
141{
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700142 bool skip = false;
143 auto dep_info_it = special_use_extensions.find(extension_name);
144
145 if (dep_info_it != special_use_extensions.end()) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200146 const char* const format = "%s(): Attempting to enable extension %s, but this extension is intended to support %s "
147 "and it is strongly recommended that it be otherwise avoided.";
148 auto& special_uses = dep_info_it->second;
149
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700150 if (special_uses.find("cadsupport") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200151 skip |= LogWarning(instance, special_use_vuids.cadsupport, format, api_name, extension_name,
152 "specialized functionality used by CAD/CAM applications");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700153 }
154 if (special_uses.find("d3demulation") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200155 skip |= LogWarning(instance, special_use_vuids.d3demulation, format, api_name, extension_name,
156 "D3D emulation layers, and applications ported from D3D, by adding functionality specific to D3D");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700157 }
158 if (special_uses.find("devtools") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200159 skip |= LogWarning(instance, special_use_vuids.devtools, format, api_name, extension_name,
160 "developer tools such as capture-replay libraries");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700161 }
162 if (special_uses.find("debugging") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200163 skip |= LogWarning(instance, special_use_vuids.debugging, format, api_name, extension_name,
164 "use by applications when debugging");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700165 }
166 if (special_uses.find("glemulation") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200167 skip |= LogWarning(instance, special_use_vuids.glemulation, format, api_name, extension_name,
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700168 "OpenGL and/or OpenGL ES emulation layers, and applications ported from those APIs, by adding functionality "
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200169 "specific to those APIs");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700170 }
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700171 }
172 return skip;
173}
174
Camden5b184be2019-08-13 07:50:19 -0600175bool BestPractices::PreCallValidateCreateInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500176 VkInstance* pInstance) const {
Camden5b184be2019-08-13 07:50:19 -0600177 bool skip = false;
178
179 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
180 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kDeviceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800181 skip |= LogWarning(instance, kVUID_BestPractices_CreateInstance_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700182 "vkCreateInstance(): Attempting to enable Device Extension %s at CreateInstance time.",
183 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600184 }
Mark Lobodzinski17d8dc62020-06-03 08:48:58 -0600185 uint32_t specified_version =
186 (pCreateInfo->pApplicationInfo ? pCreateInfo->pApplicationInfo->apiVersion : VK_API_VERSION_1_0);
187 skip |= ValidateDeprecatedExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i], specified_version,
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700188 kVUID_BestPractices_CreateInstance_DeprecatedExtension);
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200189 skip |= ValidateSpecialUseExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i], kSpecialUseInstanceVUIDs);
Camden5b184be2019-08-13 07:50:19 -0600190 }
191
192 return skip;
193}
194
195void BestPractices::PreCallRecordCreateInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator,
196 VkInstance* pInstance) {
Mark Lobodzinski97484d62020-03-03 11:57:41 -0700197 ValidationStateTracker::PreCallRecordCreateInstance(pCreateInfo, pAllocator, pInstance);
Sam Walls53bf7652020-04-21 17:35:15 +0100198
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700199 if (pCreateInfo != nullptr && pCreateInfo->pApplicationInfo != nullptr) {
Sam Walls53bf7652020-04-21 17:35:15 +0100200 instance_api_version = pCreateInfo->pApplicationInfo->apiVersion;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700201 } else {
Sam Walls53bf7652020-04-21 17:35:15 +0100202 instance_api_version = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700203 }
Camden5b184be2019-08-13 07:50:19 -0600204}
205
206bool BestPractices::PreCallValidateCreateDevice(VkPhysicalDevice physicalDevice, const VkDeviceCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500207 const VkAllocationCallbacks* pAllocator, VkDevice* pDevice) const {
Camden5b184be2019-08-13 07:50:19 -0600208 bool skip = false;
209
210 // get API version of physical device passed when creating device.
211 VkPhysicalDeviceProperties physical_device_properties{};
212 DispatchGetPhysicalDeviceProperties(physicalDevice, &physical_device_properties);
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500213 auto device_api_version = physical_device_properties.apiVersion;
Camden5b184be2019-08-13 07:50:19 -0600214
215 // check api versions and warn if instance api Version is higher than version on device.
216 if (instance_api_version > device_api_version) {
Mark Lobodzinski60880782020-08-11 08:02:07 -0600217 std::string inst_api_name = StringAPIVersion(instance_api_version);
218 std::string dev_api_name = StringAPIVersion(device_api_version);
Camden5b184be2019-08-13 07:50:19 -0600219
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700220 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_API_Mismatch,
221 "vkCreateDevice(): API Version of current instance, %s is higher than API Version on device, %s",
222 inst_api_name.c_str(), dev_api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -0600223 }
224
225 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
226 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kInstanceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800227 skip |= LogWarning(instance, kVUID_BestPractices_CreateDevice_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700228 "vkCreateDevice(): Attempting to enable Instance Extension %s at CreateDevice time.",
229 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600230 }
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700231 skip |= ValidateDeprecatedExtensions("CreateDevice", pCreateInfo->ppEnabledExtensionNames[i], instance_api_version,
232 kVUID_BestPractices_CreateDevice_DeprecatedExtension);
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200233 skip |= ValidateSpecialUseExtensions("CreateDevice", pCreateInfo->ppEnabledExtensionNames[i], kSpecialUseDeviceVUIDs);
Camden5b184be2019-08-13 07:50:19 -0600234 }
235
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600236 const auto bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
237 if ((bp_pd_state->vkGetPhysicalDeviceFeaturesState == UNCALLED) && (pCreateInfo->pEnabledFeatures != NULL)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700238 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_PDFeaturesNotCalled,
239 "vkCreateDevice() called before getting physical device features from vkGetPhysicalDeviceFeatures().");
Camden83a9c372019-08-14 11:41:38 -0600240 }
241
Szilard Papp7d2c7952020-06-22 14:38:13 +0100242 if ((VendorCheckEnabled(kBPVendorArm)) && (pCreateInfo->pEnabledFeatures != nullptr) &&
243 (pCreateInfo->pEnabledFeatures->robustBufferAccess == VK_TRUE)) {
244 skip |= LogPerformanceWarning(
245 device, kVUID_BestPractices_CreateDevice_RobustBufferAccess,
246 "%s vkCreateDevice() called with enabled robustBufferAccess. Use robustBufferAccess as a debugging tool during "
247 "development. Enabling it causes loss in performance for accesses to uniform buffers and shader storage "
248 "buffers. Disable robustBufferAccess in release builds. Only leave it enabled if the application use-case "
249 "requires the additional level of reliability due to the use of unverified user-supplied draw parameters.",
250 VendorSpecificTag(kBPVendorArm));
251 }
252
Camden5b184be2019-08-13 07:50:19 -0600253 return skip;
254}
255
256bool BestPractices::PreCallValidateCreateBuffer(VkDevice device, const VkBufferCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500257 const VkAllocationCallbacks* pAllocator, VkBuffer* pBuffer) const {
Camden5b184be2019-08-13 07:50:19 -0600258 bool skip = false;
259
260 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700261 std::stringstream buffer_hex;
262 buffer_hex << "0x" << std::hex << HandleToUint64(pBuffer);
Camden5b184be2019-08-13 07:50:19 -0600263
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700264 skip |= LogWarning(
265 device, kVUID_BestPractices_SharingModeExclusive,
266 "Warning: Buffer (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
267 "(queueFamilyIndexCount of %" PRIu32 ").",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700268 buffer_hex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600269 }
270
271 return skip;
272}
273
274bool BestPractices::PreCallValidateCreateImage(VkDevice device, const VkImageCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500275 const VkAllocationCallbacks* pAllocator, VkImage* pImage) const {
Camden5b184be2019-08-13 07:50:19 -0600276 bool skip = false;
277
278 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700279 std::stringstream image_hex;
280 image_hex << "0x" << std::hex << HandleToUint64(pImage);
Camden5b184be2019-08-13 07:50:19 -0600281
282 skip |=
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700283 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
284 "Warning: Image (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
285 "(queueFamilyIndexCount of %" PRIu32 ").",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700286 image_hex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600287 }
288
Attilio Provenzano02859b22020-02-27 14:17:28 +0000289 if (VendorCheckEnabled(kBPVendorArm)) {
290 if (pCreateInfo->samples > kMaxEfficientSamplesArm) {
291 skip |= LogPerformanceWarning(
292 device, kVUID_BestPractices_CreateImage_TooLargeSampleCount,
293 "%s vkCreateImage(): Trying to create an image with %u samples. "
294 "The hardware revision may not have full throughput for framebuffers with more than %u samples.",
295 VendorSpecificTag(kBPVendorArm), static_cast<uint32_t>(pCreateInfo->samples), kMaxEfficientSamplesArm);
296 }
297
298 if (pCreateInfo->samples > VK_SAMPLE_COUNT_1_BIT && !(pCreateInfo->usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT)) {
299 skip |= LogPerformanceWarning(
300 device, kVUID_BestPractices_CreateImage_NonTransientMSImage,
301 "%s vkCreateImage(): Trying to create a multisampled image, but createInfo.usage did not have "
302 "VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. Multisampled images may be resolved on-chip, "
303 "and do not need to be backed by physical storage. "
304 "TRANSIENT_ATTACHMENT allows tiled GPUs to not back the multisampled image with physical memory.",
305 VendorSpecificTag(kBPVendorArm));
306 }
307 }
308
Camden5b184be2019-08-13 07:50:19 -0600309 return skip;
310}
311
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +0100312void BestPractices::PreCallRecordDestroyImage(VkDevice device, VkImage image, const VkAllocationCallbacks *pAllocator) {
313 ValidationStateTracker::PreCallRecordDestroyImage(device, image, pAllocator);
314 ReleaseImageUsageState(image);
315}
316
Hans-Kristian Arntzen92664eb2021-03-29 12:19:48 +0200317void BestPractices::PreCallRecordDestroySwapchainKHR(VkDevice device, VkSwapchainKHR swapchain, const VkAllocationCallbacks* pAllocator) {
Tony-LunarG299187b2021-05-28 09:29:12 -0600318 if (VK_NULL_HANDLE != swapchain) {
319 SWAPCHAIN_NODE* chain = GetSwapchainState(swapchain);
320 for (auto& image : chain->images) {
321 if (image.image_state) {
322 ReleaseImageUsageState(image.image_state->image());
323 }
324 }
Hans-Kristian Arntzen92664eb2021-03-29 12:19:48 +0200325 }
326 ValidationStateTracker::PreCallRecordDestroySwapchainKHR(device, swapchain, pAllocator);
327}
328
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +0100329IMAGE_STATE_BP* BestPractices::GetImageUsageState(VkImage vk_image) {
330 auto itr = imageUsageMap.find(vk_image);
331 if (itr != imageUsageMap.end()) {
332 return &itr->second;
333 } else {
334 auto& state = imageUsageMap[vk_image];
335 IMAGE_STATE* image = GetImageState(vk_image);
336 state.image = image;
337 state.usages.resize(image->createInfo.arrayLayers);
338 for (auto& mips : state.usages) {
339 mips.resize(image->createInfo.mipLevels, IMAGE_SUBRESOURCE_USAGE_BP::UNDEFINED);
340 }
341 return &state;
342 }
343}
344
345void BestPractices::ReleaseImageUsageState(VkImage image) {
346 auto itr = imageUsageMap.find(image);
347 if (itr != imageUsageMap.end()) {
348 imageUsageMap.erase(itr);
349 }
350}
351
Camden5b184be2019-08-13 07:50:19 -0600352bool BestPractices::PreCallValidateCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500353 const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain) const {
Camden5b184be2019-08-13 07:50:19 -0600354 bool skip = false;
355
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600356 const auto* bp_pd_state = GetPhysicalDeviceStateBP();
357 if (bp_pd_state) {
358 if (bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState == UNCALLED) {
359 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
360 "vkCreateSwapchainKHR() called before getting surface capabilities from "
361 "vkGetPhysicalDeviceSurfaceCapabilitiesKHR().");
362 }
Camden83a9c372019-08-14 11:41:38 -0600363
Shannon McPherson73e58c82021-03-05 17:14:26 -0700364 if ((pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR) &&
365 (bp_pd_state->vkGetPhysicalDeviceSurfacePresentModesKHRState != QUERY_DETAILS)) {
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600366 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
367 "vkCreateSwapchainKHR() called before getting surface present mode(s) from "
368 "vkGetPhysicalDeviceSurfacePresentModesKHR().");
369 }
Camden83a9c372019-08-14 11:41:38 -0600370
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600371 if (bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState != QUERY_DETAILS) {
372 skip |= LogWarning(
373 device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
374 "vkCreateSwapchainKHR() called before getting surface format(s) from vkGetPhysicalDeviceSurfaceFormatsKHR().");
375 }
Camden83a9c372019-08-14 11:41:38 -0600376 }
377
Camden5b184be2019-08-13 07:50:19 -0600378 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700379 skip |=
380 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
Mark Lobodzinski019f4e32020-04-13 11:01:35 -0600381 "Warning: A Swapchain is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while "
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700382 "specifying multiple queues (queueFamilyIndexCount of %" PRIu32 ").",
383 pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600384 }
385
Szilard Papp48a6da32020-06-10 14:41:59 +0100386 if (pCreateInfo->minImageCount == 2) {
387 skip |= LogPerformanceWarning(
388 device, kVUID_BestPractices_SuboptimalSwapchainImageCount,
389 "Warning: A Swapchain is being created with minImageCount set to %" PRIu32
390 ", which means double buffering is going "
391 "to be used. Using double buffering and vsync locks rendering to an integer fraction of the vsync rate. In turn, "
392 "reducing the performance of the application if rendering is slower than vsync. Consider setting minImageCount to "
393 "3 to use triple buffering to maximize performance in such cases.",
394 pCreateInfo->minImageCount);
395 }
396
Szilard Pappd5f0f812020-06-22 09:01:29 +0100397 if (VendorCheckEnabled(kBPVendorArm) && (pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR)) {
398 skip |= LogWarning(device, kVUID_BestPractices_CreateSwapchain_PresentMode,
399 "%s Warning: Swapchain is not being created with presentation mode \"VK_PRESENT_MODE_FIFO_KHR\". "
400 "Prefer using \"VK_PRESENT_MODE_FIFO_KHR\" to avoid unnecessary CPU and GPU load and save power. "
401 "Presentation modes which are not FIFO will present the latest available frame and discard other "
402 "frame(s) if any.",
403 VendorSpecificTag(kBPVendorArm));
404 }
405
Camden5b184be2019-08-13 07:50:19 -0600406 return skip;
407}
408
409bool BestPractices::PreCallValidateCreateSharedSwapchainsKHR(VkDevice device, uint32_t swapchainCount,
410 const VkSwapchainCreateInfoKHR* pCreateInfos,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500411 const VkAllocationCallbacks* pAllocator,
412 VkSwapchainKHR* pSwapchains) const {
Camden5b184be2019-08-13 07:50:19 -0600413 bool skip = false;
414
415 for (uint32_t i = 0; i < swapchainCount; i++) {
416 if ((pCreateInfos[i].queueFamilyIndexCount > 1) && (pCreateInfos[i].imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700417 skip |= LogWarning(
418 device, kVUID_BestPractices_SharingModeExclusive,
419 "Warning: A shared swapchain (index %" PRIu32
420 ") is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple "
421 "queues (queueFamilyIndexCount of %" PRIu32 ").",
422 i, pCreateInfos[i].queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600423 }
424 }
425
426 return skip;
427}
428
429bool BestPractices::PreCallValidateCreateRenderPass(VkDevice device, const VkRenderPassCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500430 const VkAllocationCallbacks* pAllocator, VkRenderPass* pRenderPass) const {
Camden5b184be2019-08-13 07:50:19 -0600431 bool skip = false;
432
433 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; ++i) {
434 VkFormat format = pCreateInfo->pAttachments[i].format;
435 if (pCreateInfo->pAttachments[i].initialLayout == VK_IMAGE_LAYOUT_UNDEFINED) {
436 if ((FormatIsColor(format) || FormatHasDepth(format)) &&
437 pCreateInfo->pAttachments[i].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700438 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
439 "Render pass has an attachment with loadOp == VK_ATTACHMENT_LOAD_OP_LOAD and "
440 "initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
441 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
442 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600443 }
444 if (FormatHasStencil(format) && pCreateInfo->pAttachments[i].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700445 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
446 "Render pass has an attachment with stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD "
447 "and initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
448 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
449 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600450 }
451 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000452
453 const auto& attachment = pCreateInfo->pAttachments[i];
454 if (attachment.samples > VK_SAMPLE_COUNT_1_BIT) {
455 bool access_requires_memory =
456 attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD || attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE;
457
458 if (FormatHasStencil(format)) {
459 access_requires_memory |= attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
460 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE;
461 }
462
463 if (access_requires_memory) {
464 skip |= LogPerformanceWarning(
465 device, kVUID_BestPractices_CreateRenderPass_ImageRequiresMemory,
466 "Attachment %u in the VkRenderPass is a multisampled image with %u samples, but it uses loadOp/storeOp "
467 "which requires accessing data from memory. Multisampled images should always be loadOp = CLEAR or DONT_CARE, "
468 "storeOp = DONT_CARE. This allows the implementation to use lazily allocated memory effectively.",
469 i, static_cast<uint32_t>(attachment.samples));
470 }
471 }
Camden5b184be2019-08-13 07:50:19 -0600472 }
473
474 for (uint32_t dependency = 0; dependency < pCreateInfo->dependencyCount; dependency++) {
475 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].srcStageMask);
476 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].dstStageMask);
477 }
478
479 return skip;
480}
481
Tony-LunarG767180f2020-04-23 14:03:59 -0600482bool BestPractices::ValidateAttachments(const VkRenderPassCreateInfo2* rpci, uint32_t attachmentCount,
483 const VkImageView* image_views) const {
484 bool skip = false;
485
486 // Check for non-transient attachments that should be transient and vice versa
487 for (uint32_t i = 0; i < attachmentCount; ++i) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200488 const auto& attachment = rpci->pAttachments[i];
Tony-LunarG767180f2020-04-23 14:03:59 -0600489 bool attachment_should_be_transient =
490 (attachment.loadOp != VK_ATTACHMENT_LOAD_OP_LOAD && attachment.storeOp != VK_ATTACHMENT_STORE_OP_STORE);
491
492 if (FormatHasStencil(attachment.format)) {
493 attachment_should_be_transient &= (attachment.stencilLoadOp != VK_ATTACHMENT_LOAD_OP_LOAD &&
494 attachment.stencilStoreOp != VK_ATTACHMENT_STORE_OP_STORE);
495 }
496
497 auto view_state = GetImageViewState(image_views[i]);
498 if (view_state) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200499 const auto& ivci = view_state->create_info;
500 const auto& ici = GetImageState(ivci.image)->createInfo;
Tony-LunarG767180f2020-04-23 14:03:59 -0600501
502 bool image_is_transient = (ici.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) != 0;
503
504 // The check for an image that should not be transient applies to all GPUs
505 if (!attachment_should_be_transient && image_is_transient) {
506 skip |= LogPerformanceWarning(
507 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldNotBeTransient,
508 "Attachment %u in VkFramebuffer uses loadOp/storeOps which need to access physical memory, "
509 "but the image backing the image view has VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
510 "Physical memory will need to be backed lazily to this image, potentially causing stalls.",
511 i);
512 }
513
514 bool supports_lazy = false;
515 for (uint32_t j = 0; j < phys_dev_mem_props.memoryTypeCount; j++) {
516 if (phys_dev_mem_props.memoryTypes[j].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
517 supports_lazy = true;
518 }
519 }
520
521 // The check for an image that should be transient only applies to GPUs supporting
522 // lazily allocated memory
523 if (supports_lazy && attachment_should_be_transient && !image_is_transient) {
524 skip |= LogPerformanceWarning(
525 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldBeTransient,
526 "Attachment %u in VkFramebuffer uses loadOp/storeOps which never have to be backed by physical memory, "
527 "but the image backing the image view does not have VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
528 "You can save physical memory by using transient attachment backed by lazily allocated memory here.",
529 i);
530 }
531 }
532 }
533 return skip;
534}
535
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000536bool BestPractices::PreCallValidateCreateFramebuffer(VkDevice device, const VkFramebufferCreateInfo* pCreateInfo,
537 const VkAllocationCallbacks* pAllocator, VkFramebuffer* pFramebuffer) const {
538 bool skip = false;
539
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000540 auto rp_state = GetRenderPassState(pCreateInfo->renderPass);
Mike Schuchardt2df08912020-12-15 16:28:09 -0800541 if (rp_state && !(pCreateInfo->flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT)) {
Tony-LunarG767180f2020-04-23 14:03:59 -0600542 skip = ValidateAttachments(rp_state->createInfo.ptr(), pCreateInfo->attachmentCount, pCreateInfo->pAttachments);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000543 }
544
545 return skip;
546}
547
Sam Wallse746d522020-03-16 21:20:23 +0000548bool BestPractices::PreCallValidateAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
549 VkDescriptorSet* pDescriptorSets, void* ads_state_data) const {
550 bool skip = false;
551 skip |= ValidationStateTracker::PreCallValidateAllocateDescriptorSets(device, pAllocateInfo, pDescriptorSets, ads_state_data);
552
553 if (!skip) {
554 const auto& pool_handle = pAllocateInfo->descriptorPool;
555 auto iter = descriptor_pool_freed_count.find(pool_handle);
556 // if the number of freed sets > 0, it implies they could be recycled instead if desirable
557 // this warning is specific to Arm
558 if (VendorCheckEnabled(kBPVendorArm) && iter != descriptor_pool_freed_count.end() && iter->second > 0) {
559 skip |= LogPerformanceWarning(
560 device, kVUID_BestPractices_AllocateDescriptorSets_SuboptimalReuse,
561 "%s Descriptor set memory was allocated via vkAllocateDescriptorSets() for sets which were previously freed in the "
562 "same logical device. On some drivers or architectures it may be most optimal to re-use existing descriptor sets.",
563 VendorSpecificTag(kBPVendorArm));
564 }
565 }
566
567 return skip;
568}
569
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600570void BestPractices::ManualPostCallRecordAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
571 VkDescriptorSet* pDescriptorSets, VkResult result, void* ads_state) {
Sam Wallse746d522020-03-16 21:20:23 +0000572 if (result == VK_SUCCESS) {
573 // find the free count for the pool we allocated into
574 auto iter = descriptor_pool_freed_count.find(pAllocateInfo->descriptorPool);
575 if (iter != descriptor_pool_freed_count.end()) {
576 // we record successful allocations by subtracting the allocation count from the last recorded free count
577 const auto alloc_count = pAllocateInfo->descriptorSetCount;
578 // clamp the unsigned subtraction to the range [0, last_free_count]
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700579 if (iter->second > alloc_count) {
Sam Wallse746d522020-03-16 21:20:23 +0000580 iter->second -= alloc_count;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700581 } else {
Sam Wallse746d522020-03-16 21:20:23 +0000582 iter->second = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700583 }
Sam Wallse746d522020-03-16 21:20:23 +0000584 }
585 }
586}
587
588void BestPractices::PostCallRecordFreeDescriptorSets(VkDevice device, VkDescriptorPool descriptorPool, uint32_t descriptorSetCount,
589 const VkDescriptorSet* pDescriptorSets, VkResult result) {
590 ValidationStateTracker::PostCallRecordFreeDescriptorSets(device, descriptorPool, descriptorSetCount, pDescriptorSets, result);
591 if (result == VK_SUCCESS) {
592 // we want to track frees because we're interested in suggesting re-use
593 auto iter = descriptor_pool_freed_count.find(descriptorPool);
594 if (iter == descriptor_pool_freed_count.end()) {
Jeremy Gebbencbf22862021-03-03 12:01:22 -0700595 descriptor_pool_freed_count.emplace(descriptorPool, descriptorSetCount);
Sam Wallse746d522020-03-16 21:20:23 +0000596 } else {
597 iter->second += descriptorSetCount;
598 }
599 }
600}
601
Camden5b184be2019-08-13 07:50:19 -0600602bool BestPractices::PreCallValidateAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500603 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory) const {
Camden5b184be2019-08-13 07:50:19 -0600604 bool skip = false;
605
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500606 if (num_mem_objects + 1 > kMemoryObjectWarningLimit) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700607 skip |= LogPerformanceWarning(device, kVUID_BestPractices_AllocateMemory_TooManyObjects,
608 "Performance Warning: This app has > %" PRIu32 " memory objects.", kMemoryObjectWarningLimit);
Camden5b184be2019-08-13 07:50:19 -0600609 }
610
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000611 if (pAllocateInfo->allocationSize < kMinDeviceAllocationSize) {
612 skip |= LogPerformanceWarning(
613 device, kVUID_BestPractices_AllocateMemory_SmallAllocation,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600614 "vkAllocateMemory(): Allocating a VkDeviceMemory of size %" PRIu64 ". This is a very small allocation (current "
615 "threshold is %" PRIu64 " bytes). "
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000616 "You should make large allocations and sub-allocate from one large VkDeviceMemory.",
617 pAllocateInfo->allocationSize, kMinDeviceAllocationSize);
618 }
619
Camden83a9c372019-08-14 11:41:38 -0600620 // TODO: Insert get check for GetPhysicalDeviceMemoryProperties once the state is tracked in the StateTracker
621
622 return skip;
623}
624
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600625void BestPractices::ManualPostCallRecordAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
626 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory,
627 VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700628 if (result != VK_SUCCESS) {
629 static std::vector<VkResult> error_codes = {VK_ERROR_OUT_OF_HOST_MEMORY, VK_ERROR_OUT_OF_DEVICE_MEMORY,
630 VK_ERROR_TOO_MANY_OBJECTS, VK_ERROR_INVALID_EXTERNAL_HANDLE,
Mike Schuchardt2df08912020-12-15 16:28:09 -0800631 VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS};
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700632 static std::vector<VkResult> success_codes = {};
Nathaniel Cesariodb3f43f2021-05-12 09:08:23 -0600633 ValidateReturnCodes("vkAllocateMemory", result, error_codes, success_codes);
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700634 return;
635 }
636 num_mem_objects++;
637}
Camden Stocker9738af92019-10-16 13:54:03 -0700638
Mark Lobodzinskide15e582020-04-29 08:06:00 -0600639void BestPractices::ValidateReturnCodes(const char* api_name, VkResult result, const std::vector<VkResult>& error_codes,
640 const std::vector<VkResult>& success_codes) const {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700641 auto error = std::find(error_codes.begin(), error_codes.end(), result);
642 if (error != error_codes.end()) {
Gareth Webb586c46b2021-01-13 11:17:22 +0000643 static const std::vector<VkResult> common_failure_codes = {VK_ERROR_OUT_OF_DATE_KHR,
644 VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT};
645
646 auto common_failure = std::find(common_failure_codes.begin(), common_failure_codes.end(), result);
647 if (common_failure != common_failure_codes.end()) {
648 LogInfo(instance, kVUID_BestPractices_Failure_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
649 } else {
650 LogWarning(instance, kVUID_BestPractices_Error_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
651 }
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700652 return;
653 }
654 auto success = std::find(success_codes.begin(), success_codes.end(), result);
655 if (success != success_codes.end()) {
Mark Lobodzinskie7215152020-05-11 08:21:23 -0600656 LogInfo(instance, kVUID_BestPractices_NonSuccess_Result, "%s(): Returned non-success return code %s.", api_name,
657 string_VkResult(result));
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500658 }
659}
660
Jeff Bolz5c801d12019-10-09 10:38:45 -0500661bool BestPractices::PreCallValidateFreeMemory(VkDevice device, VkDeviceMemory memory,
662 const VkAllocationCallbacks* pAllocator) const {
Mark Lobodzinski91e50bf2020-01-14 09:55:11 -0700663 if (memory == VK_NULL_HANDLE) return false;
Camden83a9c372019-08-14 11:41:38 -0600664 bool skip = false;
665
Camden Stocker9738af92019-10-16 13:54:03 -0700666 const DEVICE_MEMORY_STATE* mem_info = ValidationStateTracker::GetDevMemState(memory);
Camden83a9c372019-08-14 11:41:38 -0600667
Jeremy Gebben5570abe2021-05-16 18:35:13 -0600668 for (const auto& node: mem_info->ObjectBindings()) {
669 const auto& obj = node->Handle();
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600670 LogObjectList objlist(device);
671 objlist.add(obj);
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -0600672 objlist.add(mem_info->mem());
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600673 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 -0600674 report_data->FormatHandle(obj).c_str(), report_data->FormatHandle(mem_info->mem()).c_str());
Camden83a9c372019-08-14 11:41:38 -0600675 }
676
Camden5b184be2019-08-13 07:50:19 -0600677 return skip;
678}
679
680void BestPractices::PreCallRecordFreeMemory(VkDevice device, VkDeviceMemory memory, const VkAllocationCallbacks* pAllocator) {
Mark Lobodzinski97484d62020-03-03 11:57:41 -0700681 ValidationStateTracker::PreCallRecordFreeMemory(device, memory, pAllocator);
Camden5b184be2019-08-13 07:50:19 -0600682 if (memory != VK_NULL_HANDLE) {
683 num_mem_objects--;
684 }
685}
686
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000687bool BestPractices::ValidateBindBufferMemory(VkBuffer buffer, VkDeviceMemory memory, const char* api_name) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600688 bool skip = false;
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500689 const BUFFER_STATE* buffer_state = GetBufferState(buffer);
Camden Stockerb603cc82019-09-03 10:09:02 -0600690
sfricke-samsunge2441192019-11-06 14:07:57 -0800691 if (!buffer_state->memory_requirements_checked && !buffer_state->external_memory_handle) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700692 skip |= LogWarning(device, kVUID_BestPractices_BufferMemReqNotCalled,
693 "%s: Binding memory to %s but vkGetBufferMemoryRequirements() has not been called on that buffer.",
694 api_name, report_data->FormatHandle(buffer).c_str());
Camden Stockerb603cc82019-09-03 10:09:02 -0600695 }
696
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000697 const DEVICE_MEMORY_STATE* mem_state = GetDevMemState(memory);
698
699 if (mem_state->alloc_info.allocationSize == buffer_state->createInfo.size &&
700 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
701 skip |= LogPerformanceWarning(
702 device, kVUID_BestPractices_SmallDedicatedAllocation,
703 "%s: Trying to bind %s to a memory block which is fully consumed by the buffer. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600704 "The required size of the allocation is %" PRIu64 ", but smaller buffers like this should be sub-allocated from "
705 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000706 api_name, report_data->FormatHandle(buffer).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
707 }
708
Camden Stockerb603cc82019-09-03 10:09:02 -0600709 return skip;
710}
711
712bool BestPractices::PreCallValidateBindBufferMemory(VkDevice device, VkBuffer buffer, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500713 VkDeviceSize memoryOffset) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600714 bool skip = false;
715 const char* api_name = "BindBufferMemory()";
716
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000717 skip |= ValidateBindBufferMemory(buffer, memory, api_name);
Camden Stockerb603cc82019-09-03 10:09:02 -0600718
719 return skip;
720}
721
722bool BestPractices::PreCallValidateBindBufferMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500723 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600724 char api_name[64];
725 bool skip = false;
726
727 for (uint32_t i = 0; i < bindInfoCount; i++) {
728 sprintf(api_name, "vkBindBufferMemory2() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000729 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600730 }
731
732 return skip;
733}
Camden Stockerb603cc82019-09-03 10:09:02 -0600734
735bool BestPractices::PreCallValidateBindBufferMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500736 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600737 char api_name[64];
738 bool skip = false;
Camden Stockerb603cc82019-09-03 10:09:02 -0600739
Camden Stocker8b798ab2019-09-03 10:33:28 -0600740 for (uint32_t i = 0; i < bindInfoCount; i++) {
741 sprintf(api_name, "vkBindBufferMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000742 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600743 }
744
745 return skip;
746}
747
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000748bool BestPractices::ValidateBindImageMemory(VkImage image, VkDeviceMemory memory, const char* api_name) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600749 bool skip = false;
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500750 const IMAGE_STATE* image_state = GetImageState(image);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600751
sfricke-samsung71bc6572020-04-29 15:49:43 -0700752 if (image_state->disjoint == false) {
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600753 if (!image_state->memory_requirements_checked[0] && !image_state->external_memory_handle) {
sfricke-samsungd7ea5de2020-04-08 09:19:18 -0700754 skip |= LogWarning(device, kVUID_BestPractices_ImageMemReqNotCalled,
755 "%s: Binding memory to %s but vkGetImageMemoryRequirements() has not been called on that image.",
756 api_name, report_data->FormatHandle(image).c_str());
757 }
758 } else {
759 // TODO If binding disjoint image then this needs to check that VkImagePlaneMemoryRequirementsInfo was called for each
760 // plane.
Camden Stocker8b798ab2019-09-03 10:33:28 -0600761 }
762
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000763 const DEVICE_MEMORY_STATE* mem_state = GetDevMemState(memory);
764
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600765 if (mem_state->alloc_info.allocationSize == image_state->requirements[0].size &&
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000766 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
767 skip |= LogPerformanceWarning(
768 device, kVUID_BestPractices_SmallDedicatedAllocation,
769 "%s: Trying to bind %s to a memory block which is fully consumed by the image. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600770 "The required size of the allocation is %" PRIu64 ", but smaller images like this should be sub-allocated from "
771 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000772 api_name, report_data->FormatHandle(image).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
773 }
774
775 // If we're binding memory to a image which was created as TRANSIENT and the image supports LAZY allocation,
776 // make sure this type is actually used.
777 // This warning will only trigger if this layer is run on a platform that supports LAZILY_ALLOCATED_BIT
778 // (i.e.most tile - based renderers)
779 if (image_state->createInfo.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) {
780 bool supports_lazy = false;
781 uint32_t suggested_type = 0;
782
783 for (uint32_t i = 0; i < phys_dev_mem_props.memoryTypeCount; i++) {
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600784 if ((1u << i) & image_state->requirements[0].memoryTypeBits) {
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000785 if (phys_dev_mem_props.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
786 supports_lazy = true;
787 suggested_type = i;
788 break;
789 }
790 }
791 }
792
793 uint32_t allocated_properties = phys_dev_mem_props.memoryTypes[mem_state->alloc_info.memoryTypeIndex].propertyFlags;
794
795 if (supports_lazy && (allocated_properties & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) == 0) {
796 skip |= LogPerformanceWarning(
797 device, kVUID_BestPractices_NonLazyTransientImage,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600798 "%s: Attempting to bind memory type %u to VkImage which was created with TRANSIENT_ATTACHMENT_BIT,"
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000799 "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 -0600800 "%" PRIu64 " bytes of physical memory.",
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600801 api_name, mem_state->alloc_info.memoryTypeIndex, suggested_type, image_state->requirements[0].size);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000802 }
803 }
804
Camden Stocker8b798ab2019-09-03 10:33:28 -0600805 return skip;
806}
807
808bool BestPractices::PreCallValidateBindImageMemory(VkDevice device, VkImage image, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500809 VkDeviceSize memoryOffset) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600810 bool skip = false;
811 const char* api_name = "vkBindImageMemory()";
812
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000813 skip |= ValidateBindImageMemory(image, memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600814
815 return skip;
816}
817
818bool BestPractices::PreCallValidateBindImageMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500819 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600820 char api_name[64];
821 bool skip = false;
822
823 for (uint32_t i = 0; i < bindInfoCount; i++) {
824 sprintf(api_name, "vkBindImageMemory2() pBindInfos[%u]", i);
Mark Lobodzinski1f887d32020-12-30 15:31:33 -0700825 if (!LvlFindInChain<VkBindImageMemorySwapchainInfoKHR>(pBindInfos[i].pNext)) {
Tony-LunarG5e60b852020-04-27 11:27:54 -0600826 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
827 }
Camden Stocker8b798ab2019-09-03 10:33:28 -0600828 }
829
830 return skip;
831}
832
833bool BestPractices::PreCallValidateBindImageMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500834 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600835 char api_name[64];
836 bool skip = false;
837
838 for (uint32_t i = 0; i < bindInfoCount; i++) {
839 sprintf(api_name, "vkBindImageMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000840 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600841 }
842
843 return skip;
844}
Camden83a9c372019-08-14 11:41:38 -0600845
Attilio Provenzano02859b22020-02-27 14:17:28 +0000846static inline bool FormatHasFullThroughputBlendingArm(VkFormat format) {
847 switch (format) {
848 case VK_FORMAT_B10G11R11_UFLOAT_PACK32:
849 case VK_FORMAT_R16_SFLOAT:
850 case VK_FORMAT_R16G16_SFLOAT:
851 case VK_FORMAT_R16G16B16_SFLOAT:
852 case VK_FORMAT_R16G16B16A16_SFLOAT:
853 case VK_FORMAT_R32_SFLOAT:
854 case VK_FORMAT_R32G32_SFLOAT:
855 case VK_FORMAT_R32G32B32_SFLOAT:
856 case VK_FORMAT_R32G32B32A32_SFLOAT:
857 return false;
858
859 default:
860 return true;
861 }
862}
863
864bool BestPractices::ValidateMultisampledBlendingArm(uint32_t createInfoCount,
865 const VkGraphicsPipelineCreateInfo* pCreateInfos) const {
866 bool skip = false;
867
868 for (uint32_t i = 0; i < createInfoCount; i++) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700869 auto create_info = &pCreateInfos[i];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000870
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700871 if (!create_info->pColorBlendState || !create_info->pMultisampleState ||
872 create_info->pMultisampleState->rasterizationSamples == VK_SAMPLE_COUNT_1_BIT ||
873 create_info->pMultisampleState->sampleShadingEnable) {
Attilio Provenzano02859b22020-02-27 14:17:28 +0000874 return skip;
875 }
876
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700877 auto rp_state = GetRenderPassState(create_info->renderPass);
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200878 const auto& subpass = rp_state->createInfo.pSubpasses[create_info->subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000879
Hans-Kristian Arntzenc2742e72021-07-01 14:31:06 +0200880 // According to spec, pColorBlendState must be ignored if subpass does not have color attachments.
881 uint32_t num_color_attachments = std::min(subpass.colorAttachmentCount, create_info->pColorBlendState->attachmentCount);
882
883 for (uint32_t j = 0; j < num_color_attachments; j++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200884 const auto& blend_att = create_info->pColorBlendState->pAttachments[j];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000885 uint32_t att = subpass.pColorAttachments[j].attachment;
886
887 if (att != VK_ATTACHMENT_UNUSED && blend_att.blendEnable && blend_att.colorWriteMask) {
888 if (!FormatHasFullThroughputBlendingArm(rp_state->createInfo.pAttachments[att].format)) {
889 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultisampledBlending,
890 "%s vkCreateGraphicsPipelines() - createInfo #%u: Pipeline is multisampled and "
891 "color attachment #%u makes use "
892 "of a format which cannot be blended at full throughput when using MSAA.",
893 VendorSpecificTag(kBPVendorArm), i, j);
894 }
895 }
896 }
897 }
898
899 return skip;
900}
901
Camden5b184be2019-08-13 07:50:19 -0600902bool BestPractices::PreCallValidateCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
903 const VkGraphicsPipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -0600904 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500905 void* cgpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -0600906 bool skip = StateTracker::PreCallValidateCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos,
907 pAllocator, pPipelines, cgpl_state_data);
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600908 create_graphics_pipeline_api_state* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
Camden5b184be2019-08-13 07:50:19 -0600909
910 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700911 skip |= LogPerformanceWarning(
912 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
913 "Performance Warning: This vkCreateGraphicsPipelines call is creating multiple pipelines but is not using a "
914 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -0600915 }
916
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000917 for (uint32_t i = 0; i < createInfoCount; i++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200918 const auto& create_info = pCreateInfos[i];
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000919
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600920 if (!(cgpl_state->pipe_state[i]->active_shaders & VK_SHADER_STAGE_MESH_BIT_NV)) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200921 const auto& vertex_input = *create_info.pVertexInputState;
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600922 uint32_t count = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700923 for (uint32_t j = 0; j < vertex_input.vertexBindingDescriptionCount; j++) {
924 if (vertex_input.pVertexBindingDescriptions[j].inputRate == VK_VERTEX_INPUT_RATE_INSTANCE) {
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600925 count++;
926 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000927 }
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600928 if (count > kMaxInstancedVertexBuffers) {
929 skip |= LogPerformanceWarning(
930 device, kVUID_BestPractices_CreatePipelines_TooManyInstancedVertexBuffers,
931 "The pipeline is using %u instanced vertex buffers (current limit: %u), but this can be inefficient on the "
932 "GPU. If using instanced vertex attributes prefer interleaving them in a single buffer.",
933 count, kMaxInstancedVertexBuffers);
934 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000935 }
Attilio Provenzano02859b22020-02-27 14:17:28 +0000936
Szilard Pappaaf2da32020-06-22 10:37:35 +0100937 if ((pCreateInfos[i].pRasterizationState->depthBiasEnable) &&
938 (pCreateInfos[i].pRasterizationState->depthBiasConstantFactor == 0.0f) &&
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +0200939 (pCreateInfos[i].pRasterizationState->depthBiasSlopeFactor == 0.0f) &&
940 VendorCheckEnabled(kBPVendorArm)) {
941 skip |= LogPerformanceWarning(
942 device, kVUID_BestPractices_CreatePipelines_DepthBias_Zero,
943 "%s Performance Warning: This vkCreateGraphicsPipelines call is created with depthBiasEnable set to true "
944 "and both depthBiasConstantFactor and depthBiasSlopeFactor are set to 0. This can cause reduced "
945 "efficiency during rasterization. Consider disabling depthBias or increasing either "
946 "depthBiasConstantFactor or depthBiasSlopeFactor.",
947 VendorSpecificTag(kBPVendorArm));
Szilard Pappaaf2da32020-06-22 10:37:35 +0100948 }
949
Attilio Provenzano02859b22020-02-27 14:17:28 +0000950 skip |= VendorCheckEnabled(kBPVendorArm) && ValidateMultisampledBlendingArm(createInfoCount, pCreateInfos);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000951 }
952
Camden5b184be2019-08-13 07:50:19 -0600953 return skip;
954}
955
Hans-Kristian Arntzenb033ab12021-06-16 11:16:59 +0200956void BestPractices::PreCallRecordDestroyPipeline(VkDevice device, VkPipeline pipeline, const VkAllocationCallbacks *pAllocator)
957{
958 auto itr = graphicsPipelineCIs.find(pipeline);
959 if (itr != graphicsPipelineCIs.end()) {
960 graphicsPipelineCIs.erase(itr);
961 }
962 ValidationStateTracker::PreCallRecordDestroyPipeline(device, pipeline, pAllocator);
963}
964
Sam Walls0961ec02020-03-31 16:39:15 +0100965void BestPractices::ManualPostCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t count,
966 const VkGraphicsPipelineCreateInfo* pCreateInfos,
967 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
968 VkResult result, void* cgpl_state_data) {
969 for (size_t i = 0; i < count; i++) {
970 const auto* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
971 const VkPipeline pipeline_handle = pPipelines[i];
972
973 // record depth stencil state and color blend states for depth pre-pass tracking purposes
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +0200974 GraphicsPipelineCIs& cis = graphicsPipelineCIs[pipeline_handle];
Sam Walls0961ec02020-03-31 16:39:15 +0100975
Hans-Kristian Arntzen42c0ef52021-06-14 14:46:25 +0200976 auto& create_info = cgpl_state->pCreateInfos[i];
Hans-Kristian Arntzen42c0ef52021-06-14 14:46:25 +0200977
978 cis.colorBlendStateCI =
979 create_info.pColorBlendState
980 ? new safe_VkPipelineColorBlendStateCreateInfo(create_info.pColorBlendState)
Tony-LunarG412b1b72020-07-15 10:30:13 -0600981 : nullptr;
Hans-Kristian Arntzen42c0ef52021-06-14 14:46:25 +0200982 cis.depthStencilStateCI =
Tony-LunarG412b1b72020-07-15 10:30:13 -0600983 cgpl_state->pCreateInfos[i].pDepthStencilState
Hans-Kristian Arntzen42c0ef52021-06-14 14:46:25 +0200984 ? new safe_VkPipelineDepthStencilStateCreateInfo(create_info.pDepthStencilState)
Tony-LunarG412b1b72020-07-15 10:30:13 -0600985 : nullptr;
Hans-Kristian Arntzen42c0ef52021-06-14 14:46:25 +0200986
987 // Record which frame buffer attachments we should consider to be accessed when a draw call is performed.
988 RENDER_PASS_STATE* rp = GetRenderPassState(create_info.renderPass);
989 auto& subpass = rp->createInfo.pSubpasses[create_info.subpass];
990 cis.accessFramebufferAttachments.clear();
991
992 if (cis.colorBlendStateCI) {
Hans-Kristian Arntzenc2742e72021-07-01 14:31:06 +0200993 // According to spec, pColorBlendState must be ignored if subpass does not have color attachments.
994 uint32_t num_color_attachments = std::min(subpass.colorAttachmentCount, cis.colorBlendStateCI->attachmentCount);
995 for (uint32_t j = 0; j < num_color_attachments; j++) {
Hans-Kristian Arntzen42c0ef52021-06-14 14:46:25 +0200996 if (cis.colorBlendStateCI->pAttachments[j].colorWriteMask != 0) {
997 uint32_t attachment = subpass.pColorAttachments[j].attachment;
998 if (attachment != VK_ATTACHMENT_UNUSED) {
999 cis.accessFramebufferAttachments.push_back({ attachment, VK_IMAGE_ASPECT_COLOR_BIT });
1000 }
1001 }
1002 }
1003 }
1004
1005 if (cis.depthStencilStateCI && (cis.depthStencilStateCI->depthTestEnable ||
1006 cis.depthStencilStateCI->depthBoundsTestEnable ||
1007 cis.depthStencilStateCI->stencilTestEnable)) {
1008 uint32_t attachment = subpass.pDepthStencilAttachment ?
1009 subpass.pDepthStencilAttachment->attachment :
1010 VK_ATTACHMENT_UNUSED;
1011 if (attachment != VK_ATTACHMENT_UNUSED) {
1012 VkImageAspectFlags aspects = 0;
1013 if (cis.depthStencilStateCI->depthTestEnable || cis.depthStencilStateCI->depthBoundsTestEnable) {
1014 aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
1015 }
1016 if (cis.depthStencilStateCI->stencilTestEnable) {
1017 aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
1018 }
1019 cis.accessFramebufferAttachments.push_back({ attachment, aspects });
1020 }
1021 }
Sam Walls0961ec02020-03-31 16:39:15 +01001022 }
1023}
1024
Camden5b184be2019-08-13 07:50:19 -06001025bool BestPractices::PreCallValidateCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
1026 const VkComputePipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -06001027 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001028 void* ccpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -06001029 bool skip = StateTracker::PreCallValidateCreateComputePipelines(device, pipelineCache, createInfoCount, pCreateInfos,
1030 pAllocator, pPipelines, ccpl_state_data);
Camden5b184be2019-08-13 07:50:19 -06001031
1032 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001033 skip |= LogPerformanceWarning(
1034 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
1035 "Performance Warning: This vkCreateComputePipelines call is creating multiple pipelines but is not using a "
1036 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -06001037 }
1038
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001039 if (VendorCheckEnabled(kBPVendorArm)) {
1040 for (size_t i = 0; i < createInfoCount; i++) {
1041 skip |= ValidateCreateComputePipelineArm(pCreateInfos[i]);
1042 }
1043 }
1044
1045 return skip;
1046}
1047
1048bool BestPractices::ValidateCreateComputePipelineArm(const VkComputePipelineCreateInfo& createInfo) const {
1049 bool skip = false;
1050 auto* module = GetShaderModuleState(createInfo.stage.module);
sfricke-samsung8a7341a2021-02-28 07:30:21 -08001051 // Generate warnings about work group sizes based on active resources.
sfricke-samsung962cad92021-04-13 00:46:29 -07001052 auto entrypoint = module->FindEntrypoint(createInfo.stage.pName, createInfo.stage.stage);
sfricke-samsung8a7341a2021-02-28 07:30:21 -08001053 if (entrypoint == module->end()) return false;
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001054
1055 uint32_t x = 1, y = 1, z = 1;
sfricke-samsung962cad92021-04-13 00:46:29 -07001056 module->FindLocalSize(entrypoint, x, y, z);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001057
1058 uint32_t thread_count = x * y * z;
1059
1060 // Generate a priori warnings about work group sizes.
1061 if (thread_count > kMaxEfficientWorkGroupThreadCountArm) {
1062 skip |= LogPerformanceWarning(
1063 device, kVUID_BestPractices_CreateComputePipelines_ComputeWorkGroupSize,
1064 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, %u, "
1065 "%u) (%u threads total), has more threads than advised in a single work group. It is advised to use work "
1066 "groups with less than %u threads, especially when using barrier() or shared memory.",
1067 VendorSpecificTag(kBPVendorArm), x, y, z, thread_count, kMaxEfficientWorkGroupThreadCountArm);
1068 }
1069
1070 if (thread_count == 1 || ((x > 1) && (x & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
1071 ((y > 1) && (y & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
1072 ((z > 1) && (z & (kThreadGroupDispatchCountAlignmentArm - 1)))) {
1073 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeThreadGroupAlignment,
1074 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, "
1075 "%u, %u) is not aligned to %u "
1076 "threads. On Arm Mali architectures, not aligning work group sizes to %u may "
1077 "leave threads idle on the shader "
1078 "core.",
1079 VendorSpecificTag(kBPVendorArm), x, y, z, kThreadGroupDispatchCountAlignmentArm,
1080 kThreadGroupDispatchCountAlignmentArm);
1081 }
1082
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001083 bool has_writeable_descriptors = false;
locke-lunarg63e4daf2020-08-17 17:53:25 -06001084 bool has_atomic_descriptors = false;
sfricke-samsung962cad92021-04-13 00:46:29 -07001085 auto accessible_ids = module->MarkAccessibleIds(entrypoint);
locke-lunarg63e4daf2020-08-17 17:53:25 -06001086 auto descriptor_uses =
sfricke-samsung962cad92021-04-13 00:46:29 -07001087 module->CollectInterfaceByDescriptorSlot(accessible_ids, &has_writeable_descriptors, &has_atomic_descriptors);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001088
1089 unsigned dimensions = 0;
1090 if (x > 1) dimensions++;
1091 if (y > 1) dimensions++;
1092 if (z > 1) dimensions++;
1093 // Here the dimension will really depend on the dispatch grid, but assume it's 1D.
1094 dimensions = std::max(dimensions, 1u);
1095
1096 // If we're accessing images, we almost certainly want to have a 2D workgroup for cache reasons.
1097 // There are some false positives here. We could simply have a shader that does this within a 1D grid,
1098 // or we may have a linearly tiled image, but these cases are quite unlikely in practice.
1099 bool accesses_2d = false;
1100 for (const auto& usage : descriptor_uses) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001101 auto dim = module->GetShaderResourceDimensionality(usage.second);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001102 if (dim < 0) continue;
1103 auto spvdim = spv::Dim(dim);
1104 if (spvdim != spv::Dim1D && spvdim != spv::DimBuffer) accesses_2d = true;
1105 }
1106
1107 if (accesses_2d && dimensions < 2) {
1108 LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeSpatialLocality,
1109 "%s vkCreateComputePipelines(): compute shader has work group dimensions (%u, %u, %u), which "
1110 "suggests a 1D dispatch, but the shader is accessing 2D or 3D images. The shader may be "
1111 "exhibiting poor spatial locality with respect to one or more shader resources.",
1112 VendorSpecificTag(kBPVendorArm), x, y, z);
1113 }
1114
Camden5b184be2019-08-13 07:50:19 -06001115 return skip;
1116}
1117
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001118bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags flags) const {
Camden5b184be2019-08-13 07:50:19 -06001119 bool skip = false;
1120
1121 if (flags & VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001122 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1123 "You are using VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001124 } else if (flags & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001125 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1126 "You are using VK_PIPELINE_STAGE_ALL_COMMANDS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001127 }
1128
1129 return skip;
1130}
1131
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001132bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags2KHR flags) const {
1133 bool skip = false;
1134
1135 if (flags & VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR) {
1136 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1137 "You are using VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR when %s is called\n", api_name.c_str());
1138 } else if (flags & VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR) {
1139 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1140 "You are using VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR when %s is called\n", api_name.c_str());
1141 }
1142
1143 return skip;
1144}
1145
1146bool BestPractices::CheckDependencyInfo(const std::string& api_name, const VkDependencyInfoKHR& dep_info) const {
1147 bool skip = false;
1148 auto stage_masks = sync_utils::GetGlobalStageMasks(dep_info);
1149
1150 skip |= CheckPipelineStageFlags(api_name, stage_masks.src);
1151 skip |= CheckPipelineStageFlags(api_name, stage_masks.dst);
1152
1153 return skip;
1154}
1155
Mark Lobodzinski84101d72020-04-24 09:43:48 -06001156void BestPractices::ManualPostCallRecordQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo, VkResult result) {
Mark Lobodzinski9b133c12020-03-10 10:42:56 -06001157 for (uint32_t i = 0; i < pPresentInfo->swapchainCount; ++i) {
1158 auto swapchains_result = pPresentInfo->pResults ? pPresentInfo->pResults[i] : result;
1159 if (swapchains_result == VK_SUBOPTIMAL_KHR) {
1160 LogPerformanceWarning(
1161 pPresentInfo->pSwapchains[i], kVUID_BestPractices_SuboptimalSwapchain,
1162 "vkQueuePresentKHR: %s :VK_SUBOPTIMAL_KHR was returned. VK_SUBOPTIMAL_KHR - Presentation will still succeed, "
1163 "subject to the window resize behavior, but the swapchain is no longer configured optimally for the surface it "
1164 "targets. Applications should query updated surface information and recreate their swapchain at the next "
1165 "convenient opportunity.",
1166 report_data->FormatHandle(pPresentInfo->pSwapchains[i]).c_str());
1167 }
1168 }
1169}
1170
Jeff Bolz5c801d12019-10-09 10:38:45 -05001171bool BestPractices::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
1172 VkFence fence) const {
Camden5b184be2019-08-13 07:50:19 -06001173 bool skip = false;
1174
1175 for (uint32_t submit = 0; submit < submitCount; submit++) {
1176 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreCount; semaphore++) {
1177 skip |= CheckPipelineStageFlags("vkQueueSubmit", pSubmits[submit].pWaitDstStageMask[semaphore]);
1178 }
1179 }
1180
1181 return skip;
1182}
1183
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001184bool BestPractices::PreCallValidateQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR* pSubmits,
1185 VkFence fence) const {
1186 bool skip = false;
1187
1188 for (uint32_t submit = 0; submit < submitCount; submit++) {
1189 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreInfoCount; semaphore++) {
1190 skip |= CheckPipelineStageFlags("vkQueueSubmit2KHR", pSubmits[submit].pWaitSemaphoreInfos[semaphore].stageMask);
1191 }
1192 }
1193
1194 return skip;
1195}
1196
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001197bool BestPractices::PreCallValidateCreateCommandPool(VkDevice device, const VkCommandPoolCreateInfo* pCreateInfo,
1198 const VkAllocationCallbacks* pAllocator, VkCommandPool* pCommandPool) const {
1199 bool skip = false;
1200
1201 if (pCreateInfo->flags & VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT) {
1202 skip |= LogPerformanceWarning(
1203 device, kVUID_BestPractices_CreateCommandPool_CommandBufferReset,
1204 "vkCreateCommandPool(): VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT is set. Consider resetting entire "
1205 "pool instead.");
1206 }
1207
1208 return skip;
1209}
1210
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001211void BestPractices::PreCallRecordBeginCommandBuffer(VkCommandBuffer commandBuffer, const VkCommandBufferBeginInfo *pBeginInfo)
1212{
1213 // Clear state in case we are a secondary command buffer.
1214 auto& state = cbRenderPassState[commandBuffer];
1215 state = {};
Hans-Kristian Arntzenaf81dca2021-06-18 11:14:28 +02001216 auto* cb = GetCBState(commandBuffer);
1217 cb->hasDrawCmd = false;
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001218 ValidationStateTracker::PreCallRecordBeginCommandBuffer(commandBuffer, pBeginInfo);
1219}
1220
1221void BestPractices::PreCallRecordDestroyCommandPool(VkDevice device, VkCommandPool commandPool,
1222 const VkAllocationCallbacks *pAllocation)
1223{
1224 COMMAND_POOL_STATE* pool = GetCommandPoolState(commandPool);
1225 if (pool) {
1226 for (auto& cb : pool->commandBuffers) {
1227 auto itr = cbRenderPassState.find(cb);
1228 if (itr != cbRenderPassState.end()) {
1229 cbRenderPassState.erase(itr);
1230 }
1231 }
1232 }
1233 ValidationStateTracker::PreCallRecordDestroyCommandPool(device, commandPool, pAllocation);
1234}
1235
1236void BestPractices::PreCallRecordFreeCommandBuffers(VkDevice device, VkCommandPool commandPool,
1237 uint32_t commandBufferCount, const VkCommandBuffer* pCommandBuffers) {
1238 for (uint32_t i = 0; i < commandBufferCount; i++) {
1239 auto itr = cbRenderPassState.find(pCommandBuffers[i]);
1240 if (itr != cbRenderPassState.end()) {
1241 cbRenderPassState.erase(itr);
1242 }
1243 }
1244 ValidationStateTracker::PreCallRecordFreeCommandBuffers(device, commandPool, commandBufferCount, pCommandBuffers);
1245}
1246
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001247bool BestPractices::PreCallValidateBeginCommandBuffer(VkCommandBuffer commandBuffer,
1248 const VkCommandBufferBeginInfo* pBeginInfo) const {
1249 bool skip = false;
1250
1251 if (pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT) {
1252 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_SimultaneousUse,
1253 "vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT is set.");
1254 }
1255
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001256 if (!(pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT) && VendorCheckEnabled(kBPVendorArm)) {
1257 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_OneTimeSubmit,
Attilio Provenzano02859b22020-02-27 14:17:28 +00001258 "%s vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT is not set. "
1259 "For best performance on Mali GPUs, consider setting ONE_TIME_SUBMIT by default.",
1260 VendorSpecificTag(kBPVendorArm));
1261 }
1262
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001263 return skip;
1264}
1265
Jeff Bolz5c801d12019-10-09 10:38:45 -05001266bool BestPractices::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001267 bool skip = false;
1268
1269 skip |= CheckPipelineStageFlags("vkCmdSetEvent", stageMask);
1270
1271 return skip;
1272}
1273
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001274bool BestPractices::PreCallValidateCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1275 const VkDependencyInfoKHR* pDependencyInfo) const {
1276 return CheckDependencyInfo("vkCmdSetEvent2KHR", *pDependencyInfo);
1277}
1278
Jeff Bolz5c801d12019-10-09 10:38:45 -05001279bool BestPractices::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
1280 VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001281 bool skip = false;
1282
1283 skip |= CheckPipelineStageFlags("vkCmdResetEvent", stageMask);
1284
1285 return skip;
1286}
1287
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001288bool BestPractices::PreCallValidateCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1289 VkPipelineStageFlags2KHR stageMask) const {
1290 bool skip = false;
1291
1292 skip |= CheckPipelineStageFlags("vkCmdResetEvent2KHR", stageMask);
1293
1294 return skip;
1295}
1296
Camden5b184be2019-08-13 07:50:19 -06001297bool BestPractices::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1298 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
1299 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1300 uint32_t bufferMemoryBarrierCount,
1301 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1302 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001303 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001304 bool skip = false;
1305
1306 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", srcStageMask);
1307 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", dstStageMask);
1308
1309 return skip;
1310}
1311
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001312bool BestPractices::PreCallValidateCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1313 const VkDependencyInfoKHR* pDependencyInfos) const {
1314 bool skip = false;
1315 for (uint32_t i = 0; i < eventCount; i++) {
1316 skip = CheckDependencyInfo("vkCmdWaitEvents2KHR", pDependencyInfos[i]);
1317 }
1318
1319 return skip;
1320}
1321
Camden5b184be2019-08-13 07:50:19 -06001322bool BestPractices::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
1323 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
1324 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1325 uint32_t bufferMemoryBarrierCount,
1326 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1327 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001328 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001329 bool skip = false;
1330
1331 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", srcStageMask);
1332 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", dstStageMask);
1333
1334 return skip;
1335}
1336
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001337bool BestPractices::PreCallValidateCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer,
1338 const VkDependencyInfoKHR* pDependencyInfo) const {
1339 return CheckDependencyInfo("vkCmdPipelineBarrier2KHR", *pDependencyInfo);
1340}
1341
Camden5b184be2019-08-13 07:50:19 -06001342bool BestPractices::PreCallValidateCmdWriteTimestamp(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001343 VkQueryPool queryPool, uint32_t query) const {
Camden5b184be2019-08-13 07:50:19 -06001344 bool skip = false;
1345
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001346 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp", static_cast<VkPipelineStageFlags>(pipelineStage));
1347
1348 return skip;
1349}
1350
1351bool BestPractices::PreCallValidateCmdWriteTimestamp2KHR(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
1352 VkQueryPool queryPool, uint32_t query) const {
1353 bool skip = false;
1354
1355 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp2KHR", pipelineStage);
Camden5b184be2019-08-13 07:50:19 -06001356
1357 return skip;
1358}
1359
Sam Walls0961ec02020-03-31 16:39:15 +01001360void BestPractices::PostCallRecordCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
1361 VkPipeline pipeline) {
1362 StateTracker::PostCallRecordCmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
1363
1364 if (pipelineBindPoint == VK_PIPELINE_BIND_POINT_GRAPHICS) {
1365 // check for depth/blend state tracking
1366 auto gp_cis = graphicsPipelineCIs.find(pipeline);
1367 if (gp_cis != graphicsPipelineCIs.end()) {
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001368 auto& render_pass_state = cbRenderPassState[commandBuffer];
Sam Walls0961ec02020-03-31 16:39:15 +01001369
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001370 render_pass_state.nextDrawTouchesAttachments = gp_cis->second.accessFramebufferAttachments;
1371 render_pass_state.drawTouchAttachments = true;
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02001372
Sam Walls0961ec02020-03-31 16:39:15 +01001373 const auto* blend_state = gp_cis->second.colorBlendStateCI;
1374 const auto* stencil_state = gp_cis->second.depthStencilStateCI;
1375
1376 if (blend_state) {
1377 // assume the pipeline is depth-only unless any of the attachments have color writes enabled
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001378 render_pass_state.depthOnly = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001379 for (size_t i = 0; i < blend_state->attachmentCount; i++) {
1380 if (blend_state->pAttachments[i].colorWriteMask != 0) {
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001381 render_pass_state.depthOnly = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001382 }
1383 }
1384 }
1385
1386 // check for depth value usage
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001387 render_pass_state.depthEqualComparison = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001388
1389 if (stencil_state && stencil_state->depthTestEnable) {
1390 switch (stencil_state->depthCompareOp) {
1391 case VK_COMPARE_OP_EQUAL:
1392 case VK_COMPARE_OP_GREATER_OR_EQUAL:
1393 case VK_COMPARE_OP_LESS_OR_EQUAL:
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001394 render_pass_state.depthEqualComparison = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001395 break;
1396 default:
1397 break;
1398 }
1399 }
Sam Walls0961ec02020-03-31 16:39:15 +01001400 }
1401 }
1402}
1403
Hans-Kristian Arntzen237663c2021-07-01 14:36:40 +02001404static inline bool RenderPassUsesAttachmentAsResolve(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1405 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
1406 const auto& subpass_info = createInfo.pSubpasses[subpass];
1407 if (subpass_info.pResolveAttachments) {
1408 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1409 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
1410 }
1411 }
1412 }
1413
1414 return false;
1415}
1416
Attilio Provenzano02859b22020-02-27 14:17:28 +00001417static inline bool RenderPassUsesAttachmentOnTile(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1418 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001419 const auto& subpass_info = createInfo.pSubpasses[subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001420
1421 // If an attachment is ever used as a color attachment,
1422 // resolve attachment or depth stencil attachment,
1423 // it needs to exist on tile at some point.
1424
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001425 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1426 if (subpass_info.pColorAttachments[i].attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001427 }
1428
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001429 if (subpass_info.pResolveAttachments) {
1430 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1431 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
1432 }
1433 }
1434
1435 if (subpass_info.pDepthStencilAttachment && subpass_info.pDepthStencilAttachment->attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001436 }
1437
1438 return false;
1439}
1440
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001441static inline bool RenderPassUsesAttachmentAsImageOnly(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1442 if (RenderPassUsesAttachmentOnTile(createInfo, attachment)) {
1443 return false;
1444 }
1445
1446 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001447 const auto& subpassInfo = createInfo.pSubpasses[subpass];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001448
1449 for (uint32_t i = 0; i < subpassInfo.inputAttachmentCount; i++) {
1450 if (subpassInfo.pInputAttachments[i].attachment == attachment) {
1451 return true;
1452 }
1453 }
1454 }
1455
1456 return false;
1457}
1458
Attilio Provenzano02859b22020-02-27 14:17:28 +00001459bool BestPractices::ValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1460 const VkRenderPassBeginInfo* pRenderPassBegin) const {
1461 bool skip = false;
1462
1463 if (!pRenderPassBegin) {
1464 return skip;
1465 }
1466
1467 auto rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
1468 if (rp_state) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08001469 if (rp_state->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07001470 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
Tony-LunarG767180f2020-04-23 14:03:59 -06001471 if (rpabi) {
1472 skip = ValidateAttachments(rp_state->createInfo.ptr(), rpabi->attachmentCount, rpabi->pAttachments);
1473 }
1474 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001475 // Check if any attachments have LOAD operation on them
1476 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001477 const auto& attachment = rp_state->createInfo.pAttachments[att];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001478
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001479 bool attachment_has_readback = false;
Hans-Kristian Arntzen4afb59b2021-06-18 12:41:36 +02001480 if (!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001481 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001482 }
1483
1484 if (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001485 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001486 }
1487
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001488 bool attachment_needs_readback = false;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001489
1490 // Check if the attachment is actually used in any subpass on-tile
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001491 if (attachment_has_readback && RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1492 attachment_needs_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001493 }
1494
1495 // Using LOAD_OP_LOAD is expensive on tiled GPUs, so flag it as a potential improvement
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001496 if (attachment_needs_readback && VendorCheckEnabled(kBPVendorArm)) {
1497 skip |= LogPerformanceWarning(
1498 device, kVUID_BestPractices_BeginRenderPass_AttachmentNeedsReadback,
1499 "%s Attachment #%u in render pass has begun with VK_ATTACHMENT_LOAD_OP_LOAD.\n"
1500 "Submitting this renderpass will cause the driver to inject a readback of the attachment "
1501 "which will copy in total %u pixels (renderArea = { %d, %d, %u, %u }) to the tile buffer.",
1502 VendorSpecificTag(kBPVendorArm), att,
1503 pRenderPassBegin->renderArea.extent.width * pRenderPassBegin->renderArea.extent.height,
1504 pRenderPassBegin->renderArea.offset.x, pRenderPassBegin->renderArea.offset.y,
1505 pRenderPassBegin->renderArea.extent.width, pRenderPassBegin->renderArea.extent.height);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001506 }
1507 }
1508 }
1509
1510 return skip;
1511}
1512
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001513void BestPractices::QueueValidateImageView(QueueCallbacks &funcs, const char* function_name,
1514 IMAGE_VIEW_STATE* view, IMAGE_SUBRESOURCE_USAGE_BP usage) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001515 if (view) {
Jeremy Gebbenb4d17012021-07-08 13:18:15 -06001516 QueueValidateImage(funcs, function_name, GetImageUsageState(view->create_info.image), usage,
1517 view->normalized_subresource_range);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001518 }
1519}
1520
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001521void BestPractices::QueueValidateImage(QueueCallbacks &funcs, const char* function_name,
1522 IMAGE_STATE_BP* state, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001523 const VkImageSubresourceRange& subresource_range) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001524 IMAGE_STATE* image = state->image;
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02001525
1526 // If we're viewing a 3D slice, ignore base array layer.
1527 // The entire 3D subresource is accessed as one atomic unit.
1528 const uint32_t base_array_layer = image->createInfo.imageType == VK_IMAGE_TYPE_3D ? 0 : subresource_range.baseArrayLayer;
1529
1530 const uint32_t max_layers = image->createInfo.arrayLayers - base_array_layer;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001531 const uint32_t array_layers = std::min(subresource_range.layerCount, max_layers);
1532 const uint32_t max_levels = image->createInfo.mipLevels - subresource_range.baseMipLevel;
1533 const uint32_t mip_levels = std::min(image->createInfo.mipLevels, max_levels);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001534
1535 for (uint32_t layer = 0; layer < array_layers; layer++) {
1536 for (uint32_t level = 0; level < mip_levels; level++) {
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02001537 QueueValidateImage(funcs, function_name, state, usage, layer + base_array_layer,
1538 level + subresource_range.baseMipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001539 }
1540 }
1541}
1542
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001543void BestPractices::QueueValidateImage(QueueCallbacks &funcs, const char* function_name,
1544 IMAGE_STATE_BP* state, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001545 const VkImageSubresourceLayers& subresource_layers) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001546 IMAGE_STATE* image = state->image;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001547 const uint32_t max_layers = image->createInfo.arrayLayers - subresource_layers.baseArrayLayer;
1548 const uint32_t array_layers = std::min(subresource_layers.layerCount, max_layers);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001549
1550 for (uint32_t layer = 0; layer < array_layers; layer++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001551 QueueValidateImage(funcs, function_name, state, usage, layer + subresource_layers.baseArrayLayer, subresource_layers.mipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001552 }
1553}
1554
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001555void BestPractices::QueueValidateImage(QueueCallbacks &funcs, const char* function_name,
1556 IMAGE_STATE_BP* state, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001557 uint32_t array_layer, uint32_t mip_level) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001558 funcs.push_back([this, function_name, state, usage, array_layer, mip_level](const ValidationStateTracker*, const QUEUE_STATE*) -> bool {
1559 ValidateImageInQueue(function_name, state, usage, array_layer, mip_level);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001560 return false;
1561 });
1562}
1563
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001564void BestPractices::ValidateImageInQueueArm(const char* function_name, IMAGE_STATE* image,
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001565 IMAGE_SUBRESOURCE_USAGE_BP last_usage,
1566 IMAGE_SUBRESOURCE_USAGE_BP usage,
1567 uint32_t array_layer, uint32_t mip_level) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001568 // Swapchain images are implicitly read so clear after store is expected.
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001569 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 -06001570 !image->IsSwapchainImage()) {
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001571 LogPerformanceWarning(
1572 device, kVUID_BestPractices_RenderPass_RedundantStore,
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001573 "%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 +02001574 "image was used, it was written to with STORE_OP_STORE. "
1575 "Storing to the image is probably redundant in this case, and wastes bandwidth on tile-based "
1576 "architectures.",
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001577 function_name, VendorSpecificTag(kBPVendorArm), array_layer, mip_level);
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001578 } 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 +02001579 LogPerformanceWarning(
1580 device, kVUID_BestPractices_RenderPass_RedundantClear,
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001581 "%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 +02001582 "image was used, it was written to with vkCmdClear*Image(). "
1583 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
1584 "tile-based architectures."
1585 "architectures.",
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001586 function_name, VendorSpecificTag(kBPVendorArm), array_layer, mip_level);
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01001587 } else if (usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE &&
1588 (last_usage == IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE ||
1589 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::CLEARED ||
1590 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE ||
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001591 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE)) {
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01001592 const char *last_cmd = nullptr;
1593 const char *vuid = nullptr;
1594 const char *suggestion = nullptr;
1595
1596 switch (last_usage) {
1597 case IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE:
1598 vuid = kVUID_BestPractices_RenderPass_BlitImage_LoadOpLoad;
1599 last_cmd = "vkCmdBlitImage";
1600 suggestion =
1601 "The blit is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
1602 "Rather than blitting, just render the source image in a fragment shader in this render pass, "
1603 "which avoids the memory roundtrip.";
1604 break;
1605 case IMAGE_SUBRESOURCE_USAGE_BP::CLEARED:
1606 vuid = kVUID_BestPractices_RenderPass_InefficientClear;
1607 last_cmd = "vkCmdClear*Image";
1608 suggestion =
1609 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
1610 "tile-based architectures. "
1611 "Use LOAD_OP_CLEAR instead to clear the image for free.";
1612 break;
1613 case IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE:
1614 vuid = kVUID_BestPractices_RenderPass_CopyImage_LoadOpLoad;
1615 last_cmd = "vkCmdCopy*Image";
1616 suggestion =
1617 "The copy is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
1618 "Rather than copying, just render the source image in a fragment shader in this render pass, "
1619 "which avoids the memory roundtrip.";
1620 break;
1621 case IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE:
1622 vuid = kVUID_BestPractices_RenderPass_ResolveImage_LoadOpLoad;
1623 last_cmd = "vkCmdResolveImage";
1624 suggestion =
1625 "The resolve is probably redundant in this case, and wastes a lot of bandwidth on tile-based architectures. "
1626 "Rather than resolving, and then loading, try to keep rendering in the same render pass, "
1627 "which avoids the memory roundtrip.";
1628 break;
1629 default:
1630 break;
1631 }
1632
1633 LogPerformanceWarning(
1634 device, vuid,
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001635 "%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 +01001636 "time image was used, it was written to with %s. %s",
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001637 function_name, VendorSpecificTag(kBPVendorArm), array_layer, mip_level, last_cmd, suggestion);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001638 }
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001639}
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001640
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001641void BestPractices::ValidateImageInQueue(const char* function_name, IMAGE_STATE_BP* state,
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001642 IMAGE_SUBRESOURCE_USAGE_BP usage, uint32_t array_layer,
1643 uint32_t mip_level) {
1644 IMAGE_STATE* image = state->image;
1645 IMAGE_SUBRESOURCE_USAGE_BP last_usage = state->usages[array_layer][mip_level];
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001646 state->usages[array_layer][mip_level] = usage;
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001647 if (VendorCheckEnabled(kBPVendorArm)) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001648 ValidateImageInQueueArm(function_name, image, last_usage, usage, array_layer, mip_level);
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001649 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001650}
1651
Hans-Kristian Arntzenb8336ad2021-04-28 14:54:09 +02001652void BestPractices::AddDeferredQueueOperations(CMD_BUFFER_STATE* cb) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001653 cb->queue_submit_functions.insert(cb->queue_submit_functions.end(),
Hans-Kristian Arntzenf44df192021-06-14 11:42:08 +02001654 cb->queue_submit_functions_after_render_pass.begin(),
1655 cb->queue_submit_functions_after_render_pass.end());
1656 cb->queue_submit_functions_after_render_pass.clear();
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001657}
1658
1659void BestPractices::PreCallRecordCmdEndRenderPass(VkCommandBuffer commandBuffer) {
1660 ValidationStateTracker::PreCallRecordCmdEndRenderPass(commandBuffer);
Hans-Kristian Arntzenb8336ad2021-04-28 14:54:09 +02001661 AddDeferredQueueOperations(GetCBState(commandBuffer));
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001662}
1663
1664void BestPractices::PreCallRecordCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassInfo) {
1665 ValidationStateTracker::PreCallRecordCmdEndRenderPass2(commandBuffer, pSubpassInfo);
Hans-Kristian Arntzenb8336ad2021-04-28 14:54:09 +02001666 AddDeferredQueueOperations(GetCBState(commandBuffer));
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001667}
1668
1669void BestPractices::PreCallRecordCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfoKHR *pSubpassInfo) {
1670 ValidationStateTracker::PreCallRecordCmdEndRenderPass2KHR(commandBuffer, pSubpassInfo);
Hans-Kristian Arntzenb8336ad2021-04-28 14:54:09 +02001671 AddDeferredQueueOperations(GetCBState(commandBuffer));
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001672}
1673
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02001674void BestPractices::PreCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer,
1675 const VkRenderPassBeginInfo* pRenderPassBegin,
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001676 VkSubpassContents contents) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001677 ValidationStateTracker::PreCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02001678 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1679}
1680
1681void BestPractices::PreCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer,
1682 const VkRenderPassBeginInfo* pRenderPassBegin,
1683 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1684 ValidationStateTracker::PreCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1685 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1686}
1687
1688void BestPractices::PreCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1689 const VkRenderPassBeginInfo* pRenderPassBegin,
1690 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1691 ValidationStateTracker::PreCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1692 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1693}
1694
1695void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001696
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001697 if (!pRenderPassBegin) {
1698 return;
1699 }
1700
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001701 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
1702
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001703 auto rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
1704 if (rp_state) {
1705 // Check load ops
1706 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001707 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001708
1709 if (!RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att) &&
1710 !RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1711 continue;
1712 }
1713
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001714 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::UNDEFINED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001715
1716 if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) ||
1717 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001718 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02001719 } else if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) ||
1720 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_CLEAR)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001721 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_CLEARED;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02001722 } else if (RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att)) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001723 usage = IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001724 }
1725
1726 auto framebuffer = GetFramebufferState(pRenderPassBegin->framebuffer);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001727 IMAGE_VIEW_STATE* image_view = nullptr;
1728
Tony-LunarGb3ab3572021-07-02 09:45:17 -06001729 if (framebuffer->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001730 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
1731 if (rpabi) {
1732 image_view = GetImageViewState(rpabi->pAttachments[att]);
1733 }
1734 } else {
1735 image_view = GetImageViewState(framebuffer->createInfo.pAttachments[att]);
1736 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001737
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001738 QueueValidateImageView(cb->queue_submit_functions, "vkCmdBeginRenderPass()", image_view, usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001739 }
1740
1741 // Check store ops
1742 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001743 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001744
1745 if (!RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1746 continue;
1747 }
1748
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001749 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_DISCARDED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001750
1751 if ((!FormatIsStencilOnly(attachment.format) && attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE) ||
1752 (FormatHasStencil(attachment.format) && attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001753 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_STORED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001754 }
1755
1756 auto framebuffer = GetFramebufferState(pRenderPassBegin->framebuffer);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001757
1758 IMAGE_VIEW_STATE* image_view = nullptr;
Tony-LunarGb3ab3572021-07-02 09:45:17 -06001759 if (framebuffer->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001760 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
1761 if (rpabi) {
1762 image_view = GetImageViewState(rpabi->pAttachments[att]);
1763 }
1764 } else {
1765 image_view = GetImageViewState(framebuffer->createInfo.pAttachments[att]);
1766 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001767
Hans-Kristian Arntzenf44df192021-06-14 11:42:08 +02001768 QueueValidateImageView(cb->queue_submit_functions_after_render_pass, "vkCmdEndRenderPass()", image_view, usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001769 }
1770 }
1771}
1772
Attilio Provenzano02859b22020-02-27 14:17:28 +00001773bool BestPractices::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1774 VkSubpassContents contents) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001775 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1776 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001777 return skip;
1778}
1779
1780bool BestPractices::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1781 const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08001782 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001783 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1784 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001785 return skip;
1786}
1787
1788bool BestPractices::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08001789 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001790 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1791 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001792 return skip;
1793}
1794
Sam Walls0961ec02020-03-31 16:39:15 +01001795void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1796 const VkRenderPassBeginInfo* pRenderPassBegin) {
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001797 // Reset the renderpass state
1798 auto& render_pass_state = cbRenderPassState[commandBuffer];
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02001799 render_pass_state.touchesAttachments.clear();
1800 render_pass_state.earlyClearAttachments.clear();
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001801 render_pass_state.numDrawCallsDepthOnly = 0;
1802 render_pass_state.numDrawCallsDepthEqualCompare = 0;
1803 render_pass_state.colorAttachment = false;
1804 render_pass_state.depthAttachment = false;
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02001805 render_pass_state.drawTouchAttachments = true;
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001806 // Don't reset state related to pipeline state.
Sam Walls0961ec02020-03-31 16:39:15 +01001807
Hans-Kristian Arntzenaf81dca2021-06-18 11:14:28 +02001808 auto* cb = GetCBState(commandBuffer);
1809 cb->hasDrawCmd = false;
1810
Hans-Kristian Arntzena1a92cc2021-03-17 13:09:33 +01001811 const auto* rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
Sam Walls0961ec02020-03-31 16:39:15 +01001812
1813 // track depth / color attachment usage within the renderpass
1814 for (size_t i = 0; i < rp_state->createInfo.subpassCount; i++) {
1815 // record if depth/color attachments are in use for this renderpass
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001816 if (rp_state->createInfo.pSubpasses[i].pDepthStencilAttachment != nullptr) render_pass_state.depthAttachment = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001817
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001818 if (rp_state->createInfo.pSubpasses[i].colorAttachmentCount > 0) render_pass_state.colorAttachment = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001819 }
1820}
1821
1822void BestPractices::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1823 VkSubpassContents contents) {
1824 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1825 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
1826}
1827
1828void BestPractices::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1829 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1830 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1831 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1832}
1833
1834void BestPractices::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1835 const VkRenderPassBeginInfo* pRenderPassBegin,
1836 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1837 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1838 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1839}
1840
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001841// Generic function to handle validation for all CmdDraw* type functions
1842bool BestPractices::ValidateCmdDrawType(VkCommandBuffer cmd_buffer, const char* caller) const {
1843 bool skip = false;
1844 const CMD_BUFFER_STATE* cb_state = GetCBState(cmd_buffer);
1845 if (cb_state) {
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001846 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
1847 const auto* pipeline_state = cb_state->lastBound[lv_bind_point].pipeline_state;
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001848 const auto& current_vtx_bfr_binding_info = cb_state->current_vertex_buffer_binding_info.vertex_buffer_bindings;
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001849
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001850 // Verify vertex binding
1851 if (pipeline_state->vertex_binding_descriptions_.size() <= 0) {
1852 if ((!current_vtx_bfr_binding_info.empty()) && (!cb_state->vertex_buffer_used)) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001853 skip |= LogPerformanceWarning(cb_state->commandBuffer(), kVUID_BestPractices_DrawState_VtxIndexOutOfBounds,
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001854 "Vertex buffers are bound to %s but no vertex buffers are attached to %s.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001855 report_data->FormatHandle(cb_state->commandBuffer()).c_str(),
1856 report_data->FormatHandle(pipeline_state->pipeline()).c_str());
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001857 }
1858 }
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06001859
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06001860 const auto* pipe = cb_state->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06001861 if (pipe) {
1862 const auto* rp_state = pipe->rp_state.get();
1863 if (rp_state) {
1864 for (uint32_t i = 0; i < rp_state->createInfo.subpassCount; ++i) {
1865 const auto& subpass = rp_state->createInfo.pSubpasses[i];
1866 const uint32_t depth_stencil_attachment = GetSubpassDepthStencilAttachmentIndex(
1867 pipe->graphicsPipelineCI.pDepthStencilState, subpass.pDepthStencilAttachment);
1868 if ((depth_stencil_attachment == VK_ATTACHMENT_UNUSED) && pipe->graphicsPipelineCI.pRasterizationState &&
1869 pipe->graphicsPipelineCI.pRasterizationState->depthBiasEnable == VK_TRUE) {
1870 skip |= LogWarning(cb_state->commandBuffer(), kVUID_BestPractices_DepthBiasNoAttachment,
1871 "%s: depthBiasEnable == VK_TRUE without a depth-stencil attachment.", caller);
1872 }
1873 }
1874 }
1875 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001876 }
1877 return skip;
1878}
1879
Sam Walls0961ec02020-03-31 16:39:15 +01001880void BestPractices::RecordCmdDrawType(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02001881 auto& render_pass_state = cbRenderPassState[cmd_buffer];
Sam Walls0961ec02020-03-31 16:39:15 +01001882 if (VendorCheckEnabled(kBPVendorArm)) {
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02001883 RecordCmdDrawTypeArm(render_pass_state, draw_count, caller);
1884 }
1885
1886 if (render_pass_state.drawTouchAttachments) {
1887 for (auto& touch : render_pass_state.nextDrawTouchesAttachments) {
1888 RecordAttachmentAccess(render_pass_state, touch.framebufferAttachment, touch.aspects);
1889 }
1890 // No need to touch the same attachments over and over.
1891 render_pass_state.drawTouchAttachments = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001892 }
1893}
1894
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02001895void BestPractices::RecordCmdDrawTypeArm(RenderPassState& render_pass_state, uint32_t draw_count, const char* caller) {
1896 if (draw_count >= kDepthPrePassMinDrawCountArm) {
1897 if (render_pass_state.depthOnly) render_pass_state.numDrawCallsDepthOnly++;
1898 if (render_pass_state.depthEqualComparison) render_pass_state.numDrawCallsDepthEqualCompare++;
Sam Walls0961ec02020-03-31 16:39:15 +01001899 }
1900}
1901
Camden5b184be2019-08-13 07:50:19 -06001902bool BestPractices::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001903 uint32_t firstVertex, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06001904 bool skip = false;
1905
1906 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001907 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
1908 "Warning: You are calling vkCmdDraw() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06001909 }
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06001910 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDraw()");
Camden5b184be2019-08-13 07:50:19 -06001911
1912 return skip;
1913}
1914
Sam Walls0961ec02020-03-31 16:39:15 +01001915void BestPractices::PostCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
1916 uint32_t firstVertex, uint32_t firstInstance) {
1917 StateTracker::PostCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
1918 RecordCmdDrawType(commandBuffer, vertexCount * instanceCount, "vkCmdDraw()");
1919}
1920
Camden5b184be2019-08-13 07:50:19 -06001921bool BestPractices::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001922 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06001923 bool skip = false;
1924
1925 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001926 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
1927 "Warning: You are calling vkCmdDrawIndexed() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06001928 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001929 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexed()");
1930
Attilio Provenzano02859b22020-02-27 14:17:28 +00001931 // Check if we reached the limit for small indexed draw calls.
1932 // Note that we cannot update the draw call count here, so we do it in PreCallRecordCmdDrawIndexed.
1933 const CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
1934 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices &&
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001935 (cmd_state->small_indexed_draw_call_count == kMaxSmallIndexedDrawcalls - 1) &&
1936 VendorCheckEnabled(kBPVendorArm)) {
1937 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_ManySmallIndexedDrawcalls,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -06001938 "%s: The command buffer contains many small indexed drawcalls "
Attilio Provenzano02859b22020-02-27 14:17:28 +00001939 "(at least %u drawcalls with less than %u indices each). This may cause pipeline bubbles. "
1940 "You can try batching drawcalls or instancing when applicable.",
1941 VendorSpecificTag(kBPVendorArm), kMaxSmallIndexedDrawcalls, kSmallIndexedDrawcallIndices);
1942 }
1943
Sam Walls8e77e4f2020-03-16 20:47:40 +00001944 if (VendorCheckEnabled(kBPVendorArm)) {
1945 ValidateIndexBufferArm(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
1946 }
1947
1948 return skip;
1949}
1950
1951bool BestPractices::ValidateIndexBufferArm(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1952 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
1953 bool skip = false;
1954
1955 // check for sparse/underutilised index buffer, and post-transform cache thrashing
1956 const auto* cmd_state = GetCBState(commandBuffer);
1957 if (cmd_state == nullptr) return skip;
1958
locke-lunarg1ae57d62020-11-18 10:49:19 -07001959 const auto* ib_state = cmd_state->index_buffer_binding.buffer_state.get();
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06001960 if (ib_state == nullptr || cmd_state->index_buffer_binding.buffer_state->Destroyed()) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00001961
1962 const VkIndexType ib_type = cmd_state->index_buffer_binding.index_type;
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06001963 const auto& ib_mem_state = *ib_state->MemState();
Sam Walls8e77e4f2020-03-16 20:47:40 +00001964 const VkDeviceSize ib_mem_offset = ib_mem_state.mapped_range.offset;
1965 const void* ib_mem = ib_mem_state.p_driver_data;
1966 bool primitive_restart_enable = false;
1967
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001968 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
1969 const auto& pipeline_binding_iter = cmd_state->lastBound[lv_bind_point];
1970 const auto* pipeline_state = pipeline_binding_iter.pipeline_state;
Sam Walls8e77e4f2020-03-16 20:47:40 +00001971
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001972 if (pipeline_state != nullptr && pipeline_state->graphicsPipelineCI.pInputAssemblyState != nullptr) {
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001973 primitive_restart_enable = pipeline_state->graphicsPipelineCI.pInputAssemblyState->primitiveRestartEnable == VK_TRUE;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001974 }
Sam Walls8e77e4f2020-03-16 20:47:40 +00001975
1976 // 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 -06001977 if (ib_mem && pipeline_binding_iter.IsUsing()) {
Sam Walls8e77e4f2020-03-16 20:47:40 +00001978 uint32_t scan_stride;
1979 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1980 scan_stride = sizeof(uint8_t);
1981 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1982 scan_stride = sizeof(uint16_t);
1983 } else {
1984 scan_stride = sizeof(uint32_t);
1985 }
1986
1987 const uint8_t* scan_begin = static_cast<const uint8_t*>(ib_mem) + ib_mem_offset + firstIndex * scan_stride;
1988 const uint8_t* scan_end = scan_begin + indexCount * scan_stride;
1989
1990 // Min and max are important to track for some Mali architectures. In older Mali devices without IDVS, all
1991 // vertices corresponding to indices between the minimum and maximum may be loaded, and possibly shaded,
1992 // irrespective of whether or not they're part of the draw call.
1993
1994 // start with minimum as 0xFFFFFFFF and adjust to indices in the buffer
1995 uint32_t min_index = ~0u;
1996 // start with maximum as 0 and adjust to indices in the buffer
1997 uint32_t max_index = 0u;
1998
1999 // first scan-through, we're looking to simulate a model LRU post-transform cache, estimating the number of vertices shaded
2000 // for the given index buffer
2001 uint32_t vertex_shade_count = 0;
2002
2003 PostTransformLRUCacheModel post_transform_cache;
2004
2005 // The size of the cache being modelled positively correlates with how much behaviour it can capture about
2006 // arbitrary ground-truth hardware/architecture cache behaviour. I.e. it's a good solution when we don't know the
2007 // target architecture.
2008 // However, modelling a post-transform cache with more than 32 elements gives diminishing returns in practice.
2009 // http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
2010 post_transform_cache.resize(32);
2011
2012 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
2013 uint32_t scan_index;
2014 uint32_t primitive_restart_value;
2015 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
2016 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
2017 primitive_restart_value = 0xFF;
2018 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
2019 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
2020 primitive_restart_value = 0xFFFF;
2021 } else {
2022 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
2023 primitive_restart_value = 0xFFFFFFFF;
2024 }
2025
2026 max_index = std::max(max_index, scan_index);
2027 min_index = std::min(min_index, scan_index);
2028
2029 if (!primitive_restart_enable || scan_index != primitive_restart_value) {
2030 bool in_cache = post_transform_cache.query_cache(scan_index);
2031 // if the shaded vertex corresponding to the index is not in the PT-cache, we need to shade again
2032 if (!in_cache) vertex_shade_count++;
2033 }
2034 }
2035
2036 // 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 +01002037 // 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
2038 if (max_index < min_index || max_index == min_index) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00002039
2040 if (max_index - min_index >= indexCount) {
Mark Young0ec6b062020-11-19 15:32:17 -07002041 skip |=
2042 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
2043 "%s The indices which were specified for the draw call only utilise approximately %.02f%% of "
2044 "index buffer value range. Arm Mali architectures before G71 do not have IDVS (Index-Driven "
2045 "Vertex Shading), meaning all vertices corresponding to indices between the minimum and "
2046 "maximum would be loaded, and possibly shaded, whether or not they are used.",
2047 VendorSpecificTag(kBPVendorArm),
2048 (static_cast<float>(indexCount) / static_cast<float>(max_index - min_index)) * 100.0f);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002049 return skip;
2050 }
2051
2052 // use a dynamic vector of bitsets as a memory-compact representation of which indices are included in the draw call
2053 // 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 +01002054 const size_t refs_per_bucket = 64;
2055 std::vector<std::bitset<refs_per_bucket>> vertex_reference_buckets;
2056
2057 const uint32_t n_indices = max_index - min_index + 1;
2058 const uint32_t n_buckets = (n_indices / static_cast<uint32_t>(refs_per_bucket)) +
2059 ((n_indices % static_cast<uint32_t>(refs_per_bucket)) != 0 ? 1 : 0);
2060
2061 // there needs to be at least one bitset to store a set of indices smaller than n_buckets
2062 vertex_reference_buckets.resize(std::max(1u, n_buckets));
Sam Walls8e77e4f2020-03-16 20:47:40 +00002063
2064 // To avoid using too much memory, we run over the indices again.
2065 // Knowing the size from the last scan allows us to record index usage with bitsets
2066 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
2067 uint32_t scan_index;
2068 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
2069 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
2070 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
2071 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
2072 } else {
2073 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
2074 }
2075 // keep track of the set of all indices used to reference vertices in the draw call
2076 size_t index_offset = scan_index - min_index;
Sam Walls61b06892020-07-23 16:20:50 +01002077 size_t bitset_bucket_index = index_offset / refs_per_bucket;
2078 uint64_t used_indices = 1ull << ((index_offset % refs_per_bucket) & 0xFFFFFFFFu);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002079 vertex_reference_buckets[bitset_bucket_index] |= used_indices;
2080 }
2081
2082 uint32_t vertex_reference_count = 0;
2083 for (const auto& bitset : vertex_reference_buckets) {
2084 vertex_reference_count += static_cast<uint32_t>(bitset.count());
2085 }
2086
2087 // 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 -07002088 float utilization = static_cast<float>(vertex_reference_count) / static_cast<float>(max_index - min_index + 1);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002089 // 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 -07002090 float cache_hit_rate = static_cast<float>(vertex_reference_count) / static_cast<float>(vertex_shade_count);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002091
2092 if (utilization < 0.5f) {
2093 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
2094 "%s The indices which were specified for the draw call only utilise approximately "
2095 "%.02f%% of the bound vertex buffer.",
2096 VendorSpecificTag(kBPVendorArm), utilization);
2097 }
2098
2099 if (cache_hit_rate <= 0.5f) {
2100 skip |=
2101 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_PostTransformCacheThrashing,
2102 "%s The indices which were specified for the draw call are estimated to cause thrashing of "
2103 "the post-transform vertex cache, with a hit-rate of %.02f%%. "
2104 "I.e. the ordering of the index buffer may not make optimal use of indices associated with "
2105 "recently shaded vertices.",
2106 VendorSpecificTag(kBPVendorArm), cache_hit_rate * 100.0f);
2107 }
2108 }
2109
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002110 return skip;
2111}
2112
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002113bool BestPractices::PreCallValidateCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
2114 const VkCommandBuffer* pCommandBuffers) const {
2115 bool skip = false;
2116 const CMD_BUFFER_STATE* primary = GetCBState(commandBuffer);
2117 for (uint32_t i = 0; i < commandBufferCount; i++) {
2118 auto secondary_itr = cbRenderPassState.find(pCommandBuffers[i]);
2119 if (secondary_itr == cbRenderPassState.end()) {
2120 continue;
2121 }
2122 auto& secondary = secondary_itr->second;
2123 for (auto& clear : secondary.earlyClearAttachments) {
Hans-Kristian Arntzenfa8ef9f2021-06-29 12:07:59 +02002124 if (ClearAttachmentsIsFullClear(primary, uint32_t(clear.rects.size()), clear.rects.data())) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002125 skip |= ValidateClearAttachment(commandBuffer, primary,
2126 clear.framebufferAttachment, clear.colorAttachment,
2127 clear.aspects, true);
2128 }
2129 }
2130 }
2131 return skip;
2132}
2133
2134void BestPractices::PreCallRecordCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
2135 const VkCommandBuffer* pCommandBuffers) {
2136 CMD_BUFFER_STATE* primary = GetCBState(commandBuffer);
2137 auto& primary_state = cbRenderPassState[commandBuffer];
2138
2139 for (uint32_t i = 0; i < commandBufferCount; i++) {
2140 auto& secondary = cbRenderPassState[pCommandBuffers[i]];
2141
2142 for (auto& early_clear : secondary.earlyClearAttachments) {
Hans-Kristian Arntzenfa8ef9f2021-06-29 12:07:59 +02002143 if (ClearAttachmentsIsFullClear(primary, uint32_t(early_clear.rects.size()), early_clear.rects.data())) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002144 RecordAttachmentClearAttachments(primary, primary_state, early_clear.framebufferAttachment,
2145 early_clear.colorAttachment, early_clear.aspects,
Hans-Kristian Arntzenfa8ef9f2021-06-29 12:07:59 +02002146 uint32_t(early_clear.rects.size()), early_clear.rects.data());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002147 } else {
2148 RecordAttachmentAccess(primary_state, early_clear.framebufferAttachment,
2149 early_clear.aspects);
2150 }
2151 }
2152
2153 for (auto& touch : secondary.touchesAttachments) {
2154 RecordAttachmentAccess(primary_state, touch.framebufferAttachment,
2155 touch.aspects);
2156 }
Hans-Kristian Arntzenc7eb82a2021-06-16 13:57:18 +02002157
2158 primary_state.numDrawCallsDepthEqualCompare += secondary.numDrawCallsDepthEqualCompare;
2159 primary_state.numDrawCallsDepthOnly += secondary.numDrawCallsDepthOnly;
Hans-Kristian Arntzenaf81dca2021-06-18 11:14:28 +02002160
2161 CMD_BUFFER_STATE* second_state = GetCBState(pCommandBuffers[i]);
2162 if (second_state->hasDrawCmd) {
2163 primary->hasDrawCmd = true;
2164 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002165 }
2166
2167 ValidationStateTracker::PreCallRecordCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
2168}
2169
2170void BestPractices::RecordAttachmentAccess(RenderPassState& state, uint32_t fb_attachment, VkImageAspectFlags aspects) {
2171 // Called when we have a partial clear attachment, or a normal draw call which accesses an attachment.
2172 auto itr = std::find_if(state.touchesAttachments.begin(), state.touchesAttachments.end(),
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002173 [&](const AttachmentInfo& info) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002174 return info.framebufferAttachment == fb_attachment;
2175 });
2176
2177 if (itr != state.touchesAttachments.end()) {
2178 itr->aspects |= aspects;
2179 } else {
2180 state.touchesAttachments.push_back({ fb_attachment, aspects });
2181 }
2182}
2183
2184void BestPractices::RecordAttachmentClearAttachments(CMD_BUFFER_STATE* cmd_state, RenderPassState& state,
2185 uint32_t fb_attachment, uint32_t color_attachment,
2186 VkImageAspectFlags aspects, uint32_t rectCount,
2187 const VkClearRect *pRects) {
2188 // If we observe a full clear before any other access to a frame buffer attachment,
2189 // we have candidate for redundant clear attachments.
2190 auto itr = std::find_if(state.touchesAttachments.begin(), state.touchesAttachments.end(),
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002191 [&](const AttachmentInfo& info) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002192 return info.framebufferAttachment == fb_attachment;
2193 });
2194
2195 uint32_t new_aspects = aspects;
2196 if (itr != state.touchesAttachments.end()) {
2197 new_aspects = aspects & ~itr->aspects;
2198 itr->aspects |= aspects;
2199 } else {
2200 state.touchesAttachments.push_back({ fb_attachment, aspects });
2201 }
2202
2203 if (new_aspects == 0) {
2204 return;
2205 }
2206
2207 if (cmd_state->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
2208 // The first command might be a clear, but might not be the first in the render pass, defer any checks until
2209 // CmdExecuteCommands.
2210 state.earlyClearAttachments.push_back({ fb_attachment, color_attachment, new_aspects,
2211 std::vector<VkClearRect>{pRects, pRects + rectCount} });
2212 }
2213}
2214
2215void BestPractices::PreCallRecordCmdClearAttachments(VkCommandBuffer commandBuffer,
2216 uint32_t attachmentCount, const VkClearAttachment* pClearAttachments,
2217 uint32_t rectCount, const VkClearRect* pRects) {
2218 CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
2219 RENDER_PASS_STATE* rp_state = cmd_state->activeRenderPass.get();
2220 FRAMEBUFFER_STATE* fb_state = cmd_state->activeFramebuffer.get();
2221 RenderPassState& tracking_state = cbRenderPassState[commandBuffer];
2222 bool is_secondary = cmd_state->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY;
2223
2224 if (rectCount == 0 || !rp_state) {
2225 return;
2226 }
2227
2228 if (!is_secondary && !fb_state) {
2229 return;
2230 }
2231
2232 // If we have a rect which covers the entire frame buffer, we have a LOAD_OP_CLEAR-like command.
2233 bool full_clear = ClearAttachmentsIsFullClear(cmd_state, rectCount, pRects);
2234
2235 auto& subpass = rp_state->createInfo.pSubpasses[cmd_state->activeSubpass];
2236 for (uint32_t i = 0; i < attachmentCount; i++) {
2237 auto& attachment = pClearAttachments[i];
2238 uint32_t fb_attachment = VK_ATTACHMENT_UNUSED;
2239 VkImageAspectFlags aspects = attachment.aspectMask;
2240
2241 if (aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) {
2242 if (subpass.pDepthStencilAttachment) {
2243 fb_attachment = subpass.pDepthStencilAttachment->attachment;
2244 }
2245 } else if (aspects & VK_IMAGE_ASPECT_COLOR_BIT) {
2246 fb_attachment = subpass.pColorAttachments[attachment.colorAttachment].attachment;
2247 }
2248
2249 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2250 if (full_clear) {
2251 RecordAttachmentClearAttachments(cmd_state, tracking_state,
2252 fb_attachment, attachment.colorAttachment, aspects,
2253 rectCount, pRects);
2254 } else {
2255 RecordAttachmentAccess(tracking_state, fb_attachment, aspects);
2256 }
2257 }
2258 }
2259
2260 ValidationStateTracker::PreCallRecordCmdClearAttachments(commandBuffer, attachmentCount, pClearAttachments,
2261 rectCount, pRects);
2262}
2263
Attilio Provenzano02859b22020-02-27 14:17:28 +00002264void BestPractices::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
2265 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
2266 ValidationStateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset,
2267 firstInstance);
2268
2269 CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
2270 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices) {
2271 cmd_state->small_indexed_draw_call_count++;
2272 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002273
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002274 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDrawIndexed()");
Attilio Provenzano02859b22020-02-27 14:17:28 +00002275}
2276
Sam Walls0961ec02020-03-31 16:39:15 +01002277void BestPractices::PostCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
2278 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
2279 StateTracker::PostCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
2280 RecordCmdDrawType(commandBuffer, indexCount * instanceCount, "vkCmdDrawIndexed()");
2281}
2282
sfricke-samsung681ab7b2020-10-29 01:53:35 -07002283bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2284 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
2285 uint32_t maxDrawCount, uint32_t stride) const {
2286 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCount()");
2287
2288 return skip;
2289}
2290
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002291bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
2292 VkDeviceSize offset, VkBuffer countBuffer,
2293 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
2294 uint32_t stride) const {
2295 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCountKHR()");
Camden5b184be2019-08-13 07:50:19 -06002296
2297 return skip;
2298}
2299
2300bool BestPractices::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002301 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06002302 bool skip = false;
2303
2304 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002305 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
2306 "Warning: You are calling vkCmdDrawIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002307 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirect()");
Camden5b184be2019-08-13 07:50:19 -06002308 }
2309
2310 return skip;
2311}
2312
Sam Walls0961ec02020-03-31 16:39:15 +01002313void BestPractices::PostCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2314 uint32_t count, uint32_t stride) {
2315 StateTracker::PostCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, count, stride);
2316 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndirect()");
2317}
2318
Camden5b184be2019-08-13 07:50:19 -06002319bool BestPractices::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002320 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06002321 bool skip = false;
2322
2323 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002324 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
2325 "Warning: You are calling vkCmdDrawIndexedIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002326 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirect()");
Camden5b184be2019-08-13 07:50:19 -06002327 }
2328
2329 return skip;
2330}
2331
Sam Walls0961ec02020-03-31 16:39:15 +01002332void BestPractices::PostCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2333 uint32_t count, uint32_t stride) {
2334 StateTracker::PostCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, count, stride);
2335 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndexedIndirect()");
2336}
2337
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002338void BestPractices::ValidateBoundDescriptorSets(VkCommandBuffer commandBuffer, const char* function_name) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01002339 CMD_BUFFER_STATE* cb_state = GetCBState(commandBuffer);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002340
2341 if (cb_state) {
2342 for (auto descriptor_set : cb_state->validated_descriptor_sets) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002343 const auto& layout = *descriptor_set->GetLayout();
Hans-Kristian Arntzena8199012021-03-22 12:10:07 +01002344
2345 for (uint32_t index = 0; index < descriptor_set->GetBindingCount(); ++index) {
2346 // For bindless scenarios, we should not attempt to track descriptor set state.
2347 // It is highly uncertain which resources are actually bound.
2348 // Resources which are written to such a descriptor should be marked as indeterminate w.r.t. state.
2349 VkDescriptorBindingFlags flags = layout.GetDescriptorBindingFlagsFromIndex(index);
2350 if (flags & (VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT |
2351 VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT |
2352 VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT)) {
2353 continue;
2354 }
2355
2356 auto index_range = layout.GetGlobalIndexRangeFromIndex(index);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002357 for (uint32_t i = index_range.start; i < index_range.end; ++i) {
ZandroFargnoliacf12f02020-06-18 16:50:00 +01002358 VkImageView image_view{VK_NULL_HANDLE};
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002359
2360 auto descriptor = descriptor_set->GetDescriptorFromGlobalIndex(i);
2361 switch (descriptor->GetClass()) {
2362 case cvdescriptorset::DescriptorClass::Image: {
2363 if (const auto image_descriptor = static_cast<const cvdescriptorset::ImageDescriptor*>(descriptor)) {
2364 image_view = image_descriptor->GetImageView();
2365 }
Hans-Kristian Arntzenbc3a6152021-03-22 13:05:43 +01002366 break;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002367 }
2368 case cvdescriptorset::DescriptorClass::ImageSampler: {
2369 if (const auto image_sampler_descriptor =
2370 static_cast<const cvdescriptorset::ImageSamplerDescriptor*>(descriptor)) {
2371 image_view = image_sampler_descriptor->GetImageView();
2372 }
Hans-Kristian Arntzenbc3a6152021-03-22 13:05:43 +01002373 break;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002374 }
ZandroFargnoliacf12f02020-06-18 16:50:00 +01002375 default:
Hans-Kristian Arntzenbc3a6152021-03-22 13:05:43 +01002376 break;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002377 }
2378
2379 if (image_view) {
2380 IMAGE_VIEW_STATE* image_view_state = GetImageViewState(image_view);
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002381 QueueValidateImageView(cb_state->queue_submit_functions, function_name,
2382 image_view_state, IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002383 }
2384 }
2385 }
2386 }
2387 }
2388}
2389
2390void BestPractices::PreCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
2391 uint32_t firstVertex, uint32_t firstInstance) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002392 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDraw()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002393}
2394
2395void BestPractices::PreCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2396 uint32_t drawCount, uint32_t stride) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002397 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDrawIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002398}
2399
2400void BestPractices::PreCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2401 uint32_t drawCount, uint32_t stride) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002402 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDrawIndexedIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002403}
2404
Camden5b184be2019-08-13 07:50:19 -06002405bool BestPractices::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t groupCountX, uint32_t groupCountY,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002406 uint32_t groupCountZ) const {
Camden5b184be2019-08-13 07:50:19 -06002407 bool skip = false;
2408
2409 if ((groupCountX == 0) || (groupCountY == 0) || (groupCountZ == 0)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002410 skip |= LogWarning(device, kVUID_BestPractices_CmdDispatch_GroupCountZero,
2411 "Warning: You are calling vkCmdDispatch() while one or more groupCounts are zero (groupCountX = %" PRIu32
2412 ", groupCountY = %" PRIu32 ", groupCountZ = %" PRIu32 ").",
2413 groupCountX, groupCountY, groupCountZ);
Camden5b184be2019-08-13 07:50:19 -06002414 }
2415
2416 return skip;
2417}
Camden83a9c372019-08-14 11:41:38 -06002418
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002419bool BestPractices::PreCallValidateCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo* pSubpassEndInfo) const {
2420 bool skip = false;
2421 skip |= StateTracker::PreCallValidateCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
2422 skip |= ValidateCmdEndRenderPass(commandBuffer);
2423 return skip;
2424}
2425
2426bool BestPractices::PreCallValidateCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfo* pSubpassEndInfo) const {
2427 bool skip = false;
2428 skip |= StateTracker::PreCallValidateCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
2429 skip |= ValidateCmdEndRenderPass(commandBuffer);
2430 return skip;
2431}
2432
Sam Walls0961ec02020-03-31 16:39:15 +01002433bool BestPractices::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
2434 bool skip = false;
Sam Walls0961ec02020-03-31 16:39:15 +01002435 skip |= StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002436 skip |= ValidateCmdEndRenderPass(commandBuffer);
2437 return skip;
2438}
2439
2440bool BestPractices::ValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
2441 bool skip = false;
Sam Walls0961ec02020-03-31 16:39:15 +01002442
Hans-Kristian Arntzen09aff9d2021-06-14 15:17:02 +02002443 auto render_pass_state = cbRenderPassState.find(commandBuffer);
Sam Walls0961ec02020-03-31 16:39:15 +01002444
Hans-Kristian Arntzen09aff9d2021-06-14 15:17:02 +02002445 if (render_pass_state == cbRenderPassState.end()) return skip;
Sam Walls0961ec02020-03-31 16:39:15 +01002446
Hans-Kristian Arntzen09aff9d2021-06-14 15:17:02 +02002447 bool uses_depth = (render_pass_state->second.depthAttachment || render_pass_state->second.colorAttachment) &&
2448 render_pass_state->second.numDrawCallsDepthEqualCompare >= kDepthPrePassNumDrawCallsArm &&
2449 render_pass_state->second.numDrawCallsDepthOnly >= kDepthPrePassNumDrawCallsArm;
Sam Walls0961ec02020-03-31 16:39:15 +01002450 if (uses_depth) {
2451 skip |= LogPerformanceWarning(
2452 device, kVUID_BestPractices_EndRenderPass_DepthPrePassUsage,
2453 "%s Depth pre-passes may be in use. In general, this is not recommended, as in Arm Mali GPUs since "
2454 "Mali-T620, Forward Pixel Killing (FPK) can already perform automatic hidden surface removal; in which "
2455 "case, using depth pre-passes for hidden surface removal may worsen performance.",
2456 VendorSpecificTag(kBPVendorArm));
2457 }
2458
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002459 const CMD_BUFFER_STATE* cmd = GetCBState(commandBuffer);
2460 RENDER_PASS_STATE* rp = cmd->activeRenderPass.get();
2461
2462 if (VendorCheckEnabled(kBPVendorArm) && rp) {
2463
2464 // If we use an attachment on-tile, we should access it in some way. Otherwise,
2465 // it is redundant to have it be part of the render pass.
2466 // Only consider it redundant if it will actually consume bandwidth, i.e.
2467 // LOAD_OP_LOAD is used or STORE_OP_STORE. CLEAR -> DONT_CARE is benign,
2468 // as is using pure input attachments.
2469 // CLEAR -> STORE might be considered a "useful" thing to do, but
2470 // the optimal thing to do is to defer the clear until you're actually
2471 // going to render to the image.
2472
2473 uint32_t num_attachments = rp->createInfo.attachmentCount;
2474 for (uint32_t i = 0; i < num_attachments; i++) {
Hans-Kristian Arntzen237663c2021-07-01 14:36:40 +02002475 if (!RenderPassUsesAttachmentOnTile(rp->createInfo, i) ||
2476 RenderPassUsesAttachmentAsResolve(rp->createInfo, i)) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002477 continue;
2478 }
2479
2480 auto& attachment = rp->createInfo.pAttachments[i];
2481
2482 VkImageAspectFlags bandwidth_aspects = 0;
2483
2484 if (!FormatIsStencilOnly(attachment.format) &&
2485 (attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
2486 attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE)) {
2487 if (FormatHasDepth(attachment.format)) {
2488 bandwidth_aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
2489 } else {
2490 bandwidth_aspects |= VK_IMAGE_ASPECT_COLOR_BIT;
2491 }
2492 }
2493
2494 if (FormatHasStencil(attachment.format) &&
2495 (attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
2496 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE)) {
2497 bandwidth_aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
2498 }
2499
2500 if (!bandwidth_aspects) {
2501 continue;
2502 }
2503
2504 auto itr = std::find_if(render_pass_state->second.touchesAttachments.begin(),
2505 render_pass_state->second.touchesAttachments.end(),
2506 [&](const AttachmentInfo& info) {
2507 return info.framebufferAttachment == i;
2508 });
2509 uint32_t untouched_aspects = bandwidth_aspects;
2510 if (itr != render_pass_state->second.touchesAttachments.end()) {
2511 untouched_aspects &= ~itr->aspects;
2512 }
2513
2514 if (untouched_aspects) {
2515 skip |= LogPerformanceWarning(
2516 device, kVUID_BestPractices_EndRenderPass_RedundantAttachmentOnTile,
2517 "%s Render pass was ended, but attachment #%u (format: %u, untouched aspects 0x%x) "
2518 "was never accessed by a pipeline or clear command. "
2519 "On tile-based architectures, LOAD_OP_LOAD and STORE_OP_STORE consume bandwidth and should not be part of the render pass "
2520 "if the attachments are not intended to be accessed.",
2521 VendorSpecificTag(kBPVendorArm), i, attachment.format, untouched_aspects);
2522 }
2523 }
2524 }
2525
Sam Walls0961ec02020-03-31 16:39:15 +01002526 return skip;
2527}
2528
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002529void BestPractices::PreCallRecordCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002530 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDispatch()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002531}
2532
2533void BestPractices::PreCallRecordCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002534 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDispatchIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002535}
2536
Camden Stocker9c051442019-11-06 14:28:43 -08002537bool BestPractices::ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(VkPhysicalDevice physicalDevice,
2538 const char* api_name) const {
2539 bool skip = false;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002540 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
Camden Stocker9c051442019-11-06 14:28:43 -08002541
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002542 if (bp_pd_state) {
2543 if (bp_pd_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState == UNCALLED) {
2544 skip |= LogWarning(physicalDevice, kVUID_BestPractices_DisplayPlane_PropertiesNotCalled,
2545 "Potential problem with calling %s() without first retrieving properties from "
2546 "vkGetPhysicalDeviceDisplayPlanePropertiesKHR or vkGetPhysicalDeviceDisplayPlaneProperties2KHR.",
2547 api_name);
2548 }
Camden Stocker9c051442019-11-06 14:28:43 -08002549 }
2550
2551 return skip;
2552}
2553
Camden83a9c372019-08-14 11:41:38 -06002554bool BestPractices::PreCallValidateGetDisplayPlaneSupportedDisplaysKHR(VkPhysicalDevice physicalDevice, uint32_t planeIndex,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002555 uint32_t* pDisplayCount, VkDisplayKHR* pDisplays) const {
Camden83a9c372019-08-14 11:41:38 -06002556 bool skip = false;
2557
Camden Stocker9c051442019-11-06 14:28:43 -08002558 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneSupportedDisplaysKHR");
Camden83a9c372019-08-14 11:41:38 -06002559
Camden Stocker9c051442019-11-06 14:28:43 -08002560 return skip;
2561}
2562
2563bool BestPractices::PreCallValidateGetDisplayPlaneCapabilitiesKHR(VkPhysicalDevice physicalDevice, VkDisplayModeKHR mode,
2564 uint32_t planeIndex,
2565 VkDisplayPlaneCapabilitiesKHR* pCapabilities) const {
2566 bool skip = false;
2567
2568 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilitiesKHR");
2569
2570 return skip;
2571}
2572
2573bool BestPractices::PreCallValidateGetDisplayPlaneCapabilities2KHR(VkPhysicalDevice physicalDevice,
2574 const VkDisplayPlaneInfo2KHR* pDisplayPlaneInfo,
2575 VkDisplayPlaneCapabilities2KHR* pCapabilities) const {
2576 bool skip = false;
2577
2578 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilities2KHR");
Camden83a9c372019-08-14 11:41:38 -06002579
2580 return skip;
2581}
Camden05de2d42019-08-19 10:23:56 -06002582
2583bool BestPractices::PreCallValidateGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain, uint32_t* pSwapchainImageCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002584 VkImage* pSwapchainImages) const {
Camden05de2d42019-08-19 10:23:56 -06002585 bool skip = false;
2586
Nathaniel Cesario39152e62021-07-02 13:04:16 -06002587 const auto* swapchain_state = static_cast<SWAPCHAIN_STATE_BP*>(Get<SWAPCHAIN_NODE>(swapchain));
Camden05de2d42019-08-19 10:23:56 -06002588
Nathaniel Cesario39152e62021-07-02 13:04:16 -06002589 if (swapchain_state && pSwapchainImages) {
Camden05de2d42019-08-19 10:23:56 -06002590 // Compare the preliminary value of *pSwapchainImageCount with the value this time:
Nathaniel Cesario39152e62021-07-02 13:04:16 -06002591 if (swapchain_state->vkGetSwapchainImagesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002592 skip |=
2593 LogWarning(device, kVUID_Core_Swapchain_PriorCount,
2594 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImageCount; but no prior positive value has "
2595 "been seen for pSwapchainImages.");
Camden05de2d42019-08-19 10:23:56 -06002596 }
Camden05de2d42019-08-19 10:23:56 -06002597
Nathaniel Cesario4ce98382021-05-28 11:33:20 -06002598 if (*pSwapchainImageCount > swapchain_state->get_swapchain_image_count) {
2599 skip |= LogWarning(
2600 device, kVUID_BestPractices_Swapchain_InvalidCount,
2601 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImages, and with pSwapchainImageCount set to a "
2602 "value (%d) that is greater than the value (%d) that was returned when pSwapchainImages was NULL.",
2603 *pSwapchainImageCount, swapchain_state->get_swapchain_image_count);
2604 }
2605 }
2606
Camden05de2d42019-08-19 10:23:56 -06002607 return skip;
2608}
2609
2610// Common function to handle validation for GetPhysicalDeviceQueueFamilyProperties & 2KHR version
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002611bool BestPractices::ValidateCommonGetPhysicalDeviceQueueFamilyProperties(const PHYSICAL_DEVICE_STATE* pd_state,
2612 uint32_t requested_queue_family_property_count,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002613 const CALL_STATE call_state,
2614 const char* caller_name) const {
Camden05de2d42019-08-19 10:23:56 -06002615 bool skip = false;
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002616 // Verify that for each physical device, this command is called first with NULL pQueueFamilyProperties in order to get count
2617 if (UNCALLED == call_state) {
2618 skip |= LogWarning(
2619 pd_state->phys_device, kVUID_Core_DevLimit_MissingQueryCount,
2620 "%s is called with non-NULL pQueueFamilyProperties before obtaining pQueueFamilyPropertyCount. It is "
2621 "recommended "
2622 "to first call %s with NULL pQueueFamilyProperties in order to obtain the maximal pQueueFamilyPropertyCount.",
2623 caller_name, caller_name);
2624 // Then verify that pCount that is passed in on second call matches what was returned
2625 } else if (pd_state->queue_family_known_count != requested_queue_family_property_count) {
2626 skip |= LogWarning(pd_state->phys_device, kVUID_Core_DevLimit_CountMismatch,
2627 "%s is called with non-NULL pQueueFamilyProperties and pQueueFamilyPropertyCount value %" PRIu32
2628 ", but the largest previously returned pQueueFamilyPropertyCount for this physicalDevice is %" PRIu32
2629 ". It is recommended to instead receive all the properties by calling %s with "
2630 "pQueueFamilyPropertyCount that was "
2631 "previously obtained by calling %s with NULL pQueueFamilyProperties.",
2632 caller_name, requested_queue_family_property_count, pd_state->queue_family_known_count, caller_name,
2633 caller_name);
Camden05de2d42019-08-19 10:23:56 -06002634 }
2635
2636 return skip;
2637}
2638
Jeff Bolz5c801d12019-10-09 10:38:45 -05002639bool BestPractices::PreCallValidateBindAccelerationStructureMemoryNV(
2640 VkDevice device, uint32_t bindInfoCount, const VkBindAccelerationStructureMemoryInfoNV* pBindInfos) const {
Camden Stocker82510582019-09-03 14:00:16 -06002641 bool skip = false;
2642
2643 for (uint32_t i = 0; i < bindInfoCount; i++) {
sourav parmarcd5fb182020-07-17 12:58:44 -07002644 const ACCELERATION_STRUCTURE_STATE* as_state = GetAccelerationStructureStateNV(pBindInfos[i].accelerationStructure);
Camden Stocker82510582019-09-03 14:00:16 -06002645 if (!as_state->memory_requirements_checked) {
2646 // There's not an explicit requirement in the spec to call vkGetImageMemoryRequirements() prior to calling
2647 // BindAccelerationStructureMemoryNV but it's implied in that memory being bound must conform with
2648 // VkAccelerationStructureMemoryRequirementsInfoNV from vkGetAccelerationStructureMemoryRequirementsNV
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002649 skip |= LogWarning(
2650 device, kVUID_BestPractices_BindAccelNV_NoMemReqQuery,
Camden Stocker82510582019-09-03 14:00:16 -06002651 "vkBindAccelerationStructureMemoryNV(): "
2652 "Binding memory to %s but vkGetAccelerationStructureMemoryRequirementsNV() has not been called on that structure.",
2653 report_data->FormatHandle(pBindInfos[i].accelerationStructure).c_str());
2654 }
2655 }
2656
2657 return skip;
2658}
2659
Camden05de2d42019-08-19 10:23:56 -06002660bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
2661 uint32_t* pQueueFamilyPropertyCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002662 VkQueueFamilyProperties* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06002663 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
2664 assert(physical_device_state);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002665 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physical_device_state->phys_device);
2666 if (pQueueFamilyProperties && bp_pd_state) {
2667 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
2668 bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
2669 "vkGetPhysicalDeviceQueueFamilyProperties()");
2670 }
2671 return false;
Camden05de2d42019-08-19 10:23:56 -06002672}
2673
Mike Schuchardt2df08912020-12-15 16:28:09 -08002674bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
2675 uint32_t* pQueueFamilyPropertyCount,
2676 VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06002677 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
2678 assert(physical_device_state);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002679 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physical_device_state->phys_device);
2680 if (pQueueFamilyProperties && bp_pd_state) {
2681 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
2682 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
2683 "vkGetPhysicalDeviceQueueFamilyProperties2()");
2684 }
2685 return false;
Camden05de2d42019-08-19 10:23:56 -06002686}
2687
Jeff Bolz5c801d12019-10-09 10:38:45 -05002688bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2KHR(
Mike Schuchardt2df08912020-12-15 16:28:09 -08002689 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount, VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06002690 auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
2691 assert(physical_device_state);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002692 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physical_device_state->phys_device);
2693 if (pQueueFamilyProperties && bp_pd_state) {
2694 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
2695 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
2696 "vkGetPhysicalDeviceQueueFamilyProperties2KHR()");
2697 }
2698 return false;
Camden05de2d42019-08-19 10:23:56 -06002699}
2700
2701bool BestPractices::PreCallValidateGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
2702 uint32_t* pSurfaceFormatCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002703 VkSurfaceFormatKHR* pSurfaceFormats) const {
Camden05de2d42019-08-19 10:23:56 -06002704 if (!pSurfaceFormats) return false;
2705 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002706 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2707 const auto& call_state = bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState;
Camden05de2d42019-08-19 10:23:56 -06002708 bool skip = false;
2709 if (call_state == UNCALLED) {
2710 // Since we haven't recorded a preliminary value of *pSurfaceFormatCount, that likely means that the application didn't
2711 // previously call this function with a NULL value of pSurfaceFormats:
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002712 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_MustQueryCount,
2713 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount; but no prior "
2714 "positive value has been seen for pSurfaceFormats.");
Camden05de2d42019-08-19 10:23:56 -06002715 } else {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002716 auto prev_format_count = static_cast<uint32_t>(physical_device_state->surface_formats.size());
Peter Chene191bd72019-09-16 13:04:37 -04002717 if (*pSurfaceFormatCount > prev_format_count) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002718 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_CountMismatch,
2719 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount, and with "
2720 "pSurfaceFormats set to a value (%u) that is greater than the value (%u) that was returned "
2721 "when pSurfaceFormatCount was NULL.",
2722 *pSurfaceFormatCount, prev_format_count);
Camden05de2d42019-08-19 10:23:56 -06002723 }
2724 }
2725 return skip;
2726}
Camden Stocker23cc47d2019-09-03 14:53:57 -06002727
2728bool BestPractices::PreCallValidateQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002729 VkFence fence) const {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002730 bool skip = false;
2731
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002732 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
2733 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
Camden Stocker23cc47d2019-09-03 14:53:57 -06002734 // 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 -07002735 layer_data::unordered_set<const IMAGE_STATE*> sparse_images;
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002736 // Track images getting metadata bound by this call in a set, it'll be recorded into the image_state
2737 // in RecordQueueBindSparse.
Jeremy Gebbencbf22862021-03-03 12:01:22 -07002738 layer_data::unordered_set<const IMAGE_STATE*> sparse_images_with_metadata;
Camden Stocker23cc47d2019-09-03 14:53:57 -06002739 // 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 -07002740 for (uint32_t i = 0; i < bind_info.imageBindCount; ++i) {
2741 const auto& image_bind = bind_info.pImageBinds[i];
Camden Stocker23cc47d2019-09-03 14:53:57 -06002742 auto image_state = GetImageState(image_bind.image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002743 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002744 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002745 }
Camden Stocker23cc47d2019-09-03 14:53:57 -06002746 sparse_images.insert(image_state);
2747 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
2748 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
2749 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002750 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002751 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
2752 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002753 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002754 }
2755 }
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06002756 if (!image_state->memory_requirements_checked[0]) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002757 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002758 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002759 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
2760 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002761 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002762 }
2763 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002764 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
2765 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
2766 auto image_state = GetImageState(bind_info.pImageOpaqueBinds[i].image);
2767 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002768 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002769 }
Camden Stocker23cc47d2019-09-03 14:53:57 -06002770 sparse_images.insert(image_state);
2771 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
2772 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
2773 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002774 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002775 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
2776 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002777 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002778 }
2779 }
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06002780 if (!image_state->memory_requirements_checked[0]) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002781 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002782 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002783 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
2784 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002785 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002786 }
2787 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
2788 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002789 sparse_images_with_metadata.insert(image_state);
Camden Stocker23cc47d2019-09-03 14:53:57 -06002790 }
2791 }
2792 }
2793 for (const auto& sparse_image_state : sparse_images) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002794 if (sparse_image_state->sparse_metadata_required && !sparse_image_state->sparse_metadata_bound &&
2795 sparse_images_with_metadata.find(sparse_image_state) == sparse_images_with_metadata.end()) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002796 // Warn if sparse image binding metadata required for image with sparse binding, but metadata not bound
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002797 skip |= LogWarning(sparse_image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002798 "vkQueueBindSparse(): Binding sparse memory to %s which requires a metadata aspect but no "
2799 "binding with VK_SPARSE_MEMORY_BIND_METADATA_BIT set was made.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002800 report_data->FormatHandle(sparse_image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002801 }
2802 }
2803 }
2804
2805 return skip;
2806}
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002807
Mark Lobodzinski84101d72020-04-24 09:43:48 -06002808void BestPractices::ManualPostCallRecordQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
2809 VkFence fence, VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07002810 if (result != VK_SUCCESS) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07002811 return;
2812 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002813
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002814 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
2815 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
2816 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
2817 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
2818 auto image_state = GetImageState(bind_info.pImageOpaqueBinds[i].image);
2819 if (!image_state) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002820 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002821 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002822 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
2823 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
2824 image_state->sparse_metadata_bound = true;
2825 }
2826 }
2827 }
2828 }
2829}
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002830
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002831bool BestPractices::ClearAttachmentsIsFullClear(const CMD_BUFFER_STATE* cmd,
2832 uint32_t rectCount, const VkClearRect* pRects) const {
2833 if (cmd->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
2834 // We don't know the accurate render area in a secondary,
2835 // so assume we clear the entire frame buffer.
2836 // This is resolved in CmdExecuteCommands where we can check if the clear is a full clear.
2837 return true;
2838 }
2839
2840 // If we have a rect which covers the entire frame buffer, we have a LOAD_OP_CLEAR-like command.
2841 for (uint32_t i = 0; i < rectCount; i++) {
2842 auto& rect = pRects[i];
2843 auto& render_area = cmd->activeRenderPassBeginInfo.renderArea;
2844 if (rect.rect.extent.width == render_area.extent.width && rect.rect.extent.height == render_area.extent.height) {
2845 return true;
2846 }
2847 }
2848
2849 return false;
2850}
2851
2852bool BestPractices::ValidateClearAttachment(VkCommandBuffer commandBuffer, const CMD_BUFFER_STATE* cmd,
2853 uint32_t fb_attachment, uint32_t color_attachment,
2854 VkImageAspectFlags aspects, bool secondary) const {
2855 const RENDER_PASS_STATE* rp = cmd->activeRenderPass.get();
2856 bool skip = false;
2857
2858 if (!rp || fb_attachment == VK_ATTACHMENT_UNUSED) {
2859 return skip;
2860 }
2861
2862 auto rp_itr = cbRenderPassState.find(commandBuffer);
2863 if (rp_itr == cbRenderPassState.end()) {
2864 return skip;
2865 }
2866
2867 auto attachment_itr = std::find_if(rp_itr->second.touchesAttachments.begin(), rp_itr->second.touchesAttachments.end(),
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002868 [&](const AttachmentInfo& info) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002869 return info.framebufferAttachment == fb_attachment;
2870 });
2871
2872 // Only report aspects which haven't been touched yet.
2873 VkImageAspectFlags new_aspects = aspects;
2874 if (attachment_itr != rp_itr->second.touchesAttachments.end()) {
2875 new_aspects &= ~attachment_itr->aspects;
2876 }
2877
2878 // Warn if this is issued prior to Draw Cmd and clearing the entire attachment
2879 if (!cmd->hasDrawCmd) {
2880 skip |= LogPerformanceWarning(
2881 commandBuffer, kVUID_BestPractices_DrawState_ClearCmdBeforeDraw,
Hans-Kristian Arntzen4ddd6182021-06-18 12:16:33 +02002882 "vkCmdClearAttachments() issued on %s prior to any Draw Cmds in current render pass. It is recommended you "
2883 "use RenderPass LOAD_OP_CLEAR on attachments instead.",
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002884 report_data->FormatHandle(commandBuffer).c_str());
2885 }
2886
2887 if ((new_aspects & VK_IMAGE_ASPECT_COLOR_BIT) &&
2888 rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2889 skip |= LogPerformanceWarning(
2890 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2891 "%svkCmdClearAttachments() issued on %s for color attachment #%u in this subpass, "
2892 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2893 "it is more efficient.",
2894 secondary ? "vkCmdExecuteCommands(): " : "",
2895 report_data->FormatHandle(commandBuffer).c_str(), color_attachment);
2896 }
2897
2898 if ((new_aspects & VK_IMAGE_ASPECT_DEPTH_BIT) &&
2899 rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2900 skip |= LogPerformanceWarning(
2901 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2902 "%svkCmdClearAttachments() issued on %s for the depth attachment in this subpass, "
2903 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2904 "it is more efficient.",
2905 secondary ? "vkCmdExecuteCommands(): " : "",
2906 report_data->FormatHandle(commandBuffer).c_str());
2907 }
2908
2909 if ((new_aspects & VK_IMAGE_ASPECT_STENCIL_BIT) &&
2910 rp->createInfo.pAttachments[fb_attachment].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2911 skip |= LogPerformanceWarning(
2912 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2913 "%svkCmdClearAttachments() issued on %s for the stencil attachment in this subpass, "
2914 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2915 "it is more efficient.",
2916 secondary ? "vkCmdExecuteCommands(): " : "",
2917 report_data->FormatHandle(commandBuffer).c_str());
2918 }
2919
2920 return skip;
2921}
2922
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002923bool BestPractices::PreCallValidateCmdClearAttachments(VkCommandBuffer commandBuffer, uint32_t attachmentCount,
Camden Stockerf55721f2019-09-09 11:04:49 -06002924 const VkClearAttachment* pAttachments, uint32_t rectCount,
2925 const VkClearRect* pRects) const {
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002926 bool skip = false;
2927 const CMD_BUFFER_STATE* cb_node = GetCBState(commandBuffer);
2928 if (!cb_node) return skip;
2929
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002930 if (cb_node->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
2931 // Defer checks to ExecuteCommands.
2932 return skip;
2933 }
2934
2935 // Only care about full clears, partial clears might have legitimate uses.
2936 if (!ClearAttachmentsIsFullClear(cb_node, rectCount, pRects)) {
2937 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002938 }
2939
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002940 // Check for uses of ClearAttachments along with LOAD_OP_LOAD,
2941 // as it can be more efficient to just use LOAD_OP_CLEAR
locke-lunargaecf2152020-05-12 17:15:41 -06002942 const RENDER_PASS_STATE* rp = cb_node->activeRenderPass.get();
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002943 if (rp) {
2944 const auto& subpass = rp->createInfo.pSubpasses[cb_node->activeSubpass];
2945
2946 for (uint32_t i = 0; i < attachmentCount; i++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002947 const auto& attachment = pAttachments[i];
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002948
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002949 if (attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
2950 uint32_t color_attachment = attachment.colorAttachment;
2951 uint32_t fb_attachment = subpass.pColorAttachments[color_attachment].attachment;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002952 skip |= ValidateClearAttachment(commandBuffer, cb_node,
2953 fb_attachment, color_attachment,
2954 attachment.aspectMask, false);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002955 }
2956
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002957 if (subpass.pDepthStencilAttachment &&
2958 (attachment.aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT))) {
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002959 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002960 skip |= ValidateClearAttachment(commandBuffer, cb_node,
2961 fb_attachment, VK_ATTACHMENT_UNUSED,
2962 attachment.aspectMask, false);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002963 }
2964 }
2965 }
2966
Camden Stockerf55721f2019-09-09 11:04:49 -06002967 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002968}
Attilio Provenzano02859b22020-02-27 14:17:28 +00002969
2970bool BestPractices::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
2971 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
2972 const VkImageResolve* pRegions) const {
2973 bool skip = false;
2974
2975 skip |= VendorCheckEnabled(kBPVendorArm) &&
2976 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage_ResolvingImage,
2977 "%s Attempting to use vkCmdResolveImage to resolve a multisampled image. "
2978 "This is a very slow and extremely bandwidth intensive path. "
2979 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
2980 VendorSpecificTag(kBPVendorArm));
2981
2982 return skip;
2983}
2984
Jeff Leger178b1e52020-10-05 12:22:23 -04002985bool BestPractices::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
2986 const VkResolveImageInfo2KHR* pResolveImageInfo) const {
2987 bool skip = false;
2988
2989 skip |= VendorCheckEnabled(kBPVendorArm) &&
2990 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2KHR_ResolvingImage,
2991 "%s Attempting to use vkCmdResolveImage2KHR to resolve a multisampled image. "
2992 "This is a very slow and extremely bandwidth intensive path. "
2993 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
2994 VendorSpecificTag(kBPVendorArm));
2995
2996 return skip;
2997}
2998
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002999void BestPractices::PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3000 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3001 const VkImageResolve* pRegions) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003002 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003003 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003004 auto* src = GetImageUsageState(srcImage);
3005 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003006
3007 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003008 QueueValidateImage(funcs, "vkCmdResolveImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pRegions[i].srcSubresource);
3009 QueueValidateImage(funcs, "vkCmdResolveImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003010 }
3011}
3012
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01003013void BestPractices::PreCallRecordCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
3014 const VkResolveImageInfo2KHR* pResolveImageInfo) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003015 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003016 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003017 auto* src = GetImageUsageState(pResolveImageInfo->srcImage);
3018 auto* dst = GetImageUsageState(pResolveImageInfo->dstImage);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01003019 uint32_t regionCount = pResolveImageInfo->regionCount;
3020
3021 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003022 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pResolveImageInfo->pRegions[i].srcSubresource);
3023 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pResolveImageInfo->pRegions[i].dstSubresource);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01003024 }
3025}
3026
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003027void BestPractices::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
3028 const VkClearColorValue* pColor, uint32_t rangeCount,
3029 const VkImageSubresourceRange* pRanges) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003030 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003031 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003032 auto* dst = GetImageUsageState(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003033
3034 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003035 QueueValidateImage(funcs, "vkCmdClearColorImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003036 }
3037}
3038
3039void BestPractices::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
3040 const VkClearDepthStencilValue* pDepthStencil, uint32_t rangeCount,
3041 const VkImageSubresourceRange* pRanges) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003042 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003043 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003044 auto* dst = GetImageUsageState(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003045
3046 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003047 QueueValidateImage(funcs, "vkCmdClearDepthStencilImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003048 }
3049}
3050
3051void BestPractices::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3052 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3053 const VkImageCopy* pRegions) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003054 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003055 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003056 auto* src = GetImageUsageState(srcImage);
3057 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003058
3059 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003060 QueueValidateImage(funcs, "vkCmdCopyImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].srcSubresource);
3061 QueueValidateImage(funcs, "vkCmdCopyImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003062 }
3063}
3064
3065void BestPractices::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
3066 VkImageLayout dstImageLayout, uint32_t regionCount,
3067 const VkBufferImageCopy* pRegions) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003068 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003069 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003070 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003071
3072 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003073 QueueValidateImage(funcs, "vkCmdCopyBufferToImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003074 }
3075}
3076
3077void BestPractices::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3078 VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy* pRegions) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003079 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003080 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003081 auto* src = GetImageUsageState(srcImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003082
3083 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003084 QueueValidateImage(funcs, "vkCmdCopyImageToBuffer()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003085 }
3086}
3087
3088void BestPractices::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3089 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3090 const VkImageBlit* pRegions, VkFilter filter) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003091 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003092 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003093 auto* src = GetImageUsageState(srcImage);
3094 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003095
3096 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003097 QueueValidateImage(funcs, "vkCmdBlitImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_READ, pRegions[i].srcSubresource);
3098 QueueValidateImage(funcs, "vkCmdBlitImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003099 }
3100}
3101
Attilio Provenzano02859b22020-02-27 14:17:28 +00003102bool BestPractices::PreCallValidateCreateSampler(VkDevice device, const VkSamplerCreateInfo* pCreateInfo,
3103 const VkAllocationCallbacks* pAllocator, VkSampler* pSampler) const {
3104 bool skip = false;
3105
3106 if (VendorCheckEnabled(kBPVendorArm)) {
3107 if ((pCreateInfo->addressModeU != pCreateInfo->addressModeV) || (pCreateInfo->addressModeV != pCreateInfo->addressModeW)) {
3108 skip |= LogPerformanceWarning(
3109 device, kVUID_BestPractices_CreateSampler_DifferentWrappingModes,
3110 "%s Creating a sampler object with wrapping modes which do not match (U = %u, V = %u, W = %u). "
3111 "This may cause reduced performance even if only U (1D image) or U/V wrapping modes (2D "
3112 "image) are actually used. If you need different wrapping modes, disregard this warning.",
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -06003113 VendorSpecificTag(kBPVendorArm), pCreateInfo->addressModeU, pCreateInfo->addressModeV, pCreateInfo->addressModeW);
Attilio Provenzano02859b22020-02-27 14:17:28 +00003114 }
3115
3116 if ((pCreateInfo->minLod != 0.0f) || (pCreateInfo->maxLod < VK_LOD_CLAMP_NONE)) {
3117 skip |= LogPerformanceWarning(
3118 device, kVUID_BestPractices_CreateSampler_LodClamping,
3119 "%s Creating a sampler object with LOD clamping (minLod = %f, maxLod = %f). This may cause reduced performance. "
3120 "Instead of clamping LOD in the sampler, consider using an VkImageView which restricts the mip-levels, set minLod "
3121 "to 0.0, and maxLod to VK_LOD_CLAMP_NONE.",
3122 VendorSpecificTag(kBPVendorArm), pCreateInfo->minLod, pCreateInfo->maxLod);
3123 }
3124
3125 if (pCreateInfo->mipLodBias != 0.0f) {
3126 skip |=
3127 LogPerformanceWarning(device, kVUID_BestPractices_CreateSampler_LodBias,
3128 "%s Creating a sampler object with LOD bias != 0.0 (%f). This will lead to less efficient "
3129 "descriptors being created and may cause reduced performance.",
3130 VendorSpecificTag(kBPVendorArm), pCreateInfo->mipLodBias);
3131 }
3132
3133 if ((pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
3134 pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
3135 pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER) &&
3136 (pCreateInfo->borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK)) {
3137 skip |= LogPerformanceWarning(
3138 device, kVUID_BestPractices_CreateSampler_BorderClampColor,
3139 "%s Creating a sampler object with border clamping and borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK. "
3140 "This will lead to less efficient descriptors being created and may cause reduced performance. "
3141 "If possible, use VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK as the border color.",
3142 VendorSpecificTag(kBPVendorArm));
3143 }
3144
3145 if (pCreateInfo->unnormalizedCoordinates) {
3146 skip |= LogPerformanceWarning(
3147 device, kVUID_BestPractices_CreateSampler_UnnormalizedCoordinates,
3148 "%s Creating a sampler object with unnormalized coordinates. This will lead to less efficient "
3149 "descriptors being created and may cause reduced performance.",
3150 VendorSpecificTag(kBPVendorArm));
3151 }
3152
3153 if (pCreateInfo->anisotropyEnable) {
3154 skip |= LogPerformanceWarning(
3155 device, kVUID_BestPractices_CreateSampler_Anisotropy,
3156 "%s Creating a sampler object with anisotropy. This will lead to less efficient descriptors being created "
3157 "and may cause reduced performance.",
3158 VendorSpecificTag(kBPVendorArm));
3159 }
3160 }
3161
3162 return skip;
3163}
Sam Walls8e77e4f2020-03-16 20:47:40 +00003164
3165void BestPractices::PostTransformLRUCacheModel::resize(size_t size) { _entries.resize(size); }
3166
3167bool BestPractices::PostTransformLRUCacheModel::query_cache(uint32_t value) {
3168 // look for a cache hit
3169 auto hit = std::find_if(_entries.begin(), _entries.end(), [value](const CacheEntry& entry) { return entry.value == value; });
3170 if (hit != _entries.end()) {
3171 // mark the cache hit as being most recently used
3172 hit->age = iteration++;
3173 return true;
3174 }
3175
3176 // if there's no cache hit, we need to model the entry being inserted into the cache
3177 CacheEntry new_entry = {value, iteration};
3178 if (iteration < static_cast<uint32_t>(std::distance(_entries.begin(), _entries.end()))) {
3179 // if there is still space left in the cache, use the next available slot
3180 *(_entries.begin() + iteration) = new_entry;
3181 } else {
3182 // otherwise replace the least recently used cache entry
3183 auto lru = std::min_element(_entries.begin(), hit, [](const CacheEntry& a, const CacheEntry& b) { return a.age < b.age; });
3184 *lru = new_entry;
3185 }
3186 iteration++;
3187 return false;
3188}
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003189
3190bool BestPractices::PreCallValidateAcquireNextImageKHR(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout,
3191 VkSemaphore semaphore, VkFence fence, uint32_t* pImageIndex) const {
3192 const auto swapchain_data = GetSwapchainState(swapchain);
3193 bool skip = false;
3194 if (swapchain_data && swapchain_data->images.size() == 0) {
3195 skip |= LogWarning(swapchain, kVUID_Core_DrawState_SwapchainImagesNotFound,
3196 "vkAcquireNextImageKHR: No images found to acquire from. Application probably did not call "
3197 "vkGetSwapchainImagesKHR after swapchain creation.");
3198 }
3199 return skip;
3200}
3201
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003202void BestPractices::CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(CALL_STATE& call_state, bool no_pointer) {
3203 if (no_pointer) {
3204 if (UNCALLED == call_state) {
3205 call_state = QUERY_COUNT;
3206 }
3207 } else { // Save queue family properties
3208 call_state = QUERY_DETAILS;
3209 }
3210}
3211
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003212void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
3213 uint32_t* pQueueFamilyPropertyCount,
3214 VkQueueFamilyProperties* pQueueFamilyProperties) {
3215 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(physicalDevice, pQueueFamilyPropertyCount,
3216 pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003217 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003218 if (bp_pd_state) {
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003219 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
3220 nullptr == pQueueFamilyProperties);
3221 }
3222}
3223
3224void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
3225 uint32_t* pQueueFamilyPropertyCount,
3226 VkQueueFamilyProperties2* pQueueFamilyProperties) {
3227 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(physicalDevice, pQueueFamilyPropertyCount,
3228 pQueueFamilyProperties);
3229 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3230 if (bp_pd_state) {
3231 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
3232 nullptr == pQueueFamilyProperties);
3233 }
3234}
3235
3236void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(VkPhysicalDevice physicalDevice,
3237 uint32_t* pQueueFamilyPropertyCount,
3238 VkQueueFamilyProperties2* pQueueFamilyProperties) {
3239 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(physicalDevice, pQueueFamilyPropertyCount,
3240 pQueueFamilyProperties);
3241 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3242 if (bp_pd_state) {
3243 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
3244 nullptr == pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003245 }
3246}
3247
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003248void BestPractices::PostCallRecordGetPhysicalDeviceFeatures(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures* pFeatures) {
3249 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003250 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3251 if (bp_pd_state) {
3252 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3253 }
3254}
3255
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003256void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2(VkPhysicalDevice physicalDevice,
3257 VkPhysicalDeviceFeatures2* pFeatures) {
3258 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003259 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3260 if (bp_pd_state) {
3261 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3262 }
3263}
3264
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003265void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2KHR(VkPhysicalDevice physicalDevice,
3266 VkPhysicalDeviceFeatures2* pFeatures) {
3267 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2KHR(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003268 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3269 if (bp_pd_state) {
3270 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3271 }
3272}
3273
3274void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilitiesKHR(VkPhysicalDevice physicalDevice,
3275 VkSurfaceKHR surface,
3276 VkSurfaceCapabilitiesKHR* pSurfaceCapabilities,
3277 VkResult result) {
3278 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3279 if (bp_pd_state) {
3280 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3281 }
3282}
3283
3284void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2KHR(
3285 VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
3286 VkSurfaceCapabilities2KHR* pSurfaceCapabilities, VkResult result) {
3287 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3288 if (bp_pd_state) {
3289 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3290 }
3291}
3292
3293void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2EXT(VkPhysicalDevice physicalDevice,
3294 VkSurfaceKHR surface,
3295 VkSurfaceCapabilities2EXT* pSurfaceCapabilities,
3296 VkResult result) {
3297 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3298 if (bp_pd_state) {
3299 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3300 }
3301}
3302
3303void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice physicalDevice,
3304 VkSurfaceKHR surface, uint32_t* pPresentModeCount,
3305 VkPresentModeKHR* pPresentModes, VkResult result) {
3306 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
3307 if (bp_pd_data) {
3308 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfacePresentModesKHRState;
3309
3310 if (*pPresentModeCount) {
3311 if (call_state < QUERY_COUNT) {
3312 call_state = QUERY_COUNT;
3313 }
3314 }
3315 if (pPresentModes) {
3316 if (call_state < QUERY_DETAILS) {
3317 call_state = QUERY_DETAILS;
3318 }
3319 }
3320 }
3321}
3322
3323void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
3324 uint32_t* pSurfaceFormatCount,
3325 VkSurfaceFormatKHR* pSurfaceFormats, VkResult result) {
3326 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
3327 if (bp_pd_data) {
3328 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState;
3329
3330 if (*pSurfaceFormatCount) {
3331 if (call_state < QUERY_COUNT) {
3332 call_state = QUERY_COUNT;
3333 }
3334 }
3335 if (pSurfaceFormats) {
3336 if (call_state < QUERY_DETAILS) {
3337 call_state = QUERY_DETAILS;
3338 }
3339 }
3340 }
3341}
3342
3343void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormats2KHR(VkPhysicalDevice physicalDevice,
3344 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
3345 uint32_t* pSurfaceFormatCount,
3346 VkSurfaceFormat2KHR* pSurfaceFormats, VkResult result) {
3347 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
3348 if (bp_pd_data) {
3349 if (*pSurfaceFormatCount) {
3350 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_COUNT) {
3351 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_COUNT;
3352 }
3353 }
3354 if (pSurfaceFormats) {
3355 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_DETAILS) {
3356 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_DETAILS;
3357 }
3358 }
3359 }
3360}
3361
3362void BestPractices::ManualPostCallRecordGetPhysicalDeviceDisplayPlanePropertiesKHR(VkPhysicalDevice physicalDevice,
3363 uint32_t* pPropertyCount,
3364 VkDisplayPlanePropertiesKHR* pProperties,
3365 VkResult result) {
3366 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
3367 if (bp_pd_data) {
3368 if (*pPropertyCount) {
3369 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_COUNT) {
3370 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_COUNT;
3371 }
3372 }
3373 if (pProperties) {
3374 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_DETAILS) {
3375 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_DETAILS;
3376 }
3377 }
3378 }
3379}
3380
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003381void BestPractices::ManualPostCallRecordGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain,
3382 uint32_t* pSwapchainImageCount, VkImage* pSwapchainImages,
3383 VkResult result) {
Nathaniel Cesario39152e62021-07-02 13:04:16 -06003384 auto* swapchain_state = static_cast<SWAPCHAIN_STATE_BP*>(Get<SWAPCHAIN_NODE>(swapchain));
3385 if (swapchain_state && (pSwapchainImages || *pSwapchainImageCount)) {
3386 if (swapchain_state->vkGetSwapchainImagesKHRState < QUERY_DETAILS) {
3387 swapchain_state->vkGetSwapchainImagesKHRState = QUERY_DETAILS;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003388 }
3389 }
3390}
3391
3392void BestPractices::ManualPostCallRecordEnumeratePhysicalDevices(VkInstance instance, uint32_t* pPhysicalDeviceCount,
3393 VkPhysicalDevice* pPhysicalDevices, VkResult result) {
3394 if ((nullptr != pPhysicalDevices) && ((result == VK_SUCCESS || result == VK_INCOMPLETE))) {
3395 for (uint32_t i = 0; i < *pPhysicalDeviceCount; i++) {
3396 phys_device_bp_state_map.emplace(pPhysicalDevices[i], PHYSICAL_DEVICE_STATE_BP{});
3397 }
3398 }
3399}
3400
3401void BestPractices::ManualPostCallRecordCreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo*, const VkAllocationCallbacks*,
3402 VkDevice*, VkResult result) {
3403 if (VK_SUCCESS == result) {
3404 instance_device_bp_state = &phys_device_bp_state_map[gpu];
3405 }
3406}
3407
3408PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP(const VkPhysicalDevice& phys_device) {
3409 if (phys_device_bp_state_map.count(phys_device) > 0) {
3410 return &phys_device_bp_state_map.at(phys_device);
3411 } else {
3412 return nullptr;
3413 }
3414}
3415
3416const PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP(const VkPhysicalDevice& phys_device) const {
3417 if (phys_device_bp_state_map.count(phys_device) > 0) {
3418 return &phys_device_bp_state_map.at(phys_device);
3419 } else {
3420 return nullptr;
3421 }
3422}
3423
3424PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP() {
3425 auto bp_state = (reinterpret_cast<BestPractices*>(instance_state))->instance_device_bp_state;
3426 if (bp_state) {
3427 return bp_state;
3428 } else if (!bp_state && phys_device_bp_state_map.count(physical_device_state->phys_device) > 0) {
3429 return &phys_device_bp_state_map.at(physical_device_state->phys_device);
3430 } else {
3431 return nullptr;
3432 }
3433}
3434
3435const PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP() const {
3436 auto bp_state = (reinterpret_cast<BestPractices*>(instance_state))->instance_device_bp_state;
3437 if (bp_state) {
3438 return bp_state;
3439 } else if (!bp_state && phys_device_bp_state_map.count(physical_device_state->phys_device) > 0) {
3440 return &phys_device_bp_state_map.at(physical_device_state->phys_device);
3441 } else {
3442 return nullptr;
3443 }
3444}
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003445
3446void BestPractices::PreCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits, VkFence fence) {
3447 ValidationStateTracker::PreCallRecordQueueSubmit(queue, submitCount, pSubmits, fence);
3448
3449 QUEUE_STATE* queue_state = GetQueueState(queue);
3450 for (uint32_t submit = 0; submit < submitCount; submit++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02003451 const auto& submit_info = pSubmits[submit];
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003452 for (uint32_t cb_index = 0; cb_index < submit_info.commandBufferCount; cb_index++) {
3453 CMD_BUFFER_STATE* cb = GetCBState(submit_info.pCommandBuffers[cb_index]);
3454 for (auto &func : cb->queue_submit_functions) {
3455 func(this, queue_state);
3456 }
3457 }
3458 }
3459}