blob: 7334fc984fcebd3a1a3fbba56a7b8167ebc7e53e [file] [log] [blame]
Mark Lobodzinski91e50bf2020-01-14 09:55:11 -07001/* Copyright (c) 2015-2020 The Khronos Group Inc.
2 * Copyright (c) 2015-2020 Valve Corporation
3 * Copyright (c) 2015-2020 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,
1764 bool qfp_null, const char* caller_name) const {
Camden05de2d42019-08-19 10:23:56 -06001765 bool skip = false;
1766 if (!qfp_null) {
1767 // Verify that for each physical device, this command is called first with NULL pQueueFamilyProperties in order to get count
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001768 const auto* bp_pd_state = GetPhysicalDeviceStateBP(pd_state->phys_device);
1769 if (bp_pd_state) {
1770 if (UNCALLED == bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState) {
1771 skip |= LogWarning(
1772 pd_state->phys_device, kVUID_Core_DevLimit_MissingQueryCount,
1773 "%s is called with non-NULL pQueueFamilyProperties before obtaining pQueueFamilyPropertyCount. It is "
1774 "recommended "
1775 "to first call %s with NULL pQueueFamilyProperties in order to obtain the maximal pQueueFamilyPropertyCount.",
1776 caller_name, caller_name);
1777 // Then verify that pCount that is passed in on second call matches what was returned
1778 } else if (pd_state->queue_family_known_count != requested_queue_family_property_count) {
1779 skip |=
1780 LogWarning(pd_state->phys_device, kVUID_Core_DevLimit_CountMismatch,
1781 "%s is called with non-NULL pQueueFamilyProperties and pQueueFamilyPropertyCount value %" PRIu32
1782 ", but the largest previously returned pQueueFamilyPropertyCount for this physicalDevice is %" PRIu32
1783 ". It is recommended to instead receive all the properties by calling %s with "
1784 "pQueueFamilyPropertyCount that was "
1785 "previously obtained by calling %s with NULL pQueueFamilyProperties.",
1786 caller_name, requested_queue_family_property_count, pd_state->queue_family_known_count, caller_name,
1787 caller_name);
1788 }
Camden05de2d42019-08-19 10:23:56 -06001789 }
1790 }
1791
1792 return skip;
1793}
1794
Jeff Bolz5c801d12019-10-09 10:38:45 -05001795bool BestPractices::PreCallValidateBindAccelerationStructureMemoryNV(
1796 VkDevice device, uint32_t bindInfoCount, const VkBindAccelerationStructureMemoryInfoNV* pBindInfos) const {
Camden Stocker82510582019-09-03 14:00:16 -06001797 bool skip = false;
1798
1799 for (uint32_t i = 0; i < bindInfoCount; i++) {
sourav parmarcd5fb182020-07-17 12:58:44 -07001800 const ACCELERATION_STRUCTURE_STATE* as_state = GetAccelerationStructureStateNV(pBindInfos[i].accelerationStructure);
Camden Stocker82510582019-09-03 14:00:16 -06001801 if (!as_state->memory_requirements_checked) {
1802 // There's not an explicit requirement in the spec to call vkGetImageMemoryRequirements() prior to calling
1803 // BindAccelerationStructureMemoryNV but it's implied in that memory being bound must conform with
1804 // VkAccelerationStructureMemoryRequirementsInfoNV from vkGetAccelerationStructureMemoryRequirementsNV
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001805 skip |= LogWarning(
1806 device, kVUID_BestPractices_BindAccelNV_NoMemReqQuery,
Camden Stocker82510582019-09-03 14:00:16 -06001807 "vkBindAccelerationStructureMemoryNV(): "
1808 "Binding memory to %s but vkGetAccelerationStructureMemoryRequirementsNV() has not been called on that structure.",
1809 report_data->FormatHandle(pBindInfos[i].accelerationStructure).c_str());
1810 }
1811 }
1812
1813 return skip;
1814}
1815
Camden05de2d42019-08-19 10:23:56 -06001816bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
1817 uint32_t* pQueueFamilyPropertyCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001818 VkQueueFamilyProperties* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06001819 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1820 assert(physical_device_state);
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001821 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
Camden05de2d42019-08-19 10:23:56 -06001822 (nullptr == pQueueFamilyProperties),
1823 "vkGetPhysicalDeviceQueueFamilyProperties()");
1824}
1825
Mike Schuchardt2df08912020-12-15 16:28:09 -08001826bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
1827 uint32_t* pQueueFamilyPropertyCount,
1828 VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06001829 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1830 assert(physical_device_state);
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001831 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
Camden05de2d42019-08-19 10:23:56 -06001832 (nullptr == pQueueFamilyProperties),
1833 "vkGetPhysicalDeviceQueueFamilyProperties2()");
1834}
1835
Jeff Bolz5c801d12019-10-09 10:38:45 -05001836bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2KHR(
Mike Schuchardt2df08912020-12-15 16:28:09 -08001837 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount, VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06001838 auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1839 assert(physical_device_state);
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001840 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
Camden05de2d42019-08-19 10:23:56 -06001841 (nullptr == pQueueFamilyProperties),
1842 "vkGetPhysicalDeviceQueueFamilyProperties2KHR()");
1843}
1844
1845bool BestPractices::PreCallValidateGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
1846 uint32_t* pSurfaceFormatCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001847 VkSurfaceFormatKHR* pSurfaceFormats) const {
Camden05de2d42019-08-19 10:23:56 -06001848 if (!pSurfaceFormats) return false;
1849 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001850 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
1851 const auto& call_state = bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState;
Camden05de2d42019-08-19 10:23:56 -06001852 bool skip = false;
1853 if (call_state == UNCALLED) {
1854 // Since we haven't recorded a preliminary value of *pSurfaceFormatCount, that likely means that the application didn't
1855 // previously call this function with a NULL value of pSurfaceFormats:
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001856 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_MustQueryCount,
1857 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount; but no prior "
1858 "positive value has been seen for pSurfaceFormats.");
Camden05de2d42019-08-19 10:23:56 -06001859 } else {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001860 auto prev_format_count = static_cast<uint32_t>(physical_device_state->surface_formats.size());
Peter Chene191bd72019-09-16 13:04:37 -04001861 if (*pSurfaceFormatCount > prev_format_count) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001862 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_CountMismatch,
1863 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount, and with "
1864 "pSurfaceFormats set to a value (%u) that is greater than the value (%u) that was returned "
1865 "when pSurfaceFormatCount was NULL.",
1866 *pSurfaceFormatCount, prev_format_count);
Camden05de2d42019-08-19 10:23:56 -06001867 }
1868 }
1869 return skip;
1870}
Camden Stocker23cc47d2019-09-03 14:53:57 -06001871
1872bool BestPractices::PreCallValidateQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001873 VkFence fence) const {
Camden Stocker23cc47d2019-09-03 14:53:57 -06001874 bool skip = false;
1875
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001876 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
1877 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
Camden Stocker23cc47d2019-09-03 14:53:57 -06001878 // 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 -05001879 std::unordered_set<const IMAGE_STATE*> sparse_images;
1880 // Track images getting metadata bound by this call in a set, it'll be recorded into the image_state
1881 // in RecordQueueBindSparse.
1882 std::unordered_set<const IMAGE_STATE*> sparse_images_with_metadata;
Camden Stocker23cc47d2019-09-03 14:53:57 -06001883 // 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 -07001884 for (uint32_t i = 0; i < bind_info.imageBindCount; ++i) {
1885 const auto& image_bind = bind_info.pImageBinds[i];
Camden Stocker23cc47d2019-09-03 14:53:57 -06001886 auto image_state = GetImageState(image_bind.image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001887 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06001888 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001889 }
Camden Stocker23cc47d2019-09-03 14:53:57 -06001890 sparse_images.insert(image_state);
1891 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
1892 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
1893 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001894 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1895 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
1896 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
1897 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001898 }
1899 }
1900 if (!image_state->memory_requirements_checked) {
1901 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001902 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1903 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
1904 "vkGetImageMemoryRequirements() to retrieve requirements.",
1905 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001906 }
1907 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001908 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
1909 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
1910 auto image_state = GetImageState(bind_info.pImageOpaqueBinds[i].image);
1911 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06001912 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001913 }
Camden Stocker23cc47d2019-09-03 14:53:57 -06001914 sparse_images.insert(image_state);
1915 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
1916 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
1917 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001918 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1919 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
1920 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
1921 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001922 }
1923 }
1924 if (!image_state->memory_requirements_checked) {
1925 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001926 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1927 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
1928 "vkGetImageMemoryRequirements() to retrieve requirements.",
1929 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001930 }
1931 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
1932 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001933 sparse_images_with_metadata.insert(image_state);
Camden Stocker23cc47d2019-09-03 14:53:57 -06001934 }
1935 }
1936 }
1937 for (const auto& sparse_image_state : sparse_images) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001938 if (sparse_image_state->sparse_metadata_required && !sparse_image_state->sparse_metadata_bound &&
1939 sparse_images_with_metadata.find(sparse_image_state) == sparse_images_with_metadata.end()) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06001940 // Warn if sparse image binding metadata required for image with sparse binding, but metadata not bound
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001941 skip |= LogWarning(sparse_image_state->image, kVUID_Core_MemTrack_InvalidState,
1942 "vkQueueBindSparse(): Binding sparse memory to %s which requires a metadata aspect but no "
1943 "binding with VK_SPARSE_MEMORY_BIND_METADATA_BIT set was made.",
1944 report_data->FormatHandle(sparse_image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001945 }
1946 }
1947 }
1948
1949 return skip;
1950}
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001951
Mark Lobodzinski84101d72020-04-24 09:43:48 -06001952void BestPractices::ManualPostCallRecordQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
1953 VkFence fence, VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07001954 if (result != VK_SUCCESS) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07001955 return;
1956 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001957
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001958 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
1959 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
1960 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
1961 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
1962 auto image_state = GetImageState(bind_info.pImageOpaqueBinds[i].image);
1963 if (!image_state) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001964 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001965 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001966 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
1967 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
1968 image_state->sparse_metadata_bound = true;
1969 }
1970 }
1971 }
1972 }
1973}
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001974
1975bool BestPractices::PreCallValidateCmdClearAttachments(VkCommandBuffer commandBuffer, uint32_t attachmentCount,
Camden Stockerf55721f2019-09-09 11:04:49 -06001976 const VkClearAttachment* pAttachments, uint32_t rectCount,
1977 const VkClearRect* pRects) const {
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001978 bool skip = false;
1979 const CMD_BUFFER_STATE* cb_node = GetCBState(commandBuffer);
1980 if (!cb_node) return skip;
1981
Camden Stockerf55721f2019-09-09 11:04:49 -06001982 // Warn if this is issued prior to Draw Cmd and clearing the entire attachment
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001983 if (!cb_node->hasDrawCmd && (cb_node->activeRenderPassBeginInfo.renderArea.extent.width == pRects[0].rect.extent.width) &&
1984 (cb_node->activeRenderPassBeginInfo.renderArea.extent.height == pRects[0].rect.extent.height)) {
1985 // There are times where app needs to use ClearAttachments (generally when reusing a buffer inside of a render pass)
1986 // This warning should be made more specific. It'd be best to avoid triggering this test if it's a use that must call
1987 // CmdClearAttachments.
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001988 skip |= LogPerformanceWarning(commandBuffer, kVUID_BestPractices_DrawState_ClearCmdBeforeDraw,
1989 "vkCmdClearAttachments() issued on %s prior to any Draw Cmds. It is recommended you "
1990 "use RenderPass LOAD_OP_CLEAR on Attachments prior to any Draw.",
1991 report_data->FormatHandle(commandBuffer).c_str());
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001992 }
1993
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001994 // Check for uses of ClearAttachments along with LOAD_OP_LOAD,
1995 // as it can be more efficient to just use LOAD_OP_CLEAR
locke-lunargaecf2152020-05-12 17:15:41 -06001996 const RENDER_PASS_STATE* rp = cb_node->activeRenderPass.get();
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001997 if (rp) {
1998 const auto& subpass = rp->createInfo.pSubpasses[cb_node->activeSubpass];
1999
2000 for (uint32_t i = 0; i < attachmentCount; i++) {
2001 auto& attachment = pAttachments[i];
2002 if (attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
2003 uint32_t color_attachment = attachment.colorAttachment;
2004 uint32_t fb_attachment = subpass.pColorAttachments[color_attachment].attachment;
2005
2006 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2007 if (rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2008 skip |= LogPerformanceWarning(
2009 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2010 "vkCmdClearAttachments() issued on %s for color attachment #%u in this subpass, "
2011 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2012 "it is more efficient.",
2013 report_data->FormatHandle(commandBuffer).c_str(), color_attachment);
2014 }
2015 }
2016 }
2017
2018 if (subpass.pDepthStencilAttachment && attachment.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) {
2019 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
2020
2021 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2022 if (rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2023 skip |= LogPerformanceWarning(
2024 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2025 "vkCmdClearAttachments() issued on %s for the depth attachment in this subpass, "
2026 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2027 "it is more efficient.",
2028 report_data->FormatHandle(commandBuffer).c_str());
2029 }
2030 }
2031 }
2032
2033 if (subpass.pDepthStencilAttachment && attachment.aspectMask & VK_IMAGE_ASPECT_STENCIL_BIT) {
2034 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
2035
2036 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2037 if (rp->createInfo.pAttachments[fb_attachment].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2038 skip |= LogPerformanceWarning(
2039 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2040 "vkCmdClearAttachments() issued on %s for the stencil attachment in this subpass, "
2041 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2042 "it is more efficient.",
2043 report_data->FormatHandle(commandBuffer).c_str());
2044 }
2045 }
2046 }
2047 }
2048 }
2049
Camden Stockerf55721f2019-09-09 11:04:49 -06002050 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002051}
Attilio Provenzano02859b22020-02-27 14:17:28 +00002052
2053bool BestPractices::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
2054 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
2055 const VkImageResolve* pRegions) const {
2056 bool skip = false;
2057
2058 skip |= VendorCheckEnabled(kBPVendorArm) &&
2059 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage_ResolvingImage,
2060 "%s Attempting to use vkCmdResolveImage to resolve a multisampled image. "
2061 "This is a very slow and extremely bandwidth intensive path. "
2062 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
2063 VendorSpecificTag(kBPVendorArm));
2064
2065 return skip;
2066}
2067
Jeff Leger178b1e52020-10-05 12:22:23 -04002068bool BestPractices::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
2069 const VkResolveImageInfo2KHR* pResolveImageInfo) const {
2070 bool skip = false;
2071
2072 skip |= VendorCheckEnabled(kBPVendorArm) &&
2073 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2KHR_ResolvingImage,
2074 "%s Attempting to use vkCmdResolveImage2KHR to resolve a multisampled image. "
2075 "This is a very slow and extremely bandwidth intensive path. "
2076 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
2077 VendorSpecificTag(kBPVendorArm));
2078
2079 return skip;
2080}
2081
Attilio Provenzano02859b22020-02-27 14:17:28 +00002082bool BestPractices::PreCallValidateCreateSampler(VkDevice device, const VkSamplerCreateInfo* pCreateInfo,
2083 const VkAllocationCallbacks* pAllocator, VkSampler* pSampler) const {
2084 bool skip = false;
2085
2086 if (VendorCheckEnabled(kBPVendorArm)) {
2087 if ((pCreateInfo->addressModeU != pCreateInfo->addressModeV) || (pCreateInfo->addressModeV != pCreateInfo->addressModeW)) {
2088 skip |= LogPerformanceWarning(
2089 device, kVUID_BestPractices_CreateSampler_DifferentWrappingModes,
2090 "%s Creating a sampler object with wrapping modes which do not match (U = %u, V = %u, W = %u). "
2091 "This may cause reduced performance even if only U (1D image) or U/V wrapping modes (2D "
2092 "image) are actually used. If you need different wrapping modes, disregard this warning.",
2093 VendorSpecificTag(kBPVendorArm));
2094 }
2095
2096 if ((pCreateInfo->minLod != 0.0f) || (pCreateInfo->maxLod < VK_LOD_CLAMP_NONE)) {
2097 skip |= LogPerformanceWarning(
2098 device, kVUID_BestPractices_CreateSampler_LodClamping,
2099 "%s Creating a sampler object with LOD clamping (minLod = %f, maxLod = %f). This may cause reduced performance. "
2100 "Instead of clamping LOD in the sampler, consider using an VkImageView which restricts the mip-levels, set minLod "
2101 "to 0.0, and maxLod to VK_LOD_CLAMP_NONE.",
2102 VendorSpecificTag(kBPVendorArm), pCreateInfo->minLod, pCreateInfo->maxLod);
2103 }
2104
2105 if (pCreateInfo->mipLodBias != 0.0f) {
2106 skip |=
2107 LogPerformanceWarning(device, kVUID_BestPractices_CreateSampler_LodBias,
2108 "%s Creating a sampler object with LOD bias != 0.0 (%f). This will lead to less efficient "
2109 "descriptors being created and may cause reduced performance.",
2110 VendorSpecificTag(kBPVendorArm), pCreateInfo->mipLodBias);
2111 }
2112
2113 if ((pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
2114 pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
2115 pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER) &&
2116 (pCreateInfo->borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK)) {
2117 skip |= LogPerformanceWarning(
2118 device, kVUID_BestPractices_CreateSampler_BorderClampColor,
2119 "%s Creating a sampler object with border clamping and borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK. "
2120 "This will lead to less efficient descriptors being created and may cause reduced performance. "
2121 "If possible, use VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK as the border color.",
2122 VendorSpecificTag(kBPVendorArm));
2123 }
2124
2125 if (pCreateInfo->unnormalizedCoordinates) {
2126 skip |= LogPerformanceWarning(
2127 device, kVUID_BestPractices_CreateSampler_UnnormalizedCoordinates,
2128 "%s Creating a sampler object with unnormalized coordinates. This will lead to less efficient "
2129 "descriptors being created and may cause reduced performance.",
2130 VendorSpecificTag(kBPVendorArm));
2131 }
2132
2133 if (pCreateInfo->anisotropyEnable) {
2134 skip |= LogPerformanceWarning(
2135 device, kVUID_BestPractices_CreateSampler_Anisotropy,
2136 "%s Creating a sampler object with anisotropy. This will lead to less efficient descriptors being created "
2137 "and may cause reduced performance.",
2138 VendorSpecificTag(kBPVendorArm));
2139 }
2140 }
2141
2142 return skip;
2143}
Sam Walls8e77e4f2020-03-16 20:47:40 +00002144
2145void BestPractices::PostTransformLRUCacheModel::resize(size_t size) { _entries.resize(size); }
2146
2147bool BestPractices::PostTransformLRUCacheModel::query_cache(uint32_t value) {
2148 // look for a cache hit
2149 auto hit = std::find_if(_entries.begin(), _entries.end(), [value](const CacheEntry& entry) { return entry.value == value; });
2150 if (hit != _entries.end()) {
2151 // mark the cache hit as being most recently used
2152 hit->age = iteration++;
2153 return true;
2154 }
2155
2156 // if there's no cache hit, we need to model the entry being inserted into the cache
2157 CacheEntry new_entry = {value, iteration};
2158 if (iteration < static_cast<uint32_t>(std::distance(_entries.begin(), _entries.end()))) {
2159 // if there is still space left in the cache, use the next available slot
2160 *(_entries.begin() + iteration) = new_entry;
2161 } else {
2162 // otherwise replace the least recently used cache entry
2163 auto lru = std::min_element(_entries.begin(), hit, [](const CacheEntry& a, const CacheEntry& b) { return a.age < b.age; });
2164 *lru = new_entry;
2165 }
2166 iteration++;
2167 return false;
2168}
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002169
2170bool BestPractices::PreCallValidateAcquireNextImageKHR(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout,
2171 VkSemaphore semaphore, VkFence fence, uint32_t* pImageIndex) const {
2172 const auto swapchain_data = GetSwapchainState(swapchain);
2173 bool skip = false;
2174 if (swapchain_data && swapchain_data->images.size() == 0) {
2175 skip |= LogWarning(swapchain, kVUID_Core_DrawState_SwapchainImagesNotFound,
2176 "vkAcquireNextImageKHR: No images found to acquire from. Application probably did not call "
2177 "vkGetSwapchainImagesKHR after swapchain creation.");
2178 }
2179 return skip;
2180}
2181
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002182void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
2183 uint32_t* pQueueFamilyPropertyCount,
2184 VkQueueFamilyProperties* pQueueFamilyProperties) {
2185 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(physicalDevice, pQueueFamilyPropertyCount,
2186 pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002187 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002188 if (bp_pd_state) {
2189 if (!pQueueFamilyProperties) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002190 if (UNCALLED == bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState) {
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002191 bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState = QUERY_COUNT;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002192 }
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002193 } else { // Save queue family properties
2194 bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState = QUERY_DETAILS;
2195 }
2196 }
2197}
2198
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002199void BestPractices::PostCallRecordGetPhysicalDeviceFeatures(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures* pFeatures) {
2200 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002201 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2202 if (bp_pd_state) {
2203 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
2204 }
2205}
2206
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002207void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2(VkPhysicalDevice physicalDevice,
2208 VkPhysicalDeviceFeatures2* pFeatures) {
2209 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002210 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2211 if (bp_pd_state) {
2212 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
2213 }
2214}
2215
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002216void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2KHR(VkPhysicalDevice physicalDevice,
2217 VkPhysicalDeviceFeatures2* pFeatures) {
2218 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2KHR(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002219 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2220 if (bp_pd_state) {
2221 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
2222 }
2223}
2224
2225void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilitiesKHR(VkPhysicalDevice physicalDevice,
2226 VkSurfaceKHR surface,
2227 VkSurfaceCapabilitiesKHR* pSurfaceCapabilities,
2228 VkResult result) {
2229 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2230 if (bp_pd_state) {
2231 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
2232 }
2233}
2234
2235void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2KHR(
2236 VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
2237 VkSurfaceCapabilities2KHR* pSurfaceCapabilities, VkResult result) {
2238 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2239 if (bp_pd_state) {
2240 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
2241 }
2242}
2243
2244void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2EXT(VkPhysicalDevice physicalDevice,
2245 VkSurfaceKHR surface,
2246 VkSurfaceCapabilities2EXT* pSurfaceCapabilities,
2247 VkResult result) {
2248 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2249 if (bp_pd_state) {
2250 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
2251 }
2252}
2253
2254void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice physicalDevice,
2255 VkSurfaceKHR surface, uint32_t* pPresentModeCount,
2256 VkPresentModeKHR* pPresentModes, VkResult result) {
2257 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2258 if (bp_pd_data) {
2259 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfacePresentModesKHRState;
2260
2261 if (*pPresentModeCount) {
2262 if (call_state < QUERY_COUNT) {
2263 call_state = QUERY_COUNT;
2264 }
2265 }
2266 if (pPresentModes) {
2267 if (call_state < QUERY_DETAILS) {
2268 call_state = QUERY_DETAILS;
2269 }
2270 }
2271 }
2272}
2273
2274void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
2275 uint32_t* pSurfaceFormatCount,
2276 VkSurfaceFormatKHR* pSurfaceFormats, VkResult result) {
2277 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2278 if (bp_pd_data) {
2279 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState;
2280
2281 if (*pSurfaceFormatCount) {
2282 if (call_state < QUERY_COUNT) {
2283 call_state = QUERY_COUNT;
2284 }
2285 }
2286 if (pSurfaceFormats) {
2287 if (call_state < QUERY_DETAILS) {
2288 call_state = QUERY_DETAILS;
2289 }
2290 }
2291 }
2292}
2293
2294void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormats2KHR(VkPhysicalDevice physicalDevice,
2295 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
2296 uint32_t* pSurfaceFormatCount,
2297 VkSurfaceFormat2KHR* pSurfaceFormats, VkResult result) {
2298 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2299 if (bp_pd_data) {
2300 if (*pSurfaceFormatCount) {
2301 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_COUNT) {
2302 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_COUNT;
2303 }
2304 }
2305 if (pSurfaceFormats) {
2306 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_DETAILS) {
2307 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_DETAILS;
2308 }
2309 }
2310 }
2311}
2312
2313void BestPractices::ManualPostCallRecordGetPhysicalDeviceDisplayPlanePropertiesKHR(VkPhysicalDevice physicalDevice,
2314 uint32_t* pPropertyCount,
2315 VkDisplayPlanePropertiesKHR* pProperties,
2316 VkResult result) {
2317 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2318 if (bp_pd_data) {
2319 if (*pPropertyCount) {
2320 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_COUNT) {
2321 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_COUNT;
2322 }
2323 }
2324 if (pProperties) {
2325 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_DETAILS) {
2326 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_DETAILS;
2327 }
2328 }
2329 }
2330}
2331
2332void BestPractices::ManualPostCallRecordCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
2333 const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain,
2334 VkResult result) {
2335 if (VK_SUCCESS == result) {
2336 swapchain_bp_state_map.emplace(*pSwapchain, SWAPCHAIN_STATE_BP{});
2337 }
2338}
2339
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002340void BestPractices::PostCallRecordDestroySwapchainKHR(VkDevice device, VkSwapchainKHR swapchain,
2341 const VkAllocationCallbacks* pAllocator) {
2342 ValidationStateTracker::PostCallRecordDestroySwapchainKHR(device, swapchain, pAllocator);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002343 auto swapchain_state_itr = swapchain_bp_state_map.find(swapchain);
2344 if (swapchain_state_itr != swapchain_bp_state_map.cend()) {
2345 swapchain_bp_state_map.erase(swapchain_state_itr);
2346 }
2347}
2348
2349void BestPractices::ManualPostCallRecordGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain,
2350 uint32_t* pSwapchainImageCount, VkImage* pSwapchainImages,
2351 VkResult result) {
2352 auto swapchain_state_itr = swapchain_bp_state_map.find(swapchain);
2353 assert(swapchain_state_itr != swapchain_bp_state_map.cend());
2354 auto& swapchain_state = swapchain_state_itr->second;
2355 if (pSwapchainImages || *pSwapchainImageCount) {
2356 if (swapchain_state.vkGetSwapchainImagesKHRState < QUERY_DETAILS) {
2357 swapchain_state.vkGetSwapchainImagesKHRState = QUERY_DETAILS;
2358 }
2359 }
2360}
2361
2362void BestPractices::ManualPostCallRecordEnumeratePhysicalDevices(VkInstance instance, uint32_t* pPhysicalDeviceCount,
2363 VkPhysicalDevice* pPhysicalDevices, VkResult result) {
2364 if ((nullptr != pPhysicalDevices) && ((result == VK_SUCCESS || result == VK_INCOMPLETE))) {
2365 for (uint32_t i = 0; i < *pPhysicalDeviceCount; i++) {
2366 phys_device_bp_state_map.emplace(pPhysicalDevices[i], PHYSICAL_DEVICE_STATE_BP{});
2367 }
2368 }
2369}
2370
2371void BestPractices::ManualPostCallRecordCreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo*, const VkAllocationCallbacks*,
2372 VkDevice*, VkResult result) {
2373 if (VK_SUCCESS == result) {
2374 instance_device_bp_state = &phys_device_bp_state_map[gpu];
2375 }
2376}
2377
2378PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP(const VkPhysicalDevice& phys_device) {
2379 if (phys_device_bp_state_map.count(phys_device) > 0) {
2380 return &phys_device_bp_state_map.at(phys_device);
2381 } else {
2382 return nullptr;
2383 }
2384}
2385
2386const PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP(const VkPhysicalDevice& phys_device) const {
2387 if (phys_device_bp_state_map.count(phys_device) > 0) {
2388 return &phys_device_bp_state_map.at(phys_device);
2389 } else {
2390 return nullptr;
2391 }
2392}
2393
2394PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP() {
2395 auto bp_state = (reinterpret_cast<BestPractices*>(instance_state))->instance_device_bp_state;
2396 if (bp_state) {
2397 return bp_state;
2398 } else if (!bp_state && phys_device_bp_state_map.count(physical_device_state->phys_device) > 0) {
2399 return &phys_device_bp_state_map.at(physical_device_state->phys_device);
2400 } else {
2401 return nullptr;
2402 }
2403}
2404
2405const PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP() const {
2406 auto bp_state = (reinterpret_cast<BestPractices*>(instance_state))->instance_device_bp_state;
2407 if (bp_state) {
2408 return bp_state;
2409 } else if (!bp_state && phys_device_bp_state_map.count(physical_device_state->phys_device) > 0) {
2410 return &phys_device_bp_state_map.at(physical_device_state->phys_device);
2411 } else {
2412 return nullptr;
2413 }
2414}