blob: 765d9fc9220debc5aa6c08291b0823b4a2a3c226 [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"
Camden5b184be2019-08-13 07:50:19 -060025
26#include <string>
Sam Walls8e77e4f2020-03-16 20:47:40 +000027#include <bitset>
Sam Wallsd7ab6db2020-06-19 20:41:54 +010028#include <memory>
Camden5b184be2019-08-13 07:50:19 -060029
Attilio Provenzano19d6a982020-02-27 12:41:41 +000030struct VendorSpecificInfo {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060031 EnableFlags vendor_id;
Attilio Provenzano19d6a982020-02-27 12:41:41 +000032 std::string name;
33};
34
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -070035const std::map<BPVendorFlagBits, VendorSpecificInfo> kVendorInfo = {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060036 {kBPVendorArm, {vendor_specific_arm, "Arm"}},
Attilio Provenzano19d6a982020-02-27 12:41:41 +000037};
38
39bool BestPractices::VendorCheckEnabled(BPVendorFlags vendors) const {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -070040 for (const auto& vendor : kVendorInfo) {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060041 if (vendors & vendor.first && enabled[vendor.second.vendor_id]) {
Attilio Provenzano19d6a982020-02-27 12:41:41 +000042 return true;
43 }
44 }
45 return false;
46}
47
48const char* VendorSpecificTag(BPVendorFlags vendors) {
49 // Cache built vendor tags in a map
Jeremy Gebbencbf22862021-03-03 12:01:22 -070050 static layer_data::unordered_map<BPVendorFlags, std::string> tag_map;
Attilio Provenzano19d6a982020-02-27 12:41:41 +000051
52 auto res = tag_map.find(vendors);
53 if (res == tag_map.end()) {
54 // Build the vendor tag string
55 std::stringstream vendor_tag;
56
57 vendor_tag << "[";
58 bool first_vendor = true;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -070059 for (const auto& vendor : kVendorInfo) {
Attilio Provenzano19d6a982020-02-27 12:41:41 +000060 if (vendors & vendor.first) {
61 if (!first_vendor) {
62 vendor_tag << ", ";
63 }
64 vendor_tag << vendor.second.name;
65 first_vendor = false;
66 }
67 }
68 vendor_tag << "]";
69
70 tag_map[vendors] = vendor_tag.str();
71 res = tag_map.find(vendors);
72 }
73
74 return res->second.c_str();
75}
76
Mark Lobodzinski6167e102020-02-24 17:03:55 -070077const char* DepReasonToString(ExtDeprecationReason reason) {
78 switch (reason) {
79 case kExtPromoted:
80 return "promoted to";
81 break;
82 case kExtObsoleted:
83 return "obsoleted by";
84 break;
85 case kExtDeprecated:
86 return "deprecated by";
87 break;
88 default:
89 return "";
90 break;
91 }
92}
93
94bool BestPractices::ValidateDeprecatedExtensions(const char* api_name, const char* extension_name, uint32_t version,
95 const char* vuid) const {
96 bool skip = false;
97 auto dep_info_it = deprecated_extensions.find(extension_name);
98 if (dep_info_it != deprecated_extensions.end()) {
99 auto dep_info = dep_info_it->second;
Mark Lobodzinski6a149702020-05-14 12:21:34 -0600100 if (((dep_info.target.compare("VK_VERSION_1_1") == 0) && (version >= VK_API_VERSION_1_1)) ||
101 ((dep_info.target.compare("VK_VERSION_1_2") == 0) && (version >= VK_API_VERSION_1_2))) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700102 skip |=
103 LogWarning(instance, vuid, "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
104 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
Mark Lobodzinski6a149702020-05-14 12:21:34 -0600105 } else if (dep_info.target.find("VK_VERSION") == std::string::npos) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700106 if (dep_info.target.length() == 0) {
107 skip |= LogWarning(instance, vuid,
108 "%s(): Attempting to enable deprecated extension %s, but this extension has been deprecated "
109 "without replacement.",
110 api_name, extension_name);
111 } else {
112 skip |= LogWarning(instance, vuid,
113 "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
114 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
115 }
116 }
117 }
118 return skip;
119}
120
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700121bool BestPractices::ValidateSpecialUseExtensions(const char* api_name, const char* extension_name, const char* vuid) const {
122 bool skip = false;
123 auto dep_info_it = special_use_extensions.find(extension_name);
124
125 if (dep_info_it != special_use_extensions.end()) {
126 auto special_uses = dep_info_it->second;
127 std::string message("is intended to support the following uses: ");
128 if (special_uses.find("cadsupport") != std::string::npos) {
129 message.append("specialized functionality used by CAD/CAM applications, ");
130 }
131 if (special_uses.find("d3demulation") != std::string::npos) {
132 message.append("D3D emulation layers, and applications ported from D3D, by adding functionality specific to D3D, ");
133 }
134 if (special_uses.find("devtools") != std::string::npos) {
135 message.append(" developer tools such as capture-replay libraries, ");
136 }
137 if (special_uses.find("debugging") != std::string::npos) {
138 message.append("use by applications when debugging, ");
139 }
140 if (special_uses.find("glemulation") != std::string::npos) {
141 message.append(
142 "OpenGL and/or OpenGL ES emulation layers, and applications ported from those APIs, by adding functionality "
143 "specific to those APIs, ");
144 }
145 message.append("and it is strongly recommended that they be otherwise avoided");
146
147 skip |= LogWarning(instance, vuid, "%s(): Attempting to enable extension %s, but this extension %s.", api_name,
148 extension_name, message.c_str());
149 }
150 return skip;
151}
152
Camden5b184be2019-08-13 07:50:19 -0600153bool BestPractices::PreCallValidateCreateInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500154 VkInstance* pInstance) const {
Camden5b184be2019-08-13 07:50:19 -0600155 bool skip = false;
156
157 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
158 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kDeviceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800159 skip |= LogWarning(instance, kVUID_BestPractices_CreateInstance_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700160 "vkCreateInstance(): Attempting to enable Device Extension %s at CreateInstance time.",
161 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600162 }
Mark Lobodzinski17d8dc62020-06-03 08:48:58 -0600163 uint32_t specified_version =
164 (pCreateInfo->pApplicationInfo ? pCreateInfo->pApplicationInfo->apiVersion : VK_API_VERSION_1_0);
165 skip |= ValidateDeprecatedExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i], specified_version,
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700166 kVUID_BestPractices_CreateInstance_DeprecatedExtension);
Mark Lobodzinskia431b772020-11-10 08:12:13 -0700167 skip |= ValidateSpecialUseExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i],
168 kVUID_BestPractices_CreateInstance_SpecialUseExtension);
Camden5b184be2019-08-13 07:50:19 -0600169 }
170
171 return skip;
172}
173
174void BestPractices::PreCallRecordCreateInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator,
175 VkInstance* pInstance) {
Mark Lobodzinski97484d62020-03-03 11:57:41 -0700176 ValidationStateTracker::PreCallRecordCreateInstance(pCreateInfo, pAllocator, pInstance);
Sam Walls53bf7652020-04-21 17:35:15 +0100177
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700178 if (pCreateInfo != nullptr && pCreateInfo->pApplicationInfo != nullptr) {
Sam Walls53bf7652020-04-21 17:35:15 +0100179 instance_api_version = pCreateInfo->pApplicationInfo->apiVersion;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700180 } else {
Sam Walls53bf7652020-04-21 17:35:15 +0100181 instance_api_version = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700182 }
Camden5b184be2019-08-13 07:50:19 -0600183}
184
185bool BestPractices::PreCallValidateCreateDevice(VkPhysicalDevice physicalDevice, const VkDeviceCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500186 const VkAllocationCallbacks* pAllocator, VkDevice* pDevice) const {
Camden5b184be2019-08-13 07:50:19 -0600187 bool skip = false;
188
189 // get API version of physical device passed when creating device.
190 VkPhysicalDeviceProperties physical_device_properties{};
191 DispatchGetPhysicalDeviceProperties(physicalDevice, &physical_device_properties);
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500192 auto device_api_version = physical_device_properties.apiVersion;
Camden5b184be2019-08-13 07:50:19 -0600193
194 // check api versions and warn if instance api Version is higher than version on device.
195 if (instance_api_version > device_api_version) {
Mark Lobodzinski60880782020-08-11 08:02:07 -0600196 std::string inst_api_name = StringAPIVersion(instance_api_version);
197 std::string dev_api_name = StringAPIVersion(device_api_version);
Camden5b184be2019-08-13 07:50:19 -0600198
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700199 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_API_Mismatch,
200 "vkCreateDevice(): API Version of current instance, %s is higher than API Version on device, %s",
201 inst_api_name.c_str(), dev_api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -0600202 }
203
204 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
205 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kInstanceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800206 skip |= LogWarning(instance, kVUID_BestPractices_CreateDevice_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700207 "vkCreateDevice(): Attempting to enable Instance Extension %s at CreateDevice time.",
208 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600209 }
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700210 skip |= ValidateDeprecatedExtensions("CreateDevice", pCreateInfo->ppEnabledExtensionNames[i], instance_api_version,
211 kVUID_BestPractices_CreateDevice_DeprecatedExtension);
Mark Lobodzinskia431b772020-11-10 08:12:13 -0700212 skip |= ValidateSpecialUseExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i],
213 kVUID_BestPractices_CreateDevice_SpecialUseExtension);
Camden5b184be2019-08-13 07:50:19 -0600214 }
215
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600216 const auto bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
217 if ((bp_pd_state->vkGetPhysicalDeviceFeaturesState == UNCALLED) && (pCreateInfo->pEnabledFeatures != NULL)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700218 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_PDFeaturesNotCalled,
219 "vkCreateDevice() called before getting physical device features from vkGetPhysicalDeviceFeatures().");
Camden83a9c372019-08-14 11:41:38 -0600220 }
221
Szilard Papp7d2c7952020-06-22 14:38:13 +0100222 if ((VendorCheckEnabled(kBPVendorArm)) && (pCreateInfo->pEnabledFeatures != nullptr) &&
223 (pCreateInfo->pEnabledFeatures->robustBufferAccess == VK_TRUE)) {
224 skip |= LogPerformanceWarning(
225 device, kVUID_BestPractices_CreateDevice_RobustBufferAccess,
226 "%s vkCreateDevice() called with enabled robustBufferAccess. Use robustBufferAccess as a debugging tool during "
227 "development. Enabling it causes loss in performance for accesses to uniform buffers and shader storage "
228 "buffers. Disable robustBufferAccess in release builds. Only leave it enabled if the application use-case "
229 "requires the additional level of reliability due to the use of unverified user-supplied draw parameters.",
230 VendorSpecificTag(kBPVendorArm));
231 }
232
Camden5b184be2019-08-13 07:50:19 -0600233 return skip;
234}
235
236bool BestPractices::PreCallValidateCreateBuffer(VkDevice device, const VkBufferCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500237 const VkAllocationCallbacks* pAllocator, VkBuffer* pBuffer) const {
Camden5b184be2019-08-13 07:50:19 -0600238 bool skip = false;
239
240 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700241 std::stringstream buffer_hex;
242 buffer_hex << "0x" << std::hex << HandleToUint64(pBuffer);
Camden5b184be2019-08-13 07:50:19 -0600243
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700244 skip |= LogWarning(
245 device, kVUID_BestPractices_SharingModeExclusive,
246 "Warning: Buffer (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
247 "(queueFamilyIndexCount of %" PRIu32 ").",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700248 buffer_hex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600249 }
250
251 return skip;
252}
253
254bool BestPractices::PreCallValidateCreateImage(VkDevice device, const VkImageCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500255 const VkAllocationCallbacks* pAllocator, VkImage* pImage) const {
Camden5b184be2019-08-13 07:50:19 -0600256 bool skip = false;
257
258 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700259 std::stringstream image_hex;
260 image_hex << "0x" << std::hex << HandleToUint64(pImage);
Camden5b184be2019-08-13 07:50:19 -0600261
262 skip |=
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700263 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
264 "Warning: Image (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
265 "(queueFamilyIndexCount of %" PRIu32 ").",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700266 image_hex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600267 }
268
Attilio Provenzano02859b22020-02-27 14:17:28 +0000269 if (VendorCheckEnabled(kBPVendorArm)) {
270 if (pCreateInfo->samples > kMaxEfficientSamplesArm) {
271 skip |= LogPerformanceWarning(
272 device, kVUID_BestPractices_CreateImage_TooLargeSampleCount,
273 "%s vkCreateImage(): Trying to create an image with %u samples. "
274 "The hardware revision may not have full throughput for framebuffers with more than %u samples.",
275 VendorSpecificTag(kBPVendorArm), static_cast<uint32_t>(pCreateInfo->samples), kMaxEfficientSamplesArm);
276 }
277
278 if (pCreateInfo->samples > VK_SAMPLE_COUNT_1_BIT && !(pCreateInfo->usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT)) {
279 skip |= LogPerformanceWarning(
280 device, kVUID_BestPractices_CreateImage_NonTransientMSImage,
281 "%s vkCreateImage(): Trying to create a multisampled image, but createInfo.usage did not have "
282 "VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. Multisampled images may be resolved on-chip, "
283 "and do not need to be backed by physical storage. "
284 "TRANSIENT_ATTACHMENT allows tiled GPUs to not back the multisampled image with physical memory.",
285 VendorSpecificTag(kBPVendorArm));
286 }
287 }
288
Camden5b184be2019-08-13 07:50:19 -0600289 return skip;
290}
291
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +0100292void BestPractices::PreCallRecordDestroyImage(VkDevice device, VkImage image, const VkAllocationCallbacks *pAllocator) {
293 ValidationStateTracker::PreCallRecordDestroyImage(device, image, pAllocator);
294 ReleaseImageUsageState(image);
295}
296
297IMAGE_STATE_BP* BestPractices::GetImageUsageState(VkImage vk_image) {
298 auto itr = imageUsageMap.find(vk_image);
299 if (itr != imageUsageMap.end()) {
300 return &itr->second;
301 } else {
302 auto& state = imageUsageMap[vk_image];
303 IMAGE_STATE* image = GetImageState(vk_image);
304 state.image = image;
305 state.usages.resize(image->createInfo.arrayLayers);
306 for (auto& mips : state.usages) {
307 mips.resize(image->createInfo.mipLevels, IMAGE_SUBRESOURCE_USAGE_BP::UNDEFINED);
308 }
309 return &state;
310 }
311}
312
313void BestPractices::ReleaseImageUsageState(VkImage image) {
314 auto itr = imageUsageMap.find(image);
315 if (itr != imageUsageMap.end()) {
316 imageUsageMap.erase(itr);
317 }
318}
319
Camden5b184be2019-08-13 07:50:19 -0600320bool BestPractices::PreCallValidateCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500321 const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain) const {
Camden5b184be2019-08-13 07:50:19 -0600322 bool skip = false;
323
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600324 const auto* bp_pd_state = GetPhysicalDeviceStateBP();
325 if (bp_pd_state) {
326 if (bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState == UNCALLED) {
327 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
328 "vkCreateSwapchainKHR() called before getting surface capabilities from "
329 "vkGetPhysicalDeviceSurfaceCapabilitiesKHR().");
330 }
Camden83a9c372019-08-14 11:41:38 -0600331
Shannon McPherson73e58c82021-03-05 17:14:26 -0700332 if ((pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR) &&
333 (bp_pd_state->vkGetPhysicalDeviceSurfacePresentModesKHRState != QUERY_DETAILS)) {
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600334 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
335 "vkCreateSwapchainKHR() called before getting surface present mode(s) from "
336 "vkGetPhysicalDeviceSurfacePresentModesKHR().");
337 }
Camden83a9c372019-08-14 11:41:38 -0600338
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600339 if (bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState != QUERY_DETAILS) {
340 skip |= LogWarning(
341 device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
342 "vkCreateSwapchainKHR() called before getting surface format(s) from vkGetPhysicalDeviceSurfaceFormatsKHR().");
343 }
Camden83a9c372019-08-14 11:41:38 -0600344 }
345
Camden5b184be2019-08-13 07:50:19 -0600346 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700347 skip |=
348 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
Mark Lobodzinski019f4e32020-04-13 11:01:35 -0600349 "Warning: A Swapchain is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while "
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700350 "specifying multiple queues (queueFamilyIndexCount of %" PRIu32 ").",
351 pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600352 }
353
Szilard Papp48a6da32020-06-10 14:41:59 +0100354 if (pCreateInfo->minImageCount == 2) {
355 skip |= LogPerformanceWarning(
356 device, kVUID_BestPractices_SuboptimalSwapchainImageCount,
357 "Warning: A Swapchain is being created with minImageCount set to %" PRIu32
358 ", which means double buffering is going "
359 "to be used. Using double buffering and vsync locks rendering to an integer fraction of the vsync rate. In turn, "
360 "reducing the performance of the application if rendering is slower than vsync. Consider setting minImageCount to "
361 "3 to use triple buffering to maximize performance in such cases.",
362 pCreateInfo->minImageCount);
363 }
364
Szilard Pappd5f0f812020-06-22 09:01:29 +0100365 if (VendorCheckEnabled(kBPVendorArm) && (pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR)) {
366 skip |= LogWarning(device, kVUID_BestPractices_CreateSwapchain_PresentMode,
367 "%s Warning: Swapchain is not being created with presentation mode \"VK_PRESENT_MODE_FIFO_KHR\". "
368 "Prefer using \"VK_PRESENT_MODE_FIFO_KHR\" to avoid unnecessary CPU and GPU load and save power. "
369 "Presentation modes which are not FIFO will present the latest available frame and discard other "
370 "frame(s) if any.",
371 VendorSpecificTag(kBPVendorArm));
372 }
373
Camden5b184be2019-08-13 07:50:19 -0600374 return skip;
375}
376
377bool BestPractices::PreCallValidateCreateSharedSwapchainsKHR(VkDevice device, uint32_t swapchainCount,
378 const VkSwapchainCreateInfoKHR* pCreateInfos,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500379 const VkAllocationCallbacks* pAllocator,
380 VkSwapchainKHR* pSwapchains) const {
Camden5b184be2019-08-13 07:50:19 -0600381 bool skip = false;
382
383 for (uint32_t i = 0; i < swapchainCount; i++) {
384 if ((pCreateInfos[i].queueFamilyIndexCount > 1) && (pCreateInfos[i].imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700385 skip |= LogWarning(
386 device, kVUID_BestPractices_SharingModeExclusive,
387 "Warning: A shared swapchain (index %" PRIu32
388 ") is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple "
389 "queues (queueFamilyIndexCount of %" PRIu32 ").",
390 i, pCreateInfos[i].queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600391 }
392 }
393
394 return skip;
395}
396
397bool BestPractices::PreCallValidateCreateRenderPass(VkDevice device, const VkRenderPassCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500398 const VkAllocationCallbacks* pAllocator, VkRenderPass* pRenderPass) const {
Camden5b184be2019-08-13 07:50:19 -0600399 bool skip = false;
400
401 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; ++i) {
402 VkFormat format = pCreateInfo->pAttachments[i].format;
403 if (pCreateInfo->pAttachments[i].initialLayout == VK_IMAGE_LAYOUT_UNDEFINED) {
404 if ((FormatIsColor(format) || FormatHasDepth(format)) &&
405 pCreateInfo->pAttachments[i].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700406 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
407 "Render pass has an attachment with loadOp == VK_ATTACHMENT_LOAD_OP_LOAD and "
408 "initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
409 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
410 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600411 }
412 if (FormatHasStencil(format) && pCreateInfo->pAttachments[i].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700413 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
414 "Render pass has an attachment with stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD "
415 "and initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
416 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
417 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600418 }
419 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000420
421 const auto& attachment = pCreateInfo->pAttachments[i];
422 if (attachment.samples > VK_SAMPLE_COUNT_1_BIT) {
423 bool access_requires_memory =
424 attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD || attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE;
425
426 if (FormatHasStencil(format)) {
427 access_requires_memory |= attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
428 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE;
429 }
430
431 if (access_requires_memory) {
432 skip |= LogPerformanceWarning(
433 device, kVUID_BestPractices_CreateRenderPass_ImageRequiresMemory,
434 "Attachment %u in the VkRenderPass is a multisampled image with %u samples, but it uses loadOp/storeOp "
435 "which requires accessing data from memory. Multisampled images should always be loadOp = CLEAR or DONT_CARE, "
436 "storeOp = DONT_CARE. This allows the implementation to use lazily allocated memory effectively.",
437 i, static_cast<uint32_t>(attachment.samples));
438 }
439 }
Camden5b184be2019-08-13 07:50:19 -0600440 }
441
442 for (uint32_t dependency = 0; dependency < pCreateInfo->dependencyCount; dependency++) {
443 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].srcStageMask);
444 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].dstStageMask);
445 }
446
447 return skip;
448}
449
Tony-LunarG767180f2020-04-23 14:03:59 -0600450bool BestPractices::ValidateAttachments(const VkRenderPassCreateInfo2* rpci, uint32_t attachmentCount,
451 const VkImageView* image_views) const {
452 bool skip = false;
453
454 // Check for non-transient attachments that should be transient and vice versa
455 for (uint32_t i = 0; i < attachmentCount; ++i) {
456 auto& attachment = rpci->pAttachments[i];
457 bool attachment_should_be_transient =
458 (attachment.loadOp != VK_ATTACHMENT_LOAD_OP_LOAD && attachment.storeOp != VK_ATTACHMENT_STORE_OP_STORE);
459
460 if (FormatHasStencil(attachment.format)) {
461 attachment_should_be_transient &= (attachment.stencilLoadOp != VK_ATTACHMENT_LOAD_OP_LOAD &&
462 attachment.stencilStoreOp != VK_ATTACHMENT_STORE_OP_STORE);
463 }
464
465 auto view_state = GetImageViewState(image_views[i]);
466 if (view_state) {
467 auto& ivci = view_state->create_info;
468 auto& ici = GetImageState(ivci.image)->createInfo;
469
470 bool image_is_transient = (ici.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) != 0;
471
472 // The check for an image that should not be transient applies to all GPUs
473 if (!attachment_should_be_transient && image_is_transient) {
474 skip |= LogPerformanceWarning(
475 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldNotBeTransient,
476 "Attachment %u in VkFramebuffer uses loadOp/storeOps which need to access physical memory, "
477 "but the image backing the image view has VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
478 "Physical memory will need to be backed lazily to this image, potentially causing stalls.",
479 i);
480 }
481
482 bool supports_lazy = false;
483 for (uint32_t j = 0; j < phys_dev_mem_props.memoryTypeCount; j++) {
484 if (phys_dev_mem_props.memoryTypes[j].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
485 supports_lazy = true;
486 }
487 }
488
489 // The check for an image that should be transient only applies to GPUs supporting
490 // lazily allocated memory
491 if (supports_lazy && attachment_should_be_transient && !image_is_transient) {
492 skip |= LogPerformanceWarning(
493 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldBeTransient,
494 "Attachment %u in VkFramebuffer uses loadOp/storeOps which never have to be backed by physical memory, "
495 "but the image backing the image view does not have VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
496 "You can save physical memory by using transient attachment backed by lazily allocated memory here.",
497 i);
498 }
499 }
500 }
501 return skip;
502}
503
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000504bool BestPractices::PreCallValidateCreateFramebuffer(VkDevice device, const VkFramebufferCreateInfo* pCreateInfo,
505 const VkAllocationCallbacks* pAllocator, VkFramebuffer* pFramebuffer) const {
506 bool skip = false;
507
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000508 auto rp_state = GetRenderPassState(pCreateInfo->renderPass);
Mike Schuchardt2df08912020-12-15 16:28:09 -0800509 if (rp_state && !(pCreateInfo->flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT)) {
Tony-LunarG767180f2020-04-23 14:03:59 -0600510 skip = ValidateAttachments(rp_state->createInfo.ptr(), pCreateInfo->attachmentCount, pCreateInfo->pAttachments);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000511 }
512
513 return skip;
514}
515
Sam Wallse746d522020-03-16 21:20:23 +0000516bool BestPractices::PreCallValidateAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
517 VkDescriptorSet* pDescriptorSets, void* ads_state_data) const {
518 bool skip = false;
519 skip |= ValidationStateTracker::PreCallValidateAllocateDescriptorSets(device, pAllocateInfo, pDescriptorSets, ads_state_data);
520
521 if (!skip) {
522 const auto& pool_handle = pAllocateInfo->descriptorPool;
523 auto iter = descriptor_pool_freed_count.find(pool_handle);
524 // if the number of freed sets > 0, it implies they could be recycled instead if desirable
525 // this warning is specific to Arm
526 if (VendorCheckEnabled(kBPVendorArm) && iter != descriptor_pool_freed_count.end() && iter->second > 0) {
527 skip |= LogPerformanceWarning(
528 device, kVUID_BestPractices_AllocateDescriptorSets_SuboptimalReuse,
529 "%s Descriptor set memory was allocated via vkAllocateDescriptorSets() for sets which were previously freed in the "
530 "same logical device. On some drivers or architectures it may be most optimal to re-use existing descriptor sets.",
531 VendorSpecificTag(kBPVendorArm));
532 }
533 }
534
535 return skip;
536}
537
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600538void BestPractices::ManualPostCallRecordAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
539 VkDescriptorSet* pDescriptorSets, VkResult result, void* ads_state) {
Sam Wallse746d522020-03-16 21:20:23 +0000540 if (result == VK_SUCCESS) {
541 // find the free count for the pool we allocated into
542 auto iter = descriptor_pool_freed_count.find(pAllocateInfo->descriptorPool);
543 if (iter != descriptor_pool_freed_count.end()) {
544 // we record successful allocations by subtracting the allocation count from the last recorded free count
545 const auto alloc_count = pAllocateInfo->descriptorSetCount;
546 // clamp the unsigned subtraction to the range [0, last_free_count]
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700547 if (iter->second > alloc_count) {
Sam Wallse746d522020-03-16 21:20:23 +0000548 iter->second -= alloc_count;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700549 } else {
Sam Wallse746d522020-03-16 21:20:23 +0000550 iter->second = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700551 }
Sam Wallse746d522020-03-16 21:20:23 +0000552 }
553 }
554}
555
556void BestPractices::PostCallRecordFreeDescriptorSets(VkDevice device, VkDescriptorPool descriptorPool, uint32_t descriptorSetCount,
557 const VkDescriptorSet* pDescriptorSets, VkResult result) {
558 ValidationStateTracker::PostCallRecordFreeDescriptorSets(device, descriptorPool, descriptorSetCount, pDescriptorSets, result);
559 if (result == VK_SUCCESS) {
560 // we want to track frees because we're interested in suggesting re-use
561 auto iter = descriptor_pool_freed_count.find(descriptorPool);
562 if (iter == descriptor_pool_freed_count.end()) {
Jeremy Gebbencbf22862021-03-03 12:01:22 -0700563 descriptor_pool_freed_count.emplace(descriptorPool, descriptorSetCount);
Sam Wallse746d522020-03-16 21:20:23 +0000564 } else {
565 iter->second += descriptorSetCount;
566 }
567 }
568}
569
Camden5b184be2019-08-13 07:50:19 -0600570bool BestPractices::PreCallValidateAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500571 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory) const {
Camden5b184be2019-08-13 07:50:19 -0600572 bool skip = false;
573
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500574 if (num_mem_objects + 1 > kMemoryObjectWarningLimit) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700575 skip |= LogPerformanceWarning(device, kVUID_BestPractices_AllocateMemory_TooManyObjects,
576 "Performance Warning: This app has > %" PRIu32 " memory objects.", kMemoryObjectWarningLimit);
Camden5b184be2019-08-13 07:50:19 -0600577 }
578
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000579 if (pAllocateInfo->allocationSize < kMinDeviceAllocationSize) {
580 skip |= LogPerformanceWarning(
581 device, kVUID_BestPractices_AllocateMemory_SmallAllocation,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600582 "vkAllocateMemory(): Allocating a VkDeviceMemory of size %" PRIu64 ". This is a very small allocation (current "
583 "threshold is %" PRIu64 " bytes). "
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000584 "You should make large allocations and sub-allocate from one large VkDeviceMemory.",
585 pAllocateInfo->allocationSize, kMinDeviceAllocationSize);
586 }
587
Camden83a9c372019-08-14 11:41:38 -0600588 // TODO: Insert get check for GetPhysicalDeviceMemoryProperties once the state is tracked in the StateTracker
589
590 return skip;
591}
592
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600593void BestPractices::ManualPostCallRecordAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
594 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory,
595 VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700596 if (result != VK_SUCCESS) {
597 static std::vector<VkResult> error_codes = {VK_ERROR_OUT_OF_HOST_MEMORY, VK_ERROR_OUT_OF_DEVICE_MEMORY,
598 VK_ERROR_TOO_MANY_OBJECTS, VK_ERROR_INVALID_EXTERNAL_HANDLE,
Mike Schuchardt2df08912020-12-15 16:28:09 -0800599 VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS};
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700600 static std::vector<VkResult> success_codes = {};
Nathaniel Cesariodb3f43f2021-05-12 09:08:23 -0600601 ValidateReturnCodes("vkAllocateMemory", result, error_codes, success_codes);
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700602 return;
603 }
604 num_mem_objects++;
605}
Camden Stocker9738af92019-10-16 13:54:03 -0700606
Mark Lobodzinskide15e582020-04-29 08:06:00 -0600607void BestPractices::ValidateReturnCodes(const char* api_name, VkResult result, const std::vector<VkResult>& error_codes,
608 const std::vector<VkResult>& success_codes) const {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700609 auto error = std::find(error_codes.begin(), error_codes.end(), result);
610 if (error != error_codes.end()) {
Gareth Webb586c46b2021-01-13 11:17:22 +0000611 static const std::vector<VkResult> common_failure_codes = {VK_ERROR_OUT_OF_DATE_KHR,
612 VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT};
613
614 auto common_failure = std::find(common_failure_codes.begin(), common_failure_codes.end(), result);
615 if (common_failure != common_failure_codes.end()) {
616 LogInfo(instance, kVUID_BestPractices_Failure_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
617 } else {
618 LogWarning(instance, kVUID_BestPractices_Error_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
619 }
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700620 return;
621 }
622 auto success = std::find(success_codes.begin(), success_codes.end(), result);
623 if (success != success_codes.end()) {
Mark Lobodzinskie7215152020-05-11 08:21:23 -0600624 LogInfo(instance, kVUID_BestPractices_NonSuccess_Result, "%s(): Returned non-success return code %s.", api_name,
625 string_VkResult(result));
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500626 }
627}
628
Jeff Bolz5c801d12019-10-09 10:38:45 -0500629bool BestPractices::PreCallValidateFreeMemory(VkDevice device, VkDeviceMemory memory,
630 const VkAllocationCallbacks* pAllocator) const {
Mark Lobodzinski91e50bf2020-01-14 09:55:11 -0700631 if (memory == VK_NULL_HANDLE) return false;
Camden83a9c372019-08-14 11:41:38 -0600632 bool skip = false;
633
Camden Stocker9738af92019-10-16 13:54:03 -0700634 const DEVICE_MEMORY_STATE* mem_info = ValidationStateTracker::GetDevMemState(memory);
Camden83a9c372019-08-14 11:41:38 -0600635
Jeremy Gebben5570abe2021-05-16 18:35:13 -0600636 for (const auto& node: mem_info->ObjectBindings()) {
637 const auto& obj = node->Handle();
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600638 LogObjectList objlist(device);
639 objlist.add(obj);
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -0600640 objlist.add(mem_info->mem());
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600641 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 -0600642 report_data->FormatHandle(obj).c_str(), report_data->FormatHandle(mem_info->mem()).c_str());
Camden83a9c372019-08-14 11:41:38 -0600643 }
644
Camden5b184be2019-08-13 07:50:19 -0600645 return skip;
646}
647
648void BestPractices::PreCallRecordFreeMemory(VkDevice device, VkDeviceMemory memory, const VkAllocationCallbacks* pAllocator) {
Mark Lobodzinski97484d62020-03-03 11:57:41 -0700649 ValidationStateTracker::PreCallRecordFreeMemory(device, memory, pAllocator);
Camden5b184be2019-08-13 07:50:19 -0600650 if (memory != VK_NULL_HANDLE) {
651 num_mem_objects--;
652 }
653}
654
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000655bool BestPractices::ValidateBindBufferMemory(VkBuffer buffer, VkDeviceMemory memory, const char* api_name) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600656 bool skip = false;
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500657 const BUFFER_STATE* buffer_state = GetBufferState(buffer);
Camden Stockerb603cc82019-09-03 10:09:02 -0600658
sfricke-samsunge2441192019-11-06 14:07:57 -0800659 if (!buffer_state->memory_requirements_checked && !buffer_state->external_memory_handle) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700660 skip |= LogWarning(device, kVUID_BestPractices_BufferMemReqNotCalled,
661 "%s: Binding memory to %s but vkGetBufferMemoryRequirements() has not been called on that buffer.",
662 api_name, report_data->FormatHandle(buffer).c_str());
Camden Stockerb603cc82019-09-03 10:09:02 -0600663 }
664
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000665 const DEVICE_MEMORY_STATE* mem_state = GetDevMemState(memory);
666
667 if (mem_state->alloc_info.allocationSize == buffer_state->createInfo.size &&
668 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
669 skip |= LogPerformanceWarning(
670 device, kVUID_BestPractices_SmallDedicatedAllocation,
671 "%s: Trying to bind %s to a memory block which is fully consumed by the buffer. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600672 "The required size of the allocation is %" PRIu64 ", but smaller buffers like this should be sub-allocated from "
673 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000674 api_name, report_data->FormatHandle(buffer).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
675 }
676
Camden Stockerb603cc82019-09-03 10:09:02 -0600677 return skip;
678}
679
680bool BestPractices::PreCallValidateBindBufferMemory(VkDevice device, VkBuffer buffer, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500681 VkDeviceSize memoryOffset) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600682 bool skip = false;
683 const char* api_name = "BindBufferMemory()";
684
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000685 skip |= ValidateBindBufferMemory(buffer, memory, api_name);
Camden Stockerb603cc82019-09-03 10:09:02 -0600686
687 return skip;
688}
689
690bool BestPractices::PreCallValidateBindBufferMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500691 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600692 char api_name[64];
693 bool skip = false;
694
695 for (uint32_t i = 0; i < bindInfoCount; i++) {
696 sprintf(api_name, "vkBindBufferMemory2() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000697 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600698 }
699
700 return skip;
701}
Camden Stockerb603cc82019-09-03 10:09:02 -0600702
703bool BestPractices::PreCallValidateBindBufferMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500704 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600705 char api_name[64];
706 bool skip = false;
Camden Stockerb603cc82019-09-03 10:09:02 -0600707
Camden Stocker8b798ab2019-09-03 10:33:28 -0600708 for (uint32_t i = 0; i < bindInfoCount; i++) {
709 sprintf(api_name, "vkBindBufferMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000710 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600711 }
712
713 return skip;
714}
715
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000716bool BestPractices::ValidateBindImageMemory(VkImage image, VkDeviceMemory memory, const char* api_name) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600717 bool skip = false;
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500718 const IMAGE_STATE* image_state = GetImageState(image);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600719
sfricke-samsung71bc6572020-04-29 15:49:43 -0700720 if (image_state->disjoint == false) {
sfricke-samsungd7ea5de2020-04-08 09:19:18 -0700721 if (!image_state->memory_requirements_checked && !image_state->external_memory_handle) {
722 skip |= LogWarning(device, kVUID_BestPractices_ImageMemReqNotCalled,
723 "%s: Binding memory to %s but vkGetImageMemoryRequirements() has not been called on that image.",
724 api_name, report_data->FormatHandle(image).c_str());
725 }
726 } else {
727 // TODO If binding disjoint image then this needs to check that VkImagePlaneMemoryRequirementsInfo was called for each
728 // plane.
Camden Stocker8b798ab2019-09-03 10:33:28 -0600729 }
730
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000731 const DEVICE_MEMORY_STATE* mem_state = GetDevMemState(memory);
732
733 if (mem_state->alloc_info.allocationSize == image_state->requirements.size &&
734 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
735 skip |= LogPerformanceWarning(
736 device, kVUID_BestPractices_SmallDedicatedAllocation,
737 "%s: Trying to bind %s to a memory block which is fully consumed by the image. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600738 "The required size of the allocation is %" PRIu64 ", but smaller images like this should be sub-allocated from "
739 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000740 api_name, report_data->FormatHandle(image).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
741 }
742
743 // If we're binding memory to a image which was created as TRANSIENT and the image supports LAZY allocation,
744 // make sure this type is actually used.
745 // This warning will only trigger if this layer is run on a platform that supports LAZILY_ALLOCATED_BIT
746 // (i.e.most tile - based renderers)
747 if (image_state->createInfo.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) {
748 bool supports_lazy = false;
749 uint32_t suggested_type = 0;
750
751 for (uint32_t i = 0; i < phys_dev_mem_props.memoryTypeCount; i++) {
752 if ((1u << i) & image_state->requirements.memoryTypeBits) {
753 if (phys_dev_mem_props.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
754 supports_lazy = true;
755 suggested_type = i;
756 break;
757 }
758 }
759 }
760
761 uint32_t allocated_properties = phys_dev_mem_props.memoryTypes[mem_state->alloc_info.memoryTypeIndex].propertyFlags;
762
763 if (supports_lazy && (allocated_properties & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) == 0) {
764 skip |= LogPerformanceWarning(
765 device, kVUID_BestPractices_NonLazyTransientImage,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600766 "%s: Attempting to bind memory type %u to VkImage which was created with TRANSIENT_ATTACHMENT_BIT,"
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000767 "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 -0600768 "%" PRIu64 " bytes of physical memory.",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000769 api_name, mem_state->alloc_info.memoryTypeIndex, suggested_type, image_state->requirements.size);
770 }
771 }
772
Camden Stocker8b798ab2019-09-03 10:33:28 -0600773 return skip;
774}
775
776bool BestPractices::PreCallValidateBindImageMemory(VkDevice device, VkImage image, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500777 VkDeviceSize memoryOffset) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600778 bool skip = false;
779 const char* api_name = "vkBindImageMemory()";
780
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000781 skip |= ValidateBindImageMemory(image, memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600782
783 return skip;
784}
785
786bool BestPractices::PreCallValidateBindImageMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500787 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600788 char api_name[64];
789 bool skip = false;
790
791 for (uint32_t i = 0; i < bindInfoCount; i++) {
792 sprintf(api_name, "vkBindImageMemory2() pBindInfos[%u]", i);
Mark Lobodzinski1f887d32020-12-30 15:31:33 -0700793 if (!LvlFindInChain<VkBindImageMemorySwapchainInfoKHR>(pBindInfos[i].pNext)) {
Tony-LunarG5e60b852020-04-27 11:27:54 -0600794 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
795 }
Camden Stocker8b798ab2019-09-03 10:33:28 -0600796 }
797
798 return skip;
799}
800
801bool BestPractices::PreCallValidateBindImageMemory2KHR(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, "vkBindImageMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000808 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600809 }
810
811 return skip;
812}
Camden83a9c372019-08-14 11:41:38 -0600813
Attilio Provenzano02859b22020-02-27 14:17:28 +0000814static inline bool FormatHasFullThroughputBlendingArm(VkFormat format) {
815 switch (format) {
816 case VK_FORMAT_B10G11R11_UFLOAT_PACK32:
817 case VK_FORMAT_R16_SFLOAT:
818 case VK_FORMAT_R16G16_SFLOAT:
819 case VK_FORMAT_R16G16B16_SFLOAT:
820 case VK_FORMAT_R16G16B16A16_SFLOAT:
821 case VK_FORMAT_R32_SFLOAT:
822 case VK_FORMAT_R32G32_SFLOAT:
823 case VK_FORMAT_R32G32B32_SFLOAT:
824 case VK_FORMAT_R32G32B32A32_SFLOAT:
825 return false;
826
827 default:
828 return true;
829 }
830}
831
832bool BestPractices::ValidateMultisampledBlendingArm(uint32_t createInfoCount,
833 const VkGraphicsPipelineCreateInfo* pCreateInfos) const {
834 bool skip = false;
835
836 for (uint32_t i = 0; i < createInfoCount; i++) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700837 auto create_info = &pCreateInfos[i];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000838
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700839 if (!create_info->pColorBlendState || !create_info->pMultisampleState ||
840 create_info->pMultisampleState->rasterizationSamples == VK_SAMPLE_COUNT_1_BIT ||
841 create_info->pMultisampleState->sampleShadingEnable) {
Attilio Provenzano02859b22020-02-27 14:17:28 +0000842 return skip;
843 }
844
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700845 auto rp_state = GetRenderPassState(create_info->renderPass);
846 auto& subpass = rp_state->createInfo.pSubpasses[create_info->subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000847
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700848 for (uint32_t j = 0; j < create_info->pColorBlendState->attachmentCount; j++) {
849 auto& blend_att = create_info->pColorBlendState->pAttachments[j];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000850 uint32_t att = subpass.pColorAttachments[j].attachment;
851
852 if (att != VK_ATTACHMENT_UNUSED && blend_att.blendEnable && blend_att.colorWriteMask) {
853 if (!FormatHasFullThroughputBlendingArm(rp_state->createInfo.pAttachments[att].format)) {
854 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultisampledBlending,
855 "%s vkCreateGraphicsPipelines() - createInfo #%u: Pipeline is multisampled and "
856 "color attachment #%u makes use "
857 "of a format which cannot be blended at full throughput when using MSAA.",
858 VendorSpecificTag(kBPVendorArm), i, j);
859 }
860 }
861 }
862 }
863
864 return skip;
865}
866
Camden5b184be2019-08-13 07:50:19 -0600867bool BestPractices::PreCallValidateCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
868 const VkGraphicsPipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -0600869 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500870 void* cgpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -0600871 bool skip = StateTracker::PreCallValidateCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos,
872 pAllocator, pPipelines, cgpl_state_data);
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600873 create_graphics_pipeline_api_state* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
Camden5b184be2019-08-13 07:50:19 -0600874
875 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700876 skip |= LogPerformanceWarning(
877 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
878 "Performance Warning: This vkCreateGraphicsPipelines call is creating multiple pipelines but is not using a "
879 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -0600880 }
881
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000882 for (uint32_t i = 0; i < createInfoCount; i++) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700883 auto& create_info = pCreateInfos[i];
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000884
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600885 if (!(cgpl_state->pipe_state[i]->active_shaders & VK_SHADER_STAGE_MESH_BIT_NV)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700886 auto& vertex_input = *create_info.pVertexInputState;
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600887 uint32_t count = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700888 for (uint32_t j = 0; j < vertex_input.vertexBindingDescriptionCount; j++) {
889 if (vertex_input.pVertexBindingDescriptions[j].inputRate == VK_VERTEX_INPUT_RATE_INSTANCE) {
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600890 count++;
891 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000892 }
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600893 if (count > kMaxInstancedVertexBuffers) {
894 skip |= LogPerformanceWarning(
895 device, kVUID_BestPractices_CreatePipelines_TooManyInstancedVertexBuffers,
896 "The pipeline is using %u instanced vertex buffers (current limit: %u), but this can be inefficient on the "
897 "GPU. If using instanced vertex attributes prefer interleaving them in a single buffer.",
898 count, kMaxInstancedVertexBuffers);
899 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000900 }
Attilio Provenzano02859b22020-02-27 14:17:28 +0000901
Szilard Pappaaf2da32020-06-22 10:37:35 +0100902 if ((pCreateInfos[i].pRasterizationState->depthBiasEnable) &&
903 (pCreateInfos[i].pRasterizationState->depthBiasConstantFactor == 0.0f) &&
904 (pCreateInfos[i].pRasterizationState->depthBiasSlopeFactor == 0.0f)) {
905 skip |= VendorCheckEnabled(kBPVendorArm) &&
906 LogPerformanceWarning(
907 device, kVUID_BestPractices_CreatePipelines_DepthBias_Zero,
908 "%s Performance Warning: This vkCreateGraphicsPipelines call is created with depthBiasEnable set to true "
909 "and both depthBiasConstantFactor and depthBiasSlopeFactor are set to 0. This can cause reduced "
910 "efficiency during rasterization. Consider disabling depthBias or increasing either "
911 "depthBiasConstantFactor or depthBiasSlopeFactor.",
912 VendorSpecificTag(kBPVendorArm));
913 }
914
Attilio Provenzano02859b22020-02-27 14:17:28 +0000915 skip |= VendorCheckEnabled(kBPVendorArm) && ValidateMultisampledBlendingArm(createInfoCount, pCreateInfos);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000916 }
917
Camden5b184be2019-08-13 07:50:19 -0600918 return skip;
919}
920
Sam Walls0961ec02020-03-31 16:39:15 +0100921void BestPractices::ManualPostCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t count,
922 const VkGraphicsPipelineCreateInfo* pCreateInfos,
923 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
924 VkResult result, void* cgpl_state_data) {
925 for (size_t i = 0; i < count; i++) {
926 const auto* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
927 const VkPipeline pipeline_handle = pPipelines[i];
928
929 // record depth stencil state and color blend states for depth pre-pass tracking purposes
930 auto gp_cis = graphicsPipelineCIs.find(pipeline_handle);
931
932 // add the tracking state if it doesn't exist
933 if (gp_cis == graphicsPipelineCIs.end()) {
Jeremy Gebbencbf22862021-03-03 12:01:22 -0700934 auto result = graphicsPipelineCIs.emplace(pipeline_handle, GraphicsPipelineCIs{});
Sam Walls0961ec02020-03-31 16:39:15 +0100935
936 if (!result.second) continue;
937
938 gp_cis = result.first;
939 }
940
Tony-LunarG412b1b72020-07-15 10:30:13 -0600941 gp_cis->second.colorBlendStateCI =
942 cgpl_state->pCreateInfos[i].pColorBlendState
943 ? new safe_VkPipelineColorBlendStateCreateInfo(cgpl_state->pCreateInfos[i].pColorBlendState)
944 : nullptr;
945 gp_cis->second.depthStencilStateCI =
946 cgpl_state->pCreateInfos[i].pDepthStencilState
947 ? new safe_VkPipelineDepthStencilStateCreateInfo(cgpl_state->pCreateInfos[i].pDepthStencilState)
948 : nullptr;
Sam Walls0961ec02020-03-31 16:39:15 +0100949 }
950}
951
Camden5b184be2019-08-13 07:50:19 -0600952bool BestPractices::PreCallValidateCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
953 const VkComputePipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -0600954 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500955 void* ccpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -0600956 bool skip = StateTracker::PreCallValidateCreateComputePipelines(device, pipelineCache, createInfoCount, pCreateInfos,
957 pAllocator, pPipelines, ccpl_state_data);
Camden5b184be2019-08-13 07:50:19 -0600958
959 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700960 skip |= LogPerformanceWarning(
961 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
962 "Performance Warning: This vkCreateComputePipelines call is creating multiple pipelines but is not using a "
963 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -0600964 }
965
Sam Wallsd7ab6db2020-06-19 20:41:54 +0100966 if (VendorCheckEnabled(kBPVendorArm)) {
967 for (size_t i = 0; i < createInfoCount; i++) {
968 skip |= ValidateCreateComputePipelineArm(pCreateInfos[i]);
969 }
970 }
971
972 return skip;
973}
974
975bool BestPractices::ValidateCreateComputePipelineArm(const VkComputePipelineCreateInfo& createInfo) const {
976 bool skip = false;
977 auto* module = GetShaderModuleState(createInfo.stage.module);
sfricke-samsung8a7341a2021-02-28 07:30:21 -0800978 // Generate warnings about work group sizes based on active resources.
sfricke-samsung962cad92021-04-13 00:46:29 -0700979 auto entrypoint = module->FindEntrypoint(createInfo.stage.pName, createInfo.stage.stage);
sfricke-samsung8a7341a2021-02-28 07:30:21 -0800980 if (entrypoint == module->end()) return false;
Sam Wallsd7ab6db2020-06-19 20:41:54 +0100981
982 uint32_t x = 1, y = 1, z = 1;
sfricke-samsung962cad92021-04-13 00:46:29 -0700983 module->FindLocalSize(entrypoint, x, y, z);
Sam Wallsd7ab6db2020-06-19 20:41:54 +0100984
985 uint32_t thread_count = x * y * z;
986
987 // Generate a priori warnings about work group sizes.
988 if (thread_count > kMaxEfficientWorkGroupThreadCountArm) {
989 skip |= LogPerformanceWarning(
990 device, kVUID_BestPractices_CreateComputePipelines_ComputeWorkGroupSize,
991 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, %u, "
992 "%u) (%u threads total), has more threads than advised in a single work group. It is advised to use work "
993 "groups with less than %u threads, especially when using barrier() or shared memory.",
994 VendorSpecificTag(kBPVendorArm), x, y, z, thread_count, kMaxEfficientWorkGroupThreadCountArm);
995 }
996
997 if (thread_count == 1 || ((x > 1) && (x & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
998 ((y > 1) && (y & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
999 ((z > 1) && (z & (kThreadGroupDispatchCountAlignmentArm - 1)))) {
1000 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeThreadGroupAlignment,
1001 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, "
1002 "%u, %u) is not aligned to %u "
1003 "threads. On Arm Mali architectures, not aligning work group sizes to %u may "
1004 "leave threads idle on the shader "
1005 "core.",
1006 VendorSpecificTag(kBPVendorArm), x, y, z, kThreadGroupDispatchCountAlignmentArm,
1007 kThreadGroupDispatchCountAlignmentArm);
1008 }
1009
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001010 bool has_writeable_descriptors = false;
locke-lunarg63e4daf2020-08-17 17:53:25 -06001011 bool has_atomic_descriptors = false;
sfricke-samsung962cad92021-04-13 00:46:29 -07001012 auto accessible_ids = module->MarkAccessibleIds(entrypoint);
locke-lunarg63e4daf2020-08-17 17:53:25 -06001013 auto descriptor_uses =
sfricke-samsung962cad92021-04-13 00:46:29 -07001014 module->CollectInterfaceByDescriptorSlot(accessible_ids, &has_writeable_descriptors, &has_atomic_descriptors);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001015
1016 unsigned dimensions = 0;
1017 if (x > 1) dimensions++;
1018 if (y > 1) dimensions++;
1019 if (z > 1) dimensions++;
1020 // Here the dimension will really depend on the dispatch grid, but assume it's 1D.
1021 dimensions = std::max(dimensions, 1u);
1022
1023 // If we're accessing images, we almost certainly want to have a 2D workgroup for cache reasons.
1024 // There are some false positives here. We could simply have a shader that does this within a 1D grid,
1025 // or we may have a linearly tiled image, but these cases are quite unlikely in practice.
1026 bool accesses_2d = false;
1027 for (const auto& usage : descriptor_uses) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001028 auto dim = module->GetShaderResourceDimensionality(usage.second);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001029 if (dim < 0) continue;
1030 auto spvdim = spv::Dim(dim);
1031 if (spvdim != spv::Dim1D && spvdim != spv::DimBuffer) accesses_2d = true;
1032 }
1033
1034 if (accesses_2d && dimensions < 2) {
1035 LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeSpatialLocality,
1036 "%s vkCreateComputePipelines(): compute shader has work group dimensions (%u, %u, %u), which "
1037 "suggests a 1D dispatch, but the shader is accessing 2D or 3D images. The shader may be "
1038 "exhibiting poor spatial locality with respect to one or more shader resources.",
1039 VendorSpecificTag(kBPVendorArm), x, y, z);
1040 }
1041
Camden5b184be2019-08-13 07:50:19 -06001042 return skip;
1043}
1044
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001045bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags flags) const {
Camden5b184be2019-08-13 07:50:19 -06001046 bool skip = false;
1047
1048 if (flags & VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001049 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1050 "You are using VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001051 } else if (flags & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001052 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1053 "You are using VK_PIPELINE_STAGE_ALL_COMMANDS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001054 }
1055
1056 return skip;
1057}
1058
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001059bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags2KHR flags) const {
1060 bool skip = false;
1061
1062 if (flags & VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR) {
1063 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1064 "You are using VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR when %s is called\n", api_name.c_str());
1065 } else if (flags & VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR) {
1066 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1067 "You are using VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR when %s is called\n", api_name.c_str());
1068 }
1069
1070 return skip;
1071}
1072
1073bool BestPractices::CheckDependencyInfo(const std::string& api_name, const VkDependencyInfoKHR& dep_info) const {
1074 bool skip = false;
1075 auto stage_masks = sync_utils::GetGlobalStageMasks(dep_info);
1076
1077 skip |= CheckPipelineStageFlags(api_name, stage_masks.src);
1078 skip |= CheckPipelineStageFlags(api_name, stage_masks.dst);
1079
1080 return skip;
1081}
1082
Mark Lobodzinski84101d72020-04-24 09:43:48 -06001083void BestPractices::ManualPostCallRecordQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo, VkResult result) {
Mark Lobodzinski9b133c12020-03-10 10:42:56 -06001084 for (uint32_t i = 0; i < pPresentInfo->swapchainCount; ++i) {
1085 auto swapchains_result = pPresentInfo->pResults ? pPresentInfo->pResults[i] : result;
1086 if (swapchains_result == VK_SUBOPTIMAL_KHR) {
1087 LogPerformanceWarning(
1088 pPresentInfo->pSwapchains[i], kVUID_BestPractices_SuboptimalSwapchain,
1089 "vkQueuePresentKHR: %s :VK_SUBOPTIMAL_KHR was returned. VK_SUBOPTIMAL_KHR - Presentation will still succeed, "
1090 "subject to the window resize behavior, but the swapchain is no longer configured optimally for the surface it "
1091 "targets. Applications should query updated surface information and recreate their swapchain at the next "
1092 "convenient opportunity.",
1093 report_data->FormatHandle(pPresentInfo->pSwapchains[i]).c_str());
1094 }
1095 }
1096}
1097
Jeff Bolz5c801d12019-10-09 10:38:45 -05001098bool BestPractices::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
1099 VkFence fence) const {
Camden5b184be2019-08-13 07:50:19 -06001100 bool skip = false;
1101
1102 for (uint32_t submit = 0; submit < submitCount; submit++) {
1103 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreCount; semaphore++) {
1104 skip |= CheckPipelineStageFlags("vkQueueSubmit", pSubmits[submit].pWaitDstStageMask[semaphore]);
1105 }
1106 }
1107
1108 return skip;
1109}
1110
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001111bool BestPractices::PreCallValidateQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR* pSubmits,
1112 VkFence fence) const {
1113 bool skip = false;
1114
1115 for (uint32_t submit = 0; submit < submitCount; submit++) {
1116 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreInfoCount; semaphore++) {
1117 skip |= CheckPipelineStageFlags("vkQueueSubmit2KHR", pSubmits[submit].pWaitSemaphoreInfos[semaphore].stageMask);
1118 }
1119 }
1120
1121 return skip;
1122}
1123
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001124bool BestPractices::PreCallValidateCreateCommandPool(VkDevice device, const VkCommandPoolCreateInfo* pCreateInfo,
1125 const VkAllocationCallbacks* pAllocator, VkCommandPool* pCommandPool) const {
1126 bool skip = false;
1127
1128 if (pCreateInfo->flags & VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT) {
1129 skip |= LogPerformanceWarning(
1130 device, kVUID_BestPractices_CreateCommandPool_CommandBufferReset,
1131 "vkCreateCommandPool(): VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT is set. Consider resetting entire "
1132 "pool instead.");
1133 }
1134
1135 return skip;
1136}
1137
1138bool BestPractices::PreCallValidateBeginCommandBuffer(VkCommandBuffer commandBuffer,
1139 const VkCommandBufferBeginInfo* pBeginInfo) const {
1140 bool skip = false;
1141
1142 if (pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT) {
1143 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_SimultaneousUse,
1144 "vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT is set.");
1145 }
1146
Attilio Provenzano02859b22020-02-27 14:17:28 +00001147 if (!(pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT)) {
1148 skip |= VendorCheckEnabled(kBPVendorArm) &&
1149 LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_OneTimeSubmit,
1150 "%s vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT is not set. "
1151 "For best performance on Mali GPUs, consider setting ONE_TIME_SUBMIT by default.",
1152 VendorSpecificTag(kBPVendorArm));
1153 }
1154
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001155 return skip;
1156}
1157
Jeff Bolz5c801d12019-10-09 10:38:45 -05001158bool BestPractices::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001159 bool skip = false;
1160
1161 skip |= CheckPipelineStageFlags("vkCmdSetEvent", stageMask);
1162
1163 return skip;
1164}
1165
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001166bool BestPractices::PreCallValidateCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1167 const VkDependencyInfoKHR* pDependencyInfo) const {
1168 return CheckDependencyInfo("vkCmdSetEvent2KHR", *pDependencyInfo);
1169}
1170
Jeff Bolz5c801d12019-10-09 10:38:45 -05001171bool BestPractices::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
1172 VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001173 bool skip = false;
1174
1175 skip |= CheckPipelineStageFlags("vkCmdResetEvent", stageMask);
1176
1177 return skip;
1178}
1179
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001180bool BestPractices::PreCallValidateCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1181 VkPipelineStageFlags2KHR stageMask) const {
1182 bool skip = false;
1183
1184 skip |= CheckPipelineStageFlags("vkCmdResetEvent2KHR", stageMask);
1185
1186 return skip;
1187}
1188
Camden5b184be2019-08-13 07:50:19 -06001189bool BestPractices::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1190 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
1191 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1192 uint32_t bufferMemoryBarrierCount,
1193 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1194 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001195 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001196 bool skip = false;
1197
1198 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", srcStageMask);
1199 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", dstStageMask);
1200
1201 return skip;
1202}
1203
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001204bool BestPractices::PreCallValidateCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1205 const VkDependencyInfoKHR* pDependencyInfos) const {
1206 bool skip = false;
1207 for (uint32_t i = 0; i < eventCount; i++) {
1208 skip = CheckDependencyInfo("vkCmdWaitEvents2KHR", pDependencyInfos[i]);
1209 }
1210
1211 return skip;
1212}
1213
Camden5b184be2019-08-13 07:50:19 -06001214bool BestPractices::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
1215 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
1216 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1217 uint32_t bufferMemoryBarrierCount,
1218 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1219 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001220 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001221 bool skip = false;
1222
1223 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", srcStageMask);
1224 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", dstStageMask);
1225
1226 return skip;
1227}
1228
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001229bool BestPractices::PreCallValidateCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer,
1230 const VkDependencyInfoKHR* pDependencyInfo) const {
1231 return CheckDependencyInfo("vkCmdPipelineBarrier2KHR", *pDependencyInfo);
1232}
1233
Camden5b184be2019-08-13 07:50:19 -06001234bool BestPractices::PreCallValidateCmdWriteTimestamp(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001235 VkQueryPool queryPool, uint32_t query) const {
Camden5b184be2019-08-13 07:50:19 -06001236 bool skip = false;
1237
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001238 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp", static_cast<VkPipelineStageFlags>(pipelineStage));
1239
1240 return skip;
1241}
1242
1243bool BestPractices::PreCallValidateCmdWriteTimestamp2KHR(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
1244 VkQueryPool queryPool, uint32_t query) const {
1245 bool skip = false;
1246
1247 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp2KHR", pipelineStage);
Camden5b184be2019-08-13 07:50:19 -06001248
1249 return skip;
1250}
1251
Sam Walls0961ec02020-03-31 16:39:15 +01001252void BestPractices::PostCallRecordCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
1253 VkPipeline pipeline) {
1254 StateTracker::PostCallRecordCmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
1255
1256 if (pipelineBindPoint == VK_PIPELINE_BIND_POINT_GRAPHICS) {
1257 // check for depth/blend state tracking
1258 auto gp_cis = graphicsPipelineCIs.find(pipeline);
1259 if (gp_cis != graphicsPipelineCIs.end()) {
1260 auto prepass_state = cbDepthPrePassStates.find(commandBuffer);
1261 if (prepass_state == cbDepthPrePassStates.end()) {
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001262 auto result = cbDepthPrePassStates.emplace(commandBuffer, DepthPrePassState{});
Sam Walls0961ec02020-03-31 16:39:15 +01001263
1264 if (!result.second) return;
1265
1266 prepass_state = result.first;
1267 }
1268
1269 const auto* blend_state = gp_cis->second.colorBlendStateCI;
1270 const auto* stencil_state = gp_cis->second.depthStencilStateCI;
1271
1272 if (blend_state) {
1273 // assume the pipeline is depth-only unless any of the attachments have color writes enabled
1274 prepass_state->second.depthOnly = true;
1275 for (size_t i = 0; i < blend_state->attachmentCount; i++) {
1276 if (blend_state->pAttachments[i].colorWriteMask != 0) {
1277 prepass_state->second.depthOnly = false;
1278 }
1279 }
1280 }
1281
1282 // check for depth value usage
1283 prepass_state->second.depthEqualComparison = false;
1284
1285 if (stencil_state && stencil_state->depthTestEnable) {
1286 switch (stencil_state->depthCompareOp) {
1287 case VK_COMPARE_OP_EQUAL:
1288 case VK_COMPARE_OP_GREATER_OR_EQUAL:
1289 case VK_COMPARE_OP_LESS_OR_EQUAL:
1290 prepass_state->second.depthEqualComparison = true;
1291 break;
1292 default:
1293 break;
1294 }
1295 }
1296 } else {
1297 // reset depth pre-pass tracking
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001298 cbDepthPrePassStates.emplace(commandBuffer, DepthPrePassState{});
Sam Walls0961ec02020-03-31 16:39:15 +01001299 }
1300 }
1301}
1302
Attilio Provenzano02859b22020-02-27 14:17:28 +00001303static inline bool RenderPassUsesAttachmentOnTile(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1304 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001305 auto& subpass_info = createInfo.pSubpasses[subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001306
1307 // If an attachment is ever used as a color attachment,
1308 // resolve attachment or depth stencil attachment,
1309 // it needs to exist on tile at some point.
1310
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001311 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1312 if (subpass_info.pColorAttachments[i].attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001313 }
1314
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001315 if (subpass_info.pResolveAttachments) {
1316 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1317 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
1318 }
1319 }
1320
1321 if (subpass_info.pDepthStencilAttachment && subpass_info.pDepthStencilAttachment->attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001322 }
1323
1324 return false;
1325}
1326
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001327static inline bool RenderPassUsesAttachmentAsImageOnly(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1328 if (RenderPassUsesAttachmentOnTile(createInfo, attachment)) {
1329 return false;
1330 }
1331
1332 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
1333 auto& subpassInfo = createInfo.pSubpasses[subpass];
1334
1335 for (uint32_t i = 0; i < subpassInfo.inputAttachmentCount; i++) {
1336 if (subpassInfo.pInputAttachments[i].attachment == attachment) {
1337 return true;
1338 }
1339 }
1340 }
1341
1342 return false;
1343}
1344
Attilio Provenzano02859b22020-02-27 14:17:28 +00001345bool BestPractices::ValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1346 const VkRenderPassBeginInfo* pRenderPassBegin) const {
1347 bool skip = false;
1348
1349 if (!pRenderPassBegin) {
1350 return skip;
1351 }
1352
1353 auto rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
1354 if (rp_state) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08001355 if (rp_state->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07001356 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
Tony-LunarG767180f2020-04-23 14:03:59 -06001357 if (rpabi) {
1358 skip = ValidateAttachments(rp_state->createInfo.ptr(), rpabi->attachmentCount, rpabi->pAttachments);
1359 }
1360 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001361 // Check if any attachments have LOAD operation on them
1362 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
1363 auto& attachment = rp_state->createInfo.pAttachments[att];
1364
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001365 bool attachment_has_readback = false;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001366 if (!FormatHasStencil(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001367 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001368 }
1369
1370 if (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001371 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001372 }
1373
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001374 bool attachment_needs_readback = false;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001375
1376 // Check if the attachment is actually used in any subpass on-tile
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001377 if (attachment_has_readback && RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1378 attachment_needs_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001379 }
1380
1381 // Using LOAD_OP_LOAD is expensive on tiled GPUs, so flag it as a potential improvement
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001382 if (attachment_needs_readback) {
Attilio Provenzano02859b22020-02-27 14:17:28 +00001383 skip |= VendorCheckEnabled(kBPVendorArm) &&
1384 LogPerformanceWarning(
1385 device, kVUID_BestPractices_BeginRenderPass_AttachmentNeedsReadback,
1386 "%s Attachment #%u in render pass has begun with VK_ATTACHMENT_LOAD_OP_LOAD.\n"
1387 "Submitting this renderpass will cause the driver to inject a readback of the attachment "
1388 "which will copy in total %u pixels (renderArea = { %d, %d, %u, %u }) to the tile buffer.",
1389 VendorSpecificTag(kBPVendorArm), att,
1390 pRenderPassBegin->renderArea.extent.width * pRenderPassBegin->renderArea.extent.height,
1391 pRenderPassBegin->renderArea.offset.x, pRenderPassBegin->renderArea.offset.y,
1392 pRenderPassBegin->renderArea.extent.width, pRenderPassBegin->renderArea.extent.height);
1393 }
1394 }
1395 }
1396
1397 return skip;
1398}
1399
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001400void BestPractices::ValidateImageView(IMAGE_VIEW_STATE* view, IMAGE_SUBRESOURCE_USAGE_BP usage) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001401 if (view) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001402 ValidateImage(GetImageUsageState(view->create_info.image), usage, view->create_info.subresourceRange);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001403 }
1404}
1405
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001406void BestPractices::ValidateImage(IMAGE_STATE_BP* state, IMAGE_SUBRESOURCE_USAGE_BP usage,
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001407 const VkImageSubresourceRange& subresource_range) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001408 IMAGE_STATE* image = state->image;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001409 uint32_t max_layers = image->createInfo.arrayLayers - subresource_range.baseArrayLayer;
1410 uint32_t array_layers = std::min(subresource_range.layerCount, max_layers);
1411 uint32_t max_levels = image->createInfo.mipLevels - subresource_range.baseMipLevel;
1412 uint32_t mip_levels = std::min(image->createInfo.mipLevels, max_levels);
1413
1414 for (uint32_t layer = 0; layer < array_layers; layer++) {
1415 for (uint32_t level = 0; level < mip_levels; level++) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001416 ValidateImage(state, usage, layer + subresource_range.baseArrayLayer, level + subresource_range.baseMipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001417 }
1418 }
1419}
1420
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001421void BestPractices::ValidateImage(IMAGE_STATE_BP* state, IMAGE_SUBRESOURCE_USAGE_BP usage,
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001422 const VkImageSubresourceLayers& subresource_layers) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001423 IMAGE_STATE* image = state->image;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001424 uint32_t max_layers = image->createInfo.arrayLayers - subresource_layers.baseArrayLayer;
1425 uint32_t array_layers = std::min(subresource_layers.layerCount, max_layers);
1426
1427 for (uint32_t layer = 0; layer < array_layers; layer++) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001428 ValidateImage(state, usage, layer + subresource_layers.baseArrayLayer, subresource_layers.mipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001429 }
1430}
1431
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001432void BestPractices::ValidateImage(IMAGE_STATE_BP* state,
1433 IMAGE_SUBRESOURCE_USAGE_BP usage, uint32_t array_layer,
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001434 uint32_t mip_level) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001435 IMAGE_STATE* image = state->image;
1436 IMAGE_SUBRESOURCE_USAGE_BP last_usage = state->usages[array_layer][mip_level];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001437
1438 // Swapchain images are implicitly read so clear after store is expected.
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001439 if (usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_CLEARED && last_usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_STORED &&
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001440 !image->is_swapchain_image) {
1441 VendorCheckEnabled(kBPVendorArm) &&
1442 LogPerformanceWarning(
1443 device, kVUID_BestPractices_RenderPass_RedundantStore,
1444 "%s Subresource (arrayLayer: %u, mipLevel: %u) of image was cleared as part of LOAD_OP_CLEAR, but last time "
1445 "image was used, it was written to with STORE_OP_STORE. "
1446 "Storing to the image is probably redundant in this case, and wastes bandwidth on tile-based "
1447 "architectures.",
1448 VendorSpecificTag(kBPVendorArm), array_layer, mip_level);
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001449 } else if (usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_CLEARED && last_usage == IMAGE_SUBRESOURCE_USAGE_BP::CLEARED) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001450 VendorCheckEnabled(kBPVendorArm) &&
1451 LogPerformanceWarning(
1452 device, kVUID_BestPractices_RenderPass_RedundantClear,
1453 "%s Subresource (arrayLayer: %u, mipLevel: %u) of image was cleared as part of LOAD_OP_CLEAR, but last time "
1454 "image was used, it was written to with vkCmdClear*Image(). "
1455 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
1456 "tile-based architectures."
1457 "architectures.",
1458 VendorSpecificTag(kBPVendorArm), array_layer, mip_level);
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001459 } else if (usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE && last_usage == IMAGE_SUBRESOURCE_USAGE_BP::CLEARED) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001460 VendorCheckEnabled(kBPVendorArm) &&
1461 LogPerformanceWarning(
1462 device, kVUID_BestPractices_RenderPass_InefficientClear,
1463 "%s Subresource (arrayLayer: %u, mipLevel: %u) of image was loaded to tile as part of LOAD_OP_LOAD, but last "
1464 "time image was used, it was written to with vkCmdClear*Image(). "
1465 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
1466 "tile-based architectures. "
1467 "Use LOAD_OP_CLEAR instead to clear the image for free.",
1468 VendorSpecificTag(kBPVendorArm), array_layer, mip_level);
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001469 } else if (usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE && last_usage == IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE) {
Szilard Papp29463682020-07-24 17:43:39 +01001470 VendorCheckEnabled(kBPVendorArm) &&
1471 LogPerformanceWarning(device, kVUID_BestPractices_RenderPass_BlitImage_LoadOpLoad,
1472 "%s Subresource (arraylayer: %u, mipLevel: %u) of was loaded to tile as part of LOAD_OP_LOAD, "
1473 "but last time image was used, it was written to with vkCmdBlitImage. "
1474 "The blit is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
1475 "Rather than blitting, just render the source image in a fragment shader in this render pass, "
1476 "which avoids the memory roundtrip.",
1477 VendorSpecificTag(kBPVendorArm), array_layer, mip_level);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001478 }
1479
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001480 state->usages[array_layer][mip_level] = usage;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001481}
1482
1483void BestPractices::PreCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1484 VkSubpassContents contents) {
1485 if (!pRenderPassBegin) {
1486 return;
1487 }
1488
1489 auto rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
1490 if (rp_state) {
1491 // Check load ops
1492 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
1493 auto& attachment = rp_state->createInfo.pAttachments[att];
1494
1495 if (!RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att) &&
1496 !RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1497 continue;
1498 }
1499
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001500 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::UNDEFINED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001501
1502 if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) ||
1503 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001504 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001505 }
1506
1507 if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) ||
1508 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_CLEAR)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001509 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_CLEARED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001510 }
1511
1512 if (RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001513 usage = IMAGE_SUBRESOURCE_USAGE_BP::RESOURCE_READ;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001514 }
1515
1516 auto framebuffer = GetFramebufferState(pRenderPassBegin->framebuffer);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001517 IMAGE_VIEW_STATE* image_view = nullptr;
1518
1519 if (rp_state->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
1520 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
1521 if (rpabi) {
1522 image_view = GetImageViewState(rpabi->pAttachments[att]);
1523 }
1524 } else {
1525 image_view = GetImageViewState(framebuffer->createInfo.pAttachments[att]);
1526 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001527
1528 ValidateImageView(image_view, usage);
1529 }
1530
1531 // Check store ops
1532 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
1533 auto& attachment = rp_state->createInfo.pAttachments[att];
1534
1535 if (!RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1536 continue;
1537 }
1538
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001539 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_DISCARDED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001540
1541 if ((!FormatIsStencilOnly(attachment.format) && attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE) ||
1542 (FormatHasStencil(attachment.format) && attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001543 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_STORED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001544 }
1545
1546 auto framebuffer = GetFramebufferState(pRenderPassBegin->framebuffer);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001547
1548 IMAGE_VIEW_STATE* image_view = nullptr;
1549 if (rp_state->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
1550 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
1551 if (rpabi) {
1552 image_view = GetImageViewState(rpabi->pAttachments[att]);
1553 }
1554 } else {
1555 image_view = GetImageViewState(framebuffer->createInfo.pAttachments[att]);
1556 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001557
1558 ValidateImageView(image_view, usage);
1559 }
1560 }
1561}
1562
Attilio Provenzano02859b22020-02-27 14:17:28 +00001563bool BestPractices::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1564 VkSubpassContents contents) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001565 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1566 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001567 return skip;
1568}
1569
1570bool BestPractices::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1571 const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08001572 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001573 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1574 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001575 return skip;
1576}
1577
1578bool BestPractices::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08001579 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001580 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1581 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001582 return skip;
1583}
1584
Sam Walls0961ec02020-03-31 16:39:15 +01001585void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1586 const VkRenderPassBeginInfo* pRenderPassBegin) {
1587 auto prepass_state = cbDepthPrePassStates.find(commandBuffer);
1588
1589 // add the tracking state if it doesn't exist
1590 if (prepass_state == cbDepthPrePassStates.end()) {
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001591 auto result = cbDepthPrePassStates.emplace(commandBuffer, DepthPrePassState{});
Sam Walls0961ec02020-03-31 16:39:15 +01001592
1593 if (!result.second) return;
1594
1595 prepass_state = result.first;
1596 }
1597
1598 // reset the renderpass state
1599 prepass_state->second = {};
1600
Hans-Kristian Arntzena1a92cc2021-03-17 13:09:33 +01001601 const auto* rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
Sam Walls0961ec02020-03-31 16:39:15 +01001602
1603 // track depth / color attachment usage within the renderpass
1604 for (size_t i = 0; i < rp_state->createInfo.subpassCount; i++) {
1605 // record if depth/color attachments are in use for this renderpass
1606 if (rp_state->createInfo.pSubpasses[i].pDepthStencilAttachment != nullptr) prepass_state->second.depthAttachment = true;
1607
1608 if (rp_state->createInfo.pSubpasses[i].colorAttachmentCount > 0) prepass_state->second.colorAttachment = true;
1609 }
1610}
1611
1612void BestPractices::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1613 VkSubpassContents contents) {
1614 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1615 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
1616}
1617
1618void BestPractices::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1619 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1620 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1621 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1622}
1623
1624void BestPractices::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1625 const VkRenderPassBeginInfo* pRenderPassBegin,
1626 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1627 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1628 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1629}
1630
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001631// Generic function to handle validation for all CmdDraw* type functions
1632bool BestPractices::ValidateCmdDrawType(VkCommandBuffer cmd_buffer, const char* caller) const {
1633 bool skip = false;
1634 const CMD_BUFFER_STATE* cb_state = GetCBState(cmd_buffer);
1635 if (cb_state) {
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001636 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
1637 const auto* pipeline_state = cb_state->lastBound[lv_bind_point].pipeline_state;
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001638 const auto& current_vtx_bfr_binding_info = cb_state->current_vertex_buffer_binding_info.vertex_buffer_bindings;
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001639
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001640 // Verify vertex binding
1641 if (pipeline_state->vertex_binding_descriptions_.size() <= 0) {
1642 if ((!current_vtx_bfr_binding_info.empty()) && (!cb_state->vertex_buffer_used)) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001643 skip |= LogPerformanceWarning(cb_state->commandBuffer(), kVUID_BestPractices_DrawState_VtxIndexOutOfBounds,
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001644 "Vertex buffers are bound to %s but no vertex buffers are attached to %s.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001645 report_data->FormatHandle(cb_state->commandBuffer()).c_str(),
1646 report_data->FormatHandle(pipeline_state->pipeline()).c_str());
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001647 }
1648 }
1649 }
1650 return skip;
1651}
1652
Sam Walls0961ec02020-03-31 16:39:15 +01001653void BestPractices::RecordCmdDrawType(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
1654 if (VendorCheckEnabled(kBPVendorArm)) {
1655 RecordCmdDrawTypeArm(cmd_buffer, draw_count, caller);
1656 }
1657}
1658
1659void BestPractices::RecordCmdDrawTypeArm(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
1660 auto prepass_state = cbDepthPrePassStates.find(cmd_buffer);
1661 if (prepass_state != cbDepthPrePassStates.end() && draw_count >= kDepthPrePassMinDrawCountArm) {
1662 if (prepass_state->second.depthOnly) prepass_state->second.numDrawCallsDepthOnly++;
1663
1664 if (prepass_state->second.depthEqualComparison) prepass_state->second.numDrawCallsDepthEqualCompare++;
1665 }
1666}
1667
Camden5b184be2019-08-13 07:50:19 -06001668bool BestPractices::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001669 uint32_t firstVertex, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06001670 bool skip = false;
1671
1672 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001673 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
1674 "Warning: You are calling vkCmdDraw() with an instanceCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001675 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDraw()");
Camden5b184be2019-08-13 07:50:19 -06001676 }
1677
1678 return skip;
1679}
1680
Sam Walls0961ec02020-03-31 16:39:15 +01001681void BestPractices::PostCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
1682 uint32_t firstVertex, uint32_t firstInstance) {
1683 StateTracker::PostCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
1684 RecordCmdDrawType(commandBuffer, vertexCount * instanceCount, "vkCmdDraw()");
1685}
1686
Camden5b184be2019-08-13 07:50:19 -06001687bool BestPractices::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001688 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06001689 bool skip = false;
1690
1691 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001692 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
1693 "Warning: You are calling vkCmdDrawIndexed() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06001694 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001695 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexed()");
1696
Attilio Provenzano02859b22020-02-27 14:17:28 +00001697 // Check if we reached the limit for small indexed draw calls.
1698 // Note that we cannot update the draw call count here, so we do it in PreCallRecordCmdDrawIndexed.
1699 const CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
1700 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices &&
1701 (cmd_state->small_indexed_draw_call_count == kMaxSmallIndexedDrawcalls - 1)) {
1702 skip |= VendorCheckEnabled(kBPVendorArm) &&
1703 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_ManySmallIndexedDrawcalls,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -06001704 "%s: The command buffer contains many small indexed drawcalls "
Attilio Provenzano02859b22020-02-27 14:17:28 +00001705 "(at least %u drawcalls with less than %u indices each). This may cause pipeline bubbles. "
1706 "You can try batching drawcalls or instancing when applicable.",
1707 VendorSpecificTag(kBPVendorArm), kMaxSmallIndexedDrawcalls, kSmallIndexedDrawcallIndices);
1708 }
1709
Sam Walls8e77e4f2020-03-16 20:47:40 +00001710 if (VendorCheckEnabled(kBPVendorArm)) {
1711 ValidateIndexBufferArm(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
1712 }
1713
1714 return skip;
1715}
1716
1717bool BestPractices::ValidateIndexBufferArm(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1718 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
1719 bool skip = false;
1720
1721 // check for sparse/underutilised index buffer, and post-transform cache thrashing
1722 const auto* cmd_state = GetCBState(commandBuffer);
1723 if (cmd_state == nullptr) return skip;
1724
locke-lunarg1ae57d62020-11-18 10:49:19 -07001725 const auto* ib_state = cmd_state->index_buffer_binding.buffer_state.get();
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06001726 if (ib_state == nullptr || cmd_state->index_buffer_binding.buffer_state->Destroyed()) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00001727
1728 const VkIndexType ib_type = cmd_state->index_buffer_binding.index_type;
1729 const auto& ib_mem_state = *ib_state->binding.mem_state;
1730 const VkDeviceSize ib_mem_offset = ib_mem_state.mapped_range.offset;
1731 const void* ib_mem = ib_mem_state.p_driver_data;
1732 bool primitive_restart_enable = false;
1733
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001734 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
1735 const auto& pipeline_binding_iter = cmd_state->lastBound[lv_bind_point];
1736 const auto* pipeline_state = pipeline_binding_iter.pipeline_state;
Sam Walls8e77e4f2020-03-16 20:47:40 +00001737
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001738 if (pipeline_state != nullptr && pipeline_state->graphicsPipelineCI.pInputAssemblyState != nullptr) {
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001739 primitive_restart_enable = pipeline_state->graphicsPipelineCI.pInputAssemblyState->primitiveRestartEnable == VK_TRUE;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001740 }
Sam Walls8e77e4f2020-03-16 20:47:40 +00001741
1742 // 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 -06001743 if (ib_mem && pipeline_binding_iter.IsUsing()) {
Sam Walls8e77e4f2020-03-16 20:47:40 +00001744 uint32_t scan_stride;
1745 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1746 scan_stride = sizeof(uint8_t);
1747 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1748 scan_stride = sizeof(uint16_t);
1749 } else {
1750 scan_stride = sizeof(uint32_t);
1751 }
1752
1753 const uint8_t* scan_begin = static_cast<const uint8_t*>(ib_mem) + ib_mem_offset + firstIndex * scan_stride;
1754 const uint8_t* scan_end = scan_begin + indexCount * scan_stride;
1755
1756 // Min and max are important to track for some Mali architectures. In older Mali devices without IDVS, all
1757 // vertices corresponding to indices between the minimum and maximum may be loaded, and possibly shaded,
1758 // irrespective of whether or not they're part of the draw call.
1759
1760 // start with minimum as 0xFFFFFFFF and adjust to indices in the buffer
1761 uint32_t min_index = ~0u;
1762 // start with maximum as 0 and adjust to indices in the buffer
1763 uint32_t max_index = 0u;
1764
1765 // first scan-through, we're looking to simulate a model LRU post-transform cache, estimating the number of vertices shaded
1766 // for the given index buffer
1767 uint32_t vertex_shade_count = 0;
1768
1769 PostTransformLRUCacheModel post_transform_cache;
1770
1771 // The size of the cache being modelled positively correlates with how much behaviour it can capture about
1772 // arbitrary ground-truth hardware/architecture cache behaviour. I.e. it's a good solution when we don't know the
1773 // target architecture.
1774 // However, modelling a post-transform cache with more than 32 elements gives diminishing returns in practice.
1775 // http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
1776 post_transform_cache.resize(32);
1777
1778 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
1779 uint32_t scan_index;
1780 uint32_t primitive_restart_value;
1781 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1782 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
1783 primitive_restart_value = 0xFF;
1784 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1785 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
1786 primitive_restart_value = 0xFFFF;
1787 } else {
1788 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
1789 primitive_restart_value = 0xFFFFFFFF;
1790 }
1791
1792 max_index = std::max(max_index, scan_index);
1793 min_index = std::min(min_index, scan_index);
1794
1795 if (!primitive_restart_enable || scan_index != primitive_restart_value) {
1796 bool in_cache = post_transform_cache.query_cache(scan_index);
1797 // if the shaded vertex corresponding to the index is not in the PT-cache, we need to shade again
1798 if (!in_cache) vertex_shade_count++;
1799 }
1800 }
1801
1802 // 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 +01001803 // 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
1804 if (max_index < min_index || max_index == min_index) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00001805
1806 if (max_index - min_index >= indexCount) {
Mark Young0ec6b062020-11-19 15:32:17 -07001807 skip |=
1808 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
1809 "%s The indices which were specified for the draw call only utilise approximately %.02f%% of "
1810 "index buffer value range. Arm Mali architectures before G71 do not have IDVS (Index-Driven "
1811 "Vertex Shading), meaning all vertices corresponding to indices between the minimum and "
1812 "maximum would be loaded, and possibly shaded, whether or not they are used.",
1813 VendorSpecificTag(kBPVendorArm),
1814 (static_cast<float>(indexCount) / static_cast<float>(max_index - min_index)) * 100.0f);
Sam Walls8e77e4f2020-03-16 20:47:40 +00001815 return skip;
1816 }
1817
1818 // use a dynamic vector of bitsets as a memory-compact representation of which indices are included in the draw call
1819 // 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 +01001820 const size_t refs_per_bucket = 64;
1821 std::vector<std::bitset<refs_per_bucket>> vertex_reference_buckets;
1822
1823 const uint32_t n_indices = max_index - min_index + 1;
1824 const uint32_t n_buckets = (n_indices / static_cast<uint32_t>(refs_per_bucket)) +
1825 ((n_indices % static_cast<uint32_t>(refs_per_bucket)) != 0 ? 1 : 0);
1826
1827 // there needs to be at least one bitset to store a set of indices smaller than n_buckets
1828 vertex_reference_buckets.resize(std::max(1u, n_buckets));
Sam Walls8e77e4f2020-03-16 20:47:40 +00001829
1830 // To avoid using too much memory, we run over the indices again.
1831 // Knowing the size from the last scan allows us to record index usage with bitsets
1832 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
1833 uint32_t scan_index;
1834 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1835 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
1836 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1837 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
1838 } else {
1839 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
1840 }
1841 // keep track of the set of all indices used to reference vertices in the draw call
1842 size_t index_offset = scan_index - min_index;
Sam Walls61b06892020-07-23 16:20:50 +01001843 size_t bitset_bucket_index = index_offset / refs_per_bucket;
1844 uint64_t used_indices = 1ull << ((index_offset % refs_per_bucket) & 0xFFFFFFFFu);
Sam Walls8e77e4f2020-03-16 20:47:40 +00001845 vertex_reference_buckets[bitset_bucket_index] |= used_indices;
1846 }
1847
1848 uint32_t vertex_reference_count = 0;
1849 for (const auto& bitset : vertex_reference_buckets) {
1850 vertex_reference_count += static_cast<uint32_t>(bitset.count());
1851 }
1852
1853 // 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 -07001854 float utilization = static_cast<float>(vertex_reference_count) / static_cast<float>(max_index - min_index + 1);
Sam Walls8e77e4f2020-03-16 20:47:40 +00001855 // 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 -07001856 float cache_hit_rate = static_cast<float>(vertex_reference_count) / static_cast<float>(vertex_shade_count);
Sam Walls8e77e4f2020-03-16 20:47:40 +00001857
1858 if (utilization < 0.5f) {
1859 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
1860 "%s The indices which were specified for the draw call only utilise approximately "
1861 "%.02f%% of the bound vertex buffer.",
1862 VendorSpecificTag(kBPVendorArm), utilization);
1863 }
1864
1865 if (cache_hit_rate <= 0.5f) {
1866 skip |=
1867 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_PostTransformCacheThrashing,
1868 "%s The indices which were specified for the draw call are estimated to cause thrashing of "
1869 "the post-transform vertex cache, with a hit-rate of %.02f%%. "
1870 "I.e. the ordering of the index buffer may not make optimal use of indices associated with "
1871 "recently shaded vertices.",
1872 VendorSpecificTag(kBPVendorArm), cache_hit_rate * 100.0f);
1873 }
1874 }
1875
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001876 return skip;
1877}
1878
Attilio Provenzano02859b22020-02-27 14:17:28 +00001879void BestPractices::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1880 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
1881 ValidationStateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset,
1882 firstInstance);
1883
1884 CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
1885 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices) {
1886 cmd_state->small_indexed_draw_call_count++;
1887 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001888
1889 ValidateBoundDescriptorSets(commandBuffer);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001890}
1891
Sam Walls0961ec02020-03-31 16:39:15 +01001892void BestPractices::PostCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1893 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
1894 StateTracker::PostCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
1895 RecordCmdDrawType(commandBuffer, indexCount * instanceCount, "vkCmdDrawIndexed()");
1896}
1897
sfricke-samsung681ab7b2020-10-29 01:53:35 -07001898bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
1899 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
1900 uint32_t maxDrawCount, uint32_t stride) const {
1901 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCount()");
1902
1903 return skip;
1904}
1905
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001906bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
1907 VkDeviceSize offset, VkBuffer countBuffer,
1908 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
1909 uint32_t stride) const {
1910 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCountKHR()");
Camden5b184be2019-08-13 07:50:19 -06001911
1912 return skip;
1913}
1914
1915bool BestPractices::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001916 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06001917 bool skip = false;
1918
1919 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001920 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
1921 "Warning: You are calling vkCmdDrawIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001922 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirect()");
Camden5b184be2019-08-13 07:50:19 -06001923 }
1924
1925 return skip;
1926}
1927
Sam Walls0961ec02020-03-31 16:39:15 +01001928void BestPractices::PostCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
1929 uint32_t count, uint32_t stride) {
1930 StateTracker::PostCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, count, stride);
1931 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndirect()");
1932}
1933
Camden5b184be2019-08-13 07:50:19 -06001934bool BestPractices::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001935 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06001936 bool skip = false;
1937
1938 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001939 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
1940 "Warning: You are calling vkCmdDrawIndexedIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001941 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirect()");
Camden5b184be2019-08-13 07:50:19 -06001942 }
1943
1944 return skip;
1945}
1946
Sam Walls0961ec02020-03-31 16:39:15 +01001947void BestPractices::PostCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
1948 uint32_t count, uint32_t stride) {
1949 StateTracker::PostCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, count, stride);
1950 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndexedIndirect()");
1951}
1952
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001953void BestPractices::ValidateBoundDescriptorSets(VkCommandBuffer commandBuffer) {
1954 const CMD_BUFFER_STATE* cb_state = GetCBState(commandBuffer);
1955
1956 if (cb_state) {
1957 for (auto descriptor_set : cb_state->validated_descriptor_sets) {
1958 for (uint32_t binding = 0; binding < descriptor_set->GetBindingCount(); ++binding) {
1959 auto index_range = descriptor_set->GetGlobalIndexRangeFromBinding(binding);
1960 for (uint32_t i = index_range.start; i < index_range.end; ++i) {
ZandroFargnoliacf12f02020-06-18 16:50:00 +01001961 VkImageView image_view{VK_NULL_HANDLE};
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001962
1963 auto descriptor = descriptor_set->GetDescriptorFromGlobalIndex(i);
1964 switch (descriptor->GetClass()) {
1965 case cvdescriptorset::DescriptorClass::Image: {
1966 if (const auto image_descriptor = static_cast<const cvdescriptorset::ImageDescriptor*>(descriptor)) {
1967 image_view = image_descriptor->GetImageView();
1968 }
1969 }
1970 case cvdescriptorset::DescriptorClass::ImageSampler: {
1971 if (const auto image_sampler_descriptor =
1972 static_cast<const cvdescriptorset::ImageSamplerDescriptor*>(descriptor)) {
1973 image_view = image_sampler_descriptor->GetImageView();
1974 }
1975 }
ZandroFargnoliacf12f02020-06-18 16:50:00 +01001976 default:
1977 continue;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001978 }
1979
1980 if (image_view) {
1981 IMAGE_VIEW_STATE* image_view_state = GetImageViewState(image_view);
1982
1983 if (descriptor_set->GetTypeFromIndex(i) == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001984 ValidateImageView(image_view_state, IMAGE_SUBRESOURCE_USAGE_BP::RESOURCE_READ);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001985 }
1986
1987 if (descriptor_set->GetTypeFromIndex(i) == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001988 ValidateImageView(image_view_state, IMAGE_SUBRESOURCE_USAGE_BP::RESOURCE_WRITE);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001989 }
1990 }
1991 }
1992 }
1993 }
1994 }
1995}
1996
1997void BestPractices::PreCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
1998 uint32_t firstVertex, uint32_t firstInstance) {
1999 ValidateBoundDescriptorSets(commandBuffer);
2000}
2001
2002void BestPractices::PreCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2003 uint32_t drawCount, uint32_t stride) {
2004 ValidateBoundDescriptorSets(commandBuffer);
2005}
2006
2007void BestPractices::PreCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2008 uint32_t drawCount, uint32_t stride) {
2009 ValidateBoundDescriptorSets(commandBuffer);
2010}
2011
Camden5b184be2019-08-13 07:50:19 -06002012bool BestPractices::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t groupCountX, uint32_t groupCountY,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002013 uint32_t groupCountZ) const {
Camden5b184be2019-08-13 07:50:19 -06002014 bool skip = false;
2015
2016 if ((groupCountX == 0) || (groupCountY == 0) || (groupCountZ == 0)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002017 skip |= LogWarning(device, kVUID_BestPractices_CmdDispatch_GroupCountZero,
2018 "Warning: You are calling vkCmdDispatch() while one or more groupCounts are zero (groupCountX = %" PRIu32
2019 ", groupCountY = %" PRIu32 ", groupCountZ = %" PRIu32 ").",
2020 groupCountX, groupCountY, groupCountZ);
Camden5b184be2019-08-13 07:50:19 -06002021 }
2022
2023 return skip;
2024}
Camden83a9c372019-08-14 11:41:38 -06002025
Sam Walls0961ec02020-03-31 16:39:15 +01002026bool BestPractices::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
2027 bool skip = false;
2028
2029 skip |= StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
2030
2031 auto prepass_state = cbDepthPrePassStates.find(commandBuffer);
2032
2033 if (prepass_state == cbDepthPrePassStates.end()) return skip;
2034
2035 bool uses_depth = (prepass_state->second.depthAttachment || prepass_state->second.colorAttachment) &&
2036 prepass_state->second.numDrawCallsDepthEqualCompare >= kDepthPrePassNumDrawCallsArm &&
2037 prepass_state->second.numDrawCallsDepthOnly >= kDepthPrePassNumDrawCallsArm;
2038 if (uses_depth) {
2039 skip |= LogPerformanceWarning(
2040 device, kVUID_BestPractices_EndRenderPass_DepthPrePassUsage,
2041 "%s Depth pre-passes may be in use. In general, this is not recommended, as in Arm Mali GPUs since "
2042 "Mali-T620, Forward Pixel Killing (FPK) can already perform automatic hidden surface removal; in which "
2043 "case, using depth pre-passes for hidden surface removal may worsen performance.",
2044 VendorSpecificTag(kBPVendorArm));
2045 }
2046
2047 return skip;
2048}
2049
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002050void BestPractices::PreCallRecordCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) {
2051 ValidateBoundDescriptorSets(commandBuffer);
2052}
2053
2054void BestPractices::PreCallRecordCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) {
2055 ValidateBoundDescriptorSets(commandBuffer);
2056}
2057
Camden Stocker9c051442019-11-06 14:28:43 -08002058bool BestPractices::ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(VkPhysicalDevice physicalDevice,
2059 const char* api_name) const {
2060 bool skip = false;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002061 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
Camden Stocker9c051442019-11-06 14:28:43 -08002062
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002063 if (bp_pd_state) {
2064 if (bp_pd_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState == UNCALLED) {
2065 skip |= LogWarning(physicalDevice, kVUID_BestPractices_DisplayPlane_PropertiesNotCalled,
2066 "Potential problem with calling %s() without first retrieving properties from "
2067 "vkGetPhysicalDeviceDisplayPlanePropertiesKHR or vkGetPhysicalDeviceDisplayPlaneProperties2KHR.",
2068 api_name);
2069 }
Camden Stocker9c051442019-11-06 14:28:43 -08002070 }
2071
2072 return skip;
2073}
2074
Camden83a9c372019-08-14 11:41:38 -06002075bool BestPractices::PreCallValidateGetDisplayPlaneSupportedDisplaysKHR(VkPhysicalDevice physicalDevice, uint32_t planeIndex,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002076 uint32_t* pDisplayCount, VkDisplayKHR* pDisplays) const {
Camden83a9c372019-08-14 11:41:38 -06002077 bool skip = false;
2078
Camden Stocker9c051442019-11-06 14:28:43 -08002079 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneSupportedDisplaysKHR");
Camden83a9c372019-08-14 11:41:38 -06002080
Camden Stocker9c051442019-11-06 14:28:43 -08002081 return skip;
2082}
2083
2084bool BestPractices::PreCallValidateGetDisplayPlaneCapabilitiesKHR(VkPhysicalDevice physicalDevice, VkDisplayModeKHR mode,
2085 uint32_t planeIndex,
2086 VkDisplayPlaneCapabilitiesKHR* pCapabilities) const {
2087 bool skip = false;
2088
2089 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilitiesKHR");
2090
2091 return skip;
2092}
2093
2094bool BestPractices::PreCallValidateGetDisplayPlaneCapabilities2KHR(VkPhysicalDevice physicalDevice,
2095 const VkDisplayPlaneInfo2KHR* pDisplayPlaneInfo,
2096 VkDisplayPlaneCapabilities2KHR* pCapabilities) const {
2097 bool skip = false;
2098
2099 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilities2KHR");
Camden83a9c372019-08-14 11:41:38 -06002100
2101 return skip;
2102}
Camden05de2d42019-08-19 10:23:56 -06002103
2104bool BestPractices::PreCallValidateGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain, uint32_t* pSwapchainImageCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002105 VkImage* pSwapchainImages) const {
Camden05de2d42019-08-19 10:23:56 -06002106 bool skip = false;
2107
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002108 auto swapchain_state_itr = swapchain_bp_state_map.find(swapchain);
Camden05de2d42019-08-19 10:23:56 -06002109
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002110 if ((swapchain_state_itr != swapchain_bp_state_map.cend()) && pSwapchainImages) {
Camden05de2d42019-08-19 10:23:56 -06002111 // Compare the preliminary value of *pSwapchainImageCount with the value this time:
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002112 if (swapchain_state_itr->second.vkGetSwapchainImagesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002113 skip |=
2114 LogWarning(device, kVUID_Core_Swapchain_PriorCount,
2115 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImageCount; but no prior positive value has "
2116 "been seen for pSwapchainImages.");
Camden05de2d42019-08-19 10:23:56 -06002117 }
2118 }
2119
2120 return skip;
2121}
2122
2123// Common function to handle validation for GetPhysicalDeviceQueueFamilyProperties & 2KHR version
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002124bool BestPractices::ValidateCommonGetPhysicalDeviceQueueFamilyProperties(const PHYSICAL_DEVICE_STATE* pd_state,
2125 uint32_t requested_queue_family_property_count,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002126 const CALL_STATE call_state,
2127 const char* caller_name) const {
Camden05de2d42019-08-19 10:23:56 -06002128 bool skip = false;
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002129 // Verify that for each physical device, this command is called first with NULL pQueueFamilyProperties in order to get count
2130 if (UNCALLED == call_state) {
2131 skip |= LogWarning(
2132 pd_state->phys_device, kVUID_Core_DevLimit_MissingQueryCount,
2133 "%s is called with non-NULL pQueueFamilyProperties before obtaining pQueueFamilyPropertyCount. It is "
2134 "recommended "
2135 "to first call %s with NULL pQueueFamilyProperties in order to obtain the maximal pQueueFamilyPropertyCount.",
2136 caller_name, caller_name);
2137 // Then verify that pCount that is passed in on second call matches what was returned
2138 } else if (pd_state->queue_family_known_count != requested_queue_family_property_count) {
2139 skip |= LogWarning(pd_state->phys_device, kVUID_Core_DevLimit_CountMismatch,
2140 "%s is called with non-NULL pQueueFamilyProperties and pQueueFamilyPropertyCount value %" PRIu32
2141 ", but the largest previously returned pQueueFamilyPropertyCount for this physicalDevice is %" PRIu32
2142 ". It is recommended to instead receive all the properties by calling %s with "
2143 "pQueueFamilyPropertyCount that was "
2144 "previously obtained by calling %s with NULL pQueueFamilyProperties.",
2145 caller_name, requested_queue_family_property_count, pd_state->queue_family_known_count, caller_name,
2146 caller_name);
Camden05de2d42019-08-19 10:23:56 -06002147 }
2148
2149 return skip;
2150}
2151
Jeff Bolz5c801d12019-10-09 10:38:45 -05002152bool BestPractices::PreCallValidateBindAccelerationStructureMemoryNV(
2153 VkDevice device, uint32_t bindInfoCount, const VkBindAccelerationStructureMemoryInfoNV* pBindInfos) const {
Camden Stocker82510582019-09-03 14:00:16 -06002154 bool skip = false;
2155
2156 for (uint32_t i = 0; i < bindInfoCount; i++) {
sourav parmarcd5fb182020-07-17 12:58:44 -07002157 const ACCELERATION_STRUCTURE_STATE* as_state = GetAccelerationStructureStateNV(pBindInfos[i].accelerationStructure);
Camden Stocker82510582019-09-03 14:00:16 -06002158 if (!as_state->memory_requirements_checked) {
2159 // There's not an explicit requirement in the spec to call vkGetImageMemoryRequirements() prior to calling
2160 // BindAccelerationStructureMemoryNV but it's implied in that memory being bound must conform with
2161 // VkAccelerationStructureMemoryRequirementsInfoNV from vkGetAccelerationStructureMemoryRequirementsNV
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002162 skip |= LogWarning(
2163 device, kVUID_BestPractices_BindAccelNV_NoMemReqQuery,
Camden Stocker82510582019-09-03 14:00:16 -06002164 "vkBindAccelerationStructureMemoryNV(): "
2165 "Binding memory to %s but vkGetAccelerationStructureMemoryRequirementsNV() has not been called on that structure.",
2166 report_data->FormatHandle(pBindInfos[i].accelerationStructure).c_str());
2167 }
2168 }
2169
2170 return skip;
2171}
2172
Camden05de2d42019-08-19 10:23:56 -06002173bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
2174 uint32_t* pQueueFamilyPropertyCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002175 VkQueueFamilyProperties* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06002176 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
2177 assert(physical_device_state);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002178 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physical_device_state->phys_device);
2179 if (pQueueFamilyProperties && bp_pd_state) {
2180 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
2181 bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
2182 "vkGetPhysicalDeviceQueueFamilyProperties()");
2183 }
2184 return false;
Camden05de2d42019-08-19 10:23:56 -06002185}
2186
Mike Schuchardt2df08912020-12-15 16:28:09 -08002187bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
2188 uint32_t* pQueueFamilyPropertyCount,
2189 VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06002190 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
2191 assert(physical_device_state);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002192 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physical_device_state->phys_device);
2193 if (pQueueFamilyProperties && bp_pd_state) {
2194 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
2195 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
2196 "vkGetPhysicalDeviceQueueFamilyProperties2()");
2197 }
2198 return false;
Camden05de2d42019-08-19 10:23:56 -06002199}
2200
Jeff Bolz5c801d12019-10-09 10:38:45 -05002201bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2KHR(
Mike Schuchardt2df08912020-12-15 16:28:09 -08002202 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount, VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06002203 auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
2204 assert(physical_device_state);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002205 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physical_device_state->phys_device);
2206 if (pQueueFamilyProperties && bp_pd_state) {
2207 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
2208 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
2209 "vkGetPhysicalDeviceQueueFamilyProperties2KHR()");
2210 }
2211 return false;
Camden05de2d42019-08-19 10:23:56 -06002212}
2213
2214bool BestPractices::PreCallValidateGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
2215 uint32_t* pSurfaceFormatCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002216 VkSurfaceFormatKHR* pSurfaceFormats) const {
Camden05de2d42019-08-19 10:23:56 -06002217 if (!pSurfaceFormats) return false;
2218 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002219 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2220 const auto& call_state = bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState;
Camden05de2d42019-08-19 10:23:56 -06002221 bool skip = false;
2222 if (call_state == UNCALLED) {
2223 // Since we haven't recorded a preliminary value of *pSurfaceFormatCount, that likely means that the application didn't
2224 // previously call this function with a NULL value of pSurfaceFormats:
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002225 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_MustQueryCount,
2226 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount; but no prior "
2227 "positive value has been seen for pSurfaceFormats.");
Camden05de2d42019-08-19 10:23:56 -06002228 } else {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002229 auto prev_format_count = static_cast<uint32_t>(physical_device_state->surface_formats.size());
Peter Chene191bd72019-09-16 13:04:37 -04002230 if (*pSurfaceFormatCount > prev_format_count) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002231 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_CountMismatch,
2232 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount, and with "
2233 "pSurfaceFormats set to a value (%u) that is greater than the value (%u) that was returned "
2234 "when pSurfaceFormatCount was NULL.",
2235 *pSurfaceFormatCount, prev_format_count);
Camden05de2d42019-08-19 10:23:56 -06002236 }
2237 }
2238 return skip;
2239}
Camden Stocker23cc47d2019-09-03 14:53:57 -06002240
2241bool BestPractices::PreCallValidateQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002242 VkFence fence) const {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002243 bool skip = false;
2244
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002245 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
2246 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
Camden Stocker23cc47d2019-09-03 14:53:57 -06002247 // 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 -07002248 layer_data::unordered_set<const IMAGE_STATE*> sparse_images;
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002249 // Track images getting metadata bound by this call in a set, it'll be recorded into the image_state
2250 // in RecordQueueBindSparse.
Jeremy Gebbencbf22862021-03-03 12:01:22 -07002251 layer_data::unordered_set<const IMAGE_STATE*> sparse_images_with_metadata;
Camden Stocker23cc47d2019-09-03 14:53:57 -06002252 // 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 -07002253 for (uint32_t i = 0; i < bind_info.imageBindCount; ++i) {
2254 const auto& image_bind = bind_info.pImageBinds[i];
Camden Stocker23cc47d2019-09-03 14:53:57 -06002255 auto image_state = GetImageState(image_bind.image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002256 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002257 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002258 }
Camden Stocker23cc47d2019-09-03 14:53:57 -06002259 sparse_images.insert(image_state);
2260 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
2261 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
2262 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002263 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002264 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
2265 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002266 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002267 }
2268 }
2269 if (!image_state->memory_requirements_checked) {
2270 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002271 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002272 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
2273 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002274 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002275 }
2276 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002277 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
2278 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
2279 auto image_state = GetImageState(bind_info.pImageOpaqueBinds[i].image);
2280 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002281 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002282 }
Camden Stocker23cc47d2019-09-03 14:53:57 -06002283 sparse_images.insert(image_state);
2284 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
2285 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
2286 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002287 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002288 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
2289 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002290 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002291 }
2292 }
2293 if (!image_state->memory_requirements_checked) {
2294 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002295 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002296 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
2297 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002298 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002299 }
2300 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
2301 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002302 sparse_images_with_metadata.insert(image_state);
Camden Stocker23cc47d2019-09-03 14:53:57 -06002303 }
2304 }
2305 }
2306 for (const auto& sparse_image_state : sparse_images) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002307 if (sparse_image_state->sparse_metadata_required && !sparse_image_state->sparse_metadata_bound &&
2308 sparse_images_with_metadata.find(sparse_image_state) == sparse_images_with_metadata.end()) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002309 // Warn if sparse image binding metadata required for image with sparse binding, but metadata not bound
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002310 skip |= LogWarning(sparse_image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002311 "vkQueueBindSparse(): Binding sparse memory to %s which requires a metadata aspect but no "
2312 "binding with VK_SPARSE_MEMORY_BIND_METADATA_BIT set was made.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002313 report_data->FormatHandle(sparse_image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002314 }
2315 }
2316 }
2317
2318 return skip;
2319}
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002320
Mark Lobodzinski84101d72020-04-24 09:43:48 -06002321void BestPractices::ManualPostCallRecordQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
2322 VkFence fence, VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07002323 if (result != VK_SUCCESS) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07002324 return;
2325 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002326
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002327 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
2328 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
2329 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
2330 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
2331 auto image_state = GetImageState(bind_info.pImageOpaqueBinds[i].image);
2332 if (!image_state) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002333 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002334 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002335 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
2336 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
2337 image_state->sparse_metadata_bound = true;
2338 }
2339 }
2340 }
2341 }
2342}
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002343
2344bool BestPractices::PreCallValidateCmdClearAttachments(VkCommandBuffer commandBuffer, uint32_t attachmentCount,
Camden Stockerf55721f2019-09-09 11:04:49 -06002345 const VkClearAttachment* pAttachments, uint32_t rectCount,
2346 const VkClearRect* pRects) const {
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002347 bool skip = false;
2348 const CMD_BUFFER_STATE* cb_node = GetCBState(commandBuffer);
2349 if (!cb_node) return skip;
2350
Camden Stockerf55721f2019-09-09 11:04:49 -06002351 // Warn if this is issued prior to Draw Cmd and clearing the entire attachment
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002352 if (!cb_node->hasDrawCmd && (cb_node->activeRenderPassBeginInfo.renderArea.extent.width == pRects[0].rect.extent.width) &&
2353 (cb_node->activeRenderPassBeginInfo.renderArea.extent.height == pRects[0].rect.extent.height)) {
2354 // There are times where app needs to use ClearAttachments (generally when reusing a buffer inside of a render pass)
2355 // This warning should be made more specific. It'd be best to avoid triggering this test if it's a use that must call
2356 // CmdClearAttachments.
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07002357 skip |= LogPerformanceWarning(commandBuffer, kVUID_BestPractices_DrawState_ClearCmdBeforeDraw,
2358 "vkCmdClearAttachments() issued on %s prior to any Draw Cmds. It is recommended you "
2359 "use RenderPass LOAD_OP_CLEAR on Attachments prior to any Draw.",
2360 report_data->FormatHandle(commandBuffer).c_str());
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002361 }
2362
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002363 // Check for uses of ClearAttachments along with LOAD_OP_LOAD,
2364 // as it can be more efficient to just use LOAD_OP_CLEAR
locke-lunargaecf2152020-05-12 17:15:41 -06002365 const RENDER_PASS_STATE* rp = cb_node->activeRenderPass.get();
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002366 if (rp) {
2367 const auto& subpass = rp->createInfo.pSubpasses[cb_node->activeSubpass];
2368
2369 for (uint32_t i = 0; i < attachmentCount; i++) {
2370 auto& attachment = pAttachments[i];
2371 if (attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
2372 uint32_t color_attachment = attachment.colorAttachment;
2373 uint32_t fb_attachment = subpass.pColorAttachments[color_attachment].attachment;
2374
2375 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2376 if (rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2377 skip |= LogPerformanceWarning(
2378 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2379 "vkCmdClearAttachments() issued on %s for color attachment #%u in this subpass, "
2380 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2381 "it is more efficient.",
2382 report_data->FormatHandle(commandBuffer).c_str(), color_attachment);
2383 }
2384 }
2385 }
2386
2387 if (subpass.pDepthStencilAttachment && attachment.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) {
2388 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
2389
2390 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2391 if (rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2392 skip |= LogPerformanceWarning(
2393 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2394 "vkCmdClearAttachments() issued on %s for the depth attachment in this subpass, "
2395 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2396 "it is more efficient.",
2397 report_data->FormatHandle(commandBuffer).c_str());
2398 }
2399 }
2400 }
2401
2402 if (subpass.pDepthStencilAttachment && attachment.aspectMask & VK_IMAGE_ASPECT_STENCIL_BIT) {
2403 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
2404
2405 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2406 if (rp->createInfo.pAttachments[fb_attachment].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2407 skip |= LogPerformanceWarning(
2408 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2409 "vkCmdClearAttachments() issued on %s for the stencil attachment in this subpass, "
2410 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2411 "it is more efficient.",
2412 report_data->FormatHandle(commandBuffer).c_str());
2413 }
2414 }
2415 }
2416 }
2417 }
2418
Camden Stockerf55721f2019-09-09 11:04:49 -06002419 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002420}
Attilio Provenzano02859b22020-02-27 14:17:28 +00002421
2422bool BestPractices::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
2423 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
2424 const VkImageResolve* pRegions) const {
2425 bool skip = false;
2426
2427 skip |= VendorCheckEnabled(kBPVendorArm) &&
2428 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage_ResolvingImage,
2429 "%s Attempting to use vkCmdResolveImage to resolve a multisampled image. "
2430 "This is a very slow and extremely bandwidth intensive path. "
2431 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
2432 VendorSpecificTag(kBPVendorArm));
2433
2434 return skip;
2435}
2436
Jeff Leger178b1e52020-10-05 12:22:23 -04002437bool BestPractices::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
2438 const VkResolveImageInfo2KHR* pResolveImageInfo) const {
2439 bool skip = false;
2440
2441 skip |= VendorCheckEnabled(kBPVendorArm) &&
2442 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2KHR_ResolvingImage,
2443 "%s Attempting to use vkCmdResolveImage2KHR to resolve a multisampled image. "
2444 "This is a very slow and extremely bandwidth intensive path. "
2445 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
2446 VendorSpecificTag(kBPVendorArm));
2447
2448 return skip;
2449}
2450
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002451void BestPractices::PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
2452 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
2453 const VkImageResolve* pRegions) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002454 auto* src = GetImageUsageState(srcImage);
2455 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002456
2457 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002458 ValidateImage(src, IMAGE_SUBRESOURCE_USAGE_BP::RESOURCE_READ, pRegions[i].srcSubresource);
2459 ValidateImage(dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOURCE_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002460 }
2461}
2462
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01002463void BestPractices::PreCallRecordCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
2464 const VkResolveImageInfo2KHR* pResolveImageInfo) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002465 auto* src = GetImageUsageState(pResolveImageInfo->srcImage);
2466 auto* dst = GetImageUsageState(pResolveImageInfo->dstImage);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01002467 uint32_t regionCount = pResolveImageInfo->regionCount;
2468
2469 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002470 ValidateImage(src, IMAGE_SUBRESOURCE_USAGE_BP::RESOURCE_READ, pResolveImageInfo->pRegions[i].srcSubresource);
2471 ValidateImage(dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOURCE_WRITE, pResolveImageInfo->pRegions[i].dstSubresource);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01002472 }
2473}
2474
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002475void BestPractices::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
2476 const VkClearColorValue* pColor, uint32_t rangeCount,
2477 const VkImageSubresourceRange* pRanges) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002478 auto* dst = GetImageUsageState(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002479
2480 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002481 ValidateImage(dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002482 }
2483}
2484
2485void BestPractices::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
2486 const VkClearDepthStencilValue* pDepthStencil, uint32_t rangeCount,
2487 const VkImageSubresourceRange* pRanges) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002488 auto* dst = GetImageUsageState(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002489
2490 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002491 ValidateImage(dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002492 }
2493}
2494
2495void BestPractices::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
2496 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
2497 const VkImageCopy* pRegions) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002498 auto* src = GetImageUsageState(srcImage);
2499 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002500
2501 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002502 ValidateImage(src, IMAGE_SUBRESOURCE_USAGE_BP::RESOURCE_READ, pRegions[i].srcSubresource);
2503 ValidateImage(dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOURCE_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002504 }
2505}
2506
2507void BestPractices::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
2508 VkImageLayout dstImageLayout, uint32_t regionCount,
2509 const VkBufferImageCopy* pRegions) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002510 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002511
2512 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002513 ValidateImage(dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOURCE_WRITE, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002514 }
2515}
2516
2517void BestPractices::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
2518 VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy* pRegions) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002519 auto* src = GetImageUsageState(srcImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002520
2521 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002522 ValidateImage(src, IMAGE_SUBRESOURCE_USAGE_BP::RESOURCE_READ, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002523 }
2524}
2525
2526void BestPractices::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
2527 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
2528 const VkImageBlit* pRegions, VkFilter filter) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002529 auto* src = GetImageUsageState(srcImage);
2530 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002531
2532 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002533 ValidateImage(src, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_READ, pRegions[i].srcSubresource);
2534 ValidateImage(dst, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002535 }
2536}
2537
Attilio Provenzano02859b22020-02-27 14:17:28 +00002538bool BestPractices::PreCallValidateCreateSampler(VkDevice device, const VkSamplerCreateInfo* pCreateInfo,
2539 const VkAllocationCallbacks* pAllocator, VkSampler* pSampler) const {
2540 bool skip = false;
2541
2542 if (VendorCheckEnabled(kBPVendorArm)) {
2543 if ((pCreateInfo->addressModeU != pCreateInfo->addressModeV) || (pCreateInfo->addressModeV != pCreateInfo->addressModeW)) {
2544 skip |= LogPerformanceWarning(
2545 device, kVUID_BestPractices_CreateSampler_DifferentWrappingModes,
2546 "%s Creating a sampler object with wrapping modes which do not match (U = %u, V = %u, W = %u). "
2547 "This may cause reduced performance even if only U (1D image) or U/V wrapping modes (2D "
2548 "image) are actually used. If you need different wrapping modes, disregard this warning.",
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -06002549 VendorSpecificTag(kBPVendorArm), pCreateInfo->addressModeU, pCreateInfo->addressModeV, pCreateInfo->addressModeW);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002550 }
2551
2552 if ((pCreateInfo->minLod != 0.0f) || (pCreateInfo->maxLod < VK_LOD_CLAMP_NONE)) {
2553 skip |= LogPerformanceWarning(
2554 device, kVUID_BestPractices_CreateSampler_LodClamping,
2555 "%s Creating a sampler object with LOD clamping (minLod = %f, maxLod = %f). This may cause reduced performance. "
2556 "Instead of clamping LOD in the sampler, consider using an VkImageView which restricts the mip-levels, set minLod "
2557 "to 0.0, and maxLod to VK_LOD_CLAMP_NONE.",
2558 VendorSpecificTag(kBPVendorArm), pCreateInfo->minLod, pCreateInfo->maxLod);
2559 }
2560
2561 if (pCreateInfo->mipLodBias != 0.0f) {
2562 skip |=
2563 LogPerformanceWarning(device, kVUID_BestPractices_CreateSampler_LodBias,
2564 "%s Creating a sampler object with LOD bias != 0.0 (%f). This will lead to less efficient "
2565 "descriptors being created and may cause reduced performance.",
2566 VendorSpecificTag(kBPVendorArm), pCreateInfo->mipLodBias);
2567 }
2568
2569 if ((pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
2570 pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
2571 pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER) &&
2572 (pCreateInfo->borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK)) {
2573 skip |= LogPerformanceWarning(
2574 device, kVUID_BestPractices_CreateSampler_BorderClampColor,
2575 "%s Creating a sampler object with border clamping and borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK. "
2576 "This will lead to less efficient descriptors being created and may cause reduced performance. "
2577 "If possible, use VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK as the border color.",
2578 VendorSpecificTag(kBPVendorArm));
2579 }
2580
2581 if (pCreateInfo->unnormalizedCoordinates) {
2582 skip |= LogPerformanceWarning(
2583 device, kVUID_BestPractices_CreateSampler_UnnormalizedCoordinates,
2584 "%s Creating a sampler object with unnormalized coordinates. This will lead to less efficient "
2585 "descriptors being created and may cause reduced performance.",
2586 VendorSpecificTag(kBPVendorArm));
2587 }
2588
2589 if (pCreateInfo->anisotropyEnable) {
2590 skip |= LogPerformanceWarning(
2591 device, kVUID_BestPractices_CreateSampler_Anisotropy,
2592 "%s Creating a sampler object with anisotropy. This will lead to less efficient descriptors being created "
2593 "and may cause reduced performance.",
2594 VendorSpecificTag(kBPVendorArm));
2595 }
2596 }
2597
2598 return skip;
2599}
Sam Walls8e77e4f2020-03-16 20:47:40 +00002600
2601void BestPractices::PostTransformLRUCacheModel::resize(size_t size) { _entries.resize(size); }
2602
2603bool BestPractices::PostTransformLRUCacheModel::query_cache(uint32_t value) {
2604 // look for a cache hit
2605 auto hit = std::find_if(_entries.begin(), _entries.end(), [value](const CacheEntry& entry) { return entry.value == value; });
2606 if (hit != _entries.end()) {
2607 // mark the cache hit as being most recently used
2608 hit->age = iteration++;
2609 return true;
2610 }
2611
2612 // if there's no cache hit, we need to model the entry being inserted into the cache
2613 CacheEntry new_entry = {value, iteration};
2614 if (iteration < static_cast<uint32_t>(std::distance(_entries.begin(), _entries.end()))) {
2615 // if there is still space left in the cache, use the next available slot
2616 *(_entries.begin() + iteration) = new_entry;
2617 } else {
2618 // otherwise replace the least recently used cache entry
2619 auto lru = std::min_element(_entries.begin(), hit, [](const CacheEntry& a, const CacheEntry& b) { return a.age < b.age; });
2620 *lru = new_entry;
2621 }
2622 iteration++;
2623 return false;
2624}
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002625
2626bool BestPractices::PreCallValidateAcquireNextImageKHR(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout,
2627 VkSemaphore semaphore, VkFence fence, uint32_t* pImageIndex) const {
2628 const auto swapchain_data = GetSwapchainState(swapchain);
2629 bool skip = false;
2630 if (swapchain_data && swapchain_data->images.size() == 0) {
2631 skip |= LogWarning(swapchain, kVUID_Core_DrawState_SwapchainImagesNotFound,
2632 "vkAcquireNextImageKHR: No images found to acquire from. Application probably did not call "
2633 "vkGetSwapchainImagesKHR after swapchain creation.");
2634 }
2635 return skip;
2636}
2637
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002638void BestPractices::CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(CALL_STATE& call_state, bool no_pointer) {
2639 if (no_pointer) {
2640 if (UNCALLED == call_state) {
2641 call_state = QUERY_COUNT;
2642 }
2643 } else { // Save queue family properties
2644 call_state = QUERY_DETAILS;
2645 }
2646}
2647
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002648void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
2649 uint32_t* pQueueFamilyPropertyCount,
2650 VkQueueFamilyProperties* pQueueFamilyProperties) {
2651 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(physicalDevice, pQueueFamilyPropertyCount,
2652 pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002653 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002654 if (bp_pd_state) {
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002655 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
2656 nullptr == pQueueFamilyProperties);
2657 }
2658}
2659
2660void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
2661 uint32_t* pQueueFamilyPropertyCount,
2662 VkQueueFamilyProperties2* pQueueFamilyProperties) {
2663 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(physicalDevice, pQueueFamilyPropertyCount,
2664 pQueueFamilyProperties);
2665 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2666 if (bp_pd_state) {
2667 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
2668 nullptr == pQueueFamilyProperties);
2669 }
2670}
2671
2672void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(VkPhysicalDevice physicalDevice,
2673 uint32_t* pQueueFamilyPropertyCount,
2674 VkQueueFamilyProperties2* pQueueFamilyProperties) {
2675 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(physicalDevice, pQueueFamilyPropertyCount,
2676 pQueueFamilyProperties);
2677 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2678 if (bp_pd_state) {
2679 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
2680 nullptr == pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002681 }
2682}
2683
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002684void BestPractices::PostCallRecordGetPhysicalDeviceFeatures(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures* pFeatures) {
2685 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002686 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2687 if (bp_pd_state) {
2688 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
2689 }
2690}
2691
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002692void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2(VkPhysicalDevice physicalDevice,
2693 VkPhysicalDeviceFeatures2* pFeatures) {
2694 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002695 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2696 if (bp_pd_state) {
2697 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
2698 }
2699}
2700
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002701void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2KHR(VkPhysicalDevice physicalDevice,
2702 VkPhysicalDeviceFeatures2* pFeatures) {
2703 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2KHR(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002704 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2705 if (bp_pd_state) {
2706 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
2707 }
2708}
2709
2710void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilitiesKHR(VkPhysicalDevice physicalDevice,
2711 VkSurfaceKHR surface,
2712 VkSurfaceCapabilitiesKHR* pSurfaceCapabilities,
2713 VkResult result) {
2714 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2715 if (bp_pd_state) {
2716 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
2717 }
2718}
2719
2720void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2KHR(
2721 VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
2722 VkSurfaceCapabilities2KHR* pSurfaceCapabilities, VkResult result) {
2723 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2724 if (bp_pd_state) {
2725 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
2726 }
2727}
2728
2729void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2EXT(VkPhysicalDevice physicalDevice,
2730 VkSurfaceKHR surface,
2731 VkSurfaceCapabilities2EXT* pSurfaceCapabilities,
2732 VkResult result) {
2733 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2734 if (bp_pd_state) {
2735 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
2736 }
2737}
2738
2739void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice physicalDevice,
2740 VkSurfaceKHR surface, uint32_t* pPresentModeCount,
2741 VkPresentModeKHR* pPresentModes, VkResult result) {
2742 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2743 if (bp_pd_data) {
2744 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfacePresentModesKHRState;
2745
2746 if (*pPresentModeCount) {
2747 if (call_state < QUERY_COUNT) {
2748 call_state = QUERY_COUNT;
2749 }
2750 }
2751 if (pPresentModes) {
2752 if (call_state < QUERY_DETAILS) {
2753 call_state = QUERY_DETAILS;
2754 }
2755 }
2756 }
2757}
2758
2759void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
2760 uint32_t* pSurfaceFormatCount,
2761 VkSurfaceFormatKHR* pSurfaceFormats, VkResult result) {
2762 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2763 if (bp_pd_data) {
2764 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState;
2765
2766 if (*pSurfaceFormatCount) {
2767 if (call_state < QUERY_COUNT) {
2768 call_state = QUERY_COUNT;
2769 }
2770 }
2771 if (pSurfaceFormats) {
2772 if (call_state < QUERY_DETAILS) {
2773 call_state = QUERY_DETAILS;
2774 }
2775 }
2776 }
2777}
2778
2779void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormats2KHR(VkPhysicalDevice physicalDevice,
2780 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
2781 uint32_t* pSurfaceFormatCount,
2782 VkSurfaceFormat2KHR* pSurfaceFormats, VkResult result) {
2783 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2784 if (bp_pd_data) {
2785 if (*pSurfaceFormatCount) {
2786 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_COUNT) {
2787 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_COUNT;
2788 }
2789 }
2790 if (pSurfaceFormats) {
2791 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_DETAILS) {
2792 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_DETAILS;
2793 }
2794 }
2795 }
2796}
2797
2798void BestPractices::ManualPostCallRecordGetPhysicalDeviceDisplayPlanePropertiesKHR(VkPhysicalDevice physicalDevice,
2799 uint32_t* pPropertyCount,
2800 VkDisplayPlanePropertiesKHR* pProperties,
2801 VkResult result) {
2802 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2803 if (bp_pd_data) {
2804 if (*pPropertyCount) {
2805 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_COUNT) {
2806 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_COUNT;
2807 }
2808 }
2809 if (pProperties) {
2810 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_DETAILS) {
2811 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_DETAILS;
2812 }
2813 }
2814 }
2815}
2816
2817void BestPractices::ManualPostCallRecordCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
2818 const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain,
2819 VkResult result) {
2820 if (VK_SUCCESS == result) {
2821 swapchain_bp_state_map.emplace(*pSwapchain, SWAPCHAIN_STATE_BP{});
2822 }
2823}
2824
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002825void BestPractices::PostCallRecordDestroySwapchainKHR(VkDevice device, VkSwapchainKHR swapchain,
2826 const VkAllocationCallbacks* pAllocator) {
2827 ValidationStateTracker::PostCallRecordDestroySwapchainKHR(device, swapchain, pAllocator);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002828 auto swapchain_state_itr = swapchain_bp_state_map.find(swapchain);
2829 if (swapchain_state_itr != swapchain_bp_state_map.cend()) {
2830 swapchain_bp_state_map.erase(swapchain_state_itr);
2831 }
2832}
2833
2834void BestPractices::ManualPostCallRecordGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain,
2835 uint32_t* pSwapchainImageCount, VkImage* pSwapchainImages,
2836 VkResult result) {
2837 auto swapchain_state_itr = swapchain_bp_state_map.find(swapchain);
2838 assert(swapchain_state_itr != swapchain_bp_state_map.cend());
2839 auto& swapchain_state = swapchain_state_itr->second;
2840 if (pSwapchainImages || *pSwapchainImageCount) {
2841 if (swapchain_state.vkGetSwapchainImagesKHRState < QUERY_DETAILS) {
2842 swapchain_state.vkGetSwapchainImagesKHRState = QUERY_DETAILS;
2843 }
2844 }
2845}
2846
2847void BestPractices::ManualPostCallRecordEnumeratePhysicalDevices(VkInstance instance, uint32_t* pPhysicalDeviceCount,
2848 VkPhysicalDevice* pPhysicalDevices, VkResult result) {
2849 if ((nullptr != pPhysicalDevices) && ((result == VK_SUCCESS || result == VK_INCOMPLETE))) {
2850 for (uint32_t i = 0; i < *pPhysicalDeviceCount; i++) {
2851 phys_device_bp_state_map.emplace(pPhysicalDevices[i], PHYSICAL_DEVICE_STATE_BP{});
2852 }
2853 }
2854}
2855
2856void BestPractices::ManualPostCallRecordCreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo*, const VkAllocationCallbacks*,
2857 VkDevice*, VkResult result) {
2858 if (VK_SUCCESS == result) {
2859 instance_device_bp_state = &phys_device_bp_state_map[gpu];
2860 }
2861}
2862
2863PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP(const VkPhysicalDevice& phys_device) {
2864 if (phys_device_bp_state_map.count(phys_device) > 0) {
2865 return &phys_device_bp_state_map.at(phys_device);
2866 } else {
2867 return nullptr;
2868 }
2869}
2870
2871const PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP(const VkPhysicalDevice& phys_device) const {
2872 if (phys_device_bp_state_map.count(phys_device) > 0) {
2873 return &phys_device_bp_state_map.at(phys_device);
2874 } else {
2875 return nullptr;
2876 }
2877}
2878
2879PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP() {
2880 auto bp_state = (reinterpret_cast<BestPractices*>(instance_state))->instance_device_bp_state;
2881 if (bp_state) {
2882 return bp_state;
2883 } else if (!bp_state && phys_device_bp_state_map.count(physical_device_state->phys_device) > 0) {
2884 return &phys_device_bp_state_map.at(physical_device_state->phys_device);
2885 } else {
2886 return nullptr;
2887 }
2888}
2889
2890const PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP() const {
2891 auto bp_state = (reinterpret_cast<BestPractices*>(instance_state))->instance_device_bp_state;
2892 if (bp_state) {
2893 return bp_state;
2894 } else if (!bp_state && phys_device_bp_state_map.count(physical_device_state->phys_device) > 0) {
2895 return &phys_device_bp_state_map.at(physical_device_state->phys_device);
2896 } else {
2897 return nullptr;
2898 }
2899}