blob: c29d401be4937842ae0276c78bad9424a61a61a4 [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
34const std::map<BPVendorFlagBits, VendorSpecificInfo> vendor_info = {
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 {
39 for (const auto& vendor : vendor_info) {
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;
58 for (const auto& vendor : vendor_info) {
59 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
177 if (pCreateInfo != nullptr && pCreateInfo->pApplicationInfo != nullptr)
178 instance_api_version = pCreateInfo->pApplicationInfo->apiVersion;
179 else
180 instance_api_version = 0;
Camden5b184be2019-08-13 07:50:19 -0600181}
182
183bool BestPractices::PreCallValidateCreateDevice(VkPhysicalDevice physicalDevice, const VkDeviceCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500184 const VkAllocationCallbacks* pAllocator, VkDevice* pDevice) const {
Camden5b184be2019-08-13 07:50:19 -0600185 bool skip = false;
186
187 // get API version of physical device passed when creating device.
188 VkPhysicalDeviceProperties physical_device_properties{};
189 DispatchGetPhysicalDeviceProperties(physicalDevice, &physical_device_properties);
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500190 auto device_api_version = physical_device_properties.apiVersion;
Camden5b184be2019-08-13 07:50:19 -0600191
192 // check api versions and warn if instance api Version is higher than version on device.
193 if (instance_api_version > device_api_version) {
Mark Lobodzinski60880782020-08-11 08:02:07 -0600194 std::string inst_api_name = StringAPIVersion(instance_api_version);
195 std::string dev_api_name = StringAPIVersion(device_api_version);
Camden5b184be2019-08-13 07:50:19 -0600196
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700197 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_API_Mismatch,
198 "vkCreateDevice(): API Version of current instance, %s is higher than API Version on device, %s",
199 inst_api_name.c_str(), dev_api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -0600200 }
201
202 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
203 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kInstanceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800204 skip |= LogWarning(instance, kVUID_BestPractices_CreateDevice_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700205 "vkCreateDevice(): Attempting to enable Instance Extension %s at CreateDevice time.",
206 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600207 }
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700208 skip |= ValidateDeprecatedExtensions("CreateDevice", pCreateInfo->ppEnabledExtensionNames[i], instance_api_version,
209 kVUID_BestPractices_CreateDevice_DeprecatedExtension);
Mark Lobodzinskia431b772020-11-10 08:12:13 -0700210 skip |= ValidateSpecialUseExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i],
211 kVUID_BestPractices_CreateDevice_SpecialUseExtension);
Camden5b184be2019-08-13 07:50:19 -0600212 }
213
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600214 const auto bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
215 if ((bp_pd_state->vkGetPhysicalDeviceFeaturesState == UNCALLED) && (pCreateInfo->pEnabledFeatures != NULL)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700216 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_PDFeaturesNotCalled,
217 "vkCreateDevice() called before getting physical device features from vkGetPhysicalDeviceFeatures().");
Camden83a9c372019-08-14 11:41:38 -0600218 }
219
Szilard Papp7d2c7952020-06-22 14:38:13 +0100220 if ((VendorCheckEnabled(kBPVendorArm)) && (pCreateInfo->pEnabledFeatures != nullptr) &&
221 (pCreateInfo->pEnabledFeatures->robustBufferAccess == VK_TRUE)) {
222 skip |= LogPerformanceWarning(
223 device, kVUID_BestPractices_CreateDevice_RobustBufferAccess,
224 "%s vkCreateDevice() called with enabled robustBufferAccess. Use robustBufferAccess as a debugging tool during "
225 "development. Enabling it causes loss in performance for accesses to uniform buffers and shader storage "
226 "buffers. Disable robustBufferAccess in release builds. Only leave it enabled if the application use-case "
227 "requires the additional level of reliability due to the use of unverified user-supplied draw parameters.",
228 VendorSpecificTag(kBPVendorArm));
229 }
230
Camden5b184be2019-08-13 07:50:19 -0600231 return skip;
232}
233
234bool BestPractices::PreCallValidateCreateBuffer(VkDevice device, const VkBufferCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500235 const VkAllocationCallbacks* pAllocator, VkBuffer* pBuffer) const {
Camden5b184be2019-08-13 07:50:19 -0600236 bool skip = false;
237
238 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
239 std::stringstream bufferHex;
240 bufferHex << "0x" << std::hex << HandleToUint64(pBuffer);
241
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700242 skip |= LogWarning(
243 device, kVUID_BestPractices_SharingModeExclusive,
244 "Warning: Buffer (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
245 "(queueFamilyIndexCount of %" PRIu32 ").",
246 bufferHex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600247 }
248
249 return skip;
250}
251
252bool BestPractices::PreCallValidateCreateImage(VkDevice device, const VkImageCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500253 const VkAllocationCallbacks* pAllocator, VkImage* pImage) const {
Camden5b184be2019-08-13 07:50:19 -0600254 bool skip = false;
255
256 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
257 std::stringstream imageHex;
258 imageHex << "0x" << std::hex << HandleToUint64(pImage);
259
260 skip |=
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700261 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
262 "Warning: Image (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
263 "(queueFamilyIndexCount of %" PRIu32 ").",
264 imageHex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600265 }
266
Attilio Provenzano02859b22020-02-27 14:17:28 +0000267 if (VendorCheckEnabled(kBPVendorArm)) {
268 if (pCreateInfo->samples > kMaxEfficientSamplesArm) {
269 skip |= LogPerformanceWarning(
270 device, kVUID_BestPractices_CreateImage_TooLargeSampleCount,
271 "%s vkCreateImage(): Trying to create an image with %u samples. "
272 "The hardware revision may not have full throughput for framebuffers with more than %u samples.",
273 VendorSpecificTag(kBPVendorArm), static_cast<uint32_t>(pCreateInfo->samples), kMaxEfficientSamplesArm);
274 }
275
276 if (pCreateInfo->samples > VK_SAMPLE_COUNT_1_BIT && !(pCreateInfo->usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT)) {
277 skip |= LogPerformanceWarning(
278 device, kVUID_BestPractices_CreateImage_NonTransientMSImage,
279 "%s vkCreateImage(): Trying to create a multisampled image, but createInfo.usage did not have "
280 "VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. Multisampled images may be resolved on-chip, "
281 "and do not need to be backed by physical storage. "
282 "TRANSIENT_ATTACHMENT allows tiled GPUs to not back the multisampled image with physical memory.",
283 VendorSpecificTag(kBPVendorArm));
284 }
285 }
286
Camden5b184be2019-08-13 07:50:19 -0600287 return skip;
288}
289
290bool BestPractices::PreCallValidateCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500291 const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain) const {
Camden5b184be2019-08-13 07:50:19 -0600292 bool skip = false;
293
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600294 const auto* bp_pd_state = GetPhysicalDeviceStateBP();
295 if (bp_pd_state) {
296 if (bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState == UNCALLED) {
297 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
298 "vkCreateSwapchainKHR() called before getting surface capabilities from "
299 "vkGetPhysicalDeviceSurfaceCapabilitiesKHR().");
300 }
Camden83a9c372019-08-14 11:41:38 -0600301
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600302 if (bp_pd_state->vkGetPhysicalDeviceSurfacePresentModesKHRState != QUERY_DETAILS) {
303 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
304 "vkCreateSwapchainKHR() called before getting surface present mode(s) from "
305 "vkGetPhysicalDeviceSurfacePresentModesKHR().");
306 }
Camden83a9c372019-08-14 11:41:38 -0600307
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600308 if (bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState != QUERY_DETAILS) {
309 skip |= LogWarning(
310 device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
311 "vkCreateSwapchainKHR() called before getting surface format(s) from vkGetPhysicalDeviceSurfaceFormatsKHR().");
312 }
Camden83a9c372019-08-14 11:41:38 -0600313 }
314
Camden5b184be2019-08-13 07:50:19 -0600315 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700316 skip |=
317 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
Mark Lobodzinski019f4e32020-04-13 11:01:35 -0600318 "Warning: A Swapchain is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while "
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700319 "specifying multiple queues (queueFamilyIndexCount of %" PRIu32 ").",
320 pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600321 }
322
Szilard Papp48a6da32020-06-10 14:41:59 +0100323 if (pCreateInfo->minImageCount == 2) {
324 skip |= LogPerformanceWarning(
325 device, kVUID_BestPractices_SuboptimalSwapchainImageCount,
326 "Warning: A Swapchain is being created with minImageCount set to %" PRIu32
327 ", which means double buffering is going "
328 "to be used. Using double buffering and vsync locks rendering to an integer fraction of the vsync rate. In turn, "
329 "reducing the performance of the application if rendering is slower than vsync. Consider setting minImageCount to "
330 "3 to use triple buffering to maximize performance in such cases.",
331 pCreateInfo->minImageCount);
332 }
333
Szilard Pappd5f0f812020-06-22 09:01:29 +0100334 if (VendorCheckEnabled(kBPVendorArm) && (pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR)) {
335 skip |= LogWarning(device, kVUID_BestPractices_CreateSwapchain_PresentMode,
336 "%s Warning: Swapchain is not being created with presentation mode \"VK_PRESENT_MODE_FIFO_KHR\". "
337 "Prefer using \"VK_PRESENT_MODE_FIFO_KHR\" to avoid unnecessary CPU and GPU load and save power. "
338 "Presentation modes which are not FIFO will present the latest available frame and discard other "
339 "frame(s) if any.",
340 VendorSpecificTag(kBPVendorArm));
341 }
342
Camden5b184be2019-08-13 07:50:19 -0600343 return skip;
344}
345
346bool BestPractices::PreCallValidateCreateSharedSwapchainsKHR(VkDevice device, uint32_t swapchainCount,
347 const VkSwapchainCreateInfoKHR* pCreateInfos,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500348 const VkAllocationCallbacks* pAllocator,
349 VkSwapchainKHR* pSwapchains) const {
Camden5b184be2019-08-13 07:50:19 -0600350 bool skip = false;
351
352 for (uint32_t i = 0; i < swapchainCount; i++) {
353 if ((pCreateInfos[i].queueFamilyIndexCount > 1) && (pCreateInfos[i].imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700354 skip |= LogWarning(
355 device, kVUID_BestPractices_SharingModeExclusive,
356 "Warning: A shared swapchain (index %" PRIu32
357 ") is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple "
358 "queues (queueFamilyIndexCount of %" PRIu32 ").",
359 i, pCreateInfos[i].queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600360 }
361 }
362
363 return skip;
364}
365
366bool BestPractices::PreCallValidateCreateRenderPass(VkDevice device, const VkRenderPassCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500367 const VkAllocationCallbacks* pAllocator, VkRenderPass* pRenderPass) const {
Camden5b184be2019-08-13 07:50:19 -0600368 bool skip = false;
369
370 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; ++i) {
371 VkFormat format = pCreateInfo->pAttachments[i].format;
372 if (pCreateInfo->pAttachments[i].initialLayout == VK_IMAGE_LAYOUT_UNDEFINED) {
373 if ((FormatIsColor(format) || FormatHasDepth(format)) &&
374 pCreateInfo->pAttachments[i].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700375 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
376 "Render pass has an attachment with loadOp == VK_ATTACHMENT_LOAD_OP_LOAD and "
377 "initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
378 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
379 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600380 }
381 if (FormatHasStencil(format) && pCreateInfo->pAttachments[i].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700382 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
383 "Render pass has an attachment with stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD "
384 "and initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
385 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
386 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600387 }
388 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000389
390 const auto& attachment = pCreateInfo->pAttachments[i];
391 if (attachment.samples > VK_SAMPLE_COUNT_1_BIT) {
392 bool access_requires_memory =
393 attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD || attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE;
394
395 if (FormatHasStencil(format)) {
396 access_requires_memory |= attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
397 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE;
398 }
399
400 if (access_requires_memory) {
401 skip |= LogPerformanceWarning(
402 device, kVUID_BestPractices_CreateRenderPass_ImageRequiresMemory,
403 "Attachment %u in the VkRenderPass is a multisampled image with %u samples, but it uses loadOp/storeOp "
404 "which requires accessing data from memory. Multisampled images should always be loadOp = CLEAR or DONT_CARE, "
405 "storeOp = DONT_CARE. This allows the implementation to use lazily allocated memory effectively.",
406 i, static_cast<uint32_t>(attachment.samples));
407 }
408 }
Camden5b184be2019-08-13 07:50:19 -0600409 }
410
411 for (uint32_t dependency = 0; dependency < pCreateInfo->dependencyCount; dependency++) {
412 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].srcStageMask);
413 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].dstStageMask);
414 }
415
416 return skip;
417}
418
Tony-LunarG767180f2020-04-23 14:03:59 -0600419bool BestPractices::ValidateAttachments(const VkRenderPassCreateInfo2* rpci, uint32_t attachmentCount,
420 const VkImageView* image_views) const {
421 bool skip = false;
422
423 // Check for non-transient attachments that should be transient and vice versa
424 for (uint32_t i = 0; i < attachmentCount; ++i) {
425 auto& attachment = rpci->pAttachments[i];
426 bool attachment_should_be_transient =
427 (attachment.loadOp != VK_ATTACHMENT_LOAD_OP_LOAD && attachment.storeOp != VK_ATTACHMENT_STORE_OP_STORE);
428
429 if (FormatHasStencil(attachment.format)) {
430 attachment_should_be_transient &= (attachment.stencilLoadOp != VK_ATTACHMENT_LOAD_OP_LOAD &&
431 attachment.stencilStoreOp != VK_ATTACHMENT_STORE_OP_STORE);
432 }
433
434 auto view_state = GetImageViewState(image_views[i]);
435 if (view_state) {
436 auto& ivci = view_state->create_info;
437 auto& ici = GetImageState(ivci.image)->createInfo;
438
439 bool image_is_transient = (ici.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) != 0;
440
441 // The check for an image that should not be transient applies to all GPUs
442 if (!attachment_should_be_transient && image_is_transient) {
443 skip |= LogPerformanceWarning(
444 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldNotBeTransient,
445 "Attachment %u in VkFramebuffer uses loadOp/storeOps which need to access physical memory, "
446 "but the image backing the image view has VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
447 "Physical memory will need to be backed lazily to this image, potentially causing stalls.",
448 i);
449 }
450
451 bool supports_lazy = false;
452 for (uint32_t j = 0; j < phys_dev_mem_props.memoryTypeCount; j++) {
453 if (phys_dev_mem_props.memoryTypes[j].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
454 supports_lazy = true;
455 }
456 }
457
458 // The check for an image that should be transient only applies to GPUs supporting
459 // lazily allocated memory
460 if (supports_lazy && attachment_should_be_transient && !image_is_transient) {
461 skip |= LogPerformanceWarning(
462 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldBeTransient,
463 "Attachment %u in VkFramebuffer uses loadOp/storeOps which never have to be backed by physical memory, "
464 "but the image backing the image view does not have VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
465 "You can save physical memory by using transient attachment backed by lazily allocated memory here.",
466 i);
467 }
468 }
469 }
470 return skip;
471}
472
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000473bool BestPractices::PreCallValidateCreateFramebuffer(VkDevice device, const VkFramebufferCreateInfo* pCreateInfo,
474 const VkAllocationCallbacks* pAllocator, VkFramebuffer* pFramebuffer) const {
475 bool skip = false;
476
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000477 auto rp_state = GetRenderPassState(pCreateInfo->renderPass);
Tony-LunarG767180f2020-04-23 14:03:59 -0600478 if (rp_state && !(pCreateInfo->flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT_KHR)) {
479 skip = ValidateAttachments(rp_state->createInfo.ptr(), pCreateInfo->attachmentCount, pCreateInfo->pAttachments);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000480 }
481
482 return skip;
483}
484
Sam Wallse746d522020-03-16 21:20:23 +0000485bool BestPractices::PreCallValidateAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
486 VkDescriptorSet* pDescriptorSets, void* ads_state_data) const {
487 bool skip = false;
488 skip |= ValidationStateTracker::PreCallValidateAllocateDescriptorSets(device, pAllocateInfo, pDescriptorSets, ads_state_data);
489
490 if (!skip) {
491 const auto& pool_handle = pAllocateInfo->descriptorPool;
492 auto iter = descriptor_pool_freed_count.find(pool_handle);
493 // if the number of freed sets > 0, it implies they could be recycled instead if desirable
494 // this warning is specific to Arm
495 if (VendorCheckEnabled(kBPVendorArm) && iter != descriptor_pool_freed_count.end() && iter->second > 0) {
496 skip |= LogPerformanceWarning(
497 device, kVUID_BestPractices_AllocateDescriptorSets_SuboptimalReuse,
498 "%s Descriptor set memory was allocated via vkAllocateDescriptorSets() for sets which were previously freed in the "
499 "same logical device. On some drivers or architectures it may be most optimal to re-use existing descriptor sets.",
500 VendorSpecificTag(kBPVendorArm));
501 }
502 }
503
504 return skip;
505}
506
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600507void BestPractices::ManualPostCallRecordAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
508 VkDescriptorSet* pDescriptorSets, VkResult result, void* ads_state) {
Sam Wallse746d522020-03-16 21:20:23 +0000509 if (result == VK_SUCCESS) {
510 // find the free count for the pool we allocated into
511 auto iter = descriptor_pool_freed_count.find(pAllocateInfo->descriptorPool);
512 if (iter != descriptor_pool_freed_count.end()) {
513 // we record successful allocations by subtracting the allocation count from the last recorded free count
514 const auto alloc_count = pAllocateInfo->descriptorSetCount;
515 // clamp the unsigned subtraction to the range [0, last_free_count]
516 if (iter->second > alloc_count)
517 iter->second -= alloc_count;
518 else
519 iter->second = 0;
520 }
521 }
522}
523
524void BestPractices::PostCallRecordFreeDescriptorSets(VkDevice device, VkDescriptorPool descriptorPool, uint32_t descriptorSetCount,
525 const VkDescriptorSet* pDescriptorSets, VkResult result) {
526 ValidationStateTracker::PostCallRecordFreeDescriptorSets(device, descriptorPool, descriptorSetCount, pDescriptorSets, result);
527 if (result == VK_SUCCESS) {
528 // we want to track frees because we're interested in suggesting re-use
529 auto iter = descriptor_pool_freed_count.find(descriptorPool);
530 if (iter == descriptor_pool_freed_count.end()) {
531 descriptor_pool_freed_count.insert(std::make_pair(descriptorPool, descriptorSetCount));
532 } else {
533 iter->second += descriptorSetCount;
534 }
535 }
536}
537
Camden5b184be2019-08-13 07:50:19 -0600538bool BestPractices::PreCallValidateAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500539 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory) const {
Camden5b184be2019-08-13 07:50:19 -0600540 bool skip = false;
541
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500542 if (num_mem_objects + 1 > kMemoryObjectWarningLimit) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700543 skip |= LogPerformanceWarning(device, kVUID_BestPractices_AllocateMemory_TooManyObjects,
544 "Performance Warning: This app has > %" PRIu32 " memory objects.", kMemoryObjectWarningLimit);
Camden5b184be2019-08-13 07:50:19 -0600545 }
546
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000547 if (pAllocateInfo->allocationSize < kMinDeviceAllocationSize) {
548 skip |= LogPerformanceWarning(
549 device, kVUID_BestPractices_AllocateMemory_SmallAllocation,
550 "vkAllocateMemory(): Allocating a VkDeviceMemory of size %llu. This is a very small allocation (current "
551 "threshold is %llu bytes). "
552 "You should make large allocations and sub-allocate from one large VkDeviceMemory.",
553 pAllocateInfo->allocationSize, kMinDeviceAllocationSize);
554 }
555
Camden83a9c372019-08-14 11:41:38 -0600556 // TODO: Insert get check for GetPhysicalDeviceMemoryProperties once the state is tracked in the StateTracker
557
558 return skip;
559}
560
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600561void BestPractices::ManualPostCallRecordAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
562 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory,
563 VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700564 if (result != VK_SUCCESS) {
565 static std::vector<VkResult> error_codes = {VK_ERROR_OUT_OF_HOST_MEMORY, VK_ERROR_OUT_OF_DEVICE_MEMORY,
566 VK_ERROR_TOO_MANY_OBJECTS, VK_ERROR_INVALID_EXTERNAL_HANDLE,
567 VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS_KHR};
568 static std::vector<VkResult> success_codes = {};
569 ValidateReturnCodes("vkReleaseFullScreenExclusiveModeEXT", result, error_codes, success_codes);
570 return;
571 }
572 num_mem_objects++;
573}
Camden Stocker9738af92019-10-16 13:54:03 -0700574
Mark Lobodzinskide15e582020-04-29 08:06:00 -0600575void BestPractices::ValidateReturnCodes(const char* api_name, VkResult result, const std::vector<VkResult>& error_codes,
576 const std::vector<VkResult>& success_codes) const {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700577 auto error = std::find(error_codes.begin(), error_codes.end(), result);
578 if (error != error_codes.end()) {
Mark Lobodzinski629defa2020-04-29 12:00:23 -0600579 LogWarning(instance, kVUID_BestPractices_Error_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700580 return;
581 }
582 auto success = std::find(success_codes.begin(), success_codes.end(), result);
583 if (success != success_codes.end()) {
Mark Lobodzinskie7215152020-05-11 08:21:23 -0600584 LogInfo(instance, kVUID_BestPractices_NonSuccess_Result, "%s(): Returned non-success return code %s.", api_name,
585 string_VkResult(result));
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500586 }
587}
588
Jeff Bolz5c801d12019-10-09 10:38:45 -0500589bool BestPractices::PreCallValidateFreeMemory(VkDevice device, VkDeviceMemory memory,
590 const VkAllocationCallbacks* pAllocator) const {
Mark Lobodzinski91e50bf2020-01-14 09:55:11 -0700591 if (memory == VK_NULL_HANDLE) return false;
Camden83a9c372019-08-14 11:41:38 -0600592 bool skip = false;
593
Camden Stocker9738af92019-10-16 13:54:03 -0700594 const DEVICE_MEMORY_STATE* mem_info = ValidationStateTracker::GetDevMemState(memory);
Camden83a9c372019-08-14 11:41:38 -0600595
596 for (auto& obj : mem_info->obj_bindings) {
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600597 LogObjectList objlist(device);
598 objlist.add(obj);
599 objlist.add(mem_info->mem);
600 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 -0700601 report_data->FormatHandle(obj).c_str(), report_data->FormatHandle(mem_info->mem).c_str());
Camden83a9c372019-08-14 11:41:38 -0600602 }
603
Camden5b184be2019-08-13 07:50:19 -0600604 return skip;
605}
606
607void BestPractices::PreCallRecordFreeMemory(VkDevice device, VkDeviceMemory memory, const VkAllocationCallbacks* pAllocator) {
Mark Lobodzinski97484d62020-03-03 11:57:41 -0700608 ValidationStateTracker::PreCallRecordFreeMemory(device, memory, pAllocator);
Camden5b184be2019-08-13 07:50:19 -0600609 if (memory != VK_NULL_HANDLE) {
610 num_mem_objects--;
611 }
612}
613
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000614bool BestPractices::ValidateBindBufferMemory(VkBuffer buffer, VkDeviceMemory memory, const char* api_name) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600615 bool skip = false;
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500616 const BUFFER_STATE* buffer_state = GetBufferState(buffer);
Camden Stockerb603cc82019-09-03 10:09:02 -0600617
sfricke-samsunge2441192019-11-06 14:07:57 -0800618 if (!buffer_state->memory_requirements_checked && !buffer_state->external_memory_handle) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700619 skip |= LogWarning(device, kVUID_BestPractices_BufferMemReqNotCalled,
620 "%s: Binding memory to %s but vkGetBufferMemoryRequirements() has not been called on that buffer.",
621 api_name, report_data->FormatHandle(buffer).c_str());
Camden Stockerb603cc82019-09-03 10:09:02 -0600622 }
623
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000624 const DEVICE_MEMORY_STATE* mem_state = GetDevMemState(memory);
625
626 if (mem_state->alloc_info.allocationSize == buffer_state->createInfo.size &&
627 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
628 skip |= LogPerformanceWarning(
629 device, kVUID_BestPractices_SmallDedicatedAllocation,
630 "%s: Trying to bind %s to a memory block which is fully consumed by the buffer. "
631 "The required size of the allocation is %llu, but smaller buffers like this should be sub-allocated from "
632 "larger memory blocks. (Current threshold is %llu bytes.)",
633 api_name, report_data->FormatHandle(buffer).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
634 }
635
Camden Stockerb603cc82019-09-03 10:09:02 -0600636 return skip;
637}
638
639bool BestPractices::PreCallValidateBindBufferMemory(VkDevice device, VkBuffer buffer, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500640 VkDeviceSize memoryOffset) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600641 bool skip = false;
642 const char* api_name = "BindBufferMemory()";
643
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000644 skip |= ValidateBindBufferMemory(buffer, memory, api_name);
Camden Stockerb603cc82019-09-03 10:09:02 -0600645
646 return skip;
647}
648
649bool BestPractices::PreCallValidateBindBufferMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500650 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600651 char api_name[64];
652 bool skip = false;
653
654 for (uint32_t i = 0; i < bindInfoCount; i++) {
655 sprintf(api_name, "vkBindBufferMemory2() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000656 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600657 }
658
659 return skip;
660}
Camden Stockerb603cc82019-09-03 10:09:02 -0600661
662bool BestPractices::PreCallValidateBindBufferMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500663 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600664 char api_name[64];
665 bool skip = false;
Camden Stockerb603cc82019-09-03 10:09:02 -0600666
Camden Stocker8b798ab2019-09-03 10:33:28 -0600667 for (uint32_t i = 0; i < bindInfoCount; i++) {
668 sprintf(api_name, "vkBindBufferMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000669 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600670 }
671
672 return skip;
673}
674
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000675bool BestPractices::ValidateBindImageMemory(VkImage image, VkDeviceMemory memory, const char* api_name) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600676 bool skip = false;
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500677 const IMAGE_STATE* image_state = GetImageState(image);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600678
sfricke-samsung71bc6572020-04-29 15:49:43 -0700679 if (image_state->disjoint == false) {
sfricke-samsungd7ea5de2020-04-08 09:19:18 -0700680 if (!image_state->memory_requirements_checked && !image_state->external_memory_handle) {
681 skip |= LogWarning(device, kVUID_BestPractices_ImageMemReqNotCalled,
682 "%s: Binding memory to %s but vkGetImageMemoryRequirements() has not been called on that image.",
683 api_name, report_data->FormatHandle(image).c_str());
684 }
685 } else {
686 // TODO If binding disjoint image then this needs to check that VkImagePlaneMemoryRequirementsInfo was called for each
687 // plane.
Camden Stocker8b798ab2019-09-03 10:33:28 -0600688 }
689
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000690 const DEVICE_MEMORY_STATE* mem_state = GetDevMemState(memory);
691
692 if (mem_state->alloc_info.allocationSize == image_state->requirements.size &&
693 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
694 skip |= LogPerformanceWarning(
695 device, kVUID_BestPractices_SmallDedicatedAllocation,
696 "%s: Trying to bind %s to a memory block which is fully consumed by the image. "
697 "The required size of the allocation is %llu, but smaller images like this should be sub-allocated from "
698 "larger memory blocks. (Current threshold is %llu bytes.)",
699 api_name, report_data->FormatHandle(image).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
700 }
701
702 // If we're binding memory to a image which was created as TRANSIENT and the image supports LAZY allocation,
703 // make sure this type is actually used.
704 // This warning will only trigger if this layer is run on a platform that supports LAZILY_ALLOCATED_BIT
705 // (i.e.most tile - based renderers)
706 if (image_state->createInfo.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) {
707 bool supports_lazy = false;
708 uint32_t suggested_type = 0;
709
710 for (uint32_t i = 0; i < phys_dev_mem_props.memoryTypeCount; i++) {
711 if ((1u << i) & image_state->requirements.memoryTypeBits) {
712 if (phys_dev_mem_props.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
713 supports_lazy = true;
714 suggested_type = i;
715 break;
716 }
717 }
718 }
719
720 uint32_t allocated_properties = phys_dev_mem_props.memoryTypes[mem_state->alloc_info.memoryTypeIndex].propertyFlags;
721
722 if (supports_lazy && (allocated_properties & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) == 0) {
723 skip |= LogPerformanceWarning(
724 device, kVUID_BestPractices_NonLazyTransientImage,
725 "%s: Attempting to bind memory type % u to VkImage which was created with TRANSIENT_ATTACHMENT_BIT,"
726 "but this memory type is not LAZILY_ALLOCATED_BIT. You should use memory type %u here instead to save "
727 "%llu bytes of physical memory.",
728 api_name, mem_state->alloc_info.memoryTypeIndex, suggested_type, image_state->requirements.size);
729 }
730 }
731
Camden Stocker8b798ab2019-09-03 10:33:28 -0600732 return skip;
733}
734
735bool BestPractices::PreCallValidateBindImageMemory(VkDevice device, VkImage image, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500736 VkDeviceSize memoryOffset) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600737 bool skip = false;
738 const char* api_name = "vkBindImageMemory()";
739
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000740 skip |= ValidateBindImageMemory(image, memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600741
742 return skip;
743}
744
745bool BestPractices::PreCallValidateBindImageMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500746 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600747 char api_name[64];
748 bool skip = false;
749
750 for (uint32_t i = 0; i < bindInfoCount; i++) {
751 sprintf(api_name, "vkBindImageMemory2() pBindInfos[%u]", i);
Tony-LunarG5e60b852020-04-27 11:27:54 -0600752 if (!lvl_find_in_chain<VkBindImageMemorySwapchainInfoKHR>(pBindInfos[i].pNext)) {
753 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
754 }
Camden Stocker8b798ab2019-09-03 10:33:28 -0600755 }
756
757 return skip;
758}
759
760bool BestPractices::PreCallValidateBindImageMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500761 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600762 char api_name[64];
763 bool skip = false;
764
765 for (uint32_t i = 0; i < bindInfoCount; i++) {
766 sprintf(api_name, "vkBindImageMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000767 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600768 }
769
770 return skip;
771}
Camden83a9c372019-08-14 11:41:38 -0600772
Attilio Provenzano02859b22020-02-27 14:17:28 +0000773static inline bool FormatHasFullThroughputBlendingArm(VkFormat format) {
774 switch (format) {
775 case VK_FORMAT_B10G11R11_UFLOAT_PACK32:
776 case VK_FORMAT_R16_SFLOAT:
777 case VK_FORMAT_R16G16_SFLOAT:
778 case VK_FORMAT_R16G16B16_SFLOAT:
779 case VK_FORMAT_R16G16B16A16_SFLOAT:
780 case VK_FORMAT_R32_SFLOAT:
781 case VK_FORMAT_R32G32_SFLOAT:
782 case VK_FORMAT_R32G32B32_SFLOAT:
783 case VK_FORMAT_R32G32B32A32_SFLOAT:
784 return false;
785
786 default:
787 return true;
788 }
789}
790
791bool BestPractices::ValidateMultisampledBlendingArm(uint32_t createInfoCount,
792 const VkGraphicsPipelineCreateInfo* pCreateInfos) const {
793 bool skip = false;
794
795 for (uint32_t i = 0; i < createInfoCount; i++) {
796 auto pCreateInfo = &pCreateInfos[i];
797
798 if (!pCreateInfo->pColorBlendState || !pCreateInfo->pMultisampleState ||
799 pCreateInfo->pMultisampleState->rasterizationSamples == VK_SAMPLE_COUNT_1_BIT ||
800 pCreateInfo->pMultisampleState->sampleShadingEnable) {
801 return skip;
802 }
803
804 auto rp_state = GetRenderPassState(pCreateInfo->renderPass);
805 auto& subpass = rp_state->createInfo.pSubpasses[pCreateInfo->subpass];
806
807 for (uint32_t j = 0; j < pCreateInfo->pColorBlendState->attachmentCount; j++) {
808 auto& blend_att = pCreateInfo->pColorBlendState->pAttachments[j];
809 uint32_t att = subpass.pColorAttachments[j].attachment;
810
811 if (att != VK_ATTACHMENT_UNUSED && blend_att.blendEnable && blend_att.colorWriteMask) {
812 if (!FormatHasFullThroughputBlendingArm(rp_state->createInfo.pAttachments[att].format)) {
813 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultisampledBlending,
814 "%s vkCreateGraphicsPipelines() - createInfo #%u: Pipeline is multisampled and "
815 "color attachment #%u makes use "
816 "of a format which cannot be blended at full throughput when using MSAA.",
817 VendorSpecificTag(kBPVendorArm), i, j);
818 }
819 }
820 }
821 }
822
823 return skip;
824}
825
Camden5b184be2019-08-13 07:50:19 -0600826bool BestPractices::PreCallValidateCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
827 const VkGraphicsPipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -0600828 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500829 void* cgpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -0600830 bool skip = StateTracker::PreCallValidateCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos,
831 pAllocator, pPipelines, cgpl_state_data);
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600832 create_graphics_pipeline_api_state* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
Camden5b184be2019-08-13 07:50:19 -0600833
834 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700835 skip |= LogPerformanceWarning(
836 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
837 "Performance Warning: This vkCreateGraphicsPipelines call is creating multiple pipelines but is not using a "
838 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -0600839 }
840
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000841 for (uint32_t i = 0; i < createInfoCount; i++) {
842 auto& createInfo = pCreateInfos[i];
843
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600844 if (!(cgpl_state->pipe_state[i]->active_shaders & VK_SHADER_STAGE_MESH_BIT_NV)) {
845 auto& vertexInput = *createInfo.pVertexInputState;
846 uint32_t count = 0;
847 for (uint32_t j = 0; j < vertexInput.vertexBindingDescriptionCount; j++) {
848 if (vertexInput.pVertexBindingDescriptions[j].inputRate == VK_VERTEX_INPUT_RATE_INSTANCE) {
849 count++;
850 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000851 }
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600852 if (count > kMaxInstancedVertexBuffers) {
853 skip |= LogPerformanceWarning(
854 device, kVUID_BestPractices_CreatePipelines_TooManyInstancedVertexBuffers,
855 "The pipeline is using %u instanced vertex buffers (current limit: %u), but this can be inefficient on the "
856 "GPU. If using instanced vertex attributes prefer interleaving them in a single buffer.",
857 count, kMaxInstancedVertexBuffers);
858 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000859 }
Attilio Provenzano02859b22020-02-27 14:17:28 +0000860
Szilard Pappaaf2da32020-06-22 10:37:35 +0100861 if ((pCreateInfos[i].pRasterizationState->depthBiasEnable) &&
862 (pCreateInfos[i].pRasterizationState->depthBiasConstantFactor == 0.0f) &&
863 (pCreateInfos[i].pRasterizationState->depthBiasSlopeFactor == 0.0f)) {
864 skip |= VendorCheckEnabled(kBPVendorArm) &&
865 LogPerformanceWarning(
866 device, kVUID_BestPractices_CreatePipelines_DepthBias_Zero,
867 "%s Performance Warning: This vkCreateGraphicsPipelines call is created with depthBiasEnable set to true "
868 "and both depthBiasConstantFactor and depthBiasSlopeFactor are set to 0. This can cause reduced "
869 "efficiency during rasterization. Consider disabling depthBias or increasing either "
870 "depthBiasConstantFactor or depthBiasSlopeFactor.",
871 VendorSpecificTag(kBPVendorArm));
872 }
873
Attilio Provenzano02859b22020-02-27 14:17:28 +0000874 skip |= VendorCheckEnabled(kBPVendorArm) && ValidateMultisampledBlendingArm(createInfoCount, pCreateInfos);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000875 }
876
Camden5b184be2019-08-13 07:50:19 -0600877 return skip;
878}
879
Sam Walls0961ec02020-03-31 16:39:15 +0100880void BestPractices::ManualPostCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t count,
881 const VkGraphicsPipelineCreateInfo* pCreateInfos,
882 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
883 VkResult result, void* cgpl_state_data) {
884 for (size_t i = 0; i < count; i++) {
885 const auto* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
886 const VkPipeline pipeline_handle = pPipelines[i];
887
888 // record depth stencil state and color blend states for depth pre-pass tracking purposes
889 auto gp_cis = graphicsPipelineCIs.find(pipeline_handle);
890
891 // add the tracking state if it doesn't exist
892 if (gp_cis == graphicsPipelineCIs.end()) {
893 auto result = graphicsPipelineCIs.emplace(std::make_pair(pipeline_handle, GraphicsPipelineCIs{}));
894
895 if (!result.second) continue;
896
897 gp_cis = result.first;
898 }
899
Tony-LunarG412b1b72020-07-15 10:30:13 -0600900 gp_cis->second.colorBlendStateCI =
901 cgpl_state->pCreateInfos[i].pColorBlendState
902 ? new safe_VkPipelineColorBlendStateCreateInfo(cgpl_state->pCreateInfos[i].pColorBlendState)
903 : nullptr;
904 gp_cis->second.depthStencilStateCI =
905 cgpl_state->pCreateInfos[i].pDepthStencilState
906 ? new safe_VkPipelineDepthStencilStateCreateInfo(cgpl_state->pCreateInfos[i].pDepthStencilState)
907 : nullptr;
Sam Walls0961ec02020-03-31 16:39:15 +0100908 }
909}
910
Camden5b184be2019-08-13 07:50:19 -0600911bool BestPractices::PreCallValidateCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
912 const VkComputePipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -0600913 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500914 void* ccpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -0600915 bool skip = StateTracker::PreCallValidateCreateComputePipelines(device, pipelineCache, createInfoCount, pCreateInfos,
916 pAllocator, pPipelines, ccpl_state_data);
Camden5b184be2019-08-13 07:50:19 -0600917
918 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700919 skip |= LogPerformanceWarning(
920 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
921 "Performance Warning: This vkCreateComputePipelines call is creating multiple pipelines but is not using a "
922 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -0600923 }
924
Sam Wallsd7ab6db2020-06-19 20:41:54 +0100925 if (VendorCheckEnabled(kBPVendorArm)) {
926 for (size_t i = 0; i < createInfoCount; i++) {
927 skip |= ValidateCreateComputePipelineArm(pCreateInfos[i]);
928 }
929 }
930
931 return skip;
932}
933
934bool BestPractices::ValidateCreateComputePipelineArm(const VkComputePipelineCreateInfo& createInfo) const {
935 bool skip = false;
936 auto* module = GetShaderModuleState(createInfo.stage.module);
937
938 uint32_t x = 1, y = 1, z = 1;
939 FindLocalSize(module, x, y, z);
940
941 uint32_t thread_count = x * y * z;
942
943 // Generate a priori warnings about work group sizes.
944 if (thread_count > kMaxEfficientWorkGroupThreadCountArm) {
945 skip |= LogPerformanceWarning(
946 device, kVUID_BestPractices_CreateComputePipelines_ComputeWorkGroupSize,
947 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, %u, "
948 "%u) (%u threads total), has more threads than advised in a single work group. It is advised to use work "
949 "groups with less than %u threads, especially when using barrier() or shared memory.",
950 VendorSpecificTag(kBPVendorArm), x, y, z, thread_count, kMaxEfficientWorkGroupThreadCountArm);
951 }
952
953 if (thread_count == 1 || ((x > 1) && (x & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
954 ((y > 1) && (y & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
955 ((z > 1) && (z & (kThreadGroupDispatchCountAlignmentArm - 1)))) {
956 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeThreadGroupAlignment,
957 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, "
958 "%u, %u) is not aligned to %u "
959 "threads. On Arm Mali architectures, not aligning work group sizes to %u may "
960 "leave threads idle on the shader "
961 "core.",
962 VendorSpecificTag(kBPVendorArm), x, y, z, kThreadGroupDispatchCountAlignmentArm,
963 kThreadGroupDispatchCountAlignmentArm);
964 }
965
966 // Generate warnings about work group sizes based on active resources.
967 auto entrypoint = FindEntrypoint(module, createInfo.stage.pName, createInfo.stage.stage);
968 if (entrypoint == module->end()) return false;
969
970 bool has_writeable_descriptors = false;
locke-lunarg63e4daf2020-08-17 17:53:25 -0600971 bool has_atomic_descriptors = false;
Sam Wallsd7ab6db2020-06-19 20:41:54 +0100972 auto accessible_ids = MarkAccessibleIds(module, entrypoint);
locke-lunarg63e4daf2020-08-17 17:53:25 -0600973 auto descriptor_uses =
974 CollectInterfaceByDescriptorSlot(module, accessible_ids, &has_writeable_descriptors, &has_atomic_descriptors);
Sam Wallsd7ab6db2020-06-19 20:41:54 +0100975
976 unsigned dimensions = 0;
977 if (x > 1) dimensions++;
978 if (y > 1) dimensions++;
979 if (z > 1) dimensions++;
980 // Here the dimension will really depend on the dispatch grid, but assume it's 1D.
981 dimensions = std::max(dimensions, 1u);
982
983 // If we're accessing images, we almost certainly want to have a 2D workgroup for cache reasons.
984 // There are some false positives here. We could simply have a shader that does this within a 1D grid,
985 // or we may have a linearly tiled image, but these cases are quite unlikely in practice.
986 bool accesses_2d = false;
987 for (const auto& usage : descriptor_uses) {
988 auto dim = GetShaderResourceDimensionality(module, usage.second);
989 if (dim < 0) continue;
990 auto spvdim = spv::Dim(dim);
991 if (spvdim != spv::Dim1D && spvdim != spv::DimBuffer) accesses_2d = true;
992 }
993
994 if (accesses_2d && dimensions < 2) {
995 LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeSpatialLocality,
996 "%s vkCreateComputePipelines(): compute shader has work group dimensions (%u, %u, %u), which "
997 "suggests a 1D dispatch, but the shader is accessing 2D or 3D images. The shader may be "
998 "exhibiting poor spatial locality with respect to one or more shader resources.",
999 VendorSpecificTag(kBPVendorArm), x, y, z);
1000 }
1001
Camden5b184be2019-08-13 07:50:19 -06001002 return skip;
1003}
1004
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001005bool BestPractices::CheckPipelineStageFlags(std::string api_name, const VkPipelineStageFlags flags) const {
Camden5b184be2019-08-13 07:50:19 -06001006 bool skip = false;
1007
1008 if (flags & VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001009 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1010 "You are using VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001011 } else if (flags & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001012 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1013 "You are using VK_PIPELINE_STAGE_ALL_COMMANDS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001014 }
1015
1016 return skip;
1017}
1018
Mark Lobodzinski84101d72020-04-24 09:43:48 -06001019void BestPractices::ManualPostCallRecordQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo, VkResult result) {
Mark Lobodzinski9b133c12020-03-10 10:42:56 -06001020 for (uint32_t i = 0; i < pPresentInfo->swapchainCount; ++i) {
1021 auto swapchains_result = pPresentInfo->pResults ? pPresentInfo->pResults[i] : result;
1022 if (swapchains_result == VK_SUBOPTIMAL_KHR) {
1023 LogPerformanceWarning(
1024 pPresentInfo->pSwapchains[i], kVUID_BestPractices_SuboptimalSwapchain,
1025 "vkQueuePresentKHR: %s :VK_SUBOPTIMAL_KHR was returned. VK_SUBOPTIMAL_KHR - Presentation will still succeed, "
1026 "subject to the window resize behavior, but the swapchain is no longer configured optimally for the surface it "
1027 "targets. Applications should query updated surface information and recreate their swapchain at the next "
1028 "convenient opportunity.",
1029 report_data->FormatHandle(pPresentInfo->pSwapchains[i]).c_str());
1030 }
1031 }
1032}
1033
Jeff Bolz5c801d12019-10-09 10:38:45 -05001034bool BestPractices::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
1035 VkFence fence) const {
Camden5b184be2019-08-13 07:50:19 -06001036 bool skip = false;
1037
1038 for (uint32_t submit = 0; submit < submitCount; submit++) {
1039 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreCount; semaphore++) {
1040 skip |= CheckPipelineStageFlags("vkQueueSubmit", pSubmits[submit].pWaitDstStageMask[semaphore]);
1041 }
1042 }
1043
1044 return skip;
1045}
1046
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001047bool BestPractices::PreCallValidateCreateCommandPool(VkDevice device, const VkCommandPoolCreateInfo* pCreateInfo,
1048 const VkAllocationCallbacks* pAllocator, VkCommandPool* pCommandPool) const {
1049 bool skip = false;
1050
1051 if (pCreateInfo->flags & VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT) {
1052 skip |= LogPerformanceWarning(
1053 device, kVUID_BestPractices_CreateCommandPool_CommandBufferReset,
1054 "vkCreateCommandPool(): VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT is set. Consider resetting entire "
1055 "pool instead.");
1056 }
1057
1058 return skip;
1059}
1060
1061bool BestPractices::PreCallValidateBeginCommandBuffer(VkCommandBuffer commandBuffer,
1062 const VkCommandBufferBeginInfo* pBeginInfo) const {
1063 bool skip = false;
1064
1065 if (pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT) {
1066 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_SimultaneousUse,
1067 "vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT is set.");
1068 }
1069
Attilio Provenzano02859b22020-02-27 14:17:28 +00001070 if (!(pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT)) {
1071 skip |= VendorCheckEnabled(kBPVendorArm) &&
1072 LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_OneTimeSubmit,
1073 "%s vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT is not set. "
1074 "For best performance on Mali GPUs, consider setting ONE_TIME_SUBMIT by default.",
1075 VendorSpecificTag(kBPVendorArm));
1076 }
1077
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001078 return skip;
1079}
1080
Jeff Bolz5c801d12019-10-09 10:38:45 -05001081bool BestPractices::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001082 bool skip = false;
1083
1084 skip |= CheckPipelineStageFlags("vkCmdSetEvent", stageMask);
1085
1086 return skip;
1087}
1088
Jeff Bolz5c801d12019-10-09 10:38:45 -05001089bool BestPractices::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
1090 VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001091 bool skip = false;
1092
1093 skip |= CheckPipelineStageFlags("vkCmdResetEvent", stageMask);
1094
1095 return skip;
1096}
1097
1098bool BestPractices::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1099 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
1100 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1101 uint32_t bufferMemoryBarrierCount,
1102 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1103 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001104 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001105 bool skip = false;
1106
1107 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", srcStageMask);
1108 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", dstStageMask);
1109
1110 return skip;
1111}
1112
1113bool BestPractices::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
1114 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
1115 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1116 uint32_t bufferMemoryBarrierCount,
1117 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1118 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001119 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001120 bool skip = false;
1121
1122 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", srcStageMask);
1123 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", dstStageMask);
1124
1125 return skip;
1126}
1127
1128bool BestPractices::PreCallValidateCmdWriteTimestamp(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001129 VkQueryPool queryPool, uint32_t query) const {
Camden5b184be2019-08-13 07:50:19 -06001130 bool skip = false;
1131
1132 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp", pipelineStage);
1133
1134 return skip;
1135}
1136
Sam Walls0961ec02020-03-31 16:39:15 +01001137void BestPractices::PostCallRecordCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
1138 VkPipeline pipeline) {
1139 StateTracker::PostCallRecordCmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
1140
1141 if (pipelineBindPoint == VK_PIPELINE_BIND_POINT_GRAPHICS) {
1142 // check for depth/blend state tracking
1143 auto gp_cis = graphicsPipelineCIs.find(pipeline);
1144 if (gp_cis != graphicsPipelineCIs.end()) {
1145 auto prepass_state = cbDepthPrePassStates.find(commandBuffer);
1146 if (prepass_state == cbDepthPrePassStates.end()) {
1147 auto result = cbDepthPrePassStates.emplace(std::make_pair(commandBuffer, DepthPrePassState{}));
1148
1149 if (!result.second) return;
1150
1151 prepass_state = result.first;
1152 }
1153
1154 const auto* blend_state = gp_cis->second.colorBlendStateCI;
1155 const auto* stencil_state = gp_cis->second.depthStencilStateCI;
1156
1157 if (blend_state) {
1158 // assume the pipeline is depth-only unless any of the attachments have color writes enabled
1159 prepass_state->second.depthOnly = true;
1160 for (size_t i = 0; i < blend_state->attachmentCount; i++) {
1161 if (blend_state->pAttachments[i].colorWriteMask != 0) {
1162 prepass_state->second.depthOnly = false;
1163 }
1164 }
1165 }
1166
1167 // check for depth value usage
1168 prepass_state->second.depthEqualComparison = false;
1169
1170 if (stencil_state && stencil_state->depthTestEnable) {
1171 switch (stencil_state->depthCompareOp) {
1172 case VK_COMPARE_OP_EQUAL:
1173 case VK_COMPARE_OP_GREATER_OR_EQUAL:
1174 case VK_COMPARE_OP_LESS_OR_EQUAL:
1175 prepass_state->second.depthEqualComparison = true;
1176 break;
1177 default:
1178 break;
1179 }
1180 }
1181 } else {
1182 // reset depth pre-pass tracking
1183 cbDepthPrePassStates.emplace(std::make_pair(commandBuffer, DepthPrePassState{}));
1184 }
1185 }
1186}
1187
Attilio Provenzano02859b22020-02-27 14:17:28 +00001188static inline bool RenderPassUsesAttachmentOnTile(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1189 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
1190 auto& subpassInfo = createInfo.pSubpasses[subpass];
1191
1192 // If an attachment is ever used as a color attachment,
1193 // resolve attachment or depth stencil attachment,
1194 // it needs to exist on tile at some point.
1195
1196 for (uint32_t i = 0; i < subpassInfo.colorAttachmentCount; i++)
1197 if (subpassInfo.pColorAttachments[i].attachment == attachment) return true;
1198
1199 if (subpassInfo.pResolveAttachments) {
1200 for (uint32_t i = 0; i < subpassInfo.colorAttachmentCount; i++)
1201 if (subpassInfo.pResolveAttachments[i].attachment == attachment) return true;
1202 }
1203
1204 if (subpassInfo.pDepthStencilAttachment && subpassInfo.pDepthStencilAttachment->attachment == attachment) return true;
1205 }
1206
1207 return false;
1208}
1209
1210bool BestPractices::ValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1211 const VkRenderPassBeginInfo* pRenderPassBegin) const {
1212 bool skip = false;
1213
1214 if (!pRenderPassBegin) {
1215 return skip;
1216 }
1217
1218 auto rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
1219 if (rp_state) {
Tony-LunarG767180f2020-04-23 14:03:59 -06001220 if (rp_state->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT_KHR) {
1221 const VkRenderPassAttachmentBeginInfo* rpabi =
1222 lvl_find_in_chain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
1223 if (rpabi) {
1224 skip = ValidateAttachments(rp_state->createInfo.ptr(), rpabi->attachmentCount, rpabi->pAttachments);
1225 }
1226 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001227 // Check if any attachments have LOAD operation on them
1228 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
1229 auto& attachment = rp_state->createInfo.pAttachments[att];
1230
1231 bool attachmentHasReadback = false;
1232 if (!FormatHasStencil(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
1233 attachmentHasReadback = true;
1234 }
1235
1236 if (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
1237 attachmentHasReadback = true;
1238 }
1239
1240 bool attachmentNeedsReadback = false;
1241
1242 // Check if the attachment is actually used in any subpass on-tile
1243 if (attachmentHasReadback && RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1244 attachmentNeedsReadback = true;
1245 }
1246
1247 // Using LOAD_OP_LOAD is expensive on tiled GPUs, so flag it as a potential improvement
1248 if (attachmentNeedsReadback) {
1249 skip |= VendorCheckEnabled(kBPVendorArm) &&
1250 LogPerformanceWarning(
1251 device, kVUID_BestPractices_BeginRenderPass_AttachmentNeedsReadback,
1252 "%s Attachment #%u in render pass has begun with VK_ATTACHMENT_LOAD_OP_LOAD.\n"
1253 "Submitting this renderpass will cause the driver to inject a readback of the attachment "
1254 "which will copy in total %u pixels (renderArea = { %d, %d, %u, %u }) to the tile buffer.",
1255 VendorSpecificTag(kBPVendorArm), att,
1256 pRenderPassBegin->renderArea.extent.width * pRenderPassBegin->renderArea.extent.height,
1257 pRenderPassBegin->renderArea.offset.x, pRenderPassBegin->renderArea.offset.y,
1258 pRenderPassBegin->renderArea.extent.width, pRenderPassBegin->renderArea.extent.height);
1259 }
1260 }
1261 }
1262
1263 return skip;
1264}
1265
1266bool BestPractices::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1267 VkSubpassContents contents) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001268 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1269 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001270 return skip;
1271}
1272
1273bool BestPractices::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1274 const VkRenderPassBeginInfo* pRenderPassBegin,
1275 const VkSubpassBeginInfoKHR* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001276 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1277 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001278 return skip;
1279}
1280
1281bool BestPractices::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1282 const VkSubpassBeginInfoKHR* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001283 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1284 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001285 return skip;
1286}
1287
Sam Walls0961ec02020-03-31 16:39:15 +01001288void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1289 const VkRenderPassBeginInfo* pRenderPassBegin) {
1290 auto prepass_state = cbDepthPrePassStates.find(commandBuffer);
1291
1292 // add the tracking state if it doesn't exist
1293 if (prepass_state == cbDepthPrePassStates.end()) {
1294 auto result = cbDepthPrePassStates.emplace(std::make_pair(commandBuffer, DepthPrePassState{}));
1295
1296 if (!result.second) return;
1297
1298 prepass_state = result.first;
1299 }
1300
1301 // reset the renderpass state
1302 prepass_state->second = {};
1303
1304 const auto* cb_state = GetCBState(commandBuffer);
locke-lunargaecf2152020-05-12 17:15:41 -06001305 const auto* rp_state = cb_state->activeRenderPass.get();
Sam Walls0961ec02020-03-31 16:39:15 +01001306
1307 // track depth / color attachment usage within the renderpass
1308 for (size_t i = 0; i < rp_state->createInfo.subpassCount; i++) {
1309 // record if depth/color attachments are in use for this renderpass
1310 if (rp_state->createInfo.pSubpasses[i].pDepthStencilAttachment != nullptr) prepass_state->second.depthAttachment = true;
1311
1312 if (rp_state->createInfo.pSubpasses[i].colorAttachmentCount > 0) prepass_state->second.colorAttachment = true;
1313 }
1314}
1315
1316void BestPractices::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1317 VkSubpassContents contents) {
1318 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1319 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
1320}
1321
1322void BestPractices::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1323 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1324 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1325 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1326}
1327
1328void BestPractices::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1329 const VkRenderPassBeginInfo* pRenderPassBegin,
1330 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1331 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1332 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1333}
1334
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001335// Generic function to handle validation for all CmdDraw* type functions
1336bool BestPractices::ValidateCmdDrawType(VkCommandBuffer cmd_buffer, const char* caller) const {
1337 bool skip = false;
1338 const CMD_BUFFER_STATE* cb_state = GetCBState(cmd_buffer);
1339 if (cb_state) {
1340 const auto last_bound_it = cb_state->lastBound.find(VK_PIPELINE_BIND_POINT_GRAPHICS);
1341 const PIPELINE_STATE* pipeline_state = nullptr;
1342 if (last_bound_it != cb_state->lastBound.cend()) {
1343 pipeline_state = last_bound_it->second.pipeline_state;
1344 }
1345 const auto& current_vtx_bfr_binding_info = cb_state->current_vertex_buffer_binding_info.vertex_buffer_bindings;
1346 // Verify vertex binding
1347 if (pipeline_state->vertex_binding_descriptions_.size() <= 0) {
1348 if ((!current_vtx_bfr_binding_info.empty()) && (!cb_state->vertex_buffer_used)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001349 skip |= LogPerformanceWarning(cb_state->commandBuffer, kVUID_BestPractices_DrawState_VtxIndexOutOfBounds,
1350 "Vertex buffers are bound to %s but no vertex buffers are attached to %s.",
1351 report_data->FormatHandle(cb_state->commandBuffer).c_str(),
1352 report_data->FormatHandle(pipeline_state->pipeline).c_str());
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001353 }
1354 }
1355 }
1356 return skip;
1357}
1358
Sam Walls0961ec02020-03-31 16:39:15 +01001359void BestPractices::RecordCmdDrawType(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
1360 if (VendorCheckEnabled(kBPVendorArm)) {
1361 RecordCmdDrawTypeArm(cmd_buffer, draw_count, caller);
1362 }
1363}
1364
1365void BestPractices::RecordCmdDrawTypeArm(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
1366 auto prepass_state = cbDepthPrePassStates.find(cmd_buffer);
1367 if (prepass_state != cbDepthPrePassStates.end() && draw_count >= kDepthPrePassMinDrawCountArm) {
1368 if (prepass_state->second.depthOnly) prepass_state->second.numDrawCallsDepthOnly++;
1369
1370 if (prepass_state->second.depthEqualComparison) prepass_state->second.numDrawCallsDepthEqualCompare++;
1371 }
1372}
1373
Camden5b184be2019-08-13 07:50:19 -06001374bool BestPractices::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001375 uint32_t firstVertex, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06001376 bool skip = false;
1377
1378 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001379 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
1380 "Warning: You are calling vkCmdDraw() with an instanceCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001381 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDraw()");
Camden5b184be2019-08-13 07:50:19 -06001382 }
1383
1384 return skip;
1385}
1386
Sam Walls0961ec02020-03-31 16:39:15 +01001387void BestPractices::PostCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
1388 uint32_t firstVertex, uint32_t firstInstance) {
1389 StateTracker::PostCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
1390 RecordCmdDrawType(commandBuffer, vertexCount * instanceCount, "vkCmdDraw()");
1391}
1392
Camden5b184be2019-08-13 07:50:19 -06001393bool BestPractices::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001394 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06001395 bool skip = false;
1396
1397 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001398 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
1399 "Warning: You are calling vkCmdDrawIndexed() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06001400 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001401 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexed()");
1402
Attilio Provenzano02859b22020-02-27 14:17:28 +00001403 // Check if we reached the limit for small indexed draw calls.
1404 // Note that we cannot update the draw call count here, so we do it in PreCallRecordCmdDrawIndexed.
1405 const CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
1406 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices &&
1407 (cmd_state->small_indexed_draw_call_count == kMaxSmallIndexedDrawcalls - 1)) {
1408 skip |= VendorCheckEnabled(kBPVendorArm) &&
1409 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_ManySmallIndexedDrawcalls,
1410 "The command buffer contains many small indexed drawcalls "
1411 "(at least %u drawcalls with less than %u indices each). This may cause pipeline bubbles. "
1412 "You can try batching drawcalls or instancing when applicable.",
1413 VendorSpecificTag(kBPVendorArm), kMaxSmallIndexedDrawcalls, kSmallIndexedDrawcallIndices);
1414 }
1415
Sam Walls8e77e4f2020-03-16 20:47:40 +00001416 if (VendorCheckEnabled(kBPVendorArm)) {
1417 ValidateIndexBufferArm(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
1418 }
1419
1420 return skip;
1421}
1422
1423bool BestPractices::ValidateIndexBufferArm(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1424 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
1425 bool skip = false;
1426
1427 // check for sparse/underutilised index buffer, and post-transform cache thrashing
1428 const auto* cmd_state = GetCBState(commandBuffer);
1429 if (cmd_state == nullptr) return skip;
1430
1431 const auto* ib_state = GetBufferState(cmd_state->index_buffer_binding.buffer);
1432 if (ib_state == nullptr) return skip;
1433
1434 const VkIndexType ib_type = cmd_state->index_buffer_binding.index_type;
1435 const auto& ib_mem_state = *ib_state->binding.mem_state;
1436 const VkDeviceSize ib_mem_offset = ib_mem_state.mapped_range.offset;
1437 const void* ib_mem = ib_mem_state.p_driver_data;
1438 bool primitive_restart_enable = false;
1439
1440 const auto& pipeline_binding_iter = cmd_state->lastBound.find(VK_PIPELINE_BIND_POINT_GRAPHICS);
1441
1442 if (pipeline_binding_iter != cmd_state->lastBound.end()) {
1443 const auto* pipeline_state = pipeline_binding_iter->second.pipeline_state;
1444 if (pipeline_state != nullptr && pipeline_state->graphicsPipelineCI.pInputAssemblyState != nullptr)
1445 primitive_restart_enable = pipeline_state->graphicsPipelineCI.pInputAssemblyState->primitiveRestartEnable == VK_TRUE;
1446 }
1447
1448 // no point checking index buffer if the memory is nonexistant/unmapped, or if there is no graphics pipeline bound to this CB
1449 if (ib_mem && pipeline_binding_iter != cmd_state->lastBound.end()) {
1450 uint32_t scan_stride;
1451 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1452 scan_stride = sizeof(uint8_t);
1453 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1454 scan_stride = sizeof(uint16_t);
1455 } else {
1456 scan_stride = sizeof(uint32_t);
1457 }
1458
1459 const uint8_t* scan_begin = static_cast<const uint8_t*>(ib_mem) + ib_mem_offset + firstIndex * scan_stride;
1460 const uint8_t* scan_end = scan_begin + indexCount * scan_stride;
1461
1462 // Min and max are important to track for some Mali architectures. In older Mali devices without IDVS, all
1463 // vertices corresponding to indices between the minimum and maximum may be loaded, and possibly shaded,
1464 // irrespective of whether or not they're part of the draw call.
1465
1466 // start with minimum as 0xFFFFFFFF and adjust to indices in the buffer
1467 uint32_t min_index = ~0u;
1468 // start with maximum as 0 and adjust to indices in the buffer
1469 uint32_t max_index = 0u;
1470
1471 // first scan-through, we're looking to simulate a model LRU post-transform cache, estimating the number of vertices shaded
1472 // for the given index buffer
1473 uint32_t vertex_shade_count = 0;
1474
1475 PostTransformLRUCacheModel post_transform_cache;
1476
1477 // The size of the cache being modelled positively correlates with how much behaviour it can capture about
1478 // arbitrary ground-truth hardware/architecture cache behaviour. I.e. it's a good solution when we don't know the
1479 // target architecture.
1480 // However, modelling a post-transform cache with more than 32 elements gives diminishing returns in practice.
1481 // http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
1482 post_transform_cache.resize(32);
1483
1484 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
1485 uint32_t scan_index;
1486 uint32_t primitive_restart_value;
1487 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1488 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
1489 primitive_restart_value = 0xFF;
1490 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1491 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
1492 primitive_restart_value = 0xFFFF;
1493 } else {
1494 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
1495 primitive_restart_value = 0xFFFFFFFF;
1496 }
1497
1498 max_index = std::max(max_index, scan_index);
1499 min_index = std::min(min_index, scan_index);
1500
1501 if (!primitive_restart_enable || scan_index != primitive_restart_value) {
1502 bool in_cache = post_transform_cache.query_cache(scan_index);
1503 // if the shaded vertex corresponding to the index is not in the PT-cache, we need to shade again
1504 if (!in_cache) vertex_shade_count++;
1505 }
1506 }
1507
1508 // 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 +01001509 // 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
1510 if (max_index < min_index || max_index == min_index) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00001511
1512 if (max_index - min_index >= indexCount) {
Mark Young0ec6b062020-11-19 15:32:17 -07001513 skip |=
1514 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
1515 "%s The indices which were specified for the draw call only utilise approximately %.02f%% of "
1516 "index buffer value range. Arm Mali architectures before G71 do not have IDVS (Index-Driven "
1517 "Vertex Shading), meaning all vertices corresponding to indices between the minimum and "
1518 "maximum would be loaded, and possibly shaded, whether or not they are used.",
1519 VendorSpecificTag(kBPVendorArm),
1520 (static_cast<float>(indexCount) / static_cast<float>(max_index - min_index)) * 100.0f);
Sam Walls8e77e4f2020-03-16 20:47:40 +00001521 return skip;
1522 }
1523
1524 // use a dynamic vector of bitsets as a memory-compact representation of which indices are included in the draw call
1525 // 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 +01001526 const size_t refs_per_bucket = 64;
1527 std::vector<std::bitset<refs_per_bucket>> vertex_reference_buckets;
1528
1529 const uint32_t n_indices = max_index - min_index + 1;
1530 const uint32_t n_buckets = (n_indices / static_cast<uint32_t>(refs_per_bucket)) +
1531 ((n_indices % static_cast<uint32_t>(refs_per_bucket)) != 0 ? 1 : 0);
1532
1533 // there needs to be at least one bitset to store a set of indices smaller than n_buckets
1534 vertex_reference_buckets.resize(std::max(1u, n_buckets));
Sam Walls8e77e4f2020-03-16 20:47:40 +00001535
1536 // To avoid using too much memory, we run over the indices again.
1537 // Knowing the size from the last scan allows us to record index usage with bitsets
1538 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
1539 uint32_t scan_index;
1540 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1541 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
1542 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1543 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
1544 } else {
1545 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
1546 }
1547 // keep track of the set of all indices used to reference vertices in the draw call
1548 size_t index_offset = scan_index - min_index;
Sam Walls61b06892020-07-23 16:20:50 +01001549 size_t bitset_bucket_index = index_offset / refs_per_bucket;
1550 uint64_t used_indices = 1ull << ((index_offset % refs_per_bucket) & 0xFFFFFFFFu);
Sam Walls8e77e4f2020-03-16 20:47:40 +00001551 vertex_reference_buckets[bitset_bucket_index] |= used_indices;
1552 }
1553
1554 uint32_t vertex_reference_count = 0;
1555 for (const auto& bitset : vertex_reference_buckets) {
1556 vertex_reference_count += static_cast<uint32_t>(bitset.count());
1557 }
1558
1559 // 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 -07001560 float utilization = static_cast<float>(vertex_reference_count) / static_cast<float>(max_index - min_index + 1);
Sam Walls8e77e4f2020-03-16 20:47:40 +00001561 // 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 -07001562 float cache_hit_rate = static_cast<float>(vertex_reference_count) / static_cast<float>(vertex_shade_count);
Sam Walls8e77e4f2020-03-16 20:47:40 +00001563
1564 if (utilization < 0.5f) {
1565 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
1566 "%s The indices which were specified for the draw call only utilise approximately "
1567 "%.02f%% of the bound vertex buffer.",
1568 VendorSpecificTag(kBPVendorArm), utilization);
1569 }
1570
1571 if (cache_hit_rate <= 0.5f) {
1572 skip |=
1573 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_PostTransformCacheThrashing,
1574 "%s The indices which were specified for the draw call are estimated to cause thrashing of "
1575 "the post-transform vertex cache, with a hit-rate of %.02f%%. "
1576 "I.e. the ordering of the index buffer may not make optimal use of indices associated with "
1577 "recently shaded vertices.",
1578 VendorSpecificTag(kBPVendorArm), cache_hit_rate * 100.0f);
1579 }
1580 }
1581
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001582 return skip;
1583}
1584
Attilio Provenzano02859b22020-02-27 14:17:28 +00001585void BestPractices::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1586 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
1587 ValidationStateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset,
1588 firstInstance);
1589
1590 CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
1591 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices) {
1592 cmd_state->small_indexed_draw_call_count++;
1593 }
1594}
1595
Sam Walls0961ec02020-03-31 16:39:15 +01001596void BestPractices::PostCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1597 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
1598 StateTracker::PostCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
1599 RecordCmdDrawType(commandBuffer, indexCount * instanceCount, "vkCmdDrawIndexed()");
1600}
1601
sfricke-samsung681ab7b2020-10-29 01:53:35 -07001602bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
1603 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
1604 uint32_t maxDrawCount, uint32_t stride) const {
1605 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCount()");
1606
1607 return skip;
1608}
1609
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001610bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
1611 VkDeviceSize offset, VkBuffer countBuffer,
1612 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
1613 uint32_t stride) const {
1614 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCountKHR()");
Camden5b184be2019-08-13 07:50:19 -06001615
1616 return skip;
1617}
1618
1619bool BestPractices::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001620 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06001621 bool skip = false;
1622
1623 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001624 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
1625 "Warning: You are calling vkCmdDrawIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001626 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirect()");
Camden5b184be2019-08-13 07:50:19 -06001627 }
1628
1629 return skip;
1630}
1631
Sam Walls0961ec02020-03-31 16:39:15 +01001632void BestPractices::PostCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
1633 uint32_t count, uint32_t stride) {
1634 StateTracker::PostCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, count, stride);
1635 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndirect()");
1636}
1637
Camden5b184be2019-08-13 07:50:19 -06001638bool BestPractices::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001639 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06001640 bool skip = false;
1641
1642 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001643 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
1644 "Warning: You are calling vkCmdDrawIndexedIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001645 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirect()");
Camden5b184be2019-08-13 07:50:19 -06001646 }
1647
1648 return skip;
1649}
1650
Sam Walls0961ec02020-03-31 16:39:15 +01001651void BestPractices::PostCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
1652 uint32_t count, uint32_t stride) {
1653 StateTracker::PostCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, count, stride);
1654 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndexedIndirect()");
1655}
1656
Camden5b184be2019-08-13 07:50:19 -06001657bool BestPractices::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t groupCountX, uint32_t groupCountY,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001658 uint32_t groupCountZ) const {
Camden5b184be2019-08-13 07:50:19 -06001659 bool skip = false;
1660
1661 if ((groupCountX == 0) || (groupCountY == 0) || (groupCountZ == 0)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001662 skip |= LogWarning(device, kVUID_BestPractices_CmdDispatch_GroupCountZero,
1663 "Warning: You are calling vkCmdDispatch() while one or more groupCounts are zero (groupCountX = %" PRIu32
1664 ", groupCountY = %" PRIu32 ", groupCountZ = %" PRIu32 ").",
1665 groupCountX, groupCountY, groupCountZ);
Camden5b184be2019-08-13 07:50:19 -06001666 }
1667
1668 return skip;
1669}
Camden83a9c372019-08-14 11:41:38 -06001670
Sam Walls0961ec02020-03-31 16:39:15 +01001671bool BestPractices::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
1672 bool skip = false;
1673
1674 skip |= StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
1675
1676 auto prepass_state = cbDepthPrePassStates.find(commandBuffer);
1677
1678 if (prepass_state == cbDepthPrePassStates.end()) return skip;
1679
1680 bool uses_depth = (prepass_state->second.depthAttachment || prepass_state->second.colorAttachment) &&
1681 prepass_state->second.numDrawCallsDepthEqualCompare >= kDepthPrePassNumDrawCallsArm &&
1682 prepass_state->second.numDrawCallsDepthOnly >= kDepthPrePassNumDrawCallsArm;
1683 if (uses_depth) {
1684 skip |= LogPerformanceWarning(
1685 device, kVUID_BestPractices_EndRenderPass_DepthPrePassUsage,
1686 "%s Depth pre-passes may be in use. In general, this is not recommended, as in Arm Mali GPUs since "
1687 "Mali-T620, Forward Pixel Killing (FPK) can already perform automatic hidden surface removal; in which "
1688 "case, using depth pre-passes for hidden surface removal may worsen performance.",
1689 VendorSpecificTag(kBPVendorArm));
1690 }
1691
1692 return skip;
1693}
1694
Camden Stocker9c051442019-11-06 14:28:43 -08001695bool BestPractices::ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(VkPhysicalDevice physicalDevice,
1696 const char* api_name) const {
1697 bool skip = false;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001698 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
Camden Stocker9c051442019-11-06 14:28:43 -08001699
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001700 if (bp_pd_state) {
1701 if (bp_pd_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState == UNCALLED) {
1702 skip |= LogWarning(physicalDevice, kVUID_BestPractices_DisplayPlane_PropertiesNotCalled,
1703 "Potential problem with calling %s() without first retrieving properties from "
1704 "vkGetPhysicalDeviceDisplayPlanePropertiesKHR or vkGetPhysicalDeviceDisplayPlaneProperties2KHR.",
1705 api_name);
1706 }
Camden Stocker9c051442019-11-06 14:28:43 -08001707 }
1708
1709 return skip;
1710}
1711
Camden83a9c372019-08-14 11:41:38 -06001712bool BestPractices::PreCallValidateGetDisplayPlaneSupportedDisplaysKHR(VkPhysicalDevice physicalDevice, uint32_t planeIndex,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001713 uint32_t* pDisplayCount, VkDisplayKHR* pDisplays) const {
Camden83a9c372019-08-14 11:41:38 -06001714 bool skip = false;
1715
Camden Stocker9c051442019-11-06 14:28:43 -08001716 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneSupportedDisplaysKHR");
Camden83a9c372019-08-14 11:41:38 -06001717
Camden Stocker9c051442019-11-06 14:28:43 -08001718 return skip;
1719}
1720
1721bool BestPractices::PreCallValidateGetDisplayPlaneCapabilitiesKHR(VkPhysicalDevice physicalDevice, VkDisplayModeKHR mode,
1722 uint32_t planeIndex,
1723 VkDisplayPlaneCapabilitiesKHR* pCapabilities) const {
1724 bool skip = false;
1725
1726 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilitiesKHR");
1727
1728 return skip;
1729}
1730
1731bool BestPractices::PreCallValidateGetDisplayPlaneCapabilities2KHR(VkPhysicalDevice physicalDevice,
1732 const VkDisplayPlaneInfo2KHR* pDisplayPlaneInfo,
1733 VkDisplayPlaneCapabilities2KHR* pCapabilities) const {
1734 bool skip = false;
1735
1736 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilities2KHR");
Camden83a9c372019-08-14 11:41:38 -06001737
1738 return skip;
1739}
Camden05de2d42019-08-19 10:23:56 -06001740
1741bool BestPractices::PreCallValidateGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain, uint32_t* pSwapchainImageCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001742 VkImage* pSwapchainImages) const {
Camden05de2d42019-08-19 10:23:56 -06001743 bool skip = false;
1744
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001745 auto swapchain_state_itr = swapchain_bp_state_map.find(swapchain);
Camden05de2d42019-08-19 10:23:56 -06001746
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001747 if ((swapchain_state_itr != swapchain_bp_state_map.cend()) && pSwapchainImages) {
Camden05de2d42019-08-19 10:23:56 -06001748 // Compare the preliminary value of *pSwapchainImageCount with the value this time:
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001749 if (swapchain_state_itr->second.vkGetSwapchainImagesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001750 skip |=
1751 LogWarning(device, kVUID_Core_Swapchain_PriorCount,
1752 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImageCount; but no prior positive value has "
1753 "been seen for pSwapchainImages.");
Camden05de2d42019-08-19 10:23:56 -06001754 }
1755 }
1756
1757 return skip;
1758}
1759
1760// Common function to handle validation for GetPhysicalDeviceQueueFamilyProperties & 2KHR version
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001761bool BestPractices::ValidateCommonGetPhysicalDeviceQueueFamilyProperties(const PHYSICAL_DEVICE_STATE* pd_state,
1762 uint32_t requested_queue_family_property_count,
1763 bool qfp_null, const char* caller_name) const {
Camden05de2d42019-08-19 10:23:56 -06001764 bool skip = false;
1765 if (!qfp_null) {
1766 // 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 -06001767 const auto* bp_pd_state = GetPhysicalDeviceStateBP(pd_state->phys_device);
1768 if (bp_pd_state) {
1769 if (UNCALLED == bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState) {
1770 skip |= LogWarning(
1771 pd_state->phys_device, kVUID_Core_DevLimit_MissingQueryCount,
1772 "%s is called with non-NULL pQueueFamilyProperties before obtaining pQueueFamilyPropertyCount. It is "
1773 "recommended "
1774 "to first call %s with NULL pQueueFamilyProperties in order to obtain the maximal pQueueFamilyPropertyCount.",
1775 caller_name, caller_name);
1776 // Then verify that pCount that is passed in on second call matches what was returned
1777 } else if (pd_state->queue_family_known_count != requested_queue_family_property_count) {
1778 skip |=
1779 LogWarning(pd_state->phys_device, kVUID_Core_DevLimit_CountMismatch,
1780 "%s is called with non-NULL pQueueFamilyProperties and pQueueFamilyPropertyCount value %" PRIu32
1781 ", but the largest previously returned pQueueFamilyPropertyCount for this physicalDevice is %" PRIu32
1782 ". It is recommended to instead receive all the properties by calling %s with "
1783 "pQueueFamilyPropertyCount that was "
1784 "previously obtained by calling %s with NULL pQueueFamilyProperties.",
1785 caller_name, requested_queue_family_property_count, pd_state->queue_family_known_count, caller_name,
1786 caller_name);
1787 }
Camden05de2d42019-08-19 10:23:56 -06001788 }
1789 }
1790
1791 return skip;
1792}
1793
Jeff Bolz5c801d12019-10-09 10:38:45 -05001794bool BestPractices::PreCallValidateBindAccelerationStructureMemoryNV(
1795 VkDevice device, uint32_t bindInfoCount, const VkBindAccelerationStructureMemoryInfoNV* pBindInfos) const {
Camden Stocker82510582019-09-03 14:00:16 -06001796 bool skip = false;
1797
1798 for (uint32_t i = 0; i < bindInfoCount; i++) {
1799 const ACCELERATION_STRUCTURE_STATE* as_state = GetAccelerationStructureState(pBindInfos[i].accelerationStructure);
1800 if (!as_state->memory_requirements_checked) {
1801 // There's not an explicit requirement in the spec to call vkGetImageMemoryRequirements() prior to calling
1802 // BindAccelerationStructureMemoryNV but it's implied in that memory being bound must conform with
1803 // VkAccelerationStructureMemoryRequirementsInfoNV from vkGetAccelerationStructureMemoryRequirementsNV
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001804 skip |= LogWarning(
1805 device, kVUID_BestPractices_BindAccelNV_NoMemReqQuery,
Camden Stocker82510582019-09-03 14:00:16 -06001806 "vkBindAccelerationStructureMemoryNV(): "
1807 "Binding memory to %s but vkGetAccelerationStructureMemoryRequirementsNV() has not been called on that structure.",
1808 report_data->FormatHandle(pBindInfos[i].accelerationStructure).c_str());
1809 }
1810 }
1811
1812 return skip;
1813}
1814
Camden05de2d42019-08-19 10:23:56 -06001815bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
1816 uint32_t* pQueueFamilyPropertyCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001817 VkQueueFamilyProperties* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06001818 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1819 assert(physical_device_state);
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001820 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
Camden05de2d42019-08-19 10:23:56 -06001821 (nullptr == pQueueFamilyProperties),
1822 "vkGetPhysicalDeviceQueueFamilyProperties()");
1823}
1824
Jeff Bolz5c801d12019-10-09 10:38:45 -05001825bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2(
1826 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount,
1827 VkQueueFamilyProperties2KHR* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06001828 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1829 assert(physical_device_state);
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001830 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
Camden05de2d42019-08-19 10:23:56 -06001831 (nullptr == pQueueFamilyProperties),
1832 "vkGetPhysicalDeviceQueueFamilyProperties2()");
1833}
1834
Jeff Bolz5c801d12019-10-09 10:38:45 -05001835bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2KHR(
1836 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount,
1837 VkQueueFamilyProperties2KHR* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06001838 auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1839 assert(physical_device_state);
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001840 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
Camden05de2d42019-08-19 10:23:56 -06001841 (nullptr == pQueueFamilyProperties),
1842 "vkGetPhysicalDeviceQueueFamilyProperties2KHR()");
1843}
1844
1845bool BestPractices::PreCallValidateGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
1846 uint32_t* pSurfaceFormatCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001847 VkSurfaceFormatKHR* pSurfaceFormats) const {
Camden05de2d42019-08-19 10:23:56 -06001848 if (!pSurfaceFormats) return false;
1849 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001850 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
1851 const auto& call_state = bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState;
Camden05de2d42019-08-19 10:23:56 -06001852 bool skip = false;
1853 if (call_state == UNCALLED) {
1854 // Since we haven't recorded a preliminary value of *pSurfaceFormatCount, that likely means that the application didn't
1855 // previously call this function with a NULL value of pSurfaceFormats:
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001856 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_MustQueryCount,
1857 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount; but no prior "
1858 "positive value has been seen for pSurfaceFormats.");
Camden05de2d42019-08-19 10:23:56 -06001859 } else {
1860 auto prev_format_count = (uint32_t)physical_device_state->surface_formats.size();
Peter Chene191bd72019-09-16 13:04:37 -04001861 if (*pSurfaceFormatCount > prev_format_count) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001862 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_CountMismatch,
1863 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount, and with "
1864 "pSurfaceFormats set to a value (%u) that is greater than the value (%u) that was returned "
1865 "when pSurfaceFormatCount was NULL.",
1866 *pSurfaceFormatCount, prev_format_count);
Camden05de2d42019-08-19 10:23:56 -06001867 }
1868 }
1869 return skip;
1870}
Camden Stocker23cc47d2019-09-03 14:53:57 -06001871
1872bool BestPractices::PreCallValidateQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001873 VkFence fence) const {
Camden Stocker23cc47d2019-09-03 14:53:57 -06001874 bool skip = false;
1875
1876 for (uint32_t bindIdx = 0; bindIdx < bindInfoCount; bindIdx++) {
1877 const VkBindSparseInfo& bindInfo = pBindInfo[bindIdx];
1878 // Store sparse binding image_state and after binding is complete make sure that any requiring metadata have it bound
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001879 std::unordered_set<const IMAGE_STATE*> sparse_images;
1880 // Track images getting metadata bound by this call in a set, it'll be recorded into the image_state
1881 // in RecordQueueBindSparse.
1882 std::unordered_set<const IMAGE_STATE*> sparse_images_with_metadata;
Camden Stocker23cc47d2019-09-03 14:53:57 -06001883 // If we're binding sparse image memory make sure reqs were queried and note if metadata is required and bound
1884 for (uint32_t i = 0; i < bindInfo.imageBindCount; ++i) {
1885 const auto& image_bind = bindInfo.pImageBinds[i];
1886 auto image_state = GetImageState(image_bind.image);
1887 if (!image_state)
1888 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
1889 sparse_images.insert(image_state);
1890 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
1891 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
1892 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001893 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1894 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
1895 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
1896 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001897 }
1898 }
1899 if (!image_state->memory_requirements_checked) {
1900 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001901 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1902 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
1903 "vkGetImageMemoryRequirements() to retrieve requirements.",
1904 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001905 }
1906 }
1907 for (uint32_t i = 0; i < bindInfo.imageOpaqueBindCount; ++i) {
1908 const auto& image_opaque_bind = bindInfo.pImageOpaqueBinds[i];
1909 auto image_state = GetImageState(bindInfo.pImageOpaqueBinds[i].image);
1910 if (!image_state)
1911 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
1912 sparse_images.insert(image_state);
1913 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
1914 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
1915 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001916 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1917 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
1918 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
1919 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001920 }
1921 }
1922 if (!image_state->memory_requirements_checked) {
1923 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001924 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1925 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
1926 "vkGetImageMemoryRequirements() to retrieve requirements.",
1927 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001928 }
1929 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
1930 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001931 sparse_images_with_metadata.insert(image_state);
Camden Stocker23cc47d2019-09-03 14:53:57 -06001932 }
1933 }
1934 }
1935 for (const auto& sparse_image_state : sparse_images) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001936 if (sparse_image_state->sparse_metadata_required && !sparse_image_state->sparse_metadata_bound &&
1937 sparse_images_with_metadata.find(sparse_image_state) == sparse_images_with_metadata.end()) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06001938 // Warn if sparse image binding metadata required for image with sparse binding, but metadata not bound
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001939 skip |= LogWarning(sparse_image_state->image, kVUID_Core_MemTrack_InvalidState,
1940 "vkQueueBindSparse(): Binding sparse memory to %s which requires a metadata aspect but no "
1941 "binding with VK_SPARSE_MEMORY_BIND_METADATA_BIT set was made.",
1942 report_data->FormatHandle(sparse_image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001943 }
1944 }
1945 }
1946
1947 return skip;
1948}
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001949
Mark Lobodzinski84101d72020-04-24 09:43:48 -06001950void BestPractices::ManualPostCallRecordQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
1951 VkFence fence, VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07001952 if (result != VK_SUCCESS) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07001953 return;
1954 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001955
1956 for (uint32_t bindIdx = 0; bindIdx < bindInfoCount; bindIdx++) {
1957 const VkBindSparseInfo& bindInfo = pBindInfo[bindIdx];
1958 for (uint32_t i = 0; i < bindInfo.imageOpaqueBindCount; ++i) {
1959 const auto& image_opaque_bind = bindInfo.pImageOpaqueBinds[i];
1960 auto image_state = GetImageState(bindInfo.pImageOpaqueBinds[i].image);
1961 if (!image_state)
1962 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
1963 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
1964 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
1965 image_state->sparse_metadata_bound = true;
1966 }
1967 }
1968 }
1969 }
1970}
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001971
1972bool BestPractices::PreCallValidateCmdClearAttachments(VkCommandBuffer commandBuffer, uint32_t attachmentCount,
Camden Stockerf55721f2019-09-09 11:04:49 -06001973 const VkClearAttachment* pAttachments, uint32_t rectCount,
1974 const VkClearRect* pRects) const {
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001975 bool skip = false;
1976 const CMD_BUFFER_STATE* cb_node = GetCBState(commandBuffer);
1977 if (!cb_node) return skip;
1978
Camden Stockerf55721f2019-09-09 11:04:49 -06001979 // Warn if this is issued prior to Draw Cmd and clearing the entire attachment
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001980 if (!cb_node->hasDrawCmd && (cb_node->activeRenderPassBeginInfo.renderArea.extent.width == pRects[0].rect.extent.width) &&
1981 (cb_node->activeRenderPassBeginInfo.renderArea.extent.height == pRects[0].rect.extent.height)) {
1982 // There are times where app needs to use ClearAttachments (generally when reusing a buffer inside of a render pass)
1983 // This warning should be made more specific. It'd be best to avoid triggering this test if it's a use that must call
1984 // CmdClearAttachments.
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001985 skip |= LogPerformanceWarning(commandBuffer, kVUID_BestPractices_DrawState_ClearCmdBeforeDraw,
1986 "vkCmdClearAttachments() issued on %s prior to any Draw Cmds. It is recommended you "
1987 "use RenderPass LOAD_OP_CLEAR on Attachments prior to any Draw.",
1988 report_data->FormatHandle(commandBuffer).c_str());
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001989 }
1990
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001991 // Check for uses of ClearAttachments along with LOAD_OP_LOAD,
1992 // as it can be more efficient to just use LOAD_OP_CLEAR
locke-lunargaecf2152020-05-12 17:15:41 -06001993 const RENDER_PASS_STATE* rp = cb_node->activeRenderPass.get();
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001994 if (rp) {
1995 const auto& subpass = rp->createInfo.pSubpasses[cb_node->activeSubpass];
1996
1997 for (uint32_t i = 0; i < attachmentCount; i++) {
1998 auto& attachment = pAttachments[i];
1999 if (attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
2000 uint32_t color_attachment = attachment.colorAttachment;
2001 uint32_t fb_attachment = subpass.pColorAttachments[color_attachment].attachment;
2002
2003 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2004 if (rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2005 skip |= LogPerformanceWarning(
2006 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2007 "vkCmdClearAttachments() issued on %s for color attachment #%u in this subpass, "
2008 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2009 "it is more efficient.",
2010 report_data->FormatHandle(commandBuffer).c_str(), color_attachment);
2011 }
2012 }
2013 }
2014
2015 if (subpass.pDepthStencilAttachment && attachment.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) {
2016 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
2017
2018 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2019 if (rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2020 skip |= LogPerformanceWarning(
2021 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2022 "vkCmdClearAttachments() issued on %s for the depth attachment in this subpass, "
2023 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2024 "it is more efficient.",
2025 report_data->FormatHandle(commandBuffer).c_str());
2026 }
2027 }
2028 }
2029
2030 if (subpass.pDepthStencilAttachment && attachment.aspectMask & VK_IMAGE_ASPECT_STENCIL_BIT) {
2031 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
2032
2033 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2034 if (rp->createInfo.pAttachments[fb_attachment].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2035 skip |= LogPerformanceWarning(
2036 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2037 "vkCmdClearAttachments() issued on %s for the stencil attachment in this subpass, "
2038 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2039 "it is more efficient.",
2040 report_data->FormatHandle(commandBuffer).c_str());
2041 }
2042 }
2043 }
2044 }
2045 }
2046
Camden Stockerf55721f2019-09-09 11:04:49 -06002047 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002048}
Attilio Provenzano02859b22020-02-27 14:17:28 +00002049
2050bool BestPractices::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
2051 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
2052 const VkImageResolve* pRegions) const {
2053 bool skip = false;
2054
2055 skip |= VendorCheckEnabled(kBPVendorArm) &&
2056 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage_ResolvingImage,
2057 "%s Attempting to use vkCmdResolveImage to resolve a multisampled image. "
2058 "This is a very slow and extremely bandwidth intensive path. "
2059 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
2060 VendorSpecificTag(kBPVendorArm));
2061
2062 return skip;
2063}
2064
Jeff Leger178b1e52020-10-05 12:22:23 -04002065bool BestPractices::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
2066 const VkResolveImageInfo2KHR* pResolveImageInfo) const {
2067 bool skip = false;
2068
2069 skip |= VendorCheckEnabled(kBPVendorArm) &&
2070 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2KHR_ResolvingImage,
2071 "%s Attempting to use vkCmdResolveImage2KHR to resolve a multisampled image. "
2072 "This is a very slow and extremely bandwidth intensive path. "
2073 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
2074 VendorSpecificTag(kBPVendorArm));
2075
2076 return skip;
2077}
2078
Attilio Provenzano02859b22020-02-27 14:17:28 +00002079bool BestPractices::PreCallValidateCreateSampler(VkDevice device, const VkSamplerCreateInfo* pCreateInfo,
2080 const VkAllocationCallbacks* pAllocator, VkSampler* pSampler) const {
2081 bool skip = false;
2082
2083 if (VendorCheckEnabled(kBPVendorArm)) {
2084 if ((pCreateInfo->addressModeU != pCreateInfo->addressModeV) || (pCreateInfo->addressModeV != pCreateInfo->addressModeW)) {
2085 skip |= LogPerformanceWarning(
2086 device, kVUID_BestPractices_CreateSampler_DifferentWrappingModes,
2087 "%s Creating a sampler object with wrapping modes which do not match (U = %u, V = %u, W = %u). "
2088 "This may cause reduced performance even if only U (1D image) or U/V wrapping modes (2D "
2089 "image) are actually used. If you need different wrapping modes, disregard this warning.",
2090 VendorSpecificTag(kBPVendorArm));
2091 }
2092
2093 if ((pCreateInfo->minLod != 0.0f) || (pCreateInfo->maxLod < VK_LOD_CLAMP_NONE)) {
2094 skip |= LogPerformanceWarning(
2095 device, kVUID_BestPractices_CreateSampler_LodClamping,
2096 "%s Creating a sampler object with LOD clamping (minLod = %f, maxLod = %f). This may cause reduced performance. "
2097 "Instead of clamping LOD in the sampler, consider using an VkImageView which restricts the mip-levels, set minLod "
2098 "to 0.0, and maxLod to VK_LOD_CLAMP_NONE.",
2099 VendorSpecificTag(kBPVendorArm), pCreateInfo->minLod, pCreateInfo->maxLod);
2100 }
2101
2102 if (pCreateInfo->mipLodBias != 0.0f) {
2103 skip |=
2104 LogPerformanceWarning(device, kVUID_BestPractices_CreateSampler_LodBias,
2105 "%s Creating a sampler object with LOD bias != 0.0 (%f). This will lead to less efficient "
2106 "descriptors being created and may cause reduced performance.",
2107 VendorSpecificTag(kBPVendorArm), pCreateInfo->mipLodBias);
2108 }
2109
2110 if ((pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
2111 pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
2112 pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER) &&
2113 (pCreateInfo->borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK)) {
2114 skip |= LogPerformanceWarning(
2115 device, kVUID_BestPractices_CreateSampler_BorderClampColor,
2116 "%s Creating a sampler object with border clamping and borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK. "
2117 "This will lead to less efficient descriptors being created and may cause reduced performance. "
2118 "If possible, use VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK as the border color.",
2119 VendorSpecificTag(kBPVendorArm));
2120 }
2121
2122 if (pCreateInfo->unnormalizedCoordinates) {
2123 skip |= LogPerformanceWarning(
2124 device, kVUID_BestPractices_CreateSampler_UnnormalizedCoordinates,
2125 "%s Creating a sampler object with unnormalized coordinates. This will lead to less efficient "
2126 "descriptors being created and may cause reduced performance.",
2127 VendorSpecificTag(kBPVendorArm));
2128 }
2129
2130 if (pCreateInfo->anisotropyEnable) {
2131 skip |= LogPerformanceWarning(
2132 device, kVUID_BestPractices_CreateSampler_Anisotropy,
2133 "%s Creating a sampler object with anisotropy. This will lead to less efficient descriptors being created "
2134 "and may cause reduced performance.",
2135 VendorSpecificTag(kBPVendorArm));
2136 }
2137 }
2138
2139 return skip;
2140}
Sam Walls8e77e4f2020-03-16 20:47:40 +00002141
2142void BestPractices::PostTransformLRUCacheModel::resize(size_t size) { _entries.resize(size); }
2143
2144bool BestPractices::PostTransformLRUCacheModel::query_cache(uint32_t value) {
2145 // look for a cache hit
2146 auto hit = std::find_if(_entries.begin(), _entries.end(), [value](const CacheEntry& entry) { return entry.value == value; });
2147 if (hit != _entries.end()) {
2148 // mark the cache hit as being most recently used
2149 hit->age = iteration++;
2150 return true;
2151 }
2152
2153 // if there's no cache hit, we need to model the entry being inserted into the cache
2154 CacheEntry new_entry = {value, iteration};
2155 if (iteration < static_cast<uint32_t>(std::distance(_entries.begin(), _entries.end()))) {
2156 // if there is still space left in the cache, use the next available slot
2157 *(_entries.begin() + iteration) = new_entry;
2158 } else {
2159 // otherwise replace the least recently used cache entry
2160 auto lru = std::min_element(_entries.begin(), hit, [](const CacheEntry& a, const CacheEntry& b) { return a.age < b.age; });
2161 *lru = new_entry;
2162 }
2163 iteration++;
2164 return false;
2165}
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002166
2167bool BestPractices::PreCallValidateAcquireNextImageKHR(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout,
2168 VkSemaphore semaphore, VkFence fence, uint32_t* pImageIndex) const {
2169 const auto swapchain_data = GetSwapchainState(swapchain);
2170 bool skip = false;
2171 if (swapchain_data && swapchain_data->images.size() == 0) {
2172 skip |= LogWarning(swapchain, kVUID_Core_DrawState_SwapchainImagesNotFound,
2173 "vkAcquireNextImageKHR: No images found to acquire from. Application probably did not call "
2174 "vkGetSwapchainImagesKHR after swapchain creation.");
2175 }
2176 return skip;
2177}
2178
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002179void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
2180 uint32_t* pQueueFamilyPropertyCount,
2181 VkQueueFamilyProperties* pQueueFamilyProperties) {
2182 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(physicalDevice, pQueueFamilyPropertyCount,
2183 pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002184 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002185 if (bp_pd_state) {
2186 if (!pQueueFamilyProperties) {
2187 if (UNCALLED == bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState)
2188 bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState = QUERY_COUNT;
2189 } else { // Save queue family properties
2190 bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState = QUERY_DETAILS;
2191 }
2192 }
2193}
2194
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002195void BestPractices::PostCallRecordGetPhysicalDeviceFeatures(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures* pFeatures) {
2196 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002197 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2198 if (bp_pd_state) {
2199 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
2200 }
2201}
2202
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002203void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2(VkPhysicalDevice physicalDevice,
2204 VkPhysicalDeviceFeatures2* pFeatures) {
2205 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002206 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2207 if (bp_pd_state) {
2208 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
2209 }
2210}
2211
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002212void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2KHR(VkPhysicalDevice physicalDevice,
2213 VkPhysicalDeviceFeatures2* pFeatures) {
2214 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2KHR(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002215 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2216 if (bp_pd_state) {
2217 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
2218 }
2219}
2220
2221void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilitiesKHR(VkPhysicalDevice physicalDevice,
2222 VkSurfaceKHR surface,
2223 VkSurfaceCapabilitiesKHR* pSurfaceCapabilities,
2224 VkResult result) {
2225 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2226 if (bp_pd_state) {
2227 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
2228 }
2229}
2230
2231void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2KHR(
2232 VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
2233 VkSurfaceCapabilities2KHR* pSurfaceCapabilities, VkResult result) {
2234 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2235 if (bp_pd_state) {
2236 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
2237 }
2238}
2239
2240void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2EXT(VkPhysicalDevice physicalDevice,
2241 VkSurfaceKHR surface,
2242 VkSurfaceCapabilities2EXT* pSurfaceCapabilities,
2243 VkResult result) {
2244 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2245 if (bp_pd_state) {
2246 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
2247 }
2248}
2249
2250void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice physicalDevice,
2251 VkSurfaceKHR surface, uint32_t* pPresentModeCount,
2252 VkPresentModeKHR* pPresentModes, VkResult result) {
2253 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2254 if (bp_pd_data) {
2255 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfacePresentModesKHRState;
2256
2257 if (*pPresentModeCount) {
2258 if (call_state < QUERY_COUNT) {
2259 call_state = QUERY_COUNT;
2260 }
2261 }
2262 if (pPresentModes) {
2263 if (call_state < QUERY_DETAILS) {
2264 call_state = QUERY_DETAILS;
2265 }
2266 }
2267 }
2268}
2269
2270void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
2271 uint32_t* pSurfaceFormatCount,
2272 VkSurfaceFormatKHR* pSurfaceFormats, VkResult result) {
2273 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2274 if (bp_pd_data) {
2275 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState;
2276
2277 if (*pSurfaceFormatCount) {
2278 if (call_state < QUERY_COUNT) {
2279 call_state = QUERY_COUNT;
2280 }
2281 }
2282 if (pSurfaceFormats) {
2283 if (call_state < QUERY_DETAILS) {
2284 call_state = QUERY_DETAILS;
2285 }
2286 }
2287 }
2288}
2289
2290void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormats2KHR(VkPhysicalDevice physicalDevice,
2291 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
2292 uint32_t* pSurfaceFormatCount,
2293 VkSurfaceFormat2KHR* pSurfaceFormats, VkResult result) {
2294 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2295 if (bp_pd_data) {
2296 if (*pSurfaceFormatCount) {
2297 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_COUNT) {
2298 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_COUNT;
2299 }
2300 }
2301 if (pSurfaceFormats) {
2302 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_DETAILS) {
2303 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_DETAILS;
2304 }
2305 }
2306 }
2307}
2308
2309void BestPractices::ManualPostCallRecordGetPhysicalDeviceDisplayPlanePropertiesKHR(VkPhysicalDevice physicalDevice,
2310 uint32_t* pPropertyCount,
2311 VkDisplayPlanePropertiesKHR* pProperties,
2312 VkResult result) {
2313 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2314 if (bp_pd_data) {
2315 if (*pPropertyCount) {
2316 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_COUNT) {
2317 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_COUNT;
2318 }
2319 }
2320 if (pProperties) {
2321 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_DETAILS) {
2322 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_DETAILS;
2323 }
2324 }
2325 }
2326}
2327
2328void BestPractices::ManualPostCallRecordCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
2329 const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain,
2330 VkResult result) {
2331 if (VK_SUCCESS == result) {
2332 swapchain_bp_state_map.emplace(*pSwapchain, SWAPCHAIN_STATE_BP{});
2333 }
2334}
2335
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002336void BestPractices::PostCallRecordDestroySwapchainKHR(VkDevice device, VkSwapchainKHR swapchain,
2337 const VkAllocationCallbacks* pAllocator) {
2338 ValidationStateTracker::PostCallRecordDestroySwapchainKHR(device, swapchain, pAllocator);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002339 auto swapchain_state_itr = swapchain_bp_state_map.find(swapchain);
2340 if (swapchain_state_itr != swapchain_bp_state_map.cend()) {
2341 swapchain_bp_state_map.erase(swapchain_state_itr);
2342 }
2343}
2344
2345void BestPractices::ManualPostCallRecordGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain,
2346 uint32_t* pSwapchainImageCount, VkImage* pSwapchainImages,
2347 VkResult result) {
2348 auto swapchain_state_itr = swapchain_bp_state_map.find(swapchain);
2349 assert(swapchain_state_itr != swapchain_bp_state_map.cend());
2350 auto& swapchain_state = swapchain_state_itr->second;
2351 if (pSwapchainImages || *pSwapchainImageCount) {
2352 if (swapchain_state.vkGetSwapchainImagesKHRState < QUERY_DETAILS) {
2353 swapchain_state.vkGetSwapchainImagesKHRState = QUERY_DETAILS;
2354 }
2355 }
2356}
2357
2358void BestPractices::ManualPostCallRecordEnumeratePhysicalDevices(VkInstance instance, uint32_t* pPhysicalDeviceCount,
2359 VkPhysicalDevice* pPhysicalDevices, VkResult result) {
2360 if ((nullptr != pPhysicalDevices) && ((result == VK_SUCCESS || result == VK_INCOMPLETE))) {
2361 for (uint32_t i = 0; i < *pPhysicalDeviceCount; i++) {
2362 phys_device_bp_state_map.emplace(pPhysicalDevices[i], PHYSICAL_DEVICE_STATE_BP{});
2363 }
2364 }
2365}
2366
2367void BestPractices::ManualPostCallRecordCreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo*, const VkAllocationCallbacks*,
2368 VkDevice*, VkResult result) {
2369 if (VK_SUCCESS == result) {
2370 instance_device_bp_state = &phys_device_bp_state_map[gpu];
2371 }
2372}
2373
2374PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP(const VkPhysicalDevice& phys_device) {
2375 if (phys_device_bp_state_map.count(phys_device) > 0) {
2376 return &phys_device_bp_state_map.at(phys_device);
2377 } else {
2378 return nullptr;
2379 }
2380}
2381
2382const PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP(const VkPhysicalDevice& phys_device) const {
2383 if (phys_device_bp_state_map.count(phys_device) > 0) {
2384 return &phys_device_bp_state_map.at(phys_device);
2385 } else {
2386 return nullptr;
2387 }
2388}
2389
2390PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP() {
2391 auto bp_state = (reinterpret_cast<BestPractices*>(instance_state))->instance_device_bp_state;
2392 if (bp_state) {
2393 return bp_state;
2394 } else if (!bp_state && phys_device_bp_state_map.count(physical_device_state->phys_device) > 0) {
2395 return &phys_device_bp_state_map.at(physical_device_state->phys_device);
2396 } else {
2397 return nullptr;
2398 }
2399}
2400
2401const PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP() const {
2402 auto bp_state = (reinterpret_cast<BestPractices*>(instance_state))->instance_device_bp_state;
2403 if (bp_state) {
2404 return bp_state;
2405 } else if (!bp_state && phys_device_bp_state_map.count(physical_device_state->phys_device) > 0) {
2406 return &phys_device_bp_state_map.at(physical_device_state->phys_device);
2407 } else {
2408 return nullptr;
2409 }
2410}