blob: 445c6690ead4cef379bcbbecbd5542830460fbfd [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"
Camden5b184be2019-08-13 07:50:19 -060024
25#include <string>
Sam Walls8e77e4f2020-03-16 20:47:40 +000026#include <bitset>
Sam Wallsd7ab6db2020-06-19 20:41:54 +010027#include <memory>
Camden5b184be2019-08-13 07:50:19 -060028
Attilio Provenzano19d6a982020-02-27 12:41:41 +000029struct VendorSpecificInfo {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060030 EnableFlags vendor_id;
Attilio Provenzano19d6a982020-02-27 12:41:41 +000031 std::string name;
32};
33
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -070034const std::map<BPVendorFlagBits, VendorSpecificInfo> kVendorInfo = {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060035 {kBPVendorArm, {vendor_specific_arm, "Arm"}},
Attilio Provenzano19d6a982020-02-27 12:41:41 +000036};
37
38bool BestPractices::VendorCheckEnabled(BPVendorFlags vendors) const {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -070039 for (const auto& vendor : kVendorInfo) {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060040 if (vendors & vendor.first && enabled[vendor.second.vendor_id]) {
Attilio Provenzano19d6a982020-02-27 12:41:41 +000041 return true;
42 }
43 }
44 return false;
45}
46
47const char* VendorSpecificTag(BPVendorFlags vendors) {
48 // Cache built vendor tags in a map
49 static std::unordered_map<BPVendorFlags, std::string> tag_map;
50
51 auto res = tag_map.find(vendors);
52 if (res == tag_map.end()) {
53 // Build the vendor tag string
54 std::stringstream vendor_tag;
55
56 vendor_tag << "[";
57 bool first_vendor = true;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -070058 for (const auto& vendor : kVendorInfo) {
Attilio Provenzano19d6a982020-02-27 12:41:41 +000059 if (vendors & vendor.first) {
60 if (!first_vendor) {
61 vendor_tag << ", ";
62 }
63 vendor_tag << vendor.second.name;
64 first_vendor = false;
65 }
66 }
67 vendor_tag << "]";
68
69 tag_map[vendors] = vendor_tag.str();
70 res = tag_map.find(vendors);
71 }
72
73 return res->second.c_str();
74}
75
Mark Lobodzinski6167e102020-02-24 17:03:55 -070076const char* DepReasonToString(ExtDeprecationReason reason) {
77 switch (reason) {
78 case kExtPromoted:
79 return "promoted to";
80 break;
81 case kExtObsoleted:
82 return "obsoleted by";
83 break;
84 case kExtDeprecated:
85 return "deprecated by";
86 break;
87 default:
88 return "";
89 break;
90 }
91}
92
93bool BestPractices::ValidateDeprecatedExtensions(const char* api_name, const char* extension_name, uint32_t version,
94 const char* vuid) const {
95 bool skip = false;
96 auto dep_info_it = deprecated_extensions.find(extension_name);
97 if (dep_info_it != deprecated_extensions.end()) {
98 auto dep_info = dep_info_it->second;
Mark Lobodzinski6a149702020-05-14 12:21:34 -060099 if (((dep_info.target.compare("VK_VERSION_1_1") == 0) && (version >= VK_API_VERSION_1_1)) ||
100 ((dep_info.target.compare("VK_VERSION_1_2") == 0) && (version >= VK_API_VERSION_1_2))) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700101 skip |=
102 LogWarning(instance, vuid, "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
103 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
Mark Lobodzinski6a149702020-05-14 12:21:34 -0600104 } else if (dep_info.target.find("VK_VERSION") == std::string::npos) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700105 if (dep_info.target.length() == 0) {
106 skip |= LogWarning(instance, vuid,
107 "%s(): Attempting to enable deprecated extension %s, but this extension has been deprecated "
108 "without replacement.",
109 api_name, extension_name);
110 } else {
111 skip |= LogWarning(instance, vuid,
112 "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
113 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
114 }
115 }
116 }
117 return skip;
118}
119
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700120bool BestPractices::ValidateSpecialUseExtensions(const char* api_name, const char* extension_name, const char* vuid) const {
121 bool skip = false;
122 auto dep_info_it = special_use_extensions.find(extension_name);
123
124 if (dep_info_it != special_use_extensions.end()) {
125 auto special_uses = dep_info_it->second;
126 std::string message("is intended to support the following uses: ");
127 if (special_uses.find("cadsupport") != std::string::npos) {
128 message.append("specialized functionality used by CAD/CAM applications, ");
129 }
130 if (special_uses.find("d3demulation") != std::string::npos) {
131 message.append("D3D emulation layers, and applications ported from D3D, by adding functionality specific to D3D, ");
132 }
133 if (special_uses.find("devtools") != std::string::npos) {
134 message.append(" developer tools such as capture-replay libraries, ");
135 }
136 if (special_uses.find("debugging") != std::string::npos) {
137 message.append("use by applications when debugging, ");
138 }
139 if (special_uses.find("glemulation") != std::string::npos) {
140 message.append(
141 "OpenGL and/or OpenGL ES emulation layers, and applications ported from those APIs, by adding functionality "
142 "specific to those APIs, ");
143 }
144 message.append("and it is strongly recommended that they be otherwise avoided");
145
146 skip |= LogWarning(instance, vuid, "%s(): Attempting to enable extension %s, but this extension %s.", api_name,
147 extension_name, message.c_str());
148 }
149 return skip;
150}
151
Camden5b184be2019-08-13 07:50:19 -0600152bool BestPractices::PreCallValidateCreateInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500153 VkInstance* pInstance) const {
Camden5b184be2019-08-13 07:50:19 -0600154 bool skip = false;
155
156 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
157 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kDeviceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800158 skip |= LogWarning(instance, kVUID_BestPractices_CreateInstance_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700159 "vkCreateInstance(): Attempting to enable Device Extension %s at CreateInstance time.",
160 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600161 }
Mark Lobodzinski17d8dc62020-06-03 08:48:58 -0600162 uint32_t specified_version =
163 (pCreateInfo->pApplicationInfo ? pCreateInfo->pApplicationInfo->apiVersion : VK_API_VERSION_1_0);
164 skip |= ValidateDeprecatedExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i], specified_version,
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700165 kVUID_BestPractices_CreateInstance_DeprecatedExtension);
Mark Lobodzinskia431b772020-11-10 08:12:13 -0700166 skip |= ValidateSpecialUseExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i],
167 kVUID_BestPractices_CreateInstance_SpecialUseExtension);
Camden5b184be2019-08-13 07:50:19 -0600168 }
169
170 return skip;
171}
172
173void BestPractices::PreCallRecordCreateInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator,
174 VkInstance* pInstance) {
Mark Lobodzinski97484d62020-03-03 11:57:41 -0700175 ValidationStateTracker::PreCallRecordCreateInstance(pCreateInfo, pAllocator, pInstance);
Sam Walls53bf7652020-04-21 17:35:15 +0100176
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700177 if (pCreateInfo != nullptr && pCreateInfo->pApplicationInfo != nullptr) {
Sam Walls53bf7652020-04-21 17:35:15 +0100178 instance_api_version = pCreateInfo->pApplicationInfo->apiVersion;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700179 } else {
Sam Walls53bf7652020-04-21 17:35:15 +0100180 instance_api_version = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700181 }
Camden5b184be2019-08-13 07:50:19 -0600182}
183
184bool BestPractices::PreCallValidateCreateDevice(VkPhysicalDevice physicalDevice, const VkDeviceCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500185 const VkAllocationCallbacks* pAllocator, VkDevice* pDevice) const {
Camden5b184be2019-08-13 07:50:19 -0600186 bool skip = false;
187
188 // get API version of physical device passed when creating device.
189 VkPhysicalDeviceProperties physical_device_properties{};
190 DispatchGetPhysicalDeviceProperties(physicalDevice, &physical_device_properties);
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500191 auto device_api_version = physical_device_properties.apiVersion;
Camden5b184be2019-08-13 07:50:19 -0600192
193 // check api versions and warn if instance api Version is higher than version on device.
194 if (instance_api_version > device_api_version) {
Mark Lobodzinski60880782020-08-11 08:02:07 -0600195 std::string inst_api_name = StringAPIVersion(instance_api_version);
196 std::string dev_api_name = StringAPIVersion(device_api_version);
Camden5b184be2019-08-13 07:50:19 -0600197
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700198 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_API_Mismatch,
199 "vkCreateDevice(): API Version of current instance, %s is higher than API Version on device, %s",
200 inst_api_name.c_str(), dev_api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -0600201 }
202
203 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
204 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kInstanceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800205 skip |= LogWarning(instance, kVUID_BestPractices_CreateDevice_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700206 "vkCreateDevice(): Attempting to enable Instance Extension %s at CreateDevice time.",
207 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600208 }
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700209 skip |= ValidateDeprecatedExtensions("CreateDevice", pCreateInfo->ppEnabledExtensionNames[i], instance_api_version,
210 kVUID_BestPractices_CreateDevice_DeprecatedExtension);
Mark Lobodzinskia431b772020-11-10 08:12:13 -0700211 skip |= ValidateSpecialUseExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i],
212 kVUID_BestPractices_CreateDevice_SpecialUseExtension);
Camden5b184be2019-08-13 07:50:19 -0600213 }
214
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600215 const auto bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
216 if ((bp_pd_state->vkGetPhysicalDeviceFeaturesState == UNCALLED) && (pCreateInfo->pEnabledFeatures != NULL)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700217 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_PDFeaturesNotCalled,
218 "vkCreateDevice() called before getting physical device features from vkGetPhysicalDeviceFeatures().");
Camden83a9c372019-08-14 11:41:38 -0600219 }
220
Szilard Papp7d2c7952020-06-22 14:38:13 +0100221 if ((VendorCheckEnabled(kBPVendorArm)) && (pCreateInfo->pEnabledFeatures != nullptr) &&
222 (pCreateInfo->pEnabledFeatures->robustBufferAccess == VK_TRUE)) {
223 skip |= LogPerformanceWarning(
224 device, kVUID_BestPractices_CreateDevice_RobustBufferAccess,
225 "%s vkCreateDevice() called with enabled robustBufferAccess. Use robustBufferAccess as a debugging tool during "
226 "development. Enabling it causes loss in performance for accesses to uniform buffers and shader storage "
227 "buffers. Disable robustBufferAccess in release builds. Only leave it enabled if the application use-case "
228 "requires the additional level of reliability due to the use of unverified user-supplied draw parameters.",
229 VendorSpecificTag(kBPVendorArm));
230 }
231
Camden5b184be2019-08-13 07:50:19 -0600232 return skip;
233}
234
235bool BestPractices::PreCallValidateCreateBuffer(VkDevice device, const VkBufferCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500236 const VkAllocationCallbacks* pAllocator, VkBuffer* pBuffer) const {
Camden5b184be2019-08-13 07:50:19 -0600237 bool skip = false;
238
239 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700240 std::stringstream buffer_hex;
241 buffer_hex << "0x" << std::hex << HandleToUint64(pBuffer);
Camden5b184be2019-08-13 07:50:19 -0600242
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700243 skip |= LogWarning(
244 device, kVUID_BestPractices_SharingModeExclusive,
245 "Warning: Buffer (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
246 "(queueFamilyIndexCount of %" PRIu32 ").",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700247 buffer_hex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600248 }
249
250 return skip;
251}
252
253bool BestPractices::PreCallValidateCreateImage(VkDevice device, const VkImageCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500254 const VkAllocationCallbacks* pAllocator, VkImage* pImage) const {
Camden5b184be2019-08-13 07:50:19 -0600255 bool skip = false;
256
257 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700258 std::stringstream image_hex;
259 image_hex << "0x" << std::hex << HandleToUint64(pImage);
Camden5b184be2019-08-13 07:50:19 -0600260
261 skip |=
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700262 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
263 "Warning: Image (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
264 "(queueFamilyIndexCount of %" PRIu32 ").",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700265 image_hex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600266 }
267
Attilio Provenzano02859b22020-02-27 14:17:28 +0000268 if (VendorCheckEnabled(kBPVendorArm)) {
269 if (pCreateInfo->samples > kMaxEfficientSamplesArm) {
270 skip |= LogPerformanceWarning(
271 device, kVUID_BestPractices_CreateImage_TooLargeSampleCount,
272 "%s vkCreateImage(): Trying to create an image with %u samples. "
273 "The hardware revision may not have full throughput for framebuffers with more than %u samples.",
274 VendorSpecificTag(kBPVendorArm), static_cast<uint32_t>(pCreateInfo->samples), kMaxEfficientSamplesArm);
275 }
276
277 if (pCreateInfo->samples > VK_SAMPLE_COUNT_1_BIT && !(pCreateInfo->usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT)) {
278 skip |= LogPerformanceWarning(
279 device, kVUID_BestPractices_CreateImage_NonTransientMSImage,
280 "%s vkCreateImage(): Trying to create a multisampled image, but createInfo.usage did not have "
281 "VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. Multisampled images may be resolved on-chip, "
282 "and do not need to be backed by physical storage. "
283 "TRANSIENT_ATTACHMENT allows tiled GPUs to not back the multisampled image with physical memory.",
284 VendorSpecificTag(kBPVendorArm));
285 }
286 }
287
Camden5b184be2019-08-13 07:50:19 -0600288 return skip;
289}
290
291bool BestPractices::PreCallValidateCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500292 const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain) const {
Camden5b184be2019-08-13 07:50:19 -0600293 bool skip = false;
294
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600295 const auto* bp_pd_state = GetPhysicalDeviceStateBP();
296 if (bp_pd_state) {
297 if (bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState == UNCALLED) {
298 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
299 "vkCreateSwapchainKHR() called before getting surface capabilities from "
300 "vkGetPhysicalDeviceSurfaceCapabilitiesKHR().");
301 }
Camden83a9c372019-08-14 11:41:38 -0600302
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600303 if (bp_pd_state->vkGetPhysicalDeviceSurfacePresentModesKHRState != QUERY_DETAILS) {
304 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
305 "vkCreateSwapchainKHR() called before getting surface present mode(s) from "
306 "vkGetPhysicalDeviceSurfacePresentModesKHR().");
307 }
Camden83a9c372019-08-14 11:41:38 -0600308
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600309 if (bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState != QUERY_DETAILS) {
310 skip |= LogWarning(
311 device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
312 "vkCreateSwapchainKHR() called before getting surface format(s) from vkGetPhysicalDeviceSurfaceFormatsKHR().");
313 }
Camden83a9c372019-08-14 11:41:38 -0600314 }
315
Camden5b184be2019-08-13 07:50:19 -0600316 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700317 skip |=
318 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
Mark Lobodzinski019f4e32020-04-13 11:01:35 -0600319 "Warning: A Swapchain is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while "
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700320 "specifying multiple queues (queueFamilyIndexCount of %" PRIu32 ").",
321 pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600322 }
323
Szilard Papp48a6da32020-06-10 14:41:59 +0100324 if (pCreateInfo->minImageCount == 2) {
325 skip |= LogPerformanceWarning(
326 device, kVUID_BestPractices_SuboptimalSwapchainImageCount,
327 "Warning: A Swapchain is being created with minImageCount set to %" PRIu32
328 ", which means double buffering is going "
329 "to be used. Using double buffering and vsync locks rendering to an integer fraction of the vsync rate. In turn, "
330 "reducing the performance of the application if rendering is slower than vsync. Consider setting minImageCount to "
331 "3 to use triple buffering to maximize performance in such cases.",
332 pCreateInfo->minImageCount);
333 }
334
Szilard Pappd5f0f812020-06-22 09:01:29 +0100335 if (VendorCheckEnabled(kBPVendorArm) && (pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR)) {
336 skip |= LogWarning(device, kVUID_BestPractices_CreateSwapchain_PresentMode,
337 "%s Warning: Swapchain is not being created with presentation mode \"VK_PRESENT_MODE_FIFO_KHR\". "
338 "Prefer using \"VK_PRESENT_MODE_FIFO_KHR\" to avoid unnecessary CPU and GPU load and save power. "
339 "Presentation modes which are not FIFO will present the latest available frame and discard other "
340 "frame(s) if any.",
341 VendorSpecificTag(kBPVendorArm));
342 }
343
Camden5b184be2019-08-13 07:50:19 -0600344 return skip;
345}
346
347bool BestPractices::PreCallValidateCreateSharedSwapchainsKHR(VkDevice device, uint32_t swapchainCount,
348 const VkSwapchainCreateInfoKHR* pCreateInfos,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500349 const VkAllocationCallbacks* pAllocator,
350 VkSwapchainKHR* pSwapchains) const {
Camden5b184be2019-08-13 07:50:19 -0600351 bool skip = false;
352
353 for (uint32_t i = 0; i < swapchainCount; i++) {
354 if ((pCreateInfos[i].queueFamilyIndexCount > 1) && (pCreateInfos[i].imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700355 skip |= LogWarning(
356 device, kVUID_BestPractices_SharingModeExclusive,
357 "Warning: A shared swapchain (index %" PRIu32
358 ") is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple "
359 "queues (queueFamilyIndexCount of %" PRIu32 ").",
360 i, pCreateInfos[i].queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600361 }
362 }
363
364 return skip;
365}
366
367bool BestPractices::PreCallValidateCreateRenderPass(VkDevice device, const VkRenderPassCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500368 const VkAllocationCallbacks* pAllocator, VkRenderPass* pRenderPass) const {
Camden5b184be2019-08-13 07:50:19 -0600369 bool skip = false;
370
371 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; ++i) {
372 VkFormat format = pCreateInfo->pAttachments[i].format;
373 if (pCreateInfo->pAttachments[i].initialLayout == VK_IMAGE_LAYOUT_UNDEFINED) {
374 if ((FormatIsColor(format) || FormatHasDepth(format)) &&
375 pCreateInfo->pAttachments[i].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700376 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
377 "Render pass has an attachment with loadOp == VK_ATTACHMENT_LOAD_OP_LOAD and "
378 "initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
379 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
380 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600381 }
382 if (FormatHasStencil(format) && pCreateInfo->pAttachments[i].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700383 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
384 "Render pass has an attachment with stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD "
385 "and initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
386 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
387 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600388 }
389 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000390
391 const auto& attachment = pCreateInfo->pAttachments[i];
392 if (attachment.samples > VK_SAMPLE_COUNT_1_BIT) {
393 bool access_requires_memory =
394 attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD || attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE;
395
396 if (FormatHasStencil(format)) {
397 access_requires_memory |= attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
398 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE;
399 }
400
401 if (access_requires_memory) {
402 skip |= LogPerformanceWarning(
403 device, kVUID_BestPractices_CreateRenderPass_ImageRequiresMemory,
404 "Attachment %u in the VkRenderPass is a multisampled image with %u samples, but it uses loadOp/storeOp "
405 "which requires accessing data from memory. Multisampled images should always be loadOp = CLEAR or DONT_CARE, "
406 "storeOp = DONT_CARE. This allows the implementation to use lazily allocated memory effectively.",
407 i, static_cast<uint32_t>(attachment.samples));
408 }
409 }
Camden5b184be2019-08-13 07:50:19 -0600410 }
411
412 for (uint32_t dependency = 0; dependency < pCreateInfo->dependencyCount; dependency++) {
413 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].srcStageMask);
414 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].dstStageMask);
415 }
416
417 return skip;
418}
419
Tony-LunarG767180f2020-04-23 14:03:59 -0600420bool BestPractices::ValidateAttachments(const VkRenderPassCreateInfo2* rpci, uint32_t attachmentCount,
421 const VkImageView* image_views) const {
422 bool skip = false;
423
424 // Check for non-transient attachments that should be transient and vice versa
425 for (uint32_t i = 0; i < attachmentCount; ++i) {
426 auto& attachment = rpci->pAttachments[i];
427 bool attachment_should_be_transient =
428 (attachment.loadOp != VK_ATTACHMENT_LOAD_OP_LOAD && attachment.storeOp != VK_ATTACHMENT_STORE_OP_STORE);
429
430 if (FormatHasStencil(attachment.format)) {
431 attachment_should_be_transient &= (attachment.stencilLoadOp != VK_ATTACHMENT_LOAD_OP_LOAD &&
432 attachment.stencilStoreOp != VK_ATTACHMENT_STORE_OP_STORE);
433 }
434
435 auto view_state = GetImageViewState(image_views[i]);
436 if (view_state) {
437 auto& ivci = view_state->create_info;
438 auto& ici = GetImageState(ivci.image)->createInfo;
439
440 bool image_is_transient = (ici.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) != 0;
441
442 // The check for an image that should not be transient applies to all GPUs
443 if (!attachment_should_be_transient && image_is_transient) {
444 skip |= LogPerformanceWarning(
445 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldNotBeTransient,
446 "Attachment %u in VkFramebuffer uses loadOp/storeOps which need to access physical memory, "
447 "but the image backing the image view has VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
448 "Physical memory will need to be backed lazily to this image, potentially causing stalls.",
449 i);
450 }
451
452 bool supports_lazy = false;
453 for (uint32_t j = 0; j < phys_dev_mem_props.memoryTypeCount; j++) {
454 if (phys_dev_mem_props.memoryTypes[j].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
455 supports_lazy = true;
456 }
457 }
458
459 // The check for an image that should be transient only applies to GPUs supporting
460 // lazily allocated memory
461 if (supports_lazy && attachment_should_be_transient && !image_is_transient) {
462 skip |= LogPerformanceWarning(
463 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldBeTransient,
464 "Attachment %u in VkFramebuffer uses loadOp/storeOps which never have to be backed by physical memory, "
465 "but the image backing the image view does not have VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
466 "You can save physical memory by using transient attachment backed by lazily allocated memory here.",
467 i);
468 }
469 }
470 }
471 return skip;
472}
473
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000474bool BestPractices::PreCallValidateCreateFramebuffer(VkDevice device, const VkFramebufferCreateInfo* pCreateInfo,
475 const VkAllocationCallbacks* pAllocator, VkFramebuffer* pFramebuffer) const {
476 bool skip = false;
477
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000478 auto rp_state = GetRenderPassState(pCreateInfo->renderPass);
Mike Schuchardt2df08912020-12-15 16:28:09 -0800479 if (rp_state && !(pCreateInfo->flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT)) {
Tony-LunarG767180f2020-04-23 14:03:59 -0600480 skip = ValidateAttachments(rp_state->createInfo.ptr(), pCreateInfo->attachmentCount, pCreateInfo->pAttachments);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000481 }
482
483 return skip;
484}
485
Sam Wallse746d522020-03-16 21:20:23 +0000486bool BestPractices::PreCallValidateAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
487 VkDescriptorSet* pDescriptorSets, void* ads_state_data) const {
488 bool skip = false;
489 skip |= ValidationStateTracker::PreCallValidateAllocateDescriptorSets(device, pAllocateInfo, pDescriptorSets, ads_state_data);
490
491 if (!skip) {
492 const auto& pool_handle = pAllocateInfo->descriptorPool;
493 auto iter = descriptor_pool_freed_count.find(pool_handle);
494 // if the number of freed sets > 0, it implies they could be recycled instead if desirable
495 // this warning is specific to Arm
496 if (VendorCheckEnabled(kBPVendorArm) && iter != descriptor_pool_freed_count.end() && iter->second > 0) {
497 skip |= LogPerformanceWarning(
498 device, kVUID_BestPractices_AllocateDescriptorSets_SuboptimalReuse,
499 "%s Descriptor set memory was allocated via vkAllocateDescriptorSets() for sets which were previously freed in the "
500 "same logical device. On some drivers or architectures it may be most optimal to re-use existing descriptor sets.",
501 VendorSpecificTag(kBPVendorArm));
502 }
503 }
504
505 return skip;
506}
507
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600508void BestPractices::ManualPostCallRecordAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
509 VkDescriptorSet* pDescriptorSets, VkResult result, void* ads_state) {
Sam Wallse746d522020-03-16 21:20:23 +0000510 if (result == VK_SUCCESS) {
511 // find the free count for the pool we allocated into
512 auto iter = descriptor_pool_freed_count.find(pAllocateInfo->descriptorPool);
513 if (iter != descriptor_pool_freed_count.end()) {
514 // we record successful allocations by subtracting the allocation count from the last recorded free count
515 const auto alloc_count = pAllocateInfo->descriptorSetCount;
516 // clamp the unsigned subtraction to the range [0, last_free_count]
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700517 if (iter->second > alloc_count) {
Sam Wallse746d522020-03-16 21:20:23 +0000518 iter->second -= alloc_count;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700519 } else {
Sam Wallse746d522020-03-16 21:20:23 +0000520 iter->second = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700521 }
Sam Wallse746d522020-03-16 21:20:23 +0000522 }
523 }
524}
525
526void BestPractices::PostCallRecordFreeDescriptorSets(VkDevice device, VkDescriptorPool descriptorPool, uint32_t descriptorSetCount,
527 const VkDescriptorSet* pDescriptorSets, VkResult result) {
528 ValidationStateTracker::PostCallRecordFreeDescriptorSets(device, descriptorPool, descriptorSetCount, pDescriptorSets, result);
529 if (result == VK_SUCCESS) {
530 // we want to track frees because we're interested in suggesting re-use
531 auto iter = descriptor_pool_freed_count.find(descriptorPool);
532 if (iter == descriptor_pool_freed_count.end()) {
533 descriptor_pool_freed_count.insert(std::make_pair(descriptorPool, descriptorSetCount));
534 } else {
535 iter->second += descriptorSetCount;
536 }
537 }
538}
539
Camden5b184be2019-08-13 07:50:19 -0600540bool BestPractices::PreCallValidateAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500541 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory) const {
Camden5b184be2019-08-13 07:50:19 -0600542 bool skip = false;
543
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500544 if (num_mem_objects + 1 > kMemoryObjectWarningLimit) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700545 skip |= LogPerformanceWarning(device, kVUID_BestPractices_AllocateMemory_TooManyObjects,
546 "Performance Warning: This app has > %" PRIu32 " memory objects.", kMemoryObjectWarningLimit);
Camden5b184be2019-08-13 07:50:19 -0600547 }
548
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000549 if (pAllocateInfo->allocationSize < kMinDeviceAllocationSize) {
550 skip |= LogPerformanceWarning(
551 device, kVUID_BestPractices_AllocateMemory_SmallAllocation,
552 "vkAllocateMemory(): Allocating a VkDeviceMemory of size %llu. This is a very small allocation (current "
553 "threshold is %llu bytes). "
554 "You should make large allocations and sub-allocate from one large VkDeviceMemory.",
555 pAllocateInfo->allocationSize, kMinDeviceAllocationSize);
556 }
557
Camden83a9c372019-08-14 11:41:38 -0600558 // TODO: Insert get check for GetPhysicalDeviceMemoryProperties once the state is tracked in the StateTracker
559
560 return skip;
561}
562
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600563void BestPractices::ManualPostCallRecordAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
564 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory,
565 VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700566 if (result != VK_SUCCESS) {
567 static std::vector<VkResult> error_codes = {VK_ERROR_OUT_OF_HOST_MEMORY, VK_ERROR_OUT_OF_DEVICE_MEMORY,
568 VK_ERROR_TOO_MANY_OBJECTS, VK_ERROR_INVALID_EXTERNAL_HANDLE,
Mike Schuchardt2df08912020-12-15 16:28:09 -0800569 VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS};
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700570 static std::vector<VkResult> success_codes = {};
571 ValidateReturnCodes("vkReleaseFullScreenExclusiveModeEXT", result, error_codes, success_codes);
572 return;
573 }
574 num_mem_objects++;
575}
Camden Stocker9738af92019-10-16 13:54:03 -0700576
Mark Lobodzinskide15e582020-04-29 08:06:00 -0600577void BestPractices::ValidateReturnCodes(const char* api_name, VkResult result, const std::vector<VkResult>& error_codes,
578 const std::vector<VkResult>& success_codes) const {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700579 auto error = std::find(error_codes.begin(), error_codes.end(), result);
580 if (error != error_codes.end()) {
Mark Lobodzinski629defa2020-04-29 12:00:23 -0600581 LogWarning(instance, kVUID_BestPractices_Error_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700582 return;
583 }
584 auto success = std::find(success_codes.begin(), success_codes.end(), result);
585 if (success != success_codes.end()) {
Mark Lobodzinskie7215152020-05-11 08:21:23 -0600586 LogInfo(instance, kVUID_BestPractices_NonSuccess_Result, "%s(): Returned non-success return code %s.", api_name,
587 string_VkResult(result));
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500588 }
589}
590
Jeff Bolz5c801d12019-10-09 10:38:45 -0500591bool BestPractices::PreCallValidateFreeMemory(VkDevice device, VkDeviceMemory memory,
592 const VkAllocationCallbacks* pAllocator) const {
Mark Lobodzinski91e50bf2020-01-14 09:55:11 -0700593 if (memory == VK_NULL_HANDLE) return false;
Camden83a9c372019-08-14 11:41:38 -0600594 bool skip = false;
595
Camden Stocker9738af92019-10-16 13:54:03 -0700596 const DEVICE_MEMORY_STATE* mem_info = ValidationStateTracker::GetDevMemState(memory);
Camden83a9c372019-08-14 11:41:38 -0600597
598 for (auto& obj : mem_info->obj_bindings) {
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600599 LogObjectList objlist(device);
600 objlist.add(obj);
601 objlist.add(mem_info->mem);
602 skip |= LogWarning(objlist, layer_name.c_str(), "VK Object %s still has a reference to mem obj %s.",
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700603 report_data->FormatHandle(obj).c_str(), report_data->FormatHandle(mem_info->mem).c_str());
Camden83a9c372019-08-14 11:41:38 -0600604 }
605
Camden5b184be2019-08-13 07:50:19 -0600606 return skip;
607}
608
609void BestPractices::PreCallRecordFreeMemory(VkDevice device, VkDeviceMemory memory, const VkAllocationCallbacks* pAllocator) {
Mark Lobodzinski97484d62020-03-03 11:57:41 -0700610 ValidationStateTracker::PreCallRecordFreeMemory(device, memory, pAllocator);
Camden5b184be2019-08-13 07:50:19 -0600611 if (memory != VK_NULL_HANDLE) {
612 num_mem_objects--;
613 }
614}
615
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000616bool BestPractices::ValidateBindBufferMemory(VkBuffer buffer, VkDeviceMemory memory, const char* api_name) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600617 bool skip = false;
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500618 const BUFFER_STATE* buffer_state = GetBufferState(buffer);
Camden Stockerb603cc82019-09-03 10:09:02 -0600619
sfricke-samsunge2441192019-11-06 14:07:57 -0800620 if (!buffer_state->memory_requirements_checked && !buffer_state->external_memory_handle) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700621 skip |= LogWarning(device, kVUID_BestPractices_BufferMemReqNotCalled,
622 "%s: Binding memory to %s but vkGetBufferMemoryRequirements() has not been called on that buffer.",
623 api_name, report_data->FormatHandle(buffer).c_str());
Camden Stockerb603cc82019-09-03 10:09:02 -0600624 }
625
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000626 const DEVICE_MEMORY_STATE* mem_state = GetDevMemState(memory);
627
628 if (mem_state->alloc_info.allocationSize == buffer_state->createInfo.size &&
629 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
630 skip |= LogPerformanceWarning(
631 device, kVUID_BestPractices_SmallDedicatedAllocation,
632 "%s: Trying to bind %s to a memory block which is fully consumed by the buffer. "
633 "The required size of the allocation is %llu, but smaller buffers like this should be sub-allocated from "
634 "larger memory blocks. (Current threshold is %llu bytes.)",
635 api_name, report_data->FormatHandle(buffer).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
636 }
637
Camden Stockerb603cc82019-09-03 10:09:02 -0600638 return skip;
639}
640
641bool BestPractices::PreCallValidateBindBufferMemory(VkDevice device, VkBuffer buffer, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500642 VkDeviceSize memoryOffset) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600643 bool skip = false;
644 const char* api_name = "BindBufferMemory()";
645
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000646 skip |= ValidateBindBufferMemory(buffer, memory, api_name);
Camden Stockerb603cc82019-09-03 10:09:02 -0600647
648 return skip;
649}
650
651bool BestPractices::PreCallValidateBindBufferMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500652 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600653 char api_name[64];
654 bool skip = false;
655
656 for (uint32_t i = 0; i < bindInfoCount; i++) {
657 sprintf(api_name, "vkBindBufferMemory2() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000658 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600659 }
660
661 return skip;
662}
Camden Stockerb603cc82019-09-03 10:09:02 -0600663
664bool BestPractices::PreCallValidateBindBufferMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500665 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600666 char api_name[64];
667 bool skip = false;
Camden Stockerb603cc82019-09-03 10:09:02 -0600668
Camden Stocker8b798ab2019-09-03 10:33:28 -0600669 for (uint32_t i = 0; i < bindInfoCount; i++) {
670 sprintf(api_name, "vkBindBufferMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000671 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600672 }
673
674 return skip;
675}
676
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000677bool BestPractices::ValidateBindImageMemory(VkImage image, VkDeviceMemory memory, const char* api_name) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600678 bool skip = false;
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500679 const IMAGE_STATE* image_state = GetImageState(image);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600680
sfricke-samsung71bc6572020-04-29 15:49:43 -0700681 if (image_state->disjoint == false) {
sfricke-samsungd7ea5de2020-04-08 09:19:18 -0700682 if (!image_state->memory_requirements_checked && !image_state->external_memory_handle) {
683 skip |= LogWarning(device, kVUID_BestPractices_ImageMemReqNotCalled,
684 "%s: Binding memory to %s but vkGetImageMemoryRequirements() has not been called on that image.",
685 api_name, report_data->FormatHandle(image).c_str());
686 }
687 } else {
688 // TODO If binding disjoint image then this needs to check that VkImagePlaneMemoryRequirementsInfo was called for each
689 // plane.
Camden Stocker8b798ab2019-09-03 10:33:28 -0600690 }
691
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000692 const DEVICE_MEMORY_STATE* mem_state = GetDevMemState(memory);
693
694 if (mem_state->alloc_info.allocationSize == image_state->requirements.size &&
695 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
696 skip |= LogPerformanceWarning(
697 device, kVUID_BestPractices_SmallDedicatedAllocation,
698 "%s: Trying to bind %s to a memory block which is fully consumed by the image. "
699 "The required size of the allocation is %llu, but smaller images like this should be sub-allocated from "
700 "larger memory blocks. (Current threshold is %llu bytes.)",
701 api_name, report_data->FormatHandle(image).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
702 }
703
704 // If we're binding memory to a image which was created as TRANSIENT and the image supports LAZY allocation,
705 // make sure this type is actually used.
706 // This warning will only trigger if this layer is run on a platform that supports LAZILY_ALLOCATED_BIT
707 // (i.e.most tile - based renderers)
708 if (image_state->createInfo.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) {
709 bool supports_lazy = false;
710 uint32_t suggested_type = 0;
711
712 for (uint32_t i = 0; i < phys_dev_mem_props.memoryTypeCount; i++) {
713 if ((1u << i) & image_state->requirements.memoryTypeBits) {
714 if (phys_dev_mem_props.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
715 supports_lazy = true;
716 suggested_type = i;
717 break;
718 }
719 }
720 }
721
722 uint32_t allocated_properties = phys_dev_mem_props.memoryTypes[mem_state->alloc_info.memoryTypeIndex].propertyFlags;
723
724 if (supports_lazy && (allocated_properties & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) == 0) {
725 skip |= LogPerformanceWarning(
726 device, kVUID_BestPractices_NonLazyTransientImage,
727 "%s: Attempting to bind memory type % u to VkImage which was created with TRANSIENT_ATTACHMENT_BIT,"
728 "but this memory type is not LAZILY_ALLOCATED_BIT. You should use memory type %u here instead to save "
729 "%llu bytes of physical memory.",
730 api_name, mem_state->alloc_info.memoryTypeIndex, suggested_type, image_state->requirements.size);
731 }
732 }
733
Camden Stocker8b798ab2019-09-03 10:33:28 -0600734 return skip;
735}
736
737bool BestPractices::PreCallValidateBindImageMemory(VkDevice device, VkImage image, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500738 VkDeviceSize memoryOffset) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600739 bool skip = false;
740 const char* api_name = "vkBindImageMemory()";
741
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000742 skip |= ValidateBindImageMemory(image, memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600743
744 return skip;
745}
746
747bool BestPractices::PreCallValidateBindImageMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500748 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600749 char api_name[64];
750 bool skip = false;
751
752 for (uint32_t i = 0; i < bindInfoCount; i++) {
753 sprintf(api_name, "vkBindImageMemory2() pBindInfos[%u]", i);
Mark Lobodzinski1f887d32020-12-30 15:31:33 -0700754 if (!LvlFindInChain<VkBindImageMemorySwapchainInfoKHR>(pBindInfos[i].pNext)) {
Tony-LunarG5e60b852020-04-27 11:27:54 -0600755 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
756 }
Camden Stocker8b798ab2019-09-03 10:33:28 -0600757 }
758
759 return skip;
760}
761
762bool BestPractices::PreCallValidateBindImageMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500763 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600764 char api_name[64];
765 bool skip = false;
766
767 for (uint32_t i = 0; i < bindInfoCount; i++) {
768 sprintf(api_name, "vkBindImageMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000769 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600770 }
771
772 return skip;
773}
Camden83a9c372019-08-14 11:41:38 -0600774
Attilio Provenzano02859b22020-02-27 14:17:28 +0000775static inline bool FormatHasFullThroughputBlendingArm(VkFormat format) {
776 switch (format) {
777 case VK_FORMAT_B10G11R11_UFLOAT_PACK32:
778 case VK_FORMAT_R16_SFLOAT:
779 case VK_FORMAT_R16G16_SFLOAT:
780 case VK_FORMAT_R16G16B16_SFLOAT:
781 case VK_FORMAT_R16G16B16A16_SFLOAT:
782 case VK_FORMAT_R32_SFLOAT:
783 case VK_FORMAT_R32G32_SFLOAT:
784 case VK_FORMAT_R32G32B32_SFLOAT:
785 case VK_FORMAT_R32G32B32A32_SFLOAT:
786 return false;
787
788 default:
789 return true;
790 }
791}
792
793bool BestPractices::ValidateMultisampledBlendingArm(uint32_t createInfoCount,
794 const VkGraphicsPipelineCreateInfo* pCreateInfos) const {
795 bool skip = false;
796
797 for (uint32_t i = 0; i < createInfoCount; i++) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700798 auto create_info = &pCreateInfos[i];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000799
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700800 if (!create_info->pColorBlendState || !create_info->pMultisampleState ||
801 create_info->pMultisampleState->rasterizationSamples == VK_SAMPLE_COUNT_1_BIT ||
802 create_info->pMultisampleState->sampleShadingEnable) {
Attilio Provenzano02859b22020-02-27 14:17:28 +0000803 return skip;
804 }
805
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700806 auto rp_state = GetRenderPassState(create_info->renderPass);
807 auto& subpass = rp_state->createInfo.pSubpasses[create_info->subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000808
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700809 for (uint32_t j = 0; j < create_info->pColorBlendState->attachmentCount; j++) {
810 auto& blend_att = create_info->pColorBlendState->pAttachments[j];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000811 uint32_t att = subpass.pColorAttachments[j].attachment;
812
813 if (att != VK_ATTACHMENT_UNUSED && blend_att.blendEnable && blend_att.colorWriteMask) {
814 if (!FormatHasFullThroughputBlendingArm(rp_state->createInfo.pAttachments[att].format)) {
815 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultisampledBlending,
816 "%s vkCreateGraphicsPipelines() - createInfo #%u: Pipeline is multisampled and "
817 "color attachment #%u makes use "
818 "of a format which cannot be blended at full throughput when using MSAA.",
819 VendorSpecificTag(kBPVendorArm), i, j);
820 }
821 }
822 }
823 }
824
825 return skip;
826}
827
Camden5b184be2019-08-13 07:50:19 -0600828bool BestPractices::PreCallValidateCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
829 const VkGraphicsPipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -0600830 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500831 void* cgpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -0600832 bool skip = StateTracker::PreCallValidateCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos,
833 pAllocator, pPipelines, cgpl_state_data);
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600834 create_graphics_pipeline_api_state* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
Camden5b184be2019-08-13 07:50:19 -0600835
836 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700837 skip |= LogPerformanceWarning(
838 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
839 "Performance Warning: This vkCreateGraphicsPipelines call is creating multiple pipelines but is not using a "
840 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -0600841 }
842
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000843 for (uint32_t i = 0; i < createInfoCount; i++) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700844 auto& create_info = pCreateInfos[i];
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000845
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600846 if (!(cgpl_state->pipe_state[i]->active_shaders & VK_SHADER_STAGE_MESH_BIT_NV)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700847 auto& vertex_input = *create_info.pVertexInputState;
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600848 uint32_t count = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700849 for (uint32_t j = 0; j < vertex_input.vertexBindingDescriptionCount; j++) {
850 if (vertex_input.pVertexBindingDescriptions[j].inputRate == VK_VERTEX_INPUT_RATE_INSTANCE) {
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600851 count++;
852 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000853 }
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600854 if (count > kMaxInstancedVertexBuffers) {
855 skip |= LogPerformanceWarning(
856 device, kVUID_BestPractices_CreatePipelines_TooManyInstancedVertexBuffers,
857 "The pipeline is using %u instanced vertex buffers (current limit: %u), but this can be inefficient on the "
858 "GPU. If using instanced vertex attributes prefer interleaving them in a single buffer.",
859 count, kMaxInstancedVertexBuffers);
860 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000861 }
Attilio Provenzano02859b22020-02-27 14:17:28 +0000862
Szilard Pappaaf2da32020-06-22 10:37:35 +0100863 if ((pCreateInfos[i].pRasterizationState->depthBiasEnable) &&
864 (pCreateInfos[i].pRasterizationState->depthBiasConstantFactor == 0.0f) &&
865 (pCreateInfos[i].pRasterizationState->depthBiasSlopeFactor == 0.0f)) {
866 skip |= VendorCheckEnabled(kBPVendorArm) &&
867 LogPerformanceWarning(
868 device, kVUID_BestPractices_CreatePipelines_DepthBias_Zero,
869 "%s Performance Warning: This vkCreateGraphicsPipelines call is created with depthBiasEnable set to true "
870 "and both depthBiasConstantFactor and depthBiasSlopeFactor are set to 0. This can cause reduced "
871 "efficiency during rasterization. Consider disabling depthBias or increasing either "
872 "depthBiasConstantFactor or depthBiasSlopeFactor.",
873 VendorSpecificTag(kBPVendorArm));
874 }
875
Attilio Provenzano02859b22020-02-27 14:17:28 +0000876 skip |= VendorCheckEnabled(kBPVendorArm) && ValidateMultisampledBlendingArm(createInfoCount, pCreateInfos);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000877 }
878
Camden5b184be2019-08-13 07:50:19 -0600879 return skip;
880}
881
Sam Walls0961ec02020-03-31 16:39:15 +0100882void BestPractices::ManualPostCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t count,
883 const VkGraphicsPipelineCreateInfo* pCreateInfos,
884 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
885 VkResult result, void* cgpl_state_data) {
886 for (size_t i = 0; i < count; i++) {
887 const auto* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
888 const VkPipeline pipeline_handle = pPipelines[i];
889
890 // record depth stencil state and color blend states for depth pre-pass tracking purposes
891 auto gp_cis = graphicsPipelineCIs.find(pipeline_handle);
892
893 // add the tracking state if it doesn't exist
894 if (gp_cis == graphicsPipelineCIs.end()) {
895 auto result = graphicsPipelineCIs.emplace(std::make_pair(pipeline_handle, GraphicsPipelineCIs{}));
896
897 if (!result.second) continue;
898
899 gp_cis = result.first;
900 }
901
Tony-LunarG412b1b72020-07-15 10:30:13 -0600902 gp_cis->second.colorBlendStateCI =
903 cgpl_state->pCreateInfos[i].pColorBlendState
904 ? new safe_VkPipelineColorBlendStateCreateInfo(cgpl_state->pCreateInfos[i].pColorBlendState)
905 : nullptr;
906 gp_cis->second.depthStencilStateCI =
907 cgpl_state->pCreateInfos[i].pDepthStencilState
908 ? new safe_VkPipelineDepthStencilStateCreateInfo(cgpl_state->pCreateInfos[i].pDepthStencilState)
909 : nullptr;
Sam Walls0961ec02020-03-31 16:39:15 +0100910 }
911}
912
Camden5b184be2019-08-13 07:50:19 -0600913bool BestPractices::PreCallValidateCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
914 const VkComputePipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -0600915 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500916 void* ccpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -0600917 bool skip = StateTracker::PreCallValidateCreateComputePipelines(device, pipelineCache, createInfoCount, pCreateInfos,
918 pAllocator, pPipelines, ccpl_state_data);
Camden5b184be2019-08-13 07:50:19 -0600919
920 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700921 skip |= LogPerformanceWarning(
922 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
923 "Performance Warning: This vkCreateComputePipelines call is creating multiple pipelines but is not using a "
924 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -0600925 }
926
Sam Wallsd7ab6db2020-06-19 20:41:54 +0100927 if (VendorCheckEnabled(kBPVendorArm)) {
928 for (size_t i = 0; i < createInfoCount; i++) {
929 skip |= ValidateCreateComputePipelineArm(pCreateInfos[i]);
930 }
931 }
932
933 return skip;
934}
935
936bool BestPractices::ValidateCreateComputePipelineArm(const VkComputePipelineCreateInfo& createInfo) const {
937 bool skip = false;
938 auto* module = GetShaderModuleState(createInfo.stage.module);
939
940 uint32_t x = 1, y = 1, z = 1;
941 FindLocalSize(module, x, y, z);
942
943 uint32_t thread_count = x * y * z;
944
945 // Generate a priori warnings about work group sizes.
946 if (thread_count > kMaxEfficientWorkGroupThreadCountArm) {
947 skip |= LogPerformanceWarning(
948 device, kVUID_BestPractices_CreateComputePipelines_ComputeWorkGroupSize,
949 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, %u, "
950 "%u) (%u threads total), has more threads than advised in a single work group. It is advised to use work "
951 "groups with less than %u threads, especially when using barrier() or shared memory.",
952 VendorSpecificTag(kBPVendorArm), x, y, z, thread_count, kMaxEfficientWorkGroupThreadCountArm);
953 }
954
955 if (thread_count == 1 || ((x > 1) && (x & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
956 ((y > 1) && (y & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
957 ((z > 1) && (z & (kThreadGroupDispatchCountAlignmentArm - 1)))) {
958 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeThreadGroupAlignment,
959 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, "
960 "%u, %u) is not aligned to %u "
961 "threads. On Arm Mali architectures, not aligning work group sizes to %u may "
962 "leave threads idle on the shader "
963 "core.",
964 VendorSpecificTag(kBPVendorArm), x, y, z, kThreadGroupDispatchCountAlignmentArm,
965 kThreadGroupDispatchCountAlignmentArm);
966 }
967
968 // Generate warnings about work group sizes based on active resources.
969 auto entrypoint = FindEntrypoint(module, createInfo.stage.pName, createInfo.stage.stage);
970 if (entrypoint == module->end()) return false;
971
972 bool has_writeable_descriptors = false;
locke-lunarg63e4daf2020-08-17 17:53:25 -0600973 bool has_atomic_descriptors = false;
Sam Wallsd7ab6db2020-06-19 20:41:54 +0100974 auto accessible_ids = MarkAccessibleIds(module, entrypoint);
locke-lunarg63e4daf2020-08-17 17:53:25 -0600975 auto descriptor_uses =
976 CollectInterfaceByDescriptorSlot(module, accessible_ids, &has_writeable_descriptors, &has_atomic_descriptors);
Sam Wallsd7ab6db2020-06-19 20:41:54 +0100977
978 unsigned dimensions = 0;
979 if (x > 1) dimensions++;
980 if (y > 1) dimensions++;
981 if (z > 1) dimensions++;
982 // Here the dimension will really depend on the dispatch grid, but assume it's 1D.
983 dimensions = std::max(dimensions, 1u);
984
985 // If we're accessing images, we almost certainly want to have a 2D workgroup for cache reasons.
986 // There are some false positives here. We could simply have a shader that does this within a 1D grid,
987 // or we may have a linearly tiled image, but these cases are quite unlikely in practice.
988 bool accesses_2d = false;
989 for (const auto& usage : descriptor_uses) {
990 auto dim = GetShaderResourceDimensionality(module, usage.second);
991 if (dim < 0) continue;
992 auto spvdim = spv::Dim(dim);
993 if (spvdim != spv::Dim1D && spvdim != spv::DimBuffer) accesses_2d = true;
994 }
995
996 if (accesses_2d && dimensions < 2) {
997 LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeSpatialLocality,
998 "%s vkCreateComputePipelines(): compute shader has work group dimensions (%u, %u, %u), which "
999 "suggests a 1D dispatch, but the shader is accessing 2D or 3D images. The shader may be "
1000 "exhibiting poor spatial locality with respect to one or more shader resources.",
1001 VendorSpecificTag(kBPVendorArm), x, y, z);
1002 }
1003
Camden5b184be2019-08-13 07:50:19 -06001004 return skip;
1005}
1006
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001007bool BestPractices::CheckPipelineStageFlags(std::string api_name, const VkPipelineStageFlags flags) const {
Camden5b184be2019-08-13 07:50:19 -06001008 bool skip = false;
1009
1010 if (flags & VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001011 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1012 "You are using VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001013 } else if (flags & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001014 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1015 "You are using VK_PIPELINE_STAGE_ALL_COMMANDS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001016 }
1017
1018 return skip;
1019}
1020
Mark Lobodzinski84101d72020-04-24 09:43:48 -06001021void BestPractices::ManualPostCallRecordQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo, VkResult result) {
Mark Lobodzinski9b133c12020-03-10 10:42:56 -06001022 for (uint32_t i = 0; i < pPresentInfo->swapchainCount; ++i) {
1023 auto swapchains_result = pPresentInfo->pResults ? pPresentInfo->pResults[i] : result;
1024 if (swapchains_result == VK_SUBOPTIMAL_KHR) {
1025 LogPerformanceWarning(
1026 pPresentInfo->pSwapchains[i], kVUID_BestPractices_SuboptimalSwapchain,
1027 "vkQueuePresentKHR: %s :VK_SUBOPTIMAL_KHR was returned. VK_SUBOPTIMAL_KHR - Presentation will still succeed, "
1028 "subject to the window resize behavior, but the swapchain is no longer configured optimally for the surface it "
1029 "targets. Applications should query updated surface information and recreate their swapchain at the next "
1030 "convenient opportunity.",
1031 report_data->FormatHandle(pPresentInfo->pSwapchains[i]).c_str());
1032 }
1033 }
1034}
1035
Jeff Bolz5c801d12019-10-09 10:38:45 -05001036bool BestPractices::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
1037 VkFence fence) const {
Camden5b184be2019-08-13 07:50:19 -06001038 bool skip = false;
1039
1040 for (uint32_t submit = 0; submit < submitCount; submit++) {
1041 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreCount; semaphore++) {
1042 skip |= CheckPipelineStageFlags("vkQueueSubmit", pSubmits[submit].pWaitDstStageMask[semaphore]);
1043 }
1044 }
1045
1046 return skip;
1047}
1048
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001049bool BestPractices::PreCallValidateCreateCommandPool(VkDevice device, const VkCommandPoolCreateInfo* pCreateInfo,
1050 const VkAllocationCallbacks* pAllocator, VkCommandPool* pCommandPool) const {
1051 bool skip = false;
1052
1053 if (pCreateInfo->flags & VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT) {
1054 skip |= LogPerformanceWarning(
1055 device, kVUID_BestPractices_CreateCommandPool_CommandBufferReset,
1056 "vkCreateCommandPool(): VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT is set. Consider resetting entire "
1057 "pool instead.");
1058 }
1059
1060 return skip;
1061}
1062
1063bool BestPractices::PreCallValidateBeginCommandBuffer(VkCommandBuffer commandBuffer,
1064 const VkCommandBufferBeginInfo* pBeginInfo) const {
1065 bool skip = false;
1066
1067 if (pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT) {
1068 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_SimultaneousUse,
1069 "vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT is set.");
1070 }
1071
Attilio Provenzano02859b22020-02-27 14:17:28 +00001072 if (!(pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT)) {
1073 skip |= VendorCheckEnabled(kBPVendorArm) &&
1074 LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_OneTimeSubmit,
1075 "%s vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT is not set. "
1076 "For best performance on Mali GPUs, consider setting ONE_TIME_SUBMIT by default.",
1077 VendorSpecificTag(kBPVendorArm));
1078 }
1079
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001080 return skip;
1081}
1082
Jeff Bolz5c801d12019-10-09 10:38:45 -05001083bool BestPractices::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001084 bool skip = false;
1085
1086 skip |= CheckPipelineStageFlags("vkCmdSetEvent", stageMask);
1087
1088 return skip;
1089}
1090
Jeff Bolz5c801d12019-10-09 10:38:45 -05001091bool BestPractices::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
1092 VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001093 bool skip = false;
1094
1095 skip |= CheckPipelineStageFlags("vkCmdResetEvent", stageMask);
1096
1097 return skip;
1098}
1099
1100bool BestPractices::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1101 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
1102 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1103 uint32_t bufferMemoryBarrierCount,
1104 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1105 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001106 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001107 bool skip = false;
1108
1109 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", srcStageMask);
1110 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", dstStageMask);
1111
1112 return skip;
1113}
1114
1115bool BestPractices::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
1116 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
1117 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1118 uint32_t bufferMemoryBarrierCount,
1119 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1120 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001121 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001122 bool skip = false;
1123
1124 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", srcStageMask);
1125 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", dstStageMask);
1126
1127 return skip;
1128}
1129
1130bool BestPractices::PreCallValidateCmdWriteTimestamp(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001131 VkQueryPool queryPool, uint32_t query) const {
Camden5b184be2019-08-13 07:50:19 -06001132 bool skip = false;
1133
1134 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp", pipelineStage);
1135
1136 return skip;
1137}
1138
Sam Walls0961ec02020-03-31 16:39:15 +01001139void BestPractices::PostCallRecordCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
1140 VkPipeline pipeline) {
1141 StateTracker::PostCallRecordCmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
1142
1143 if (pipelineBindPoint == VK_PIPELINE_BIND_POINT_GRAPHICS) {
1144 // check for depth/blend state tracking
1145 auto gp_cis = graphicsPipelineCIs.find(pipeline);
1146 if (gp_cis != graphicsPipelineCIs.end()) {
1147 auto prepass_state = cbDepthPrePassStates.find(commandBuffer);
1148 if (prepass_state == cbDepthPrePassStates.end()) {
1149 auto result = cbDepthPrePassStates.emplace(std::make_pair(commandBuffer, DepthPrePassState{}));
1150
1151 if (!result.second) return;
1152
1153 prepass_state = result.first;
1154 }
1155
1156 const auto* blend_state = gp_cis->second.colorBlendStateCI;
1157 const auto* stencil_state = gp_cis->second.depthStencilStateCI;
1158
1159 if (blend_state) {
1160 // assume the pipeline is depth-only unless any of the attachments have color writes enabled
1161 prepass_state->second.depthOnly = true;
1162 for (size_t i = 0; i < blend_state->attachmentCount; i++) {
1163 if (blend_state->pAttachments[i].colorWriteMask != 0) {
1164 prepass_state->second.depthOnly = false;
1165 }
1166 }
1167 }
1168
1169 // check for depth value usage
1170 prepass_state->second.depthEqualComparison = false;
1171
1172 if (stencil_state && stencil_state->depthTestEnable) {
1173 switch (stencil_state->depthCompareOp) {
1174 case VK_COMPARE_OP_EQUAL:
1175 case VK_COMPARE_OP_GREATER_OR_EQUAL:
1176 case VK_COMPARE_OP_LESS_OR_EQUAL:
1177 prepass_state->second.depthEqualComparison = true;
1178 break;
1179 default:
1180 break;
1181 }
1182 }
1183 } else {
1184 // reset depth pre-pass tracking
1185 cbDepthPrePassStates.emplace(std::make_pair(commandBuffer, DepthPrePassState{}));
1186 }
1187 }
1188}
1189
Attilio Provenzano02859b22020-02-27 14:17:28 +00001190static inline bool RenderPassUsesAttachmentOnTile(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1191 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001192 auto& subpass_info = createInfo.pSubpasses[subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001193
1194 // If an attachment is ever used as a color attachment,
1195 // resolve attachment or depth stencil attachment,
1196 // it needs to exist on tile at some point.
1197
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001198 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1199 if (subpass_info.pColorAttachments[i].attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001200 }
1201
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001202 if (subpass_info.pResolveAttachments) {
1203 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1204 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
1205 }
1206 }
1207
1208 if (subpass_info.pDepthStencilAttachment && subpass_info.pDepthStencilAttachment->attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001209 }
1210
1211 return false;
1212}
1213
1214bool BestPractices::ValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1215 const VkRenderPassBeginInfo* pRenderPassBegin) const {
1216 bool skip = false;
1217
1218 if (!pRenderPassBegin) {
1219 return skip;
1220 }
1221
1222 auto rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
1223 if (rp_state) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08001224 if (rp_state->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07001225 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
Tony-LunarG767180f2020-04-23 14:03:59 -06001226 if (rpabi) {
1227 skip = ValidateAttachments(rp_state->createInfo.ptr(), rpabi->attachmentCount, rpabi->pAttachments);
1228 }
1229 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001230 // Check if any attachments have LOAD operation on them
1231 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
1232 auto& attachment = rp_state->createInfo.pAttachments[att];
1233
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001234 bool attachment_has_readback = false;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001235 if (!FormatHasStencil(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001236 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001237 }
1238
1239 if (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001240 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001241 }
1242
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001243 bool attachment_needs_readback = false;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001244
1245 // Check if the attachment is actually used in any subpass on-tile
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001246 if (attachment_has_readback && RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1247 attachment_needs_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001248 }
1249
1250 // Using LOAD_OP_LOAD is expensive on tiled GPUs, so flag it as a potential improvement
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001251 if (attachment_needs_readback) {
Attilio Provenzano02859b22020-02-27 14:17:28 +00001252 skip |= VendorCheckEnabled(kBPVendorArm) &&
1253 LogPerformanceWarning(
1254 device, kVUID_BestPractices_BeginRenderPass_AttachmentNeedsReadback,
1255 "%s Attachment #%u in render pass has begun with VK_ATTACHMENT_LOAD_OP_LOAD.\n"
1256 "Submitting this renderpass will cause the driver to inject a readback of the attachment "
1257 "which will copy in total %u pixels (renderArea = { %d, %d, %u, %u }) to the tile buffer.",
1258 VendorSpecificTag(kBPVendorArm), att,
1259 pRenderPassBegin->renderArea.extent.width * pRenderPassBegin->renderArea.extent.height,
1260 pRenderPassBegin->renderArea.offset.x, pRenderPassBegin->renderArea.offset.y,
1261 pRenderPassBegin->renderArea.extent.width, pRenderPassBegin->renderArea.extent.height);
1262 }
1263 }
1264 }
1265
1266 return skip;
1267}
1268
1269bool BestPractices::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1270 VkSubpassContents contents) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001271 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1272 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001273 return skip;
1274}
1275
1276bool BestPractices::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1277 const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08001278 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001279 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1280 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001281 return skip;
1282}
1283
1284bool BestPractices::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08001285 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001286 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1287 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001288 return skip;
1289}
1290
Sam Walls0961ec02020-03-31 16:39:15 +01001291void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1292 const VkRenderPassBeginInfo* pRenderPassBegin) {
1293 auto prepass_state = cbDepthPrePassStates.find(commandBuffer);
1294
1295 // add the tracking state if it doesn't exist
1296 if (prepass_state == cbDepthPrePassStates.end()) {
1297 auto result = cbDepthPrePassStates.emplace(std::make_pair(commandBuffer, DepthPrePassState{}));
1298
1299 if (!result.second) return;
1300
1301 prepass_state = result.first;
1302 }
1303
1304 // reset the renderpass state
1305 prepass_state->second = {};
1306
1307 const auto* cb_state = GetCBState(commandBuffer);
locke-lunargaecf2152020-05-12 17:15:41 -06001308 const auto* rp_state = cb_state->activeRenderPass.get();
Sam Walls0961ec02020-03-31 16:39:15 +01001309
1310 // track depth / color attachment usage within the renderpass
1311 for (size_t i = 0; i < rp_state->createInfo.subpassCount; i++) {
1312 // record if depth/color attachments are in use for this renderpass
1313 if (rp_state->createInfo.pSubpasses[i].pDepthStencilAttachment != nullptr) prepass_state->second.depthAttachment = true;
1314
1315 if (rp_state->createInfo.pSubpasses[i].colorAttachmentCount > 0) prepass_state->second.colorAttachment = true;
1316 }
1317}
1318
1319void BestPractices::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1320 VkSubpassContents contents) {
1321 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1322 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
1323}
1324
1325void BestPractices::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1326 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1327 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1328 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1329}
1330
1331void BestPractices::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1332 const VkRenderPassBeginInfo* pRenderPassBegin,
1333 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1334 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1335 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1336}
1337
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001338// Generic function to handle validation for all CmdDraw* type functions
1339bool BestPractices::ValidateCmdDrawType(VkCommandBuffer cmd_buffer, const char* caller) const {
1340 bool skip = false;
1341 const CMD_BUFFER_STATE* cb_state = GetCBState(cmd_buffer);
1342 if (cb_state) {
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001343 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
1344 const auto* pipeline_state = cb_state->lastBound[lv_bind_point].pipeline_state;
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001345 const auto& current_vtx_bfr_binding_info = cb_state->current_vertex_buffer_binding_info.vertex_buffer_bindings;
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001346
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001347 // Verify vertex binding
1348 if (pipeline_state->vertex_binding_descriptions_.size() <= 0) {
1349 if ((!current_vtx_bfr_binding_info.empty()) && (!cb_state->vertex_buffer_used)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001350 skip |= LogPerformanceWarning(cb_state->commandBuffer, kVUID_BestPractices_DrawState_VtxIndexOutOfBounds,
1351 "Vertex buffers are bound to %s but no vertex buffers are attached to %s.",
1352 report_data->FormatHandle(cb_state->commandBuffer).c_str(),
1353 report_data->FormatHandle(pipeline_state->pipeline).c_str());
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001354 }
1355 }
1356 }
1357 return skip;
1358}
1359
Sam Walls0961ec02020-03-31 16:39:15 +01001360void BestPractices::RecordCmdDrawType(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
1361 if (VendorCheckEnabled(kBPVendorArm)) {
1362 RecordCmdDrawTypeArm(cmd_buffer, draw_count, caller);
1363 }
1364}
1365
1366void BestPractices::RecordCmdDrawTypeArm(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
1367 auto prepass_state = cbDepthPrePassStates.find(cmd_buffer);
1368 if (prepass_state != cbDepthPrePassStates.end() && draw_count >= kDepthPrePassMinDrawCountArm) {
1369 if (prepass_state->second.depthOnly) prepass_state->second.numDrawCallsDepthOnly++;
1370
1371 if (prepass_state->second.depthEqualComparison) prepass_state->second.numDrawCallsDepthEqualCompare++;
1372 }
1373}
1374
Camden5b184be2019-08-13 07:50:19 -06001375bool BestPractices::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001376 uint32_t firstVertex, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06001377 bool skip = false;
1378
1379 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001380 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
1381 "Warning: You are calling vkCmdDraw() with an instanceCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001382 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDraw()");
Camden5b184be2019-08-13 07:50:19 -06001383 }
1384
1385 return skip;
1386}
1387
Sam Walls0961ec02020-03-31 16:39:15 +01001388void BestPractices::PostCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
1389 uint32_t firstVertex, uint32_t firstInstance) {
1390 StateTracker::PostCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
1391 RecordCmdDrawType(commandBuffer, vertexCount * instanceCount, "vkCmdDraw()");
1392}
1393
Camden5b184be2019-08-13 07:50:19 -06001394bool BestPractices::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001395 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06001396 bool skip = false;
1397
1398 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001399 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
1400 "Warning: You are calling vkCmdDrawIndexed() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06001401 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001402 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexed()");
1403
Attilio Provenzano02859b22020-02-27 14:17:28 +00001404 // Check if we reached the limit for small indexed draw calls.
1405 // Note that we cannot update the draw call count here, so we do it in PreCallRecordCmdDrawIndexed.
1406 const CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
1407 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices &&
1408 (cmd_state->small_indexed_draw_call_count == kMaxSmallIndexedDrawcalls - 1)) {
1409 skip |= VendorCheckEnabled(kBPVendorArm) &&
1410 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_ManySmallIndexedDrawcalls,
1411 "The command buffer contains many small indexed drawcalls "
1412 "(at least %u drawcalls with less than %u indices each). This may cause pipeline bubbles. "
1413 "You can try batching drawcalls or instancing when applicable.",
1414 VendorSpecificTag(kBPVendorArm), kMaxSmallIndexedDrawcalls, kSmallIndexedDrawcallIndices);
1415 }
1416
Sam Walls8e77e4f2020-03-16 20:47:40 +00001417 if (VendorCheckEnabled(kBPVendorArm)) {
1418 ValidateIndexBufferArm(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
1419 }
1420
1421 return skip;
1422}
1423
1424bool BestPractices::ValidateIndexBufferArm(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1425 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
1426 bool skip = false;
1427
1428 // check for sparse/underutilised index buffer, and post-transform cache thrashing
1429 const auto* cmd_state = GetCBState(commandBuffer);
1430 if (cmd_state == nullptr) return skip;
1431
locke-lunarg1ae57d62020-11-18 10:49:19 -07001432 const auto* ib_state = cmd_state->index_buffer_binding.buffer_state.get();
1433 if (ib_state == nullptr || cmd_state->index_buffer_binding.buffer_state->destroyed) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00001434
1435 const VkIndexType ib_type = cmd_state->index_buffer_binding.index_type;
1436 const auto& ib_mem_state = *ib_state->binding.mem_state;
1437 const VkDeviceSize ib_mem_offset = ib_mem_state.mapped_range.offset;
1438 const void* ib_mem = ib_mem_state.p_driver_data;
1439 bool primitive_restart_enable = false;
1440
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001441 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
1442 const auto& pipeline_binding_iter = cmd_state->lastBound[lv_bind_point];
1443 const auto* pipeline_state = pipeline_binding_iter.pipeline_state;
Sam Walls8e77e4f2020-03-16 20:47:40 +00001444
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001445 if (pipeline_state != nullptr && pipeline_state->graphicsPipelineCI.pInputAssemblyState != nullptr) {
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001446 primitive_restart_enable = pipeline_state->graphicsPipelineCI.pInputAssemblyState->primitiveRestartEnable == VK_TRUE;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001447 }
Sam Walls8e77e4f2020-03-16 20:47:40 +00001448
1449 // 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 -06001450 if (ib_mem && pipeline_binding_iter.IsUsing()) {
Sam Walls8e77e4f2020-03-16 20:47:40 +00001451 uint32_t scan_stride;
1452 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1453 scan_stride = sizeof(uint8_t);
1454 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1455 scan_stride = sizeof(uint16_t);
1456 } else {
1457 scan_stride = sizeof(uint32_t);
1458 }
1459
1460 const uint8_t* scan_begin = static_cast<const uint8_t*>(ib_mem) + ib_mem_offset + firstIndex * scan_stride;
1461 const uint8_t* scan_end = scan_begin + indexCount * scan_stride;
1462
1463 // Min and max are important to track for some Mali architectures. In older Mali devices without IDVS, all
1464 // vertices corresponding to indices between the minimum and maximum may be loaded, and possibly shaded,
1465 // irrespective of whether or not they're part of the draw call.
1466
1467 // start with minimum as 0xFFFFFFFF and adjust to indices in the buffer
1468 uint32_t min_index = ~0u;
1469 // start with maximum as 0 and adjust to indices in the buffer
1470 uint32_t max_index = 0u;
1471
1472 // first scan-through, we're looking to simulate a model LRU post-transform cache, estimating the number of vertices shaded
1473 // for the given index buffer
1474 uint32_t vertex_shade_count = 0;
1475
1476 PostTransformLRUCacheModel post_transform_cache;
1477
1478 // The size of the cache being modelled positively correlates with how much behaviour it can capture about
1479 // arbitrary ground-truth hardware/architecture cache behaviour. I.e. it's a good solution when we don't know the
1480 // target architecture.
1481 // However, modelling a post-transform cache with more than 32 elements gives diminishing returns in practice.
1482 // http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
1483 post_transform_cache.resize(32);
1484
1485 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
1486 uint32_t scan_index;
1487 uint32_t primitive_restart_value;
1488 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1489 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
1490 primitive_restart_value = 0xFF;
1491 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1492 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
1493 primitive_restart_value = 0xFFFF;
1494 } else {
1495 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
1496 primitive_restart_value = 0xFFFFFFFF;
1497 }
1498
1499 max_index = std::max(max_index, scan_index);
1500 min_index = std::min(min_index, scan_index);
1501
1502 if (!primitive_restart_enable || scan_index != primitive_restart_value) {
1503 bool in_cache = post_transform_cache.query_cache(scan_index);
1504 // if the shaded vertex corresponding to the index is not in the PT-cache, we need to shade again
1505 if (!in_cache) vertex_shade_count++;
1506 }
1507 }
1508
1509 // 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 +01001510 // 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
1511 if (max_index < min_index || max_index == min_index) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00001512
1513 if (max_index - min_index >= indexCount) {
Mark Young0ec6b062020-11-19 15:32:17 -07001514 skip |=
1515 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
1516 "%s The indices which were specified for the draw call only utilise approximately %.02f%% of "
1517 "index buffer value range. Arm Mali architectures before G71 do not have IDVS (Index-Driven "
1518 "Vertex Shading), meaning all vertices corresponding to indices between the minimum and "
1519 "maximum would be loaded, and possibly shaded, whether or not they are used.",
1520 VendorSpecificTag(kBPVendorArm),
1521 (static_cast<float>(indexCount) / static_cast<float>(max_index - min_index)) * 100.0f);
Sam Walls8e77e4f2020-03-16 20:47:40 +00001522 return skip;
1523 }
1524
1525 // use a dynamic vector of bitsets as a memory-compact representation of which indices are included in the draw call
1526 // 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 +01001527 const size_t refs_per_bucket = 64;
1528 std::vector<std::bitset<refs_per_bucket>> vertex_reference_buckets;
1529
1530 const uint32_t n_indices = max_index - min_index + 1;
1531 const uint32_t n_buckets = (n_indices / static_cast<uint32_t>(refs_per_bucket)) +
1532 ((n_indices % static_cast<uint32_t>(refs_per_bucket)) != 0 ? 1 : 0);
1533
1534 // there needs to be at least one bitset to store a set of indices smaller than n_buckets
1535 vertex_reference_buckets.resize(std::max(1u, n_buckets));
Sam Walls8e77e4f2020-03-16 20:47:40 +00001536
1537 // To avoid using too much memory, we run over the indices again.
1538 // Knowing the size from the last scan allows us to record index usage with bitsets
1539 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
1540 uint32_t scan_index;
1541 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1542 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
1543 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1544 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
1545 } else {
1546 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
1547 }
1548 // keep track of the set of all indices used to reference vertices in the draw call
1549 size_t index_offset = scan_index - min_index;
Sam Walls61b06892020-07-23 16:20:50 +01001550 size_t bitset_bucket_index = index_offset / refs_per_bucket;
1551 uint64_t used_indices = 1ull << ((index_offset % refs_per_bucket) & 0xFFFFFFFFu);
Sam Walls8e77e4f2020-03-16 20:47:40 +00001552 vertex_reference_buckets[bitset_bucket_index] |= used_indices;
1553 }
1554
1555 uint32_t vertex_reference_count = 0;
1556 for (const auto& bitset : vertex_reference_buckets) {
1557 vertex_reference_count += static_cast<uint32_t>(bitset.count());
1558 }
1559
1560 // 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 -07001561 float utilization = static_cast<float>(vertex_reference_count) / static_cast<float>(max_index - min_index + 1);
Sam Walls8e77e4f2020-03-16 20:47:40 +00001562 // 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 -07001563 float cache_hit_rate = static_cast<float>(vertex_reference_count) / static_cast<float>(vertex_shade_count);
Sam Walls8e77e4f2020-03-16 20:47:40 +00001564
1565 if (utilization < 0.5f) {
1566 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
1567 "%s The indices which were specified for the draw call only utilise approximately "
1568 "%.02f%% of the bound vertex buffer.",
1569 VendorSpecificTag(kBPVendorArm), utilization);
1570 }
1571
1572 if (cache_hit_rate <= 0.5f) {
1573 skip |=
1574 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_PostTransformCacheThrashing,
1575 "%s The indices which were specified for the draw call are estimated to cause thrashing of "
1576 "the post-transform vertex cache, with a hit-rate of %.02f%%. "
1577 "I.e. the ordering of the index buffer may not make optimal use of indices associated with "
1578 "recently shaded vertices.",
1579 VendorSpecificTag(kBPVendorArm), cache_hit_rate * 100.0f);
1580 }
1581 }
1582
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001583 return skip;
1584}
1585
Attilio Provenzano02859b22020-02-27 14:17:28 +00001586void BestPractices::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1587 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
1588 ValidationStateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset,
1589 firstInstance);
1590
1591 CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
1592 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices) {
1593 cmd_state->small_indexed_draw_call_count++;
1594 }
1595}
1596
Sam Walls0961ec02020-03-31 16:39:15 +01001597void BestPractices::PostCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1598 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
1599 StateTracker::PostCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
1600 RecordCmdDrawType(commandBuffer, indexCount * instanceCount, "vkCmdDrawIndexed()");
1601}
1602
sfricke-samsung681ab7b2020-10-29 01:53:35 -07001603bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
1604 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
1605 uint32_t maxDrawCount, uint32_t stride) const {
1606 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCount()");
1607
1608 return skip;
1609}
1610
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001611bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
1612 VkDeviceSize offset, VkBuffer countBuffer,
1613 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
1614 uint32_t stride) const {
1615 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCountKHR()");
Camden5b184be2019-08-13 07:50:19 -06001616
1617 return skip;
1618}
1619
1620bool BestPractices::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001621 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06001622 bool skip = false;
1623
1624 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001625 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
1626 "Warning: You are calling vkCmdDrawIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001627 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirect()");
Camden5b184be2019-08-13 07:50:19 -06001628 }
1629
1630 return skip;
1631}
1632
Sam Walls0961ec02020-03-31 16:39:15 +01001633void BestPractices::PostCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
1634 uint32_t count, uint32_t stride) {
1635 StateTracker::PostCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, count, stride);
1636 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndirect()");
1637}
1638
Camden5b184be2019-08-13 07:50:19 -06001639bool BestPractices::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001640 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06001641 bool skip = false;
1642
1643 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001644 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
1645 "Warning: You are calling vkCmdDrawIndexedIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001646 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirect()");
Camden5b184be2019-08-13 07:50:19 -06001647 }
1648
1649 return skip;
1650}
1651
Sam Walls0961ec02020-03-31 16:39:15 +01001652void BestPractices::PostCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
1653 uint32_t count, uint32_t stride) {
1654 StateTracker::PostCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, count, stride);
1655 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndexedIndirect()");
1656}
1657
Camden5b184be2019-08-13 07:50:19 -06001658bool BestPractices::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t groupCountX, uint32_t groupCountY,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001659 uint32_t groupCountZ) const {
Camden5b184be2019-08-13 07:50:19 -06001660 bool skip = false;
1661
1662 if ((groupCountX == 0) || (groupCountY == 0) || (groupCountZ == 0)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001663 skip |= LogWarning(device, kVUID_BestPractices_CmdDispatch_GroupCountZero,
1664 "Warning: You are calling vkCmdDispatch() while one or more groupCounts are zero (groupCountX = %" PRIu32
1665 ", groupCountY = %" PRIu32 ", groupCountZ = %" PRIu32 ").",
1666 groupCountX, groupCountY, groupCountZ);
Camden5b184be2019-08-13 07:50:19 -06001667 }
1668
1669 return skip;
1670}
Camden83a9c372019-08-14 11:41:38 -06001671
Sam Walls0961ec02020-03-31 16:39:15 +01001672bool BestPractices::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
1673 bool skip = false;
1674
1675 skip |= StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
1676
1677 auto prepass_state = cbDepthPrePassStates.find(commandBuffer);
1678
1679 if (prepass_state == cbDepthPrePassStates.end()) return skip;
1680
1681 bool uses_depth = (prepass_state->second.depthAttachment || prepass_state->second.colorAttachment) &&
1682 prepass_state->second.numDrawCallsDepthEqualCompare >= kDepthPrePassNumDrawCallsArm &&
1683 prepass_state->second.numDrawCallsDepthOnly >= kDepthPrePassNumDrawCallsArm;
1684 if (uses_depth) {
1685 skip |= LogPerformanceWarning(
1686 device, kVUID_BestPractices_EndRenderPass_DepthPrePassUsage,
1687 "%s Depth pre-passes may be in use. In general, this is not recommended, as in Arm Mali GPUs since "
1688 "Mali-T620, Forward Pixel Killing (FPK) can already perform automatic hidden surface removal; in which "
1689 "case, using depth pre-passes for hidden surface removal may worsen performance.",
1690 VendorSpecificTag(kBPVendorArm));
1691 }
1692
1693 return skip;
1694}
1695
Camden Stocker9c051442019-11-06 14:28:43 -08001696bool BestPractices::ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(VkPhysicalDevice physicalDevice,
1697 const char* api_name) const {
1698 bool skip = false;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001699 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
Camden Stocker9c051442019-11-06 14:28:43 -08001700
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001701 if (bp_pd_state) {
1702 if (bp_pd_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState == UNCALLED) {
1703 skip |= LogWarning(physicalDevice, kVUID_BestPractices_DisplayPlane_PropertiesNotCalled,
1704 "Potential problem with calling %s() without first retrieving properties from "
1705 "vkGetPhysicalDeviceDisplayPlanePropertiesKHR or vkGetPhysicalDeviceDisplayPlaneProperties2KHR.",
1706 api_name);
1707 }
Camden Stocker9c051442019-11-06 14:28:43 -08001708 }
1709
1710 return skip;
1711}
1712
Camden83a9c372019-08-14 11:41:38 -06001713bool BestPractices::PreCallValidateGetDisplayPlaneSupportedDisplaysKHR(VkPhysicalDevice physicalDevice, uint32_t planeIndex,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001714 uint32_t* pDisplayCount, VkDisplayKHR* pDisplays) const {
Camden83a9c372019-08-14 11:41:38 -06001715 bool skip = false;
1716
Camden Stocker9c051442019-11-06 14:28:43 -08001717 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneSupportedDisplaysKHR");
Camden83a9c372019-08-14 11:41:38 -06001718
Camden Stocker9c051442019-11-06 14:28:43 -08001719 return skip;
1720}
1721
1722bool BestPractices::PreCallValidateGetDisplayPlaneCapabilitiesKHR(VkPhysicalDevice physicalDevice, VkDisplayModeKHR mode,
1723 uint32_t planeIndex,
1724 VkDisplayPlaneCapabilitiesKHR* pCapabilities) const {
1725 bool skip = false;
1726
1727 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilitiesKHR");
1728
1729 return skip;
1730}
1731
1732bool BestPractices::PreCallValidateGetDisplayPlaneCapabilities2KHR(VkPhysicalDevice physicalDevice,
1733 const VkDisplayPlaneInfo2KHR* pDisplayPlaneInfo,
1734 VkDisplayPlaneCapabilities2KHR* pCapabilities) const {
1735 bool skip = false;
1736
1737 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilities2KHR");
Camden83a9c372019-08-14 11:41:38 -06001738
1739 return skip;
1740}
Camden05de2d42019-08-19 10:23:56 -06001741
1742bool BestPractices::PreCallValidateGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain, uint32_t* pSwapchainImageCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001743 VkImage* pSwapchainImages) const {
Camden05de2d42019-08-19 10:23:56 -06001744 bool skip = false;
1745
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001746 auto swapchain_state_itr = swapchain_bp_state_map.find(swapchain);
Camden05de2d42019-08-19 10:23:56 -06001747
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001748 if ((swapchain_state_itr != swapchain_bp_state_map.cend()) && pSwapchainImages) {
Camden05de2d42019-08-19 10:23:56 -06001749 // Compare the preliminary value of *pSwapchainImageCount with the value this time:
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001750 if (swapchain_state_itr->second.vkGetSwapchainImagesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001751 skip |=
1752 LogWarning(device, kVUID_Core_Swapchain_PriorCount,
1753 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImageCount; but no prior positive value has "
1754 "been seen for pSwapchainImages.");
Camden05de2d42019-08-19 10:23:56 -06001755 }
1756 }
1757
1758 return skip;
1759}
1760
1761// Common function to handle validation for GetPhysicalDeviceQueueFamilyProperties & 2KHR version
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001762bool BestPractices::ValidateCommonGetPhysicalDeviceQueueFamilyProperties(const PHYSICAL_DEVICE_STATE* pd_state,
1763 uint32_t requested_queue_family_property_count,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07001764 const CALL_STATE call_state,
1765 const char* caller_name) const {
Camden05de2d42019-08-19 10:23:56 -06001766 bool skip = false;
Nathaniel Cesario56a96652020-12-30 13:23:42 -07001767 // Verify that for each physical device, this command is called first with NULL pQueueFamilyProperties in order to get count
1768 if (UNCALLED == call_state) {
1769 skip |= LogWarning(
1770 pd_state->phys_device, kVUID_Core_DevLimit_MissingQueryCount,
1771 "%s is called with non-NULL pQueueFamilyProperties before obtaining pQueueFamilyPropertyCount. It is "
1772 "recommended "
1773 "to first call %s with NULL pQueueFamilyProperties in order to obtain the maximal pQueueFamilyPropertyCount.",
1774 caller_name, caller_name);
1775 // Then verify that pCount that is passed in on second call matches what was returned
1776 } else if (pd_state->queue_family_known_count != requested_queue_family_property_count) {
1777 skip |= LogWarning(pd_state->phys_device, kVUID_Core_DevLimit_CountMismatch,
1778 "%s is called with non-NULL pQueueFamilyProperties and pQueueFamilyPropertyCount value %" PRIu32
1779 ", but the largest previously returned pQueueFamilyPropertyCount for this physicalDevice is %" PRIu32
1780 ". It is recommended to instead receive all the properties by calling %s with "
1781 "pQueueFamilyPropertyCount that was "
1782 "previously obtained by calling %s with NULL pQueueFamilyProperties.",
1783 caller_name, requested_queue_family_property_count, pd_state->queue_family_known_count, caller_name,
1784 caller_name);
Camden05de2d42019-08-19 10:23:56 -06001785 }
1786
1787 return skip;
1788}
1789
Jeff Bolz5c801d12019-10-09 10:38:45 -05001790bool BestPractices::PreCallValidateBindAccelerationStructureMemoryNV(
1791 VkDevice device, uint32_t bindInfoCount, const VkBindAccelerationStructureMemoryInfoNV* pBindInfos) const {
Camden Stocker82510582019-09-03 14:00:16 -06001792 bool skip = false;
1793
1794 for (uint32_t i = 0; i < bindInfoCount; i++) {
sourav parmarcd5fb182020-07-17 12:58:44 -07001795 const ACCELERATION_STRUCTURE_STATE* as_state = GetAccelerationStructureStateNV(pBindInfos[i].accelerationStructure);
Camden Stocker82510582019-09-03 14:00:16 -06001796 if (!as_state->memory_requirements_checked) {
1797 // There's not an explicit requirement in the spec to call vkGetImageMemoryRequirements() prior to calling
1798 // BindAccelerationStructureMemoryNV but it's implied in that memory being bound must conform with
1799 // VkAccelerationStructureMemoryRequirementsInfoNV from vkGetAccelerationStructureMemoryRequirementsNV
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001800 skip |= LogWarning(
1801 device, kVUID_BestPractices_BindAccelNV_NoMemReqQuery,
Camden Stocker82510582019-09-03 14:00:16 -06001802 "vkBindAccelerationStructureMemoryNV(): "
1803 "Binding memory to %s but vkGetAccelerationStructureMemoryRequirementsNV() has not been called on that structure.",
1804 report_data->FormatHandle(pBindInfos[i].accelerationStructure).c_str());
1805 }
1806 }
1807
1808 return skip;
1809}
1810
Camden05de2d42019-08-19 10:23:56 -06001811bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
1812 uint32_t* pQueueFamilyPropertyCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001813 VkQueueFamilyProperties* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06001814 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1815 assert(physical_device_state);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07001816 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physical_device_state->phys_device);
1817 if (pQueueFamilyProperties && bp_pd_state) {
1818 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
1819 bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
1820 "vkGetPhysicalDeviceQueueFamilyProperties()");
1821 }
1822 return false;
Camden05de2d42019-08-19 10:23:56 -06001823}
1824
Mike Schuchardt2df08912020-12-15 16:28:09 -08001825bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
1826 uint32_t* pQueueFamilyPropertyCount,
1827 VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06001828 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1829 assert(physical_device_state);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07001830 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physical_device_state->phys_device);
1831 if (pQueueFamilyProperties && bp_pd_state) {
1832 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
1833 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
1834 "vkGetPhysicalDeviceQueueFamilyProperties2()");
1835 }
1836 return false;
Camden05de2d42019-08-19 10:23:56 -06001837}
1838
Jeff Bolz5c801d12019-10-09 10:38:45 -05001839bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2KHR(
Mike Schuchardt2df08912020-12-15 16:28:09 -08001840 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount, VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06001841 auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1842 assert(physical_device_state);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07001843 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physical_device_state->phys_device);
1844 if (pQueueFamilyProperties && bp_pd_state) {
1845 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
1846 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
1847 "vkGetPhysicalDeviceQueueFamilyProperties2KHR()");
1848 }
1849 return false;
Camden05de2d42019-08-19 10:23:56 -06001850}
1851
1852bool BestPractices::PreCallValidateGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
1853 uint32_t* pSurfaceFormatCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001854 VkSurfaceFormatKHR* pSurfaceFormats) const {
Camden05de2d42019-08-19 10:23:56 -06001855 if (!pSurfaceFormats) return false;
1856 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001857 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
1858 const auto& call_state = bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState;
Camden05de2d42019-08-19 10:23:56 -06001859 bool skip = false;
1860 if (call_state == UNCALLED) {
1861 // Since we haven't recorded a preliminary value of *pSurfaceFormatCount, that likely means that the application didn't
1862 // previously call this function with a NULL value of pSurfaceFormats:
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001863 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_MustQueryCount,
1864 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount; but no prior "
1865 "positive value has been seen for pSurfaceFormats.");
Camden05de2d42019-08-19 10:23:56 -06001866 } else {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001867 auto prev_format_count = static_cast<uint32_t>(physical_device_state->surface_formats.size());
Peter Chene191bd72019-09-16 13:04:37 -04001868 if (*pSurfaceFormatCount > prev_format_count) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001869 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_CountMismatch,
1870 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount, and with "
1871 "pSurfaceFormats set to a value (%u) that is greater than the value (%u) that was returned "
1872 "when pSurfaceFormatCount was NULL.",
1873 *pSurfaceFormatCount, prev_format_count);
Camden05de2d42019-08-19 10:23:56 -06001874 }
1875 }
1876 return skip;
1877}
Camden Stocker23cc47d2019-09-03 14:53:57 -06001878
1879bool BestPractices::PreCallValidateQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001880 VkFence fence) const {
Camden Stocker23cc47d2019-09-03 14:53:57 -06001881 bool skip = false;
1882
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001883 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
1884 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
Camden Stocker23cc47d2019-09-03 14:53:57 -06001885 // Store sparse binding image_state and after binding is complete make sure that any requiring metadata have it bound
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001886 std::unordered_set<const IMAGE_STATE*> sparse_images;
1887 // Track images getting metadata bound by this call in a set, it'll be recorded into the image_state
1888 // in RecordQueueBindSparse.
1889 std::unordered_set<const IMAGE_STATE*> sparse_images_with_metadata;
Camden Stocker23cc47d2019-09-03 14:53:57 -06001890 // 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 -07001891 for (uint32_t i = 0; i < bind_info.imageBindCount; ++i) {
1892 const auto& image_bind = bind_info.pImageBinds[i];
Camden Stocker23cc47d2019-09-03 14:53:57 -06001893 auto image_state = GetImageState(image_bind.image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001894 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06001895 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001896 }
Camden Stocker23cc47d2019-09-03 14:53:57 -06001897 sparse_images.insert(image_state);
1898 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
1899 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
1900 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001901 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1902 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
1903 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
1904 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001905 }
1906 }
1907 if (!image_state->memory_requirements_checked) {
1908 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001909 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1910 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
1911 "vkGetImageMemoryRequirements() to retrieve requirements.",
1912 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001913 }
1914 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001915 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
1916 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
1917 auto image_state = GetImageState(bind_info.pImageOpaqueBinds[i].image);
1918 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06001919 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001920 }
Camden Stocker23cc47d2019-09-03 14:53:57 -06001921 sparse_images.insert(image_state);
1922 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
1923 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
1924 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001925 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1926 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
1927 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
1928 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001929 }
1930 }
1931 if (!image_state->memory_requirements_checked) {
1932 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001933 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1934 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
1935 "vkGetImageMemoryRequirements() to retrieve requirements.",
1936 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001937 }
1938 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
1939 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001940 sparse_images_with_metadata.insert(image_state);
Camden Stocker23cc47d2019-09-03 14:53:57 -06001941 }
1942 }
1943 }
1944 for (const auto& sparse_image_state : sparse_images) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001945 if (sparse_image_state->sparse_metadata_required && !sparse_image_state->sparse_metadata_bound &&
1946 sparse_images_with_metadata.find(sparse_image_state) == sparse_images_with_metadata.end()) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06001947 // Warn if sparse image binding metadata required for image with sparse binding, but metadata not bound
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001948 skip |= LogWarning(sparse_image_state->image, kVUID_Core_MemTrack_InvalidState,
1949 "vkQueueBindSparse(): Binding sparse memory to %s which requires a metadata aspect but no "
1950 "binding with VK_SPARSE_MEMORY_BIND_METADATA_BIT set was made.",
1951 report_data->FormatHandle(sparse_image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001952 }
1953 }
1954 }
1955
1956 return skip;
1957}
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001958
Mark Lobodzinski84101d72020-04-24 09:43:48 -06001959void BestPractices::ManualPostCallRecordQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
1960 VkFence fence, VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07001961 if (result != VK_SUCCESS) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07001962 return;
1963 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001964
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001965 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
1966 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
1967 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
1968 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
1969 auto image_state = GetImageState(bind_info.pImageOpaqueBinds[i].image);
1970 if (!image_state) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001971 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001972 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001973 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
1974 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
1975 image_state->sparse_metadata_bound = true;
1976 }
1977 }
1978 }
1979 }
1980}
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001981
1982bool BestPractices::PreCallValidateCmdClearAttachments(VkCommandBuffer commandBuffer, uint32_t attachmentCount,
Camden Stockerf55721f2019-09-09 11:04:49 -06001983 const VkClearAttachment* pAttachments, uint32_t rectCount,
1984 const VkClearRect* pRects) const {
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001985 bool skip = false;
1986 const CMD_BUFFER_STATE* cb_node = GetCBState(commandBuffer);
1987 if (!cb_node) return skip;
1988
Camden Stockerf55721f2019-09-09 11:04:49 -06001989 // Warn if this is issued prior to Draw Cmd and clearing the entire attachment
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001990 if (!cb_node->hasDrawCmd && (cb_node->activeRenderPassBeginInfo.renderArea.extent.width == pRects[0].rect.extent.width) &&
1991 (cb_node->activeRenderPassBeginInfo.renderArea.extent.height == pRects[0].rect.extent.height)) {
1992 // There are times where app needs to use ClearAttachments (generally when reusing a buffer inside of a render pass)
1993 // This warning should be made more specific. It'd be best to avoid triggering this test if it's a use that must call
1994 // CmdClearAttachments.
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001995 skip |= LogPerformanceWarning(commandBuffer, kVUID_BestPractices_DrawState_ClearCmdBeforeDraw,
1996 "vkCmdClearAttachments() issued on %s prior to any Draw Cmds. It is recommended you "
1997 "use RenderPass LOAD_OP_CLEAR on Attachments prior to any Draw.",
1998 report_data->FormatHandle(commandBuffer).c_str());
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001999 }
2000
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002001 // Check for uses of ClearAttachments along with LOAD_OP_LOAD,
2002 // as it can be more efficient to just use LOAD_OP_CLEAR
locke-lunargaecf2152020-05-12 17:15:41 -06002003 const RENDER_PASS_STATE* rp = cb_node->activeRenderPass.get();
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002004 if (rp) {
2005 const auto& subpass = rp->createInfo.pSubpasses[cb_node->activeSubpass];
2006
2007 for (uint32_t i = 0; i < attachmentCount; i++) {
2008 auto& attachment = pAttachments[i];
2009 if (attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
2010 uint32_t color_attachment = attachment.colorAttachment;
2011 uint32_t fb_attachment = subpass.pColorAttachments[color_attachment].attachment;
2012
2013 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2014 if (rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2015 skip |= LogPerformanceWarning(
2016 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2017 "vkCmdClearAttachments() issued on %s for color attachment #%u in this subpass, "
2018 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2019 "it is more efficient.",
2020 report_data->FormatHandle(commandBuffer).c_str(), color_attachment);
2021 }
2022 }
2023 }
2024
2025 if (subpass.pDepthStencilAttachment && attachment.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) {
2026 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
2027
2028 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2029 if (rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2030 skip |= LogPerformanceWarning(
2031 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2032 "vkCmdClearAttachments() issued on %s for the depth attachment in this subpass, "
2033 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2034 "it is more efficient.",
2035 report_data->FormatHandle(commandBuffer).c_str());
2036 }
2037 }
2038 }
2039
2040 if (subpass.pDepthStencilAttachment && attachment.aspectMask & VK_IMAGE_ASPECT_STENCIL_BIT) {
2041 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
2042
2043 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2044 if (rp->createInfo.pAttachments[fb_attachment].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2045 skip |= LogPerformanceWarning(
2046 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2047 "vkCmdClearAttachments() issued on %s for the stencil attachment in this subpass, "
2048 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2049 "it is more efficient.",
2050 report_data->FormatHandle(commandBuffer).c_str());
2051 }
2052 }
2053 }
2054 }
2055 }
2056
Camden Stockerf55721f2019-09-09 11:04:49 -06002057 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002058}
Attilio Provenzano02859b22020-02-27 14:17:28 +00002059
2060bool BestPractices::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
2061 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
2062 const VkImageResolve* pRegions) const {
2063 bool skip = false;
2064
2065 skip |= VendorCheckEnabled(kBPVendorArm) &&
2066 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage_ResolvingImage,
2067 "%s Attempting to use vkCmdResolveImage to resolve a multisampled image. "
2068 "This is a very slow and extremely bandwidth intensive path. "
2069 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
2070 VendorSpecificTag(kBPVendorArm));
2071
2072 return skip;
2073}
2074
Jeff Leger178b1e52020-10-05 12:22:23 -04002075bool BestPractices::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
2076 const VkResolveImageInfo2KHR* pResolveImageInfo) const {
2077 bool skip = false;
2078
2079 skip |= VendorCheckEnabled(kBPVendorArm) &&
2080 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2KHR_ResolvingImage,
2081 "%s Attempting to use vkCmdResolveImage2KHR to resolve a multisampled image. "
2082 "This is a very slow and extremely bandwidth intensive path. "
2083 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
2084 VendorSpecificTag(kBPVendorArm));
2085
2086 return skip;
2087}
2088
Attilio Provenzano02859b22020-02-27 14:17:28 +00002089bool BestPractices::PreCallValidateCreateSampler(VkDevice device, const VkSamplerCreateInfo* pCreateInfo,
2090 const VkAllocationCallbacks* pAllocator, VkSampler* pSampler) const {
2091 bool skip = false;
2092
2093 if (VendorCheckEnabled(kBPVendorArm)) {
2094 if ((pCreateInfo->addressModeU != pCreateInfo->addressModeV) || (pCreateInfo->addressModeV != pCreateInfo->addressModeW)) {
2095 skip |= LogPerformanceWarning(
2096 device, kVUID_BestPractices_CreateSampler_DifferentWrappingModes,
2097 "%s Creating a sampler object with wrapping modes which do not match (U = %u, V = %u, W = %u). "
2098 "This may cause reduced performance even if only U (1D image) or U/V wrapping modes (2D "
2099 "image) are actually used. If you need different wrapping modes, disregard this warning.",
2100 VendorSpecificTag(kBPVendorArm));
2101 }
2102
2103 if ((pCreateInfo->minLod != 0.0f) || (pCreateInfo->maxLod < VK_LOD_CLAMP_NONE)) {
2104 skip |= LogPerformanceWarning(
2105 device, kVUID_BestPractices_CreateSampler_LodClamping,
2106 "%s Creating a sampler object with LOD clamping (minLod = %f, maxLod = %f). This may cause reduced performance. "
2107 "Instead of clamping LOD in the sampler, consider using an VkImageView which restricts the mip-levels, set minLod "
2108 "to 0.0, and maxLod to VK_LOD_CLAMP_NONE.",
2109 VendorSpecificTag(kBPVendorArm), pCreateInfo->minLod, pCreateInfo->maxLod);
2110 }
2111
2112 if (pCreateInfo->mipLodBias != 0.0f) {
2113 skip |=
2114 LogPerformanceWarning(device, kVUID_BestPractices_CreateSampler_LodBias,
2115 "%s Creating a sampler object with LOD bias != 0.0 (%f). This will lead to less efficient "
2116 "descriptors being created and may cause reduced performance.",
2117 VendorSpecificTag(kBPVendorArm), pCreateInfo->mipLodBias);
2118 }
2119
2120 if ((pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
2121 pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
2122 pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER) &&
2123 (pCreateInfo->borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK)) {
2124 skip |= LogPerformanceWarning(
2125 device, kVUID_BestPractices_CreateSampler_BorderClampColor,
2126 "%s Creating a sampler object with border clamping and borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK. "
2127 "This will lead to less efficient descriptors being created and may cause reduced performance. "
2128 "If possible, use VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK as the border color.",
2129 VendorSpecificTag(kBPVendorArm));
2130 }
2131
2132 if (pCreateInfo->unnormalizedCoordinates) {
2133 skip |= LogPerformanceWarning(
2134 device, kVUID_BestPractices_CreateSampler_UnnormalizedCoordinates,
2135 "%s Creating a sampler object with unnormalized coordinates. This will lead to less efficient "
2136 "descriptors being created and may cause reduced performance.",
2137 VendorSpecificTag(kBPVendorArm));
2138 }
2139
2140 if (pCreateInfo->anisotropyEnable) {
2141 skip |= LogPerformanceWarning(
2142 device, kVUID_BestPractices_CreateSampler_Anisotropy,
2143 "%s Creating a sampler object with anisotropy. This will lead to less efficient descriptors being created "
2144 "and may cause reduced performance.",
2145 VendorSpecificTag(kBPVendorArm));
2146 }
2147 }
2148
2149 return skip;
2150}
Sam Walls8e77e4f2020-03-16 20:47:40 +00002151
2152void BestPractices::PostTransformLRUCacheModel::resize(size_t size) { _entries.resize(size); }
2153
2154bool BestPractices::PostTransformLRUCacheModel::query_cache(uint32_t value) {
2155 // look for a cache hit
2156 auto hit = std::find_if(_entries.begin(), _entries.end(), [value](const CacheEntry& entry) { return entry.value == value; });
2157 if (hit != _entries.end()) {
2158 // mark the cache hit as being most recently used
2159 hit->age = iteration++;
2160 return true;
2161 }
2162
2163 // if there's no cache hit, we need to model the entry being inserted into the cache
2164 CacheEntry new_entry = {value, iteration};
2165 if (iteration < static_cast<uint32_t>(std::distance(_entries.begin(), _entries.end()))) {
2166 // if there is still space left in the cache, use the next available slot
2167 *(_entries.begin() + iteration) = new_entry;
2168 } else {
2169 // otherwise replace the least recently used cache entry
2170 auto lru = std::min_element(_entries.begin(), hit, [](const CacheEntry& a, const CacheEntry& b) { return a.age < b.age; });
2171 *lru = new_entry;
2172 }
2173 iteration++;
2174 return false;
2175}
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002176
2177bool BestPractices::PreCallValidateAcquireNextImageKHR(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout,
2178 VkSemaphore semaphore, VkFence fence, uint32_t* pImageIndex) const {
2179 const auto swapchain_data = GetSwapchainState(swapchain);
2180 bool skip = false;
2181 if (swapchain_data && swapchain_data->images.size() == 0) {
2182 skip |= LogWarning(swapchain, kVUID_Core_DrawState_SwapchainImagesNotFound,
2183 "vkAcquireNextImageKHR: No images found to acquire from. Application probably did not call "
2184 "vkGetSwapchainImagesKHR after swapchain creation.");
2185 }
2186 return skip;
2187}
2188
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002189void BestPractices::CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(CALL_STATE& call_state, bool no_pointer) {
2190 if (no_pointer) {
2191 if (UNCALLED == call_state) {
2192 call_state = QUERY_COUNT;
2193 }
2194 } else { // Save queue family properties
2195 call_state = QUERY_DETAILS;
2196 }
2197}
2198
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002199void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
2200 uint32_t* pQueueFamilyPropertyCount,
2201 VkQueueFamilyProperties* pQueueFamilyProperties) {
2202 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(physicalDevice, pQueueFamilyPropertyCount,
2203 pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002204 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002205 if (bp_pd_state) {
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002206 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
2207 nullptr == pQueueFamilyProperties);
2208 }
2209}
2210
2211void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
2212 uint32_t* pQueueFamilyPropertyCount,
2213 VkQueueFamilyProperties2* pQueueFamilyProperties) {
2214 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(physicalDevice, pQueueFamilyPropertyCount,
2215 pQueueFamilyProperties);
2216 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2217 if (bp_pd_state) {
2218 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
2219 nullptr == pQueueFamilyProperties);
2220 }
2221}
2222
2223void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(VkPhysicalDevice physicalDevice,
2224 uint32_t* pQueueFamilyPropertyCount,
2225 VkQueueFamilyProperties2* pQueueFamilyProperties) {
2226 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(physicalDevice, pQueueFamilyPropertyCount,
2227 pQueueFamilyProperties);
2228 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2229 if (bp_pd_state) {
2230 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
2231 nullptr == pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002232 }
2233}
2234
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002235void BestPractices::PostCallRecordGetPhysicalDeviceFeatures(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures* pFeatures) {
2236 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002237 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2238 if (bp_pd_state) {
2239 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
2240 }
2241}
2242
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002243void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2(VkPhysicalDevice physicalDevice,
2244 VkPhysicalDeviceFeatures2* pFeatures) {
2245 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002246 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2247 if (bp_pd_state) {
2248 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
2249 }
2250}
2251
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002252void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2KHR(VkPhysicalDevice physicalDevice,
2253 VkPhysicalDeviceFeatures2* pFeatures) {
2254 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2KHR(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002255 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2256 if (bp_pd_state) {
2257 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
2258 }
2259}
2260
2261void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilitiesKHR(VkPhysicalDevice physicalDevice,
2262 VkSurfaceKHR surface,
2263 VkSurfaceCapabilitiesKHR* pSurfaceCapabilities,
2264 VkResult result) {
2265 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2266 if (bp_pd_state) {
2267 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
2268 }
2269}
2270
2271void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2KHR(
2272 VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
2273 VkSurfaceCapabilities2KHR* pSurfaceCapabilities, VkResult result) {
2274 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2275 if (bp_pd_state) {
2276 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
2277 }
2278}
2279
2280void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2EXT(VkPhysicalDevice physicalDevice,
2281 VkSurfaceKHR surface,
2282 VkSurfaceCapabilities2EXT* pSurfaceCapabilities,
2283 VkResult result) {
2284 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2285 if (bp_pd_state) {
2286 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
2287 }
2288}
2289
2290void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice physicalDevice,
2291 VkSurfaceKHR surface, uint32_t* pPresentModeCount,
2292 VkPresentModeKHR* pPresentModes, VkResult result) {
2293 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2294 if (bp_pd_data) {
2295 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfacePresentModesKHRState;
2296
2297 if (*pPresentModeCount) {
2298 if (call_state < QUERY_COUNT) {
2299 call_state = QUERY_COUNT;
2300 }
2301 }
2302 if (pPresentModes) {
2303 if (call_state < QUERY_DETAILS) {
2304 call_state = QUERY_DETAILS;
2305 }
2306 }
2307 }
2308}
2309
2310void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
2311 uint32_t* pSurfaceFormatCount,
2312 VkSurfaceFormatKHR* pSurfaceFormats, VkResult result) {
2313 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2314 if (bp_pd_data) {
2315 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState;
2316
2317 if (*pSurfaceFormatCount) {
2318 if (call_state < QUERY_COUNT) {
2319 call_state = QUERY_COUNT;
2320 }
2321 }
2322 if (pSurfaceFormats) {
2323 if (call_state < QUERY_DETAILS) {
2324 call_state = QUERY_DETAILS;
2325 }
2326 }
2327 }
2328}
2329
2330void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormats2KHR(VkPhysicalDevice physicalDevice,
2331 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
2332 uint32_t* pSurfaceFormatCount,
2333 VkSurfaceFormat2KHR* pSurfaceFormats, VkResult result) {
2334 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2335 if (bp_pd_data) {
2336 if (*pSurfaceFormatCount) {
2337 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_COUNT) {
2338 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_COUNT;
2339 }
2340 }
2341 if (pSurfaceFormats) {
2342 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_DETAILS) {
2343 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_DETAILS;
2344 }
2345 }
2346 }
2347}
2348
2349void BestPractices::ManualPostCallRecordGetPhysicalDeviceDisplayPlanePropertiesKHR(VkPhysicalDevice physicalDevice,
2350 uint32_t* pPropertyCount,
2351 VkDisplayPlanePropertiesKHR* pProperties,
2352 VkResult result) {
2353 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2354 if (bp_pd_data) {
2355 if (*pPropertyCount) {
2356 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_COUNT) {
2357 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_COUNT;
2358 }
2359 }
2360 if (pProperties) {
2361 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_DETAILS) {
2362 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_DETAILS;
2363 }
2364 }
2365 }
2366}
2367
2368void BestPractices::ManualPostCallRecordCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
2369 const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain,
2370 VkResult result) {
2371 if (VK_SUCCESS == result) {
2372 swapchain_bp_state_map.emplace(*pSwapchain, SWAPCHAIN_STATE_BP{});
2373 }
2374}
2375
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002376void BestPractices::PostCallRecordDestroySwapchainKHR(VkDevice device, VkSwapchainKHR swapchain,
2377 const VkAllocationCallbacks* pAllocator) {
2378 ValidationStateTracker::PostCallRecordDestroySwapchainKHR(device, swapchain, pAllocator);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002379 auto swapchain_state_itr = swapchain_bp_state_map.find(swapchain);
2380 if (swapchain_state_itr != swapchain_bp_state_map.cend()) {
2381 swapchain_bp_state_map.erase(swapchain_state_itr);
2382 }
2383}
2384
2385void BestPractices::ManualPostCallRecordGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain,
2386 uint32_t* pSwapchainImageCount, VkImage* pSwapchainImages,
2387 VkResult result) {
2388 auto swapchain_state_itr = swapchain_bp_state_map.find(swapchain);
2389 assert(swapchain_state_itr != swapchain_bp_state_map.cend());
2390 auto& swapchain_state = swapchain_state_itr->second;
2391 if (pSwapchainImages || *pSwapchainImageCount) {
2392 if (swapchain_state.vkGetSwapchainImagesKHRState < QUERY_DETAILS) {
2393 swapchain_state.vkGetSwapchainImagesKHRState = QUERY_DETAILS;
2394 }
2395 }
2396}
2397
2398void BestPractices::ManualPostCallRecordEnumeratePhysicalDevices(VkInstance instance, uint32_t* pPhysicalDeviceCount,
2399 VkPhysicalDevice* pPhysicalDevices, VkResult result) {
2400 if ((nullptr != pPhysicalDevices) && ((result == VK_SUCCESS || result == VK_INCOMPLETE))) {
2401 for (uint32_t i = 0; i < *pPhysicalDeviceCount; i++) {
2402 phys_device_bp_state_map.emplace(pPhysicalDevices[i], PHYSICAL_DEVICE_STATE_BP{});
2403 }
2404 }
2405}
2406
2407void BestPractices::ManualPostCallRecordCreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo*, const VkAllocationCallbacks*,
2408 VkDevice*, VkResult result) {
2409 if (VK_SUCCESS == result) {
2410 instance_device_bp_state = &phys_device_bp_state_map[gpu];
2411 }
2412}
2413
2414PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP(const VkPhysicalDevice& phys_device) {
2415 if (phys_device_bp_state_map.count(phys_device) > 0) {
2416 return &phys_device_bp_state_map.at(phys_device);
2417 } else {
2418 return nullptr;
2419 }
2420}
2421
2422const PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP(const VkPhysicalDevice& phys_device) const {
2423 if (phys_device_bp_state_map.count(phys_device) > 0) {
2424 return &phys_device_bp_state_map.at(phys_device);
2425 } else {
2426 return nullptr;
2427 }
2428}
2429
2430PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP() {
2431 auto bp_state = (reinterpret_cast<BestPractices*>(instance_state))->instance_device_bp_state;
2432 if (bp_state) {
2433 return bp_state;
2434 } else if (!bp_state && phys_device_bp_state_map.count(physical_device_state->phys_device) > 0) {
2435 return &phys_device_bp_state_map.at(physical_device_state->phys_device);
2436 } else {
2437 return nullptr;
2438 }
2439}
2440
2441const PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP() const {
2442 auto bp_state = (reinterpret_cast<BestPractices*>(instance_state))->instance_device_bp_state;
2443 if (bp_state) {
2444 return bp_state;
2445 } else if (!bp_state && phys_device_bp_state_map.count(physical_device_state->phys_device) > 0) {
2446 return &phys_device_bp_state_map.at(physical_device_state->phys_device);
2447 } else {
2448 return nullptr;
2449 }
2450}