blob: 1627dc7d5c4fac345a1d026da3938ec5280bb560 [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
Camden5b184be2019-08-13 07:50:19 -0600120bool BestPractices::PreCallValidateCreateInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500121 VkInstance* pInstance) const {
Camden5b184be2019-08-13 07:50:19 -0600122 bool skip = false;
123
124 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
125 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kDeviceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800126 skip |= LogWarning(instance, kVUID_BestPractices_CreateInstance_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700127 "vkCreateInstance(): Attempting to enable Device Extension %s at CreateInstance time.",
128 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600129 }
Mark Lobodzinski17d8dc62020-06-03 08:48:58 -0600130 uint32_t specified_version =
131 (pCreateInfo->pApplicationInfo ? pCreateInfo->pApplicationInfo->apiVersion : VK_API_VERSION_1_0);
132 skip |= ValidateDeprecatedExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i], specified_version,
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700133 kVUID_BestPractices_CreateInstance_DeprecatedExtension);
Camden5b184be2019-08-13 07:50:19 -0600134 }
135
136 return skip;
137}
138
139void BestPractices::PreCallRecordCreateInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator,
140 VkInstance* pInstance) {
Mark Lobodzinski97484d62020-03-03 11:57:41 -0700141 ValidationStateTracker::PreCallRecordCreateInstance(pCreateInfo, pAllocator, pInstance);
Sam Walls53bf7652020-04-21 17:35:15 +0100142
143 if (pCreateInfo != nullptr && pCreateInfo->pApplicationInfo != nullptr)
144 instance_api_version = pCreateInfo->pApplicationInfo->apiVersion;
145 else
146 instance_api_version = 0;
Camden5b184be2019-08-13 07:50:19 -0600147}
148
149bool BestPractices::PreCallValidateCreateDevice(VkPhysicalDevice physicalDevice, const VkDeviceCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500150 const VkAllocationCallbacks* pAllocator, VkDevice* pDevice) const {
Camden5b184be2019-08-13 07:50:19 -0600151 bool skip = false;
152
153 // get API version of physical device passed when creating device.
154 VkPhysicalDeviceProperties physical_device_properties{};
155 DispatchGetPhysicalDeviceProperties(physicalDevice, &physical_device_properties);
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500156 auto device_api_version = physical_device_properties.apiVersion;
Camden5b184be2019-08-13 07:50:19 -0600157
158 // check api versions and warn if instance api Version is higher than version on device.
159 if (instance_api_version > device_api_version) {
Mark Lobodzinski60880782020-08-11 08:02:07 -0600160 std::string inst_api_name = StringAPIVersion(instance_api_version);
161 std::string dev_api_name = StringAPIVersion(device_api_version);
Camden5b184be2019-08-13 07:50:19 -0600162
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700163 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_API_Mismatch,
164 "vkCreateDevice(): API Version of current instance, %s is higher than API Version on device, %s",
165 inst_api_name.c_str(), dev_api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -0600166 }
167
168 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
169 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kInstanceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800170 skip |= LogWarning(instance, kVUID_BestPractices_CreateDevice_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700171 "vkCreateDevice(): Attempting to enable Instance Extension %s at CreateDevice time.",
172 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600173 }
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700174 skip |= ValidateDeprecatedExtensions("CreateDevice", pCreateInfo->ppEnabledExtensionNames[i], instance_api_version,
175 kVUID_BestPractices_CreateDevice_DeprecatedExtension);
Camden5b184be2019-08-13 07:50:19 -0600176 }
177
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600178 const auto bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
179 if ((bp_pd_state->vkGetPhysicalDeviceFeaturesState == UNCALLED) && (pCreateInfo->pEnabledFeatures != NULL)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700180 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_PDFeaturesNotCalled,
181 "vkCreateDevice() called before getting physical device features from vkGetPhysicalDeviceFeatures().");
Camden83a9c372019-08-14 11:41:38 -0600182 }
183
Szilard Papp7d2c7952020-06-22 14:38:13 +0100184 if ((VendorCheckEnabled(kBPVendorArm)) && (pCreateInfo->pEnabledFeatures != nullptr) &&
185 (pCreateInfo->pEnabledFeatures->robustBufferAccess == VK_TRUE)) {
186 skip |= LogPerformanceWarning(
187 device, kVUID_BestPractices_CreateDevice_RobustBufferAccess,
188 "%s vkCreateDevice() called with enabled robustBufferAccess. Use robustBufferAccess as a debugging tool during "
189 "development. Enabling it causes loss in performance for accesses to uniform buffers and shader storage "
190 "buffers. Disable robustBufferAccess in release builds. Only leave it enabled if the application use-case "
191 "requires the additional level of reliability due to the use of unverified user-supplied draw parameters.",
192 VendorSpecificTag(kBPVendorArm));
193 }
194
Camden5b184be2019-08-13 07:50:19 -0600195 return skip;
196}
197
198bool BestPractices::PreCallValidateCreateBuffer(VkDevice device, const VkBufferCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500199 const VkAllocationCallbacks* pAllocator, VkBuffer* pBuffer) const {
Camden5b184be2019-08-13 07:50:19 -0600200 bool skip = false;
201
202 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
203 std::stringstream bufferHex;
204 bufferHex << "0x" << std::hex << HandleToUint64(pBuffer);
205
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700206 skip |= LogWarning(
207 device, kVUID_BestPractices_SharingModeExclusive,
208 "Warning: Buffer (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
209 "(queueFamilyIndexCount of %" PRIu32 ").",
210 bufferHex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600211 }
212
213 return skip;
214}
215
216bool BestPractices::PreCallValidateCreateImage(VkDevice device, const VkImageCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500217 const VkAllocationCallbacks* pAllocator, VkImage* pImage) const {
Camden5b184be2019-08-13 07:50:19 -0600218 bool skip = false;
219
220 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
221 std::stringstream imageHex;
222 imageHex << "0x" << std::hex << HandleToUint64(pImage);
223
224 skip |=
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700225 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
226 "Warning: Image (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
227 "(queueFamilyIndexCount of %" PRIu32 ").",
228 imageHex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600229 }
230
Attilio Provenzano02859b22020-02-27 14:17:28 +0000231 if (VendorCheckEnabled(kBPVendorArm)) {
232 if (pCreateInfo->samples > kMaxEfficientSamplesArm) {
233 skip |= LogPerformanceWarning(
234 device, kVUID_BestPractices_CreateImage_TooLargeSampleCount,
235 "%s vkCreateImage(): Trying to create an image with %u samples. "
236 "The hardware revision may not have full throughput for framebuffers with more than %u samples.",
237 VendorSpecificTag(kBPVendorArm), static_cast<uint32_t>(pCreateInfo->samples), kMaxEfficientSamplesArm);
238 }
239
240 if (pCreateInfo->samples > VK_SAMPLE_COUNT_1_BIT && !(pCreateInfo->usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT)) {
241 skip |= LogPerformanceWarning(
242 device, kVUID_BestPractices_CreateImage_NonTransientMSImage,
243 "%s vkCreateImage(): Trying to create a multisampled image, but createInfo.usage did not have "
244 "VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. Multisampled images may be resolved on-chip, "
245 "and do not need to be backed by physical storage. "
246 "TRANSIENT_ATTACHMENT allows tiled GPUs to not back the multisampled image with physical memory.",
247 VendorSpecificTag(kBPVendorArm));
248 }
249 }
250
Camden5b184be2019-08-13 07:50:19 -0600251 return skip;
252}
253
254bool BestPractices::PreCallValidateCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500255 const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain) const {
Camden5b184be2019-08-13 07:50:19 -0600256 bool skip = false;
257
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600258 const auto* bp_pd_state = GetPhysicalDeviceStateBP();
259 if (bp_pd_state) {
260 if (bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState == UNCALLED) {
261 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
262 "vkCreateSwapchainKHR() called before getting surface capabilities from "
263 "vkGetPhysicalDeviceSurfaceCapabilitiesKHR().");
264 }
Camden83a9c372019-08-14 11:41:38 -0600265
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600266 if (bp_pd_state->vkGetPhysicalDeviceSurfacePresentModesKHRState != QUERY_DETAILS) {
267 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
268 "vkCreateSwapchainKHR() called before getting surface present mode(s) from "
269 "vkGetPhysicalDeviceSurfacePresentModesKHR().");
270 }
Camden83a9c372019-08-14 11:41:38 -0600271
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600272 if (bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState != QUERY_DETAILS) {
273 skip |= LogWarning(
274 device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
275 "vkCreateSwapchainKHR() called before getting surface format(s) from vkGetPhysicalDeviceSurfaceFormatsKHR().");
276 }
Camden83a9c372019-08-14 11:41:38 -0600277 }
278
Camden5b184be2019-08-13 07:50:19 -0600279 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700280 skip |=
281 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
Mark Lobodzinski019f4e32020-04-13 11:01:35 -0600282 "Warning: A Swapchain is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while "
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700283 "specifying multiple queues (queueFamilyIndexCount of %" PRIu32 ").",
284 pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600285 }
286
Szilard Papp48a6da32020-06-10 14:41:59 +0100287 if (pCreateInfo->minImageCount == 2) {
288 skip |= LogPerformanceWarning(
289 device, kVUID_BestPractices_SuboptimalSwapchainImageCount,
290 "Warning: A Swapchain is being created with minImageCount set to %" PRIu32
291 ", which means double buffering is going "
292 "to be used. Using double buffering and vsync locks rendering to an integer fraction of the vsync rate. In turn, "
293 "reducing the performance of the application if rendering is slower than vsync. Consider setting minImageCount to "
294 "3 to use triple buffering to maximize performance in such cases.",
295 pCreateInfo->minImageCount);
296 }
297
Szilard Pappd5f0f812020-06-22 09:01:29 +0100298 if (VendorCheckEnabled(kBPVendorArm) && (pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR)) {
299 skip |= LogWarning(device, kVUID_BestPractices_CreateSwapchain_PresentMode,
300 "%s Warning: Swapchain is not being created with presentation mode \"VK_PRESENT_MODE_FIFO_KHR\". "
301 "Prefer using \"VK_PRESENT_MODE_FIFO_KHR\" to avoid unnecessary CPU and GPU load and save power. "
302 "Presentation modes which are not FIFO will present the latest available frame and discard other "
303 "frame(s) if any.",
304 VendorSpecificTag(kBPVendorArm));
305 }
306
Camden5b184be2019-08-13 07:50:19 -0600307 return skip;
308}
309
310bool BestPractices::PreCallValidateCreateSharedSwapchainsKHR(VkDevice device, uint32_t swapchainCount,
311 const VkSwapchainCreateInfoKHR* pCreateInfos,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500312 const VkAllocationCallbacks* pAllocator,
313 VkSwapchainKHR* pSwapchains) const {
Camden5b184be2019-08-13 07:50:19 -0600314 bool skip = false;
315
316 for (uint32_t i = 0; i < swapchainCount; i++) {
317 if ((pCreateInfos[i].queueFamilyIndexCount > 1) && (pCreateInfos[i].imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700318 skip |= LogWarning(
319 device, kVUID_BestPractices_SharingModeExclusive,
320 "Warning: A shared swapchain (index %" PRIu32
321 ") is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple "
322 "queues (queueFamilyIndexCount of %" PRIu32 ").",
323 i, pCreateInfos[i].queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600324 }
325 }
326
327 return skip;
328}
329
330bool BestPractices::PreCallValidateCreateRenderPass(VkDevice device, const VkRenderPassCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500331 const VkAllocationCallbacks* pAllocator, VkRenderPass* pRenderPass) const {
Camden5b184be2019-08-13 07:50:19 -0600332 bool skip = false;
333
334 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; ++i) {
335 VkFormat format = pCreateInfo->pAttachments[i].format;
336 if (pCreateInfo->pAttachments[i].initialLayout == VK_IMAGE_LAYOUT_UNDEFINED) {
337 if ((FormatIsColor(format) || FormatHasDepth(format)) &&
338 pCreateInfo->pAttachments[i].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700339 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
340 "Render pass has an attachment with loadOp == VK_ATTACHMENT_LOAD_OP_LOAD and "
341 "initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
342 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
343 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600344 }
345 if (FormatHasStencil(format) && pCreateInfo->pAttachments[i].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700346 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
347 "Render pass has an attachment with stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD "
348 "and initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
349 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
350 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600351 }
352 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000353
354 const auto& attachment = pCreateInfo->pAttachments[i];
355 if (attachment.samples > VK_SAMPLE_COUNT_1_BIT) {
356 bool access_requires_memory =
357 attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD || attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE;
358
359 if (FormatHasStencil(format)) {
360 access_requires_memory |= attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
361 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE;
362 }
363
364 if (access_requires_memory) {
365 skip |= LogPerformanceWarning(
366 device, kVUID_BestPractices_CreateRenderPass_ImageRequiresMemory,
367 "Attachment %u in the VkRenderPass is a multisampled image with %u samples, but it uses loadOp/storeOp "
368 "which requires accessing data from memory. Multisampled images should always be loadOp = CLEAR or DONT_CARE, "
369 "storeOp = DONT_CARE. This allows the implementation to use lazily allocated memory effectively.",
370 i, static_cast<uint32_t>(attachment.samples));
371 }
372 }
Camden5b184be2019-08-13 07:50:19 -0600373 }
374
375 for (uint32_t dependency = 0; dependency < pCreateInfo->dependencyCount; dependency++) {
376 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].srcStageMask);
377 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].dstStageMask);
378 }
379
380 return skip;
381}
382
Tony-LunarG767180f2020-04-23 14:03:59 -0600383bool BestPractices::ValidateAttachments(const VkRenderPassCreateInfo2* rpci, uint32_t attachmentCount,
384 const VkImageView* image_views) const {
385 bool skip = false;
386
387 // Check for non-transient attachments that should be transient and vice versa
388 for (uint32_t i = 0; i < attachmentCount; ++i) {
389 auto& attachment = rpci->pAttachments[i];
390 bool attachment_should_be_transient =
391 (attachment.loadOp != VK_ATTACHMENT_LOAD_OP_LOAD && attachment.storeOp != VK_ATTACHMENT_STORE_OP_STORE);
392
393 if (FormatHasStencil(attachment.format)) {
394 attachment_should_be_transient &= (attachment.stencilLoadOp != VK_ATTACHMENT_LOAD_OP_LOAD &&
395 attachment.stencilStoreOp != VK_ATTACHMENT_STORE_OP_STORE);
396 }
397
398 auto view_state = GetImageViewState(image_views[i]);
399 if (view_state) {
400 auto& ivci = view_state->create_info;
401 auto& ici = GetImageState(ivci.image)->createInfo;
402
403 bool image_is_transient = (ici.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) != 0;
404
405 // The check for an image that should not be transient applies to all GPUs
406 if (!attachment_should_be_transient && image_is_transient) {
407 skip |= LogPerformanceWarning(
408 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldNotBeTransient,
409 "Attachment %u in VkFramebuffer uses loadOp/storeOps which need to access physical memory, "
410 "but the image backing the image view has VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
411 "Physical memory will need to be backed lazily to this image, potentially causing stalls.",
412 i);
413 }
414
415 bool supports_lazy = false;
416 for (uint32_t j = 0; j < phys_dev_mem_props.memoryTypeCount; j++) {
417 if (phys_dev_mem_props.memoryTypes[j].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
418 supports_lazy = true;
419 }
420 }
421
422 // The check for an image that should be transient only applies to GPUs supporting
423 // lazily allocated memory
424 if (supports_lazy && attachment_should_be_transient && !image_is_transient) {
425 skip |= LogPerformanceWarning(
426 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldBeTransient,
427 "Attachment %u in VkFramebuffer uses loadOp/storeOps which never have to be backed by physical memory, "
428 "but the image backing the image view does not have VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
429 "You can save physical memory by using transient attachment backed by lazily allocated memory here.",
430 i);
431 }
432 }
433 }
434 return skip;
435}
436
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000437bool BestPractices::PreCallValidateCreateFramebuffer(VkDevice device, const VkFramebufferCreateInfo* pCreateInfo,
438 const VkAllocationCallbacks* pAllocator, VkFramebuffer* pFramebuffer) const {
439 bool skip = false;
440
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000441 auto rp_state = GetRenderPassState(pCreateInfo->renderPass);
Tony-LunarG767180f2020-04-23 14:03:59 -0600442 if (rp_state && !(pCreateInfo->flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT_KHR)) {
443 skip = ValidateAttachments(rp_state->createInfo.ptr(), pCreateInfo->attachmentCount, pCreateInfo->pAttachments);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000444 }
445
446 return skip;
447}
448
Sam Wallse746d522020-03-16 21:20:23 +0000449bool BestPractices::PreCallValidateAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
450 VkDescriptorSet* pDescriptorSets, void* ads_state_data) const {
451 bool skip = false;
452 skip |= ValidationStateTracker::PreCallValidateAllocateDescriptorSets(device, pAllocateInfo, pDescriptorSets, ads_state_data);
453
454 if (!skip) {
455 const auto& pool_handle = pAllocateInfo->descriptorPool;
456 auto iter = descriptor_pool_freed_count.find(pool_handle);
457 // if the number of freed sets > 0, it implies they could be recycled instead if desirable
458 // this warning is specific to Arm
459 if (VendorCheckEnabled(kBPVendorArm) && iter != descriptor_pool_freed_count.end() && iter->second > 0) {
460 skip |= LogPerformanceWarning(
461 device, kVUID_BestPractices_AllocateDescriptorSets_SuboptimalReuse,
462 "%s Descriptor set memory was allocated via vkAllocateDescriptorSets() for sets which were previously freed in the "
463 "same logical device. On some drivers or architectures it may be most optimal to re-use existing descriptor sets.",
464 VendorSpecificTag(kBPVendorArm));
465 }
466 }
467
468 return skip;
469}
470
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600471void BestPractices::ManualPostCallRecordAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
472 VkDescriptorSet* pDescriptorSets, VkResult result, void* ads_state) {
Sam Wallse746d522020-03-16 21:20:23 +0000473 if (result == VK_SUCCESS) {
474 // find the free count for the pool we allocated into
475 auto iter = descriptor_pool_freed_count.find(pAllocateInfo->descriptorPool);
476 if (iter != descriptor_pool_freed_count.end()) {
477 // we record successful allocations by subtracting the allocation count from the last recorded free count
478 const auto alloc_count = pAllocateInfo->descriptorSetCount;
479 // clamp the unsigned subtraction to the range [0, last_free_count]
480 if (iter->second > alloc_count)
481 iter->second -= alloc_count;
482 else
483 iter->second = 0;
484 }
485 }
486}
487
488void BestPractices::PostCallRecordFreeDescriptorSets(VkDevice device, VkDescriptorPool descriptorPool, uint32_t descriptorSetCount,
489 const VkDescriptorSet* pDescriptorSets, VkResult result) {
490 ValidationStateTracker::PostCallRecordFreeDescriptorSets(device, descriptorPool, descriptorSetCount, pDescriptorSets, result);
491 if (result == VK_SUCCESS) {
492 // we want to track frees because we're interested in suggesting re-use
493 auto iter = descriptor_pool_freed_count.find(descriptorPool);
494 if (iter == descriptor_pool_freed_count.end()) {
495 descriptor_pool_freed_count.insert(std::make_pair(descriptorPool, descriptorSetCount));
496 } else {
497 iter->second += descriptorSetCount;
498 }
499 }
500}
501
Camden5b184be2019-08-13 07:50:19 -0600502bool BestPractices::PreCallValidateAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500503 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory) const {
Camden5b184be2019-08-13 07:50:19 -0600504 bool skip = false;
505
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500506 if (num_mem_objects + 1 > kMemoryObjectWarningLimit) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700507 skip |= LogPerformanceWarning(device, kVUID_BestPractices_AllocateMemory_TooManyObjects,
508 "Performance Warning: This app has > %" PRIu32 " memory objects.", kMemoryObjectWarningLimit);
Camden5b184be2019-08-13 07:50:19 -0600509 }
510
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000511 if (pAllocateInfo->allocationSize < kMinDeviceAllocationSize) {
512 skip |= LogPerformanceWarning(
513 device, kVUID_BestPractices_AllocateMemory_SmallAllocation,
514 "vkAllocateMemory(): Allocating a VkDeviceMemory of size %llu. This is a very small allocation (current "
515 "threshold is %llu bytes). "
516 "You should make large allocations and sub-allocate from one large VkDeviceMemory.",
517 pAllocateInfo->allocationSize, kMinDeviceAllocationSize);
518 }
519
Camden83a9c372019-08-14 11:41:38 -0600520 // TODO: Insert get check for GetPhysicalDeviceMemoryProperties once the state is tracked in the StateTracker
521
522 return skip;
523}
524
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600525void BestPractices::ManualPostCallRecordAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
526 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory,
527 VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700528 if (result != VK_SUCCESS) {
529 static std::vector<VkResult> error_codes = {VK_ERROR_OUT_OF_HOST_MEMORY, VK_ERROR_OUT_OF_DEVICE_MEMORY,
530 VK_ERROR_TOO_MANY_OBJECTS, VK_ERROR_INVALID_EXTERNAL_HANDLE,
531 VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS_KHR};
532 static std::vector<VkResult> success_codes = {};
533 ValidateReturnCodes("vkReleaseFullScreenExclusiveModeEXT", result, error_codes, success_codes);
534 return;
535 }
536 num_mem_objects++;
537}
Camden Stocker9738af92019-10-16 13:54:03 -0700538
Mark Lobodzinskide15e582020-04-29 08:06:00 -0600539void BestPractices::ValidateReturnCodes(const char* api_name, VkResult result, const std::vector<VkResult>& error_codes,
540 const std::vector<VkResult>& success_codes) const {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700541 auto error = std::find(error_codes.begin(), error_codes.end(), result);
542 if (error != error_codes.end()) {
Mark Lobodzinski629defa2020-04-29 12:00:23 -0600543 LogWarning(instance, kVUID_BestPractices_Error_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700544 return;
545 }
546 auto success = std::find(success_codes.begin(), success_codes.end(), result);
547 if (success != success_codes.end()) {
Mark Lobodzinskie7215152020-05-11 08:21:23 -0600548 LogInfo(instance, kVUID_BestPractices_NonSuccess_Result, "%s(): Returned non-success return code %s.", api_name,
549 string_VkResult(result));
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500550 }
551}
552
Jeff Bolz5c801d12019-10-09 10:38:45 -0500553bool BestPractices::PreCallValidateFreeMemory(VkDevice device, VkDeviceMemory memory,
554 const VkAllocationCallbacks* pAllocator) const {
Mark Lobodzinski91e50bf2020-01-14 09:55:11 -0700555 if (memory == VK_NULL_HANDLE) return false;
Camden83a9c372019-08-14 11:41:38 -0600556 bool skip = false;
557
Camden Stocker9738af92019-10-16 13:54:03 -0700558 const DEVICE_MEMORY_STATE* mem_info = ValidationStateTracker::GetDevMemState(memory);
Camden83a9c372019-08-14 11:41:38 -0600559
560 for (auto& obj : mem_info->obj_bindings) {
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600561 LogObjectList objlist(device);
562 objlist.add(obj);
563 objlist.add(mem_info->mem);
564 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 -0700565 report_data->FormatHandle(obj).c_str(), report_data->FormatHandle(mem_info->mem).c_str());
Camden83a9c372019-08-14 11:41:38 -0600566 }
567
Camden5b184be2019-08-13 07:50:19 -0600568 return skip;
569}
570
571void BestPractices::PreCallRecordFreeMemory(VkDevice device, VkDeviceMemory memory, const VkAllocationCallbacks* pAllocator) {
Mark Lobodzinski97484d62020-03-03 11:57:41 -0700572 ValidationStateTracker::PreCallRecordFreeMemory(device, memory, pAllocator);
Camden5b184be2019-08-13 07:50:19 -0600573 if (memory != VK_NULL_HANDLE) {
574 num_mem_objects--;
575 }
576}
577
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000578bool BestPractices::ValidateBindBufferMemory(VkBuffer buffer, VkDeviceMemory memory, const char* api_name) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600579 bool skip = false;
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500580 const BUFFER_STATE* buffer_state = GetBufferState(buffer);
Camden Stockerb603cc82019-09-03 10:09:02 -0600581
sfricke-samsunge2441192019-11-06 14:07:57 -0800582 if (!buffer_state->memory_requirements_checked && !buffer_state->external_memory_handle) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700583 skip |= LogWarning(device, kVUID_BestPractices_BufferMemReqNotCalled,
584 "%s: Binding memory to %s but vkGetBufferMemoryRequirements() has not been called on that buffer.",
585 api_name, report_data->FormatHandle(buffer).c_str());
Camden Stockerb603cc82019-09-03 10:09:02 -0600586 }
587
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000588 const DEVICE_MEMORY_STATE* mem_state = GetDevMemState(memory);
589
590 if (mem_state->alloc_info.allocationSize == buffer_state->createInfo.size &&
591 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
592 skip |= LogPerformanceWarning(
593 device, kVUID_BestPractices_SmallDedicatedAllocation,
594 "%s: Trying to bind %s to a memory block which is fully consumed by the buffer. "
595 "The required size of the allocation is %llu, but smaller buffers like this should be sub-allocated from "
596 "larger memory blocks. (Current threshold is %llu bytes.)",
597 api_name, report_data->FormatHandle(buffer).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
598 }
599
Camden Stockerb603cc82019-09-03 10:09:02 -0600600 return skip;
601}
602
603bool BestPractices::PreCallValidateBindBufferMemory(VkDevice device, VkBuffer buffer, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500604 VkDeviceSize memoryOffset) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600605 bool skip = false;
606 const char* api_name = "BindBufferMemory()";
607
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000608 skip |= ValidateBindBufferMemory(buffer, memory, api_name);
Camden Stockerb603cc82019-09-03 10:09:02 -0600609
610 return skip;
611}
612
613bool BestPractices::PreCallValidateBindBufferMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500614 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600615 char api_name[64];
616 bool skip = false;
617
618 for (uint32_t i = 0; i < bindInfoCount; i++) {
619 sprintf(api_name, "vkBindBufferMemory2() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000620 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600621 }
622
623 return skip;
624}
Camden Stockerb603cc82019-09-03 10:09:02 -0600625
626bool BestPractices::PreCallValidateBindBufferMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500627 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600628 char api_name[64];
629 bool skip = false;
Camden Stockerb603cc82019-09-03 10:09:02 -0600630
Camden Stocker8b798ab2019-09-03 10:33:28 -0600631 for (uint32_t i = 0; i < bindInfoCount; i++) {
632 sprintf(api_name, "vkBindBufferMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000633 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600634 }
635
636 return skip;
637}
638
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000639bool BestPractices::ValidateBindImageMemory(VkImage image, VkDeviceMemory memory, const char* api_name) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600640 bool skip = false;
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500641 const IMAGE_STATE* image_state = GetImageState(image);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600642
sfricke-samsung71bc6572020-04-29 15:49:43 -0700643 if (image_state->disjoint == false) {
sfricke-samsungd7ea5de2020-04-08 09:19:18 -0700644 if (!image_state->memory_requirements_checked && !image_state->external_memory_handle) {
645 skip |= LogWarning(device, kVUID_BestPractices_ImageMemReqNotCalled,
646 "%s: Binding memory to %s but vkGetImageMemoryRequirements() has not been called on that image.",
647 api_name, report_data->FormatHandle(image).c_str());
648 }
649 } else {
650 // TODO If binding disjoint image then this needs to check that VkImagePlaneMemoryRequirementsInfo was called for each
651 // plane.
Camden Stocker8b798ab2019-09-03 10:33:28 -0600652 }
653
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000654 const DEVICE_MEMORY_STATE* mem_state = GetDevMemState(memory);
655
656 if (mem_state->alloc_info.allocationSize == image_state->requirements.size &&
657 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
658 skip |= LogPerformanceWarning(
659 device, kVUID_BestPractices_SmallDedicatedAllocation,
660 "%s: Trying to bind %s to a memory block which is fully consumed by the image. "
661 "The required size of the allocation is %llu, but smaller images like this should be sub-allocated from "
662 "larger memory blocks. (Current threshold is %llu bytes.)",
663 api_name, report_data->FormatHandle(image).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
664 }
665
666 // If we're binding memory to a image which was created as TRANSIENT and the image supports LAZY allocation,
667 // make sure this type is actually used.
668 // This warning will only trigger if this layer is run on a platform that supports LAZILY_ALLOCATED_BIT
669 // (i.e.most tile - based renderers)
670 if (image_state->createInfo.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) {
671 bool supports_lazy = false;
672 uint32_t suggested_type = 0;
673
674 for (uint32_t i = 0; i < phys_dev_mem_props.memoryTypeCount; i++) {
675 if ((1u << i) & image_state->requirements.memoryTypeBits) {
676 if (phys_dev_mem_props.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
677 supports_lazy = true;
678 suggested_type = i;
679 break;
680 }
681 }
682 }
683
684 uint32_t allocated_properties = phys_dev_mem_props.memoryTypes[mem_state->alloc_info.memoryTypeIndex].propertyFlags;
685
686 if (supports_lazy && (allocated_properties & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) == 0) {
687 skip |= LogPerformanceWarning(
688 device, kVUID_BestPractices_NonLazyTransientImage,
689 "%s: Attempting to bind memory type % u to VkImage which was created with TRANSIENT_ATTACHMENT_BIT,"
690 "but this memory type is not LAZILY_ALLOCATED_BIT. You should use memory type %u here instead to save "
691 "%llu bytes of physical memory.",
692 api_name, mem_state->alloc_info.memoryTypeIndex, suggested_type, image_state->requirements.size);
693 }
694 }
695
Camden Stocker8b798ab2019-09-03 10:33:28 -0600696 return skip;
697}
698
699bool BestPractices::PreCallValidateBindImageMemory(VkDevice device, VkImage image, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500700 VkDeviceSize memoryOffset) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600701 bool skip = false;
702 const char* api_name = "vkBindImageMemory()";
703
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000704 skip |= ValidateBindImageMemory(image, memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600705
706 return skip;
707}
708
709bool BestPractices::PreCallValidateBindImageMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500710 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600711 char api_name[64];
712 bool skip = false;
713
714 for (uint32_t i = 0; i < bindInfoCount; i++) {
715 sprintf(api_name, "vkBindImageMemory2() pBindInfos[%u]", i);
Tony-LunarG5e60b852020-04-27 11:27:54 -0600716 if (!lvl_find_in_chain<VkBindImageMemorySwapchainInfoKHR>(pBindInfos[i].pNext)) {
717 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
718 }
Camden Stocker8b798ab2019-09-03 10:33:28 -0600719 }
720
721 return skip;
722}
723
724bool BestPractices::PreCallValidateBindImageMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500725 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600726 char api_name[64];
727 bool skip = false;
728
729 for (uint32_t i = 0; i < bindInfoCount; i++) {
730 sprintf(api_name, "vkBindImageMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000731 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600732 }
733
734 return skip;
735}
Camden83a9c372019-08-14 11:41:38 -0600736
Attilio Provenzano02859b22020-02-27 14:17:28 +0000737static inline bool FormatHasFullThroughputBlendingArm(VkFormat format) {
738 switch (format) {
739 case VK_FORMAT_B10G11R11_UFLOAT_PACK32:
740 case VK_FORMAT_R16_SFLOAT:
741 case VK_FORMAT_R16G16_SFLOAT:
742 case VK_FORMAT_R16G16B16_SFLOAT:
743 case VK_FORMAT_R16G16B16A16_SFLOAT:
744 case VK_FORMAT_R32_SFLOAT:
745 case VK_FORMAT_R32G32_SFLOAT:
746 case VK_FORMAT_R32G32B32_SFLOAT:
747 case VK_FORMAT_R32G32B32A32_SFLOAT:
748 return false;
749
750 default:
751 return true;
752 }
753}
754
755bool BestPractices::ValidateMultisampledBlendingArm(uint32_t createInfoCount,
756 const VkGraphicsPipelineCreateInfo* pCreateInfos) const {
757 bool skip = false;
758
759 for (uint32_t i = 0; i < createInfoCount; i++) {
760 auto pCreateInfo = &pCreateInfos[i];
761
762 if (!pCreateInfo->pColorBlendState || !pCreateInfo->pMultisampleState ||
763 pCreateInfo->pMultisampleState->rasterizationSamples == VK_SAMPLE_COUNT_1_BIT ||
764 pCreateInfo->pMultisampleState->sampleShadingEnable) {
765 return skip;
766 }
767
768 auto rp_state = GetRenderPassState(pCreateInfo->renderPass);
769 auto& subpass = rp_state->createInfo.pSubpasses[pCreateInfo->subpass];
770
771 for (uint32_t j = 0; j < pCreateInfo->pColorBlendState->attachmentCount; j++) {
772 auto& blend_att = pCreateInfo->pColorBlendState->pAttachments[j];
773 uint32_t att = subpass.pColorAttachments[j].attachment;
774
775 if (att != VK_ATTACHMENT_UNUSED && blend_att.blendEnable && blend_att.colorWriteMask) {
776 if (!FormatHasFullThroughputBlendingArm(rp_state->createInfo.pAttachments[att].format)) {
777 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultisampledBlending,
778 "%s vkCreateGraphicsPipelines() - createInfo #%u: Pipeline is multisampled and "
779 "color attachment #%u makes use "
780 "of a format which cannot be blended at full throughput when using MSAA.",
781 VendorSpecificTag(kBPVendorArm), i, j);
782 }
783 }
784 }
785 }
786
787 return skip;
788}
789
Camden5b184be2019-08-13 07:50:19 -0600790bool BestPractices::PreCallValidateCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
791 const VkGraphicsPipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -0600792 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500793 void* cgpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -0600794 bool skip = StateTracker::PreCallValidateCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos,
795 pAllocator, pPipelines, cgpl_state_data);
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600796 create_graphics_pipeline_api_state* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
Camden5b184be2019-08-13 07:50:19 -0600797
798 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700799 skip |= LogPerformanceWarning(
800 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
801 "Performance Warning: This vkCreateGraphicsPipelines call is creating multiple pipelines but is not using a "
802 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -0600803 }
804
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000805 for (uint32_t i = 0; i < createInfoCount; i++) {
806 auto& createInfo = pCreateInfos[i];
807
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600808 if (!(cgpl_state->pipe_state[i]->active_shaders & VK_SHADER_STAGE_MESH_BIT_NV)) {
809 auto& vertexInput = *createInfo.pVertexInputState;
810 uint32_t count = 0;
811 for (uint32_t j = 0; j < vertexInput.vertexBindingDescriptionCount; j++) {
812 if (vertexInput.pVertexBindingDescriptions[j].inputRate == VK_VERTEX_INPUT_RATE_INSTANCE) {
813 count++;
814 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000815 }
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600816 if (count > kMaxInstancedVertexBuffers) {
817 skip |= LogPerformanceWarning(
818 device, kVUID_BestPractices_CreatePipelines_TooManyInstancedVertexBuffers,
819 "The pipeline is using %u instanced vertex buffers (current limit: %u), but this can be inefficient on the "
820 "GPU. If using instanced vertex attributes prefer interleaving them in a single buffer.",
821 count, kMaxInstancedVertexBuffers);
822 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000823 }
Attilio Provenzano02859b22020-02-27 14:17:28 +0000824
Szilard Pappaaf2da32020-06-22 10:37:35 +0100825 if ((pCreateInfos[i].pRasterizationState->depthBiasEnable) &&
826 (pCreateInfos[i].pRasterizationState->depthBiasConstantFactor == 0.0f) &&
827 (pCreateInfos[i].pRasterizationState->depthBiasSlopeFactor == 0.0f)) {
828 skip |= VendorCheckEnabled(kBPVendorArm) &&
829 LogPerformanceWarning(
830 device, kVUID_BestPractices_CreatePipelines_DepthBias_Zero,
831 "%s Performance Warning: This vkCreateGraphicsPipelines call is created with depthBiasEnable set to true "
832 "and both depthBiasConstantFactor and depthBiasSlopeFactor are set to 0. This can cause reduced "
833 "efficiency during rasterization. Consider disabling depthBias or increasing either "
834 "depthBiasConstantFactor or depthBiasSlopeFactor.",
835 VendorSpecificTag(kBPVendorArm));
836 }
837
Attilio Provenzano02859b22020-02-27 14:17:28 +0000838 skip |= VendorCheckEnabled(kBPVendorArm) && ValidateMultisampledBlendingArm(createInfoCount, pCreateInfos);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000839 }
840
Camden5b184be2019-08-13 07:50:19 -0600841 return skip;
842}
843
Sam Walls0961ec02020-03-31 16:39:15 +0100844void BestPractices::ManualPostCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t count,
845 const VkGraphicsPipelineCreateInfo* pCreateInfos,
846 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
847 VkResult result, void* cgpl_state_data) {
848 for (size_t i = 0; i < count; i++) {
849 const auto* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
850 const VkPipeline pipeline_handle = pPipelines[i];
851
852 // record depth stencil state and color blend states for depth pre-pass tracking purposes
853 auto gp_cis = graphicsPipelineCIs.find(pipeline_handle);
854
855 // add the tracking state if it doesn't exist
856 if (gp_cis == graphicsPipelineCIs.end()) {
857 auto result = graphicsPipelineCIs.emplace(std::make_pair(pipeline_handle, GraphicsPipelineCIs{}));
858
859 if (!result.second) continue;
860
861 gp_cis = result.first;
862 }
863
Tony-LunarG412b1b72020-07-15 10:30:13 -0600864 gp_cis->second.colorBlendStateCI =
865 cgpl_state->pCreateInfos[i].pColorBlendState
866 ? new safe_VkPipelineColorBlendStateCreateInfo(cgpl_state->pCreateInfos[i].pColorBlendState)
867 : nullptr;
868 gp_cis->second.depthStencilStateCI =
869 cgpl_state->pCreateInfos[i].pDepthStencilState
870 ? new safe_VkPipelineDepthStencilStateCreateInfo(cgpl_state->pCreateInfos[i].pDepthStencilState)
871 : nullptr;
Sam Walls0961ec02020-03-31 16:39:15 +0100872 }
873}
874
Camden5b184be2019-08-13 07:50:19 -0600875bool BestPractices::PreCallValidateCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
876 const VkComputePipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -0600877 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500878 void* ccpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -0600879 bool skip = StateTracker::PreCallValidateCreateComputePipelines(device, pipelineCache, createInfoCount, pCreateInfos,
880 pAllocator, pPipelines, ccpl_state_data);
Camden5b184be2019-08-13 07:50:19 -0600881
882 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700883 skip |= LogPerformanceWarning(
884 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
885 "Performance Warning: This vkCreateComputePipelines call is creating multiple pipelines but is not using a "
886 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -0600887 }
888
Sam Wallsd7ab6db2020-06-19 20:41:54 +0100889 if (VendorCheckEnabled(kBPVendorArm)) {
890 for (size_t i = 0; i < createInfoCount; i++) {
891 skip |= ValidateCreateComputePipelineArm(pCreateInfos[i]);
892 }
893 }
894
895 return skip;
896}
897
898bool BestPractices::ValidateCreateComputePipelineArm(const VkComputePipelineCreateInfo& createInfo) const {
899 bool skip = false;
900 auto* module = GetShaderModuleState(createInfo.stage.module);
901
902 uint32_t x = 1, y = 1, z = 1;
903 FindLocalSize(module, x, y, z);
904
905 uint32_t thread_count = x * y * z;
906
907 // Generate a priori warnings about work group sizes.
908 if (thread_count > kMaxEfficientWorkGroupThreadCountArm) {
909 skip |= LogPerformanceWarning(
910 device, kVUID_BestPractices_CreateComputePipelines_ComputeWorkGroupSize,
911 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, %u, "
912 "%u) (%u threads total), has more threads than advised in a single work group. It is advised to use work "
913 "groups with less than %u threads, especially when using barrier() or shared memory.",
914 VendorSpecificTag(kBPVendorArm), x, y, z, thread_count, kMaxEfficientWorkGroupThreadCountArm);
915 }
916
917 if (thread_count == 1 || ((x > 1) && (x & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
918 ((y > 1) && (y & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
919 ((z > 1) && (z & (kThreadGroupDispatchCountAlignmentArm - 1)))) {
920 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeThreadGroupAlignment,
921 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, "
922 "%u, %u) is not aligned to %u "
923 "threads. On Arm Mali architectures, not aligning work group sizes to %u may "
924 "leave threads idle on the shader "
925 "core.",
926 VendorSpecificTag(kBPVendorArm), x, y, z, kThreadGroupDispatchCountAlignmentArm,
927 kThreadGroupDispatchCountAlignmentArm);
928 }
929
930 // Generate warnings about work group sizes based on active resources.
931 auto entrypoint = FindEntrypoint(module, createInfo.stage.pName, createInfo.stage.stage);
932 if (entrypoint == module->end()) return false;
933
934 bool has_writeable_descriptors = false;
locke-lunarg63e4daf2020-08-17 17:53:25 -0600935 bool has_atomic_descriptors = false;
Sam Wallsd7ab6db2020-06-19 20:41:54 +0100936 auto accessible_ids = MarkAccessibleIds(module, entrypoint);
locke-lunarg63e4daf2020-08-17 17:53:25 -0600937 auto descriptor_uses =
938 CollectInterfaceByDescriptorSlot(module, accessible_ids, &has_writeable_descriptors, &has_atomic_descriptors);
Sam Wallsd7ab6db2020-06-19 20:41:54 +0100939
940 unsigned dimensions = 0;
941 if (x > 1) dimensions++;
942 if (y > 1) dimensions++;
943 if (z > 1) dimensions++;
944 // Here the dimension will really depend on the dispatch grid, but assume it's 1D.
945 dimensions = std::max(dimensions, 1u);
946
947 // If we're accessing images, we almost certainly want to have a 2D workgroup for cache reasons.
948 // There are some false positives here. We could simply have a shader that does this within a 1D grid,
949 // or we may have a linearly tiled image, but these cases are quite unlikely in practice.
950 bool accesses_2d = false;
951 for (const auto& usage : descriptor_uses) {
952 auto dim = GetShaderResourceDimensionality(module, usage.second);
953 if (dim < 0) continue;
954 auto spvdim = spv::Dim(dim);
955 if (spvdim != spv::Dim1D && spvdim != spv::DimBuffer) accesses_2d = true;
956 }
957
958 if (accesses_2d && dimensions < 2) {
959 LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeSpatialLocality,
960 "%s vkCreateComputePipelines(): compute shader has work group dimensions (%u, %u, %u), which "
961 "suggests a 1D dispatch, but the shader is accessing 2D or 3D images. The shader may be "
962 "exhibiting poor spatial locality with respect to one or more shader resources.",
963 VendorSpecificTag(kBPVendorArm), x, y, z);
964 }
965
Camden5b184be2019-08-13 07:50:19 -0600966 return skip;
967}
968
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500969bool BestPractices::CheckPipelineStageFlags(std::string api_name, const VkPipelineStageFlags flags) const {
Camden5b184be2019-08-13 07:50:19 -0600970 bool skip = false;
971
972 if (flags & VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700973 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
974 "You are using VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -0600975 } else if (flags & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700976 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
977 "You are using VK_PIPELINE_STAGE_ALL_COMMANDS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -0600978 }
979
980 return skip;
981}
982
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600983void BestPractices::ManualPostCallRecordQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo, VkResult result) {
Mark Lobodzinski9b133c12020-03-10 10:42:56 -0600984 for (uint32_t i = 0; i < pPresentInfo->swapchainCount; ++i) {
985 auto swapchains_result = pPresentInfo->pResults ? pPresentInfo->pResults[i] : result;
986 if (swapchains_result == VK_SUBOPTIMAL_KHR) {
987 LogPerformanceWarning(
988 pPresentInfo->pSwapchains[i], kVUID_BestPractices_SuboptimalSwapchain,
989 "vkQueuePresentKHR: %s :VK_SUBOPTIMAL_KHR was returned. VK_SUBOPTIMAL_KHR - Presentation will still succeed, "
990 "subject to the window resize behavior, but the swapchain is no longer configured optimally for the surface it "
991 "targets. Applications should query updated surface information and recreate their swapchain at the next "
992 "convenient opportunity.",
993 report_data->FormatHandle(pPresentInfo->pSwapchains[i]).c_str());
994 }
995 }
996}
997
Jeff Bolz5c801d12019-10-09 10:38:45 -0500998bool BestPractices::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
999 VkFence fence) const {
Camden5b184be2019-08-13 07:50:19 -06001000 bool skip = false;
1001
1002 for (uint32_t submit = 0; submit < submitCount; submit++) {
1003 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreCount; semaphore++) {
1004 skip |= CheckPipelineStageFlags("vkQueueSubmit", pSubmits[submit].pWaitDstStageMask[semaphore]);
1005 }
1006 }
1007
1008 return skip;
1009}
1010
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001011bool BestPractices::PreCallValidateCreateCommandPool(VkDevice device, const VkCommandPoolCreateInfo* pCreateInfo,
1012 const VkAllocationCallbacks* pAllocator, VkCommandPool* pCommandPool) const {
1013 bool skip = false;
1014
1015 if (pCreateInfo->flags & VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT) {
1016 skip |= LogPerformanceWarning(
1017 device, kVUID_BestPractices_CreateCommandPool_CommandBufferReset,
1018 "vkCreateCommandPool(): VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT is set. Consider resetting entire "
1019 "pool instead.");
1020 }
1021
1022 return skip;
1023}
1024
1025bool BestPractices::PreCallValidateBeginCommandBuffer(VkCommandBuffer commandBuffer,
1026 const VkCommandBufferBeginInfo* pBeginInfo) const {
1027 bool skip = false;
1028
1029 if (pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT) {
1030 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_SimultaneousUse,
1031 "vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT is set.");
1032 }
1033
Attilio Provenzano02859b22020-02-27 14:17:28 +00001034 if (!(pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT)) {
1035 skip |= VendorCheckEnabled(kBPVendorArm) &&
1036 LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_OneTimeSubmit,
1037 "%s vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT is not set. "
1038 "For best performance on Mali GPUs, consider setting ONE_TIME_SUBMIT by default.",
1039 VendorSpecificTag(kBPVendorArm));
1040 }
1041
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001042 return skip;
1043}
1044
Jeff Bolz5c801d12019-10-09 10:38:45 -05001045bool BestPractices::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001046 bool skip = false;
1047
1048 skip |= CheckPipelineStageFlags("vkCmdSetEvent", stageMask);
1049
1050 return skip;
1051}
1052
Jeff Bolz5c801d12019-10-09 10:38:45 -05001053bool BestPractices::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
1054 VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001055 bool skip = false;
1056
1057 skip |= CheckPipelineStageFlags("vkCmdResetEvent", stageMask);
1058
1059 return skip;
1060}
1061
1062bool BestPractices::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1063 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
1064 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1065 uint32_t bufferMemoryBarrierCount,
1066 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1067 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001068 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001069 bool skip = false;
1070
1071 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", srcStageMask);
1072 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", dstStageMask);
1073
1074 return skip;
1075}
1076
1077bool BestPractices::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
1078 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
1079 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1080 uint32_t bufferMemoryBarrierCount,
1081 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1082 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001083 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001084 bool skip = false;
1085
1086 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", srcStageMask);
1087 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", dstStageMask);
1088
1089 return skip;
1090}
1091
1092bool BestPractices::PreCallValidateCmdWriteTimestamp(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001093 VkQueryPool queryPool, uint32_t query) const {
Camden5b184be2019-08-13 07:50:19 -06001094 bool skip = false;
1095
1096 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp", pipelineStage);
1097
1098 return skip;
1099}
1100
Sam Walls0961ec02020-03-31 16:39:15 +01001101void BestPractices::PostCallRecordCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
1102 VkPipeline pipeline) {
1103 StateTracker::PostCallRecordCmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
1104
1105 if (pipelineBindPoint == VK_PIPELINE_BIND_POINT_GRAPHICS) {
1106 // check for depth/blend state tracking
1107 auto gp_cis = graphicsPipelineCIs.find(pipeline);
1108 if (gp_cis != graphicsPipelineCIs.end()) {
1109 auto prepass_state = cbDepthPrePassStates.find(commandBuffer);
1110 if (prepass_state == cbDepthPrePassStates.end()) {
1111 auto result = cbDepthPrePassStates.emplace(std::make_pair(commandBuffer, DepthPrePassState{}));
1112
1113 if (!result.second) return;
1114
1115 prepass_state = result.first;
1116 }
1117
1118 const auto* blend_state = gp_cis->second.colorBlendStateCI;
1119 const auto* stencil_state = gp_cis->second.depthStencilStateCI;
1120
1121 if (blend_state) {
1122 // assume the pipeline is depth-only unless any of the attachments have color writes enabled
1123 prepass_state->second.depthOnly = true;
1124 for (size_t i = 0; i < blend_state->attachmentCount; i++) {
1125 if (blend_state->pAttachments[i].colorWriteMask != 0) {
1126 prepass_state->second.depthOnly = false;
1127 }
1128 }
1129 }
1130
1131 // check for depth value usage
1132 prepass_state->second.depthEqualComparison = false;
1133
1134 if (stencil_state && stencil_state->depthTestEnable) {
1135 switch (stencil_state->depthCompareOp) {
1136 case VK_COMPARE_OP_EQUAL:
1137 case VK_COMPARE_OP_GREATER_OR_EQUAL:
1138 case VK_COMPARE_OP_LESS_OR_EQUAL:
1139 prepass_state->second.depthEqualComparison = true;
1140 break;
1141 default:
1142 break;
1143 }
1144 }
1145 } else {
1146 // reset depth pre-pass tracking
1147 cbDepthPrePassStates.emplace(std::make_pair(commandBuffer, DepthPrePassState{}));
1148 }
1149 }
1150}
1151
Attilio Provenzano02859b22020-02-27 14:17:28 +00001152static inline bool RenderPassUsesAttachmentOnTile(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1153 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
1154 auto& subpassInfo = createInfo.pSubpasses[subpass];
1155
1156 // If an attachment is ever used as a color attachment,
1157 // resolve attachment or depth stencil attachment,
1158 // it needs to exist on tile at some point.
1159
1160 for (uint32_t i = 0; i < subpassInfo.colorAttachmentCount; i++)
1161 if (subpassInfo.pColorAttachments[i].attachment == attachment) return true;
1162
1163 if (subpassInfo.pResolveAttachments) {
1164 for (uint32_t i = 0; i < subpassInfo.colorAttachmentCount; i++)
1165 if (subpassInfo.pResolveAttachments[i].attachment == attachment) return true;
1166 }
1167
1168 if (subpassInfo.pDepthStencilAttachment && subpassInfo.pDepthStencilAttachment->attachment == attachment) return true;
1169 }
1170
1171 return false;
1172}
1173
1174bool BestPractices::ValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1175 const VkRenderPassBeginInfo* pRenderPassBegin) const {
1176 bool skip = false;
1177
1178 if (!pRenderPassBegin) {
1179 return skip;
1180 }
1181
1182 auto rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
1183 if (rp_state) {
Tony-LunarG767180f2020-04-23 14:03:59 -06001184 if (rp_state->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT_KHR) {
1185 const VkRenderPassAttachmentBeginInfo* rpabi =
1186 lvl_find_in_chain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
1187 if (rpabi) {
1188 skip = ValidateAttachments(rp_state->createInfo.ptr(), rpabi->attachmentCount, rpabi->pAttachments);
1189 }
1190 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001191 // Check if any attachments have LOAD operation on them
1192 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
1193 auto& attachment = rp_state->createInfo.pAttachments[att];
1194
1195 bool attachmentHasReadback = false;
1196 if (!FormatHasStencil(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
1197 attachmentHasReadback = true;
1198 }
1199
1200 if (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
1201 attachmentHasReadback = true;
1202 }
1203
1204 bool attachmentNeedsReadback = false;
1205
1206 // Check if the attachment is actually used in any subpass on-tile
1207 if (attachmentHasReadback && RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1208 attachmentNeedsReadback = true;
1209 }
1210
1211 // Using LOAD_OP_LOAD is expensive on tiled GPUs, so flag it as a potential improvement
1212 if (attachmentNeedsReadback) {
1213 skip |= VendorCheckEnabled(kBPVendorArm) &&
1214 LogPerformanceWarning(
1215 device, kVUID_BestPractices_BeginRenderPass_AttachmentNeedsReadback,
1216 "%s Attachment #%u in render pass has begun with VK_ATTACHMENT_LOAD_OP_LOAD.\n"
1217 "Submitting this renderpass will cause the driver to inject a readback of the attachment "
1218 "which will copy in total %u pixels (renderArea = { %d, %d, %u, %u }) to the tile buffer.",
1219 VendorSpecificTag(kBPVendorArm), att,
1220 pRenderPassBegin->renderArea.extent.width * pRenderPassBegin->renderArea.extent.height,
1221 pRenderPassBegin->renderArea.offset.x, pRenderPassBegin->renderArea.offset.y,
1222 pRenderPassBegin->renderArea.extent.width, pRenderPassBegin->renderArea.extent.height);
1223 }
1224 }
1225 }
1226
1227 return skip;
1228}
1229
1230bool BestPractices::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1231 VkSubpassContents contents) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001232 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1233 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001234 return skip;
1235}
1236
1237bool BestPractices::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1238 const VkRenderPassBeginInfo* pRenderPassBegin,
1239 const VkSubpassBeginInfoKHR* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001240 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1241 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001242 return skip;
1243}
1244
1245bool BestPractices::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1246 const VkSubpassBeginInfoKHR* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001247 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1248 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001249 return skip;
1250}
1251
Sam Walls0961ec02020-03-31 16:39:15 +01001252void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1253 const VkRenderPassBeginInfo* pRenderPassBegin) {
1254 auto prepass_state = cbDepthPrePassStates.find(commandBuffer);
1255
1256 // add the tracking state if it doesn't exist
1257 if (prepass_state == cbDepthPrePassStates.end()) {
1258 auto result = cbDepthPrePassStates.emplace(std::make_pair(commandBuffer, DepthPrePassState{}));
1259
1260 if (!result.second) return;
1261
1262 prepass_state = result.first;
1263 }
1264
1265 // reset the renderpass state
1266 prepass_state->second = {};
1267
1268 const auto* cb_state = GetCBState(commandBuffer);
locke-lunargaecf2152020-05-12 17:15:41 -06001269 const auto* rp_state = cb_state->activeRenderPass.get();
Sam Walls0961ec02020-03-31 16:39:15 +01001270
1271 // track depth / color attachment usage within the renderpass
1272 for (size_t i = 0; i < rp_state->createInfo.subpassCount; i++) {
1273 // record if depth/color attachments are in use for this renderpass
1274 if (rp_state->createInfo.pSubpasses[i].pDepthStencilAttachment != nullptr) prepass_state->second.depthAttachment = true;
1275
1276 if (rp_state->createInfo.pSubpasses[i].colorAttachmentCount > 0) prepass_state->second.colorAttachment = true;
1277 }
1278}
1279
1280void BestPractices::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1281 VkSubpassContents contents) {
1282 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1283 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
1284}
1285
1286void BestPractices::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1287 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1288 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1289 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1290}
1291
1292void BestPractices::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1293 const VkRenderPassBeginInfo* pRenderPassBegin,
1294 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1295 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1296 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1297}
1298
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001299// Generic function to handle validation for all CmdDraw* type functions
1300bool BestPractices::ValidateCmdDrawType(VkCommandBuffer cmd_buffer, const char* caller) const {
1301 bool skip = false;
1302 const CMD_BUFFER_STATE* cb_state = GetCBState(cmd_buffer);
1303 if (cb_state) {
1304 const auto last_bound_it = cb_state->lastBound.find(VK_PIPELINE_BIND_POINT_GRAPHICS);
1305 const PIPELINE_STATE* pipeline_state = nullptr;
1306 if (last_bound_it != cb_state->lastBound.cend()) {
1307 pipeline_state = last_bound_it->second.pipeline_state;
1308 }
1309 const auto& current_vtx_bfr_binding_info = cb_state->current_vertex_buffer_binding_info.vertex_buffer_bindings;
1310 // Verify vertex binding
1311 if (pipeline_state->vertex_binding_descriptions_.size() <= 0) {
1312 if ((!current_vtx_bfr_binding_info.empty()) && (!cb_state->vertex_buffer_used)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001313 skip |= LogPerformanceWarning(cb_state->commandBuffer, kVUID_BestPractices_DrawState_VtxIndexOutOfBounds,
1314 "Vertex buffers are bound to %s but no vertex buffers are attached to %s.",
1315 report_data->FormatHandle(cb_state->commandBuffer).c_str(),
1316 report_data->FormatHandle(pipeline_state->pipeline).c_str());
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001317 }
1318 }
1319 }
1320 return skip;
1321}
1322
Sam Walls0961ec02020-03-31 16:39:15 +01001323void BestPractices::RecordCmdDrawType(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
1324 if (VendorCheckEnabled(kBPVendorArm)) {
1325 RecordCmdDrawTypeArm(cmd_buffer, draw_count, caller);
1326 }
1327}
1328
1329void BestPractices::RecordCmdDrawTypeArm(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
1330 auto prepass_state = cbDepthPrePassStates.find(cmd_buffer);
1331 if (prepass_state != cbDepthPrePassStates.end() && draw_count >= kDepthPrePassMinDrawCountArm) {
1332 if (prepass_state->second.depthOnly) prepass_state->second.numDrawCallsDepthOnly++;
1333
1334 if (prepass_state->second.depthEqualComparison) prepass_state->second.numDrawCallsDepthEqualCompare++;
1335 }
1336}
1337
Camden5b184be2019-08-13 07:50:19 -06001338bool BestPractices::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001339 uint32_t firstVertex, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06001340 bool skip = false;
1341
1342 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001343 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
1344 "Warning: You are calling vkCmdDraw() with an instanceCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001345 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDraw()");
Camden5b184be2019-08-13 07:50:19 -06001346 }
1347
1348 return skip;
1349}
1350
Sam Walls0961ec02020-03-31 16:39:15 +01001351void BestPractices::PostCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
1352 uint32_t firstVertex, uint32_t firstInstance) {
1353 StateTracker::PostCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
1354 RecordCmdDrawType(commandBuffer, vertexCount * instanceCount, "vkCmdDraw()");
1355}
1356
Camden5b184be2019-08-13 07:50:19 -06001357bool BestPractices::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001358 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06001359 bool skip = false;
1360
1361 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001362 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
1363 "Warning: You are calling vkCmdDrawIndexed() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06001364 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001365 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexed()");
1366
Attilio Provenzano02859b22020-02-27 14:17:28 +00001367 // Check if we reached the limit for small indexed draw calls.
1368 // Note that we cannot update the draw call count here, so we do it in PreCallRecordCmdDrawIndexed.
1369 const CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
1370 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices &&
1371 (cmd_state->small_indexed_draw_call_count == kMaxSmallIndexedDrawcalls - 1)) {
1372 skip |= VendorCheckEnabled(kBPVendorArm) &&
1373 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_ManySmallIndexedDrawcalls,
1374 "The command buffer contains many small indexed drawcalls "
1375 "(at least %u drawcalls with less than %u indices each). This may cause pipeline bubbles. "
1376 "You can try batching drawcalls or instancing when applicable.",
1377 VendorSpecificTag(kBPVendorArm), kMaxSmallIndexedDrawcalls, kSmallIndexedDrawcallIndices);
1378 }
1379
Sam Walls8e77e4f2020-03-16 20:47:40 +00001380 if (VendorCheckEnabled(kBPVendorArm)) {
1381 ValidateIndexBufferArm(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
1382 }
1383
1384 return skip;
1385}
1386
1387bool BestPractices::ValidateIndexBufferArm(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1388 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
1389 bool skip = false;
1390
1391 // check for sparse/underutilised index buffer, and post-transform cache thrashing
1392 const auto* cmd_state = GetCBState(commandBuffer);
1393 if (cmd_state == nullptr) return skip;
1394
1395 const auto* ib_state = GetBufferState(cmd_state->index_buffer_binding.buffer);
1396 if (ib_state == nullptr) return skip;
1397
1398 const VkIndexType ib_type = cmd_state->index_buffer_binding.index_type;
1399 const auto& ib_mem_state = *ib_state->binding.mem_state;
1400 const VkDeviceSize ib_mem_offset = ib_mem_state.mapped_range.offset;
1401 const void* ib_mem = ib_mem_state.p_driver_data;
1402 bool primitive_restart_enable = false;
1403
1404 const auto& pipeline_binding_iter = cmd_state->lastBound.find(VK_PIPELINE_BIND_POINT_GRAPHICS);
1405
1406 if (pipeline_binding_iter != cmd_state->lastBound.end()) {
1407 const auto* pipeline_state = pipeline_binding_iter->second.pipeline_state;
1408 if (pipeline_state != nullptr && pipeline_state->graphicsPipelineCI.pInputAssemblyState != nullptr)
1409 primitive_restart_enable = pipeline_state->graphicsPipelineCI.pInputAssemblyState->primitiveRestartEnable == VK_TRUE;
1410 }
1411
1412 // no point checking index buffer if the memory is nonexistant/unmapped, or if there is no graphics pipeline bound to this CB
1413 if (ib_mem && pipeline_binding_iter != cmd_state->lastBound.end()) {
1414 uint32_t scan_stride;
1415 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1416 scan_stride = sizeof(uint8_t);
1417 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1418 scan_stride = sizeof(uint16_t);
1419 } else {
1420 scan_stride = sizeof(uint32_t);
1421 }
1422
1423 const uint8_t* scan_begin = static_cast<const uint8_t*>(ib_mem) + ib_mem_offset + firstIndex * scan_stride;
1424 const uint8_t* scan_end = scan_begin + indexCount * scan_stride;
1425
1426 // Min and max are important to track for some Mali architectures. In older Mali devices without IDVS, all
1427 // vertices corresponding to indices between the minimum and maximum may be loaded, and possibly shaded,
1428 // irrespective of whether or not they're part of the draw call.
1429
1430 // start with minimum as 0xFFFFFFFF and adjust to indices in the buffer
1431 uint32_t min_index = ~0u;
1432 // start with maximum as 0 and adjust to indices in the buffer
1433 uint32_t max_index = 0u;
1434
1435 // first scan-through, we're looking to simulate a model LRU post-transform cache, estimating the number of vertices shaded
1436 // for the given index buffer
1437 uint32_t vertex_shade_count = 0;
1438
1439 PostTransformLRUCacheModel post_transform_cache;
1440
1441 // The size of the cache being modelled positively correlates with how much behaviour it can capture about
1442 // arbitrary ground-truth hardware/architecture cache behaviour. I.e. it's a good solution when we don't know the
1443 // target architecture.
1444 // However, modelling a post-transform cache with more than 32 elements gives diminishing returns in practice.
1445 // http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
1446 post_transform_cache.resize(32);
1447
1448 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
1449 uint32_t scan_index;
1450 uint32_t primitive_restart_value;
1451 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1452 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
1453 primitive_restart_value = 0xFF;
1454 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1455 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
1456 primitive_restart_value = 0xFFFF;
1457 } else {
1458 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
1459 primitive_restart_value = 0xFFFFFFFF;
1460 }
1461
1462 max_index = std::max(max_index, scan_index);
1463 min_index = std::min(min_index, scan_index);
1464
1465 if (!primitive_restart_enable || scan_index != primitive_restart_value) {
1466 bool in_cache = post_transform_cache.query_cache(scan_index);
1467 // if the shaded vertex corresponding to the index is not in the PT-cache, we need to shade again
1468 if (!in_cache) vertex_shade_count++;
1469 }
1470 }
1471
1472 // 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 +01001473 // 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
1474 if (max_index < min_index || max_index == min_index) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00001475
1476 if (max_index - min_index >= indexCount) {
1477 skip |= LogPerformanceWarning(
1478 device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
1479 "%s The indices which were specified for the draw call only utilise approximately %.02f%% of "
1480 "index buffer value range. Arm Mali architectures before G71 do not have IDVS (Index-Driven "
1481 "Vertex Shading), meaning all vertices corresponding to indices between the minimum and "
1482 "maximum would be loaded, and possibly shaded, whether or not they are used.",
1483 VendorSpecificTag(kBPVendorArm), (static_cast<float>(indexCount) / (max_index - min_index)) * 100.0f);
1484 return skip;
1485 }
1486
1487 // use a dynamic vector of bitsets as a memory-compact representation of which indices are included in the draw call
1488 // 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 +01001489 const size_t refs_per_bucket = 64;
1490 std::vector<std::bitset<refs_per_bucket>> vertex_reference_buckets;
1491
1492 const uint32_t n_indices = max_index - min_index + 1;
1493 const uint32_t n_buckets = (n_indices / static_cast<uint32_t>(refs_per_bucket)) +
1494 ((n_indices % static_cast<uint32_t>(refs_per_bucket)) != 0 ? 1 : 0);
1495
1496 // there needs to be at least one bitset to store a set of indices smaller than n_buckets
1497 vertex_reference_buckets.resize(std::max(1u, n_buckets));
Sam Walls8e77e4f2020-03-16 20:47:40 +00001498
1499 // To avoid using too much memory, we run over the indices again.
1500 // Knowing the size from the last scan allows us to record index usage with bitsets
1501 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
1502 uint32_t scan_index;
1503 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1504 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
1505 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1506 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
1507 } else {
1508 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
1509 }
1510 // keep track of the set of all indices used to reference vertices in the draw call
1511 size_t index_offset = scan_index - min_index;
Sam Walls61b06892020-07-23 16:20:50 +01001512 size_t bitset_bucket_index = index_offset / refs_per_bucket;
1513 uint64_t used_indices = 1ull << ((index_offset % refs_per_bucket) & 0xFFFFFFFFu);
Sam Walls8e77e4f2020-03-16 20:47:40 +00001514 vertex_reference_buckets[bitset_bucket_index] |= used_indices;
1515 }
1516
1517 uint32_t vertex_reference_count = 0;
1518 for (const auto& bitset : vertex_reference_buckets) {
1519 vertex_reference_count += static_cast<uint32_t>(bitset.count());
1520 }
1521
1522 // low index buffer utilization implies that: of the vertices available to the draw call, not all are utilized
1523 float utilization = static_cast<float>(vertex_reference_count) / (max_index - min_index + 1);
1524 // low hit rate (high miss rate) implies the order of indices in the draw call may be possible to improve
1525 float cache_hit_rate = static_cast<float>(vertex_reference_count) / vertex_shade_count;
1526
1527 if (utilization < 0.5f) {
1528 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
1529 "%s The indices which were specified for the draw call only utilise approximately "
1530 "%.02f%% of the bound vertex buffer.",
1531 VendorSpecificTag(kBPVendorArm), utilization);
1532 }
1533
1534 if (cache_hit_rate <= 0.5f) {
1535 skip |=
1536 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_PostTransformCacheThrashing,
1537 "%s The indices which were specified for the draw call are estimated to cause thrashing of "
1538 "the post-transform vertex cache, with a hit-rate of %.02f%%. "
1539 "I.e. the ordering of the index buffer may not make optimal use of indices associated with "
1540 "recently shaded vertices.",
1541 VendorSpecificTag(kBPVendorArm), cache_hit_rate * 100.0f);
1542 }
1543 }
1544
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001545 return skip;
1546}
1547
Attilio Provenzano02859b22020-02-27 14:17:28 +00001548void BestPractices::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1549 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
1550 ValidationStateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset,
1551 firstInstance);
1552
1553 CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
1554 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices) {
1555 cmd_state->small_indexed_draw_call_count++;
1556 }
1557}
1558
Sam Walls0961ec02020-03-31 16:39:15 +01001559void BestPractices::PostCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1560 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
1561 StateTracker::PostCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
1562 RecordCmdDrawType(commandBuffer, indexCount * instanceCount, "vkCmdDrawIndexed()");
1563}
1564
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001565bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
1566 VkDeviceSize offset, VkBuffer countBuffer,
1567 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
1568 uint32_t stride) const {
1569 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCountKHR()");
Camden5b184be2019-08-13 07:50:19 -06001570
1571 return skip;
1572}
1573
1574bool BestPractices::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001575 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06001576 bool skip = false;
1577
1578 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001579 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
1580 "Warning: You are calling vkCmdDrawIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001581 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirect()");
Camden5b184be2019-08-13 07:50:19 -06001582 }
1583
1584 return skip;
1585}
1586
Sam Walls0961ec02020-03-31 16:39:15 +01001587void BestPractices::PostCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
1588 uint32_t count, uint32_t stride) {
1589 StateTracker::PostCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, count, stride);
1590 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndirect()");
1591}
1592
Camden5b184be2019-08-13 07:50:19 -06001593bool BestPractices::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001594 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06001595 bool skip = false;
1596
1597 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001598 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
1599 "Warning: You are calling vkCmdDrawIndexedIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001600 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirect()");
Camden5b184be2019-08-13 07:50:19 -06001601 }
1602
1603 return skip;
1604}
1605
Sam Walls0961ec02020-03-31 16:39:15 +01001606void BestPractices::PostCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
1607 uint32_t count, uint32_t stride) {
1608 StateTracker::PostCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, count, stride);
1609 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndexedIndirect()");
1610}
1611
Camden5b184be2019-08-13 07:50:19 -06001612bool BestPractices::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t groupCountX, uint32_t groupCountY,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001613 uint32_t groupCountZ) const {
Camden5b184be2019-08-13 07:50:19 -06001614 bool skip = false;
1615
1616 if ((groupCountX == 0) || (groupCountY == 0) || (groupCountZ == 0)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001617 skip |= LogWarning(device, kVUID_BestPractices_CmdDispatch_GroupCountZero,
1618 "Warning: You are calling vkCmdDispatch() while one or more groupCounts are zero (groupCountX = %" PRIu32
1619 ", groupCountY = %" PRIu32 ", groupCountZ = %" PRIu32 ").",
1620 groupCountX, groupCountY, groupCountZ);
Camden5b184be2019-08-13 07:50:19 -06001621 }
1622
1623 return skip;
1624}
Camden83a9c372019-08-14 11:41:38 -06001625
Sam Walls0961ec02020-03-31 16:39:15 +01001626bool BestPractices::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
1627 bool skip = false;
1628
1629 skip |= StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
1630
1631 auto prepass_state = cbDepthPrePassStates.find(commandBuffer);
1632
1633 if (prepass_state == cbDepthPrePassStates.end()) return skip;
1634
1635 bool uses_depth = (prepass_state->second.depthAttachment || prepass_state->second.colorAttachment) &&
1636 prepass_state->second.numDrawCallsDepthEqualCompare >= kDepthPrePassNumDrawCallsArm &&
1637 prepass_state->second.numDrawCallsDepthOnly >= kDepthPrePassNumDrawCallsArm;
1638 if (uses_depth) {
1639 skip |= LogPerformanceWarning(
1640 device, kVUID_BestPractices_EndRenderPass_DepthPrePassUsage,
1641 "%s Depth pre-passes may be in use. In general, this is not recommended, as in Arm Mali GPUs since "
1642 "Mali-T620, Forward Pixel Killing (FPK) can already perform automatic hidden surface removal; in which "
1643 "case, using depth pre-passes for hidden surface removal may worsen performance.",
1644 VendorSpecificTag(kBPVendorArm));
1645 }
1646
1647 return skip;
1648}
1649
Camden Stocker9c051442019-11-06 14:28:43 -08001650bool BestPractices::ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(VkPhysicalDevice physicalDevice,
1651 const char* api_name) const {
1652 bool skip = false;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001653 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
Camden Stocker9c051442019-11-06 14:28:43 -08001654
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001655 if (bp_pd_state) {
1656 if (bp_pd_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState == UNCALLED) {
1657 skip |= LogWarning(physicalDevice, kVUID_BestPractices_DisplayPlane_PropertiesNotCalled,
1658 "Potential problem with calling %s() without first retrieving properties from "
1659 "vkGetPhysicalDeviceDisplayPlanePropertiesKHR or vkGetPhysicalDeviceDisplayPlaneProperties2KHR.",
1660 api_name);
1661 }
Camden Stocker9c051442019-11-06 14:28:43 -08001662 }
1663
1664 return skip;
1665}
1666
Camden83a9c372019-08-14 11:41:38 -06001667bool BestPractices::PreCallValidateGetDisplayPlaneSupportedDisplaysKHR(VkPhysicalDevice physicalDevice, uint32_t planeIndex,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001668 uint32_t* pDisplayCount, VkDisplayKHR* pDisplays) const {
Camden83a9c372019-08-14 11:41:38 -06001669 bool skip = false;
1670
Camden Stocker9c051442019-11-06 14:28:43 -08001671 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneSupportedDisplaysKHR");
Camden83a9c372019-08-14 11:41:38 -06001672
Camden Stocker9c051442019-11-06 14:28:43 -08001673 return skip;
1674}
1675
1676bool BestPractices::PreCallValidateGetDisplayPlaneCapabilitiesKHR(VkPhysicalDevice physicalDevice, VkDisplayModeKHR mode,
1677 uint32_t planeIndex,
1678 VkDisplayPlaneCapabilitiesKHR* pCapabilities) const {
1679 bool skip = false;
1680
1681 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilitiesKHR");
1682
1683 return skip;
1684}
1685
1686bool BestPractices::PreCallValidateGetDisplayPlaneCapabilities2KHR(VkPhysicalDevice physicalDevice,
1687 const VkDisplayPlaneInfo2KHR* pDisplayPlaneInfo,
1688 VkDisplayPlaneCapabilities2KHR* pCapabilities) const {
1689 bool skip = false;
1690
1691 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilities2KHR");
Camden83a9c372019-08-14 11:41:38 -06001692
1693 return skip;
1694}
Camden05de2d42019-08-19 10:23:56 -06001695
1696bool BestPractices::PreCallValidateGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain, uint32_t* pSwapchainImageCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001697 VkImage* pSwapchainImages) const {
Camden05de2d42019-08-19 10:23:56 -06001698 bool skip = false;
1699
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001700 auto swapchain_state_itr = swapchain_bp_state_map.find(swapchain);
Camden05de2d42019-08-19 10:23:56 -06001701
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001702 if ((swapchain_state_itr != swapchain_bp_state_map.cend()) && pSwapchainImages) {
Camden05de2d42019-08-19 10:23:56 -06001703 // Compare the preliminary value of *pSwapchainImageCount with the value this time:
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001704 if (swapchain_state_itr->second.vkGetSwapchainImagesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001705 skip |=
1706 LogWarning(device, kVUID_Core_Swapchain_PriorCount,
1707 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImageCount; but no prior positive value has "
1708 "been seen for pSwapchainImages.");
Camden05de2d42019-08-19 10:23:56 -06001709 }
1710 }
1711
1712 return skip;
1713}
1714
1715// Common function to handle validation for GetPhysicalDeviceQueueFamilyProperties & 2KHR version
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001716bool BestPractices::ValidateCommonGetPhysicalDeviceQueueFamilyProperties(const PHYSICAL_DEVICE_STATE* pd_state,
1717 uint32_t requested_queue_family_property_count,
1718 bool qfp_null, const char* caller_name) const {
Camden05de2d42019-08-19 10:23:56 -06001719 bool skip = false;
1720 if (!qfp_null) {
1721 // 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 -06001722 const auto* bp_pd_state = GetPhysicalDeviceStateBP(pd_state->phys_device);
1723 if (bp_pd_state) {
1724 if (UNCALLED == bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState) {
1725 skip |= LogWarning(
1726 pd_state->phys_device, kVUID_Core_DevLimit_MissingQueryCount,
1727 "%s is called with non-NULL pQueueFamilyProperties before obtaining pQueueFamilyPropertyCount. It is "
1728 "recommended "
1729 "to first call %s with NULL pQueueFamilyProperties in order to obtain the maximal pQueueFamilyPropertyCount.",
1730 caller_name, caller_name);
1731 // Then verify that pCount that is passed in on second call matches what was returned
1732 } else if (pd_state->queue_family_known_count != requested_queue_family_property_count) {
1733 skip |=
1734 LogWarning(pd_state->phys_device, kVUID_Core_DevLimit_CountMismatch,
1735 "%s is called with non-NULL pQueueFamilyProperties and pQueueFamilyPropertyCount value %" PRIu32
1736 ", but the largest previously returned pQueueFamilyPropertyCount for this physicalDevice is %" PRIu32
1737 ". It is recommended to instead receive all the properties by calling %s with "
1738 "pQueueFamilyPropertyCount that was "
1739 "previously obtained by calling %s with NULL pQueueFamilyProperties.",
1740 caller_name, requested_queue_family_property_count, pd_state->queue_family_known_count, caller_name,
1741 caller_name);
1742 }
Camden05de2d42019-08-19 10:23:56 -06001743 }
1744 }
1745
1746 return skip;
1747}
1748
Jeff Bolz5c801d12019-10-09 10:38:45 -05001749bool BestPractices::PreCallValidateBindAccelerationStructureMemoryNV(
1750 VkDevice device, uint32_t bindInfoCount, const VkBindAccelerationStructureMemoryInfoNV* pBindInfos) const {
Camden Stocker82510582019-09-03 14:00:16 -06001751 bool skip = false;
1752
1753 for (uint32_t i = 0; i < bindInfoCount; i++) {
1754 const ACCELERATION_STRUCTURE_STATE* as_state = GetAccelerationStructureState(pBindInfos[i].accelerationStructure);
1755 if (!as_state->memory_requirements_checked) {
1756 // There's not an explicit requirement in the spec to call vkGetImageMemoryRequirements() prior to calling
1757 // BindAccelerationStructureMemoryNV but it's implied in that memory being bound must conform with
1758 // VkAccelerationStructureMemoryRequirementsInfoNV from vkGetAccelerationStructureMemoryRequirementsNV
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001759 skip |= LogWarning(
1760 device, kVUID_BestPractices_BindAccelNV_NoMemReqQuery,
Camden Stocker82510582019-09-03 14:00:16 -06001761 "vkBindAccelerationStructureMemoryNV(): "
1762 "Binding memory to %s but vkGetAccelerationStructureMemoryRequirementsNV() has not been called on that structure.",
1763 report_data->FormatHandle(pBindInfos[i].accelerationStructure).c_str());
1764 }
1765 }
1766
1767 return skip;
1768}
1769
Camden05de2d42019-08-19 10:23:56 -06001770bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
1771 uint32_t* pQueueFamilyPropertyCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001772 VkQueueFamilyProperties* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06001773 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1774 assert(physical_device_state);
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001775 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
Camden05de2d42019-08-19 10:23:56 -06001776 (nullptr == pQueueFamilyProperties),
1777 "vkGetPhysicalDeviceQueueFamilyProperties()");
1778}
1779
Jeff Bolz5c801d12019-10-09 10:38:45 -05001780bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2(
1781 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount,
1782 VkQueueFamilyProperties2KHR* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06001783 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1784 assert(physical_device_state);
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001785 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
Camden05de2d42019-08-19 10:23:56 -06001786 (nullptr == pQueueFamilyProperties),
1787 "vkGetPhysicalDeviceQueueFamilyProperties2()");
1788}
1789
Jeff Bolz5c801d12019-10-09 10:38:45 -05001790bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2KHR(
1791 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount,
1792 VkQueueFamilyProperties2KHR* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06001793 auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1794 assert(physical_device_state);
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001795 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
Camden05de2d42019-08-19 10:23:56 -06001796 (nullptr == pQueueFamilyProperties),
1797 "vkGetPhysicalDeviceQueueFamilyProperties2KHR()");
1798}
1799
1800bool BestPractices::PreCallValidateGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
1801 uint32_t* pSurfaceFormatCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001802 VkSurfaceFormatKHR* pSurfaceFormats) const {
Camden05de2d42019-08-19 10:23:56 -06001803 if (!pSurfaceFormats) return false;
1804 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001805 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
1806 const auto& call_state = bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState;
Camden05de2d42019-08-19 10:23:56 -06001807 bool skip = false;
1808 if (call_state == UNCALLED) {
1809 // Since we haven't recorded a preliminary value of *pSurfaceFormatCount, that likely means that the application didn't
1810 // previously call this function with a NULL value of pSurfaceFormats:
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001811 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_MustQueryCount,
1812 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount; but no prior "
1813 "positive value has been seen for pSurfaceFormats.");
Camden05de2d42019-08-19 10:23:56 -06001814 } else {
1815 auto prev_format_count = (uint32_t)physical_device_state->surface_formats.size();
Peter Chene191bd72019-09-16 13:04:37 -04001816 if (*pSurfaceFormatCount > prev_format_count) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001817 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_CountMismatch,
1818 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount, and with "
1819 "pSurfaceFormats set to a value (%u) that is greater than the value (%u) that was returned "
1820 "when pSurfaceFormatCount was NULL.",
1821 *pSurfaceFormatCount, prev_format_count);
Camden05de2d42019-08-19 10:23:56 -06001822 }
1823 }
1824 return skip;
1825}
Camden Stocker23cc47d2019-09-03 14:53:57 -06001826
1827bool BestPractices::PreCallValidateQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001828 VkFence fence) const {
Camden Stocker23cc47d2019-09-03 14:53:57 -06001829 bool skip = false;
1830
1831 for (uint32_t bindIdx = 0; bindIdx < bindInfoCount; bindIdx++) {
1832 const VkBindSparseInfo& bindInfo = pBindInfo[bindIdx];
1833 // 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 -05001834 std::unordered_set<const IMAGE_STATE*> sparse_images;
1835 // Track images getting metadata bound by this call in a set, it'll be recorded into the image_state
1836 // in RecordQueueBindSparse.
1837 std::unordered_set<const IMAGE_STATE*> sparse_images_with_metadata;
Camden Stocker23cc47d2019-09-03 14:53:57 -06001838 // If we're binding sparse image memory make sure reqs were queried and note if metadata is required and bound
1839 for (uint32_t i = 0; i < bindInfo.imageBindCount; ++i) {
1840 const auto& image_bind = bindInfo.pImageBinds[i];
1841 auto image_state = GetImageState(image_bind.image);
1842 if (!image_state)
1843 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
1844 sparse_images.insert(image_state);
1845 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
1846 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
1847 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001848 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1849 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
1850 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
1851 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001852 }
1853 }
1854 if (!image_state->memory_requirements_checked) {
1855 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001856 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1857 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
1858 "vkGetImageMemoryRequirements() to retrieve requirements.",
1859 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001860 }
1861 }
1862 for (uint32_t i = 0; i < bindInfo.imageOpaqueBindCount; ++i) {
1863 const auto& image_opaque_bind = bindInfo.pImageOpaqueBinds[i];
1864 auto image_state = GetImageState(bindInfo.pImageOpaqueBinds[i].image);
1865 if (!image_state)
1866 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
1867 sparse_images.insert(image_state);
1868 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
1869 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
1870 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001871 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1872 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
1873 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
1874 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001875 }
1876 }
1877 if (!image_state->memory_requirements_checked) {
1878 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001879 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1880 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
1881 "vkGetImageMemoryRequirements() to retrieve requirements.",
1882 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001883 }
1884 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
1885 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001886 sparse_images_with_metadata.insert(image_state);
Camden Stocker23cc47d2019-09-03 14:53:57 -06001887 }
1888 }
1889 }
1890 for (const auto& sparse_image_state : sparse_images) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001891 if (sparse_image_state->sparse_metadata_required && !sparse_image_state->sparse_metadata_bound &&
1892 sparse_images_with_metadata.find(sparse_image_state) == sparse_images_with_metadata.end()) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06001893 // Warn if sparse image binding metadata required for image with sparse binding, but metadata not bound
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001894 skip |= LogWarning(sparse_image_state->image, kVUID_Core_MemTrack_InvalidState,
1895 "vkQueueBindSparse(): Binding sparse memory to %s which requires a metadata aspect but no "
1896 "binding with VK_SPARSE_MEMORY_BIND_METADATA_BIT set was made.",
1897 report_data->FormatHandle(sparse_image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001898 }
1899 }
1900 }
1901
1902 return skip;
1903}
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001904
Mark Lobodzinski84101d72020-04-24 09:43:48 -06001905void BestPractices::ManualPostCallRecordQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
1906 VkFence fence, VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07001907 if (result != VK_SUCCESS) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07001908 return;
1909 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001910
1911 for (uint32_t bindIdx = 0; bindIdx < bindInfoCount; bindIdx++) {
1912 const VkBindSparseInfo& bindInfo = pBindInfo[bindIdx];
1913 for (uint32_t i = 0; i < bindInfo.imageOpaqueBindCount; ++i) {
1914 const auto& image_opaque_bind = bindInfo.pImageOpaqueBinds[i];
1915 auto image_state = GetImageState(bindInfo.pImageOpaqueBinds[i].image);
1916 if (!image_state)
1917 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
1918 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
1919 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
1920 image_state->sparse_metadata_bound = true;
1921 }
1922 }
1923 }
1924 }
1925}
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001926
1927bool BestPractices::PreCallValidateCmdClearAttachments(VkCommandBuffer commandBuffer, uint32_t attachmentCount,
Camden Stockerf55721f2019-09-09 11:04:49 -06001928 const VkClearAttachment* pAttachments, uint32_t rectCount,
1929 const VkClearRect* pRects) const {
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001930 bool skip = false;
1931 const CMD_BUFFER_STATE* cb_node = GetCBState(commandBuffer);
1932 if (!cb_node) return skip;
1933
Camden Stockerf55721f2019-09-09 11:04:49 -06001934 // Warn if this is issued prior to Draw Cmd and clearing the entire attachment
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001935 if (!cb_node->hasDrawCmd && (cb_node->activeRenderPassBeginInfo.renderArea.extent.width == pRects[0].rect.extent.width) &&
1936 (cb_node->activeRenderPassBeginInfo.renderArea.extent.height == pRects[0].rect.extent.height)) {
1937 // There are times where app needs to use ClearAttachments (generally when reusing a buffer inside of a render pass)
1938 // This warning should be made more specific. It'd be best to avoid triggering this test if it's a use that must call
1939 // CmdClearAttachments.
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001940 skip |= LogPerformanceWarning(commandBuffer, kVUID_BestPractices_DrawState_ClearCmdBeforeDraw,
1941 "vkCmdClearAttachments() issued on %s prior to any Draw Cmds. It is recommended you "
1942 "use RenderPass LOAD_OP_CLEAR on Attachments prior to any Draw.",
1943 report_data->FormatHandle(commandBuffer).c_str());
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001944 }
1945
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001946 // Check for uses of ClearAttachments along with LOAD_OP_LOAD,
1947 // as it can be more efficient to just use LOAD_OP_CLEAR
locke-lunargaecf2152020-05-12 17:15:41 -06001948 const RENDER_PASS_STATE* rp = cb_node->activeRenderPass.get();
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001949 if (rp) {
1950 const auto& subpass = rp->createInfo.pSubpasses[cb_node->activeSubpass];
1951
1952 for (uint32_t i = 0; i < attachmentCount; i++) {
1953 auto& attachment = pAttachments[i];
1954 if (attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
1955 uint32_t color_attachment = attachment.colorAttachment;
1956 uint32_t fb_attachment = subpass.pColorAttachments[color_attachment].attachment;
1957
1958 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
1959 if (rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
1960 skip |= LogPerformanceWarning(
1961 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
1962 "vkCmdClearAttachments() issued on %s for color attachment #%u in this subpass, "
1963 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
1964 "it is more efficient.",
1965 report_data->FormatHandle(commandBuffer).c_str(), color_attachment);
1966 }
1967 }
1968 }
1969
1970 if (subpass.pDepthStencilAttachment && attachment.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) {
1971 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
1972
1973 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
1974 if (rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
1975 skip |= LogPerformanceWarning(
1976 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
1977 "vkCmdClearAttachments() issued on %s for the depth attachment in this subpass, "
1978 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
1979 "it is more efficient.",
1980 report_data->FormatHandle(commandBuffer).c_str());
1981 }
1982 }
1983 }
1984
1985 if (subpass.pDepthStencilAttachment && attachment.aspectMask & VK_IMAGE_ASPECT_STENCIL_BIT) {
1986 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
1987
1988 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
1989 if (rp->createInfo.pAttachments[fb_attachment].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
1990 skip |= LogPerformanceWarning(
1991 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
1992 "vkCmdClearAttachments() issued on %s for the stencil attachment in this subpass, "
1993 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
1994 "it is more efficient.",
1995 report_data->FormatHandle(commandBuffer).c_str());
1996 }
1997 }
1998 }
1999 }
2000 }
2001
Camden Stockerf55721f2019-09-09 11:04:49 -06002002 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002003}
Attilio Provenzano02859b22020-02-27 14:17:28 +00002004
2005bool BestPractices::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
2006 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
2007 const VkImageResolve* pRegions) const {
2008 bool skip = false;
2009
2010 skip |= VendorCheckEnabled(kBPVendorArm) &&
2011 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage_ResolvingImage,
2012 "%s Attempting to use vkCmdResolveImage to resolve a multisampled image. "
2013 "This is a very slow and extremely bandwidth intensive path. "
2014 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
2015 VendorSpecificTag(kBPVendorArm));
2016
2017 return skip;
2018}
2019
2020bool BestPractices::PreCallValidateCreateSampler(VkDevice device, const VkSamplerCreateInfo* pCreateInfo,
2021 const VkAllocationCallbacks* pAllocator, VkSampler* pSampler) const {
2022 bool skip = false;
2023
2024 if (VendorCheckEnabled(kBPVendorArm)) {
2025 if ((pCreateInfo->addressModeU != pCreateInfo->addressModeV) || (pCreateInfo->addressModeV != pCreateInfo->addressModeW)) {
2026 skip |= LogPerformanceWarning(
2027 device, kVUID_BestPractices_CreateSampler_DifferentWrappingModes,
2028 "%s Creating a sampler object with wrapping modes which do not match (U = %u, V = %u, W = %u). "
2029 "This may cause reduced performance even if only U (1D image) or U/V wrapping modes (2D "
2030 "image) are actually used. If you need different wrapping modes, disregard this warning.",
2031 VendorSpecificTag(kBPVendorArm));
2032 }
2033
2034 if ((pCreateInfo->minLod != 0.0f) || (pCreateInfo->maxLod < VK_LOD_CLAMP_NONE)) {
2035 skip |= LogPerformanceWarning(
2036 device, kVUID_BestPractices_CreateSampler_LodClamping,
2037 "%s Creating a sampler object with LOD clamping (minLod = %f, maxLod = %f). This may cause reduced performance. "
2038 "Instead of clamping LOD in the sampler, consider using an VkImageView which restricts the mip-levels, set minLod "
2039 "to 0.0, and maxLod to VK_LOD_CLAMP_NONE.",
2040 VendorSpecificTag(kBPVendorArm), pCreateInfo->minLod, pCreateInfo->maxLod);
2041 }
2042
2043 if (pCreateInfo->mipLodBias != 0.0f) {
2044 skip |=
2045 LogPerformanceWarning(device, kVUID_BestPractices_CreateSampler_LodBias,
2046 "%s Creating a sampler object with LOD bias != 0.0 (%f). This will lead to less efficient "
2047 "descriptors being created and may cause reduced performance.",
2048 VendorSpecificTag(kBPVendorArm), pCreateInfo->mipLodBias);
2049 }
2050
2051 if ((pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
2052 pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
2053 pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER) &&
2054 (pCreateInfo->borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK)) {
2055 skip |= LogPerformanceWarning(
2056 device, kVUID_BestPractices_CreateSampler_BorderClampColor,
2057 "%s Creating a sampler object with border clamping and borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK. "
2058 "This will lead to less efficient descriptors being created and may cause reduced performance. "
2059 "If possible, use VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK as the border color.",
2060 VendorSpecificTag(kBPVendorArm));
2061 }
2062
2063 if (pCreateInfo->unnormalizedCoordinates) {
2064 skip |= LogPerformanceWarning(
2065 device, kVUID_BestPractices_CreateSampler_UnnormalizedCoordinates,
2066 "%s Creating a sampler object with unnormalized coordinates. This will lead to less efficient "
2067 "descriptors being created and may cause reduced performance.",
2068 VendorSpecificTag(kBPVendorArm));
2069 }
2070
2071 if (pCreateInfo->anisotropyEnable) {
2072 skip |= LogPerformanceWarning(
2073 device, kVUID_BestPractices_CreateSampler_Anisotropy,
2074 "%s Creating a sampler object with anisotropy. This will lead to less efficient descriptors being created "
2075 "and may cause reduced performance.",
2076 VendorSpecificTag(kBPVendorArm));
2077 }
2078 }
2079
2080 return skip;
2081}
Sam Walls8e77e4f2020-03-16 20:47:40 +00002082
2083void BestPractices::PostTransformLRUCacheModel::resize(size_t size) { _entries.resize(size); }
2084
2085bool BestPractices::PostTransformLRUCacheModel::query_cache(uint32_t value) {
2086 // look for a cache hit
2087 auto hit = std::find_if(_entries.begin(), _entries.end(), [value](const CacheEntry& entry) { return entry.value == value; });
2088 if (hit != _entries.end()) {
2089 // mark the cache hit as being most recently used
2090 hit->age = iteration++;
2091 return true;
2092 }
2093
2094 // if there's no cache hit, we need to model the entry being inserted into the cache
2095 CacheEntry new_entry = {value, iteration};
2096 if (iteration < static_cast<uint32_t>(std::distance(_entries.begin(), _entries.end()))) {
2097 // if there is still space left in the cache, use the next available slot
2098 *(_entries.begin() + iteration) = new_entry;
2099 } else {
2100 // otherwise replace the least recently used cache entry
2101 auto lru = std::min_element(_entries.begin(), hit, [](const CacheEntry& a, const CacheEntry& b) { return a.age < b.age; });
2102 *lru = new_entry;
2103 }
2104 iteration++;
2105 return false;
2106}
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002107
2108bool BestPractices::PreCallValidateAcquireNextImageKHR(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout,
2109 VkSemaphore semaphore, VkFence fence, uint32_t* pImageIndex) const {
2110 const auto swapchain_data = GetSwapchainState(swapchain);
2111 bool skip = false;
2112 if (swapchain_data && swapchain_data->images.size() == 0) {
2113 skip |= LogWarning(swapchain, kVUID_Core_DrawState_SwapchainImagesNotFound,
2114 "vkAcquireNextImageKHR: No images found to acquire from. Application probably did not call "
2115 "vkGetSwapchainImagesKHR after swapchain creation.");
2116 }
2117 return skip;
2118}
2119
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002120void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
2121 uint32_t* pQueueFamilyPropertyCount,
2122 VkQueueFamilyProperties* pQueueFamilyProperties) {
2123 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(physicalDevice, pQueueFamilyPropertyCount,
2124 pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002125 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002126 if (bp_pd_state) {
2127 if (!pQueueFamilyProperties) {
2128 if (UNCALLED == bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState)
2129 bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState = QUERY_COUNT;
2130 } else { // Save queue family properties
2131 bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState = QUERY_DETAILS;
2132 }
2133 }
2134}
2135
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002136void BestPractices::PostCallRecordGetPhysicalDeviceFeatures(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures* pFeatures) {
2137 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002138 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2139 if (bp_pd_state) {
2140 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
2141 }
2142}
2143
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002144void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2(VkPhysicalDevice physicalDevice,
2145 VkPhysicalDeviceFeatures2* pFeatures) {
2146 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002147 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2148 if (bp_pd_state) {
2149 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
2150 }
2151}
2152
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002153void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2KHR(VkPhysicalDevice physicalDevice,
2154 VkPhysicalDeviceFeatures2* pFeatures) {
2155 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2KHR(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002156 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2157 if (bp_pd_state) {
2158 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
2159 }
2160}
2161
2162void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilitiesKHR(VkPhysicalDevice physicalDevice,
2163 VkSurfaceKHR surface,
2164 VkSurfaceCapabilitiesKHR* pSurfaceCapabilities,
2165 VkResult result) {
2166 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2167 if (bp_pd_state) {
2168 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
2169 }
2170}
2171
2172void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2KHR(
2173 VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
2174 VkSurfaceCapabilities2KHR* pSurfaceCapabilities, VkResult result) {
2175 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2176 if (bp_pd_state) {
2177 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
2178 }
2179}
2180
2181void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2EXT(VkPhysicalDevice physicalDevice,
2182 VkSurfaceKHR surface,
2183 VkSurfaceCapabilities2EXT* pSurfaceCapabilities,
2184 VkResult result) {
2185 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2186 if (bp_pd_state) {
2187 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
2188 }
2189}
2190
2191void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice physicalDevice,
2192 VkSurfaceKHR surface, uint32_t* pPresentModeCount,
2193 VkPresentModeKHR* pPresentModes, VkResult result) {
2194 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2195 if (bp_pd_data) {
2196 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfacePresentModesKHRState;
2197
2198 if (*pPresentModeCount) {
2199 if (call_state < QUERY_COUNT) {
2200 call_state = QUERY_COUNT;
2201 }
2202 }
2203 if (pPresentModes) {
2204 if (call_state < QUERY_DETAILS) {
2205 call_state = QUERY_DETAILS;
2206 }
2207 }
2208 }
2209}
2210
2211void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
2212 uint32_t* pSurfaceFormatCount,
2213 VkSurfaceFormatKHR* pSurfaceFormats, VkResult result) {
2214 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2215 if (bp_pd_data) {
2216 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState;
2217
2218 if (*pSurfaceFormatCount) {
2219 if (call_state < QUERY_COUNT) {
2220 call_state = QUERY_COUNT;
2221 }
2222 }
2223 if (pSurfaceFormats) {
2224 if (call_state < QUERY_DETAILS) {
2225 call_state = QUERY_DETAILS;
2226 }
2227 }
2228 }
2229}
2230
2231void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormats2KHR(VkPhysicalDevice physicalDevice,
2232 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
2233 uint32_t* pSurfaceFormatCount,
2234 VkSurfaceFormat2KHR* pSurfaceFormats, VkResult result) {
2235 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2236 if (bp_pd_data) {
2237 if (*pSurfaceFormatCount) {
2238 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_COUNT) {
2239 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_COUNT;
2240 }
2241 }
2242 if (pSurfaceFormats) {
2243 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_DETAILS) {
2244 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_DETAILS;
2245 }
2246 }
2247 }
2248}
2249
2250void BestPractices::ManualPostCallRecordGetPhysicalDeviceDisplayPlanePropertiesKHR(VkPhysicalDevice physicalDevice,
2251 uint32_t* pPropertyCount,
2252 VkDisplayPlanePropertiesKHR* pProperties,
2253 VkResult result) {
2254 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2255 if (bp_pd_data) {
2256 if (*pPropertyCount) {
2257 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_COUNT) {
2258 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_COUNT;
2259 }
2260 }
2261 if (pProperties) {
2262 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_DETAILS) {
2263 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_DETAILS;
2264 }
2265 }
2266 }
2267}
2268
2269void BestPractices::ManualPostCallRecordCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
2270 const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain,
2271 VkResult result) {
2272 if (VK_SUCCESS == result) {
2273 swapchain_bp_state_map.emplace(*pSwapchain, SWAPCHAIN_STATE_BP{});
2274 }
2275}
2276
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002277void BestPractices::PostCallRecordDestroySwapchainKHR(VkDevice device, VkSwapchainKHR swapchain,
2278 const VkAllocationCallbacks* pAllocator) {
2279 ValidationStateTracker::PostCallRecordDestroySwapchainKHR(device, swapchain, pAllocator);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002280 auto swapchain_state_itr = swapchain_bp_state_map.find(swapchain);
2281 if (swapchain_state_itr != swapchain_bp_state_map.cend()) {
2282 swapchain_bp_state_map.erase(swapchain_state_itr);
2283 }
2284}
2285
2286void BestPractices::ManualPostCallRecordGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain,
2287 uint32_t* pSwapchainImageCount, VkImage* pSwapchainImages,
2288 VkResult result) {
2289 auto swapchain_state_itr = swapchain_bp_state_map.find(swapchain);
2290 assert(swapchain_state_itr != swapchain_bp_state_map.cend());
2291 auto& swapchain_state = swapchain_state_itr->second;
2292 if (pSwapchainImages || *pSwapchainImageCount) {
2293 if (swapchain_state.vkGetSwapchainImagesKHRState < QUERY_DETAILS) {
2294 swapchain_state.vkGetSwapchainImagesKHRState = QUERY_DETAILS;
2295 }
2296 }
2297}
2298
2299void BestPractices::ManualPostCallRecordEnumeratePhysicalDevices(VkInstance instance, uint32_t* pPhysicalDeviceCount,
2300 VkPhysicalDevice* pPhysicalDevices, VkResult result) {
2301 if ((nullptr != pPhysicalDevices) && ((result == VK_SUCCESS || result == VK_INCOMPLETE))) {
2302 for (uint32_t i = 0; i < *pPhysicalDeviceCount; i++) {
2303 phys_device_bp_state_map.emplace(pPhysicalDevices[i], PHYSICAL_DEVICE_STATE_BP{});
2304 }
2305 }
2306}
2307
2308void BestPractices::ManualPostCallRecordCreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo*, const VkAllocationCallbacks*,
2309 VkDevice*, VkResult result) {
2310 if (VK_SUCCESS == result) {
2311 instance_device_bp_state = &phys_device_bp_state_map[gpu];
2312 }
2313}
2314
2315PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP(const VkPhysicalDevice& phys_device) {
2316 if (phys_device_bp_state_map.count(phys_device) > 0) {
2317 return &phys_device_bp_state_map.at(phys_device);
2318 } else {
2319 return nullptr;
2320 }
2321}
2322
2323const PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP(const VkPhysicalDevice& phys_device) const {
2324 if (phys_device_bp_state_map.count(phys_device) > 0) {
2325 return &phys_device_bp_state_map.at(phys_device);
2326 } else {
2327 return nullptr;
2328 }
2329}
2330
2331PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP() {
2332 auto bp_state = (reinterpret_cast<BestPractices*>(instance_state))->instance_device_bp_state;
2333 if (bp_state) {
2334 return bp_state;
2335 } else if (!bp_state && phys_device_bp_state_map.count(physical_device_state->phys_device) > 0) {
2336 return &phys_device_bp_state_map.at(physical_device_state->phys_device);
2337 } else {
2338 return nullptr;
2339 }
2340}
2341
2342const PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP() const {
2343 auto bp_state = (reinterpret_cast<BestPractices*>(instance_state))->instance_device_bp_state;
2344 if (bp_state) {
2345 return bp_state;
2346 } else if (!bp_state && phys_device_bp_state_map.count(physical_device_state->phys_device) > 0) {
2347 return &phys_device_bp_state_map.at(physical_device_state->phys_device);
2348 } else {
2349 return nullptr;
2350 }
2351}