blob: 9933df14115782833c3a73a5c4ef8bed8a512fa2 [file] [log] [blame]
Nathaniel Cesario56a96652020-12-30 13:23:42 -07001/* Copyright (c) 2015-2021 The Khronos Group Inc.
2 * 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
42bool BestPractices::VendorCheckEnabled(BPVendorFlags vendors) const {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -070043 for (const auto& vendor : kVendorInfo) {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060044 if (vendors & vendor.first && enabled[vendor.second.vendor_id]) {
Attilio Provenzano19d6a982020-02-27 12:41:41 +000045 return true;
46 }
47 }
48 return false;
49}
50
51const char* VendorSpecificTag(BPVendorFlags vendors) {
52 // Cache built vendor tags in a map
Jeremy Gebbencbf22862021-03-03 12:01:22 -070053 static layer_data::unordered_map<BPVendorFlags, std::string> tag_map;
Attilio Provenzano19d6a982020-02-27 12:41:41 +000054
55 auto res = tag_map.find(vendors);
56 if (res == tag_map.end()) {
57 // Build the vendor tag string
58 std::stringstream vendor_tag;
59
60 vendor_tag << "[";
61 bool first_vendor = true;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -070062 for (const auto& vendor : kVendorInfo) {
Attilio Provenzano19d6a982020-02-27 12:41:41 +000063 if (vendors & vendor.first) {
64 if (!first_vendor) {
65 vendor_tag << ", ";
66 }
67 vendor_tag << vendor.second.name;
68 first_vendor = false;
69 }
70 }
71 vendor_tag << "]";
72
73 tag_map[vendors] = vendor_tag.str();
74 res = tag_map.find(vendors);
75 }
76
77 return res->second.c_str();
78}
79
Mark Lobodzinski6167e102020-02-24 17:03:55 -070080const char* DepReasonToString(ExtDeprecationReason reason) {
81 switch (reason) {
82 case kExtPromoted:
83 return "promoted to";
84 break;
85 case kExtObsoleted:
86 return "obsoleted by";
87 break;
88 case kExtDeprecated:
89 return "deprecated by";
90 break;
91 default:
92 return "";
93 break;
94 }
95}
96
97bool BestPractices::ValidateDeprecatedExtensions(const char* api_name, const char* extension_name, uint32_t version,
98 const char* vuid) const {
99 bool skip = false;
100 auto dep_info_it = deprecated_extensions.find(extension_name);
101 if (dep_info_it != deprecated_extensions.end()) {
102 auto dep_info = dep_info_it->second;
Mark Lobodzinski6a149702020-05-14 12:21:34 -0600103 if (((dep_info.target.compare("VK_VERSION_1_1") == 0) && (version >= VK_API_VERSION_1_1)) ||
104 ((dep_info.target.compare("VK_VERSION_1_2") == 0) && (version >= VK_API_VERSION_1_2))) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700105 skip |=
106 LogWarning(instance, vuid, "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
107 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
Mark Lobodzinski6a149702020-05-14 12:21:34 -0600108 } else if (dep_info.target.find("VK_VERSION") == std::string::npos) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700109 if (dep_info.target.length() == 0) {
110 skip |= LogWarning(instance, vuid,
111 "%s(): Attempting to enable deprecated extension %s, but this extension has been deprecated "
112 "without replacement.",
113 api_name, extension_name);
114 } else {
115 skip |= LogWarning(instance, vuid,
116 "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
117 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
118 }
119 }
120 }
121 return skip;
122}
123
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700124bool BestPractices::ValidateSpecialUseExtensions(const char* api_name, const char* extension_name, const char* vuid) const {
125 bool skip = false;
126 auto dep_info_it = special_use_extensions.find(extension_name);
127
128 if (dep_info_it != special_use_extensions.end()) {
129 auto special_uses = dep_info_it->second;
130 std::string message("is intended to support the following uses: ");
131 if (special_uses.find("cadsupport") != std::string::npos) {
132 message.append("specialized functionality used by CAD/CAM applications, ");
133 }
134 if (special_uses.find("d3demulation") != std::string::npos) {
135 message.append("D3D emulation layers, and applications ported from D3D, by adding functionality specific to D3D, ");
136 }
137 if (special_uses.find("devtools") != std::string::npos) {
138 message.append(" developer tools such as capture-replay libraries, ");
139 }
140 if (special_uses.find("debugging") != std::string::npos) {
141 message.append("use by applications when debugging, ");
142 }
143 if (special_uses.find("glemulation") != std::string::npos) {
144 message.append(
145 "OpenGL and/or OpenGL ES emulation layers, and applications ported from those APIs, by adding functionality "
146 "specific to those APIs, ");
147 }
148 message.append("and it is strongly recommended that they be otherwise avoided");
149
150 skip |= LogWarning(instance, vuid, "%s(): Attempting to enable extension %s, but this extension %s.", api_name,
151 extension_name, message.c_str());
152 }
153 return skip;
154}
155
Camden5b184be2019-08-13 07:50:19 -0600156bool BestPractices::PreCallValidateCreateInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500157 VkInstance* pInstance) const {
Camden5b184be2019-08-13 07:50:19 -0600158 bool skip = false;
159
160 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
161 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kDeviceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800162 skip |= LogWarning(instance, kVUID_BestPractices_CreateInstance_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700163 "vkCreateInstance(): Attempting to enable Device Extension %s at CreateInstance time.",
164 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600165 }
Mark Lobodzinski17d8dc62020-06-03 08:48:58 -0600166 uint32_t specified_version =
167 (pCreateInfo->pApplicationInfo ? pCreateInfo->pApplicationInfo->apiVersion : VK_API_VERSION_1_0);
168 skip |= ValidateDeprecatedExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i], specified_version,
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700169 kVUID_BestPractices_CreateInstance_DeprecatedExtension);
Mark Lobodzinskia431b772020-11-10 08:12:13 -0700170 skip |= ValidateSpecialUseExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i],
171 kVUID_BestPractices_CreateInstance_SpecialUseExtension);
Camden5b184be2019-08-13 07:50:19 -0600172 }
173
174 return skip;
175}
176
177void BestPractices::PreCallRecordCreateInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator,
178 VkInstance* pInstance) {
Mark Lobodzinski97484d62020-03-03 11:57:41 -0700179 ValidationStateTracker::PreCallRecordCreateInstance(pCreateInfo, pAllocator, pInstance);
Sam Walls53bf7652020-04-21 17:35:15 +0100180
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700181 if (pCreateInfo != nullptr && pCreateInfo->pApplicationInfo != nullptr) {
Sam Walls53bf7652020-04-21 17:35:15 +0100182 instance_api_version = pCreateInfo->pApplicationInfo->apiVersion;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700183 } else {
Sam Walls53bf7652020-04-21 17:35:15 +0100184 instance_api_version = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700185 }
Camden5b184be2019-08-13 07:50:19 -0600186}
187
188bool BestPractices::PreCallValidateCreateDevice(VkPhysicalDevice physicalDevice, const VkDeviceCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500189 const VkAllocationCallbacks* pAllocator, VkDevice* pDevice) const {
Camden5b184be2019-08-13 07:50:19 -0600190 bool skip = false;
191
192 // get API version of physical device passed when creating device.
193 VkPhysicalDeviceProperties physical_device_properties{};
194 DispatchGetPhysicalDeviceProperties(physicalDevice, &physical_device_properties);
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500195 auto device_api_version = physical_device_properties.apiVersion;
Camden5b184be2019-08-13 07:50:19 -0600196
197 // check api versions and warn if instance api Version is higher than version on device.
198 if (instance_api_version > device_api_version) {
Mark Lobodzinski60880782020-08-11 08:02:07 -0600199 std::string inst_api_name = StringAPIVersion(instance_api_version);
200 std::string dev_api_name = StringAPIVersion(device_api_version);
Camden5b184be2019-08-13 07:50:19 -0600201
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700202 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_API_Mismatch,
203 "vkCreateDevice(): API Version of current instance, %s is higher than API Version on device, %s",
204 inst_api_name.c_str(), dev_api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -0600205 }
206
207 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
208 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kInstanceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800209 skip |= LogWarning(instance, kVUID_BestPractices_CreateDevice_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700210 "vkCreateDevice(): Attempting to enable Instance Extension %s at CreateDevice time.",
211 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600212 }
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700213 skip |= ValidateDeprecatedExtensions("CreateDevice", pCreateInfo->ppEnabledExtensionNames[i], instance_api_version,
214 kVUID_BestPractices_CreateDevice_DeprecatedExtension);
Mark Lobodzinskia431b772020-11-10 08:12:13 -0700215 skip |= ValidateSpecialUseExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i],
216 kVUID_BestPractices_CreateDevice_SpecialUseExtension);
Camden5b184be2019-08-13 07:50:19 -0600217 }
218
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600219 const auto bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
220 if ((bp_pd_state->vkGetPhysicalDeviceFeaturesState == UNCALLED) && (pCreateInfo->pEnabledFeatures != NULL)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700221 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_PDFeaturesNotCalled,
222 "vkCreateDevice() called before getting physical device features from vkGetPhysicalDeviceFeatures().");
Camden83a9c372019-08-14 11:41:38 -0600223 }
224
Szilard Papp7d2c7952020-06-22 14:38:13 +0100225 if ((VendorCheckEnabled(kBPVendorArm)) && (pCreateInfo->pEnabledFeatures != nullptr) &&
226 (pCreateInfo->pEnabledFeatures->robustBufferAccess == VK_TRUE)) {
227 skip |= LogPerformanceWarning(
228 device, kVUID_BestPractices_CreateDevice_RobustBufferAccess,
229 "%s vkCreateDevice() called with enabled robustBufferAccess. Use robustBufferAccess as a debugging tool during "
230 "development. Enabling it causes loss in performance for accesses to uniform buffers and shader storage "
231 "buffers. Disable robustBufferAccess in release builds. Only leave it enabled if the application use-case "
232 "requires the additional level of reliability due to the use of unverified user-supplied draw parameters.",
233 VendorSpecificTag(kBPVendorArm));
234 }
235
Camden5b184be2019-08-13 07:50:19 -0600236 return skip;
237}
238
239bool BestPractices::PreCallValidateCreateBuffer(VkDevice device, const VkBufferCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500240 const VkAllocationCallbacks* pAllocator, VkBuffer* pBuffer) const {
Camden5b184be2019-08-13 07:50:19 -0600241 bool skip = false;
242
243 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700244 std::stringstream buffer_hex;
245 buffer_hex << "0x" << std::hex << HandleToUint64(pBuffer);
Camden5b184be2019-08-13 07:50:19 -0600246
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700247 skip |= LogWarning(
248 device, kVUID_BestPractices_SharingModeExclusive,
249 "Warning: Buffer (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
250 "(queueFamilyIndexCount of %" PRIu32 ").",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700251 buffer_hex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600252 }
253
254 return skip;
255}
256
257bool BestPractices::PreCallValidateCreateImage(VkDevice device, const VkImageCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500258 const VkAllocationCallbacks* pAllocator, VkImage* pImage) const {
Camden5b184be2019-08-13 07:50:19 -0600259 bool skip = false;
260
261 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700262 std::stringstream image_hex;
263 image_hex << "0x" << std::hex << HandleToUint64(pImage);
Camden5b184be2019-08-13 07:50:19 -0600264
265 skip |=
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700266 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
267 "Warning: Image (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
268 "(queueFamilyIndexCount of %" PRIu32 ").",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700269 image_hex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600270 }
271
Attilio Provenzano02859b22020-02-27 14:17:28 +0000272 if (VendorCheckEnabled(kBPVendorArm)) {
273 if (pCreateInfo->samples > kMaxEfficientSamplesArm) {
274 skip |= LogPerformanceWarning(
275 device, kVUID_BestPractices_CreateImage_TooLargeSampleCount,
276 "%s vkCreateImage(): Trying to create an image with %u samples. "
277 "The hardware revision may not have full throughput for framebuffers with more than %u samples.",
278 VendorSpecificTag(kBPVendorArm), static_cast<uint32_t>(pCreateInfo->samples), kMaxEfficientSamplesArm);
279 }
280
281 if (pCreateInfo->samples > VK_SAMPLE_COUNT_1_BIT && !(pCreateInfo->usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT)) {
282 skip |= LogPerformanceWarning(
283 device, kVUID_BestPractices_CreateImage_NonTransientMSImage,
284 "%s vkCreateImage(): Trying to create a multisampled image, but createInfo.usage did not have "
285 "VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. Multisampled images may be resolved on-chip, "
286 "and do not need to be backed by physical storage. "
287 "TRANSIENT_ATTACHMENT allows tiled GPUs to not back the multisampled image with physical memory.",
288 VendorSpecificTag(kBPVendorArm));
289 }
290 }
291
Camden5b184be2019-08-13 07:50:19 -0600292 return skip;
293}
294
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +0100295void BestPractices::PreCallRecordDestroyImage(VkDevice device, VkImage image, const VkAllocationCallbacks *pAllocator) {
296 ValidationStateTracker::PreCallRecordDestroyImage(device, image, pAllocator);
297 ReleaseImageUsageState(image);
298}
299
Hans-Kristian Arntzen92664eb2021-03-29 12:19:48 +0200300void BestPractices::PreCallRecordDestroySwapchainKHR(VkDevice device, VkSwapchainKHR swapchain, const VkAllocationCallbacks* pAllocator) {
Tony-LunarG299187b2021-05-28 09:29:12 -0600301 if (VK_NULL_HANDLE != swapchain) {
302 SWAPCHAIN_NODE* chain = GetSwapchainState(swapchain);
303 for (auto& image : chain->images) {
304 if (image.image_state) {
305 ReleaseImageUsageState(image.image_state->image());
306 }
307 }
Hans-Kristian Arntzen92664eb2021-03-29 12:19:48 +0200308 }
309 ValidationStateTracker::PreCallRecordDestroySwapchainKHR(device, swapchain, pAllocator);
310}
311
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +0100312IMAGE_STATE_BP* BestPractices::GetImageUsageState(VkImage vk_image) {
313 auto itr = imageUsageMap.find(vk_image);
314 if (itr != imageUsageMap.end()) {
315 return &itr->second;
316 } else {
317 auto& state = imageUsageMap[vk_image];
318 IMAGE_STATE* image = GetImageState(vk_image);
319 state.image = image;
320 state.usages.resize(image->createInfo.arrayLayers);
321 for (auto& mips : state.usages) {
322 mips.resize(image->createInfo.mipLevels, IMAGE_SUBRESOURCE_USAGE_BP::UNDEFINED);
323 }
324 return &state;
325 }
326}
327
328void BestPractices::ReleaseImageUsageState(VkImage image) {
329 auto itr = imageUsageMap.find(image);
330 if (itr != imageUsageMap.end()) {
331 imageUsageMap.erase(itr);
332 }
333}
334
Camden5b184be2019-08-13 07:50:19 -0600335bool BestPractices::PreCallValidateCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500336 const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain) const {
Camden5b184be2019-08-13 07:50:19 -0600337 bool skip = false;
338
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600339 const auto* bp_pd_state = GetPhysicalDeviceStateBP();
340 if (bp_pd_state) {
341 if (bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState == UNCALLED) {
342 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
343 "vkCreateSwapchainKHR() called before getting surface capabilities from "
344 "vkGetPhysicalDeviceSurfaceCapabilitiesKHR().");
345 }
Camden83a9c372019-08-14 11:41:38 -0600346
Shannon McPherson73e58c82021-03-05 17:14:26 -0700347 if ((pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR) &&
348 (bp_pd_state->vkGetPhysicalDeviceSurfacePresentModesKHRState != QUERY_DETAILS)) {
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600349 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
350 "vkCreateSwapchainKHR() called before getting surface present mode(s) from "
351 "vkGetPhysicalDeviceSurfacePresentModesKHR().");
352 }
Camden83a9c372019-08-14 11:41:38 -0600353
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600354 if (bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState != QUERY_DETAILS) {
355 skip |= LogWarning(
356 device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
357 "vkCreateSwapchainKHR() called before getting surface format(s) from vkGetPhysicalDeviceSurfaceFormatsKHR().");
358 }
Camden83a9c372019-08-14 11:41:38 -0600359 }
360
Camden5b184be2019-08-13 07:50:19 -0600361 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700362 skip |=
363 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
Mark Lobodzinski019f4e32020-04-13 11:01:35 -0600364 "Warning: A Swapchain is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while "
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700365 "specifying multiple queues (queueFamilyIndexCount of %" PRIu32 ").",
366 pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600367 }
368
Szilard Papp48a6da32020-06-10 14:41:59 +0100369 if (pCreateInfo->minImageCount == 2) {
370 skip |= LogPerformanceWarning(
371 device, kVUID_BestPractices_SuboptimalSwapchainImageCount,
372 "Warning: A Swapchain is being created with minImageCount set to %" PRIu32
373 ", which means double buffering is going "
374 "to be used. Using double buffering and vsync locks rendering to an integer fraction of the vsync rate. In turn, "
375 "reducing the performance of the application if rendering is slower than vsync. Consider setting minImageCount to "
376 "3 to use triple buffering to maximize performance in such cases.",
377 pCreateInfo->minImageCount);
378 }
379
Szilard Pappd5f0f812020-06-22 09:01:29 +0100380 if (VendorCheckEnabled(kBPVendorArm) && (pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR)) {
381 skip |= LogWarning(device, kVUID_BestPractices_CreateSwapchain_PresentMode,
382 "%s Warning: Swapchain is not being created with presentation mode \"VK_PRESENT_MODE_FIFO_KHR\". "
383 "Prefer using \"VK_PRESENT_MODE_FIFO_KHR\" to avoid unnecessary CPU and GPU load and save power. "
384 "Presentation modes which are not FIFO will present the latest available frame and discard other "
385 "frame(s) if any.",
386 VendorSpecificTag(kBPVendorArm));
387 }
388
Camden5b184be2019-08-13 07:50:19 -0600389 return skip;
390}
391
392bool BestPractices::PreCallValidateCreateSharedSwapchainsKHR(VkDevice device, uint32_t swapchainCount,
393 const VkSwapchainCreateInfoKHR* pCreateInfos,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500394 const VkAllocationCallbacks* pAllocator,
395 VkSwapchainKHR* pSwapchains) const {
Camden5b184be2019-08-13 07:50:19 -0600396 bool skip = false;
397
398 for (uint32_t i = 0; i < swapchainCount; i++) {
399 if ((pCreateInfos[i].queueFamilyIndexCount > 1) && (pCreateInfos[i].imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700400 skip |= LogWarning(
401 device, kVUID_BestPractices_SharingModeExclusive,
402 "Warning: A shared swapchain (index %" PRIu32
403 ") is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple "
404 "queues (queueFamilyIndexCount of %" PRIu32 ").",
405 i, pCreateInfos[i].queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600406 }
407 }
408
409 return skip;
410}
411
412bool BestPractices::PreCallValidateCreateRenderPass(VkDevice device, const VkRenderPassCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500413 const VkAllocationCallbacks* pAllocator, VkRenderPass* pRenderPass) const {
Camden5b184be2019-08-13 07:50:19 -0600414 bool skip = false;
415
416 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; ++i) {
417 VkFormat format = pCreateInfo->pAttachments[i].format;
418 if (pCreateInfo->pAttachments[i].initialLayout == VK_IMAGE_LAYOUT_UNDEFINED) {
419 if ((FormatIsColor(format) || FormatHasDepth(format)) &&
420 pCreateInfo->pAttachments[i].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700421 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
422 "Render pass has an attachment with loadOp == VK_ATTACHMENT_LOAD_OP_LOAD and "
423 "initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
424 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
425 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600426 }
427 if (FormatHasStencil(format) && pCreateInfo->pAttachments[i].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700428 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
429 "Render pass has an attachment with stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD "
430 "and initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
431 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
432 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600433 }
434 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000435
436 const auto& attachment = pCreateInfo->pAttachments[i];
437 if (attachment.samples > VK_SAMPLE_COUNT_1_BIT) {
438 bool access_requires_memory =
439 attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD || attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE;
440
441 if (FormatHasStencil(format)) {
442 access_requires_memory |= attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
443 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE;
444 }
445
446 if (access_requires_memory) {
447 skip |= LogPerformanceWarning(
448 device, kVUID_BestPractices_CreateRenderPass_ImageRequiresMemory,
449 "Attachment %u in the VkRenderPass is a multisampled image with %u samples, but it uses loadOp/storeOp "
450 "which requires accessing data from memory. Multisampled images should always be loadOp = CLEAR or DONT_CARE, "
451 "storeOp = DONT_CARE. This allows the implementation to use lazily allocated memory effectively.",
452 i, static_cast<uint32_t>(attachment.samples));
453 }
454 }
Camden5b184be2019-08-13 07:50:19 -0600455 }
456
457 for (uint32_t dependency = 0; dependency < pCreateInfo->dependencyCount; dependency++) {
458 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].srcStageMask);
459 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].dstStageMask);
460 }
461
462 return skip;
463}
464
Tony-LunarG767180f2020-04-23 14:03:59 -0600465bool BestPractices::ValidateAttachments(const VkRenderPassCreateInfo2* rpci, uint32_t attachmentCount,
466 const VkImageView* image_views) const {
467 bool skip = false;
468
469 // Check for non-transient attachments that should be transient and vice versa
470 for (uint32_t i = 0; i < attachmentCount; ++i) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200471 const auto& attachment = rpci->pAttachments[i];
Tony-LunarG767180f2020-04-23 14:03:59 -0600472 bool attachment_should_be_transient =
473 (attachment.loadOp != VK_ATTACHMENT_LOAD_OP_LOAD && attachment.storeOp != VK_ATTACHMENT_STORE_OP_STORE);
474
475 if (FormatHasStencil(attachment.format)) {
476 attachment_should_be_transient &= (attachment.stencilLoadOp != VK_ATTACHMENT_LOAD_OP_LOAD &&
477 attachment.stencilStoreOp != VK_ATTACHMENT_STORE_OP_STORE);
478 }
479
480 auto view_state = GetImageViewState(image_views[i]);
481 if (view_state) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200482 const auto& ivci = view_state->create_info;
483 const auto& ici = GetImageState(ivci.image)->createInfo;
Tony-LunarG767180f2020-04-23 14:03:59 -0600484
485 bool image_is_transient = (ici.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) != 0;
486
487 // The check for an image that should not be transient applies to all GPUs
488 if (!attachment_should_be_transient && image_is_transient) {
489 skip |= LogPerformanceWarning(
490 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldNotBeTransient,
491 "Attachment %u in VkFramebuffer uses loadOp/storeOps which need to access physical memory, "
492 "but the image backing the image view has VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
493 "Physical memory will need to be backed lazily to this image, potentially causing stalls.",
494 i);
495 }
496
497 bool supports_lazy = false;
498 for (uint32_t j = 0; j < phys_dev_mem_props.memoryTypeCount; j++) {
499 if (phys_dev_mem_props.memoryTypes[j].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
500 supports_lazy = true;
501 }
502 }
503
504 // The check for an image that should be transient only applies to GPUs supporting
505 // lazily allocated memory
506 if (supports_lazy && attachment_should_be_transient && !image_is_transient) {
507 skip |= LogPerformanceWarning(
508 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldBeTransient,
509 "Attachment %u in VkFramebuffer uses loadOp/storeOps which never have to be backed by physical memory, "
510 "but the image backing the image view does not have VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
511 "You can save physical memory by using transient attachment backed by lazily allocated memory here.",
512 i);
513 }
514 }
515 }
516 return skip;
517}
518
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000519bool BestPractices::PreCallValidateCreateFramebuffer(VkDevice device, const VkFramebufferCreateInfo* pCreateInfo,
520 const VkAllocationCallbacks* pAllocator, VkFramebuffer* pFramebuffer) const {
521 bool skip = false;
522
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000523 auto rp_state = GetRenderPassState(pCreateInfo->renderPass);
Mike Schuchardt2df08912020-12-15 16:28:09 -0800524 if (rp_state && !(pCreateInfo->flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT)) {
Tony-LunarG767180f2020-04-23 14:03:59 -0600525 skip = ValidateAttachments(rp_state->createInfo.ptr(), pCreateInfo->attachmentCount, pCreateInfo->pAttachments);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000526 }
527
528 return skip;
529}
530
Sam Wallse746d522020-03-16 21:20:23 +0000531bool BestPractices::PreCallValidateAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
532 VkDescriptorSet* pDescriptorSets, void* ads_state_data) const {
533 bool skip = false;
534 skip |= ValidationStateTracker::PreCallValidateAllocateDescriptorSets(device, pAllocateInfo, pDescriptorSets, ads_state_data);
535
536 if (!skip) {
537 const auto& pool_handle = pAllocateInfo->descriptorPool;
538 auto iter = descriptor_pool_freed_count.find(pool_handle);
539 // if the number of freed sets > 0, it implies they could be recycled instead if desirable
540 // this warning is specific to Arm
541 if (VendorCheckEnabled(kBPVendorArm) && iter != descriptor_pool_freed_count.end() && iter->second > 0) {
542 skip |= LogPerformanceWarning(
543 device, kVUID_BestPractices_AllocateDescriptorSets_SuboptimalReuse,
544 "%s Descriptor set memory was allocated via vkAllocateDescriptorSets() for sets which were previously freed in the "
545 "same logical device. On some drivers or architectures it may be most optimal to re-use existing descriptor sets.",
546 VendorSpecificTag(kBPVendorArm));
547 }
548 }
549
550 return skip;
551}
552
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600553void BestPractices::ManualPostCallRecordAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
554 VkDescriptorSet* pDescriptorSets, VkResult result, void* ads_state) {
Sam Wallse746d522020-03-16 21:20:23 +0000555 if (result == VK_SUCCESS) {
556 // find the free count for the pool we allocated into
557 auto iter = descriptor_pool_freed_count.find(pAllocateInfo->descriptorPool);
558 if (iter != descriptor_pool_freed_count.end()) {
559 // we record successful allocations by subtracting the allocation count from the last recorded free count
560 const auto alloc_count = pAllocateInfo->descriptorSetCount;
561 // clamp the unsigned subtraction to the range [0, last_free_count]
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700562 if (iter->second > alloc_count) {
Sam Wallse746d522020-03-16 21:20:23 +0000563 iter->second -= alloc_count;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700564 } else {
Sam Wallse746d522020-03-16 21:20:23 +0000565 iter->second = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700566 }
Sam Wallse746d522020-03-16 21:20:23 +0000567 }
568 }
569}
570
571void BestPractices::PostCallRecordFreeDescriptorSets(VkDevice device, VkDescriptorPool descriptorPool, uint32_t descriptorSetCount,
572 const VkDescriptorSet* pDescriptorSets, VkResult result) {
573 ValidationStateTracker::PostCallRecordFreeDescriptorSets(device, descriptorPool, descriptorSetCount, pDescriptorSets, result);
574 if (result == VK_SUCCESS) {
575 // we want to track frees because we're interested in suggesting re-use
576 auto iter = descriptor_pool_freed_count.find(descriptorPool);
577 if (iter == descriptor_pool_freed_count.end()) {
Jeremy Gebbencbf22862021-03-03 12:01:22 -0700578 descriptor_pool_freed_count.emplace(descriptorPool, descriptorSetCount);
Sam Wallse746d522020-03-16 21:20:23 +0000579 } else {
580 iter->second += descriptorSetCount;
581 }
582 }
583}
584
Camden5b184be2019-08-13 07:50:19 -0600585bool BestPractices::PreCallValidateAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500586 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory) const {
Camden5b184be2019-08-13 07:50:19 -0600587 bool skip = false;
588
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500589 if (num_mem_objects + 1 > kMemoryObjectWarningLimit) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700590 skip |= LogPerformanceWarning(device, kVUID_BestPractices_AllocateMemory_TooManyObjects,
591 "Performance Warning: This app has > %" PRIu32 " memory objects.", kMemoryObjectWarningLimit);
Camden5b184be2019-08-13 07:50:19 -0600592 }
593
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000594 if (pAllocateInfo->allocationSize < kMinDeviceAllocationSize) {
595 skip |= LogPerformanceWarning(
596 device, kVUID_BestPractices_AllocateMemory_SmallAllocation,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600597 "vkAllocateMemory(): Allocating a VkDeviceMemory of size %" PRIu64 ". This is a very small allocation (current "
598 "threshold is %" PRIu64 " bytes). "
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000599 "You should make large allocations and sub-allocate from one large VkDeviceMemory.",
600 pAllocateInfo->allocationSize, kMinDeviceAllocationSize);
601 }
602
Camden83a9c372019-08-14 11:41:38 -0600603 // TODO: Insert get check for GetPhysicalDeviceMemoryProperties once the state is tracked in the StateTracker
604
605 return skip;
606}
607
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600608void BestPractices::ManualPostCallRecordAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
609 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory,
610 VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700611 if (result != VK_SUCCESS) {
612 static std::vector<VkResult> error_codes = {VK_ERROR_OUT_OF_HOST_MEMORY, VK_ERROR_OUT_OF_DEVICE_MEMORY,
613 VK_ERROR_TOO_MANY_OBJECTS, VK_ERROR_INVALID_EXTERNAL_HANDLE,
Mike Schuchardt2df08912020-12-15 16:28:09 -0800614 VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS};
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700615 static std::vector<VkResult> success_codes = {};
Nathaniel Cesariodb3f43f2021-05-12 09:08:23 -0600616 ValidateReturnCodes("vkAllocateMemory", result, error_codes, success_codes);
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700617 return;
618 }
619 num_mem_objects++;
620}
Camden Stocker9738af92019-10-16 13:54:03 -0700621
Mark Lobodzinskide15e582020-04-29 08:06:00 -0600622void BestPractices::ValidateReturnCodes(const char* api_name, VkResult result, const std::vector<VkResult>& error_codes,
623 const std::vector<VkResult>& success_codes) const {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700624 auto error = std::find(error_codes.begin(), error_codes.end(), result);
625 if (error != error_codes.end()) {
Gareth Webb586c46b2021-01-13 11:17:22 +0000626 static const std::vector<VkResult> common_failure_codes = {VK_ERROR_OUT_OF_DATE_KHR,
627 VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT};
628
629 auto common_failure = std::find(common_failure_codes.begin(), common_failure_codes.end(), result);
630 if (common_failure != common_failure_codes.end()) {
631 LogInfo(instance, kVUID_BestPractices_Failure_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
632 } else {
633 LogWarning(instance, kVUID_BestPractices_Error_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
634 }
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700635 return;
636 }
637 auto success = std::find(success_codes.begin(), success_codes.end(), result);
638 if (success != success_codes.end()) {
Mark Lobodzinskie7215152020-05-11 08:21:23 -0600639 LogInfo(instance, kVUID_BestPractices_NonSuccess_Result, "%s(): Returned non-success return code %s.", api_name,
640 string_VkResult(result));
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500641 }
642}
643
Jeff Bolz5c801d12019-10-09 10:38:45 -0500644bool BestPractices::PreCallValidateFreeMemory(VkDevice device, VkDeviceMemory memory,
645 const VkAllocationCallbacks* pAllocator) const {
Mark Lobodzinski91e50bf2020-01-14 09:55:11 -0700646 if (memory == VK_NULL_HANDLE) return false;
Camden83a9c372019-08-14 11:41:38 -0600647 bool skip = false;
648
Camden Stocker9738af92019-10-16 13:54:03 -0700649 const DEVICE_MEMORY_STATE* mem_info = ValidationStateTracker::GetDevMemState(memory);
Camden83a9c372019-08-14 11:41:38 -0600650
Jeremy Gebben5570abe2021-05-16 18:35:13 -0600651 for (const auto& node: mem_info->ObjectBindings()) {
652 const auto& obj = node->Handle();
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600653 LogObjectList objlist(device);
654 objlist.add(obj);
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -0600655 objlist.add(mem_info->mem());
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600656 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 -0600657 report_data->FormatHandle(obj).c_str(), report_data->FormatHandle(mem_info->mem()).c_str());
Camden83a9c372019-08-14 11:41:38 -0600658 }
659
Camden5b184be2019-08-13 07:50:19 -0600660 return skip;
661}
662
663void BestPractices::PreCallRecordFreeMemory(VkDevice device, VkDeviceMemory memory, const VkAllocationCallbacks* pAllocator) {
Mark Lobodzinski97484d62020-03-03 11:57:41 -0700664 ValidationStateTracker::PreCallRecordFreeMemory(device, memory, pAllocator);
Camden5b184be2019-08-13 07:50:19 -0600665 if (memory != VK_NULL_HANDLE) {
666 num_mem_objects--;
667 }
668}
669
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000670bool BestPractices::ValidateBindBufferMemory(VkBuffer buffer, VkDeviceMemory memory, const char* api_name) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600671 bool skip = false;
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500672 const BUFFER_STATE* buffer_state = GetBufferState(buffer);
Camden Stockerb603cc82019-09-03 10:09:02 -0600673
sfricke-samsunge2441192019-11-06 14:07:57 -0800674 if (!buffer_state->memory_requirements_checked && !buffer_state->external_memory_handle) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700675 skip |= LogWarning(device, kVUID_BestPractices_BufferMemReqNotCalled,
676 "%s: Binding memory to %s but vkGetBufferMemoryRequirements() has not been called on that buffer.",
677 api_name, report_data->FormatHandle(buffer).c_str());
Camden Stockerb603cc82019-09-03 10:09:02 -0600678 }
679
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000680 const DEVICE_MEMORY_STATE* mem_state = GetDevMemState(memory);
681
682 if (mem_state->alloc_info.allocationSize == buffer_state->createInfo.size &&
683 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
684 skip |= LogPerformanceWarning(
685 device, kVUID_BestPractices_SmallDedicatedAllocation,
686 "%s: Trying to bind %s to a memory block which is fully consumed by the buffer. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600687 "The required size of the allocation is %" PRIu64 ", but smaller buffers like this should be sub-allocated from "
688 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000689 api_name, report_data->FormatHandle(buffer).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
690 }
691
Camden Stockerb603cc82019-09-03 10:09:02 -0600692 return skip;
693}
694
695bool BestPractices::PreCallValidateBindBufferMemory(VkDevice device, VkBuffer buffer, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500696 VkDeviceSize memoryOffset) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600697 bool skip = false;
698 const char* api_name = "BindBufferMemory()";
699
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000700 skip |= ValidateBindBufferMemory(buffer, memory, api_name);
Camden Stockerb603cc82019-09-03 10:09:02 -0600701
702 return skip;
703}
704
705bool BestPractices::PreCallValidateBindBufferMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500706 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600707 char api_name[64];
708 bool skip = false;
709
710 for (uint32_t i = 0; i < bindInfoCount; i++) {
711 sprintf(api_name, "vkBindBufferMemory2() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000712 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600713 }
714
715 return skip;
716}
Camden Stockerb603cc82019-09-03 10:09:02 -0600717
718bool BestPractices::PreCallValidateBindBufferMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500719 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600720 char api_name[64];
721 bool skip = false;
Camden Stockerb603cc82019-09-03 10:09:02 -0600722
Camden Stocker8b798ab2019-09-03 10:33:28 -0600723 for (uint32_t i = 0; i < bindInfoCount; i++) {
724 sprintf(api_name, "vkBindBufferMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000725 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600726 }
727
728 return skip;
729}
730
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000731bool BestPractices::ValidateBindImageMemory(VkImage image, VkDeviceMemory memory, const char* api_name) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600732 bool skip = false;
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500733 const IMAGE_STATE* image_state = GetImageState(image);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600734
sfricke-samsung71bc6572020-04-29 15:49:43 -0700735 if (image_state->disjoint == false) {
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600736 if (!image_state->memory_requirements_checked[0] && !image_state->external_memory_handle) {
sfricke-samsungd7ea5de2020-04-08 09:19:18 -0700737 skip |= LogWarning(device, kVUID_BestPractices_ImageMemReqNotCalled,
738 "%s: Binding memory to %s but vkGetImageMemoryRequirements() has not been called on that image.",
739 api_name, report_data->FormatHandle(image).c_str());
740 }
741 } else {
742 // TODO If binding disjoint image then this needs to check that VkImagePlaneMemoryRequirementsInfo was called for each
743 // plane.
Camden Stocker8b798ab2019-09-03 10:33:28 -0600744 }
745
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000746 const DEVICE_MEMORY_STATE* mem_state = GetDevMemState(memory);
747
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600748 if (mem_state->alloc_info.allocationSize == image_state->requirements[0].size &&
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000749 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
750 skip |= LogPerformanceWarning(
751 device, kVUID_BestPractices_SmallDedicatedAllocation,
752 "%s: Trying to bind %s to a memory block which is fully consumed by the image. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600753 "The required size of the allocation is %" PRIu64 ", but smaller images like this should be sub-allocated from "
754 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000755 api_name, report_data->FormatHandle(image).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
756 }
757
758 // If we're binding memory to a image which was created as TRANSIENT and the image supports LAZY allocation,
759 // make sure this type is actually used.
760 // This warning will only trigger if this layer is run on a platform that supports LAZILY_ALLOCATED_BIT
761 // (i.e.most tile - based renderers)
762 if (image_state->createInfo.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) {
763 bool supports_lazy = false;
764 uint32_t suggested_type = 0;
765
766 for (uint32_t i = 0; i < phys_dev_mem_props.memoryTypeCount; i++) {
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600767 if ((1u << i) & image_state->requirements[0].memoryTypeBits) {
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000768 if (phys_dev_mem_props.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
769 supports_lazy = true;
770 suggested_type = i;
771 break;
772 }
773 }
774 }
775
776 uint32_t allocated_properties = phys_dev_mem_props.memoryTypes[mem_state->alloc_info.memoryTypeIndex].propertyFlags;
777
778 if (supports_lazy && (allocated_properties & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) == 0) {
779 skip |= LogPerformanceWarning(
780 device, kVUID_BestPractices_NonLazyTransientImage,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600781 "%s: Attempting to bind memory type %u to VkImage which was created with TRANSIENT_ATTACHMENT_BIT,"
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000782 "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 -0600783 "%" PRIu64 " bytes of physical memory.",
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600784 api_name, mem_state->alloc_info.memoryTypeIndex, suggested_type, image_state->requirements[0].size);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000785 }
786 }
787
Camden Stocker8b798ab2019-09-03 10:33:28 -0600788 return skip;
789}
790
791bool BestPractices::PreCallValidateBindImageMemory(VkDevice device, VkImage image, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500792 VkDeviceSize memoryOffset) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600793 bool skip = false;
794 const char* api_name = "vkBindImageMemory()";
795
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000796 skip |= ValidateBindImageMemory(image, memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600797
798 return skip;
799}
800
801bool BestPractices::PreCallValidateBindImageMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500802 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600803 char api_name[64];
804 bool skip = false;
805
806 for (uint32_t i = 0; i < bindInfoCount; i++) {
807 sprintf(api_name, "vkBindImageMemory2() pBindInfos[%u]", i);
Mark Lobodzinski1f887d32020-12-30 15:31:33 -0700808 if (!LvlFindInChain<VkBindImageMemorySwapchainInfoKHR>(pBindInfos[i].pNext)) {
Tony-LunarG5e60b852020-04-27 11:27:54 -0600809 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
810 }
Camden Stocker8b798ab2019-09-03 10:33:28 -0600811 }
812
813 return skip;
814}
815
816bool BestPractices::PreCallValidateBindImageMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500817 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600818 char api_name[64];
819 bool skip = false;
820
821 for (uint32_t i = 0; i < bindInfoCount; i++) {
822 sprintf(api_name, "vkBindImageMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000823 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600824 }
825
826 return skip;
827}
Camden83a9c372019-08-14 11:41:38 -0600828
Attilio Provenzano02859b22020-02-27 14:17:28 +0000829static inline bool FormatHasFullThroughputBlendingArm(VkFormat format) {
830 switch (format) {
831 case VK_FORMAT_B10G11R11_UFLOAT_PACK32:
832 case VK_FORMAT_R16_SFLOAT:
833 case VK_FORMAT_R16G16_SFLOAT:
834 case VK_FORMAT_R16G16B16_SFLOAT:
835 case VK_FORMAT_R16G16B16A16_SFLOAT:
836 case VK_FORMAT_R32_SFLOAT:
837 case VK_FORMAT_R32G32_SFLOAT:
838 case VK_FORMAT_R32G32B32_SFLOAT:
839 case VK_FORMAT_R32G32B32A32_SFLOAT:
840 return false;
841
842 default:
843 return true;
844 }
845}
846
847bool BestPractices::ValidateMultisampledBlendingArm(uint32_t createInfoCount,
848 const VkGraphicsPipelineCreateInfo* pCreateInfos) const {
849 bool skip = false;
850
851 for (uint32_t i = 0; i < createInfoCount; i++) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700852 auto create_info = &pCreateInfos[i];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000853
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700854 if (!create_info->pColorBlendState || !create_info->pMultisampleState ||
855 create_info->pMultisampleState->rasterizationSamples == VK_SAMPLE_COUNT_1_BIT ||
856 create_info->pMultisampleState->sampleShadingEnable) {
Attilio Provenzano02859b22020-02-27 14:17:28 +0000857 return skip;
858 }
859
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700860 auto rp_state = GetRenderPassState(create_info->renderPass);
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200861 const auto& subpass = rp_state->createInfo.pSubpasses[create_info->subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000862
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700863 for (uint32_t j = 0; j < create_info->pColorBlendState->attachmentCount; j++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200864 const auto& blend_att = create_info->pColorBlendState->pAttachments[j];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000865 uint32_t att = subpass.pColorAttachments[j].attachment;
866
867 if (att != VK_ATTACHMENT_UNUSED && blend_att.blendEnable && blend_att.colorWriteMask) {
868 if (!FormatHasFullThroughputBlendingArm(rp_state->createInfo.pAttachments[att].format)) {
869 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultisampledBlending,
870 "%s vkCreateGraphicsPipelines() - createInfo #%u: Pipeline is multisampled and "
871 "color attachment #%u makes use "
872 "of a format which cannot be blended at full throughput when using MSAA.",
873 VendorSpecificTag(kBPVendorArm), i, j);
874 }
875 }
876 }
877 }
878
879 return skip;
880}
881
Camden5b184be2019-08-13 07:50:19 -0600882bool BestPractices::PreCallValidateCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
883 const VkGraphicsPipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -0600884 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500885 void* cgpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -0600886 bool skip = StateTracker::PreCallValidateCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos,
887 pAllocator, pPipelines, cgpl_state_data);
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600888 create_graphics_pipeline_api_state* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
Camden5b184be2019-08-13 07:50:19 -0600889
890 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700891 skip |= LogPerformanceWarning(
892 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
893 "Performance Warning: This vkCreateGraphicsPipelines call is creating multiple pipelines but is not using a "
894 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -0600895 }
896
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000897 for (uint32_t i = 0; i < createInfoCount; i++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200898 const auto& create_info = pCreateInfos[i];
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000899
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600900 if (!(cgpl_state->pipe_state[i]->active_shaders & VK_SHADER_STAGE_MESH_BIT_NV)) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200901 const auto& vertex_input = *create_info.pVertexInputState;
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600902 uint32_t count = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700903 for (uint32_t j = 0; j < vertex_input.vertexBindingDescriptionCount; j++) {
904 if (vertex_input.pVertexBindingDescriptions[j].inputRate == VK_VERTEX_INPUT_RATE_INSTANCE) {
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600905 count++;
906 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000907 }
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600908 if (count > kMaxInstancedVertexBuffers) {
909 skip |= LogPerformanceWarning(
910 device, kVUID_BestPractices_CreatePipelines_TooManyInstancedVertexBuffers,
911 "The pipeline is using %u instanced vertex buffers (current limit: %u), but this can be inefficient on the "
912 "GPU. If using instanced vertex attributes prefer interleaving them in a single buffer.",
913 count, kMaxInstancedVertexBuffers);
914 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000915 }
Attilio Provenzano02859b22020-02-27 14:17:28 +0000916
Szilard Pappaaf2da32020-06-22 10:37:35 +0100917 if ((pCreateInfos[i].pRasterizationState->depthBiasEnable) &&
918 (pCreateInfos[i].pRasterizationState->depthBiasConstantFactor == 0.0f) &&
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +0200919 (pCreateInfos[i].pRasterizationState->depthBiasSlopeFactor == 0.0f) &&
920 VendorCheckEnabled(kBPVendorArm)) {
921 skip |= LogPerformanceWarning(
922 device, kVUID_BestPractices_CreatePipelines_DepthBias_Zero,
923 "%s Performance Warning: This vkCreateGraphicsPipelines call is created with depthBiasEnable set to true "
924 "and both depthBiasConstantFactor and depthBiasSlopeFactor are set to 0. This can cause reduced "
925 "efficiency during rasterization. Consider disabling depthBias or increasing either "
926 "depthBiasConstantFactor or depthBiasSlopeFactor.",
927 VendorSpecificTag(kBPVendorArm));
Szilard Pappaaf2da32020-06-22 10:37:35 +0100928 }
929
Attilio Provenzano02859b22020-02-27 14:17:28 +0000930 skip |= VendorCheckEnabled(kBPVendorArm) && ValidateMultisampledBlendingArm(createInfoCount, pCreateInfos);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000931 }
932
Camden5b184be2019-08-13 07:50:19 -0600933 return skip;
934}
935
Hans-Kristian Arntzenb033ab12021-06-16 11:16:59 +0200936void BestPractices::PreCallRecordDestroyPipeline(VkDevice device, VkPipeline pipeline, const VkAllocationCallbacks *pAllocator)
937{
938 auto itr = graphicsPipelineCIs.find(pipeline);
939 if (itr != graphicsPipelineCIs.end()) {
940 graphicsPipelineCIs.erase(itr);
941 }
942 ValidationStateTracker::PreCallRecordDestroyPipeline(device, pipeline, pAllocator);
943}
944
Sam Walls0961ec02020-03-31 16:39:15 +0100945void BestPractices::ManualPostCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t count,
946 const VkGraphicsPipelineCreateInfo* pCreateInfos,
947 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
948 VkResult result, void* cgpl_state_data) {
949 for (size_t i = 0; i < count; i++) {
950 const auto* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
951 const VkPipeline pipeline_handle = pPipelines[i];
952
953 // record depth stencil state and color blend states for depth pre-pass tracking purposes
954 auto gp_cis = graphicsPipelineCIs.find(pipeline_handle);
955
956 // add the tracking state if it doesn't exist
957 if (gp_cis == graphicsPipelineCIs.end()) {
Jeremy Gebbencbf22862021-03-03 12:01:22 -0700958 auto result = graphicsPipelineCIs.emplace(pipeline_handle, GraphicsPipelineCIs{});
Sam Walls0961ec02020-03-31 16:39:15 +0100959
960 if (!result.second) continue;
961
962 gp_cis = result.first;
963 }
964
Hans-Kristian Arntzen42c0ef52021-06-14 14:46:25 +0200965 auto& create_info = cgpl_state->pCreateInfos[i];
966 GraphicsPipelineCIs &cis = gp_cis->second;
967
968 cis.colorBlendStateCI =
969 create_info.pColorBlendState
970 ? new safe_VkPipelineColorBlendStateCreateInfo(create_info.pColorBlendState)
Tony-LunarG412b1b72020-07-15 10:30:13 -0600971 : nullptr;
Hans-Kristian Arntzen42c0ef52021-06-14 14:46:25 +0200972 cis.depthStencilStateCI =
Tony-LunarG412b1b72020-07-15 10:30:13 -0600973 cgpl_state->pCreateInfos[i].pDepthStencilState
Hans-Kristian Arntzen42c0ef52021-06-14 14:46:25 +0200974 ? new safe_VkPipelineDepthStencilStateCreateInfo(create_info.pDepthStencilState)
Tony-LunarG412b1b72020-07-15 10:30:13 -0600975 : nullptr;
Hans-Kristian Arntzen42c0ef52021-06-14 14:46:25 +0200976
977 // Record which frame buffer attachments we should consider to be accessed when a draw call is performed.
978 RENDER_PASS_STATE* rp = GetRenderPassState(create_info.renderPass);
979 auto& subpass = rp->createInfo.pSubpasses[create_info.subpass];
980 cis.accessFramebufferAttachments.clear();
981
982 if (cis.colorBlendStateCI) {
983 for (uint32_t j = 0; j < cis.colorBlendStateCI->attachmentCount; j++) {
984 if (cis.colorBlendStateCI->pAttachments[j].colorWriteMask != 0) {
985 uint32_t attachment = subpass.pColorAttachments[j].attachment;
986 if (attachment != VK_ATTACHMENT_UNUSED) {
987 cis.accessFramebufferAttachments.push_back({ attachment, VK_IMAGE_ASPECT_COLOR_BIT });
988 }
989 }
990 }
991 }
992
993 if (cis.depthStencilStateCI && (cis.depthStencilStateCI->depthTestEnable ||
994 cis.depthStencilStateCI->depthBoundsTestEnable ||
995 cis.depthStencilStateCI->stencilTestEnable)) {
996 uint32_t attachment = subpass.pDepthStencilAttachment ?
997 subpass.pDepthStencilAttachment->attachment :
998 VK_ATTACHMENT_UNUSED;
999 if (attachment != VK_ATTACHMENT_UNUSED) {
1000 VkImageAspectFlags aspects = 0;
1001 if (cis.depthStencilStateCI->depthTestEnable || cis.depthStencilStateCI->depthBoundsTestEnable) {
1002 aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
1003 }
1004 if (cis.depthStencilStateCI->stencilTestEnable) {
1005 aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
1006 }
1007 cis.accessFramebufferAttachments.push_back({ attachment, aspects });
1008 }
1009 }
Sam Walls0961ec02020-03-31 16:39:15 +01001010 }
1011}
1012
Camden5b184be2019-08-13 07:50:19 -06001013bool BestPractices::PreCallValidateCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
1014 const VkComputePipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -06001015 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001016 void* ccpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -06001017 bool skip = StateTracker::PreCallValidateCreateComputePipelines(device, pipelineCache, createInfoCount, pCreateInfos,
1018 pAllocator, pPipelines, ccpl_state_data);
Camden5b184be2019-08-13 07:50:19 -06001019
1020 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001021 skip |= LogPerformanceWarning(
1022 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
1023 "Performance Warning: This vkCreateComputePipelines call is creating multiple pipelines but is not using a "
1024 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -06001025 }
1026
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001027 if (VendorCheckEnabled(kBPVendorArm)) {
1028 for (size_t i = 0; i < createInfoCount; i++) {
1029 skip |= ValidateCreateComputePipelineArm(pCreateInfos[i]);
1030 }
1031 }
1032
1033 return skip;
1034}
1035
1036bool BestPractices::ValidateCreateComputePipelineArm(const VkComputePipelineCreateInfo& createInfo) const {
1037 bool skip = false;
1038 auto* module = GetShaderModuleState(createInfo.stage.module);
sfricke-samsung8a7341a2021-02-28 07:30:21 -08001039 // Generate warnings about work group sizes based on active resources.
sfricke-samsung962cad92021-04-13 00:46:29 -07001040 auto entrypoint = module->FindEntrypoint(createInfo.stage.pName, createInfo.stage.stage);
sfricke-samsung8a7341a2021-02-28 07:30:21 -08001041 if (entrypoint == module->end()) return false;
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001042
1043 uint32_t x = 1, y = 1, z = 1;
sfricke-samsung962cad92021-04-13 00:46:29 -07001044 module->FindLocalSize(entrypoint, x, y, z);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001045
1046 uint32_t thread_count = x * y * z;
1047
1048 // Generate a priori warnings about work group sizes.
1049 if (thread_count > kMaxEfficientWorkGroupThreadCountArm) {
1050 skip |= LogPerformanceWarning(
1051 device, kVUID_BestPractices_CreateComputePipelines_ComputeWorkGroupSize,
1052 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, %u, "
1053 "%u) (%u threads total), has more threads than advised in a single work group. It is advised to use work "
1054 "groups with less than %u threads, especially when using barrier() or shared memory.",
1055 VendorSpecificTag(kBPVendorArm), x, y, z, thread_count, kMaxEfficientWorkGroupThreadCountArm);
1056 }
1057
1058 if (thread_count == 1 || ((x > 1) && (x & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
1059 ((y > 1) && (y & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
1060 ((z > 1) && (z & (kThreadGroupDispatchCountAlignmentArm - 1)))) {
1061 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeThreadGroupAlignment,
1062 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, "
1063 "%u, %u) is not aligned to %u "
1064 "threads. On Arm Mali architectures, not aligning work group sizes to %u may "
1065 "leave threads idle on the shader "
1066 "core.",
1067 VendorSpecificTag(kBPVendorArm), x, y, z, kThreadGroupDispatchCountAlignmentArm,
1068 kThreadGroupDispatchCountAlignmentArm);
1069 }
1070
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001071 bool has_writeable_descriptors = false;
locke-lunarg63e4daf2020-08-17 17:53:25 -06001072 bool has_atomic_descriptors = false;
sfricke-samsung962cad92021-04-13 00:46:29 -07001073 auto accessible_ids = module->MarkAccessibleIds(entrypoint);
locke-lunarg63e4daf2020-08-17 17:53:25 -06001074 auto descriptor_uses =
sfricke-samsung962cad92021-04-13 00:46:29 -07001075 module->CollectInterfaceByDescriptorSlot(accessible_ids, &has_writeable_descriptors, &has_atomic_descriptors);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001076
1077 unsigned dimensions = 0;
1078 if (x > 1) dimensions++;
1079 if (y > 1) dimensions++;
1080 if (z > 1) dimensions++;
1081 // Here the dimension will really depend on the dispatch grid, but assume it's 1D.
1082 dimensions = std::max(dimensions, 1u);
1083
1084 // If we're accessing images, we almost certainly want to have a 2D workgroup for cache reasons.
1085 // There are some false positives here. We could simply have a shader that does this within a 1D grid,
1086 // or we may have a linearly tiled image, but these cases are quite unlikely in practice.
1087 bool accesses_2d = false;
1088 for (const auto& usage : descriptor_uses) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001089 auto dim = module->GetShaderResourceDimensionality(usage.second);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001090 if (dim < 0) continue;
1091 auto spvdim = spv::Dim(dim);
1092 if (spvdim != spv::Dim1D && spvdim != spv::DimBuffer) accesses_2d = true;
1093 }
1094
1095 if (accesses_2d && dimensions < 2) {
1096 LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeSpatialLocality,
1097 "%s vkCreateComputePipelines(): compute shader has work group dimensions (%u, %u, %u), which "
1098 "suggests a 1D dispatch, but the shader is accessing 2D or 3D images. The shader may be "
1099 "exhibiting poor spatial locality with respect to one or more shader resources.",
1100 VendorSpecificTag(kBPVendorArm), x, y, z);
1101 }
1102
Camden5b184be2019-08-13 07:50:19 -06001103 return skip;
1104}
1105
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001106bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags flags) const {
Camden5b184be2019-08-13 07:50:19 -06001107 bool skip = false;
1108
1109 if (flags & VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001110 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1111 "You are using VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001112 } else if (flags & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001113 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1114 "You are using VK_PIPELINE_STAGE_ALL_COMMANDS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001115 }
1116
1117 return skip;
1118}
1119
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001120bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags2KHR flags) const {
1121 bool skip = false;
1122
1123 if (flags & VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR) {
1124 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1125 "You are using VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR when %s is called\n", api_name.c_str());
1126 } else if (flags & VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR) {
1127 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1128 "You are using VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR when %s is called\n", api_name.c_str());
1129 }
1130
1131 return skip;
1132}
1133
1134bool BestPractices::CheckDependencyInfo(const std::string& api_name, const VkDependencyInfoKHR& dep_info) const {
1135 bool skip = false;
1136 auto stage_masks = sync_utils::GetGlobalStageMasks(dep_info);
1137
1138 skip |= CheckPipelineStageFlags(api_name, stage_masks.src);
1139 skip |= CheckPipelineStageFlags(api_name, stage_masks.dst);
1140
1141 return skip;
1142}
1143
Mark Lobodzinski84101d72020-04-24 09:43:48 -06001144void BestPractices::ManualPostCallRecordQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo, VkResult result) {
Mark Lobodzinski9b133c12020-03-10 10:42:56 -06001145 for (uint32_t i = 0; i < pPresentInfo->swapchainCount; ++i) {
1146 auto swapchains_result = pPresentInfo->pResults ? pPresentInfo->pResults[i] : result;
1147 if (swapchains_result == VK_SUBOPTIMAL_KHR) {
1148 LogPerformanceWarning(
1149 pPresentInfo->pSwapchains[i], kVUID_BestPractices_SuboptimalSwapchain,
1150 "vkQueuePresentKHR: %s :VK_SUBOPTIMAL_KHR was returned. VK_SUBOPTIMAL_KHR - Presentation will still succeed, "
1151 "subject to the window resize behavior, but the swapchain is no longer configured optimally for the surface it "
1152 "targets. Applications should query updated surface information and recreate their swapchain at the next "
1153 "convenient opportunity.",
1154 report_data->FormatHandle(pPresentInfo->pSwapchains[i]).c_str());
1155 }
1156 }
1157}
1158
Jeff Bolz5c801d12019-10-09 10:38:45 -05001159bool BestPractices::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
1160 VkFence fence) const {
Camden5b184be2019-08-13 07:50:19 -06001161 bool skip = false;
1162
1163 for (uint32_t submit = 0; submit < submitCount; submit++) {
1164 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreCount; semaphore++) {
1165 skip |= CheckPipelineStageFlags("vkQueueSubmit", pSubmits[submit].pWaitDstStageMask[semaphore]);
1166 }
1167 }
1168
1169 return skip;
1170}
1171
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001172bool BestPractices::PreCallValidateQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR* pSubmits,
1173 VkFence fence) const {
1174 bool skip = false;
1175
1176 for (uint32_t submit = 0; submit < submitCount; submit++) {
1177 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreInfoCount; semaphore++) {
1178 skip |= CheckPipelineStageFlags("vkQueueSubmit2KHR", pSubmits[submit].pWaitSemaphoreInfos[semaphore].stageMask);
1179 }
1180 }
1181
1182 return skip;
1183}
1184
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001185bool BestPractices::PreCallValidateCreateCommandPool(VkDevice device, const VkCommandPoolCreateInfo* pCreateInfo,
1186 const VkAllocationCallbacks* pAllocator, VkCommandPool* pCommandPool) const {
1187 bool skip = false;
1188
1189 if (pCreateInfo->flags & VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT) {
1190 skip |= LogPerformanceWarning(
1191 device, kVUID_BestPractices_CreateCommandPool_CommandBufferReset,
1192 "vkCreateCommandPool(): VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT is set. Consider resetting entire "
1193 "pool instead.");
1194 }
1195
1196 return skip;
1197}
1198
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001199void BestPractices::PreCallRecordBeginCommandBuffer(VkCommandBuffer commandBuffer, const VkCommandBufferBeginInfo *pBeginInfo)
1200{
1201 // Clear state in case we are a secondary command buffer.
1202 auto& state = cbRenderPassState[commandBuffer];
1203 state = {};
1204 ValidationStateTracker::PreCallRecordBeginCommandBuffer(commandBuffer, pBeginInfo);
1205}
1206
1207void BestPractices::PreCallRecordDestroyCommandPool(VkDevice device, VkCommandPool commandPool,
1208 const VkAllocationCallbacks *pAllocation)
1209{
1210 COMMAND_POOL_STATE* pool = GetCommandPoolState(commandPool);
1211 if (pool) {
1212 for (auto& cb : pool->commandBuffers) {
1213 auto itr = cbRenderPassState.find(cb);
1214 if (itr != cbRenderPassState.end()) {
1215 cbRenderPassState.erase(itr);
1216 }
1217 }
1218 }
1219 ValidationStateTracker::PreCallRecordDestroyCommandPool(device, commandPool, pAllocation);
1220}
1221
1222void BestPractices::PreCallRecordFreeCommandBuffers(VkDevice device, VkCommandPool commandPool,
1223 uint32_t commandBufferCount, const VkCommandBuffer* pCommandBuffers) {
1224 for (uint32_t i = 0; i < commandBufferCount; i++) {
1225 auto itr = cbRenderPassState.find(pCommandBuffers[i]);
1226 if (itr != cbRenderPassState.end()) {
1227 cbRenderPassState.erase(itr);
1228 }
1229 }
1230 ValidationStateTracker::PreCallRecordFreeCommandBuffers(device, commandPool, commandBufferCount, pCommandBuffers);
1231}
1232
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001233bool BestPractices::PreCallValidateBeginCommandBuffer(VkCommandBuffer commandBuffer,
1234 const VkCommandBufferBeginInfo* pBeginInfo) const {
1235 bool skip = false;
1236
1237 if (pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT) {
1238 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_SimultaneousUse,
1239 "vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT is set.");
1240 }
1241
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001242 if (!(pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT) && VendorCheckEnabled(kBPVendorArm)) {
1243 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_OneTimeSubmit,
Attilio Provenzano02859b22020-02-27 14:17:28 +00001244 "%s vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT is not set. "
1245 "For best performance on Mali GPUs, consider setting ONE_TIME_SUBMIT by default.",
1246 VendorSpecificTag(kBPVendorArm));
1247 }
1248
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001249 return skip;
1250}
1251
Jeff Bolz5c801d12019-10-09 10:38:45 -05001252bool BestPractices::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001253 bool skip = false;
1254
1255 skip |= CheckPipelineStageFlags("vkCmdSetEvent", stageMask);
1256
1257 return skip;
1258}
1259
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001260bool BestPractices::PreCallValidateCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1261 const VkDependencyInfoKHR* pDependencyInfo) const {
1262 return CheckDependencyInfo("vkCmdSetEvent2KHR", *pDependencyInfo);
1263}
1264
Jeff Bolz5c801d12019-10-09 10:38:45 -05001265bool BestPractices::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
1266 VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001267 bool skip = false;
1268
1269 skip |= CheckPipelineStageFlags("vkCmdResetEvent", stageMask);
1270
1271 return skip;
1272}
1273
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001274bool BestPractices::PreCallValidateCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1275 VkPipelineStageFlags2KHR stageMask) const {
1276 bool skip = false;
1277
1278 skip |= CheckPipelineStageFlags("vkCmdResetEvent2KHR", stageMask);
1279
1280 return skip;
1281}
1282
Camden5b184be2019-08-13 07:50:19 -06001283bool BestPractices::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1284 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
1285 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1286 uint32_t bufferMemoryBarrierCount,
1287 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1288 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001289 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001290 bool skip = false;
1291
1292 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", srcStageMask);
1293 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", dstStageMask);
1294
1295 return skip;
1296}
1297
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001298bool BestPractices::PreCallValidateCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1299 const VkDependencyInfoKHR* pDependencyInfos) const {
1300 bool skip = false;
1301 for (uint32_t i = 0; i < eventCount; i++) {
1302 skip = CheckDependencyInfo("vkCmdWaitEvents2KHR", pDependencyInfos[i]);
1303 }
1304
1305 return skip;
1306}
1307
Camden5b184be2019-08-13 07:50:19 -06001308bool BestPractices::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
1309 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
1310 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1311 uint32_t bufferMemoryBarrierCount,
1312 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1313 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001314 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001315 bool skip = false;
1316
1317 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", srcStageMask);
1318 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", dstStageMask);
1319
1320 return skip;
1321}
1322
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001323bool BestPractices::PreCallValidateCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer,
1324 const VkDependencyInfoKHR* pDependencyInfo) const {
1325 return CheckDependencyInfo("vkCmdPipelineBarrier2KHR", *pDependencyInfo);
1326}
1327
Camden5b184be2019-08-13 07:50:19 -06001328bool BestPractices::PreCallValidateCmdWriteTimestamp(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001329 VkQueryPool queryPool, uint32_t query) const {
Camden5b184be2019-08-13 07:50:19 -06001330 bool skip = false;
1331
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001332 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp", static_cast<VkPipelineStageFlags>(pipelineStage));
1333
1334 return skip;
1335}
1336
1337bool BestPractices::PreCallValidateCmdWriteTimestamp2KHR(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
1338 VkQueryPool queryPool, uint32_t query) const {
1339 bool skip = false;
1340
1341 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp2KHR", pipelineStage);
Camden5b184be2019-08-13 07:50:19 -06001342
1343 return skip;
1344}
1345
Sam Walls0961ec02020-03-31 16:39:15 +01001346void BestPractices::PostCallRecordCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
1347 VkPipeline pipeline) {
1348 StateTracker::PostCallRecordCmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
1349
1350 if (pipelineBindPoint == VK_PIPELINE_BIND_POINT_GRAPHICS) {
1351 // check for depth/blend state tracking
1352 auto gp_cis = graphicsPipelineCIs.find(pipeline);
1353 if (gp_cis != graphicsPipelineCIs.end()) {
Hans-Kristian Arntzen09aff9d2021-06-14 15:17:02 +02001354 auto render_pass_state = cbRenderPassState.find(commandBuffer);
1355 if (render_pass_state == cbRenderPassState.end()) {
1356 auto result = cbRenderPassState.emplace(commandBuffer, RenderPassState{});
Sam Walls0961ec02020-03-31 16:39:15 +01001357
1358 if (!result.second) return;
1359
Hans-Kristian Arntzen09aff9d2021-06-14 15:17:02 +02001360 render_pass_state = result.first;
Sam Walls0961ec02020-03-31 16:39:15 +01001361 }
1362
1363 const auto* blend_state = gp_cis->second.colorBlendStateCI;
1364 const auto* stencil_state = gp_cis->second.depthStencilStateCI;
1365
1366 if (blend_state) {
1367 // assume the pipeline is depth-only unless any of the attachments have color writes enabled
Hans-Kristian Arntzen09aff9d2021-06-14 15:17:02 +02001368 render_pass_state->second.depthOnly = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001369 for (size_t i = 0; i < blend_state->attachmentCount; i++) {
1370 if (blend_state->pAttachments[i].colorWriteMask != 0) {
Hans-Kristian Arntzen09aff9d2021-06-14 15:17:02 +02001371 render_pass_state->second.depthOnly = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001372 }
1373 }
1374 }
1375
1376 // check for depth value usage
Hans-Kristian Arntzen09aff9d2021-06-14 15:17:02 +02001377 render_pass_state->second.depthEqualComparison = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001378
1379 if (stencil_state && stencil_state->depthTestEnable) {
1380 switch (stencil_state->depthCompareOp) {
1381 case VK_COMPARE_OP_EQUAL:
1382 case VK_COMPARE_OP_GREATER_OR_EQUAL:
1383 case VK_COMPARE_OP_LESS_OR_EQUAL:
Hans-Kristian Arntzen09aff9d2021-06-14 15:17:02 +02001384 render_pass_state->second.depthEqualComparison = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001385 break;
1386 default:
1387 break;
1388 }
1389 }
1390 } else {
1391 // reset depth pre-pass tracking
Hans-Kristian Arntzen09aff9d2021-06-14 15:17:02 +02001392 cbRenderPassState.emplace(commandBuffer, RenderPassState{});
Sam Walls0961ec02020-03-31 16:39:15 +01001393 }
1394 }
1395}
1396
Attilio Provenzano02859b22020-02-27 14:17:28 +00001397static inline bool RenderPassUsesAttachmentOnTile(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1398 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001399 const auto& subpass_info = createInfo.pSubpasses[subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001400
1401 // If an attachment is ever used as a color attachment,
1402 // resolve attachment or depth stencil attachment,
1403 // it needs to exist on tile at some point.
1404
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001405 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1406 if (subpass_info.pColorAttachments[i].attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001407 }
1408
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001409 if (subpass_info.pResolveAttachments) {
1410 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1411 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
1412 }
1413 }
1414
1415 if (subpass_info.pDepthStencilAttachment && subpass_info.pDepthStencilAttachment->attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001416 }
1417
1418 return false;
1419}
1420
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001421static inline bool RenderPassUsesAttachmentAsImageOnly(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1422 if (RenderPassUsesAttachmentOnTile(createInfo, attachment)) {
1423 return false;
1424 }
1425
1426 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001427 const auto& subpassInfo = createInfo.pSubpasses[subpass];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001428
1429 for (uint32_t i = 0; i < subpassInfo.inputAttachmentCount; i++) {
1430 if (subpassInfo.pInputAttachments[i].attachment == attachment) {
1431 return true;
1432 }
1433 }
1434 }
1435
1436 return false;
1437}
1438
Attilio Provenzano02859b22020-02-27 14:17:28 +00001439bool BestPractices::ValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1440 const VkRenderPassBeginInfo* pRenderPassBegin) const {
1441 bool skip = false;
1442
1443 if (!pRenderPassBegin) {
1444 return skip;
1445 }
1446
1447 auto rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
1448 if (rp_state) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08001449 if (rp_state->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07001450 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
Tony-LunarG767180f2020-04-23 14:03:59 -06001451 if (rpabi) {
1452 skip = ValidateAttachments(rp_state->createInfo.ptr(), rpabi->attachmentCount, rpabi->pAttachments);
1453 }
1454 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001455 // Check if any attachments have LOAD operation on them
1456 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001457 const auto& attachment = rp_state->createInfo.pAttachments[att];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001458
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001459 bool attachment_has_readback = false;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001460 if (!FormatHasStencil(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001461 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001462 }
1463
1464 if (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001465 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001466 }
1467
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001468 bool attachment_needs_readback = false;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001469
1470 // Check if the attachment is actually used in any subpass on-tile
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001471 if (attachment_has_readback && RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1472 attachment_needs_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001473 }
1474
1475 // Using LOAD_OP_LOAD is expensive on tiled GPUs, so flag it as a potential improvement
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001476 if (attachment_needs_readback && VendorCheckEnabled(kBPVendorArm)) {
1477 skip |= LogPerformanceWarning(
1478 device, kVUID_BestPractices_BeginRenderPass_AttachmentNeedsReadback,
1479 "%s Attachment #%u in render pass has begun with VK_ATTACHMENT_LOAD_OP_LOAD.\n"
1480 "Submitting this renderpass will cause the driver to inject a readback of the attachment "
1481 "which will copy in total %u pixels (renderArea = { %d, %d, %u, %u }) to the tile buffer.",
1482 VendorSpecificTag(kBPVendorArm), att,
1483 pRenderPassBegin->renderArea.extent.width * pRenderPassBegin->renderArea.extent.height,
1484 pRenderPassBegin->renderArea.offset.x, pRenderPassBegin->renderArea.offset.y,
1485 pRenderPassBegin->renderArea.extent.width, pRenderPassBegin->renderArea.extent.height);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001486 }
1487 }
1488 }
1489
1490 return skip;
1491}
1492
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001493void BestPractices::QueueValidateImageView(QueueCallbacks &funcs, const char* function_name,
1494 IMAGE_VIEW_STATE* view, IMAGE_SUBRESOURCE_USAGE_BP usage) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001495 if (view) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001496 QueueValidateImage(funcs, function_name, GetImageUsageState(view->create_info.image), usage, view->create_info.subresourceRange);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001497 }
1498}
1499
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001500void BestPractices::QueueValidateImage(QueueCallbacks &funcs, const char* function_name,
1501 IMAGE_STATE_BP* state, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001502 const VkImageSubresourceRange& subresource_range) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001503 IMAGE_STATE* image = state->image;
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02001504
1505 // If we're viewing a 3D slice, ignore base array layer.
1506 // The entire 3D subresource is accessed as one atomic unit.
1507 const uint32_t base_array_layer = image->createInfo.imageType == VK_IMAGE_TYPE_3D ? 0 : subresource_range.baseArrayLayer;
1508
1509 const uint32_t max_layers = image->createInfo.arrayLayers - base_array_layer;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001510 const uint32_t array_layers = std::min(subresource_range.layerCount, max_layers);
1511 const uint32_t max_levels = image->createInfo.mipLevels - subresource_range.baseMipLevel;
1512 const uint32_t mip_levels = std::min(image->createInfo.mipLevels, max_levels);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001513
1514 for (uint32_t layer = 0; layer < array_layers; layer++) {
1515 for (uint32_t level = 0; level < mip_levels; level++) {
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02001516 QueueValidateImage(funcs, function_name, state, usage, layer + base_array_layer,
1517 level + subresource_range.baseMipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001518 }
1519 }
1520}
1521
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001522void BestPractices::QueueValidateImage(QueueCallbacks &funcs, const char* function_name,
1523 IMAGE_STATE_BP* state, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001524 const VkImageSubresourceLayers& subresource_layers) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001525 IMAGE_STATE* image = state->image;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001526 const uint32_t max_layers = image->createInfo.arrayLayers - subresource_layers.baseArrayLayer;
1527 const uint32_t array_layers = std::min(subresource_layers.layerCount, max_layers);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001528
1529 for (uint32_t layer = 0; layer < array_layers; layer++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001530 QueueValidateImage(funcs, function_name, state, usage, layer + subresource_layers.baseArrayLayer, subresource_layers.mipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001531 }
1532}
1533
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001534void BestPractices::QueueValidateImage(QueueCallbacks &funcs, const char* function_name,
1535 IMAGE_STATE_BP* state, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001536 uint32_t array_layer, uint32_t mip_level) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001537 funcs.push_back([this, function_name, state, usage, array_layer, mip_level](const ValidationStateTracker*, const QUEUE_STATE*) -> bool {
1538 ValidateImageInQueue(function_name, state, usage, array_layer, mip_level);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001539 return false;
1540 });
1541}
1542
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001543void BestPractices::ValidateImageInQueueArm(const char* function_name, IMAGE_STATE* image,
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001544 IMAGE_SUBRESOURCE_USAGE_BP last_usage,
1545 IMAGE_SUBRESOURCE_USAGE_BP usage,
1546 uint32_t array_layer, uint32_t mip_level) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001547 // Swapchain images are implicitly read so clear after store is expected.
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001548 if (usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_CLEARED && last_usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_STORED &&
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001549 !image->is_swapchain_image) {
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001550 LogPerformanceWarning(
1551 device, kVUID_BestPractices_RenderPass_RedundantStore,
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001552 "%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 +02001553 "image was used, it was written to with STORE_OP_STORE. "
1554 "Storing to the image is probably redundant in this case, and wastes bandwidth on tile-based "
1555 "architectures.",
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001556 function_name, VendorSpecificTag(kBPVendorArm), array_layer, mip_level);
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001557 } 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 +02001558 LogPerformanceWarning(
1559 device, kVUID_BestPractices_RenderPass_RedundantClear,
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001560 "%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 +02001561 "image was used, it was written to with vkCmdClear*Image(). "
1562 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
1563 "tile-based architectures."
1564 "architectures.",
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001565 function_name, VendorSpecificTag(kBPVendorArm), array_layer, mip_level);
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01001566 } else if (usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE &&
1567 (last_usage == IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE ||
1568 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::CLEARED ||
1569 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE ||
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001570 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE)) {
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01001571 const char *last_cmd = nullptr;
1572 const char *vuid = nullptr;
1573 const char *suggestion = nullptr;
1574
1575 switch (last_usage) {
1576 case IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE:
1577 vuid = kVUID_BestPractices_RenderPass_BlitImage_LoadOpLoad;
1578 last_cmd = "vkCmdBlitImage";
1579 suggestion =
1580 "The blit is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
1581 "Rather than blitting, just render the source image in a fragment shader in this render pass, "
1582 "which avoids the memory roundtrip.";
1583 break;
1584 case IMAGE_SUBRESOURCE_USAGE_BP::CLEARED:
1585 vuid = kVUID_BestPractices_RenderPass_InefficientClear;
1586 last_cmd = "vkCmdClear*Image";
1587 suggestion =
1588 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
1589 "tile-based architectures. "
1590 "Use LOAD_OP_CLEAR instead to clear the image for free.";
1591 break;
1592 case IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE:
1593 vuid = kVUID_BestPractices_RenderPass_CopyImage_LoadOpLoad;
1594 last_cmd = "vkCmdCopy*Image";
1595 suggestion =
1596 "The copy is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
1597 "Rather than copying, just render the source image in a fragment shader in this render pass, "
1598 "which avoids the memory roundtrip.";
1599 break;
1600 case IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE:
1601 vuid = kVUID_BestPractices_RenderPass_ResolveImage_LoadOpLoad;
1602 last_cmd = "vkCmdResolveImage";
1603 suggestion =
1604 "The resolve is probably redundant in this case, and wastes a lot of bandwidth on tile-based architectures. "
1605 "Rather than resolving, and then loading, try to keep rendering in the same render pass, "
1606 "which avoids the memory roundtrip.";
1607 break;
1608 default:
1609 break;
1610 }
1611
1612 LogPerformanceWarning(
1613 device, vuid,
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001614 "%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 +01001615 "time image was used, it was written to with %s. %s",
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001616 function_name, VendorSpecificTag(kBPVendorArm), array_layer, mip_level, last_cmd, suggestion);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001617 }
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001618}
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001619
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001620void BestPractices::ValidateImageInQueue(const char* function_name, IMAGE_STATE_BP* state,
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001621 IMAGE_SUBRESOURCE_USAGE_BP usage, uint32_t array_layer,
1622 uint32_t mip_level) {
1623 IMAGE_STATE* image = state->image;
1624 IMAGE_SUBRESOURCE_USAGE_BP last_usage = state->usages[array_layer][mip_level];
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001625 state->usages[array_layer][mip_level] = usage;
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001626 if (VendorCheckEnabled(kBPVendorArm)) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001627 ValidateImageInQueueArm(function_name, image, last_usage, usage, array_layer, mip_level);
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001628 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001629}
1630
Hans-Kristian Arntzenb8336ad2021-04-28 14:54:09 +02001631void BestPractices::AddDeferredQueueOperations(CMD_BUFFER_STATE* cb) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001632 cb->queue_submit_functions.insert(cb->queue_submit_functions.end(),
Hans-Kristian Arntzenf44df192021-06-14 11:42:08 +02001633 cb->queue_submit_functions_after_render_pass.begin(),
1634 cb->queue_submit_functions_after_render_pass.end());
1635 cb->queue_submit_functions_after_render_pass.clear();
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001636}
1637
1638void BestPractices::PreCallRecordCmdEndRenderPass(VkCommandBuffer commandBuffer) {
1639 ValidationStateTracker::PreCallRecordCmdEndRenderPass(commandBuffer);
Hans-Kristian Arntzenb8336ad2021-04-28 14:54:09 +02001640 AddDeferredQueueOperations(GetCBState(commandBuffer));
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001641}
1642
1643void BestPractices::PreCallRecordCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassInfo) {
1644 ValidationStateTracker::PreCallRecordCmdEndRenderPass2(commandBuffer, pSubpassInfo);
Hans-Kristian Arntzenb8336ad2021-04-28 14:54:09 +02001645 AddDeferredQueueOperations(GetCBState(commandBuffer));
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001646}
1647
1648void BestPractices::PreCallRecordCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfoKHR *pSubpassInfo) {
1649 ValidationStateTracker::PreCallRecordCmdEndRenderPass2KHR(commandBuffer, pSubpassInfo);
Hans-Kristian Arntzenb8336ad2021-04-28 14:54:09 +02001650 AddDeferredQueueOperations(GetCBState(commandBuffer));
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001651}
1652
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001653void BestPractices::PreCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1654 VkSubpassContents contents) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001655 ValidationStateTracker::PreCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1656
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001657 if (!pRenderPassBegin) {
1658 return;
1659 }
1660
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001661 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
1662
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001663 auto rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
1664 if (rp_state) {
1665 // Check load ops
1666 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001667 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001668
1669 if (!RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att) &&
1670 !RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1671 continue;
1672 }
1673
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001674 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::UNDEFINED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001675
1676 if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) ||
1677 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001678 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02001679 } else if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) ||
1680 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_CLEAR)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001681 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_CLEARED;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02001682 } else if (RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att)) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001683 usage = IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001684 }
1685
1686 auto framebuffer = GetFramebufferState(pRenderPassBegin->framebuffer);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001687 IMAGE_VIEW_STATE* image_view = nullptr;
1688
Tony-LunarGb3ab3572021-07-02 09:45:17 -06001689 if (framebuffer->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001690 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
1691 if (rpabi) {
1692 image_view = GetImageViewState(rpabi->pAttachments[att]);
1693 }
1694 } else {
1695 image_view = GetImageViewState(framebuffer->createInfo.pAttachments[att]);
1696 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001697
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001698 QueueValidateImageView(cb->queue_submit_functions, "vkCmdBeginRenderPass()", image_view, usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001699 }
1700
1701 // Check store ops
1702 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001703 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001704
1705 if (!RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1706 continue;
1707 }
1708
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001709 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_DISCARDED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001710
1711 if ((!FormatIsStencilOnly(attachment.format) && attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE) ||
1712 (FormatHasStencil(attachment.format) && attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001713 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_STORED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001714 }
1715
1716 auto framebuffer = GetFramebufferState(pRenderPassBegin->framebuffer);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001717
1718 IMAGE_VIEW_STATE* image_view = nullptr;
Tony-LunarGb3ab3572021-07-02 09:45:17 -06001719 if (framebuffer->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001720 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
1721 if (rpabi) {
1722 image_view = GetImageViewState(rpabi->pAttachments[att]);
1723 }
1724 } else {
1725 image_view = GetImageViewState(framebuffer->createInfo.pAttachments[att]);
1726 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001727
Hans-Kristian Arntzenf44df192021-06-14 11:42:08 +02001728 QueueValidateImageView(cb->queue_submit_functions_after_render_pass, "vkCmdEndRenderPass()", image_view, usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001729 }
1730 }
1731}
1732
Attilio Provenzano02859b22020-02-27 14:17:28 +00001733bool BestPractices::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1734 VkSubpassContents contents) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001735 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1736 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001737 return skip;
1738}
1739
1740bool BestPractices::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1741 const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08001742 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001743 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1744 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001745 return skip;
1746}
1747
1748bool BestPractices::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08001749 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001750 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1751 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001752 return skip;
1753}
1754
Sam Walls0961ec02020-03-31 16:39:15 +01001755void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1756 const VkRenderPassBeginInfo* pRenderPassBegin) {
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001757 // Reset the renderpass state
1758 auto& render_pass_state = cbRenderPassState[commandBuffer];
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02001759 render_pass_state.touchesAttachments.clear();
1760 render_pass_state.earlyClearAttachments.clear();
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001761 render_pass_state.numDrawCallsDepthOnly = 0;
1762 render_pass_state.numDrawCallsDepthEqualCompare = 0;
1763 render_pass_state.colorAttachment = false;
1764 render_pass_state.depthAttachment = false;
1765 // Don't reset state related to pipeline state.
Sam Walls0961ec02020-03-31 16:39:15 +01001766
Hans-Kristian Arntzena1a92cc2021-03-17 13:09:33 +01001767 const auto* rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
Sam Walls0961ec02020-03-31 16:39:15 +01001768
1769 // track depth / color attachment usage within the renderpass
1770 for (size_t i = 0; i < rp_state->createInfo.subpassCount; i++) {
1771 // record if depth/color attachments are in use for this renderpass
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001772 if (rp_state->createInfo.pSubpasses[i].pDepthStencilAttachment != nullptr) render_pass_state.depthAttachment = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001773
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001774 if (rp_state->createInfo.pSubpasses[i].colorAttachmentCount > 0) render_pass_state.colorAttachment = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001775 }
1776}
1777
1778void BestPractices::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1779 VkSubpassContents contents) {
1780 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1781 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
1782}
1783
1784void BestPractices::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1785 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1786 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1787 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1788}
1789
1790void BestPractices::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1791 const VkRenderPassBeginInfo* pRenderPassBegin,
1792 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1793 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1794 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1795}
1796
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001797// Generic function to handle validation for all CmdDraw* type functions
1798bool BestPractices::ValidateCmdDrawType(VkCommandBuffer cmd_buffer, const char* caller) const {
1799 bool skip = false;
1800 const CMD_BUFFER_STATE* cb_state = GetCBState(cmd_buffer);
1801 if (cb_state) {
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001802 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
1803 const auto* pipeline_state = cb_state->lastBound[lv_bind_point].pipeline_state;
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001804 const auto& current_vtx_bfr_binding_info = cb_state->current_vertex_buffer_binding_info.vertex_buffer_bindings;
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001805
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001806 // Verify vertex binding
1807 if (pipeline_state->vertex_binding_descriptions_.size() <= 0) {
1808 if ((!current_vtx_bfr_binding_info.empty()) && (!cb_state->vertex_buffer_used)) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001809 skip |= LogPerformanceWarning(cb_state->commandBuffer(), kVUID_BestPractices_DrawState_VtxIndexOutOfBounds,
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001810 "Vertex buffers are bound to %s but no vertex buffers are attached to %s.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001811 report_data->FormatHandle(cb_state->commandBuffer()).c_str(),
1812 report_data->FormatHandle(pipeline_state->pipeline()).c_str());
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001813 }
1814 }
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06001815
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06001816 const auto* pipe = cb_state->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06001817 if (pipe) {
1818 const auto* rp_state = pipe->rp_state.get();
1819 if (rp_state) {
1820 for (uint32_t i = 0; i < rp_state->createInfo.subpassCount; ++i) {
1821 const auto& subpass = rp_state->createInfo.pSubpasses[i];
1822 const uint32_t depth_stencil_attachment = GetSubpassDepthStencilAttachmentIndex(
1823 pipe->graphicsPipelineCI.pDepthStencilState, subpass.pDepthStencilAttachment);
1824 if ((depth_stencil_attachment == VK_ATTACHMENT_UNUSED) && pipe->graphicsPipelineCI.pRasterizationState &&
1825 pipe->graphicsPipelineCI.pRasterizationState->depthBiasEnable == VK_TRUE) {
1826 skip |= LogWarning(cb_state->commandBuffer(), kVUID_BestPractices_DepthBiasNoAttachment,
1827 "%s: depthBiasEnable == VK_TRUE without a depth-stencil attachment.", caller);
1828 }
1829 }
1830 }
1831 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001832 }
1833 return skip;
1834}
1835
Sam Walls0961ec02020-03-31 16:39:15 +01001836void BestPractices::RecordCmdDrawType(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
1837 if (VendorCheckEnabled(kBPVendorArm)) {
1838 RecordCmdDrawTypeArm(cmd_buffer, draw_count, caller);
1839 }
1840}
1841
1842void BestPractices::RecordCmdDrawTypeArm(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
Hans-Kristian Arntzen09aff9d2021-06-14 15:17:02 +02001843 auto render_pass_state = cbRenderPassState.find(cmd_buffer);
1844 if (render_pass_state != cbRenderPassState.end() && draw_count >= kDepthPrePassMinDrawCountArm) {
1845 if (render_pass_state->second.depthOnly) render_pass_state->second.numDrawCallsDepthOnly++;
Sam Walls0961ec02020-03-31 16:39:15 +01001846
Hans-Kristian Arntzen09aff9d2021-06-14 15:17:02 +02001847 if (render_pass_state->second.depthEqualComparison) render_pass_state->second.numDrawCallsDepthEqualCompare++;
Sam Walls0961ec02020-03-31 16:39:15 +01001848 }
1849}
1850
Camden5b184be2019-08-13 07:50:19 -06001851bool BestPractices::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001852 uint32_t firstVertex, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06001853 bool skip = false;
1854
1855 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001856 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
1857 "Warning: You are calling vkCmdDraw() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06001858 }
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06001859 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDraw()");
Camden5b184be2019-08-13 07:50:19 -06001860
1861 return skip;
1862}
1863
Sam Walls0961ec02020-03-31 16:39:15 +01001864void BestPractices::PostCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
1865 uint32_t firstVertex, uint32_t firstInstance) {
1866 StateTracker::PostCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
1867 RecordCmdDrawType(commandBuffer, vertexCount * instanceCount, "vkCmdDraw()");
1868}
1869
Camden5b184be2019-08-13 07:50:19 -06001870bool BestPractices::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001871 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06001872 bool skip = false;
1873
1874 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001875 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
1876 "Warning: You are calling vkCmdDrawIndexed() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06001877 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001878 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexed()");
1879
Attilio Provenzano02859b22020-02-27 14:17:28 +00001880 // Check if we reached the limit for small indexed draw calls.
1881 // Note that we cannot update the draw call count here, so we do it in PreCallRecordCmdDrawIndexed.
1882 const CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
1883 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices &&
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001884 (cmd_state->small_indexed_draw_call_count == kMaxSmallIndexedDrawcalls - 1) &&
1885 VendorCheckEnabled(kBPVendorArm)) {
1886 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_ManySmallIndexedDrawcalls,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -06001887 "%s: The command buffer contains many small indexed drawcalls "
Attilio Provenzano02859b22020-02-27 14:17:28 +00001888 "(at least %u drawcalls with less than %u indices each). This may cause pipeline bubbles. "
1889 "You can try batching drawcalls or instancing when applicable.",
1890 VendorSpecificTag(kBPVendorArm), kMaxSmallIndexedDrawcalls, kSmallIndexedDrawcallIndices);
1891 }
1892
Sam Walls8e77e4f2020-03-16 20:47:40 +00001893 if (VendorCheckEnabled(kBPVendorArm)) {
1894 ValidateIndexBufferArm(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
1895 }
1896
1897 return skip;
1898}
1899
1900bool BestPractices::ValidateIndexBufferArm(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1901 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
1902 bool skip = false;
1903
1904 // check for sparse/underutilised index buffer, and post-transform cache thrashing
1905 const auto* cmd_state = GetCBState(commandBuffer);
1906 if (cmd_state == nullptr) return skip;
1907
locke-lunarg1ae57d62020-11-18 10:49:19 -07001908 const auto* ib_state = cmd_state->index_buffer_binding.buffer_state.get();
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06001909 if (ib_state == nullptr || cmd_state->index_buffer_binding.buffer_state->Destroyed()) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00001910
1911 const VkIndexType ib_type = cmd_state->index_buffer_binding.index_type;
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06001912 const auto& ib_mem_state = *ib_state->MemState();
Sam Walls8e77e4f2020-03-16 20:47:40 +00001913 const VkDeviceSize ib_mem_offset = ib_mem_state.mapped_range.offset;
1914 const void* ib_mem = ib_mem_state.p_driver_data;
1915 bool primitive_restart_enable = false;
1916
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001917 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
1918 const auto& pipeline_binding_iter = cmd_state->lastBound[lv_bind_point];
1919 const auto* pipeline_state = pipeline_binding_iter.pipeline_state;
Sam Walls8e77e4f2020-03-16 20:47:40 +00001920
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001921 if (pipeline_state != nullptr && pipeline_state->graphicsPipelineCI.pInputAssemblyState != nullptr) {
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001922 primitive_restart_enable = pipeline_state->graphicsPipelineCI.pInputAssemblyState->primitiveRestartEnable == VK_TRUE;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001923 }
Sam Walls8e77e4f2020-03-16 20:47:40 +00001924
1925 // 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 -06001926 if (ib_mem && pipeline_binding_iter.IsUsing()) {
Sam Walls8e77e4f2020-03-16 20:47:40 +00001927 uint32_t scan_stride;
1928 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1929 scan_stride = sizeof(uint8_t);
1930 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1931 scan_stride = sizeof(uint16_t);
1932 } else {
1933 scan_stride = sizeof(uint32_t);
1934 }
1935
1936 const uint8_t* scan_begin = static_cast<const uint8_t*>(ib_mem) + ib_mem_offset + firstIndex * scan_stride;
1937 const uint8_t* scan_end = scan_begin + indexCount * scan_stride;
1938
1939 // Min and max are important to track for some Mali architectures. In older Mali devices without IDVS, all
1940 // vertices corresponding to indices between the minimum and maximum may be loaded, and possibly shaded,
1941 // irrespective of whether or not they're part of the draw call.
1942
1943 // start with minimum as 0xFFFFFFFF and adjust to indices in the buffer
1944 uint32_t min_index = ~0u;
1945 // start with maximum as 0 and adjust to indices in the buffer
1946 uint32_t max_index = 0u;
1947
1948 // first scan-through, we're looking to simulate a model LRU post-transform cache, estimating the number of vertices shaded
1949 // for the given index buffer
1950 uint32_t vertex_shade_count = 0;
1951
1952 PostTransformLRUCacheModel post_transform_cache;
1953
1954 // The size of the cache being modelled positively correlates with how much behaviour it can capture about
1955 // arbitrary ground-truth hardware/architecture cache behaviour. I.e. it's a good solution when we don't know the
1956 // target architecture.
1957 // However, modelling a post-transform cache with more than 32 elements gives diminishing returns in practice.
1958 // http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
1959 post_transform_cache.resize(32);
1960
1961 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
1962 uint32_t scan_index;
1963 uint32_t primitive_restart_value;
1964 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1965 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
1966 primitive_restart_value = 0xFF;
1967 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1968 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
1969 primitive_restart_value = 0xFFFF;
1970 } else {
1971 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
1972 primitive_restart_value = 0xFFFFFFFF;
1973 }
1974
1975 max_index = std::max(max_index, scan_index);
1976 min_index = std::min(min_index, scan_index);
1977
1978 if (!primitive_restart_enable || scan_index != primitive_restart_value) {
1979 bool in_cache = post_transform_cache.query_cache(scan_index);
1980 // if the shaded vertex corresponding to the index is not in the PT-cache, we need to shade again
1981 if (!in_cache) vertex_shade_count++;
1982 }
1983 }
1984
1985 // 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 +01001986 // 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
1987 if (max_index < min_index || max_index == min_index) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00001988
1989 if (max_index - min_index >= indexCount) {
Mark Young0ec6b062020-11-19 15:32:17 -07001990 skip |=
1991 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
1992 "%s The indices which were specified for the draw call only utilise approximately %.02f%% of "
1993 "index buffer value range. Arm Mali architectures before G71 do not have IDVS (Index-Driven "
1994 "Vertex Shading), meaning all vertices corresponding to indices between the minimum and "
1995 "maximum would be loaded, and possibly shaded, whether or not they are used.",
1996 VendorSpecificTag(kBPVendorArm),
1997 (static_cast<float>(indexCount) / static_cast<float>(max_index - min_index)) * 100.0f);
Sam Walls8e77e4f2020-03-16 20:47:40 +00001998 return skip;
1999 }
2000
2001 // use a dynamic vector of bitsets as a memory-compact representation of which indices are included in the draw call
2002 // 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 +01002003 const size_t refs_per_bucket = 64;
2004 std::vector<std::bitset<refs_per_bucket>> vertex_reference_buckets;
2005
2006 const uint32_t n_indices = max_index - min_index + 1;
2007 const uint32_t n_buckets = (n_indices / static_cast<uint32_t>(refs_per_bucket)) +
2008 ((n_indices % static_cast<uint32_t>(refs_per_bucket)) != 0 ? 1 : 0);
2009
2010 // there needs to be at least one bitset to store a set of indices smaller than n_buckets
2011 vertex_reference_buckets.resize(std::max(1u, n_buckets));
Sam Walls8e77e4f2020-03-16 20:47:40 +00002012
2013 // To avoid using too much memory, we run over the indices again.
2014 // Knowing the size from the last scan allows us to record index usage with bitsets
2015 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
2016 uint32_t scan_index;
2017 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
2018 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
2019 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
2020 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
2021 } else {
2022 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
2023 }
2024 // keep track of the set of all indices used to reference vertices in the draw call
2025 size_t index_offset = scan_index - min_index;
Sam Walls61b06892020-07-23 16:20:50 +01002026 size_t bitset_bucket_index = index_offset / refs_per_bucket;
2027 uint64_t used_indices = 1ull << ((index_offset % refs_per_bucket) & 0xFFFFFFFFu);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002028 vertex_reference_buckets[bitset_bucket_index] |= used_indices;
2029 }
2030
2031 uint32_t vertex_reference_count = 0;
2032 for (const auto& bitset : vertex_reference_buckets) {
2033 vertex_reference_count += static_cast<uint32_t>(bitset.count());
2034 }
2035
2036 // 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 -07002037 float utilization = static_cast<float>(vertex_reference_count) / static_cast<float>(max_index - min_index + 1);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002038 // 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 -07002039 float cache_hit_rate = static_cast<float>(vertex_reference_count) / static_cast<float>(vertex_shade_count);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002040
2041 if (utilization < 0.5f) {
2042 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
2043 "%s The indices which were specified for the draw call only utilise approximately "
2044 "%.02f%% of the bound vertex buffer.",
2045 VendorSpecificTag(kBPVendorArm), utilization);
2046 }
2047
2048 if (cache_hit_rate <= 0.5f) {
2049 skip |=
2050 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_PostTransformCacheThrashing,
2051 "%s The indices which were specified for the draw call are estimated to cause thrashing of "
2052 "the post-transform vertex cache, with a hit-rate of %.02f%%. "
2053 "I.e. the ordering of the index buffer may not make optimal use of indices associated with "
2054 "recently shaded vertices.",
2055 VendorSpecificTag(kBPVendorArm), cache_hit_rate * 100.0f);
2056 }
2057 }
2058
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002059 return skip;
2060}
2061
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002062bool BestPractices::PreCallValidateCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
2063 const VkCommandBuffer* pCommandBuffers) const {
2064 bool skip = false;
2065 const CMD_BUFFER_STATE* primary = GetCBState(commandBuffer);
2066 for (uint32_t i = 0; i < commandBufferCount; i++) {
2067 auto secondary_itr = cbRenderPassState.find(pCommandBuffers[i]);
2068 if (secondary_itr == cbRenderPassState.end()) {
2069 continue;
2070 }
2071 auto& secondary = secondary_itr->second;
2072 for (auto& clear : secondary.earlyClearAttachments) {
2073 if (ClearAttachmentsIsFullClear(primary, clear.rects.size(), clear.rects.data())) {
2074 skip |= ValidateClearAttachment(commandBuffer, primary,
2075 clear.framebufferAttachment, clear.colorAttachment,
2076 clear.aspects, true);
2077 }
2078 }
2079 }
2080 return skip;
2081}
2082
2083void BestPractices::PreCallRecordCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
2084 const VkCommandBuffer* pCommandBuffers) {
2085 CMD_BUFFER_STATE* primary = GetCBState(commandBuffer);
2086 auto& primary_state = cbRenderPassState[commandBuffer];
2087
2088 for (uint32_t i = 0; i < commandBufferCount; i++) {
2089 auto& secondary = cbRenderPassState[pCommandBuffers[i]];
2090
2091 for (auto& early_clear : secondary.earlyClearAttachments) {
2092 if (ClearAttachmentsIsFullClear(primary, early_clear.rects.size(), early_clear.rects.data())) {
2093 RecordAttachmentClearAttachments(primary, primary_state, early_clear.framebufferAttachment,
2094 early_clear.colorAttachment, early_clear.aspects,
2095 early_clear.rects.size(), early_clear.rects.data());
2096 } else {
2097 RecordAttachmentAccess(primary_state, early_clear.framebufferAttachment,
2098 early_clear.aspects);
2099 }
2100 }
2101
2102 for (auto& touch : secondary.touchesAttachments) {
2103 RecordAttachmentAccess(primary_state, touch.framebufferAttachment,
2104 touch.aspects);
2105 }
Hans-Kristian Arntzenc7eb82a2021-06-16 13:57:18 +02002106
2107 primary_state.numDrawCallsDepthEqualCompare += secondary.numDrawCallsDepthEqualCompare;
2108 primary_state.numDrawCallsDepthOnly += secondary.numDrawCallsDepthOnly;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002109 }
2110
2111 ValidationStateTracker::PreCallRecordCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
2112}
2113
2114void BestPractices::RecordAttachmentAccess(RenderPassState& state, uint32_t fb_attachment, VkImageAspectFlags aspects) {
2115 // Called when we have a partial clear attachment, or a normal draw call which accesses an attachment.
2116 auto itr = std::find_if(state.touchesAttachments.begin(), state.touchesAttachments.end(),
2117 [&](const RenderPassState::AttachmentInfo& info) {
2118 return info.framebufferAttachment == fb_attachment;
2119 });
2120
2121 if (itr != state.touchesAttachments.end()) {
2122 itr->aspects |= aspects;
2123 } else {
2124 state.touchesAttachments.push_back({ fb_attachment, aspects });
2125 }
2126}
2127
2128void BestPractices::RecordAttachmentClearAttachments(CMD_BUFFER_STATE* cmd_state, RenderPassState& state,
2129 uint32_t fb_attachment, uint32_t color_attachment,
2130 VkImageAspectFlags aspects, uint32_t rectCount,
2131 const VkClearRect *pRects) {
2132 // If we observe a full clear before any other access to a frame buffer attachment,
2133 // we have candidate for redundant clear attachments.
2134 auto itr = std::find_if(state.touchesAttachments.begin(), state.touchesAttachments.end(),
2135 [&](const RenderPassState::AttachmentInfo& info) {
2136 return info.framebufferAttachment == fb_attachment;
2137 });
2138
2139 uint32_t new_aspects = aspects;
2140 if (itr != state.touchesAttachments.end()) {
2141 new_aspects = aspects & ~itr->aspects;
2142 itr->aspects |= aspects;
2143 } else {
2144 state.touchesAttachments.push_back({ fb_attachment, aspects });
2145 }
2146
2147 if (new_aspects == 0) {
2148 return;
2149 }
2150
2151 if (cmd_state->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
2152 // The first command might be a clear, but might not be the first in the render pass, defer any checks until
2153 // CmdExecuteCommands.
2154 state.earlyClearAttachments.push_back({ fb_attachment, color_attachment, new_aspects,
2155 std::vector<VkClearRect>{pRects, pRects + rectCount} });
2156 }
2157}
2158
2159void BestPractices::PreCallRecordCmdClearAttachments(VkCommandBuffer commandBuffer,
2160 uint32_t attachmentCount, const VkClearAttachment* pClearAttachments,
2161 uint32_t rectCount, const VkClearRect* pRects) {
2162 CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
2163 RENDER_PASS_STATE* rp_state = cmd_state->activeRenderPass.get();
2164 FRAMEBUFFER_STATE* fb_state = cmd_state->activeFramebuffer.get();
2165 RenderPassState& tracking_state = cbRenderPassState[commandBuffer];
2166 bool is_secondary = cmd_state->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY;
2167
2168 if (rectCount == 0 || !rp_state) {
2169 return;
2170 }
2171
2172 if (!is_secondary && !fb_state) {
2173 return;
2174 }
2175
2176 // If we have a rect which covers the entire frame buffer, we have a LOAD_OP_CLEAR-like command.
2177 bool full_clear = ClearAttachmentsIsFullClear(cmd_state, rectCount, pRects);
2178
2179 auto& subpass = rp_state->createInfo.pSubpasses[cmd_state->activeSubpass];
2180 for (uint32_t i = 0; i < attachmentCount; i++) {
2181 auto& attachment = pClearAttachments[i];
2182 uint32_t fb_attachment = VK_ATTACHMENT_UNUSED;
2183 VkImageAspectFlags aspects = attachment.aspectMask;
2184
2185 if (aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) {
2186 if (subpass.pDepthStencilAttachment) {
2187 fb_attachment = subpass.pDepthStencilAttachment->attachment;
2188 }
2189 } else if (aspects & VK_IMAGE_ASPECT_COLOR_BIT) {
2190 fb_attachment = subpass.pColorAttachments[attachment.colorAttachment].attachment;
2191 }
2192
2193 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2194 if (full_clear) {
2195 RecordAttachmentClearAttachments(cmd_state, tracking_state,
2196 fb_attachment, attachment.colorAttachment, aspects,
2197 rectCount, pRects);
2198 } else {
2199 RecordAttachmentAccess(tracking_state, fb_attachment, aspects);
2200 }
2201 }
2202 }
2203
2204 ValidationStateTracker::PreCallRecordCmdClearAttachments(commandBuffer, attachmentCount, pClearAttachments,
2205 rectCount, pRects);
2206}
2207
Attilio Provenzano02859b22020-02-27 14:17:28 +00002208void BestPractices::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
2209 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
2210 ValidationStateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset,
2211 firstInstance);
2212
2213 CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
2214 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices) {
2215 cmd_state->small_indexed_draw_call_count++;
2216 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002217
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002218 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDrawIndexed()");
Attilio Provenzano02859b22020-02-27 14:17:28 +00002219}
2220
Sam Walls0961ec02020-03-31 16:39:15 +01002221void BestPractices::PostCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
2222 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
2223 StateTracker::PostCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
2224 RecordCmdDrawType(commandBuffer, indexCount * instanceCount, "vkCmdDrawIndexed()");
2225}
2226
sfricke-samsung681ab7b2020-10-29 01:53:35 -07002227bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2228 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
2229 uint32_t maxDrawCount, uint32_t stride) const {
2230 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCount()");
2231
2232 return skip;
2233}
2234
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002235bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
2236 VkDeviceSize offset, VkBuffer countBuffer,
2237 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
2238 uint32_t stride) const {
2239 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCountKHR()");
Camden5b184be2019-08-13 07:50:19 -06002240
2241 return skip;
2242}
2243
2244bool BestPractices::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002245 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06002246 bool skip = false;
2247
2248 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002249 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
2250 "Warning: You are calling vkCmdDrawIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002251 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirect()");
Camden5b184be2019-08-13 07:50:19 -06002252 }
2253
2254 return skip;
2255}
2256
Sam Walls0961ec02020-03-31 16:39:15 +01002257void BestPractices::PostCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2258 uint32_t count, uint32_t stride) {
2259 StateTracker::PostCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, count, stride);
2260 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndirect()");
2261}
2262
Camden5b184be2019-08-13 07:50:19 -06002263bool BestPractices::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002264 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06002265 bool skip = false;
2266
2267 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002268 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
2269 "Warning: You are calling vkCmdDrawIndexedIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002270 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirect()");
Camden5b184be2019-08-13 07:50:19 -06002271 }
2272
2273 return skip;
2274}
2275
Sam Walls0961ec02020-03-31 16:39:15 +01002276void BestPractices::PostCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2277 uint32_t count, uint32_t stride) {
2278 StateTracker::PostCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, count, stride);
2279 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndexedIndirect()");
2280}
2281
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002282void BestPractices::ValidateBoundDescriptorSets(VkCommandBuffer commandBuffer, const char* function_name) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01002283 CMD_BUFFER_STATE* cb_state = GetCBState(commandBuffer);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002284
2285 if (cb_state) {
2286 for (auto descriptor_set : cb_state->validated_descriptor_sets) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002287 const auto& layout = *descriptor_set->GetLayout();
Hans-Kristian Arntzena8199012021-03-22 12:10:07 +01002288
2289 for (uint32_t index = 0; index < descriptor_set->GetBindingCount(); ++index) {
2290 // For bindless scenarios, we should not attempt to track descriptor set state.
2291 // It is highly uncertain which resources are actually bound.
2292 // Resources which are written to such a descriptor should be marked as indeterminate w.r.t. state.
2293 VkDescriptorBindingFlags flags = layout.GetDescriptorBindingFlagsFromIndex(index);
2294 if (flags & (VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT |
2295 VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT |
2296 VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT)) {
2297 continue;
2298 }
2299
2300 auto index_range = layout.GetGlobalIndexRangeFromIndex(index);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002301 for (uint32_t i = index_range.start; i < index_range.end; ++i) {
ZandroFargnoliacf12f02020-06-18 16:50:00 +01002302 VkImageView image_view{VK_NULL_HANDLE};
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002303
2304 auto descriptor = descriptor_set->GetDescriptorFromGlobalIndex(i);
2305 switch (descriptor->GetClass()) {
2306 case cvdescriptorset::DescriptorClass::Image: {
2307 if (const auto image_descriptor = static_cast<const cvdescriptorset::ImageDescriptor*>(descriptor)) {
2308 image_view = image_descriptor->GetImageView();
2309 }
Hans-Kristian Arntzenbc3a6152021-03-22 13:05:43 +01002310 break;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002311 }
2312 case cvdescriptorset::DescriptorClass::ImageSampler: {
2313 if (const auto image_sampler_descriptor =
2314 static_cast<const cvdescriptorset::ImageSamplerDescriptor*>(descriptor)) {
2315 image_view = image_sampler_descriptor->GetImageView();
2316 }
Hans-Kristian Arntzenbc3a6152021-03-22 13:05:43 +01002317 break;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002318 }
ZandroFargnoliacf12f02020-06-18 16:50:00 +01002319 default:
Hans-Kristian Arntzenbc3a6152021-03-22 13:05:43 +01002320 break;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002321 }
2322
2323 if (image_view) {
2324 IMAGE_VIEW_STATE* image_view_state = GetImageViewState(image_view);
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002325 QueueValidateImageView(cb_state->queue_submit_functions, function_name,
2326 image_view_state, IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002327 }
2328 }
2329 }
2330 }
2331 }
2332}
2333
2334void BestPractices::PreCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
2335 uint32_t firstVertex, uint32_t firstInstance) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002336 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDraw()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002337}
2338
2339void BestPractices::PreCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2340 uint32_t drawCount, uint32_t stride) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002341 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDrawIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002342}
2343
2344void BestPractices::PreCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2345 uint32_t drawCount, uint32_t stride) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002346 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDrawIndexedIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002347}
2348
Camden5b184be2019-08-13 07:50:19 -06002349bool BestPractices::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t groupCountX, uint32_t groupCountY,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002350 uint32_t groupCountZ) const {
Camden5b184be2019-08-13 07:50:19 -06002351 bool skip = false;
2352
2353 if ((groupCountX == 0) || (groupCountY == 0) || (groupCountZ == 0)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002354 skip |= LogWarning(device, kVUID_BestPractices_CmdDispatch_GroupCountZero,
2355 "Warning: You are calling vkCmdDispatch() while one or more groupCounts are zero (groupCountX = %" PRIu32
2356 ", groupCountY = %" PRIu32 ", groupCountZ = %" PRIu32 ").",
2357 groupCountX, groupCountY, groupCountZ);
Camden5b184be2019-08-13 07:50:19 -06002358 }
2359
2360 return skip;
2361}
Camden83a9c372019-08-14 11:41:38 -06002362
Sam Walls0961ec02020-03-31 16:39:15 +01002363bool BestPractices::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
2364 bool skip = false;
2365
2366 skip |= StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
2367
Hans-Kristian Arntzen09aff9d2021-06-14 15:17:02 +02002368 auto render_pass_state = cbRenderPassState.find(commandBuffer);
Sam Walls0961ec02020-03-31 16:39:15 +01002369
Hans-Kristian Arntzen09aff9d2021-06-14 15:17:02 +02002370 if (render_pass_state == cbRenderPassState.end()) return skip;
Sam Walls0961ec02020-03-31 16:39:15 +01002371
Hans-Kristian Arntzen09aff9d2021-06-14 15:17:02 +02002372 bool uses_depth = (render_pass_state->second.depthAttachment || render_pass_state->second.colorAttachment) &&
2373 render_pass_state->second.numDrawCallsDepthEqualCompare >= kDepthPrePassNumDrawCallsArm &&
2374 render_pass_state->second.numDrawCallsDepthOnly >= kDepthPrePassNumDrawCallsArm;
Sam Walls0961ec02020-03-31 16:39:15 +01002375 if (uses_depth) {
2376 skip |= LogPerformanceWarning(
2377 device, kVUID_BestPractices_EndRenderPass_DepthPrePassUsage,
2378 "%s Depth pre-passes may be in use. In general, this is not recommended, as in Arm Mali GPUs since "
2379 "Mali-T620, Forward Pixel Killing (FPK) can already perform automatic hidden surface removal; in which "
2380 "case, using depth pre-passes for hidden surface removal may worsen performance.",
2381 VendorSpecificTag(kBPVendorArm));
2382 }
2383
2384 return skip;
2385}
2386
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002387void BestPractices::PreCallRecordCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002388 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDispatch()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002389}
2390
2391void BestPractices::PreCallRecordCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002392 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDispatchIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002393}
2394
Camden Stocker9c051442019-11-06 14:28:43 -08002395bool BestPractices::ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(VkPhysicalDevice physicalDevice,
2396 const char* api_name) const {
2397 bool skip = false;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002398 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
Camden Stocker9c051442019-11-06 14:28:43 -08002399
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002400 if (bp_pd_state) {
2401 if (bp_pd_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState == UNCALLED) {
2402 skip |= LogWarning(physicalDevice, kVUID_BestPractices_DisplayPlane_PropertiesNotCalled,
2403 "Potential problem with calling %s() without first retrieving properties from "
2404 "vkGetPhysicalDeviceDisplayPlanePropertiesKHR or vkGetPhysicalDeviceDisplayPlaneProperties2KHR.",
2405 api_name);
2406 }
Camden Stocker9c051442019-11-06 14:28:43 -08002407 }
2408
2409 return skip;
2410}
2411
Camden83a9c372019-08-14 11:41:38 -06002412bool BestPractices::PreCallValidateGetDisplayPlaneSupportedDisplaysKHR(VkPhysicalDevice physicalDevice, uint32_t planeIndex,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002413 uint32_t* pDisplayCount, VkDisplayKHR* pDisplays) const {
Camden83a9c372019-08-14 11:41:38 -06002414 bool skip = false;
2415
Camden Stocker9c051442019-11-06 14:28:43 -08002416 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneSupportedDisplaysKHR");
Camden83a9c372019-08-14 11:41:38 -06002417
Camden Stocker9c051442019-11-06 14:28:43 -08002418 return skip;
2419}
2420
2421bool BestPractices::PreCallValidateGetDisplayPlaneCapabilitiesKHR(VkPhysicalDevice physicalDevice, VkDisplayModeKHR mode,
2422 uint32_t planeIndex,
2423 VkDisplayPlaneCapabilitiesKHR* pCapabilities) const {
2424 bool skip = false;
2425
2426 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilitiesKHR");
2427
2428 return skip;
2429}
2430
2431bool BestPractices::PreCallValidateGetDisplayPlaneCapabilities2KHR(VkPhysicalDevice physicalDevice,
2432 const VkDisplayPlaneInfo2KHR* pDisplayPlaneInfo,
2433 VkDisplayPlaneCapabilities2KHR* pCapabilities) const {
2434 bool skip = false;
2435
2436 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilities2KHR");
Camden83a9c372019-08-14 11:41:38 -06002437
2438 return skip;
2439}
Camden05de2d42019-08-19 10:23:56 -06002440
2441bool BestPractices::PreCallValidateGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain, uint32_t* pSwapchainImageCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002442 VkImage* pSwapchainImages) const {
Camden05de2d42019-08-19 10:23:56 -06002443 bool skip = false;
2444
Nathaniel Cesario39152e62021-07-02 13:04:16 -06002445 const auto* swapchain_state = static_cast<SWAPCHAIN_STATE_BP*>(Get<SWAPCHAIN_NODE>(swapchain));
Camden05de2d42019-08-19 10:23:56 -06002446
Nathaniel Cesario39152e62021-07-02 13:04:16 -06002447 if (swapchain_state && pSwapchainImages) {
Camden05de2d42019-08-19 10:23:56 -06002448 // Compare the preliminary value of *pSwapchainImageCount with the value this time:
Nathaniel Cesario39152e62021-07-02 13:04:16 -06002449 if (swapchain_state->vkGetSwapchainImagesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002450 skip |=
2451 LogWarning(device, kVUID_Core_Swapchain_PriorCount,
2452 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImageCount; but no prior positive value has "
2453 "been seen for pSwapchainImages.");
Camden05de2d42019-08-19 10:23:56 -06002454 }
Camden05de2d42019-08-19 10:23:56 -06002455
Nathaniel Cesario4ce98382021-05-28 11:33:20 -06002456 if (*pSwapchainImageCount > swapchain_state->get_swapchain_image_count) {
2457 skip |= LogWarning(
2458 device, kVUID_BestPractices_Swapchain_InvalidCount,
2459 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImages, and with pSwapchainImageCount set to a "
2460 "value (%d) that is greater than the value (%d) that was returned when pSwapchainImages was NULL.",
2461 *pSwapchainImageCount, swapchain_state->get_swapchain_image_count);
2462 }
2463 }
2464
Camden05de2d42019-08-19 10:23:56 -06002465 return skip;
2466}
2467
2468// Common function to handle validation for GetPhysicalDeviceQueueFamilyProperties & 2KHR version
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002469bool BestPractices::ValidateCommonGetPhysicalDeviceQueueFamilyProperties(const PHYSICAL_DEVICE_STATE* pd_state,
2470 uint32_t requested_queue_family_property_count,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002471 const CALL_STATE call_state,
2472 const char* caller_name) const {
Camden05de2d42019-08-19 10:23:56 -06002473 bool skip = false;
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002474 // Verify that for each physical device, this command is called first with NULL pQueueFamilyProperties in order to get count
2475 if (UNCALLED == call_state) {
2476 skip |= LogWarning(
2477 pd_state->phys_device, kVUID_Core_DevLimit_MissingQueryCount,
2478 "%s is called with non-NULL pQueueFamilyProperties before obtaining pQueueFamilyPropertyCount. It is "
2479 "recommended "
2480 "to first call %s with NULL pQueueFamilyProperties in order to obtain the maximal pQueueFamilyPropertyCount.",
2481 caller_name, caller_name);
2482 // Then verify that pCount that is passed in on second call matches what was returned
2483 } else if (pd_state->queue_family_known_count != requested_queue_family_property_count) {
2484 skip |= LogWarning(pd_state->phys_device, kVUID_Core_DevLimit_CountMismatch,
2485 "%s is called with non-NULL pQueueFamilyProperties and pQueueFamilyPropertyCount value %" PRIu32
2486 ", but the largest previously returned pQueueFamilyPropertyCount for this physicalDevice is %" PRIu32
2487 ". It is recommended to instead receive all the properties by calling %s with "
2488 "pQueueFamilyPropertyCount that was "
2489 "previously obtained by calling %s with NULL pQueueFamilyProperties.",
2490 caller_name, requested_queue_family_property_count, pd_state->queue_family_known_count, caller_name,
2491 caller_name);
Camden05de2d42019-08-19 10:23:56 -06002492 }
2493
2494 return skip;
2495}
2496
Jeff Bolz5c801d12019-10-09 10:38:45 -05002497bool BestPractices::PreCallValidateBindAccelerationStructureMemoryNV(
2498 VkDevice device, uint32_t bindInfoCount, const VkBindAccelerationStructureMemoryInfoNV* pBindInfos) const {
Camden Stocker82510582019-09-03 14:00:16 -06002499 bool skip = false;
2500
2501 for (uint32_t i = 0; i < bindInfoCount; i++) {
sourav parmarcd5fb182020-07-17 12:58:44 -07002502 const ACCELERATION_STRUCTURE_STATE* as_state = GetAccelerationStructureStateNV(pBindInfos[i].accelerationStructure);
Camden Stocker82510582019-09-03 14:00:16 -06002503 if (!as_state->memory_requirements_checked) {
2504 // There's not an explicit requirement in the spec to call vkGetImageMemoryRequirements() prior to calling
2505 // BindAccelerationStructureMemoryNV but it's implied in that memory being bound must conform with
2506 // VkAccelerationStructureMemoryRequirementsInfoNV from vkGetAccelerationStructureMemoryRequirementsNV
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002507 skip |= LogWarning(
2508 device, kVUID_BestPractices_BindAccelNV_NoMemReqQuery,
Camden Stocker82510582019-09-03 14:00:16 -06002509 "vkBindAccelerationStructureMemoryNV(): "
2510 "Binding memory to %s but vkGetAccelerationStructureMemoryRequirementsNV() has not been called on that structure.",
2511 report_data->FormatHandle(pBindInfos[i].accelerationStructure).c_str());
2512 }
2513 }
2514
2515 return skip;
2516}
2517
Camden05de2d42019-08-19 10:23:56 -06002518bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
2519 uint32_t* pQueueFamilyPropertyCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002520 VkQueueFamilyProperties* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06002521 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
2522 assert(physical_device_state);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002523 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physical_device_state->phys_device);
2524 if (pQueueFamilyProperties && bp_pd_state) {
2525 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
2526 bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
2527 "vkGetPhysicalDeviceQueueFamilyProperties()");
2528 }
2529 return false;
Camden05de2d42019-08-19 10:23:56 -06002530}
2531
Mike Schuchardt2df08912020-12-15 16:28:09 -08002532bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
2533 uint32_t* pQueueFamilyPropertyCount,
2534 VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06002535 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
2536 assert(physical_device_state);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002537 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physical_device_state->phys_device);
2538 if (pQueueFamilyProperties && bp_pd_state) {
2539 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
2540 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
2541 "vkGetPhysicalDeviceQueueFamilyProperties2()");
2542 }
2543 return false;
Camden05de2d42019-08-19 10:23:56 -06002544}
2545
Jeff Bolz5c801d12019-10-09 10:38:45 -05002546bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2KHR(
Mike Schuchardt2df08912020-12-15 16:28:09 -08002547 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount, VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06002548 auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
2549 assert(physical_device_state);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002550 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physical_device_state->phys_device);
2551 if (pQueueFamilyProperties && bp_pd_state) {
2552 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
2553 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
2554 "vkGetPhysicalDeviceQueueFamilyProperties2KHR()");
2555 }
2556 return false;
Camden05de2d42019-08-19 10:23:56 -06002557}
2558
2559bool BestPractices::PreCallValidateGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
2560 uint32_t* pSurfaceFormatCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002561 VkSurfaceFormatKHR* pSurfaceFormats) const {
Camden05de2d42019-08-19 10:23:56 -06002562 if (!pSurfaceFormats) return false;
2563 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002564 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2565 const auto& call_state = bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState;
Camden05de2d42019-08-19 10:23:56 -06002566 bool skip = false;
2567 if (call_state == UNCALLED) {
2568 // Since we haven't recorded a preliminary value of *pSurfaceFormatCount, that likely means that the application didn't
2569 // previously call this function with a NULL value of pSurfaceFormats:
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002570 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_MustQueryCount,
2571 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount; but no prior "
2572 "positive value has been seen for pSurfaceFormats.");
Camden05de2d42019-08-19 10:23:56 -06002573 } else {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002574 auto prev_format_count = static_cast<uint32_t>(physical_device_state->surface_formats.size());
Peter Chene191bd72019-09-16 13:04:37 -04002575 if (*pSurfaceFormatCount > prev_format_count) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002576 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_CountMismatch,
2577 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount, and with "
2578 "pSurfaceFormats set to a value (%u) that is greater than the value (%u) that was returned "
2579 "when pSurfaceFormatCount was NULL.",
2580 *pSurfaceFormatCount, prev_format_count);
Camden05de2d42019-08-19 10:23:56 -06002581 }
2582 }
2583 return skip;
2584}
Camden Stocker23cc47d2019-09-03 14:53:57 -06002585
2586bool BestPractices::PreCallValidateQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002587 VkFence fence) const {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002588 bool skip = false;
2589
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002590 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
2591 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
Camden Stocker23cc47d2019-09-03 14:53:57 -06002592 // 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 -07002593 layer_data::unordered_set<const IMAGE_STATE*> sparse_images;
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002594 // Track images getting metadata bound by this call in a set, it'll be recorded into the image_state
2595 // in RecordQueueBindSparse.
Jeremy Gebbencbf22862021-03-03 12:01:22 -07002596 layer_data::unordered_set<const IMAGE_STATE*> sparse_images_with_metadata;
Camden Stocker23cc47d2019-09-03 14:53:57 -06002597 // 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 -07002598 for (uint32_t i = 0; i < bind_info.imageBindCount; ++i) {
2599 const auto& image_bind = bind_info.pImageBinds[i];
Camden Stocker23cc47d2019-09-03 14:53:57 -06002600 auto image_state = GetImageState(image_bind.image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002601 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002602 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002603 }
Camden Stocker23cc47d2019-09-03 14:53:57 -06002604 sparse_images.insert(image_state);
2605 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
2606 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
2607 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002608 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002609 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
2610 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002611 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002612 }
2613 }
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06002614 if (!image_state->memory_requirements_checked[0]) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002615 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002616 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002617 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
2618 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002619 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002620 }
2621 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002622 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
2623 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
2624 auto image_state = GetImageState(bind_info.pImageOpaqueBinds[i].image);
2625 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002626 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002627 }
Camden Stocker23cc47d2019-09-03 14:53:57 -06002628 sparse_images.insert(image_state);
2629 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
2630 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
2631 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002632 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002633 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
2634 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002635 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002636 }
2637 }
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06002638 if (!image_state->memory_requirements_checked[0]) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002639 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002640 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002641 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
2642 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002643 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002644 }
2645 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
2646 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002647 sparse_images_with_metadata.insert(image_state);
Camden Stocker23cc47d2019-09-03 14:53:57 -06002648 }
2649 }
2650 }
2651 for (const auto& sparse_image_state : sparse_images) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002652 if (sparse_image_state->sparse_metadata_required && !sparse_image_state->sparse_metadata_bound &&
2653 sparse_images_with_metadata.find(sparse_image_state) == sparse_images_with_metadata.end()) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002654 // Warn if sparse image binding metadata required for image with sparse binding, but metadata not bound
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002655 skip |= LogWarning(sparse_image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002656 "vkQueueBindSparse(): Binding sparse memory to %s which requires a metadata aspect but no "
2657 "binding with VK_SPARSE_MEMORY_BIND_METADATA_BIT set was made.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002658 report_data->FormatHandle(sparse_image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002659 }
2660 }
2661 }
2662
2663 return skip;
2664}
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002665
Mark Lobodzinski84101d72020-04-24 09:43:48 -06002666void BestPractices::ManualPostCallRecordQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
2667 VkFence fence, VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07002668 if (result != VK_SUCCESS) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07002669 return;
2670 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002671
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002672 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
2673 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
2674 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
2675 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
2676 auto image_state = GetImageState(bind_info.pImageOpaqueBinds[i].image);
2677 if (!image_state) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002678 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002679 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002680 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
2681 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
2682 image_state->sparse_metadata_bound = true;
2683 }
2684 }
2685 }
2686 }
2687}
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002688
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002689bool BestPractices::ClearAttachmentsIsFullClear(const CMD_BUFFER_STATE* cmd,
2690 uint32_t rectCount, const VkClearRect* pRects) const {
2691 if (cmd->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
2692 // We don't know the accurate render area in a secondary,
2693 // so assume we clear the entire frame buffer.
2694 // This is resolved in CmdExecuteCommands where we can check if the clear is a full clear.
2695 return true;
2696 }
2697
2698 // If we have a rect which covers the entire frame buffer, we have a LOAD_OP_CLEAR-like command.
2699 for (uint32_t i = 0; i < rectCount; i++) {
2700 auto& rect = pRects[i];
2701 auto& render_area = cmd->activeRenderPassBeginInfo.renderArea;
2702 if (rect.rect.extent.width == render_area.extent.width && rect.rect.extent.height == render_area.extent.height) {
2703 return true;
2704 }
2705 }
2706
2707 return false;
2708}
2709
2710bool BestPractices::ValidateClearAttachment(VkCommandBuffer commandBuffer, const CMD_BUFFER_STATE* cmd,
2711 uint32_t fb_attachment, uint32_t color_attachment,
2712 VkImageAspectFlags aspects, bool secondary) const {
2713 const RENDER_PASS_STATE* rp = cmd->activeRenderPass.get();
2714 bool skip = false;
2715
2716 if (!rp || fb_attachment == VK_ATTACHMENT_UNUSED) {
2717 return skip;
2718 }
2719
2720 auto rp_itr = cbRenderPassState.find(commandBuffer);
2721 if (rp_itr == cbRenderPassState.end()) {
2722 return skip;
2723 }
2724
2725 auto attachment_itr = std::find_if(rp_itr->second.touchesAttachments.begin(), rp_itr->second.touchesAttachments.end(),
2726 [&](const RenderPassState::AttachmentInfo& info) {
2727 return info.framebufferAttachment == fb_attachment;
2728 });
2729
2730 // Only report aspects which haven't been touched yet.
2731 VkImageAspectFlags new_aspects = aspects;
2732 if (attachment_itr != rp_itr->second.touchesAttachments.end()) {
2733 new_aspects &= ~attachment_itr->aspects;
2734 }
2735
2736 // Warn if this is issued prior to Draw Cmd and clearing the entire attachment
2737 if (!cmd->hasDrawCmd) {
2738 skip |= LogPerformanceWarning(
2739 commandBuffer, kVUID_BestPractices_DrawState_ClearCmdBeforeDraw,
2740 "vkCmdClearAttachments() issued on %s prior to any Draw Cmds. It is recommended you "
2741 "use RenderPass LOAD_OP_CLEAR on Attachments prior to any Draw.",
2742 report_data->FormatHandle(commandBuffer).c_str());
2743 }
2744
2745 if ((new_aspects & VK_IMAGE_ASPECT_COLOR_BIT) &&
2746 rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2747 skip |= LogPerformanceWarning(
2748 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2749 "%svkCmdClearAttachments() issued on %s for color attachment #%u in this subpass, "
2750 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2751 "it is more efficient.",
2752 secondary ? "vkCmdExecuteCommands(): " : "",
2753 report_data->FormatHandle(commandBuffer).c_str(), color_attachment);
2754 }
2755
2756 if ((new_aspects & VK_IMAGE_ASPECT_DEPTH_BIT) &&
2757 rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2758 skip |= LogPerformanceWarning(
2759 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2760 "%svkCmdClearAttachments() issued on %s for the depth attachment in this subpass, "
2761 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2762 "it is more efficient.",
2763 secondary ? "vkCmdExecuteCommands(): " : "",
2764 report_data->FormatHandle(commandBuffer).c_str());
2765 }
2766
2767 if ((new_aspects & VK_IMAGE_ASPECT_STENCIL_BIT) &&
2768 rp->createInfo.pAttachments[fb_attachment].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2769 skip |= LogPerformanceWarning(
2770 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2771 "%svkCmdClearAttachments() issued on %s for the stencil attachment in this subpass, "
2772 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2773 "it is more efficient.",
2774 secondary ? "vkCmdExecuteCommands(): " : "",
2775 report_data->FormatHandle(commandBuffer).c_str());
2776 }
2777
2778 return skip;
2779}
2780
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002781bool BestPractices::PreCallValidateCmdClearAttachments(VkCommandBuffer commandBuffer, uint32_t attachmentCount,
Camden Stockerf55721f2019-09-09 11:04:49 -06002782 const VkClearAttachment* pAttachments, uint32_t rectCount,
2783 const VkClearRect* pRects) const {
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002784 bool skip = false;
2785 const CMD_BUFFER_STATE* cb_node = GetCBState(commandBuffer);
2786 if (!cb_node) return skip;
2787
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002788 if (cb_node->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
2789 // Defer checks to ExecuteCommands.
2790 return skip;
2791 }
2792
2793 // Only care about full clears, partial clears might have legitimate uses.
2794 if (!ClearAttachmentsIsFullClear(cb_node, rectCount, pRects)) {
2795 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002796 }
2797
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002798 // Check for uses of ClearAttachments along with LOAD_OP_LOAD,
2799 // as it can be more efficient to just use LOAD_OP_CLEAR
locke-lunargaecf2152020-05-12 17:15:41 -06002800 const RENDER_PASS_STATE* rp = cb_node->activeRenderPass.get();
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002801 if (rp) {
2802 const auto& subpass = rp->createInfo.pSubpasses[cb_node->activeSubpass];
2803
2804 for (uint32_t i = 0; i < attachmentCount; i++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002805 const auto& attachment = pAttachments[i];
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002806
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002807 if (attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
2808 uint32_t color_attachment = attachment.colorAttachment;
2809 uint32_t fb_attachment = subpass.pColorAttachments[color_attachment].attachment;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002810 skip |= ValidateClearAttachment(commandBuffer, cb_node,
2811 fb_attachment, color_attachment,
2812 attachment.aspectMask, false);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002813 }
2814
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002815 if (subpass.pDepthStencilAttachment &&
2816 (attachment.aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT))) {
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002817 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002818 skip |= ValidateClearAttachment(commandBuffer, cb_node,
2819 fb_attachment, VK_ATTACHMENT_UNUSED,
2820 attachment.aspectMask, false);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002821 }
2822 }
2823 }
2824
Camden Stockerf55721f2019-09-09 11:04:49 -06002825 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002826}
Attilio Provenzano02859b22020-02-27 14:17:28 +00002827
2828bool BestPractices::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
2829 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
2830 const VkImageResolve* pRegions) const {
2831 bool skip = false;
2832
2833 skip |= VendorCheckEnabled(kBPVendorArm) &&
2834 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage_ResolvingImage,
2835 "%s Attempting to use vkCmdResolveImage to resolve a multisampled image. "
2836 "This is a very slow and extremely bandwidth intensive path. "
2837 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
2838 VendorSpecificTag(kBPVendorArm));
2839
2840 return skip;
2841}
2842
Jeff Leger178b1e52020-10-05 12:22:23 -04002843bool BestPractices::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
2844 const VkResolveImageInfo2KHR* pResolveImageInfo) const {
2845 bool skip = false;
2846
2847 skip |= VendorCheckEnabled(kBPVendorArm) &&
2848 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2KHR_ResolvingImage,
2849 "%s Attempting to use vkCmdResolveImage2KHR to resolve a multisampled image. "
2850 "This is a very slow and extremely bandwidth intensive path. "
2851 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
2852 VendorSpecificTag(kBPVendorArm));
2853
2854 return skip;
2855}
2856
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002857void BestPractices::PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
2858 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
2859 const VkImageResolve* pRegions) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01002860 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002861 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002862 auto* src = GetImageUsageState(srcImage);
2863 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002864
2865 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002866 QueueValidateImage(funcs, "vkCmdResolveImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pRegions[i].srcSubresource);
2867 QueueValidateImage(funcs, "vkCmdResolveImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002868 }
2869}
2870
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01002871void BestPractices::PreCallRecordCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
2872 const VkResolveImageInfo2KHR* pResolveImageInfo) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01002873 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002874 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002875 auto* src = GetImageUsageState(pResolveImageInfo->srcImage);
2876 auto* dst = GetImageUsageState(pResolveImageInfo->dstImage);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01002877 uint32_t regionCount = pResolveImageInfo->regionCount;
2878
2879 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002880 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pResolveImageInfo->pRegions[i].srcSubresource);
2881 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pResolveImageInfo->pRegions[i].dstSubresource);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01002882 }
2883}
2884
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002885void BestPractices::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
2886 const VkClearColorValue* pColor, uint32_t rangeCount,
2887 const VkImageSubresourceRange* pRanges) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01002888 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002889 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002890 auto* dst = GetImageUsageState(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002891
2892 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002893 QueueValidateImage(funcs, "vkCmdClearColorImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002894 }
2895}
2896
2897void BestPractices::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
2898 const VkClearDepthStencilValue* pDepthStencil, uint32_t rangeCount,
2899 const VkImageSubresourceRange* pRanges) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01002900 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002901 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002902 auto* dst = GetImageUsageState(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002903
2904 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002905 QueueValidateImage(funcs, "vkCmdClearDepthStencilImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002906 }
2907}
2908
2909void BestPractices::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
2910 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
2911 const VkImageCopy* pRegions) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01002912 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002913 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002914 auto* src = GetImageUsageState(srcImage);
2915 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002916
2917 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002918 QueueValidateImage(funcs, "vkCmdCopyImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].srcSubresource);
2919 QueueValidateImage(funcs, "vkCmdCopyImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002920 }
2921}
2922
2923void BestPractices::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
2924 VkImageLayout dstImageLayout, uint32_t regionCount,
2925 const VkBufferImageCopy* pRegions) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01002926 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002927 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002928 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002929
2930 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002931 QueueValidateImage(funcs, "vkCmdCopyBufferToImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002932 }
2933}
2934
2935void BestPractices::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
2936 VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy* pRegions) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01002937 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002938 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002939 auto* src = GetImageUsageState(srcImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002940
2941 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002942 QueueValidateImage(funcs, "vkCmdCopyImageToBuffer()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002943 }
2944}
2945
2946void BestPractices::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
2947 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
2948 const VkImageBlit* pRegions, VkFilter filter) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01002949 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002950 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002951 auto* src = GetImageUsageState(srcImage);
2952 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002953
2954 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002955 QueueValidateImage(funcs, "vkCmdBlitImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_READ, pRegions[i].srcSubresource);
2956 QueueValidateImage(funcs, "vkCmdBlitImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002957 }
2958}
2959
Attilio Provenzano02859b22020-02-27 14:17:28 +00002960bool BestPractices::PreCallValidateCreateSampler(VkDevice device, const VkSamplerCreateInfo* pCreateInfo,
2961 const VkAllocationCallbacks* pAllocator, VkSampler* pSampler) const {
2962 bool skip = false;
2963
2964 if (VendorCheckEnabled(kBPVendorArm)) {
2965 if ((pCreateInfo->addressModeU != pCreateInfo->addressModeV) || (pCreateInfo->addressModeV != pCreateInfo->addressModeW)) {
2966 skip |= LogPerformanceWarning(
2967 device, kVUID_BestPractices_CreateSampler_DifferentWrappingModes,
2968 "%s Creating a sampler object with wrapping modes which do not match (U = %u, V = %u, W = %u). "
2969 "This may cause reduced performance even if only U (1D image) or U/V wrapping modes (2D "
2970 "image) are actually used. If you need different wrapping modes, disregard this warning.",
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -06002971 VendorSpecificTag(kBPVendorArm), pCreateInfo->addressModeU, pCreateInfo->addressModeV, pCreateInfo->addressModeW);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002972 }
2973
2974 if ((pCreateInfo->minLod != 0.0f) || (pCreateInfo->maxLod < VK_LOD_CLAMP_NONE)) {
2975 skip |= LogPerformanceWarning(
2976 device, kVUID_BestPractices_CreateSampler_LodClamping,
2977 "%s Creating a sampler object with LOD clamping (minLod = %f, maxLod = %f). This may cause reduced performance. "
2978 "Instead of clamping LOD in the sampler, consider using an VkImageView which restricts the mip-levels, set minLod "
2979 "to 0.0, and maxLod to VK_LOD_CLAMP_NONE.",
2980 VendorSpecificTag(kBPVendorArm), pCreateInfo->minLod, pCreateInfo->maxLod);
2981 }
2982
2983 if (pCreateInfo->mipLodBias != 0.0f) {
2984 skip |=
2985 LogPerformanceWarning(device, kVUID_BestPractices_CreateSampler_LodBias,
2986 "%s Creating a sampler object with LOD bias != 0.0 (%f). This will lead to less efficient "
2987 "descriptors being created and may cause reduced performance.",
2988 VendorSpecificTag(kBPVendorArm), pCreateInfo->mipLodBias);
2989 }
2990
2991 if ((pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
2992 pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
2993 pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER) &&
2994 (pCreateInfo->borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK)) {
2995 skip |= LogPerformanceWarning(
2996 device, kVUID_BestPractices_CreateSampler_BorderClampColor,
2997 "%s Creating a sampler object with border clamping and borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK. "
2998 "This will lead to less efficient descriptors being created and may cause reduced performance. "
2999 "If possible, use VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK as the border color.",
3000 VendorSpecificTag(kBPVendorArm));
3001 }
3002
3003 if (pCreateInfo->unnormalizedCoordinates) {
3004 skip |= LogPerformanceWarning(
3005 device, kVUID_BestPractices_CreateSampler_UnnormalizedCoordinates,
3006 "%s Creating a sampler object with unnormalized coordinates. This will lead to less efficient "
3007 "descriptors being created and may cause reduced performance.",
3008 VendorSpecificTag(kBPVendorArm));
3009 }
3010
3011 if (pCreateInfo->anisotropyEnable) {
3012 skip |= LogPerformanceWarning(
3013 device, kVUID_BestPractices_CreateSampler_Anisotropy,
3014 "%s Creating a sampler object with anisotropy. This will lead to less efficient descriptors being created "
3015 "and may cause reduced performance.",
3016 VendorSpecificTag(kBPVendorArm));
3017 }
3018 }
3019
3020 return skip;
3021}
Sam Walls8e77e4f2020-03-16 20:47:40 +00003022
3023void BestPractices::PostTransformLRUCacheModel::resize(size_t size) { _entries.resize(size); }
3024
3025bool BestPractices::PostTransformLRUCacheModel::query_cache(uint32_t value) {
3026 // look for a cache hit
3027 auto hit = std::find_if(_entries.begin(), _entries.end(), [value](const CacheEntry& entry) { return entry.value == value; });
3028 if (hit != _entries.end()) {
3029 // mark the cache hit as being most recently used
3030 hit->age = iteration++;
3031 return true;
3032 }
3033
3034 // if there's no cache hit, we need to model the entry being inserted into the cache
3035 CacheEntry new_entry = {value, iteration};
3036 if (iteration < static_cast<uint32_t>(std::distance(_entries.begin(), _entries.end()))) {
3037 // if there is still space left in the cache, use the next available slot
3038 *(_entries.begin() + iteration) = new_entry;
3039 } else {
3040 // otherwise replace the least recently used cache entry
3041 auto lru = std::min_element(_entries.begin(), hit, [](const CacheEntry& a, const CacheEntry& b) { return a.age < b.age; });
3042 *lru = new_entry;
3043 }
3044 iteration++;
3045 return false;
3046}
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003047
3048bool BestPractices::PreCallValidateAcquireNextImageKHR(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout,
3049 VkSemaphore semaphore, VkFence fence, uint32_t* pImageIndex) const {
3050 const auto swapchain_data = GetSwapchainState(swapchain);
3051 bool skip = false;
3052 if (swapchain_data && swapchain_data->images.size() == 0) {
3053 skip |= LogWarning(swapchain, kVUID_Core_DrawState_SwapchainImagesNotFound,
3054 "vkAcquireNextImageKHR: No images found to acquire from. Application probably did not call "
3055 "vkGetSwapchainImagesKHR after swapchain creation.");
3056 }
3057 return skip;
3058}
3059
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003060void BestPractices::CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(CALL_STATE& call_state, bool no_pointer) {
3061 if (no_pointer) {
3062 if (UNCALLED == call_state) {
3063 call_state = QUERY_COUNT;
3064 }
3065 } else { // Save queue family properties
3066 call_state = QUERY_DETAILS;
3067 }
3068}
3069
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003070void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
3071 uint32_t* pQueueFamilyPropertyCount,
3072 VkQueueFamilyProperties* pQueueFamilyProperties) {
3073 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(physicalDevice, pQueueFamilyPropertyCount,
3074 pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003075 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003076 if (bp_pd_state) {
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003077 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
3078 nullptr == pQueueFamilyProperties);
3079 }
3080}
3081
3082void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
3083 uint32_t* pQueueFamilyPropertyCount,
3084 VkQueueFamilyProperties2* pQueueFamilyProperties) {
3085 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(physicalDevice, pQueueFamilyPropertyCount,
3086 pQueueFamilyProperties);
3087 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3088 if (bp_pd_state) {
3089 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
3090 nullptr == pQueueFamilyProperties);
3091 }
3092}
3093
3094void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(VkPhysicalDevice physicalDevice,
3095 uint32_t* pQueueFamilyPropertyCount,
3096 VkQueueFamilyProperties2* pQueueFamilyProperties) {
3097 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(physicalDevice, pQueueFamilyPropertyCount,
3098 pQueueFamilyProperties);
3099 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3100 if (bp_pd_state) {
3101 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
3102 nullptr == pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003103 }
3104}
3105
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003106void BestPractices::PostCallRecordGetPhysicalDeviceFeatures(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures* pFeatures) {
3107 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003108 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3109 if (bp_pd_state) {
3110 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3111 }
3112}
3113
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003114void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2(VkPhysicalDevice physicalDevice,
3115 VkPhysicalDeviceFeatures2* pFeatures) {
3116 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003117 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3118 if (bp_pd_state) {
3119 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3120 }
3121}
3122
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003123void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2KHR(VkPhysicalDevice physicalDevice,
3124 VkPhysicalDeviceFeatures2* pFeatures) {
3125 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2KHR(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003126 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3127 if (bp_pd_state) {
3128 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3129 }
3130}
3131
3132void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilitiesKHR(VkPhysicalDevice physicalDevice,
3133 VkSurfaceKHR surface,
3134 VkSurfaceCapabilitiesKHR* pSurfaceCapabilities,
3135 VkResult result) {
3136 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3137 if (bp_pd_state) {
3138 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3139 }
3140}
3141
3142void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2KHR(
3143 VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
3144 VkSurfaceCapabilities2KHR* pSurfaceCapabilities, VkResult result) {
3145 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3146 if (bp_pd_state) {
3147 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3148 }
3149}
3150
3151void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2EXT(VkPhysicalDevice physicalDevice,
3152 VkSurfaceKHR surface,
3153 VkSurfaceCapabilities2EXT* pSurfaceCapabilities,
3154 VkResult result) {
3155 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3156 if (bp_pd_state) {
3157 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3158 }
3159}
3160
3161void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice physicalDevice,
3162 VkSurfaceKHR surface, uint32_t* pPresentModeCount,
3163 VkPresentModeKHR* pPresentModes, VkResult result) {
3164 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
3165 if (bp_pd_data) {
3166 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfacePresentModesKHRState;
3167
3168 if (*pPresentModeCount) {
3169 if (call_state < QUERY_COUNT) {
3170 call_state = QUERY_COUNT;
3171 }
3172 }
3173 if (pPresentModes) {
3174 if (call_state < QUERY_DETAILS) {
3175 call_state = QUERY_DETAILS;
3176 }
3177 }
3178 }
3179}
3180
3181void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
3182 uint32_t* pSurfaceFormatCount,
3183 VkSurfaceFormatKHR* pSurfaceFormats, VkResult result) {
3184 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
3185 if (bp_pd_data) {
3186 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState;
3187
3188 if (*pSurfaceFormatCount) {
3189 if (call_state < QUERY_COUNT) {
3190 call_state = QUERY_COUNT;
3191 }
3192 }
3193 if (pSurfaceFormats) {
3194 if (call_state < QUERY_DETAILS) {
3195 call_state = QUERY_DETAILS;
3196 }
3197 }
3198 }
3199}
3200
3201void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormats2KHR(VkPhysicalDevice physicalDevice,
3202 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
3203 uint32_t* pSurfaceFormatCount,
3204 VkSurfaceFormat2KHR* pSurfaceFormats, VkResult result) {
3205 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
3206 if (bp_pd_data) {
3207 if (*pSurfaceFormatCount) {
3208 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_COUNT) {
3209 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_COUNT;
3210 }
3211 }
3212 if (pSurfaceFormats) {
3213 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_DETAILS) {
3214 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_DETAILS;
3215 }
3216 }
3217 }
3218}
3219
3220void BestPractices::ManualPostCallRecordGetPhysicalDeviceDisplayPlanePropertiesKHR(VkPhysicalDevice physicalDevice,
3221 uint32_t* pPropertyCount,
3222 VkDisplayPlanePropertiesKHR* pProperties,
3223 VkResult result) {
3224 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
3225 if (bp_pd_data) {
3226 if (*pPropertyCount) {
3227 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_COUNT) {
3228 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_COUNT;
3229 }
3230 }
3231 if (pProperties) {
3232 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_DETAILS) {
3233 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_DETAILS;
3234 }
3235 }
3236 }
3237}
3238
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003239void BestPractices::ManualPostCallRecordGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain,
3240 uint32_t* pSwapchainImageCount, VkImage* pSwapchainImages,
3241 VkResult result) {
Nathaniel Cesario39152e62021-07-02 13:04:16 -06003242 auto* swapchain_state = static_cast<SWAPCHAIN_STATE_BP*>(Get<SWAPCHAIN_NODE>(swapchain));
3243 if (swapchain_state && (pSwapchainImages || *pSwapchainImageCount)) {
3244 if (swapchain_state->vkGetSwapchainImagesKHRState < QUERY_DETAILS) {
3245 swapchain_state->vkGetSwapchainImagesKHRState = QUERY_DETAILS;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003246 }
3247 }
3248}
3249
3250void BestPractices::ManualPostCallRecordEnumeratePhysicalDevices(VkInstance instance, uint32_t* pPhysicalDeviceCount,
3251 VkPhysicalDevice* pPhysicalDevices, VkResult result) {
3252 if ((nullptr != pPhysicalDevices) && ((result == VK_SUCCESS || result == VK_INCOMPLETE))) {
3253 for (uint32_t i = 0; i < *pPhysicalDeviceCount; i++) {
3254 phys_device_bp_state_map.emplace(pPhysicalDevices[i], PHYSICAL_DEVICE_STATE_BP{});
3255 }
3256 }
3257}
3258
3259void BestPractices::ManualPostCallRecordCreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo*, const VkAllocationCallbacks*,
3260 VkDevice*, VkResult result) {
3261 if (VK_SUCCESS == result) {
3262 instance_device_bp_state = &phys_device_bp_state_map[gpu];
3263 }
3264}
3265
3266PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP(const VkPhysicalDevice& phys_device) {
3267 if (phys_device_bp_state_map.count(phys_device) > 0) {
3268 return &phys_device_bp_state_map.at(phys_device);
3269 } else {
3270 return nullptr;
3271 }
3272}
3273
3274const PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP(const VkPhysicalDevice& phys_device) const {
3275 if (phys_device_bp_state_map.count(phys_device) > 0) {
3276 return &phys_device_bp_state_map.at(phys_device);
3277 } else {
3278 return nullptr;
3279 }
3280}
3281
3282PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP() {
3283 auto bp_state = (reinterpret_cast<BestPractices*>(instance_state))->instance_device_bp_state;
3284 if (bp_state) {
3285 return bp_state;
3286 } else if (!bp_state && phys_device_bp_state_map.count(physical_device_state->phys_device) > 0) {
3287 return &phys_device_bp_state_map.at(physical_device_state->phys_device);
3288 } else {
3289 return nullptr;
3290 }
3291}
3292
3293const PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP() const {
3294 auto bp_state = (reinterpret_cast<BestPractices*>(instance_state))->instance_device_bp_state;
3295 if (bp_state) {
3296 return bp_state;
3297 } else if (!bp_state && phys_device_bp_state_map.count(physical_device_state->phys_device) > 0) {
3298 return &phys_device_bp_state_map.at(physical_device_state->phys_device);
3299 } else {
3300 return nullptr;
3301 }
3302}
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003303
3304void BestPractices::PreCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits, VkFence fence) {
3305 ValidationStateTracker::PreCallRecordQueueSubmit(queue, submitCount, pSubmits, fence);
3306
3307 QUEUE_STATE* queue_state = GetQueueState(queue);
3308 for (uint32_t submit = 0; submit < submitCount; submit++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02003309 const auto& submit_info = pSubmits[submit];
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003310 for (uint32_t cb_index = 0; cb_index < submit_info.commandBufferCount; cb_index++) {
3311 CMD_BUFFER_STATE* cb = GetCBState(submit_info.pCommandBuffers[cb_index]);
3312 for (auto &func : cb->queue_submit_functions) {
3313 func(this, queue_state);
3314 }
3315 }
3316 }
3317}