blob: 5de9d45b22ec58d40afdd0b924d2e9feeec4682f [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);
Tony-LunarG767180f2020-04-23 14:03:59 -0600479 if (rp_state && !(pCreateInfo->flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT_KHR)) {
480 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,
569 VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS_KHR};
570 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);
Tony-LunarG5e60b852020-04-27 11:27:54 -0600754 if (!lvl_find_in_chain<VkBindImageMemorySwapchainInfoKHR>(pBindInfos[i].pNext)) {
755 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) {
Tony-LunarG767180f2020-04-23 14:03:59 -06001224 if (rp_state->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT_KHR) {
1225 const VkRenderPassAttachmentBeginInfo* rpabi =
1226 lvl_find_in_chain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
1227 if (rpabi) {
1228 skip = ValidateAttachments(rp_state->createInfo.ptr(), rpabi->attachmentCount, rpabi->pAttachments);
1229 }
1230 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001231 // Check if any attachments have LOAD operation on them
1232 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
1233 auto& attachment = rp_state->createInfo.pAttachments[att];
1234
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001235 bool attachment_has_readback = false;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001236 if (!FormatHasStencil(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001237 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001238 }
1239
1240 if (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001241 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001242 }
1243
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001244 bool attachment_needs_readback = false;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001245
1246 // Check if the attachment is actually used in any subpass on-tile
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001247 if (attachment_has_readback && RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1248 attachment_needs_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001249 }
1250
1251 // Using LOAD_OP_LOAD is expensive on tiled GPUs, so flag it as a potential improvement
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001252 if (attachment_needs_readback) {
Attilio Provenzano02859b22020-02-27 14:17:28 +00001253 skip |= VendorCheckEnabled(kBPVendorArm) &&
1254 LogPerformanceWarning(
1255 device, kVUID_BestPractices_BeginRenderPass_AttachmentNeedsReadback,
1256 "%s Attachment #%u in render pass has begun with VK_ATTACHMENT_LOAD_OP_LOAD.\n"
1257 "Submitting this renderpass will cause the driver to inject a readback of the attachment "
1258 "which will copy in total %u pixels (renderArea = { %d, %d, %u, %u }) to the tile buffer.",
1259 VendorSpecificTag(kBPVendorArm), att,
1260 pRenderPassBegin->renderArea.extent.width * pRenderPassBegin->renderArea.extent.height,
1261 pRenderPassBegin->renderArea.offset.x, pRenderPassBegin->renderArea.offset.y,
1262 pRenderPassBegin->renderArea.extent.width, pRenderPassBegin->renderArea.extent.height);
1263 }
1264 }
1265 }
1266
1267 return skip;
1268}
1269
1270bool BestPractices::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1271 VkSubpassContents contents) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001272 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1273 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001274 return skip;
1275}
1276
1277bool BestPractices::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1278 const VkRenderPassBeginInfo* pRenderPassBegin,
1279 const VkSubpassBeginInfoKHR* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001280 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1281 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001282 return skip;
1283}
1284
1285bool BestPractices::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1286 const VkSubpassBeginInfoKHR* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001287 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1288 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001289 return skip;
1290}
1291
Sam Walls0961ec02020-03-31 16:39:15 +01001292void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1293 const VkRenderPassBeginInfo* pRenderPassBegin) {
1294 auto prepass_state = cbDepthPrePassStates.find(commandBuffer);
1295
1296 // add the tracking state if it doesn't exist
1297 if (prepass_state == cbDepthPrePassStates.end()) {
1298 auto result = cbDepthPrePassStates.emplace(std::make_pair(commandBuffer, DepthPrePassState{}));
1299
1300 if (!result.second) return;
1301
1302 prepass_state = result.first;
1303 }
1304
1305 // reset the renderpass state
1306 prepass_state->second = {};
1307
1308 const auto* cb_state = GetCBState(commandBuffer);
locke-lunargaecf2152020-05-12 17:15:41 -06001309 const auto* rp_state = cb_state->activeRenderPass.get();
Sam Walls0961ec02020-03-31 16:39:15 +01001310
1311 // track depth / color attachment usage within the renderpass
1312 for (size_t i = 0; i < rp_state->createInfo.subpassCount; i++) {
1313 // record if depth/color attachments are in use for this renderpass
1314 if (rp_state->createInfo.pSubpasses[i].pDepthStencilAttachment != nullptr) prepass_state->second.depthAttachment = true;
1315
1316 if (rp_state->createInfo.pSubpasses[i].colorAttachmentCount > 0) prepass_state->second.colorAttachment = true;
1317 }
1318}
1319
1320void BestPractices::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1321 VkSubpassContents contents) {
1322 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1323 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
1324}
1325
1326void BestPractices::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1327 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1328 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1329 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1330}
1331
1332void BestPractices::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1333 const VkRenderPassBeginInfo* pRenderPassBegin,
1334 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1335 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1336 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1337}
1338
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001339// Generic function to handle validation for all CmdDraw* type functions
1340bool BestPractices::ValidateCmdDrawType(VkCommandBuffer cmd_buffer, const char* caller) const {
1341 bool skip = false;
1342 const CMD_BUFFER_STATE* cb_state = GetCBState(cmd_buffer);
1343 if (cb_state) {
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001344 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
1345 const auto* pipeline_state = cb_state->lastBound[lv_bind_point].pipeline_state;
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001346 const auto& current_vtx_bfr_binding_info = cb_state->current_vertex_buffer_binding_info.vertex_buffer_bindings;
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001347
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001348 // Verify vertex binding
1349 if (pipeline_state->vertex_binding_descriptions_.size() <= 0) {
1350 if ((!current_vtx_bfr_binding_info.empty()) && (!cb_state->vertex_buffer_used)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001351 skip |= LogPerformanceWarning(cb_state->commandBuffer, kVUID_BestPractices_DrawState_VtxIndexOutOfBounds,
1352 "Vertex buffers are bound to %s but no vertex buffers are attached to %s.",
1353 report_data->FormatHandle(cb_state->commandBuffer).c_str(),
1354 report_data->FormatHandle(pipeline_state->pipeline).c_str());
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001355 }
1356 }
1357 }
1358 return skip;
1359}
1360
Sam Walls0961ec02020-03-31 16:39:15 +01001361void BestPractices::RecordCmdDrawType(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
1362 if (VendorCheckEnabled(kBPVendorArm)) {
1363 RecordCmdDrawTypeArm(cmd_buffer, draw_count, caller);
1364 }
1365}
1366
1367void BestPractices::RecordCmdDrawTypeArm(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
1368 auto prepass_state = cbDepthPrePassStates.find(cmd_buffer);
1369 if (prepass_state != cbDepthPrePassStates.end() && draw_count >= kDepthPrePassMinDrawCountArm) {
1370 if (prepass_state->second.depthOnly) prepass_state->second.numDrawCallsDepthOnly++;
1371
1372 if (prepass_state->second.depthEqualComparison) prepass_state->second.numDrawCallsDepthEqualCompare++;
1373 }
1374}
1375
Camden5b184be2019-08-13 07:50:19 -06001376bool BestPractices::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001377 uint32_t firstVertex, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06001378 bool skip = false;
1379
1380 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001381 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
1382 "Warning: You are calling vkCmdDraw() with an instanceCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001383 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDraw()");
Camden5b184be2019-08-13 07:50:19 -06001384 }
1385
1386 return skip;
1387}
1388
Sam Walls0961ec02020-03-31 16:39:15 +01001389void BestPractices::PostCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
1390 uint32_t firstVertex, uint32_t firstInstance) {
1391 StateTracker::PostCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
1392 RecordCmdDrawType(commandBuffer, vertexCount * instanceCount, "vkCmdDraw()");
1393}
1394
Camden5b184be2019-08-13 07:50:19 -06001395bool BestPractices::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001396 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06001397 bool skip = false;
1398
1399 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001400 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
1401 "Warning: You are calling vkCmdDrawIndexed() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06001402 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001403 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexed()");
1404
Attilio Provenzano02859b22020-02-27 14:17:28 +00001405 // Check if we reached the limit for small indexed draw calls.
1406 // Note that we cannot update the draw call count here, so we do it in PreCallRecordCmdDrawIndexed.
1407 const CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
1408 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices &&
1409 (cmd_state->small_indexed_draw_call_count == kMaxSmallIndexedDrawcalls - 1)) {
1410 skip |= VendorCheckEnabled(kBPVendorArm) &&
1411 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_ManySmallIndexedDrawcalls,
1412 "The command buffer contains many small indexed drawcalls "
1413 "(at least %u drawcalls with less than %u indices each). This may cause pipeline bubbles. "
1414 "You can try batching drawcalls or instancing when applicable.",
1415 VendorSpecificTag(kBPVendorArm), kMaxSmallIndexedDrawcalls, kSmallIndexedDrawcallIndices);
1416 }
1417
Sam Walls8e77e4f2020-03-16 20:47:40 +00001418 if (VendorCheckEnabled(kBPVendorArm)) {
1419 ValidateIndexBufferArm(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
1420 }
1421
1422 return skip;
1423}
1424
1425bool BestPractices::ValidateIndexBufferArm(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1426 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
1427 bool skip = false;
1428
1429 // check for sparse/underutilised index buffer, and post-transform cache thrashing
1430 const auto* cmd_state = GetCBState(commandBuffer);
1431 if (cmd_state == nullptr) return skip;
1432
locke-lunarg1ae57d62020-11-18 10:49:19 -07001433 const auto* ib_state = cmd_state->index_buffer_binding.buffer_state.get();
1434 if (ib_state == nullptr || cmd_state->index_buffer_binding.buffer_state->destroyed) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00001435
1436 const VkIndexType ib_type = cmd_state->index_buffer_binding.index_type;
1437 const auto& ib_mem_state = *ib_state->binding.mem_state;
1438 const VkDeviceSize ib_mem_offset = ib_mem_state.mapped_range.offset;
1439 const void* ib_mem = ib_mem_state.p_driver_data;
1440 bool primitive_restart_enable = false;
1441
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001442 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
1443 const auto& pipeline_binding_iter = cmd_state->lastBound[lv_bind_point];
1444 const auto* pipeline_state = pipeline_binding_iter.pipeline_state;
Sam Walls8e77e4f2020-03-16 20:47:40 +00001445
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001446 if (pipeline_state != nullptr && pipeline_state->graphicsPipelineCI.pInputAssemblyState != nullptr) {
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001447 primitive_restart_enable = pipeline_state->graphicsPipelineCI.pInputAssemblyState->primitiveRestartEnable == VK_TRUE;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001448 }
Sam Walls8e77e4f2020-03-16 20:47:40 +00001449
1450 // 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 -06001451 if (ib_mem && pipeline_binding_iter.IsUsing()) {
Sam Walls8e77e4f2020-03-16 20:47:40 +00001452 uint32_t scan_stride;
1453 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1454 scan_stride = sizeof(uint8_t);
1455 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1456 scan_stride = sizeof(uint16_t);
1457 } else {
1458 scan_stride = sizeof(uint32_t);
1459 }
1460
1461 const uint8_t* scan_begin = static_cast<const uint8_t*>(ib_mem) + ib_mem_offset + firstIndex * scan_stride;
1462 const uint8_t* scan_end = scan_begin + indexCount * scan_stride;
1463
1464 // Min and max are important to track for some Mali architectures. In older Mali devices without IDVS, all
1465 // vertices corresponding to indices between the minimum and maximum may be loaded, and possibly shaded,
1466 // irrespective of whether or not they're part of the draw call.
1467
1468 // start with minimum as 0xFFFFFFFF and adjust to indices in the buffer
1469 uint32_t min_index = ~0u;
1470 // start with maximum as 0 and adjust to indices in the buffer
1471 uint32_t max_index = 0u;
1472
1473 // first scan-through, we're looking to simulate a model LRU post-transform cache, estimating the number of vertices shaded
1474 // for the given index buffer
1475 uint32_t vertex_shade_count = 0;
1476
1477 PostTransformLRUCacheModel post_transform_cache;
1478
1479 // The size of the cache being modelled positively correlates with how much behaviour it can capture about
1480 // arbitrary ground-truth hardware/architecture cache behaviour. I.e. it's a good solution when we don't know the
1481 // target architecture.
1482 // However, modelling a post-transform cache with more than 32 elements gives diminishing returns in practice.
1483 // http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
1484 post_transform_cache.resize(32);
1485
1486 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
1487 uint32_t scan_index;
1488 uint32_t primitive_restart_value;
1489 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1490 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
1491 primitive_restart_value = 0xFF;
1492 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1493 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
1494 primitive_restart_value = 0xFFFF;
1495 } else {
1496 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
1497 primitive_restart_value = 0xFFFFFFFF;
1498 }
1499
1500 max_index = std::max(max_index, scan_index);
1501 min_index = std::min(min_index, scan_index);
1502
1503 if (!primitive_restart_enable || scan_index != primitive_restart_value) {
1504 bool in_cache = post_transform_cache.query_cache(scan_index);
1505 // if the shaded vertex corresponding to the index is not in the PT-cache, we need to shade again
1506 if (!in_cache) vertex_shade_count++;
1507 }
1508 }
1509
1510 // 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 +01001511 // 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
1512 if (max_index < min_index || max_index == min_index) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00001513
1514 if (max_index - min_index >= indexCount) {
Mark Young0ec6b062020-11-19 15:32:17 -07001515 skip |=
1516 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
1517 "%s The indices which were specified for the draw call only utilise approximately %.02f%% of "
1518 "index buffer value range. Arm Mali architectures before G71 do not have IDVS (Index-Driven "
1519 "Vertex Shading), meaning all vertices corresponding to indices between the minimum and "
1520 "maximum would be loaded, and possibly shaded, whether or not they are used.",
1521 VendorSpecificTag(kBPVendorArm),
1522 (static_cast<float>(indexCount) / static_cast<float>(max_index - min_index)) * 100.0f);
Sam Walls8e77e4f2020-03-16 20:47:40 +00001523 return skip;
1524 }
1525
1526 // use a dynamic vector of bitsets as a memory-compact representation of which indices are included in the draw call
1527 // 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 +01001528 const size_t refs_per_bucket = 64;
1529 std::vector<std::bitset<refs_per_bucket>> vertex_reference_buckets;
1530
1531 const uint32_t n_indices = max_index - min_index + 1;
1532 const uint32_t n_buckets = (n_indices / static_cast<uint32_t>(refs_per_bucket)) +
1533 ((n_indices % static_cast<uint32_t>(refs_per_bucket)) != 0 ? 1 : 0);
1534
1535 // there needs to be at least one bitset to store a set of indices smaller than n_buckets
1536 vertex_reference_buckets.resize(std::max(1u, n_buckets));
Sam Walls8e77e4f2020-03-16 20:47:40 +00001537
1538 // To avoid using too much memory, we run over the indices again.
1539 // Knowing the size from the last scan allows us to record index usage with bitsets
1540 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
1541 uint32_t scan_index;
1542 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1543 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
1544 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1545 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
1546 } else {
1547 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
1548 }
1549 // keep track of the set of all indices used to reference vertices in the draw call
1550 size_t index_offset = scan_index - min_index;
Sam Walls61b06892020-07-23 16:20:50 +01001551 size_t bitset_bucket_index = index_offset / refs_per_bucket;
1552 uint64_t used_indices = 1ull << ((index_offset % refs_per_bucket) & 0xFFFFFFFFu);
Sam Walls8e77e4f2020-03-16 20:47:40 +00001553 vertex_reference_buckets[bitset_bucket_index] |= used_indices;
1554 }
1555
1556 uint32_t vertex_reference_count = 0;
1557 for (const auto& bitset : vertex_reference_buckets) {
1558 vertex_reference_count += static_cast<uint32_t>(bitset.count());
1559 }
1560
1561 // 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 -07001562 float utilization = static_cast<float>(vertex_reference_count) / static_cast<float>(max_index - min_index + 1);
Sam Walls8e77e4f2020-03-16 20:47:40 +00001563 // 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 -07001564 float cache_hit_rate = static_cast<float>(vertex_reference_count) / static_cast<float>(vertex_shade_count);
Sam Walls8e77e4f2020-03-16 20:47:40 +00001565
1566 if (utilization < 0.5f) {
1567 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
1568 "%s The indices which were specified for the draw call only utilise approximately "
1569 "%.02f%% of the bound vertex buffer.",
1570 VendorSpecificTag(kBPVendorArm), utilization);
1571 }
1572
1573 if (cache_hit_rate <= 0.5f) {
1574 skip |=
1575 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_PostTransformCacheThrashing,
1576 "%s The indices which were specified for the draw call are estimated to cause thrashing of "
1577 "the post-transform vertex cache, with a hit-rate of %.02f%%. "
1578 "I.e. the ordering of the index buffer may not make optimal use of indices associated with "
1579 "recently shaded vertices.",
1580 VendorSpecificTag(kBPVendorArm), cache_hit_rate * 100.0f);
1581 }
1582 }
1583
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001584 return skip;
1585}
1586
Attilio Provenzano02859b22020-02-27 14:17:28 +00001587void BestPractices::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1588 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
1589 ValidationStateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset,
1590 firstInstance);
1591
1592 CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
1593 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices) {
1594 cmd_state->small_indexed_draw_call_count++;
1595 }
1596}
1597
Sam Walls0961ec02020-03-31 16:39:15 +01001598void BestPractices::PostCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1599 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
1600 StateTracker::PostCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
1601 RecordCmdDrawType(commandBuffer, indexCount * instanceCount, "vkCmdDrawIndexed()");
1602}
1603
sfricke-samsung681ab7b2020-10-29 01:53:35 -07001604bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
1605 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
1606 uint32_t maxDrawCount, uint32_t stride) const {
1607 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCount()");
1608
1609 return skip;
1610}
1611
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001612bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
1613 VkDeviceSize offset, VkBuffer countBuffer,
1614 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
1615 uint32_t stride) const {
1616 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCountKHR()");
Camden5b184be2019-08-13 07:50:19 -06001617
1618 return skip;
1619}
1620
1621bool BestPractices::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001622 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06001623 bool skip = false;
1624
1625 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001626 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
1627 "Warning: You are calling vkCmdDrawIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001628 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirect()");
Camden5b184be2019-08-13 07:50:19 -06001629 }
1630
1631 return skip;
1632}
1633
Sam Walls0961ec02020-03-31 16:39:15 +01001634void BestPractices::PostCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
1635 uint32_t count, uint32_t stride) {
1636 StateTracker::PostCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, count, stride);
1637 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndirect()");
1638}
1639
Camden5b184be2019-08-13 07:50:19 -06001640bool BestPractices::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001641 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06001642 bool skip = false;
1643
1644 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001645 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
1646 "Warning: You are calling vkCmdDrawIndexedIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001647 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirect()");
Camden5b184be2019-08-13 07:50:19 -06001648 }
1649
1650 return skip;
1651}
1652
Sam Walls0961ec02020-03-31 16:39:15 +01001653void BestPractices::PostCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
1654 uint32_t count, uint32_t stride) {
1655 StateTracker::PostCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, count, stride);
1656 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndexedIndirect()");
1657}
1658
Camden5b184be2019-08-13 07:50:19 -06001659bool BestPractices::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t groupCountX, uint32_t groupCountY,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001660 uint32_t groupCountZ) const {
Camden5b184be2019-08-13 07:50:19 -06001661 bool skip = false;
1662
1663 if ((groupCountX == 0) || (groupCountY == 0) || (groupCountZ == 0)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001664 skip |= LogWarning(device, kVUID_BestPractices_CmdDispatch_GroupCountZero,
1665 "Warning: You are calling vkCmdDispatch() while one or more groupCounts are zero (groupCountX = %" PRIu32
1666 ", groupCountY = %" PRIu32 ", groupCountZ = %" PRIu32 ").",
1667 groupCountX, groupCountY, groupCountZ);
Camden5b184be2019-08-13 07:50:19 -06001668 }
1669
1670 return skip;
1671}
Camden83a9c372019-08-14 11:41:38 -06001672
Sam Walls0961ec02020-03-31 16:39:15 +01001673bool BestPractices::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
1674 bool skip = false;
1675
1676 skip |= StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
1677
1678 auto prepass_state = cbDepthPrePassStates.find(commandBuffer);
1679
1680 if (prepass_state == cbDepthPrePassStates.end()) return skip;
1681
1682 bool uses_depth = (prepass_state->second.depthAttachment || prepass_state->second.colorAttachment) &&
1683 prepass_state->second.numDrawCallsDepthEqualCompare >= kDepthPrePassNumDrawCallsArm &&
1684 prepass_state->second.numDrawCallsDepthOnly >= kDepthPrePassNumDrawCallsArm;
1685 if (uses_depth) {
1686 skip |= LogPerformanceWarning(
1687 device, kVUID_BestPractices_EndRenderPass_DepthPrePassUsage,
1688 "%s Depth pre-passes may be in use. In general, this is not recommended, as in Arm Mali GPUs since "
1689 "Mali-T620, Forward Pixel Killing (FPK) can already perform automatic hidden surface removal; in which "
1690 "case, using depth pre-passes for hidden surface removal may worsen performance.",
1691 VendorSpecificTag(kBPVendorArm));
1692 }
1693
1694 return skip;
1695}
1696
Camden Stocker9c051442019-11-06 14:28:43 -08001697bool BestPractices::ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(VkPhysicalDevice physicalDevice,
1698 const char* api_name) const {
1699 bool skip = false;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001700 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
Camden Stocker9c051442019-11-06 14:28:43 -08001701
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001702 if (bp_pd_state) {
1703 if (bp_pd_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState == UNCALLED) {
1704 skip |= LogWarning(physicalDevice, kVUID_BestPractices_DisplayPlane_PropertiesNotCalled,
1705 "Potential problem with calling %s() without first retrieving properties from "
1706 "vkGetPhysicalDeviceDisplayPlanePropertiesKHR or vkGetPhysicalDeviceDisplayPlaneProperties2KHR.",
1707 api_name);
1708 }
Camden Stocker9c051442019-11-06 14:28:43 -08001709 }
1710
1711 return skip;
1712}
1713
Camden83a9c372019-08-14 11:41:38 -06001714bool BestPractices::PreCallValidateGetDisplayPlaneSupportedDisplaysKHR(VkPhysicalDevice physicalDevice, uint32_t planeIndex,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001715 uint32_t* pDisplayCount, VkDisplayKHR* pDisplays) const {
Camden83a9c372019-08-14 11:41:38 -06001716 bool skip = false;
1717
Camden Stocker9c051442019-11-06 14:28:43 -08001718 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneSupportedDisplaysKHR");
Camden83a9c372019-08-14 11:41:38 -06001719
Camden Stocker9c051442019-11-06 14:28:43 -08001720 return skip;
1721}
1722
1723bool BestPractices::PreCallValidateGetDisplayPlaneCapabilitiesKHR(VkPhysicalDevice physicalDevice, VkDisplayModeKHR mode,
1724 uint32_t planeIndex,
1725 VkDisplayPlaneCapabilitiesKHR* pCapabilities) const {
1726 bool skip = false;
1727
1728 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilitiesKHR");
1729
1730 return skip;
1731}
1732
1733bool BestPractices::PreCallValidateGetDisplayPlaneCapabilities2KHR(VkPhysicalDevice physicalDevice,
1734 const VkDisplayPlaneInfo2KHR* pDisplayPlaneInfo,
1735 VkDisplayPlaneCapabilities2KHR* pCapabilities) const {
1736 bool skip = false;
1737
1738 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilities2KHR");
Camden83a9c372019-08-14 11:41:38 -06001739
1740 return skip;
1741}
Camden05de2d42019-08-19 10:23:56 -06001742
1743bool BestPractices::PreCallValidateGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain, uint32_t* pSwapchainImageCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001744 VkImage* pSwapchainImages) const {
Camden05de2d42019-08-19 10:23:56 -06001745 bool skip = false;
1746
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001747 auto swapchain_state_itr = swapchain_bp_state_map.find(swapchain);
Camden05de2d42019-08-19 10:23:56 -06001748
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001749 if ((swapchain_state_itr != swapchain_bp_state_map.cend()) && pSwapchainImages) {
Camden05de2d42019-08-19 10:23:56 -06001750 // Compare the preliminary value of *pSwapchainImageCount with the value this time:
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001751 if (swapchain_state_itr->second.vkGetSwapchainImagesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001752 skip |=
1753 LogWarning(device, kVUID_Core_Swapchain_PriorCount,
1754 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImageCount; but no prior positive value has "
1755 "been seen for pSwapchainImages.");
Camden05de2d42019-08-19 10:23:56 -06001756 }
1757 }
1758
1759 return skip;
1760}
1761
1762// Common function to handle validation for GetPhysicalDeviceQueueFamilyProperties & 2KHR version
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001763bool BestPractices::ValidateCommonGetPhysicalDeviceQueueFamilyProperties(const PHYSICAL_DEVICE_STATE* pd_state,
1764 uint32_t requested_queue_family_property_count,
1765 bool qfp_null, const char* caller_name) const {
Camden05de2d42019-08-19 10:23:56 -06001766 bool skip = false;
1767 if (!qfp_null) {
1768 // 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 -06001769 const auto* bp_pd_state = GetPhysicalDeviceStateBP(pd_state->phys_device);
1770 if (bp_pd_state) {
1771 if (UNCALLED == bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState) {
1772 skip |= LogWarning(
1773 pd_state->phys_device, kVUID_Core_DevLimit_MissingQueryCount,
1774 "%s is called with non-NULL pQueueFamilyProperties before obtaining pQueueFamilyPropertyCount. It is "
1775 "recommended "
1776 "to first call %s with NULL pQueueFamilyProperties in order to obtain the maximal pQueueFamilyPropertyCount.",
1777 caller_name, caller_name);
1778 // Then verify that pCount that is passed in on second call matches what was returned
1779 } else if (pd_state->queue_family_known_count != requested_queue_family_property_count) {
1780 skip |=
1781 LogWarning(pd_state->phys_device, kVUID_Core_DevLimit_CountMismatch,
1782 "%s is called with non-NULL pQueueFamilyProperties and pQueueFamilyPropertyCount value %" PRIu32
1783 ", but the largest previously returned pQueueFamilyPropertyCount for this physicalDevice is %" PRIu32
1784 ". It is recommended to instead receive all the properties by calling %s with "
1785 "pQueueFamilyPropertyCount that was "
1786 "previously obtained by calling %s with NULL pQueueFamilyProperties.",
1787 caller_name, requested_queue_family_property_count, pd_state->queue_family_known_count, caller_name,
1788 caller_name);
1789 }
Camden05de2d42019-08-19 10:23:56 -06001790 }
1791 }
1792
1793 return skip;
1794}
1795
Jeff Bolz5c801d12019-10-09 10:38:45 -05001796bool BestPractices::PreCallValidateBindAccelerationStructureMemoryNV(
1797 VkDevice device, uint32_t bindInfoCount, const VkBindAccelerationStructureMemoryInfoNV* pBindInfos) const {
Camden Stocker82510582019-09-03 14:00:16 -06001798 bool skip = false;
1799
1800 for (uint32_t i = 0; i < bindInfoCount; i++) {
sourav parmarcd5fb182020-07-17 12:58:44 -07001801 const ACCELERATION_STRUCTURE_STATE* as_state = GetAccelerationStructureStateNV(pBindInfos[i].accelerationStructure);
Camden Stocker82510582019-09-03 14:00:16 -06001802 if (!as_state->memory_requirements_checked) {
1803 // There's not an explicit requirement in the spec to call vkGetImageMemoryRequirements() prior to calling
1804 // BindAccelerationStructureMemoryNV but it's implied in that memory being bound must conform with
1805 // VkAccelerationStructureMemoryRequirementsInfoNV from vkGetAccelerationStructureMemoryRequirementsNV
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001806 skip |= LogWarning(
1807 device, kVUID_BestPractices_BindAccelNV_NoMemReqQuery,
Camden Stocker82510582019-09-03 14:00:16 -06001808 "vkBindAccelerationStructureMemoryNV(): "
1809 "Binding memory to %s but vkGetAccelerationStructureMemoryRequirementsNV() has not been called on that structure.",
1810 report_data->FormatHandle(pBindInfos[i].accelerationStructure).c_str());
1811 }
1812 }
1813
1814 return skip;
1815}
1816
Camden05de2d42019-08-19 10:23:56 -06001817bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
1818 uint32_t* pQueueFamilyPropertyCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001819 VkQueueFamilyProperties* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06001820 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1821 assert(physical_device_state);
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001822 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
Camden05de2d42019-08-19 10:23:56 -06001823 (nullptr == pQueueFamilyProperties),
1824 "vkGetPhysicalDeviceQueueFamilyProperties()");
1825}
1826
Jeff Bolz5c801d12019-10-09 10:38:45 -05001827bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2(
1828 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount,
1829 VkQueueFamilyProperties2KHR* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06001830 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1831 assert(physical_device_state);
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001832 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
Camden05de2d42019-08-19 10:23:56 -06001833 (nullptr == pQueueFamilyProperties),
1834 "vkGetPhysicalDeviceQueueFamilyProperties2()");
1835}
1836
Jeff Bolz5c801d12019-10-09 10:38:45 -05001837bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2KHR(
1838 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount,
1839 VkQueueFamilyProperties2KHR* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06001840 auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1841 assert(physical_device_state);
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001842 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
Camden05de2d42019-08-19 10:23:56 -06001843 (nullptr == pQueueFamilyProperties),
1844 "vkGetPhysicalDeviceQueueFamilyProperties2KHR()");
1845}
1846
1847bool BestPractices::PreCallValidateGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
1848 uint32_t* pSurfaceFormatCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001849 VkSurfaceFormatKHR* pSurfaceFormats) const {
Camden05de2d42019-08-19 10:23:56 -06001850 if (!pSurfaceFormats) return false;
1851 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001852 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
1853 const auto& call_state = bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState;
Camden05de2d42019-08-19 10:23:56 -06001854 bool skip = false;
1855 if (call_state == UNCALLED) {
1856 // Since we haven't recorded a preliminary value of *pSurfaceFormatCount, that likely means that the application didn't
1857 // previously call this function with a NULL value of pSurfaceFormats:
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001858 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_MustQueryCount,
1859 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount; but no prior "
1860 "positive value has been seen for pSurfaceFormats.");
Camden05de2d42019-08-19 10:23:56 -06001861 } else {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001862 auto prev_format_count = static_cast<uint32_t>(physical_device_state->surface_formats.size());
Peter Chene191bd72019-09-16 13:04:37 -04001863 if (*pSurfaceFormatCount > prev_format_count) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001864 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_CountMismatch,
1865 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount, and with "
1866 "pSurfaceFormats set to a value (%u) that is greater than the value (%u) that was returned "
1867 "when pSurfaceFormatCount was NULL.",
1868 *pSurfaceFormatCount, prev_format_count);
Camden05de2d42019-08-19 10:23:56 -06001869 }
1870 }
1871 return skip;
1872}
Camden Stocker23cc47d2019-09-03 14:53:57 -06001873
1874bool BestPractices::PreCallValidateQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001875 VkFence fence) const {
Camden Stocker23cc47d2019-09-03 14:53:57 -06001876 bool skip = false;
1877
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001878 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
1879 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
Camden Stocker23cc47d2019-09-03 14:53:57 -06001880 // 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 -05001881 std::unordered_set<const IMAGE_STATE*> sparse_images;
1882 // Track images getting metadata bound by this call in a set, it'll be recorded into the image_state
1883 // in RecordQueueBindSparse.
1884 std::unordered_set<const IMAGE_STATE*> sparse_images_with_metadata;
Camden Stocker23cc47d2019-09-03 14:53:57 -06001885 // 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 -07001886 for (uint32_t i = 0; i < bind_info.imageBindCount; ++i) {
1887 const auto& image_bind = bind_info.pImageBinds[i];
Camden Stocker23cc47d2019-09-03 14:53:57 -06001888 auto image_state = GetImageState(image_bind.image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001889 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06001890 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001891 }
Camden Stocker23cc47d2019-09-03 14:53:57 -06001892 sparse_images.insert(image_state);
1893 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
1894 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
1895 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001896 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1897 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
1898 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
1899 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001900 }
1901 }
1902 if (!image_state->memory_requirements_checked) {
1903 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001904 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1905 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
1906 "vkGetImageMemoryRequirements() to retrieve requirements.",
1907 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001908 }
1909 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001910 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
1911 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
1912 auto image_state = GetImageState(bind_info.pImageOpaqueBinds[i].image);
1913 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06001914 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001915 }
Camden Stocker23cc47d2019-09-03 14:53:57 -06001916 sparse_images.insert(image_state);
1917 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
1918 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
1919 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001920 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1921 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
1922 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
1923 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001924 }
1925 }
1926 if (!image_state->memory_requirements_checked) {
1927 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001928 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1929 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
1930 "vkGetImageMemoryRequirements() to retrieve requirements.",
1931 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001932 }
1933 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
1934 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001935 sparse_images_with_metadata.insert(image_state);
Camden Stocker23cc47d2019-09-03 14:53:57 -06001936 }
1937 }
1938 }
1939 for (const auto& sparse_image_state : sparse_images) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001940 if (sparse_image_state->sparse_metadata_required && !sparse_image_state->sparse_metadata_bound &&
1941 sparse_images_with_metadata.find(sparse_image_state) == sparse_images_with_metadata.end()) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06001942 // Warn if sparse image binding metadata required for image with sparse binding, but metadata not bound
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001943 skip |= LogWarning(sparse_image_state->image, kVUID_Core_MemTrack_InvalidState,
1944 "vkQueueBindSparse(): Binding sparse memory to %s which requires a metadata aspect but no "
1945 "binding with VK_SPARSE_MEMORY_BIND_METADATA_BIT set was made.",
1946 report_data->FormatHandle(sparse_image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001947 }
1948 }
1949 }
1950
1951 return skip;
1952}
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001953
Mark Lobodzinski84101d72020-04-24 09:43:48 -06001954void BestPractices::ManualPostCallRecordQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
1955 VkFence fence, VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07001956 if (result != VK_SUCCESS) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07001957 return;
1958 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001959
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001960 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
1961 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
1962 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
1963 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
1964 auto image_state = GetImageState(bind_info.pImageOpaqueBinds[i].image);
1965 if (!image_state) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001966 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001967 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001968 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
1969 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
1970 image_state->sparse_metadata_bound = true;
1971 }
1972 }
1973 }
1974 }
1975}
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001976
1977bool BestPractices::PreCallValidateCmdClearAttachments(VkCommandBuffer commandBuffer, uint32_t attachmentCount,
Camden Stockerf55721f2019-09-09 11:04:49 -06001978 const VkClearAttachment* pAttachments, uint32_t rectCount,
1979 const VkClearRect* pRects) const {
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001980 bool skip = false;
1981 const CMD_BUFFER_STATE* cb_node = GetCBState(commandBuffer);
1982 if (!cb_node) return skip;
1983
Camden Stockerf55721f2019-09-09 11:04:49 -06001984 // Warn if this is issued prior to Draw Cmd and clearing the entire attachment
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001985 if (!cb_node->hasDrawCmd && (cb_node->activeRenderPassBeginInfo.renderArea.extent.width == pRects[0].rect.extent.width) &&
1986 (cb_node->activeRenderPassBeginInfo.renderArea.extent.height == pRects[0].rect.extent.height)) {
1987 // There are times where app needs to use ClearAttachments (generally when reusing a buffer inside of a render pass)
1988 // This warning should be made more specific. It'd be best to avoid triggering this test if it's a use that must call
1989 // CmdClearAttachments.
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001990 skip |= LogPerformanceWarning(commandBuffer, kVUID_BestPractices_DrawState_ClearCmdBeforeDraw,
1991 "vkCmdClearAttachments() issued on %s prior to any Draw Cmds. It is recommended you "
1992 "use RenderPass LOAD_OP_CLEAR on Attachments prior to any Draw.",
1993 report_data->FormatHandle(commandBuffer).c_str());
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001994 }
1995
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001996 // Check for uses of ClearAttachments along with LOAD_OP_LOAD,
1997 // as it can be more efficient to just use LOAD_OP_CLEAR
locke-lunargaecf2152020-05-12 17:15:41 -06001998 const RENDER_PASS_STATE* rp = cb_node->activeRenderPass.get();
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001999 if (rp) {
2000 const auto& subpass = rp->createInfo.pSubpasses[cb_node->activeSubpass];
2001
2002 for (uint32_t i = 0; i < attachmentCount; i++) {
2003 auto& attachment = pAttachments[i];
2004 if (attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
2005 uint32_t color_attachment = attachment.colorAttachment;
2006 uint32_t fb_attachment = subpass.pColorAttachments[color_attachment].attachment;
2007
2008 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2009 if (rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2010 skip |= LogPerformanceWarning(
2011 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2012 "vkCmdClearAttachments() issued on %s for color attachment #%u in this subpass, "
2013 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2014 "it is more efficient.",
2015 report_data->FormatHandle(commandBuffer).c_str(), color_attachment);
2016 }
2017 }
2018 }
2019
2020 if (subpass.pDepthStencilAttachment && attachment.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) {
2021 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
2022
2023 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2024 if (rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2025 skip |= LogPerformanceWarning(
2026 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2027 "vkCmdClearAttachments() issued on %s for the depth attachment in this subpass, "
2028 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2029 "it is more efficient.",
2030 report_data->FormatHandle(commandBuffer).c_str());
2031 }
2032 }
2033 }
2034
2035 if (subpass.pDepthStencilAttachment && attachment.aspectMask & VK_IMAGE_ASPECT_STENCIL_BIT) {
2036 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
2037
2038 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2039 if (rp->createInfo.pAttachments[fb_attachment].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2040 skip |= LogPerformanceWarning(
2041 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2042 "vkCmdClearAttachments() issued on %s for the stencil attachment in this subpass, "
2043 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2044 "it is more efficient.",
2045 report_data->FormatHandle(commandBuffer).c_str());
2046 }
2047 }
2048 }
2049 }
2050 }
2051
Camden Stockerf55721f2019-09-09 11:04:49 -06002052 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002053}
Attilio Provenzano02859b22020-02-27 14:17:28 +00002054
2055bool BestPractices::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
2056 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
2057 const VkImageResolve* pRegions) const {
2058 bool skip = false;
2059
2060 skip |= VendorCheckEnabled(kBPVendorArm) &&
2061 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage_ResolvingImage,
2062 "%s Attempting to use vkCmdResolveImage to resolve a multisampled image. "
2063 "This is a very slow and extremely bandwidth intensive path. "
2064 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
2065 VendorSpecificTag(kBPVendorArm));
2066
2067 return skip;
2068}
2069
Jeff Leger178b1e52020-10-05 12:22:23 -04002070bool BestPractices::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
2071 const VkResolveImageInfo2KHR* pResolveImageInfo) const {
2072 bool skip = false;
2073
2074 skip |= VendorCheckEnabled(kBPVendorArm) &&
2075 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2KHR_ResolvingImage,
2076 "%s Attempting to use vkCmdResolveImage2KHR to resolve a multisampled image. "
2077 "This is a very slow and extremely bandwidth intensive path. "
2078 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
2079 VendorSpecificTag(kBPVendorArm));
2080
2081 return skip;
2082}
2083
Attilio Provenzano02859b22020-02-27 14:17:28 +00002084bool BestPractices::PreCallValidateCreateSampler(VkDevice device, const VkSamplerCreateInfo* pCreateInfo,
2085 const VkAllocationCallbacks* pAllocator, VkSampler* pSampler) const {
2086 bool skip = false;
2087
2088 if (VendorCheckEnabled(kBPVendorArm)) {
2089 if ((pCreateInfo->addressModeU != pCreateInfo->addressModeV) || (pCreateInfo->addressModeV != pCreateInfo->addressModeW)) {
2090 skip |= LogPerformanceWarning(
2091 device, kVUID_BestPractices_CreateSampler_DifferentWrappingModes,
2092 "%s Creating a sampler object with wrapping modes which do not match (U = %u, V = %u, W = %u). "
2093 "This may cause reduced performance even if only U (1D image) or U/V wrapping modes (2D "
2094 "image) are actually used. If you need different wrapping modes, disregard this warning.",
2095 VendorSpecificTag(kBPVendorArm));
2096 }
2097
2098 if ((pCreateInfo->minLod != 0.0f) || (pCreateInfo->maxLod < VK_LOD_CLAMP_NONE)) {
2099 skip |= LogPerformanceWarning(
2100 device, kVUID_BestPractices_CreateSampler_LodClamping,
2101 "%s Creating a sampler object with LOD clamping (minLod = %f, maxLod = %f). This may cause reduced performance. "
2102 "Instead of clamping LOD in the sampler, consider using an VkImageView which restricts the mip-levels, set minLod "
2103 "to 0.0, and maxLod to VK_LOD_CLAMP_NONE.",
2104 VendorSpecificTag(kBPVendorArm), pCreateInfo->minLod, pCreateInfo->maxLod);
2105 }
2106
2107 if (pCreateInfo->mipLodBias != 0.0f) {
2108 skip |=
2109 LogPerformanceWarning(device, kVUID_BestPractices_CreateSampler_LodBias,
2110 "%s Creating a sampler object with LOD bias != 0.0 (%f). This will lead to less efficient "
2111 "descriptors being created and may cause reduced performance.",
2112 VendorSpecificTag(kBPVendorArm), pCreateInfo->mipLodBias);
2113 }
2114
2115 if ((pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
2116 pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
2117 pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER) &&
2118 (pCreateInfo->borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK)) {
2119 skip |= LogPerformanceWarning(
2120 device, kVUID_BestPractices_CreateSampler_BorderClampColor,
2121 "%s Creating a sampler object with border clamping and borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK. "
2122 "This will lead to less efficient descriptors being created and may cause reduced performance. "
2123 "If possible, use VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK as the border color.",
2124 VendorSpecificTag(kBPVendorArm));
2125 }
2126
2127 if (pCreateInfo->unnormalizedCoordinates) {
2128 skip |= LogPerformanceWarning(
2129 device, kVUID_BestPractices_CreateSampler_UnnormalizedCoordinates,
2130 "%s Creating a sampler object with unnormalized coordinates. This will lead to less efficient "
2131 "descriptors being created and may cause reduced performance.",
2132 VendorSpecificTag(kBPVendorArm));
2133 }
2134
2135 if (pCreateInfo->anisotropyEnable) {
2136 skip |= LogPerformanceWarning(
2137 device, kVUID_BestPractices_CreateSampler_Anisotropy,
2138 "%s Creating a sampler object with anisotropy. This will lead to less efficient descriptors being created "
2139 "and may cause reduced performance.",
2140 VendorSpecificTag(kBPVendorArm));
2141 }
2142 }
2143
2144 return skip;
2145}
Sam Walls8e77e4f2020-03-16 20:47:40 +00002146
2147void BestPractices::PostTransformLRUCacheModel::resize(size_t size) { _entries.resize(size); }
2148
2149bool BestPractices::PostTransformLRUCacheModel::query_cache(uint32_t value) {
2150 // look for a cache hit
2151 auto hit = std::find_if(_entries.begin(), _entries.end(), [value](const CacheEntry& entry) { return entry.value == value; });
2152 if (hit != _entries.end()) {
2153 // mark the cache hit as being most recently used
2154 hit->age = iteration++;
2155 return true;
2156 }
2157
2158 // if there's no cache hit, we need to model the entry being inserted into the cache
2159 CacheEntry new_entry = {value, iteration};
2160 if (iteration < static_cast<uint32_t>(std::distance(_entries.begin(), _entries.end()))) {
2161 // if there is still space left in the cache, use the next available slot
2162 *(_entries.begin() + iteration) = new_entry;
2163 } else {
2164 // otherwise replace the least recently used cache entry
2165 auto lru = std::min_element(_entries.begin(), hit, [](const CacheEntry& a, const CacheEntry& b) { return a.age < b.age; });
2166 *lru = new_entry;
2167 }
2168 iteration++;
2169 return false;
2170}
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002171
2172bool BestPractices::PreCallValidateAcquireNextImageKHR(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout,
2173 VkSemaphore semaphore, VkFence fence, uint32_t* pImageIndex) const {
2174 const auto swapchain_data = GetSwapchainState(swapchain);
2175 bool skip = false;
2176 if (swapchain_data && swapchain_data->images.size() == 0) {
2177 skip |= LogWarning(swapchain, kVUID_Core_DrawState_SwapchainImagesNotFound,
2178 "vkAcquireNextImageKHR: No images found to acquire from. Application probably did not call "
2179 "vkGetSwapchainImagesKHR after swapchain creation.");
2180 }
2181 return skip;
2182}
2183
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002184void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
2185 uint32_t* pQueueFamilyPropertyCount,
2186 VkQueueFamilyProperties* pQueueFamilyProperties) {
2187 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(physicalDevice, pQueueFamilyPropertyCount,
2188 pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002189 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002190 if (bp_pd_state) {
2191 if (!pQueueFamilyProperties) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002192 if (UNCALLED == bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState) {
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002193 bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState = QUERY_COUNT;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002194 }
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002195 } else { // Save queue family properties
2196 bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState = QUERY_DETAILS;
2197 }
2198 }
2199}
2200
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002201void BestPractices::PostCallRecordGetPhysicalDeviceFeatures(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures* pFeatures) {
2202 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002203 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2204 if (bp_pd_state) {
2205 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
2206 }
2207}
2208
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002209void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2(VkPhysicalDevice physicalDevice,
2210 VkPhysicalDeviceFeatures2* pFeatures) {
2211 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002212 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2213 if (bp_pd_state) {
2214 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
2215 }
2216}
2217
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002218void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2KHR(VkPhysicalDevice physicalDevice,
2219 VkPhysicalDeviceFeatures2* pFeatures) {
2220 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2KHR(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002221 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2222 if (bp_pd_state) {
2223 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
2224 }
2225}
2226
2227void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilitiesKHR(VkPhysicalDevice physicalDevice,
2228 VkSurfaceKHR surface,
2229 VkSurfaceCapabilitiesKHR* pSurfaceCapabilities,
2230 VkResult result) {
2231 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2232 if (bp_pd_state) {
2233 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
2234 }
2235}
2236
2237void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2KHR(
2238 VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
2239 VkSurfaceCapabilities2KHR* pSurfaceCapabilities, VkResult result) {
2240 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2241 if (bp_pd_state) {
2242 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
2243 }
2244}
2245
2246void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2EXT(VkPhysicalDevice physicalDevice,
2247 VkSurfaceKHR surface,
2248 VkSurfaceCapabilities2EXT* pSurfaceCapabilities,
2249 VkResult result) {
2250 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2251 if (bp_pd_state) {
2252 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
2253 }
2254}
2255
2256void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice physicalDevice,
2257 VkSurfaceKHR surface, uint32_t* pPresentModeCount,
2258 VkPresentModeKHR* pPresentModes, VkResult result) {
2259 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2260 if (bp_pd_data) {
2261 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfacePresentModesKHRState;
2262
2263 if (*pPresentModeCount) {
2264 if (call_state < QUERY_COUNT) {
2265 call_state = QUERY_COUNT;
2266 }
2267 }
2268 if (pPresentModes) {
2269 if (call_state < QUERY_DETAILS) {
2270 call_state = QUERY_DETAILS;
2271 }
2272 }
2273 }
2274}
2275
2276void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
2277 uint32_t* pSurfaceFormatCount,
2278 VkSurfaceFormatKHR* pSurfaceFormats, VkResult result) {
2279 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2280 if (bp_pd_data) {
2281 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState;
2282
2283 if (*pSurfaceFormatCount) {
2284 if (call_state < QUERY_COUNT) {
2285 call_state = QUERY_COUNT;
2286 }
2287 }
2288 if (pSurfaceFormats) {
2289 if (call_state < QUERY_DETAILS) {
2290 call_state = QUERY_DETAILS;
2291 }
2292 }
2293 }
2294}
2295
2296void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormats2KHR(VkPhysicalDevice physicalDevice,
2297 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
2298 uint32_t* pSurfaceFormatCount,
2299 VkSurfaceFormat2KHR* pSurfaceFormats, VkResult result) {
2300 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2301 if (bp_pd_data) {
2302 if (*pSurfaceFormatCount) {
2303 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_COUNT) {
2304 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_COUNT;
2305 }
2306 }
2307 if (pSurfaceFormats) {
2308 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_DETAILS) {
2309 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_DETAILS;
2310 }
2311 }
2312 }
2313}
2314
2315void BestPractices::ManualPostCallRecordGetPhysicalDeviceDisplayPlanePropertiesKHR(VkPhysicalDevice physicalDevice,
2316 uint32_t* pPropertyCount,
2317 VkDisplayPlanePropertiesKHR* pProperties,
2318 VkResult result) {
2319 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2320 if (bp_pd_data) {
2321 if (*pPropertyCount) {
2322 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_COUNT) {
2323 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_COUNT;
2324 }
2325 }
2326 if (pProperties) {
2327 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_DETAILS) {
2328 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_DETAILS;
2329 }
2330 }
2331 }
2332}
2333
2334void BestPractices::ManualPostCallRecordCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
2335 const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain,
2336 VkResult result) {
2337 if (VK_SUCCESS == result) {
2338 swapchain_bp_state_map.emplace(*pSwapchain, SWAPCHAIN_STATE_BP{});
2339 }
2340}
2341
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002342void BestPractices::PostCallRecordDestroySwapchainKHR(VkDevice device, VkSwapchainKHR swapchain,
2343 const VkAllocationCallbacks* pAllocator) {
2344 ValidationStateTracker::PostCallRecordDestroySwapchainKHR(device, swapchain, pAllocator);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002345 auto swapchain_state_itr = swapchain_bp_state_map.find(swapchain);
2346 if (swapchain_state_itr != swapchain_bp_state_map.cend()) {
2347 swapchain_bp_state_map.erase(swapchain_state_itr);
2348 }
2349}
2350
2351void BestPractices::ManualPostCallRecordGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain,
2352 uint32_t* pSwapchainImageCount, VkImage* pSwapchainImages,
2353 VkResult result) {
2354 auto swapchain_state_itr = swapchain_bp_state_map.find(swapchain);
2355 assert(swapchain_state_itr != swapchain_bp_state_map.cend());
2356 auto& swapchain_state = swapchain_state_itr->second;
2357 if (pSwapchainImages || *pSwapchainImageCount) {
2358 if (swapchain_state.vkGetSwapchainImagesKHRState < QUERY_DETAILS) {
2359 swapchain_state.vkGetSwapchainImagesKHRState = QUERY_DETAILS;
2360 }
2361 }
2362}
2363
2364void BestPractices::ManualPostCallRecordEnumeratePhysicalDevices(VkInstance instance, uint32_t* pPhysicalDeviceCount,
2365 VkPhysicalDevice* pPhysicalDevices, VkResult result) {
2366 if ((nullptr != pPhysicalDevices) && ((result == VK_SUCCESS || result == VK_INCOMPLETE))) {
2367 for (uint32_t i = 0; i < *pPhysicalDeviceCount; i++) {
2368 phys_device_bp_state_map.emplace(pPhysicalDevices[i], PHYSICAL_DEVICE_STATE_BP{});
2369 }
2370 }
2371}
2372
2373void BestPractices::ManualPostCallRecordCreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo*, const VkAllocationCallbacks*,
2374 VkDevice*, VkResult result) {
2375 if (VK_SUCCESS == result) {
2376 instance_device_bp_state = &phys_device_bp_state_map[gpu];
2377 }
2378}
2379
2380PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP(const VkPhysicalDevice& phys_device) {
2381 if (phys_device_bp_state_map.count(phys_device) > 0) {
2382 return &phys_device_bp_state_map.at(phys_device);
2383 } else {
2384 return nullptr;
2385 }
2386}
2387
2388const PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP(const VkPhysicalDevice& phys_device) const {
2389 if (phys_device_bp_state_map.count(phys_device) > 0) {
2390 return &phys_device_bp_state_map.at(phys_device);
2391 } else {
2392 return nullptr;
2393 }
2394}
2395
2396PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP() {
2397 auto bp_state = (reinterpret_cast<BestPractices*>(instance_state))->instance_device_bp_state;
2398 if (bp_state) {
2399 return bp_state;
2400 } else if (!bp_state && phys_device_bp_state_map.count(physical_device_state->phys_device) > 0) {
2401 return &phys_device_bp_state_map.at(physical_device_state->phys_device);
2402 } else {
2403 return nullptr;
2404 }
2405}
2406
2407const PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP() const {
2408 auto bp_state = (reinterpret_cast<BestPractices*>(instance_state))->instance_device_bp_state;
2409 if (bp_state) {
2410 return bp_state;
2411 } else if (!bp_state && phys_device_bp_state_map.count(physical_device_state->phys_device) > 0) {
2412 return &phys_device_bp_state_map.at(physical_device_state->phys_device);
2413 } else {
2414 return nullptr;
2415 }
2416}