blob: b32ddad3005b5b48558e5866ea25620c3df78666 [file] [log] [blame]
Gareth Webbdc6549a2021-06-16 03:52:24 +01001/* Copyright (c) 2015-2021 The Khronos Group Inc.
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002 * Copyright (c) 2015-2021 Valve Corporation
3 * Copyright (c) 2015-2021 LunarG, Inc.
Camdeneaa86ea2019-07-26 11:00:09 -06004 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 * Author: Camden Stocker <camden@lunarg.com>
18 */
19
Mark Lobodzinski57b8ae82020-02-20 16:37:14 -070020#include "best_practices_validation.h"
Camden5b184be2019-08-13 07:50:19 -060021#include "layer_chassis_dispatch.h"
Camden Stocker0a660ce2019-08-27 15:30:40 -060022#include "best_practices_error_enums.h"
Sam Wallsd7ab6db2020-06-19 20:41:54 +010023#include "shader_validation.h"
Jeremy Gebbena3705f42021-01-19 16:47:43 -070024#include "sync_utils.h"
Jeremy Gebben159b3cc2021-06-03 09:09:03 -060025#include "cmd_buffer_state.h"
26#include "device_state.h"
27#include "render_pass_state.h"
Camden5b184be2019-08-13 07:50:19 -060028
29#include <string>
Sam Walls8e77e4f2020-03-16 20:47:40 +000030#include <bitset>
Sam Wallsd7ab6db2020-06-19 20:41:54 +010031#include <memory>
Camden5b184be2019-08-13 07:50:19 -060032
Attilio Provenzano19d6a982020-02-27 12:41:41 +000033struct VendorSpecificInfo {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060034 EnableFlags vendor_id;
Attilio Provenzano19d6a982020-02-27 12:41:41 +000035 std::string name;
36};
37
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -070038const std::map<BPVendorFlagBits, VendorSpecificInfo> kVendorInfo = {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060039 {kBPVendorArm, {vendor_specific_arm, "Arm"}},
Attilio Provenzano19d6a982020-02-27 12:41:41 +000040};
41
Hannes Harnisch607d1d92021-07-10 18:44:56 +020042const SpecialUseVUIDs kSpecialUseInstanceVUIDs {
43 kVUID_BestPractices_CreateInstance_SpecialUseExtension_CADSupport,
44 kVUID_BestPractices_CreateInstance_SpecialUseExtension_D3DEmulation,
45 kVUID_BestPractices_CreateInstance_SpecialUseExtension_DevTools,
46 kVUID_BestPractices_CreateInstance_SpecialUseExtension_Debugging,
47 kVUID_BestPractices_CreateInstance_SpecialUseExtension_GLEmulation,
48};
49
50const SpecialUseVUIDs kSpecialUseDeviceVUIDs {
51 kVUID_BestPractices_CreateDevice_SpecialUseExtension_CADSupport,
52 kVUID_BestPractices_CreateDevice_SpecialUseExtension_D3DEmulation,
53 kVUID_BestPractices_CreateDevice_SpecialUseExtension_DevTools,
54 kVUID_BestPractices_CreateDevice_SpecialUseExtension_Debugging,
55 kVUID_BestPractices_CreateDevice_SpecialUseExtension_GLEmulation,
56};
57
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -060058std::shared_ptr<CMD_BUFFER_STATE> BestPractices::CreateCmdBufferState(VkCommandBuffer cb,
59 const VkCommandBufferAllocateInfo* pCreateInfo,
60 std::shared_ptr<COMMAND_POOL_STATE>& pool) {
61 return std::static_pointer_cast<CMD_BUFFER_STATE>(std::make_shared<CMD_BUFFER_STATE_BP>(this, cb, pCreateInfo, pool));
62}
63
64CMD_BUFFER_STATE_BP::CMD_BUFFER_STATE_BP(BestPractices* bp, VkCommandBuffer cb, const VkCommandBufferAllocateInfo* pCreateInfo,
65 std::shared_ptr<COMMAND_POOL_STATE>& pool)
66 : CMD_BUFFER_STATE(bp, cb, pCreateInfo, pool) {}
67
Attilio Provenzano19d6a982020-02-27 12:41:41 +000068bool BestPractices::VendorCheckEnabled(BPVendorFlags vendors) const {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -070069 for (const auto& vendor : kVendorInfo) {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060070 if (vendors & vendor.first && enabled[vendor.second.vendor_id]) {
Attilio Provenzano19d6a982020-02-27 12:41:41 +000071 return true;
72 }
73 }
74 return false;
75}
76
77const char* VendorSpecificTag(BPVendorFlags vendors) {
78 // Cache built vendor tags in a map
Jeremy Gebbencbf22862021-03-03 12:01:22 -070079 static layer_data::unordered_map<BPVendorFlags, std::string> tag_map;
Attilio Provenzano19d6a982020-02-27 12:41:41 +000080
81 auto res = tag_map.find(vendors);
82 if (res == tag_map.end()) {
83 // Build the vendor tag string
84 std::stringstream vendor_tag;
85
86 vendor_tag << "[";
87 bool first_vendor = true;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -070088 for (const auto& vendor : kVendorInfo) {
Attilio Provenzano19d6a982020-02-27 12:41:41 +000089 if (vendors & vendor.first) {
90 if (!first_vendor) {
91 vendor_tag << ", ";
92 }
93 vendor_tag << vendor.second.name;
94 first_vendor = false;
95 }
96 }
97 vendor_tag << "]";
98
99 tag_map[vendors] = vendor_tag.str();
100 res = tag_map.find(vendors);
101 }
102
103 return res->second.c_str();
104}
105
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700106const char* DepReasonToString(ExtDeprecationReason reason) {
107 switch (reason) {
108 case kExtPromoted:
109 return "promoted to";
110 break;
111 case kExtObsoleted:
112 return "obsoleted by";
113 break;
114 case kExtDeprecated:
115 return "deprecated by";
116 break;
117 default:
118 return "";
119 break;
120 }
121}
122
123bool BestPractices::ValidateDeprecatedExtensions(const char* api_name, const char* extension_name, uint32_t version,
124 const char* vuid) const {
125 bool skip = false;
126 auto dep_info_it = deprecated_extensions.find(extension_name);
127 if (dep_info_it != deprecated_extensions.end()) {
128 auto dep_info = dep_info_it->second;
Mark Lobodzinski6a149702020-05-14 12:21:34 -0600129 if (((dep_info.target.compare("VK_VERSION_1_1") == 0) && (version >= VK_API_VERSION_1_1)) ||
130 ((dep_info.target.compare("VK_VERSION_1_2") == 0) && (version >= VK_API_VERSION_1_2))) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700131 skip |=
132 LogWarning(instance, vuid, "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
133 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
Mark Lobodzinski6a149702020-05-14 12:21:34 -0600134 } else if (dep_info.target.find("VK_VERSION") == std::string::npos) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700135 if (dep_info.target.length() == 0) {
136 skip |= LogWarning(instance, vuid,
137 "%s(): Attempting to enable deprecated extension %s, but this extension has been deprecated "
138 "without replacement.",
139 api_name, extension_name);
140 } else {
141 skip |= LogWarning(instance, vuid,
142 "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
143 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
144 }
145 }
146 }
147 return skip;
148}
149
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200150bool BestPractices::ValidateSpecialUseExtensions(const char* api_name, const char* extension_name, const SpecialUseVUIDs& special_use_vuids) const
151{
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700152 bool skip = false;
153 auto dep_info_it = special_use_extensions.find(extension_name);
154
155 if (dep_info_it != special_use_extensions.end()) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200156 const char* const format = "%s(): Attempting to enable extension %s, but this extension is intended to support %s "
157 "and it is strongly recommended that it be otherwise avoided.";
158 auto& special_uses = dep_info_it->second;
159
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700160 if (special_uses.find("cadsupport") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200161 skip |= LogWarning(instance, special_use_vuids.cadsupport, format, api_name, extension_name,
162 "specialized functionality used by CAD/CAM applications");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700163 }
164 if (special_uses.find("d3demulation") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200165 skip |= LogWarning(instance, special_use_vuids.d3demulation, format, api_name, extension_name,
166 "D3D emulation layers, and applications ported from D3D, by adding functionality specific to D3D");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700167 }
168 if (special_uses.find("devtools") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200169 skip |= LogWarning(instance, special_use_vuids.devtools, format, api_name, extension_name,
170 "developer tools such as capture-replay libraries");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700171 }
172 if (special_uses.find("debugging") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200173 skip |= LogWarning(instance, special_use_vuids.debugging, format, api_name, extension_name,
174 "use by applications when debugging");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700175 }
176 if (special_uses.find("glemulation") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200177 skip |= LogWarning(instance, special_use_vuids.glemulation, format, api_name, extension_name,
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700178 "OpenGL and/or OpenGL ES emulation layers, and applications ported from those APIs, by adding functionality "
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200179 "specific to those APIs");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700180 }
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700181 }
182 return skip;
183}
184
Camden5b184be2019-08-13 07:50:19 -0600185bool BestPractices::PreCallValidateCreateInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500186 VkInstance* pInstance) const {
Camden5b184be2019-08-13 07:50:19 -0600187 bool skip = false;
188
189 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
190 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kDeviceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800191 skip |= LogWarning(instance, kVUID_BestPractices_CreateInstance_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700192 "vkCreateInstance(): Attempting to enable Device Extension %s at CreateInstance time.",
193 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600194 }
Mark Lobodzinski17d8dc62020-06-03 08:48:58 -0600195 uint32_t specified_version =
196 (pCreateInfo->pApplicationInfo ? pCreateInfo->pApplicationInfo->apiVersion : VK_API_VERSION_1_0);
197 skip |= ValidateDeprecatedExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i], specified_version,
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700198 kVUID_BestPractices_CreateInstance_DeprecatedExtension);
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200199 skip |= ValidateSpecialUseExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i], kSpecialUseInstanceVUIDs);
Camden5b184be2019-08-13 07:50:19 -0600200 }
201
202 return skip;
203}
204
205void BestPractices::PreCallRecordCreateInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator,
206 VkInstance* pInstance) {
Mark Lobodzinski97484d62020-03-03 11:57:41 -0700207 ValidationStateTracker::PreCallRecordCreateInstance(pCreateInfo, pAllocator, pInstance);
Sam Walls53bf7652020-04-21 17:35:15 +0100208
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700209 if (pCreateInfo != nullptr && pCreateInfo->pApplicationInfo != nullptr) {
Sam Walls53bf7652020-04-21 17:35:15 +0100210 instance_api_version = pCreateInfo->pApplicationInfo->apiVersion;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700211 } else {
Sam Walls53bf7652020-04-21 17:35:15 +0100212 instance_api_version = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700213 }
Camden5b184be2019-08-13 07:50:19 -0600214}
215
216bool BestPractices::PreCallValidateCreateDevice(VkPhysicalDevice physicalDevice, const VkDeviceCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500217 const VkAllocationCallbacks* pAllocator, VkDevice* pDevice) const {
Camden5b184be2019-08-13 07:50:19 -0600218 bool skip = false;
219
220 // get API version of physical device passed when creating device.
221 VkPhysicalDeviceProperties physical_device_properties{};
222 DispatchGetPhysicalDeviceProperties(physicalDevice, &physical_device_properties);
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500223 auto device_api_version = physical_device_properties.apiVersion;
Camden5b184be2019-08-13 07:50:19 -0600224
225 // check api versions and warn if instance api Version is higher than version on device.
226 if (instance_api_version > device_api_version) {
Mark Lobodzinski60880782020-08-11 08:02:07 -0600227 std::string inst_api_name = StringAPIVersion(instance_api_version);
228 std::string dev_api_name = StringAPIVersion(device_api_version);
Camden5b184be2019-08-13 07:50:19 -0600229
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700230 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_API_Mismatch,
231 "vkCreateDevice(): API Version of current instance, %s is higher than API Version on device, %s",
232 inst_api_name.c_str(), dev_api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -0600233 }
234
235 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
236 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kInstanceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800237 skip |= LogWarning(instance, kVUID_BestPractices_CreateDevice_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700238 "vkCreateDevice(): Attempting to enable Instance Extension %s at CreateDevice time.",
239 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600240 }
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700241 skip |= ValidateDeprecatedExtensions("CreateDevice", pCreateInfo->ppEnabledExtensionNames[i], instance_api_version,
242 kVUID_BestPractices_CreateDevice_DeprecatedExtension);
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200243 skip |= ValidateSpecialUseExtensions("CreateDevice", pCreateInfo->ppEnabledExtensionNames[i], kSpecialUseDeviceVUIDs);
Camden5b184be2019-08-13 07:50:19 -0600244 }
245
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600246 const auto bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
247 if ((bp_pd_state->vkGetPhysicalDeviceFeaturesState == UNCALLED) && (pCreateInfo->pEnabledFeatures != NULL)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700248 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_PDFeaturesNotCalled,
249 "vkCreateDevice() called before getting physical device features from vkGetPhysicalDeviceFeatures().");
Camden83a9c372019-08-14 11:41:38 -0600250 }
251
Szilard Papp7d2c7952020-06-22 14:38:13 +0100252 if ((VendorCheckEnabled(kBPVendorArm)) && (pCreateInfo->pEnabledFeatures != nullptr) &&
253 (pCreateInfo->pEnabledFeatures->robustBufferAccess == VK_TRUE)) {
254 skip |= LogPerformanceWarning(
255 device, kVUID_BestPractices_CreateDevice_RobustBufferAccess,
256 "%s vkCreateDevice() called with enabled robustBufferAccess. Use robustBufferAccess as a debugging tool during "
257 "development. Enabling it causes loss in performance for accesses to uniform buffers and shader storage "
258 "buffers. Disable robustBufferAccess in release builds. Only leave it enabled if the application use-case "
259 "requires the additional level of reliability due to the use of unverified user-supplied draw parameters.",
260 VendorSpecificTag(kBPVendorArm));
261 }
262
Camden5b184be2019-08-13 07:50:19 -0600263 return skip;
264}
265
266bool BestPractices::PreCallValidateCreateBuffer(VkDevice device, const VkBufferCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500267 const VkAllocationCallbacks* pAllocator, VkBuffer* pBuffer) const {
Camden5b184be2019-08-13 07:50:19 -0600268 bool skip = false;
269
270 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700271 std::stringstream buffer_hex;
272 buffer_hex << "0x" << std::hex << HandleToUint64(pBuffer);
Camden5b184be2019-08-13 07:50:19 -0600273
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700274 skip |= LogWarning(
275 device, kVUID_BestPractices_SharingModeExclusive,
276 "Warning: Buffer (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
277 "(queueFamilyIndexCount of %" PRIu32 ").",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700278 buffer_hex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600279 }
280
281 return skip;
282}
283
284bool BestPractices::PreCallValidateCreateImage(VkDevice device, const VkImageCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500285 const VkAllocationCallbacks* pAllocator, VkImage* pImage) const {
Camden5b184be2019-08-13 07:50:19 -0600286 bool skip = false;
287
288 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700289 std::stringstream image_hex;
290 image_hex << "0x" << std::hex << HandleToUint64(pImage);
Camden5b184be2019-08-13 07:50:19 -0600291
292 skip |=
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700293 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
294 "Warning: Image (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
295 "(queueFamilyIndexCount of %" PRIu32 ").",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700296 image_hex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600297 }
298
Attilio Provenzano02859b22020-02-27 14:17:28 +0000299 if (VendorCheckEnabled(kBPVendorArm)) {
300 if (pCreateInfo->samples > kMaxEfficientSamplesArm) {
301 skip |= LogPerformanceWarning(
302 device, kVUID_BestPractices_CreateImage_TooLargeSampleCount,
303 "%s vkCreateImage(): Trying to create an image with %u samples. "
304 "The hardware revision may not have full throughput for framebuffers with more than %u samples.",
305 VendorSpecificTag(kBPVendorArm), static_cast<uint32_t>(pCreateInfo->samples), kMaxEfficientSamplesArm);
306 }
307
308 if (pCreateInfo->samples > VK_SAMPLE_COUNT_1_BIT && !(pCreateInfo->usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT)) {
309 skip |= LogPerformanceWarning(
310 device, kVUID_BestPractices_CreateImage_NonTransientMSImage,
311 "%s vkCreateImage(): Trying to create a multisampled image, but createInfo.usage did not have "
312 "VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. Multisampled images may be resolved on-chip, "
313 "and do not need to be backed by physical storage. "
314 "TRANSIENT_ATTACHMENT allows tiled GPUs to not back the multisampled image with physical memory.",
315 VendorSpecificTag(kBPVendorArm));
316 }
317 }
318
Camden5b184be2019-08-13 07:50:19 -0600319 return skip;
320}
321
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +0100322void BestPractices::PreCallRecordDestroyImage(VkDevice device, VkImage image, const VkAllocationCallbacks *pAllocator) {
323 ValidationStateTracker::PreCallRecordDestroyImage(device, image, pAllocator);
324 ReleaseImageUsageState(image);
325}
326
Hans-Kristian Arntzen92664eb2021-03-29 12:19:48 +0200327void BestPractices::PreCallRecordDestroySwapchainKHR(VkDevice device, VkSwapchainKHR swapchain, const VkAllocationCallbacks* pAllocator) {
Tony-LunarG299187b2021-05-28 09:29:12 -0600328 if (VK_NULL_HANDLE != swapchain) {
329 SWAPCHAIN_NODE* chain = GetSwapchainState(swapchain);
330 for (auto& image : chain->images) {
331 if (image.image_state) {
332 ReleaseImageUsageState(image.image_state->image());
333 }
334 }
Hans-Kristian Arntzen92664eb2021-03-29 12:19:48 +0200335 }
336 ValidationStateTracker::PreCallRecordDestroySwapchainKHR(device, swapchain, pAllocator);
337}
338
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +0100339IMAGE_STATE_BP* BestPractices::GetImageUsageState(VkImage vk_image) {
340 auto itr = imageUsageMap.find(vk_image);
341 if (itr != imageUsageMap.end()) {
342 return &itr->second;
343 } else {
344 auto& state = imageUsageMap[vk_image];
345 IMAGE_STATE* image = GetImageState(vk_image);
346 state.image = image;
347 state.usages.resize(image->createInfo.arrayLayers);
348 for (auto& mips : state.usages) {
349 mips.resize(image->createInfo.mipLevels, IMAGE_SUBRESOURCE_USAGE_BP::UNDEFINED);
350 }
351 return &state;
352 }
353}
354
355void BestPractices::ReleaseImageUsageState(VkImage image) {
356 auto itr = imageUsageMap.find(image);
357 if (itr != imageUsageMap.end()) {
358 imageUsageMap.erase(itr);
359 }
360}
361
Camden5b184be2019-08-13 07:50:19 -0600362bool BestPractices::PreCallValidateCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500363 const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain) const {
Camden5b184be2019-08-13 07:50:19 -0600364 bool skip = false;
365
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600366 const auto* bp_pd_state = GetPhysicalDeviceStateBP();
367 if (bp_pd_state) {
368 if (bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState == UNCALLED) {
369 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
370 "vkCreateSwapchainKHR() called before getting surface capabilities from "
371 "vkGetPhysicalDeviceSurfaceCapabilitiesKHR().");
372 }
Camden83a9c372019-08-14 11:41:38 -0600373
Shannon McPherson73e58c82021-03-05 17:14:26 -0700374 if ((pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR) &&
375 (bp_pd_state->vkGetPhysicalDeviceSurfacePresentModesKHRState != QUERY_DETAILS)) {
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600376 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
377 "vkCreateSwapchainKHR() called before getting surface present mode(s) from "
378 "vkGetPhysicalDeviceSurfacePresentModesKHR().");
379 }
Camden83a9c372019-08-14 11:41:38 -0600380
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600381 if (bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState != QUERY_DETAILS) {
382 skip |= LogWarning(
383 device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
384 "vkCreateSwapchainKHR() called before getting surface format(s) from vkGetPhysicalDeviceSurfaceFormatsKHR().");
385 }
Camden83a9c372019-08-14 11:41:38 -0600386 }
387
Camden5b184be2019-08-13 07:50:19 -0600388 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700389 skip |=
390 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
Mark Lobodzinski019f4e32020-04-13 11:01:35 -0600391 "Warning: A Swapchain is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while "
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700392 "specifying multiple queues (queueFamilyIndexCount of %" PRIu32 ").",
393 pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600394 }
395
Szilard Papp48a6da32020-06-10 14:41:59 +0100396 if (pCreateInfo->minImageCount == 2) {
397 skip |= LogPerformanceWarning(
398 device, kVUID_BestPractices_SuboptimalSwapchainImageCount,
399 "Warning: A Swapchain is being created with minImageCount set to %" PRIu32
400 ", which means double buffering is going "
401 "to be used. Using double buffering and vsync locks rendering to an integer fraction of the vsync rate. In turn, "
402 "reducing the performance of the application if rendering is slower than vsync. Consider setting minImageCount to "
403 "3 to use triple buffering to maximize performance in such cases.",
404 pCreateInfo->minImageCount);
405 }
406
Szilard Pappd5f0f812020-06-22 09:01:29 +0100407 if (VendorCheckEnabled(kBPVendorArm) && (pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR)) {
408 skip |= LogWarning(device, kVUID_BestPractices_CreateSwapchain_PresentMode,
409 "%s Warning: Swapchain is not being created with presentation mode \"VK_PRESENT_MODE_FIFO_KHR\". "
410 "Prefer using \"VK_PRESENT_MODE_FIFO_KHR\" to avoid unnecessary CPU and GPU load and save power. "
411 "Presentation modes which are not FIFO will present the latest available frame and discard other "
412 "frame(s) if any.",
413 VendorSpecificTag(kBPVendorArm));
414 }
415
Camden5b184be2019-08-13 07:50:19 -0600416 return skip;
417}
418
419bool BestPractices::PreCallValidateCreateSharedSwapchainsKHR(VkDevice device, uint32_t swapchainCount,
420 const VkSwapchainCreateInfoKHR* pCreateInfos,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500421 const VkAllocationCallbacks* pAllocator,
422 VkSwapchainKHR* pSwapchains) const {
Camden5b184be2019-08-13 07:50:19 -0600423 bool skip = false;
424
425 for (uint32_t i = 0; i < swapchainCount; i++) {
426 if ((pCreateInfos[i].queueFamilyIndexCount > 1) && (pCreateInfos[i].imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700427 skip |= LogWarning(
428 device, kVUID_BestPractices_SharingModeExclusive,
429 "Warning: A shared swapchain (index %" PRIu32
430 ") is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple "
431 "queues (queueFamilyIndexCount of %" PRIu32 ").",
432 i, pCreateInfos[i].queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600433 }
434 }
435
436 return skip;
437}
438
439bool BestPractices::PreCallValidateCreateRenderPass(VkDevice device, const VkRenderPassCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500440 const VkAllocationCallbacks* pAllocator, VkRenderPass* pRenderPass) const {
Camden5b184be2019-08-13 07:50:19 -0600441 bool skip = false;
442
443 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; ++i) {
444 VkFormat format = pCreateInfo->pAttachments[i].format;
445 if (pCreateInfo->pAttachments[i].initialLayout == VK_IMAGE_LAYOUT_UNDEFINED) {
446 if ((FormatIsColor(format) || FormatHasDepth(format)) &&
447 pCreateInfo->pAttachments[i].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700448 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
449 "Render pass has an attachment with loadOp == VK_ATTACHMENT_LOAD_OP_LOAD and "
450 "initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
451 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
452 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600453 }
454 if (FormatHasStencil(format) && pCreateInfo->pAttachments[i].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700455 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
456 "Render pass has an attachment with stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD "
457 "and initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
458 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
459 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600460 }
461 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000462
463 const auto& attachment = pCreateInfo->pAttachments[i];
464 if (attachment.samples > VK_SAMPLE_COUNT_1_BIT) {
465 bool access_requires_memory =
466 attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD || attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE;
467
468 if (FormatHasStencil(format)) {
469 access_requires_memory |= attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
470 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE;
471 }
472
473 if (access_requires_memory) {
474 skip |= LogPerformanceWarning(
475 device, kVUID_BestPractices_CreateRenderPass_ImageRequiresMemory,
476 "Attachment %u in the VkRenderPass is a multisampled image with %u samples, but it uses loadOp/storeOp "
477 "which requires accessing data from memory. Multisampled images should always be loadOp = CLEAR or DONT_CARE, "
478 "storeOp = DONT_CARE. This allows the implementation to use lazily allocated memory effectively.",
479 i, static_cast<uint32_t>(attachment.samples));
480 }
481 }
Camden5b184be2019-08-13 07:50:19 -0600482 }
483
484 for (uint32_t dependency = 0; dependency < pCreateInfo->dependencyCount; dependency++) {
485 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].srcStageMask);
486 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].dstStageMask);
487 }
488
489 return skip;
490}
491
Tony-LunarG767180f2020-04-23 14:03:59 -0600492bool BestPractices::ValidateAttachments(const VkRenderPassCreateInfo2* rpci, uint32_t attachmentCount,
493 const VkImageView* image_views) const {
494 bool skip = false;
495
496 // Check for non-transient attachments that should be transient and vice versa
497 for (uint32_t i = 0; i < attachmentCount; ++i) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200498 const auto& attachment = rpci->pAttachments[i];
Tony-LunarG767180f2020-04-23 14:03:59 -0600499 bool attachment_should_be_transient =
500 (attachment.loadOp != VK_ATTACHMENT_LOAD_OP_LOAD && attachment.storeOp != VK_ATTACHMENT_STORE_OP_STORE);
501
502 if (FormatHasStencil(attachment.format)) {
503 attachment_should_be_transient &= (attachment.stencilLoadOp != VK_ATTACHMENT_LOAD_OP_LOAD &&
504 attachment.stencilStoreOp != VK_ATTACHMENT_STORE_OP_STORE);
505 }
506
507 auto view_state = GetImageViewState(image_views[i]);
508 if (view_state) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200509 const auto& ivci = view_state->create_info;
510 const auto& ici = GetImageState(ivci.image)->createInfo;
Tony-LunarG767180f2020-04-23 14:03:59 -0600511
512 bool image_is_transient = (ici.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) != 0;
513
514 // The check for an image that should not be transient applies to all GPUs
515 if (!attachment_should_be_transient && image_is_transient) {
516 skip |= LogPerformanceWarning(
517 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldNotBeTransient,
518 "Attachment %u in VkFramebuffer uses loadOp/storeOps which need to access physical memory, "
519 "but the image backing the image view has VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
520 "Physical memory will need to be backed lazily to this image, potentially causing stalls.",
521 i);
522 }
523
524 bool supports_lazy = false;
525 for (uint32_t j = 0; j < phys_dev_mem_props.memoryTypeCount; j++) {
526 if (phys_dev_mem_props.memoryTypes[j].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
527 supports_lazy = true;
528 }
529 }
530
531 // The check for an image that should be transient only applies to GPUs supporting
532 // lazily allocated memory
533 if (supports_lazy && attachment_should_be_transient && !image_is_transient) {
534 skip |= LogPerformanceWarning(
535 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldBeTransient,
536 "Attachment %u in VkFramebuffer uses loadOp/storeOps which never have to be backed by physical memory, "
537 "but the image backing the image view does not have VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
538 "You can save physical memory by using transient attachment backed by lazily allocated memory here.",
539 i);
540 }
541 }
542 }
543 return skip;
544}
545
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000546bool BestPractices::PreCallValidateCreateFramebuffer(VkDevice device, const VkFramebufferCreateInfo* pCreateInfo,
547 const VkAllocationCallbacks* pAllocator, VkFramebuffer* pFramebuffer) const {
548 bool skip = false;
549
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000550 auto rp_state = GetRenderPassState(pCreateInfo->renderPass);
Mike Schuchardt2df08912020-12-15 16:28:09 -0800551 if (rp_state && !(pCreateInfo->flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT)) {
Tony-LunarG767180f2020-04-23 14:03:59 -0600552 skip = ValidateAttachments(rp_state->createInfo.ptr(), pCreateInfo->attachmentCount, pCreateInfo->pAttachments);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000553 }
554
555 return skip;
556}
557
Sam Wallse746d522020-03-16 21:20:23 +0000558bool BestPractices::PreCallValidateAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
559 VkDescriptorSet* pDescriptorSets, void* ads_state_data) const {
560 bool skip = false;
561 skip |= ValidationStateTracker::PreCallValidateAllocateDescriptorSets(device, pAllocateInfo, pDescriptorSets, ads_state_data);
562
563 if (!skip) {
564 const auto& pool_handle = pAllocateInfo->descriptorPool;
565 auto iter = descriptor_pool_freed_count.find(pool_handle);
566 // if the number of freed sets > 0, it implies they could be recycled instead if desirable
567 // this warning is specific to Arm
568 if (VendorCheckEnabled(kBPVendorArm) && iter != descriptor_pool_freed_count.end() && iter->second > 0) {
569 skip |= LogPerformanceWarning(
570 device, kVUID_BestPractices_AllocateDescriptorSets_SuboptimalReuse,
571 "%s Descriptor set memory was allocated via vkAllocateDescriptorSets() for sets which were previously freed in the "
572 "same logical device. On some drivers or architectures it may be most optimal to re-use existing descriptor sets.",
573 VendorSpecificTag(kBPVendorArm));
574 }
575 }
576
577 return skip;
578}
579
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600580void BestPractices::ManualPostCallRecordAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
581 VkDescriptorSet* pDescriptorSets, VkResult result, void* ads_state) {
Sam Wallse746d522020-03-16 21:20:23 +0000582 if (result == VK_SUCCESS) {
583 // find the free count for the pool we allocated into
584 auto iter = descriptor_pool_freed_count.find(pAllocateInfo->descriptorPool);
585 if (iter != descriptor_pool_freed_count.end()) {
586 // we record successful allocations by subtracting the allocation count from the last recorded free count
587 const auto alloc_count = pAllocateInfo->descriptorSetCount;
588 // clamp the unsigned subtraction to the range [0, last_free_count]
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700589 if (iter->second > alloc_count) {
Sam Wallse746d522020-03-16 21:20:23 +0000590 iter->second -= alloc_count;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700591 } else {
Sam Wallse746d522020-03-16 21:20:23 +0000592 iter->second = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700593 }
Sam Wallse746d522020-03-16 21:20:23 +0000594 }
595 }
596}
597
598void BestPractices::PostCallRecordFreeDescriptorSets(VkDevice device, VkDescriptorPool descriptorPool, uint32_t descriptorSetCount,
599 const VkDescriptorSet* pDescriptorSets, VkResult result) {
600 ValidationStateTracker::PostCallRecordFreeDescriptorSets(device, descriptorPool, descriptorSetCount, pDescriptorSets, result);
601 if (result == VK_SUCCESS) {
602 // we want to track frees because we're interested in suggesting re-use
603 auto iter = descriptor_pool_freed_count.find(descriptorPool);
604 if (iter == descriptor_pool_freed_count.end()) {
Jeremy Gebbencbf22862021-03-03 12:01:22 -0700605 descriptor_pool_freed_count.emplace(descriptorPool, descriptorSetCount);
Sam Wallse746d522020-03-16 21:20:23 +0000606 } else {
607 iter->second += descriptorSetCount;
608 }
609 }
610}
611
Camden5b184be2019-08-13 07:50:19 -0600612bool BestPractices::PreCallValidateAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500613 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory) const {
Camden5b184be2019-08-13 07:50:19 -0600614 bool skip = false;
615
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500616 if (num_mem_objects + 1 > kMemoryObjectWarningLimit) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700617 skip |= LogPerformanceWarning(device, kVUID_BestPractices_AllocateMemory_TooManyObjects,
618 "Performance Warning: This app has > %" PRIu32 " memory objects.", kMemoryObjectWarningLimit);
Camden5b184be2019-08-13 07:50:19 -0600619 }
620
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000621 if (pAllocateInfo->allocationSize < kMinDeviceAllocationSize) {
622 skip |= LogPerformanceWarning(
623 device, kVUID_BestPractices_AllocateMemory_SmallAllocation,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600624 "vkAllocateMemory(): Allocating a VkDeviceMemory of size %" PRIu64 ". This is a very small allocation (current "
625 "threshold is %" PRIu64 " bytes). "
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000626 "You should make large allocations and sub-allocate from one large VkDeviceMemory.",
627 pAllocateInfo->allocationSize, kMinDeviceAllocationSize);
628 }
629
Camden83a9c372019-08-14 11:41:38 -0600630 // TODO: Insert get check for GetPhysicalDeviceMemoryProperties once the state is tracked in the StateTracker
631
632 return skip;
633}
634
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600635void BestPractices::ManualPostCallRecordAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
636 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory,
637 VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700638 if (result != VK_SUCCESS) {
639 static std::vector<VkResult> error_codes = {VK_ERROR_OUT_OF_HOST_MEMORY, VK_ERROR_OUT_OF_DEVICE_MEMORY,
640 VK_ERROR_TOO_MANY_OBJECTS, VK_ERROR_INVALID_EXTERNAL_HANDLE,
Mike Schuchardt2df08912020-12-15 16:28:09 -0800641 VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS};
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700642 static std::vector<VkResult> success_codes = {};
Nathaniel Cesariodb3f43f2021-05-12 09:08:23 -0600643 ValidateReturnCodes("vkAllocateMemory", result, error_codes, success_codes);
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700644 return;
645 }
646 num_mem_objects++;
647}
Camden Stocker9738af92019-10-16 13:54:03 -0700648
Mark Lobodzinskide15e582020-04-29 08:06:00 -0600649void BestPractices::ValidateReturnCodes(const char* api_name, VkResult result, const std::vector<VkResult>& error_codes,
650 const std::vector<VkResult>& success_codes) const {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700651 auto error = std::find(error_codes.begin(), error_codes.end(), result);
652 if (error != error_codes.end()) {
Gareth Webb586c46b2021-01-13 11:17:22 +0000653 static const std::vector<VkResult> common_failure_codes = {VK_ERROR_OUT_OF_DATE_KHR,
654 VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT};
655
656 auto common_failure = std::find(common_failure_codes.begin(), common_failure_codes.end(), result);
657 if (common_failure != common_failure_codes.end()) {
658 LogInfo(instance, kVUID_BestPractices_Failure_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
659 } else {
660 LogWarning(instance, kVUID_BestPractices_Error_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
661 }
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700662 return;
663 }
664 auto success = std::find(success_codes.begin(), success_codes.end(), result);
665 if (success != success_codes.end()) {
Mark Lobodzinskie7215152020-05-11 08:21:23 -0600666 LogInfo(instance, kVUID_BestPractices_NonSuccess_Result, "%s(): Returned non-success return code %s.", api_name,
667 string_VkResult(result));
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500668 }
669}
670
Jeff Bolz5c801d12019-10-09 10:38:45 -0500671bool BestPractices::PreCallValidateFreeMemory(VkDevice device, VkDeviceMemory memory,
672 const VkAllocationCallbacks* pAllocator) const {
Mark Lobodzinski91e50bf2020-01-14 09:55:11 -0700673 if (memory == VK_NULL_HANDLE) return false;
Camden83a9c372019-08-14 11:41:38 -0600674 bool skip = false;
675
Camden Stocker9738af92019-10-16 13:54:03 -0700676 const DEVICE_MEMORY_STATE* mem_info = ValidationStateTracker::GetDevMemState(memory);
Camden83a9c372019-08-14 11:41:38 -0600677
Jeremy Gebben5570abe2021-05-16 18:35:13 -0600678 for (const auto& node: mem_info->ObjectBindings()) {
679 const auto& obj = node->Handle();
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600680 LogObjectList objlist(device);
681 objlist.add(obj);
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -0600682 objlist.add(mem_info->mem());
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600683 skip |= LogWarning(objlist, layer_name.c_str(), "VK Object %s still has a reference to mem obj %s.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -0600684 report_data->FormatHandle(obj).c_str(), report_data->FormatHandle(mem_info->mem()).c_str());
Camden83a9c372019-08-14 11:41:38 -0600685 }
686
Camden5b184be2019-08-13 07:50:19 -0600687 return skip;
688}
689
690void BestPractices::PreCallRecordFreeMemory(VkDevice device, VkDeviceMemory memory, const VkAllocationCallbacks* pAllocator) {
Mark Lobodzinski97484d62020-03-03 11:57:41 -0700691 ValidationStateTracker::PreCallRecordFreeMemory(device, memory, pAllocator);
Camden5b184be2019-08-13 07:50:19 -0600692 if (memory != VK_NULL_HANDLE) {
693 num_mem_objects--;
694 }
695}
696
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000697bool BestPractices::ValidateBindBufferMemory(VkBuffer buffer, VkDeviceMemory memory, const char* api_name) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600698 bool skip = false;
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500699 const BUFFER_STATE* buffer_state = GetBufferState(buffer);
Camden Stockerb603cc82019-09-03 10:09:02 -0600700
sfricke-samsunge2441192019-11-06 14:07:57 -0800701 if (!buffer_state->memory_requirements_checked && !buffer_state->external_memory_handle) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700702 skip |= LogWarning(device, kVUID_BestPractices_BufferMemReqNotCalled,
703 "%s: Binding memory to %s but vkGetBufferMemoryRequirements() has not been called on that buffer.",
704 api_name, report_data->FormatHandle(buffer).c_str());
Camden Stockerb603cc82019-09-03 10:09:02 -0600705 }
706
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000707 const DEVICE_MEMORY_STATE* mem_state = GetDevMemState(memory);
708
709 if (mem_state->alloc_info.allocationSize == buffer_state->createInfo.size &&
710 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
711 skip |= LogPerformanceWarning(
712 device, kVUID_BestPractices_SmallDedicatedAllocation,
713 "%s: Trying to bind %s to a memory block which is fully consumed by the buffer. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600714 "The required size of the allocation is %" PRIu64 ", but smaller buffers like this should be sub-allocated from "
715 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000716 api_name, report_data->FormatHandle(buffer).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
717 }
718
Camden Stockerb603cc82019-09-03 10:09:02 -0600719 return skip;
720}
721
722bool BestPractices::PreCallValidateBindBufferMemory(VkDevice device, VkBuffer buffer, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500723 VkDeviceSize memoryOffset) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600724 bool skip = false;
725 const char* api_name = "BindBufferMemory()";
726
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000727 skip |= ValidateBindBufferMemory(buffer, memory, api_name);
Camden Stockerb603cc82019-09-03 10:09:02 -0600728
729 return skip;
730}
731
732bool BestPractices::PreCallValidateBindBufferMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500733 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600734 char api_name[64];
735 bool skip = false;
736
737 for (uint32_t i = 0; i < bindInfoCount; i++) {
738 sprintf(api_name, "vkBindBufferMemory2() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000739 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600740 }
741
742 return skip;
743}
Camden Stockerb603cc82019-09-03 10:09:02 -0600744
745bool BestPractices::PreCallValidateBindBufferMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500746 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600747 char api_name[64];
748 bool skip = false;
Camden Stockerb603cc82019-09-03 10:09:02 -0600749
Camden Stocker8b798ab2019-09-03 10:33:28 -0600750 for (uint32_t i = 0; i < bindInfoCount; i++) {
751 sprintf(api_name, "vkBindBufferMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000752 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600753 }
754
755 return skip;
756}
757
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000758bool BestPractices::ValidateBindImageMemory(VkImage image, VkDeviceMemory memory, const char* api_name) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600759 bool skip = false;
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500760 const IMAGE_STATE* image_state = GetImageState(image);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600761
sfricke-samsung71bc6572020-04-29 15:49:43 -0700762 if (image_state->disjoint == false) {
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600763 if (!image_state->memory_requirements_checked[0] && !image_state->external_memory_handle) {
sfricke-samsungd7ea5de2020-04-08 09:19:18 -0700764 skip |= LogWarning(device, kVUID_BestPractices_ImageMemReqNotCalled,
765 "%s: Binding memory to %s but vkGetImageMemoryRequirements() has not been called on that image.",
766 api_name, report_data->FormatHandle(image).c_str());
767 }
768 } else {
769 // TODO If binding disjoint image then this needs to check that VkImagePlaneMemoryRequirementsInfo was called for each
770 // plane.
Camden Stocker8b798ab2019-09-03 10:33:28 -0600771 }
772
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000773 const DEVICE_MEMORY_STATE* mem_state = GetDevMemState(memory);
774
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600775 if (mem_state->alloc_info.allocationSize == image_state->requirements[0].size &&
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000776 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
777 skip |= LogPerformanceWarning(
778 device, kVUID_BestPractices_SmallDedicatedAllocation,
779 "%s: Trying to bind %s to a memory block which is fully consumed by the image. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600780 "The required size of the allocation is %" PRIu64 ", but smaller images like this should be sub-allocated from "
781 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000782 api_name, report_data->FormatHandle(image).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
783 }
784
785 // If we're binding memory to a image which was created as TRANSIENT and the image supports LAZY allocation,
786 // make sure this type is actually used.
787 // This warning will only trigger if this layer is run on a platform that supports LAZILY_ALLOCATED_BIT
788 // (i.e.most tile - based renderers)
789 if (image_state->createInfo.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) {
790 bool supports_lazy = false;
791 uint32_t suggested_type = 0;
792
793 for (uint32_t i = 0; i < phys_dev_mem_props.memoryTypeCount; i++) {
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600794 if ((1u << i) & image_state->requirements[0].memoryTypeBits) {
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000795 if (phys_dev_mem_props.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
796 supports_lazy = true;
797 suggested_type = i;
798 break;
799 }
800 }
801 }
802
803 uint32_t allocated_properties = phys_dev_mem_props.memoryTypes[mem_state->alloc_info.memoryTypeIndex].propertyFlags;
804
805 if (supports_lazy && (allocated_properties & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) == 0) {
806 skip |= LogPerformanceWarning(
807 device, kVUID_BestPractices_NonLazyTransientImage,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600808 "%s: Attempting to bind memory type %u to VkImage which was created with TRANSIENT_ATTACHMENT_BIT,"
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000809 "but this memory type is not LAZILY_ALLOCATED_BIT. You should use memory type %u here instead to save "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600810 "%" PRIu64 " bytes of physical memory.",
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600811 api_name, mem_state->alloc_info.memoryTypeIndex, suggested_type, image_state->requirements[0].size);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000812 }
813 }
814
Camden Stocker8b798ab2019-09-03 10:33:28 -0600815 return skip;
816}
817
818bool BestPractices::PreCallValidateBindImageMemory(VkDevice device, VkImage image, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500819 VkDeviceSize memoryOffset) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600820 bool skip = false;
821 const char* api_name = "vkBindImageMemory()";
822
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000823 skip |= ValidateBindImageMemory(image, memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600824
825 return skip;
826}
827
828bool BestPractices::PreCallValidateBindImageMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500829 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600830 char api_name[64];
831 bool skip = false;
832
833 for (uint32_t i = 0; i < bindInfoCount; i++) {
834 sprintf(api_name, "vkBindImageMemory2() pBindInfos[%u]", i);
Mark Lobodzinski1f887d32020-12-30 15:31:33 -0700835 if (!LvlFindInChain<VkBindImageMemorySwapchainInfoKHR>(pBindInfos[i].pNext)) {
Tony-LunarG5e60b852020-04-27 11:27:54 -0600836 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
837 }
Camden Stocker8b798ab2019-09-03 10:33:28 -0600838 }
839
840 return skip;
841}
842
843bool BestPractices::PreCallValidateBindImageMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500844 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600845 char api_name[64];
846 bool skip = false;
847
848 for (uint32_t i = 0; i < bindInfoCount; i++) {
849 sprintf(api_name, "vkBindImageMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000850 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600851 }
852
853 return skip;
854}
Camden83a9c372019-08-14 11:41:38 -0600855
Attilio Provenzano02859b22020-02-27 14:17:28 +0000856static inline bool FormatHasFullThroughputBlendingArm(VkFormat format) {
857 switch (format) {
858 case VK_FORMAT_B10G11R11_UFLOAT_PACK32:
859 case VK_FORMAT_R16_SFLOAT:
860 case VK_FORMAT_R16G16_SFLOAT:
861 case VK_FORMAT_R16G16B16_SFLOAT:
862 case VK_FORMAT_R16G16B16A16_SFLOAT:
863 case VK_FORMAT_R32_SFLOAT:
864 case VK_FORMAT_R32G32_SFLOAT:
865 case VK_FORMAT_R32G32B32_SFLOAT:
866 case VK_FORMAT_R32G32B32A32_SFLOAT:
867 return false;
868
869 default:
870 return true;
871 }
872}
873
874bool BestPractices::ValidateMultisampledBlendingArm(uint32_t createInfoCount,
875 const VkGraphicsPipelineCreateInfo* pCreateInfos) const {
876 bool skip = false;
877
878 for (uint32_t i = 0; i < createInfoCount; i++) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700879 auto create_info = &pCreateInfos[i];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000880
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700881 if (!create_info->pColorBlendState || !create_info->pMultisampleState ||
882 create_info->pMultisampleState->rasterizationSamples == VK_SAMPLE_COUNT_1_BIT ||
883 create_info->pMultisampleState->sampleShadingEnable) {
Attilio Provenzano02859b22020-02-27 14:17:28 +0000884 return skip;
885 }
886
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700887 auto rp_state = GetRenderPassState(create_info->renderPass);
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200888 const auto& subpass = rp_state->createInfo.pSubpasses[create_info->subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000889
Hans-Kristian Arntzenc2742e72021-07-01 14:31:06 +0200890 // According to spec, pColorBlendState must be ignored if subpass does not have color attachments.
891 uint32_t num_color_attachments = std::min(subpass.colorAttachmentCount, create_info->pColorBlendState->attachmentCount);
892
893 for (uint32_t j = 0; j < num_color_attachments; j++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200894 const auto& blend_att = create_info->pColorBlendState->pAttachments[j];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000895 uint32_t att = subpass.pColorAttachments[j].attachment;
896
897 if (att != VK_ATTACHMENT_UNUSED && blend_att.blendEnable && blend_att.colorWriteMask) {
898 if (!FormatHasFullThroughputBlendingArm(rp_state->createInfo.pAttachments[att].format)) {
899 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultisampledBlending,
900 "%s vkCreateGraphicsPipelines() - createInfo #%u: Pipeline is multisampled and "
901 "color attachment #%u makes use "
902 "of a format which cannot be blended at full throughput when using MSAA.",
903 VendorSpecificTag(kBPVendorArm), i, j);
904 }
905 }
906 }
907 }
908
909 return skip;
910}
911
Camden5b184be2019-08-13 07:50:19 -0600912bool BestPractices::PreCallValidateCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
913 const VkGraphicsPipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -0600914 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500915 void* cgpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -0600916 bool skip = StateTracker::PreCallValidateCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos,
917 pAllocator, pPipelines, cgpl_state_data);
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600918 create_graphics_pipeline_api_state* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
Camden5b184be2019-08-13 07:50:19 -0600919
920 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700921 skip |= LogPerformanceWarning(
922 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
923 "Performance Warning: This vkCreateGraphicsPipelines call is creating multiple pipelines but is not using a "
924 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -0600925 }
926
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000927 for (uint32_t i = 0; i < createInfoCount; i++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200928 const auto& create_info = pCreateInfos[i];
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000929
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600930 if (!(cgpl_state->pipe_state[i]->active_shaders & VK_SHADER_STAGE_MESH_BIT_NV)) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200931 const auto& vertex_input = *create_info.pVertexInputState;
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600932 uint32_t count = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700933 for (uint32_t j = 0; j < vertex_input.vertexBindingDescriptionCount; j++) {
934 if (vertex_input.pVertexBindingDescriptions[j].inputRate == VK_VERTEX_INPUT_RATE_INSTANCE) {
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600935 count++;
936 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000937 }
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600938 if (count > kMaxInstancedVertexBuffers) {
939 skip |= LogPerformanceWarning(
940 device, kVUID_BestPractices_CreatePipelines_TooManyInstancedVertexBuffers,
941 "The pipeline is using %u instanced vertex buffers (current limit: %u), but this can be inefficient on the "
942 "GPU. If using instanced vertex attributes prefer interleaving them in a single buffer.",
943 count, kMaxInstancedVertexBuffers);
944 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000945 }
Attilio Provenzano02859b22020-02-27 14:17:28 +0000946
Szilard Pappaaf2da32020-06-22 10:37:35 +0100947 if ((pCreateInfos[i].pRasterizationState->depthBiasEnable) &&
948 (pCreateInfos[i].pRasterizationState->depthBiasConstantFactor == 0.0f) &&
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +0200949 (pCreateInfos[i].pRasterizationState->depthBiasSlopeFactor == 0.0f) &&
950 VendorCheckEnabled(kBPVendorArm)) {
951 skip |= LogPerformanceWarning(
952 device, kVUID_BestPractices_CreatePipelines_DepthBias_Zero,
953 "%s Performance Warning: This vkCreateGraphicsPipelines call is created with depthBiasEnable set to true "
954 "and both depthBiasConstantFactor and depthBiasSlopeFactor are set to 0. This can cause reduced "
955 "efficiency during rasterization. Consider disabling depthBias or increasing either "
956 "depthBiasConstantFactor or depthBiasSlopeFactor.",
957 VendorSpecificTag(kBPVendorArm));
Szilard Pappaaf2da32020-06-22 10:37:35 +0100958 }
959
Attilio Provenzano02859b22020-02-27 14:17:28 +0000960 skip |= VendorCheckEnabled(kBPVendorArm) && ValidateMultisampledBlendingArm(createInfoCount, pCreateInfos);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000961 }
962
Camden5b184be2019-08-13 07:50:19 -0600963 return skip;
964}
965
Hans-Kristian Arntzenb033ab12021-06-16 11:16:59 +0200966void BestPractices::PreCallRecordDestroyPipeline(VkDevice device, VkPipeline pipeline, const VkAllocationCallbacks *pAllocator)
967{
968 auto itr = graphicsPipelineCIs.find(pipeline);
969 if (itr != graphicsPipelineCIs.end()) {
970 graphicsPipelineCIs.erase(itr);
971 }
972 ValidationStateTracker::PreCallRecordDestroyPipeline(device, pipeline, pAllocator);
973}
974
Sam Walls0961ec02020-03-31 16:39:15 +0100975void BestPractices::ManualPostCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t count,
976 const VkGraphicsPipelineCreateInfo* pCreateInfos,
977 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
978 VkResult result, void* cgpl_state_data) {
979 for (size_t i = 0; i < count; i++) {
980 const auto* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
981 const VkPipeline pipeline_handle = pPipelines[i];
982
983 // record depth stencil state and color blend states for depth pre-pass tracking purposes
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +0200984 GraphicsPipelineCIs& cis = graphicsPipelineCIs[pipeline_handle];
Sam Walls0961ec02020-03-31 16:39:15 +0100985
Hans-Kristian Arntzen42c0ef52021-06-14 14:46:25 +0200986 auto& create_info = cgpl_state->pCreateInfos[i];
Hans-Kristian Arntzen42c0ef52021-06-14 14:46:25 +0200987
Jeremy Gebben396d06a2021-08-12 11:03:04 -0600988 if (create_info.pColorBlendState) {
989 cis.colorBlendStateCI.emplace(create_info.pColorBlendState);
990 }
991
992 if (create_info.pDepthStencilState) {
993 cis.depthStencilStateCI.emplace(create_info.pDepthStencilState);
994 }
Hans-Kristian Arntzen42c0ef52021-06-14 14:46:25 +0200995
996 // Record which frame buffer attachments we should consider to be accessed when a draw call is performed.
997 RENDER_PASS_STATE* rp = GetRenderPassState(create_info.renderPass);
998 auto& subpass = rp->createInfo.pSubpasses[create_info.subpass];
999 cis.accessFramebufferAttachments.clear();
1000
1001 if (cis.colorBlendStateCI) {
Hans-Kristian Arntzenc2742e72021-07-01 14:31:06 +02001002 // According to spec, pColorBlendState must be ignored if subpass does not have color attachments.
1003 uint32_t num_color_attachments = std::min(subpass.colorAttachmentCount, cis.colorBlendStateCI->attachmentCount);
1004 for (uint32_t j = 0; j < num_color_attachments; j++) {
Hans-Kristian Arntzen42c0ef52021-06-14 14:46:25 +02001005 if (cis.colorBlendStateCI->pAttachments[j].colorWriteMask != 0) {
1006 uint32_t attachment = subpass.pColorAttachments[j].attachment;
1007 if (attachment != VK_ATTACHMENT_UNUSED) {
1008 cis.accessFramebufferAttachments.push_back({ attachment, VK_IMAGE_ASPECT_COLOR_BIT });
1009 }
1010 }
1011 }
1012 }
1013
1014 if (cis.depthStencilStateCI && (cis.depthStencilStateCI->depthTestEnable ||
1015 cis.depthStencilStateCI->depthBoundsTestEnable ||
1016 cis.depthStencilStateCI->stencilTestEnable)) {
1017 uint32_t attachment = subpass.pDepthStencilAttachment ?
1018 subpass.pDepthStencilAttachment->attachment :
1019 VK_ATTACHMENT_UNUSED;
1020 if (attachment != VK_ATTACHMENT_UNUSED) {
1021 VkImageAspectFlags aspects = 0;
1022 if (cis.depthStencilStateCI->depthTestEnable || cis.depthStencilStateCI->depthBoundsTestEnable) {
1023 aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
1024 }
1025 if (cis.depthStencilStateCI->stencilTestEnable) {
1026 aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
1027 }
1028 cis.accessFramebufferAttachments.push_back({ attachment, aspects });
1029 }
1030 }
Sam Walls0961ec02020-03-31 16:39:15 +01001031 }
1032}
1033
Camden5b184be2019-08-13 07:50:19 -06001034bool BestPractices::PreCallValidateCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
1035 const VkComputePipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -06001036 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001037 void* ccpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -06001038 bool skip = StateTracker::PreCallValidateCreateComputePipelines(device, pipelineCache, createInfoCount, pCreateInfos,
1039 pAllocator, pPipelines, ccpl_state_data);
Camden5b184be2019-08-13 07:50:19 -06001040
1041 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001042 skip |= LogPerformanceWarning(
1043 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
1044 "Performance Warning: This vkCreateComputePipelines call is creating multiple pipelines but is not using a "
1045 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -06001046 }
1047
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001048 if (VendorCheckEnabled(kBPVendorArm)) {
1049 for (size_t i = 0; i < createInfoCount; i++) {
1050 skip |= ValidateCreateComputePipelineArm(pCreateInfos[i]);
1051 }
1052 }
1053
1054 return skip;
1055}
1056
1057bool BestPractices::ValidateCreateComputePipelineArm(const VkComputePipelineCreateInfo& createInfo) const {
1058 bool skip = false;
1059 auto* module = GetShaderModuleState(createInfo.stage.module);
sfricke-samsung8a7341a2021-02-28 07:30:21 -08001060 // Generate warnings about work group sizes based on active resources.
sfricke-samsung962cad92021-04-13 00:46:29 -07001061 auto entrypoint = module->FindEntrypoint(createInfo.stage.pName, createInfo.stage.stage);
sfricke-samsung8a7341a2021-02-28 07:30:21 -08001062 if (entrypoint == module->end()) return false;
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001063
1064 uint32_t x = 1, y = 1, z = 1;
sfricke-samsung962cad92021-04-13 00:46:29 -07001065 module->FindLocalSize(entrypoint, x, y, z);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001066
1067 uint32_t thread_count = x * y * z;
1068
1069 // Generate a priori warnings about work group sizes.
1070 if (thread_count > kMaxEfficientWorkGroupThreadCountArm) {
1071 skip |= LogPerformanceWarning(
1072 device, kVUID_BestPractices_CreateComputePipelines_ComputeWorkGroupSize,
1073 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, %u, "
1074 "%u) (%u threads total), has more threads than advised in a single work group. It is advised to use work "
1075 "groups with less than %u threads, especially when using barrier() or shared memory.",
1076 VendorSpecificTag(kBPVendorArm), x, y, z, thread_count, kMaxEfficientWorkGroupThreadCountArm);
1077 }
1078
1079 if (thread_count == 1 || ((x > 1) && (x & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
1080 ((y > 1) && (y & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
1081 ((z > 1) && (z & (kThreadGroupDispatchCountAlignmentArm - 1)))) {
1082 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeThreadGroupAlignment,
1083 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, "
1084 "%u, %u) is not aligned to %u "
1085 "threads. On Arm Mali architectures, not aligning work group sizes to %u may "
1086 "leave threads idle on the shader "
1087 "core.",
1088 VendorSpecificTag(kBPVendorArm), x, y, z, kThreadGroupDispatchCountAlignmentArm,
1089 kThreadGroupDispatchCountAlignmentArm);
1090 }
1091
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001092 bool has_writeable_descriptors = false;
locke-lunarg63e4daf2020-08-17 17:53:25 -06001093 bool has_atomic_descriptors = false;
sfricke-samsung962cad92021-04-13 00:46:29 -07001094 auto accessible_ids = module->MarkAccessibleIds(entrypoint);
locke-lunarg63e4daf2020-08-17 17:53:25 -06001095 auto descriptor_uses =
sfricke-samsung962cad92021-04-13 00:46:29 -07001096 module->CollectInterfaceByDescriptorSlot(accessible_ids, &has_writeable_descriptors, &has_atomic_descriptors);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001097
1098 unsigned dimensions = 0;
1099 if (x > 1) dimensions++;
1100 if (y > 1) dimensions++;
1101 if (z > 1) dimensions++;
1102 // Here the dimension will really depend on the dispatch grid, but assume it's 1D.
1103 dimensions = std::max(dimensions, 1u);
1104
1105 // If we're accessing images, we almost certainly want to have a 2D workgroup for cache reasons.
1106 // There are some false positives here. We could simply have a shader that does this within a 1D grid,
1107 // or we may have a linearly tiled image, but these cases are quite unlikely in practice.
1108 bool accesses_2d = false;
1109 for (const auto& usage : descriptor_uses) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001110 auto dim = module->GetShaderResourceDimensionality(usage.second);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001111 if (dim < 0) continue;
1112 auto spvdim = spv::Dim(dim);
1113 if (spvdim != spv::Dim1D && spvdim != spv::DimBuffer) accesses_2d = true;
1114 }
1115
1116 if (accesses_2d && dimensions < 2) {
1117 LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeSpatialLocality,
1118 "%s vkCreateComputePipelines(): compute shader has work group dimensions (%u, %u, %u), which "
1119 "suggests a 1D dispatch, but the shader is accessing 2D or 3D images. The shader may be "
1120 "exhibiting poor spatial locality with respect to one or more shader resources.",
1121 VendorSpecificTag(kBPVendorArm), x, y, z);
1122 }
1123
Camden5b184be2019-08-13 07:50:19 -06001124 return skip;
1125}
1126
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001127bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags flags) const {
Camden5b184be2019-08-13 07:50:19 -06001128 bool skip = false;
1129
1130 if (flags & VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001131 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1132 "You are using VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001133 } else if (flags & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001134 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1135 "You are using VK_PIPELINE_STAGE_ALL_COMMANDS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001136 }
1137
1138 return skip;
1139}
1140
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001141bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags2KHR flags) const {
1142 bool skip = false;
1143
1144 if (flags & VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR) {
1145 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1146 "You are using VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR when %s is called\n", api_name.c_str());
1147 } else if (flags & VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR) {
1148 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1149 "You are using VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR when %s is called\n", api_name.c_str());
1150 }
1151
1152 return skip;
1153}
1154
1155bool BestPractices::CheckDependencyInfo(const std::string& api_name, const VkDependencyInfoKHR& dep_info) const {
1156 bool skip = false;
1157 auto stage_masks = sync_utils::GetGlobalStageMasks(dep_info);
1158
1159 skip |= CheckPipelineStageFlags(api_name, stage_masks.src);
1160 skip |= CheckPipelineStageFlags(api_name, stage_masks.dst);
1161
1162 return skip;
1163}
1164
Mark Lobodzinski84101d72020-04-24 09:43:48 -06001165void BestPractices::ManualPostCallRecordQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo, VkResult result) {
Mark Lobodzinski9b133c12020-03-10 10:42:56 -06001166 for (uint32_t i = 0; i < pPresentInfo->swapchainCount; ++i) {
1167 auto swapchains_result = pPresentInfo->pResults ? pPresentInfo->pResults[i] : result;
1168 if (swapchains_result == VK_SUBOPTIMAL_KHR) {
1169 LogPerformanceWarning(
1170 pPresentInfo->pSwapchains[i], kVUID_BestPractices_SuboptimalSwapchain,
1171 "vkQueuePresentKHR: %s :VK_SUBOPTIMAL_KHR was returned. VK_SUBOPTIMAL_KHR - Presentation will still succeed, "
1172 "subject to the window resize behavior, but the swapchain is no longer configured optimally for the surface it "
1173 "targets. Applications should query updated surface information and recreate their swapchain at the next "
1174 "convenient opportunity.",
1175 report_data->FormatHandle(pPresentInfo->pSwapchains[i]).c_str());
1176 }
1177 }
1178}
1179
Jeff Bolz5c801d12019-10-09 10:38:45 -05001180bool BestPractices::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
1181 VkFence fence) const {
Camden5b184be2019-08-13 07:50:19 -06001182 bool skip = false;
1183
1184 for (uint32_t submit = 0; submit < submitCount; submit++) {
1185 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreCount; semaphore++) {
1186 skip |= CheckPipelineStageFlags("vkQueueSubmit", pSubmits[submit].pWaitDstStageMask[semaphore]);
1187 }
1188 }
1189
1190 return skip;
1191}
1192
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001193bool BestPractices::PreCallValidateQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR* pSubmits,
1194 VkFence fence) const {
1195 bool skip = false;
1196
1197 for (uint32_t submit = 0; submit < submitCount; submit++) {
1198 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreInfoCount; semaphore++) {
1199 skip |= CheckPipelineStageFlags("vkQueueSubmit2KHR", pSubmits[submit].pWaitSemaphoreInfos[semaphore].stageMask);
1200 }
1201 }
1202
1203 return skip;
1204}
1205
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001206bool BestPractices::PreCallValidateCreateCommandPool(VkDevice device, const VkCommandPoolCreateInfo* pCreateInfo,
1207 const VkAllocationCallbacks* pAllocator, VkCommandPool* pCommandPool) const {
1208 bool skip = false;
1209
1210 if (pCreateInfo->flags & VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT) {
1211 skip |= LogPerformanceWarning(
1212 device, kVUID_BestPractices_CreateCommandPool_CommandBufferReset,
1213 "vkCreateCommandPool(): VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT is set. Consider resetting entire "
1214 "pool instead.");
1215 }
1216
1217 return skip;
1218}
1219
1220bool BestPractices::PreCallValidateBeginCommandBuffer(VkCommandBuffer commandBuffer,
1221 const VkCommandBufferBeginInfo* pBeginInfo) const {
1222 bool skip = false;
1223
1224 if (pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT) {
1225 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_SimultaneousUse,
1226 "vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT is set.");
1227 }
1228
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001229 if (!(pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT) && VendorCheckEnabled(kBPVendorArm)) {
1230 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_OneTimeSubmit,
Attilio Provenzano02859b22020-02-27 14:17:28 +00001231 "%s vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT is not set. "
1232 "For best performance on Mali GPUs, consider setting ONE_TIME_SUBMIT by default.",
1233 VendorSpecificTag(kBPVendorArm));
1234 }
1235
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001236 return skip;
1237}
1238
Jeff Bolz5c801d12019-10-09 10:38:45 -05001239bool BestPractices::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001240 bool skip = false;
1241
1242 skip |= CheckPipelineStageFlags("vkCmdSetEvent", stageMask);
1243
1244 return skip;
1245}
1246
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001247bool BestPractices::PreCallValidateCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1248 const VkDependencyInfoKHR* pDependencyInfo) const {
1249 return CheckDependencyInfo("vkCmdSetEvent2KHR", *pDependencyInfo);
1250}
1251
Jeff Bolz5c801d12019-10-09 10:38:45 -05001252bool BestPractices::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
1253 VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001254 bool skip = false;
1255
1256 skip |= CheckPipelineStageFlags("vkCmdResetEvent", stageMask);
1257
1258 return skip;
1259}
1260
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001261bool BestPractices::PreCallValidateCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1262 VkPipelineStageFlags2KHR stageMask) const {
1263 bool skip = false;
1264
1265 skip |= CheckPipelineStageFlags("vkCmdResetEvent2KHR", stageMask);
1266
1267 return skip;
1268}
1269
Camden5b184be2019-08-13 07:50:19 -06001270bool BestPractices::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1271 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
1272 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1273 uint32_t bufferMemoryBarrierCount,
1274 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1275 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001276 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001277 bool skip = false;
1278
1279 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", srcStageMask);
1280 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", dstStageMask);
1281
1282 return skip;
1283}
1284
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001285bool BestPractices::PreCallValidateCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1286 const VkDependencyInfoKHR* pDependencyInfos) const {
1287 bool skip = false;
1288 for (uint32_t i = 0; i < eventCount; i++) {
1289 skip = CheckDependencyInfo("vkCmdWaitEvents2KHR", pDependencyInfos[i]);
1290 }
1291
1292 return skip;
1293}
1294
Camden5b184be2019-08-13 07:50:19 -06001295bool BestPractices::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
1296 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
1297 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1298 uint32_t bufferMemoryBarrierCount,
1299 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1300 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001301 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001302 bool skip = false;
1303
1304 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", srcStageMask);
1305 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", dstStageMask);
1306
1307 return skip;
1308}
1309
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001310bool BestPractices::PreCallValidateCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer,
1311 const VkDependencyInfoKHR* pDependencyInfo) const {
1312 return CheckDependencyInfo("vkCmdPipelineBarrier2KHR", *pDependencyInfo);
1313}
1314
Camden5b184be2019-08-13 07:50:19 -06001315bool BestPractices::PreCallValidateCmdWriteTimestamp(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001316 VkQueryPool queryPool, uint32_t query) const {
Camden5b184be2019-08-13 07:50:19 -06001317 bool skip = false;
1318
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001319 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp", static_cast<VkPipelineStageFlags>(pipelineStage));
1320
1321 return skip;
1322}
1323
1324bool BestPractices::PreCallValidateCmdWriteTimestamp2KHR(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
1325 VkQueryPool queryPool, uint32_t query) const {
1326 bool skip = false;
1327
1328 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp2KHR", pipelineStage);
Camden5b184be2019-08-13 07:50:19 -06001329
1330 return skip;
1331}
1332
Sam Walls0961ec02020-03-31 16:39:15 +01001333void BestPractices::PostCallRecordCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
1334 VkPipeline pipeline) {
1335 StateTracker::PostCallRecordCmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
1336
1337 if (pipelineBindPoint == VK_PIPELINE_BIND_POINT_GRAPHICS) {
1338 // check for depth/blend state tracking
1339 auto gp_cis = graphicsPipelineCIs.find(pipeline);
1340 if (gp_cis != graphicsPipelineCIs.end()) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06001341 auto* cb_node = GetCBState(commandBuffer);
1342 assert(cb_node);
1343 auto& render_pass_state = cb_node->render_pass_state;
Sam Walls0961ec02020-03-31 16:39:15 +01001344
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001345 render_pass_state.nextDrawTouchesAttachments = gp_cis->second.accessFramebufferAttachments;
1346 render_pass_state.drawTouchAttachments = true;
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02001347
Jeremy Gebben396d06a2021-08-12 11:03:04 -06001348 const auto& blend_state = gp_cis->second.colorBlendStateCI;
1349 const auto& stencil_state = gp_cis->second.depthStencilStateCI;
Sam Walls0961ec02020-03-31 16:39:15 +01001350
1351 if (blend_state) {
1352 // assume the pipeline is depth-only unless any of the attachments have color writes enabled
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001353 render_pass_state.depthOnly = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001354 for (size_t i = 0; i < blend_state->attachmentCount; i++) {
1355 if (blend_state->pAttachments[i].colorWriteMask != 0) {
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001356 render_pass_state.depthOnly = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001357 }
1358 }
1359 }
1360
1361 // check for depth value usage
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001362 render_pass_state.depthEqualComparison = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001363
1364 if (stencil_state && stencil_state->depthTestEnable) {
1365 switch (stencil_state->depthCompareOp) {
1366 case VK_COMPARE_OP_EQUAL:
1367 case VK_COMPARE_OP_GREATER_OR_EQUAL:
1368 case VK_COMPARE_OP_LESS_OR_EQUAL:
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001369 render_pass_state.depthEqualComparison = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001370 break;
1371 default:
1372 break;
1373 }
1374 }
Sam Walls0961ec02020-03-31 16:39:15 +01001375 }
1376 }
1377}
1378
Hans-Kristian Arntzen237663c2021-07-01 14:36:40 +02001379static inline bool RenderPassUsesAttachmentAsResolve(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1380 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
1381 const auto& subpass_info = createInfo.pSubpasses[subpass];
1382 if (subpass_info.pResolveAttachments) {
1383 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1384 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
1385 }
1386 }
1387 }
1388
1389 return false;
1390}
1391
Attilio Provenzano02859b22020-02-27 14:17:28 +00001392static inline bool RenderPassUsesAttachmentOnTile(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1393 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001394 const auto& subpass_info = createInfo.pSubpasses[subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001395
1396 // If an attachment is ever used as a color attachment,
1397 // resolve attachment or depth stencil attachment,
1398 // it needs to exist on tile at some point.
1399
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001400 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1401 if (subpass_info.pColorAttachments[i].attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001402 }
1403
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001404 if (subpass_info.pResolveAttachments) {
1405 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1406 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
1407 }
1408 }
1409
1410 if (subpass_info.pDepthStencilAttachment && subpass_info.pDepthStencilAttachment->attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001411 }
1412
1413 return false;
1414}
1415
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001416static inline bool RenderPassUsesAttachmentAsImageOnly(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1417 if (RenderPassUsesAttachmentOnTile(createInfo, attachment)) {
1418 return false;
1419 }
1420
1421 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001422 const auto& subpassInfo = createInfo.pSubpasses[subpass];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001423
1424 for (uint32_t i = 0; i < subpassInfo.inputAttachmentCount; i++) {
1425 if (subpassInfo.pInputAttachments[i].attachment == attachment) {
1426 return true;
1427 }
1428 }
1429 }
1430
1431 return false;
1432}
1433
Attilio Provenzano02859b22020-02-27 14:17:28 +00001434bool BestPractices::ValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1435 const VkRenderPassBeginInfo* pRenderPassBegin) const {
1436 bool skip = false;
1437
1438 if (!pRenderPassBegin) {
1439 return skip;
1440 }
1441
Gareth Webbdc6549a2021-06-16 03:52:24 +01001442 if (pRenderPassBegin->renderArea.extent.width == 0 || pRenderPassBegin->renderArea.extent.height == 0) {
1443 skip |= LogWarning(device, kVUID_BestPractices_BeginRenderPass_ZeroSizeRenderArea,
1444 "This render pass has a zero-size render area. It cannot write to any attachments, "
1445 "and can only be used for side effects such as layout transitions.");
1446 }
1447
Attilio Provenzano02859b22020-02-27 14:17:28 +00001448 auto rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
1449 if (rp_state) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08001450 if (rp_state->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07001451 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
Tony-LunarG767180f2020-04-23 14:03:59 -06001452 if (rpabi) {
1453 skip = ValidateAttachments(rp_state->createInfo.ptr(), rpabi->attachmentCount, rpabi->pAttachments);
1454 }
1455 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001456 // Check if any attachments have LOAD operation on them
1457 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001458 const auto& attachment = rp_state->createInfo.pAttachments[att];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001459
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001460 bool attachment_has_readback = false;
Hans-Kristian Arntzen4afb59b2021-06-18 12:41:36 +02001461 if (!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001462 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001463 }
1464
1465 if (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001466 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001467 }
1468
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001469 bool attachment_needs_readback = false;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001470
1471 // Check if the attachment is actually used in any subpass on-tile
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001472 if (attachment_has_readback && RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1473 attachment_needs_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001474 }
1475
1476 // Using LOAD_OP_LOAD is expensive on tiled GPUs, so flag it as a potential improvement
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001477 if (attachment_needs_readback && VendorCheckEnabled(kBPVendorArm)) {
1478 skip |= LogPerformanceWarning(
1479 device, kVUID_BestPractices_BeginRenderPass_AttachmentNeedsReadback,
1480 "%s Attachment #%u in render pass has begun with VK_ATTACHMENT_LOAD_OP_LOAD.\n"
1481 "Submitting this renderpass will cause the driver to inject a readback of the attachment "
1482 "which will copy in total %u pixels (renderArea = { %d, %d, %u, %u }) to the tile buffer.",
1483 VendorSpecificTag(kBPVendorArm), att,
1484 pRenderPassBegin->renderArea.extent.width * pRenderPassBegin->renderArea.extent.height,
1485 pRenderPassBegin->renderArea.offset.x, pRenderPassBegin->renderArea.offset.y,
1486 pRenderPassBegin->renderArea.extent.width, pRenderPassBegin->renderArea.extent.height);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001487 }
1488 }
1489 }
1490
1491 return skip;
1492}
1493
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001494void BestPractices::QueueValidateImageView(QueueCallbacks &funcs, const char* function_name,
1495 IMAGE_VIEW_STATE* view, IMAGE_SUBRESOURCE_USAGE_BP usage) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001496 if (view) {
Jeremy Gebbenb4d17012021-07-08 13:18:15 -06001497 QueueValidateImage(funcs, function_name, GetImageUsageState(view->create_info.image), usage,
1498 view->normalized_subresource_range);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001499 }
1500}
1501
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001502void BestPractices::QueueValidateImage(QueueCallbacks &funcs, const char* function_name,
1503 IMAGE_STATE_BP* state, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001504 const VkImageSubresourceRange& subresource_range) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001505 IMAGE_STATE* image = state->image;
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02001506
1507 // If we're viewing a 3D slice, ignore base array layer.
1508 // The entire 3D subresource is accessed as one atomic unit.
1509 const uint32_t base_array_layer = image->createInfo.imageType == VK_IMAGE_TYPE_3D ? 0 : subresource_range.baseArrayLayer;
1510
1511 const uint32_t max_layers = image->createInfo.arrayLayers - base_array_layer;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001512 const uint32_t array_layers = std::min(subresource_range.layerCount, max_layers);
1513 const uint32_t max_levels = image->createInfo.mipLevels - subresource_range.baseMipLevel;
1514 const uint32_t mip_levels = std::min(image->createInfo.mipLevels, max_levels);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001515
1516 for (uint32_t layer = 0; layer < array_layers; layer++) {
1517 for (uint32_t level = 0; level < mip_levels; level++) {
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02001518 QueueValidateImage(funcs, function_name, state, usage, layer + base_array_layer,
1519 level + subresource_range.baseMipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001520 }
1521 }
1522}
1523
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001524void BestPractices::QueueValidateImage(QueueCallbacks &funcs, const char* function_name,
1525 IMAGE_STATE_BP* state, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001526 const VkImageSubresourceLayers& subresource_layers) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001527 IMAGE_STATE* image = state->image;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001528 const uint32_t max_layers = image->createInfo.arrayLayers - subresource_layers.baseArrayLayer;
1529 const uint32_t array_layers = std::min(subresource_layers.layerCount, max_layers);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001530
1531 for (uint32_t layer = 0; layer < array_layers; layer++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001532 QueueValidateImage(funcs, function_name, state, usage, layer + subresource_layers.baseArrayLayer, subresource_layers.mipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001533 }
1534}
1535
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001536void BestPractices::QueueValidateImage(QueueCallbacks &funcs, const char* function_name,
1537 IMAGE_STATE_BP* state, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001538 uint32_t array_layer, uint32_t mip_level) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001539 funcs.push_back([this, function_name, state, usage, array_layer, mip_level](const ValidationStateTracker*, const QUEUE_STATE*) -> bool {
1540 ValidateImageInQueue(function_name, state, usage, array_layer, mip_level);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001541 return false;
1542 });
1543}
1544
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001545void BestPractices::ValidateImageInQueueArm(const char* function_name, IMAGE_STATE* image,
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001546 IMAGE_SUBRESOURCE_USAGE_BP last_usage,
1547 IMAGE_SUBRESOURCE_USAGE_BP usage,
1548 uint32_t array_layer, uint32_t mip_level) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001549 // Swapchain images are implicitly read so clear after store is expected.
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001550 if (usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_CLEARED && last_usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_STORED &&
Jeremy Gebben82e11d52021-07-26 09:19:37 -06001551 !image->IsSwapchainImage()) {
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001552 LogPerformanceWarning(
1553 device, kVUID_BestPractices_RenderPass_RedundantStore,
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001554 "%s: %s Subresource (arrayLayer: %u, mipLevel: %u) of image was cleared as part of LOAD_OP_CLEAR, but last time "
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001555 "image was used, it was written to with STORE_OP_STORE. "
1556 "Storing to the image is probably redundant in this case, and wastes bandwidth on tile-based "
1557 "architectures.",
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001558 function_name, VendorSpecificTag(kBPVendorArm), array_layer, mip_level);
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001559 } else if (usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_CLEARED && last_usage == IMAGE_SUBRESOURCE_USAGE_BP::CLEARED) {
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001560 LogPerformanceWarning(
1561 device, kVUID_BestPractices_RenderPass_RedundantClear,
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001562 "%s: %s Subresource (arrayLayer: %u, mipLevel: %u) of image was cleared as part of LOAD_OP_CLEAR, but last time "
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001563 "image was used, it was written to with vkCmdClear*Image(). "
1564 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
1565 "tile-based architectures."
1566 "architectures.",
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001567 function_name, VendorSpecificTag(kBPVendorArm), array_layer, mip_level);
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01001568 } else if (usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE &&
1569 (last_usage == IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE ||
1570 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::CLEARED ||
1571 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE ||
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001572 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE)) {
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01001573 const char *last_cmd = nullptr;
1574 const char *vuid = nullptr;
1575 const char *suggestion = nullptr;
1576
1577 switch (last_usage) {
1578 case IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE:
1579 vuid = kVUID_BestPractices_RenderPass_BlitImage_LoadOpLoad;
1580 last_cmd = "vkCmdBlitImage";
1581 suggestion =
1582 "The blit is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
1583 "Rather than blitting, just render the source image in a fragment shader in this render pass, "
1584 "which avoids the memory roundtrip.";
1585 break;
1586 case IMAGE_SUBRESOURCE_USAGE_BP::CLEARED:
1587 vuid = kVUID_BestPractices_RenderPass_InefficientClear;
1588 last_cmd = "vkCmdClear*Image";
1589 suggestion =
1590 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
1591 "tile-based architectures. "
1592 "Use LOAD_OP_CLEAR instead to clear the image for free.";
1593 break;
1594 case IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE:
1595 vuid = kVUID_BestPractices_RenderPass_CopyImage_LoadOpLoad;
1596 last_cmd = "vkCmdCopy*Image";
1597 suggestion =
1598 "The copy is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
1599 "Rather than copying, just render the source image in a fragment shader in this render pass, "
1600 "which avoids the memory roundtrip.";
1601 break;
1602 case IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE:
1603 vuid = kVUID_BestPractices_RenderPass_ResolveImage_LoadOpLoad;
1604 last_cmd = "vkCmdResolveImage";
1605 suggestion =
1606 "The resolve is probably redundant in this case, and wastes a lot of bandwidth on tile-based architectures. "
1607 "Rather than resolving, and then loading, try to keep rendering in the same render pass, "
1608 "which avoids the memory roundtrip.";
1609 break;
1610 default:
1611 break;
1612 }
1613
1614 LogPerformanceWarning(
1615 device, vuid,
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001616 "%s: %s Subresource (arrayLayer: %u, mipLevel: %u) of image was loaded to tile as part of LOAD_OP_LOAD, but last "
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01001617 "time image was used, it was written to with %s. %s",
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001618 function_name, VendorSpecificTag(kBPVendorArm), array_layer, mip_level, last_cmd, suggestion);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001619 }
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001620}
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001621
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001622void BestPractices::ValidateImageInQueue(const char* function_name, IMAGE_STATE_BP* state,
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001623 IMAGE_SUBRESOURCE_USAGE_BP usage, uint32_t array_layer,
1624 uint32_t mip_level) {
1625 IMAGE_STATE* image = state->image;
1626 IMAGE_SUBRESOURCE_USAGE_BP last_usage = state->usages[array_layer][mip_level];
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001627 state->usages[array_layer][mip_level] = usage;
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001628 if (VendorCheckEnabled(kBPVendorArm)) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001629 ValidateImageInQueueArm(function_name, image, last_usage, usage, array_layer, mip_level);
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001630 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001631}
1632
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06001633void BestPractices::AddDeferredQueueOperations(CMD_BUFFER_STATE_BP* cb) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001634 cb->queue_submit_functions.insert(cb->queue_submit_functions.end(),
Hans-Kristian Arntzenf44df192021-06-14 11:42:08 +02001635 cb->queue_submit_functions_after_render_pass.begin(),
1636 cb->queue_submit_functions_after_render_pass.end());
1637 cb->queue_submit_functions_after_render_pass.clear();
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001638}
1639
1640void BestPractices::PreCallRecordCmdEndRenderPass(VkCommandBuffer commandBuffer) {
1641 ValidationStateTracker::PreCallRecordCmdEndRenderPass(commandBuffer);
Hans-Kristian Arntzenb8336ad2021-04-28 14:54:09 +02001642 AddDeferredQueueOperations(GetCBState(commandBuffer));
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001643}
1644
1645void BestPractices::PreCallRecordCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassInfo) {
1646 ValidationStateTracker::PreCallRecordCmdEndRenderPass2(commandBuffer, pSubpassInfo);
Hans-Kristian Arntzenb8336ad2021-04-28 14:54:09 +02001647 AddDeferredQueueOperations(GetCBState(commandBuffer));
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001648}
1649
1650void BestPractices::PreCallRecordCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfoKHR *pSubpassInfo) {
1651 ValidationStateTracker::PreCallRecordCmdEndRenderPass2KHR(commandBuffer, pSubpassInfo);
Hans-Kristian Arntzenb8336ad2021-04-28 14:54:09 +02001652 AddDeferredQueueOperations(GetCBState(commandBuffer));
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001653}
1654
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02001655void BestPractices::PreCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer,
1656 const VkRenderPassBeginInfo* pRenderPassBegin,
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001657 VkSubpassContents contents) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001658 ValidationStateTracker::PreCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02001659 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1660}
1661
1662void BestPractices::PreCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer,
1663 const VkRenderPassBeginInfo* pRenderPassBegin,
1664 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1665 ValidationStateTracker::PreCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1666 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1667}
1668
1669void BestPractices::PreCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1670 const VkRenderPassBeginInfo* pRenderPassBegin,
1671 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1672 ValidationStateTracker::PreCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1673 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1674}
1675
1676void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001677
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001678 if (!pRenderPassBegin) {
1679 return;
1680 }
1681
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06001682 auto* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001683
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06001684 auto* rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001685 if (rp_state) {
1686 // Check load ops
1687 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001688 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001689
1690 if (!RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att) &&
1691 !RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1692 continue;
1693 }
1694
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001695 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::UNDEFINED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001696
1697 if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) ||
1698 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001699 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02001700 } else if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) ||
1701 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_CLEAR)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001702 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_CLEARED;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02001703 } else if (RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att)) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001704 usage = IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001705 }
1706
1707 auto framebuffer = GetFramebufferState(pRenderPassBegin->framebuffer);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001708 IMAGE_VIEW_STATE* image_view = nullptr;
1709
Tony-LunarGb3ab3572021-07-02 09:45:17 -06001710 if (framebuffer->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001711 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
1712 if (rpabi) {
1713 image_view = GetImageViewState(rpabi->pAttachments[att]);
1714 }
1715 } else {
1716 image_view = GetImageViewState(framebuffer->createInfo.pAttachments[att]);
1717 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001718
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001719 QueueValidateImageView(cb->queue_submit_functions, "vkCmdBeginRenderPass()", image_view, usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001720 }
1721
1722 // Check store ops
1723 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001724 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001725
1726 if (!RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1727 continue;
1728 }
1729
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001730 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_DISCARDED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001731
1732 if ((!FormatIsStencilOnly(attachment.format) && attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE) ||
1733 (FormatHasStencil(attachment.format) && attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001734 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_STORED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001735 }
1736
1737 auto framebuffer = GetFramebufferState(pRenderPassBegin->framebuffer);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001738
1739 IMAGE_VIEW_STATE* image_view = nullptr;
Tony-LunarGb3ab3572021-07-02 09:45:17 -06001740 if (framebuffer->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001741 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
1742 if (rpabi) {
1743 image_view = GetImageViewState(rpabi->pAttachments[att]);
1744 }
1745 } else {
1746 image_view = GetImageViewState(framebuffer->createInfo.pAttachments[att]);
1747 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001748
Hans-Kristian Arntzenf44df192021-06-14 11:42:08 +02001749 QueueValidateImageView(cb->queue_submit_functions_after_render_pass, "vkCmdEndRenderPass()", image_view, usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001750 }
1751 }
1752}
1753
Attilio Provenzano02859b22020-02-27 14:17:28 +00001754bool BestPractices::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1755 VkSubpassContents contents) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001756 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1757 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001758 return skip;
1759}
1760
1761bool BestPractices::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1762 const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08001763 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001764 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1765 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001766 return skip;
1767}
1768
1769bool BestPractices::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08001770 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001771 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1772 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001773 return skip;
1774}
1775
Sam Walls0961ec02020-03-31 16:39:15 +01001776void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1777 const VkRenderPassBeginInfo* pRenderPassBegin) {
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001778 // Reset the renderpass state
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06001779 auto* cb = GetCBState(commandBuffer);
1780 cb->hasDrawCmd = false;
1781 assert(cb);
1782 auto& render_pass_state = cb->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02001783 render_pass_state.touchesAttachments.clear();
1784 render_pass_state.earlyClearAttachments.clear();
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001785 render_pass_state.numDrawCallsDepthOnly = 0;
1786 render_pass_state.numDrawCallsDepthEqualCompare = 0;
1787 render_pass_state.colorAttachment = false;
1788 render_pass_state.depthAttachment = false;
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02001789 render_pass_state.drawTouchAttachments = true;
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001790 // Don't reset state related to pipeline state.
Sam Walls0961ec02020-03-31 16:39:15 +01001791
Hans-Kristian Arntzena1a92cc2021-03-17 13:09:33 +01001792 const auto* rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
Sam Walls0961ec02020-03-31 16:39:15 +01001793
1794 // track depth / color attachment usage within the renderpass
1795 for (size_t i = 0; i < rp_state->createInfo.subpassCount; i++) {
1796 // record if depth/color attachments are in use for this renderpass
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001797 if (rp_state->createInfo.pSubpasses[i].pDepthStencilAttachment != nullptr) render_pass_state.depthAttachment = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001798
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001799 if (rp_state->createInfo.pSubpasses[i].colorAttachmentCount > 0) render_pass_state.colorAttachment = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001800 }
1801}
1802
1803void BestPractices::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1804 VkSubpassContents contents) {
1805 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1806 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
1807}
1808
1809void BestPractices::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1810 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1811 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1812 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1813}
1814
1815void BestPractices::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1816 const VkRenderPassBeginInfo* pRenderPassBegin,
1817 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1818 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1819 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1820}
1821
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001822// Generic function to handle validation for all CmdDraw* type functions
1823bool BestPractices::ValidateCmdDrawType(VkCommandBuffer cmd_buffer, const char* caller) const {
1824 bool skip = false;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06001825 const auto* cb_state = GetCBState(cmd_buffer);
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001826 if (cb_state) {
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001827 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
1828 const auto* pipeline_state = cb_state->lastBound[lv_bind_point].pipeline_state;
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001829 const auto& current_vtx_bfr_binding_info = cb_state->current_vertex_buffer_binding_info.vertex_buffer_bindings;
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001830
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001831 // Verify vertex binding
1832 if (pipeline_state->vertex_binding_descriptions_.size() <= 0) {
1833 if ((!current_vtx_bfr_binding_info.empty()) && (!cb_state->vertex_buffer_used)) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001834 skip |= LogPerformanceWarning(cb_state->commandBuffer(), kVUID_BestPractices_DrawState_VtxIndexOutOfBounds,
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001835 "Vertex buffers are bound to %s but no vertex buffers are attached to %s.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001836 report_data->FormatHandle(cb_state->commandBuffer()).c_str(),
1837 report_data->FormatHandle(pipeline_state->pipeline()).c_str());
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001838 }
1839 }
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06001840
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06001841 const auto* pipe = cb_state->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06001842 if (pipe) {
1843 const auto* rp_state = pipe->rp_state.get();
1844 if (rp_state) {
1845 for (uint32_t i = 0; i < rp_state->createInfo.subpassCount; ++i) {
1846 const auto& subpass = rp_state->createInfo.pSubpasses[i];
1847 const uint32_t depth_stencil_attachment = GetSubpassDepthStencilAttachmentIndex(
1848 pipe->graphicsPipelineCI.pDepthStencilState, subpass.pDepthStencilAttachment);
1849 if ((depth_stencil_attachment == VK_ATTACHMENT_UNUSED) && pipe->graphicsPipelineCI.pRasterizationState &&
1850 pipe->graphicsPipelineCI.pRasterizationState->depthBiasEnable == VK_TRUE) {
1851 skip |= LogWarning(cb_state->commandBuffer(), kVUID_BestPractices_DepthBiasNoAttachment,
1852 "%s: depthBiasEnable == VK_TRUE without a depth-stencil attachment.", caller);
1853 }
1854 }
1855 }
1856 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001857 }
1858 return skip;
1859}
1860
Sam Walls0961ec02020-03-31 16:39:15 +01001861void BestPractices::RecordCmdDrawType(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06001862 auto* cb_node = GetCBState(cmd_buffer);
1863 assert(cb_node);
1864 auto& render_pass_state = cb_node->render_pass_state;
Sam Walls0961ec02020-03-31 16:39:15 +01001865 if (VendorCheckEnabled(kBPVendorArm)) {
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02001866 RecordCmdDrawTypeArm(render_pass_state, draw_count, caller);
1867 }
1868
1869 if (render_pass_state.drawTouchAttachments) {
1870 for (auto& touch : render_pass_state.nextDrawTouchesAttachments) {
1871 RecordAttachmentAccess(render_pass_state, touch.framebufferAttachment, touch.aspects);
1872 }
1873 // No need to touch the same attachments over and over.
1874 render_pass_state.drawTouchAttachments = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001875 }
1876}
1877
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02001878void BestPractices::RecordCmdDrawTypeArm(RenderPassState& render_pass_state, uint32_t draw_count, const char* caller) {
1879 if (draw_count >= kDepthPrePassMinDrawCountArm) {
1880 if (render_pass_state.depthOnly) render_pass_state.numDrawCallsDepthOnly++;
1881 if (render_pass_state.depthEqualComparison) render_pass_state.numDrawCallsDepthEqualCompare++;
Sam Walls0961ec02020-03-31 16:39:15 +01001882 }
1883}
1884
Camden5b184be2019-08-13 07:50:19 -06001885bool BestPractices::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001886 uint32_t firstVertex, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06001887 bool skip = false;
1888
1889 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001890 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
1891 "Warning: You are calling vkCmdDraw() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06001892 }
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06001893 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDraw()");
Camden5b184be2019-08-13 07:50:19 -06001894
1895 return skip;
1896}
1897
Sam Walls0961ec02020-03-31 16:39:15 +01001898void BestPractices::PostCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
1899 uint32_t firstVertex, uint32_t firstInstance) {
1900 StateTracker::PostCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
1901 RecordCmdDrawType(commandBuffer, vertexCount * instanceCount, "vkCmdDraw()");
1902}
1903
Camden5b184be2019-08-13 07:50:19 -06001904bool BestPractices::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001905 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06001906 bool skip = false;
1907
1908 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001909 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
1910 "Warning: You are calling vkCmdDrawIndexed() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06001911 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001912 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexed()");
1913
Attilio Provenzano02859b22020-02-27 14:17:28 +00001914 // Check if we reached the limit for small indexed draw calls.
1915 // Note that we cannot update the draw call count here, so we do it in PreCallRecordCmdDrawIndexed.
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06001916 const auto* cmd_state = GetCBState(commandBuffer);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001917 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices &&
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001918 (cmd_state->small_indexed_draw_call_count == kMaxSmallIndexedDrawcalls - 1) &&
1919 VendorCheckEnabled(kBPVendorArm)) {
1920 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_ManySmallIndexedDrawcalls,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -06001921 "%s: The command buffer contains many small indexed drawcalls "
Attilio Provenzano02859b22020-02-27 14:17:28 +00001922 "(at least %u drawcalls with less than %u indices each). This may cause pipeline bubbles. "
1923 "You can try batching drawcalls or instancing when applicable.",
1924 VendorSpecificTag(kBPVendorArm), kMaxSmallIndexedDrawcalls, kSmallIndexedDrawcallIndices);
1925 }
1926
Sam Walls8e77e4f2020-03-16 20:47:40 +00001927 if (VendorCheckEnabled(kBPVendorArm)) {
1928 ValidateIndexBufferArm(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
1929 }
1930
1931 return skip;
1932}
1933
1934bool BestPractices::ValidateIndexBufferArm(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1935 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
1936 bool skip = false;
1937
1938 // check for sparse/underutilised index buffer, and post-transform cache thrashing
1939 const auto* cmd_state = GetCBState(commandBuffer);
1940 if (cmd_state == nullptr) return skip;
1941
locke-lunarg1ae57d62020-11-18 10:49:19 -07001942 const auto* ib_state = cmd_state->index_buffer_binding.buffer_state.get();
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06001943 if (ib_state == nullptr || cmd_state->index_buffer_binding.buffer_state->Destroyed()) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00001944
1945 const VkIndexType ib_type = cmd_state->index_buffer_binding.index_type;
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06001946 const auto& ib_mem_state = *ib_state->MemState();
Sam Walls8e77e4f2020-03-16 20:47:40 +00001947 const VkDeviceSize ib_mem_offset = ib_mem_state.mapped_range.offset;
1948 const void* ib_mem = ib_mem_state.p_driver_data;
1949 bool primitive_restart_enable = false;
1950
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001951 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
1952 const auto& pipeline_binding_iter = cmd_state->lastBound[lv_bind_point];
1953 const auto* pipeline_state = pipeline_binding_iter.pipeline_state;
Sam Walls8e77e4f2020-03-16 20:47:40 +00001954
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001955 if (pipeline_state != nullptr && pipeline_state->graphicsPipelineCI.pInputAssemblyState != nullptr) {
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001956 primitive_restart_enable = pipeline_state->graphicsPipelineCI.pInputAssemblyState->primitiveRestartEnable == VK_TRUE;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001957 }
Sam Walls8e77e4f2020-03-16 20:47:40 +00001958
1959 // no point checking index buffer if the memory is nonexistant/unmapped, or if there is no graphics pipeline bound to this CB
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001960 if (ib_mem && pipeline_binding_iter.IsUsing()) {
Sam Walls8e77e4f2020-03-16 20:47:40 +00001961 uint32_t scan_stride;
1962 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1963 scan_stride = sizeof(uint8_t);
1964 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1965 scan_stride = sizeof(uint16_t);
1966 } else {
1967 scan_stride = sizeof(uint32_t);
1968 }
1969
1970 const uint8_t* scan_begin = static_cast<const uint8_t*>(ib_mem) + ib_mem_offset + firstIndex * scan_stride;
1971 const uint8_t* scan_end = scan_begin + indexCount * scan_stride;
1972
1973 // Min and max are important to track for some Mali architectures. In older Mali devices without IDVS, all
1974 // vertices corresponding to indices between the minimum and maximum may be loaded, and possibly shaded,
1975 // irrespective of whether or not they're part of the draw call.
1976
1977 // start with minimum as 0xFFFFFFFF and adjust to indices in the buffer
1978 uint32_t min_index = ~0u;
1979 // start with maximum as 0 and adjust to indices in the buffer
1980 uint32_t max_index = 0u;
1981
1982 // first scan-through, we're looking to simulate a model LRU post-transform cache, estimating the number of vertices shaded
1983 // for the given index buffer
1984 uint32_t vertex_shade_count = 0;
1985
1986 PostTransformLRUCacheModel post_transform_cache;
1987
1988 // The size of the cache being modelled positively correlates with how much behaviour it can capture about
1989 // arbitrary ground-truth hardware/architecture cache behaviour. I.e. it's a good solution when we don't know the
1990 // target architecture.
1991 // However, modelling a post-transform cache with more than 32 elements gives diminishing returns in practice.
1992 // http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
1993 post_transform_cache.resize(32);
1994
1995 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
1996 uint32_t scan_index;
1997 uint32_t primitive_restart_value;
1998 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1999 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
2000 primitive_restart_value = 0xFF;
2001 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
2002 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
2003 primitive_restart_value = 0xFFFF;
2004 } else {
2005 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
2006 primitive_restart_value = 0xFFFFFFFF;
2007 }
2008
2009 max_index = std::max(max_index, scan_index);
2010 min_index = std::min(min_index, scan_index);
2011
2012 if (!primitive_restart_enable || scan_index != primitive_restart_value) {
2013 bool in_cache = post_transform_cache.query_cache(scan_index);
2014 // if the shaded vertex corresponding to the index is not in the PT-cache, we need to shade again
2015 if (!in_cache) vertex_shade_count++;
2016 }
2017 }
2018
2019 // 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 +01002020 // 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
2021 if (max_index < min_index || max_index == min_index) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00002022
2023 if (max_index - min_index >= indexCount) {
Mark Young0ec6b062020-11-19 15:32:17 -07002024 skip |=
2025 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
2026 "%s The indices which were specified for the draw call only utilise approximately %.02f%% of "
2027 "index buffer value range. Arm Mali architectures before G71 do not have IDVS (Index-Driven "
2028 "Vertex Shading), meaning all vertices corresponding to indices between the minimum and "
2029 "maximum would be loaded, and possibly shaded, whether or not they are used.",
2030 VendorSpecificTag(kBPVendorArm),
2031 (static_cast<float>(indexCount) / static_cast<float>(max_index - min_index)) * 100.0f);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002032 return skip;
2033 }
2034
2035 // use a dynamic vector of bitsets as a memory-compact representation of which indices are included in the draw call
2036 // 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 +01002037 const size_t refs_per_bucket = 64;
2038 std::vector<std::bitset<refs_per_bucket>> vertex_reference_buckets;
2039
2040 const uint32_t n_indices = max_index - min_index + 1;
2041 const uint32_t n_buckets = (n_indices / static_cast<uint32_t>(refs_per_bucket)) +
2042 ((n_indices % static_cast<uint32_t>(refs_per_bucket)) != 0 ? 1 : 0);
2043
2044 // there needs to be at least one bitset to store a set of indices smaller than n_buckets
2045 vertex_reference_buckets.resize(std::max(1u, n_buckets));
Sam Walls8e77e4f2020-03-16 20:47:40 +00002046
2047 // To avoid using too much memory, we run over the indices again.
2048 // Knowing the size from the last scan allows us to record index usage with bitsets
2049 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
2050 uint32_t scan_index;
2051 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
2052 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
2053 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
2054 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
2055 } else {
2056 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
2057 }
2058 // keep track of the set of all indices used to reference vertices in the draw call
2059 size_t index_offset = scan_index - min_index;
Sam Walls61b06892020-07-23 16:20:50 +01002060 size_t bitset_bucket_index = index_offset / refs_per_bucket;
2061 uint64_t used_indices = 1ull << ((index_offset % refs_per_bucket) & 0xFFFFFFFFu);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002062 vertex_reference_buckets[bitset_bucket_index] |= used_indices;
2063 }
2064
2065 uint32_t vertex_reference_count = 0;
2066 for (const auto& bitset : vertex_reference_buckets) {
2067 vertex_reference_count += static_cast<uint32_t>(bitset.count());
2068 }
2069
2070 // low index buffer utilization implies that: of the vertices available to the draw call, not all are utilized
Mark Young0ec6b062020-11-19 15:32:17 -07002071 float utilization = static_cast<float>(vertex_reference_count) / static_cast<float>(max_index - min_index + 1);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002072 // low hit rate (high miss rate) implies the order of indices in the draw call may be possible to improve
Mark Young0ec6b062020-11-19 15:32:17 -07002073 float cache_hit_rate = static_cast<float>(vertex_reference_count) / static_cast<float>(vertex_shade_count);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002074
2075 if (utilization < 0.5f) {
2076 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
2077 "%s The indices which were specified for the draw call only utilise approximately "
2078 "%.02f%% of the bound vertex buffer.",
2079 VendorSpecificTag(kBPVendorArm), utilization);
2080 }
2081
2082 if (cache_hit_rate <= 0.5f) {
2083 skip |=
2084 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_PostTransformCacheThrashing,
2085 "%s The indices which were specified for the draw call are estimated to cause thrashing of "
2086 "the post-transform vertex cache, with a hit-rate of %.02f%%. "
2087 "I.e. the ordering of the index buffer may not make optimal use of indices associated with "
2088 "recently shaded vertices.",
2089 VendorSpecificTag(kBPVendorArm), cache_hit_rate * 100.0f);
2090 }
2091 }
2092
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002093 return skip;
2094}
2095
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002096bool BestPractices::PreCallValidateCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
2097 const VkCommandBuffer* pCommandBuffers) const {
2098 bool skip = false;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002099 const auto* primary = GetCBState(commandBuffer);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002100 for (uint32_t i = 0; i < commandBufferCount; i++) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002101 const auto* secondary_cb = GetCBState(pCommandBuffers[i]);
2102 if (secondary_cb == nullptr) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002103 continue;
2104 }
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002105 const auto& secondary = secondary_cb->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002106 for (auto& clear : secondary.earlyClearAttachments) {
Hans-Kristian Arntzenfa8ef9f2021-06-29 12:07:59 +02002107 if (ClearAttachmentsIsFullClear(primary, uint32_t(clear.rects.size()), clear.rects.data())) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002108 skip |= ValidateClearAttachment(commandBuffer, primary,
2109 clear.framebufferAttachment, clear.colorAttachment,
2110 clear.aspects, true);
2111 }
2112 }
2113 }
2114 return skip;
2115}
2116
2117void BestPractices::PreCallRecordCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
2118 const VkCommandBuffer* pCommandBuffers) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002119 auto* primary = GetCBState(commandBuffer);
2120 auto& primary_state = primary->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002121
2122 for (uint32_t i = 0; i < commandBufferCount; i++) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002123 auto* secondary_cb = GetCBState(pCommandBuffers[i]);
2124 if (secondary_cb == nullptr) {
2125 continue;
2126 }
2127 auto& secondary = secondary_cb->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002128
2129 for (auto& early_clear : secondary.earlyClearAttachments) {
Hans-Kristian Arntzenfa8ef9f2021-06-29 12:07:59 +02002130 if (ClearAttachmentsIsFullClear(primary, uint32_t(early_clear.rects.size()), early_clear.rects.data())) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002131 RecordAttachmentClearAttachments(primary, primary_state, early_clear.framebufferAttachment,
2132 early_clear.colorAttachment, early_clear.aspects,
Hans-Kristian Arntzenfa8ef9f2021-06-29 12:07:59 +02002133 uint32_t(early_clear.rects.size()), early_clear.rects.data());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002134 } else {
2135 RecordAttachmentAccess(primary_state, early_clear.framebufferAttachment,
2136 early_clear.aspects);
2137 }
2138 }
2139
2140 for (auto& touch : secondary.touchesAttachments) {
2141 RecordAttachmentAccess(primary_state, touch.framebufferAttachment,
2142 touch.aspects);
2143 }
Hans-Kristian Arntzenc7eb82a2021-06-16 13:57:18 +02002144
2145 primary_state.numDrawCallsDepthEqualCompare += secondary.numDrawCallsDepthEqualCompare;
2146 primary_state.numDrawCallsDepthOnly += secondary.numDrawCallsDepthOnly;
Hans-Kristian Arntzenaf81dca2021-06-18 11:14:28 +02002147
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002148 auto* second_state = GetCBState(pCommandBuffers[i]);
Hans-Kristian Arntzenaf81dca2021-06-18 11:14:28 +02002149 if (second_state->hasDrawCmd) {
2150 primary->hasDrawCmd = true;
2151 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002152 }
2153
2154 ValidationStateTracker::PreCallRecordCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
2155}
2156
2157void BestPractices::RecordAttachmentAccess(RenderPassState& state, uint32_t fb_attachment, VkImageAspectFlags aspects) {
2158 // Called when we have a partial clear attachment, or a normal draw call which accesses an attachment.
2159 auto itr = std::find_if(state.touchesAttachments.begin(), state.touchesAttachments.end(),
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002160 [&](const AttachmentInfo& info) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002161 return info.framebufferAttachment == fb_attachment;
2162 });
2163
2164 if (itr != state.touchesAttachments.end()) {
2165 itr->aspects |= aspects;
2166 } else {
2167 state.touchesAttachments.push_back({ fb_attachment, aspects });
2168 }
2169}
2170
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002171void BestPractices::RecordAttachmentClearAttachments(CMD_BUFFER_STATE_BP* cmd_state, RenderPassState& state, uint32_t fb_attachment,
2172 uint32_t color_attachment, VkImageAspectFlags aspects, uint32_t rectCount,
2173 const VkClearRect* pRects) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002174 // If we observe a full clear before any other access to a frame buffer attachment,
2175 // we have candidate for redundant clear attachments.
2176 auto itr = std::find_if(state.touchesAttachments.begin(), state.touchesAttachments.end(),
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002177 [&](const AttachmentInfo& info) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002178 return info.framebufferAttachment == fb_attachment;
2179 });
2180
2181 uint32_t new_aspects = aspects;
2182 if (itr != state.touchesAttachments.end()) {
2183 new_aspects = aspects & ~itr->aspects;
2184 itr->aspects |= aspects;
2185 } else {
2186 state.touchesAttachments.push_back({ fb_attachment, aspects });
2187 }
2188
2189 if (new_aspects == 0) {
2190 return;
2191 }
2192
2193 if (cmd_state->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
2194 // The first command might be a clear, but might not be the first in the render pass, defer any checks until
2195 // CmdExecuteCommands.
2196 state.earlyClearAttachments.push_back({ fb_attachment, color_attachment, new_aspects,
2197 std::vector<VkClearRect>{pRects, pRects + rectCount} });
2198 }
2199}
2200
2201void BestPractices::PreCallRecordCmdClearAttachments(VkCommandBuffer commandBuffer,
2202 uint32_t attachmentCount, const VkClearAttachment* pClearAttachments,
2203 uint32_t rectCount, const VkClearRect* pRects) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002204 auto* cmd_state = GetCBState(commandBuffer);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002205 RENDER_PASS_STATE* rp_state = cmd_state->activeRenderPass.get();
2206 FRAMEBUFFER_STATE* fb_state = cmd_state->activeFramebuffer.get();
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002207 RenderPassState& tracking_state = cmd_state->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002208 bool is_secondary = cmd_state->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY;
2209
2210 if (rectCount == 0 || !rp_state) {
2211 return;
2212 }
2213
2214 if (!is_secondary && !fb_state) {
2215 return;
2216 }
2217
2218 // If we have a rect which covers the entire frame buffer, we have a LOAD_OP_CLEAR-like command.
2219 bool full_clear = ClearAttachmentsIsFullClear(cmd_state, rectCount, pRects);
2220
2221 auto& subpass = rp_state->createInfo.pSubpasses[cmd_state->activeSubpass];
2222 for (uint32_t i = 0; i < attachmentCount; i++) {
2223 auto& attachment = pClearAttachments[i];
2224 uint32_t fb_attachment = VK_ATTACHMENT_UNUSED;
2225 VkImageAspectFlags aspects = attachment.aspectMask;
2226
2227 if (aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) {
2228 if (subpass.pDepthStencilAttachment) {
2229 fb_attachment = subpass.pDepthStencilAttachment->attachment;
2230 }
2231 } else if (aspects & VK_IMAGE_ASPECT_COLOR_BIT) {
2232 fb_attachment = subpass.pColorAttachments[attachment.colorAttachment].attachment;
2233 }
2234
2235 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2236 if (full_clear) {
2237 RecordAttachmentClearAttachments(cmd_state, tracking_state,
2238 fb_attachment, attachment.colorAttachment, aspects,
2239 rectCount, pRects);
2240 } else {
2241 RecordAttachmentAccess(tracking_state, fb_attachment, aspects);
2242 }
2243 }
2244 }
2245
2246 ValidationStateTracker::PreCallRecordCmdClearAttachments(commandBuffer, attachmentCount, pClearAttachments,
2247 rectCount, pRects);
2248}
2249
Attilio Provenzano02859b22020-02-27 14:17:28 +00002250void BestPractices::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
2251 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
2252 ValidationStateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset,
2253 firstInstance);
2254
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002255 auto* cmd_state = GetCBState(commandBuffer);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002256 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices) {
2257 cmd_state->small_indexed_draw_call_count++;
2258 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002259
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002260 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDrawIndexed()");
Attilio Provenzano02859b22020-02-27 14:17:28 +00002261}
2262
Sam Walls0961ec02020-03-31 16:39:15 +01002263void BestPractices::PostCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
2264 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
2265 StateTracker::PostCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
2266 RecordCmdDrawType(commandBuffer, indexCount * instanceCount, "vkCmdDrawIndexed()");
2267}
2268
sfricke-samsung681ab7b2020-10-29 01:53:35 -07002269bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2270 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
2271 uint32_t maxDrawCount, uint32_t stride) const {
2272 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCount()");
2273
2274 return skip;
2275}
2276
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002277bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
2278 VkDeviceSize offset, VkBuffer countBuffer,
2279 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
2280 uint32_t stride) const {
2281 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCountKHR()");
Camden5b184be2019-08-13 07:50:19 -06002282
2283 return skip;
2284}
2285
2286bool BestPractices::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002287 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06002288 bool skip = false;
2289
2290 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002291 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
2292 "Warning: You are calling vkCmdDrawIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002293 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirect()");
Camden5b184be2019-08-13 07:50:19 -06002294 }
2295
2296 return skip;
2297}
2298
Sam Walls0961ec02020-03-31 16:39:15 +01002299void BestPractices::PostCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2300 uint32_t count, uint32_t stride) {
2301 StateTracker::PostCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, count, stride);
2302 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndirect()");
2303}
2304
Camden5b184be2019-08-13 07:50:19 -06002305bool BestPractices::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002306 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06002307 bool skip = false;
2308
2309 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002310 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
2311 "Warning: You are calling vkCmdDrawIndexedIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002312 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirect()");
Camden5b184be2019-08-13 07:50:19 -06002313 }
2314
2315 return skip;
2316}
2317
Sam Walls0961ec02020-03-31 16:39:15 +01002318void BestPractices::PostCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2319 uint32_t count, uint32_t stride) {
2320 StateTracker::PostCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, count, stride);
2321 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndexedIndirect()");
2322}
2323
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002324void BestPractices::ValidateBoundDescriptorSets(VkCommandBuffer commandBuffer, const char* function_name) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002325 auto* cb_state = GetCBState(commandBuffer);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002326
2327 if (cb_state) {
2328 for (auto descriptor_set : cb_state->validated_descriptor_sets) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002329 const auto& layout = *descriptor_set->GetLayout();
Hans-Kristian Arntzena8199012021-03-22 12:10:07 +01002330
2331 for (uint32_t index = 0; index < descriptor_set->GetBindingCount(); ++index) {
2332 // For bindless scenarios, we should not attempt to track descriptor set state.
2333 // It is highly uncertain which resources are actually bound.
2334 // Resources which are written to such a descriptor should be marked as indeterminate w.r.t. state.
2335 VkDescriptorBindingFlags flags = layout.GetDescriptorBindingFlagsFromIndex(index);
2336 if (flags & (VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT |
2337 VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT |
2338 VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT)) {
2339 continue;
2340 }
2341
2342 auto index_range = layout.GetGlobalIndexRangeFromIndex(index);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002343 for (uint32_t i = index_range.start; i < index_range.end; ++i) {
ZandroFargnoliacf12f02020-06-18 16:50:00 +01002344 VkImageView image_view{VK_NULL_HANDLE};
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002345
2346 auto descriptor = descriptor_set->GetDescriptorFromGlobalIndex(i);
2347 switch (descriptor->GetClass()) {
2348 case cvdescriptorset::DescriptorClass::Image: {
2349 if (const auto image_descriptor = static_cast<const cvdescriptorset::ImageDescriptor*>(descriptor)) {
2350 image_view = image_descriptor->GetImageView();
2351 }
Hans-Kristian Arntzenbc3a6152021-03-22 13:05:43 +01002352 break;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002353 }
2354 case cvdescriptorset::DescriptorClass::ImageSampler: {
2355 if (const auto image_sampler_descriptor =
2356 static_cast<const cvdescriptorset::ImageSamplerDescriptor*>(descriptor)) {
2357 image_view = image_sampler_descriptor->GetImageView();
2358 }
Hans-Kristian Arntzenbc3a6152021-03-22 13:05:43 +01002359 break;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002360 }
ZandroFargnoliacf12f02020-06-18 16:50:00 +01002361 default:
Hans-Kristian Arntzenbc3a6152021-03-22 13:05:43 +01002362 break;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002363 }
2364
2365 if (image_view) {
2366 IMAGE_VIEW_STATE* image_view_state = GetImageViewState(image_view);
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002367 QueueValidateImageView(cb_state->queue_submit_functions, function_name,
2368 image_view_state, IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002369 }
2370 }
2371 }
2372 }
2373 }
2374}
2375
2376void BestPractices::PreCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
2377 uint32_t firstVertex, uint32_t firstInstance) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002378 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDraw()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002379}
2380
2381void BestPractices::PreCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2382 uint32_t drawCount, uint32_t stride) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002383 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDrawIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002384}
2385
2386void BestPractices::PreCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2387 uint32_t drawCount, uint32_t stride) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002388 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDrawIndexedIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002389}
2390
Camden5b184be2019-08-13 07:50:19 -06002391bool BestPractices::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t groupCountX, uint32_t groupCountY,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002392 uint32_t groupCountZ) const {
Camden5b184be2019-08-13 07:50:19 -06002393 bool skip = false;
2394
2395 if ((groupCountX == 0) || (groupCountY == 0) || (groupCountZ == 0)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002396 skip |= LogWarning(device, kVUID_BestPractices_CmdDispatch_GroupCountZero,
2397 "Warning: You are calling vkCmdDispatch() while one or more groupCounts are zero (groupCountX = %" PRIu32
2398 ", groupCountY = %" PRIu32 ", groupCountZ = %" PRIu32 ").",
2399 groupCountX, groupCountY, groupCountZ);
Camden5b184be2019-08-13 07:50:19 -06002400 }
2401
2402 return skip;
2403}
Camden83a9c372019-08-14 11:41:38 -06002404
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002405bool BestPractices::PreCallValidateCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo* pSubpassEndInfo) const {
2406 bool skip = false;
2407 skip |= StateTracker::PreCallValidateCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
2408 skip |= ValidateCmdEndRenderPass(commandBuffer);
2409 return skip;
2410}
2411
2412bool BestPractices::PreCallValidateCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfo* pSubpassEndInfo) const {
2413 bool skip = false;
2414 skip |= StateTracker::PreCallValidateCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
2415 skip |= ValidateCmdEndRenderPass(commandBuffer);
2416 return skip;
2417}
2418
Sam Walls0961ec02020-03-31 16:39:15 +01002419bool BestPractices::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
2420 bool skip = false;
Sam Walls0961ec02020-03-31 16:39:15 +01002421 skip |= StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002422 skip |= ValidateCmdEndRenderPass(commandBuffer);
2423 return skip;
2424}
2425
2426bool BestPractices::ValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
2427 bool skip = false;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002428 const auto* cmd = GetCBState(commandBuffer);
Sam Walls0961ec02020-03-31 16:39:15 +01002429
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002430 if (cmd == nullptr) return skip;
2431 auto &render_pass_state = cmd->render_pass_state;
Sam Walls0961ec02020-03-31 16:39:15 +01002432
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002433 bool uses_depth = (render_pass_state.depthAttachment || render_pass_state.colorAttachment) &&
2434 render_pass_state.numDrawCallsDepthEqualCompare >= kDepthPrePassNumDrawCallsArm &&
2435 render_pass_state.numDrawCallsDepthOnly >= kDepthPrePassNumDrawCallsArm;
Sam Walls0961ec02020-03-31 16:39:15 +01002436 if (uses_depth) {
2437 skip |= LogPerformanceWarning(
2438 device, kVUID_BestPractices_EndRenderPass_DepthPrePassUsage,
2439 "%s Depth pre-passes may be in use. In general, this is not recommended, as in Arm Mali GPUs since "
2440 "Mali-T620, Forward Pixel Killing (FPK) can already perform automatic hidden surface removal; in which "
2441 "case, using depth pre-passes for hidden surface removal may worsen performance.",
2442 VendorSpecificTag(kBPVendorArm));
2443 }
2444
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002445 RENDER_PASS_STATE* rp = cmd->activeRenderPass.get();
2446
2447 if (VendorCheckEnabled(kBPVendorArm) && rp) {
2448
2449 // If we use an attachment on-tile, we should access it in some way. Otherwise,
2450 // it is redundant to have it be part of the render pass.
2451 // Only consider it redundant if it will actually consume bandwidth, i.e.
2452 // LOAD_OP_LOAD is used or STORE_OP_STORE. CLEAR -> DONT_CARE is benign,
2453 // as is using pure input attachments.
2454 // CLEAR -> STORE might be considered a "useful" thing to do, but
2455 // the optimal thing to do is to defer the clear until you're actually
2456 // going to render to the image.
2457
2458 uint32_t num_attachments = rp->createInfo.attachmentCount;
2459 for (uint32_t i = 0; i < num_attachments; i++) {
Hans-Kristian Arntzen237663c2021-07-01 14:36:40 +02002460 if (!RenderPassUsesAttachmentOnTile(rp->createInfo, i) ||
2461 RenderPassUsesAttachmentAsResolve(rp->createInfo, i)) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002462 continue;
2463 }
2464
2465 auto& attachment = rp->createInfo.pAttachments[i];
2466
2467 VkImageAspectFlags bandwidth_aspects = 0;
2468
2469 if (!FormatIsStencilOnly(attachment.format) &&
2470 (attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
2471 attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE)) {
2472 if (FormatHasDepth(attachment.format)) {
2473 bandwidth_aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
2474 } else {
2475 bandwidth_aspects |= VK_IMAGE_ASPECT_COLOR_BIT;
2476 }
2477 }
2478
2479 if (FormatHasStencil(attachment.format) &&
2480 (attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
2481 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE)) {
2482 bandwidth_aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
2483 }
2484
2485 if (!bandwidth_aspects) {
2486 continue;
2487 }
2488
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002489 auto itr = std::find_if(render_pass_state.touchesAttachments.begin(), render_pass_state.touchesAttachments.end(),
2490 [&](const AttachmentInfo& info) { return info.framebufferAttachment == i; });
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002491 uint32_t untouched_aspects = bandwidth_aspects;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002492 if (itr != render_pass_state.touchesAttachments.end()) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002493 untouched_aspects &= ~itr->aspects;
2494 }
2495
2496 if (untouched_aspects) {
2497 skip |= LogPerformanceWarning(
2498 device, kVUID_BestPractices_EndRenderPass_RedundantAttachmentOnTile,
2499 "%s Render pass was ended, but attachment #%u (format: %u, untouched aspects 0x%x) "
2500 "was never accessed by a pipeline or clear command. "
2501 "On tile-based architectures, LOAD_OP_LOAD and STORE_OP_STORE consume bandwidth and should not be part of the render pass "
2502 "if the attachments are not intended to be accessed.",
2503 VendorSpecificTag(kBPVendorArm), i, attachment.format, untouched_aspects);
2504 }
2505 }
2506 }
2507
Sam Walls0961ec02020-03-31 16:39:15 +01002508 return skip;
2509}
2510
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002511void BestPractices::PreCallRecordCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002512 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDispatch()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002513}
2514
2515void BestPractices::PreCallRecordCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002516 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDispatchIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002517}
2518
Camden Stocker9c051442019-11-06 14:28:43 -08002519bool BestPractices::ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(VkPhysicalDevice physicalDevice,
2520 const char* api_name) const {
2521 bool skip = false;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002522 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
Camden Stocker9c051442019-11-06 14:28:43 -08002523
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002524 if (bp_pd_state) {
2525 if (bp_pd_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState == UNCALLED) {
2526 skip |= LogWarning(physicalDevice, kVUID_BestPractices_DisplayPlane_PropertiesNotCalled,
2527 "Potential problem with calling %s() without first retrieving properties from "
2528 "vkGetPhysicalDeviceDisplayPlanePropertiesKHR or vkGetPhysicalDeviceDisplayPlaneProperties2KHR.",
2529 api_name);
2530 }
Camden Stocker9c051442019-11-06 14:28:43 -08002531 }
2532
2533 return skip;
2534}
2535
Camden83a9c372019-08-14 11:41:38 -06002536bool BestPractices::PreCallValidateGetDisplayPlaneSupportedDisplaysKHR(VkPhysicalDevice physicalDevice, uint32_t planeIndex,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002537 uint32_t* pDisplayCount, VkDisplayKHR* pDisplays) const {
Camden83a9c372019-08-14 11:41:38 -06002538 bool skip = false;
2539
Camden Stocker9c051442019-11-06 14:28:43 -08002540 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneSupportedDisplaysKHR");
Camden83a9c372019-08-14 11:41:38 -06002541
Camden Stocker9c051442019-11-06 14:28:43 -08002542 return skip;
2543}
2544
2545bool BestPractices::PreCallValidateGetDisplayPlaneCapabilitiesKHR(VkPhysicalDevice physicalDevice, VkDisplayModeKHR mode,
2546 uint32_t planeIndex,
2547 VkDisplayPlaneCapabilitiesKHR* pCapabilities) const {
2548 bool skip = false;
2549
2550 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilitiesKHR");
2551
2552 return skip;
2553}
2554
2555bool BestPractices::PreCallValidateGetDisplayPlaneCapabilities2KHR(VkPhysicalDevice physicalDevice,
2556 const VkDisplayPlaneInfo2KHR* pDisplayPlaneInfo,
2557 VkDisplayPlaneCapabilities2KHR* pCapabilities) const {
2558 bool skip = false;
2559
2560 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilities2KHR");
Camden83a9c372019-08-14 11:41:38 -06002561
2562 return skip;
2563}
Camden05de2d42019-08-19 10:23:56 -06002564
2565bool BestPractices::PreCallValidateGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain, uint32_t* pSwapchainImageCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002566 VkImage* pSwapchainImages) const {
Camden05de2d42019-08-19 10:23:56 -06002567 bool skip = false;
2568
Nathaniel Cesario39152e62021-07-02 13:04:16 -06002569 const auto* swapchain_state = static_cast<SWAPCHAIN_STATE_BP*>(Get<SWAPCHAIN_NODE>(swapchain));
Camden05de2d42019-08-19 10:23:56 -06002570
Nathaniel Cesario39152e62021-07-02 13:04:16 -06002571 if (swapchain_state && pSwapchainImages) {
Camden05de2d42019-08-19 10:23:56 -06002572 // Compare the preliminary value of *pSwapchainImageCount with the value this time:
Nathaniel Cesario39152e62021-07-02 13:04:16 -06002573 if (swapchain_state->vkGetSwapchainImagesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002574 skip |=
2575 LogWarning(device, kVUID_Core_Swapchain_PriorCount,
2576 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImageCount; but no prior positive value has "
2577 "been seen for pSwapchainImages.");
Camden05de2d42019-08-19 10:23:56 -06002578 }
Camden05de2d42019-08-19 10:23:56 -06002579
Nathaniel Cesario4ce98382021-05-28 11:33:20 -06002580 if (*pSwapchainImageCount > swapchain_state->get_swapchain_image_count) {
2581 skip |= LogWarning(
2582 device, kVUID_BestPractices_Swapchain_InvalidCount,
2583 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImages, and with pSwapchainImageCount set to a "
2584 "value (%d) that is greater than the value (%d) that was returned when pSwapchainImages was NULL.",
2585 *pSwapchainImageCount, swapchain_state->get_swapchain_image_count);
2586 }
2587 }
2588
Camden05de2d42019-08-19 10:23:56 -06002589 return skip;
2590}
2591
2592// Common function to handle validation for GetPhysicalDeviceQueueFamilyProperties & 2KHR version
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002593bool BestPractices::ValidateCommonGetPhysicalDeviceQueueFamilyProperties(const PHYSICAL_DEVICE_STATE* pd_state,
2594 uint32_t requested_queue_family_property_count,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002595 const CALL_STATE call_state,
2596 const char* caller_name) const {
Camden05de2d42019-08-19 10:23:56 -06002597 bool skip = false;
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002598 // Verify that for each physical device, this command is called first with NULL pQueueFamilyProperties in order to get count
2599 if (UNCALLED == call_state) {
2600 skip |= LogWarning(
2601 pd_state->phys_device, kVUID_Core_DevLimit_MissingQueryCount,
2602 "%s is called with non-NULL pQueueFamilyProperties before obtaining pQueueFamilyPropertyCount. It is "
2603 "recommended "
2604 "to first call %s with NULL pQueueFamilyProperties in order to obtain the maximal pQueueFamilyPropertyCount.",
2605 caller_name, caller_name);
2606 // Then verify that pCount that is passed in on second call matches what was returned
2607 } else if (pd_state->queue_family_known_count != requested_queue_family_property_count) {
2608 skip |= LogWarning(pd_state->phys_device, kVUID_Core_DevLimit_CountMismatch,
2609 "%s is called with non-NULL pQueueFamilyProperties and pQueueFamilyPropertyCount value %" PRIu32
2610 ", but the largest previously returned pQueueFamilyPropertyCount for this physicalDevice is %" PRIu32
2611 ". It is recommended to instead receive all the properties by calling %s with "
2612 "pQueueFamilyPropertyCount that was "
2613 "previously obtained by calling %s with NULL pQueueFamilyProperties.",
2614 caller_name, requested_queue_family_property_count, pd_state->queue_family_known_count, caller_name,
2615 caller_name);
Camden05de2d42019-08-19 10:23:56 -06002616 }
2617
2618 return skip;
2619}
2620
Jeff Bolz5c801d12019-10-09 10:38:45 -05002621bool BestPractices::PreCallValidateBindAccelerationStructureMemoryNV(
2622 VkDevice device, uint32_t bindInfoCount, const VkBindAccelerationStructureMemoryInfoNV* pBindInfos) const {
Camden Stocker82510582019-09-03 14:00:16 -06002623 bool skip = false;
2624
2625 for (uint32_t i = 0; i < bindInfoCount; i++) {
sourav parmarcd5fb182020-07-17 12:58:44 -07002626 const ACCELERATION_STRUCTURE_STATE* as_state = GetAccelerationStructureStateNV(pBindInfos[i].accelerationStructure);
Camden Stocker82510582019-09-03 14:00:16 -06002627 if (!as_state->memory_requirements_checked) {
2628 // There's not an explicit requirement in the spec to call vkGetImageMemoryRequirements() prior to calling
2629 // BindAccelerationStructureMemoryNV but it's implied in that memory being bound must conform with
2630 // VkAccelerationStructureMemoryRequirementsInfoNV from vkGetAccelerationStructureMemoryRequirementsNV
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002631 skip |= LogWarning(
2632 device, kVUID_BestPractices_BindAccelNV_NoMemReqQuery,
Camden Stocker82510582019-09-03 14:00:16 -06002633 "vkBindAccelerationStructureMemoryNV(): "
2634 "Binding memory to %s but vkGetAccelerationStructureMemoryRequirementsNV() has not been called on that structure.",
2635 report_data->FormatHandle(pBindInfos[i].accelerationStructure).c_str());
2636 }
2637 }
2638
2639 return skip;
2640}
2641
Camden05de2d42019-08-19 10:23:56 -06002642bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
2643 uint32_t* pQueueFamilyPropertyCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002644 VkQueueFamilyProperties* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06002645 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
2646 assert(physical_device_state);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002647 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physical_device_state->phys_device);
2648 if (pQueueFamilyProperties && bp_pd_state) {
2649 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
2650 bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
2651 "vkGetPhysicalDeviceQueueFamilyProperties()");
2652 }
2653 return false;
Camden05de2d42019-08-19 10:23:56 -06002654}
2655
Mike Schuchardt2df08912020-12-15 16:28:09 -08002656bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
2657 uint32_t* pQueueFamilyPropertyCount,
2658 VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06002659 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
2660 assert(physical_device_state);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002661 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physical_device_state->phys_device);
2662 if (pQueueFamilyProperties && bp_pd_state) {
2663 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
2664 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
2665 "vkGetPhysicalDeviceQueueFamilyProperties2()");
2666 }
2667 return false;
Camden05de2d42019-08-19 10:23:56 -06002668}
2669
Jeff Bolz5c801d12019-10-09 10:38:45 -05002670bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2KHR(
Mike Schuchardt2df08912020-12-15 16:28:09 -08002671 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount, VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06002672 auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
2673 assert(physical_device_state);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002674 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physical_device_state->phys_device);
2675 if (pQueueFamilyProperties && bp_pd_state) {
2676 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
2677 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
2678 "vkGetPhysicalDeviceQueueFamilyProperties2KHR()");
2679 }
2680 return false;
Camden05de2d42019-08-19 10:23:56 -06002681}
2682
2683bool BestPractices::PreCallValidateGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
2684 uint32_t* pSurfaceFormatCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002685 VkSurfaceFormatKHR* pSurfaceFormats) const {
Camden05de2d42019-08-19 10:23:56 -06002686 if (!pSurfaceFormats) return false;
2687 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002688 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2689 const auto& call_state = bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState;
Camden05de2d42019-08-19 10:23:56 -06002690 bool skip = false;
2691 if (call_state == UNCALLED) {
2692 // Since we haven't recorded a preliminary value of *pSurfaceFormatCount, that likely means that the application didn't
2693 // previously call this function with a NULL value of pSurfaceFormats:
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002694 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_MustQueryCount,
2695 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount; but no prior "
2696 "positive value has been seen for pSurfaceFormats.");
Camden05de2d42019-08-19 10:23:56 -06002697 } else {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002698 auto prev_format_count = static_cast<uint32_t>(physical_device_state->surface_formats.size());
Peter Chene191bd72019-09-16 13:04:37 -04002699 if (*pSurfaceFormatCount > prev_format_count) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002700 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_CountMismatch,
2701 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount, and with "
2702 "pSurfaceFormats set to a value (%u) that is greater than the value (%u) that was returned "
2703 "when pSurfaceFormatCount was NULL.",
2704 *pSurfaceFormatCount, prev_format_count);
Camden05de2d42019-08-19 10:23:56 -06002705 }
2706 }
2707 return skip;
2708}
Camden Stocker23cc47d2019-09-03 14:53:57 -06002709
2710bool BestPractices::PreCallValidateQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002711 VkFence fence) const {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002712 bool skip = false;
2713
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002714 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
2715 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
Camden Stocker23cc47d2019-09-03 14:53:57 -06002716 // Store sparse binding image_state and after binding is complete make sure that any requiring metadata have it bound
Jeremy Gebbencbf22862021-03-03 12:01:22 -07002717 layer_data::unordered_set<const IMAGE_STATE*> sparse_images;
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002718 // Track images getting metadata bound by this call in a set, it'll be recorded into the image_state
2719 // in RecordQueueBindSparse.
Jeremy Gebbencbf22862021-03-03 12:01:22 -07002720 layer_data::unordered_set<const IMAGE_STATE*> sparse_images_with_metadata;
Camden Stocker23cc47d2019-09-03 14:53:57 -06002721 // If we're binding sparse image memory make sure reqs were queried and note if metadata is required and bound
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002722 for (uint32_t i = 0; i < bind_info.imageBindCount; ++i) {
2723 const auto& image_bind = bind_info.pImageBinds[i];
Camden Stocker23cc47d2019-09-03 14:53:57 -06002724 auto image_state = GetImageState(image_bind.image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002725 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002726 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002727 }
Camden Stocker23cc47d2019-09-03 14:53:57 -06002728 sparse_images.insert(image_state);
2729 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
2730 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
2731 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002732 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002733 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
2734 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002735 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002736 }
2737 }
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06002738 if (!image_state->memory_requirements_checked[0]) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002739 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002740 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002741 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
2742 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002743 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002744 }
2745 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002746 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
2747 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
2748 auto image_state = GetImageState(bind_info.pImageOpaqueBinds[i].image);
2749 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002750 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002751 }
Camden Stocker23cc47d2019-09-03 14:53:57 -06002752 sparse_images.insert(image_state);
2753 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
2754 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
2755 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002756 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002757 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
2758 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002759 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002760 }
2761 }
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06002762 if (!image_state->memory_requirements_checked[0]) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002763 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002764 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002765 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
2766 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002767 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002768 }
2769 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
2770 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002771 sparse_images_with_metadata.insert(image_state);
Camden Stocker23cc47d2019-09-03 14:53:57 -06002772 }
2773 }
2774 }
2775 for (const auto& sparse_image_state : sparse_images) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002776 if (sparse_image_state->sparse_metadata_required && !sparse_image_state->sparse_metadata_bound &&
2777 sparse_images_with_metadata.find(sparse_image_state) == sparse_images_with_metadata.end()) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002778 // Warn if sparse image binding metadata required for image with sparse binding, but metadata not bound
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002779 skip |= LogWarning(sparse_image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002780 "vkQueueBindSparse(): Binding sparse memory to %s which requires a metadata aspect but no "
2781 "binding with VK_SPARSE_MEMORY_BIND_METADATA_BIT set was made.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002782 report_data->FormatHandle(sparse_image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002783 }
2784 }
2785 }
2786
2787 return skip;
2788}
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002789
Mark Lobodzinski84101d72020-04-24 09:43:48 -06002790void BestPractices::ManualPostCallRecordQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
2791 VkFence fence, VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07002792 if (result != VK_SUCCESS) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07002793 return;
2794 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002795
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002796 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
2797 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
2798 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
2799 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
2800 auto image_state = GetImageState(bind_info.pImageOpaqueBinds[i].image);
2801 if (!image_state) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002802 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002803 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002804 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
2805 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
2806 image_state->sparse_metadata_bound = true;
2807 }
2808 }
2809 }
2810 }
2811}
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002812
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002813bool BestPractices::ClearAttachmentsIsFullClear(const CMD_BUFFER_STATE_BP* cmd, uint32_t rectCount,
2814 const VkClearRect* pRects) const {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002815 if (cmd->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
2816 // We don't know the accurate render area in a secondary,
2817 // so assume we clear the entire frame buffer.
2818 // This is resolved in CmdExecuteCommands where we can check if the clear is a full clear.
2819 return true;
2820 }
2821
2822 // If we have a rect which covers the entire frame buffer, we have a LOAD_OP_CLEAR-like command.
2823 for (uint32_t i = 0; i < rectCount; i++) {
2824 auto& rect = pRects[i];
2825 auto& render_area = cmd->activeRenderPassBeginInfo.renderArea;
2826 if (rect.rect.extent.width == render_area.extent.width && rect.rect.extent.height == render_area.extent.height) {
2827 return true;
2828 }
2829 }
2830
2831 return false;
2832}
2833
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002834bool BestPractices::ValidateClearAttachment(VkCommandBuffer commandBuffer, const CMD_BUFFER_STATE_BP* cmd, uint32_t fb_attachment,
2835 uint32_t color_attachment, VkImageAspectFlags aspects, bool secondary) const {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002836 const RENDER_PASS_STATE* rp = cmd->activeRenderPass.get();
2837 bool skip = false;
2838
2839 if (!rp || fb_attachment == VK_ATTACHMENT_UNUSED) {
2840 return skip;
2841 }
2842
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002843 const auto& rp_state = cmd->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002844
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002845 auto attachment_itr = std::find_if(rp_state.touchesAttachments.begin(), rp_state.touchesAttachments.end(),
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002846 [&](const AttachmentInfo& info) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002847 return info.framebufferAttachment == fb_attachment;
2848 });
2849
2850 // Only report aspects which haven't been touched yet.
2851 VkImageAspectFlags new_aspects = aspects;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002852 if (attachment_itr != rp_state.touchesAttachments.end()) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002853 new_aspects &= ~attachment_itr->aspects;
2854 }
2855
2856 // Warn if this is issued prior to Draw Cmd and clearing the entire attachment
2857 if (!cmd->hasDrawCmd) {
2858 skip |= LogPerformanceWarning(
2859 commandBuffer, kVUID_BestPractices_DrawState_ClearCmdBeforeDraw,
Hans-Kristian Arntzen4ddd6182021-06-18 12:16:33 +02002860 "vkCmdClearAttachments() issued on %s prior to any Draw Cmds in current render pass. It is recommended you "
2861 "use RenderPass LOAD_OP_CLEAR on attachments instead.",
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002862 report_data->FormatHandle(commandBuffer).c_str());
2863 }
2864
2865 if ((new_aspects & VK_IMAGE_ASPECT_COLOR_BIT) &&
2866 rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2867 skip |= LogPerformanceWarning(
2868 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2869 "%svkCmdClearAttachments() issued on %s for color attachment #%u in this subpass, "
2870 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2871 "it is more efficient.",
2872 secondary ? "vkCmdExecuteCommands(): " : "",
2873 report_data->FormatHandle(commandBuffer).c_str(), color_attachment);
2874 }
2875
2876 if ((new_aspects & VK_IMAGE_ASPECT_DEPTH_BIT) &&
2877 rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2878 skip |= LogPerformanceWarning(
2879 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2880 "%svkCmdClearAttachments() issued on %s for the depth attachment in this subpass, "
2881 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2882 "it is more efficient.",
2883 secondary ? "vkCmdExecuteCommands(): " : "",
2884 report_data->FormatHandle(commandBuffer).c_str());
2885 }
2886
2887 if ((new_aspects & VK_IMAGE_ASPECT_STENCIL_BIT) &&
2888 rp->createInfo.pAttachments[fb_attachment].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2889 skip |= LogPerformanceWarning(
2890 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2891 "%svkCmdClearAttachments() issued on %s for the stencil attachment in this subpass, "
2892 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2893 "it is more efficient.",
2894 secondary ? "vkCmdExecuteCommands(): " : "",
2895 report_data->FormatHandle(commandBuffer).c_str());
2896 }
2897
2898 return skip;
2899}
2900
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002901bool BestPractices::PreCallValidateCmdClearAttachments(VkCommandBuffer commandBuffer, uint32_t attachmentCount,
Camden Stockerf55721f2019-09-09 11:04:49 -06002902 const VkClearAttachment* pAttachments, uint32_t rectCount,
2903 const VkClearRect* pRects) const {
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002904 bool skip = false;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002905 const auto* cb_node = GetCBState(commandBuffer);
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002906 if (!cb_node) return skip;
2907
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002908 if (cb_node->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
2909 // Defer checks to ExecuteCommands.
2910 return skip;
2911 }
2912
2913 // Only care about full clears, partial clears might have legitimate uses.
2914 if (!ClearAttachmentsIsFullClear(cb_node, rectCount, pRects)) {
2915 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002916 }
2917
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002918 // Check for uses of ClearAttachments along with LOAD_OP_LOAD,
2919 // as it can be more efficient to just use LOAD_OP_CLEAR
locke-lunargaecf2152020-05-12 17:15:41 -06002920 const RENDER_PASS_STATE* rp = cb_node->activeRenderPass.get();
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002921 if (rp) {
2922 const auto& subpass = rp->createInfo.pSubpasses[cb_node->activeSubpass];
2923
2924 for (uint32_t i = 0; i < attachmentCount; i++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002925 const auto& attachment = pAttachments[i];
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002926
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002927 if (attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
2928 uint32_t color_attachment = attachment.colorAttachment;
2929 uint32_t fb_attachment = subpass.pColorAttachments[color_attachment].attachment;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002930 skip |= ValidateClearAttachment(commandBuffer, cb_node,
2931 fb_attachment, color_attachment,
2932 attachment.aspectMask, false);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002933 }
2934
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002935 if (subpass.pDepthStencilAttachment &&
2936 (attachment.aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT))) {
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002937 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002938 skip |= ValidateClearAttachment(commandBuffer, cb_node,
2939 fb_attachment, VK_ATTACHMENT_UNUSED,
2940 attachment.aspectMask, false);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002941 }
2942 }
2943 }
2944
Camden Stockerf55721f2019-09-09 11:04:49 -06002945 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002946}
Attilio Provenzano02859b22020-02-27 14:17:28 +00002947
2948bool BestPractices::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
2949 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
2950 const VkImageResolve* pRegions) const {
2951 bool skip = false;
2952
2953 skip |= VendorCheckEnabled(kBPVendorArm) &&
2954 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage_ResolvingImage,
2955 "%s Attempting to use vkCmdResolveImage to resolve a multisampled image. "
2956 "This is a very slow and extremely bandwidth intensive path. "
2957 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
2958 VendorSpecificTag(kBPVendorArm));
2959
2960 return skip;
2961}
2962
Jeff Leger178b1e52020-10-05 12:22:23 -04002963bool BestPractices::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
2964 const VkResolveImageInfo2KHR* pResolveImageInfo) const {
2965 bool skip = false;
2966
2967 skip |= VendorCheckEnabled(kBPVendorArm) &&
2968 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2KHR_ResolvingImage,
2969 "%s Attempting to use vkCmdResolveImage2KHR to resolve a multisampled image. "
2970 "This is a very slow and extremely bandwidth intensive path. "
2971 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
2972 VendorSpecificTag(kBPVendorArm));
2973
2974 return skip;
2975}
2976
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002977void BestPractices::PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
2978 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
2979 const VkImageResolve* pRegions) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002980 auto* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002981 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002982 auto* src = GetImageUsageState(srcImage);
2983 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002984
2985 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002986 QueueValidateImage(funcs, "vkCmdResolveImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pRegions[i].srcSubresource);
2987 QueueValidateImage(funcs, "vkCmdResolveImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002988 }
2989}
2990
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01002991void BestPractices::PreCallRecordCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
2992 const VkResolveImageInfo2KHR* pResolveImageInfo) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002993 auto* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002994 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002995 auto* src = GetImageUsageState(pResolveImageInfo->srcImage);
2996 auto* dst = GetImageUsageState(pResolveImageInfo->dstImage);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01002997 uint32_t regionCount = pResolveImageInfo->regionCount;
2998
2999 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003000 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pResolveImageInfo->pRegions[i].srcSubresource);
3001 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pResolveImageInfo->pRegions[i].dstSubresource);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01003002 }
3003}
3004
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003005void BestPractices::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
3006 const VkClearColorValue* pColor, uint32_t rangeCount,
3007 const VkImageSubresourceRange* pRanges) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003008 auto* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003009 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003010 auto* dst = GetImageUsageState(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003011
3012 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003013 QueueValidateImage(funcs, "vkCmdClearColorImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003014 }
3015}
3016
3017void BestPractices::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
3018 const VkClearDepthStencilValue* pDepthStencil, uint32_t rangeCount,
3019 const VkImageSubresourceRange* pRanges) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003020 auto* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003021 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003022 auto* dst = GetImageUsageState(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003023
3024 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003025 QueueValidateImage(funcs, "vkCmdClearDepthStencilImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003026 }
3027}
3028
3029void BestPractices::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3030 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3031 const VkImageCopy* pRegions) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003032 auto* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003033 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003034 auto* src = GetImageUsageState(srcImage);
3035 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003036
3037 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003038 QueueValidateImage(funcs, "vkCmdCopyImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].srcSubresource);
3039 QueueValidateImage(funcs, "vkCmdCopyImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003040 }
3041}
3042
3043void BestPractices::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
3044 VkImageLayout dstImageLayout, uint32_t regionCount,
3045 const VkBufferImageCopy* pRegions) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003046 auto* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003047 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003048 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003049
3050 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003051 QueueValidateImage(funcs, "vkCmdCopyBufferToImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003052 }
3053}
3054
3055void BestPractices::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3056 VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy* pRegions) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003057 auto* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003058 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003059 auto* src = GetImageUsageState(srcImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003060
3061 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003062 QueueValidateImage(funcs, "vkCmdCopyImageToBuffer()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003063 }
3064}
3065
3066void BestPractices::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3067 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3068 const VkImageBlit* pRegions, VkFilter filter) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003069 auto* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003070 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003071 auto* src = GetImageUsageState(srcImage);
3072 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003073
3074 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003075 QueueValidateImage(funcs, "vkCmdBlitImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_READ, pRegions[i].srcSubresource);
3076 QueueValidateImage(funcs, "vkCmdBlitImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003077 }
3078}
3079
Attilio Provenzano02859b22020-02-27 14:17:28 +00003080bool BestPractices::PreCallValidateCreateSampler(VkDevice device, const VkSamplerCreateInfo* pCreateInfo,
3081 const VkAllocationCallbacks* pAllocator, VkSampler* pSampler) const {
3082 bool skip = false;
3083
3084 if (VendorCheckEnabled(kBPVendorArm)) {
3085 if ((pCreateInfo->addressModeU != pCreateInfo->addressModeV) || (pCreateInfo->addressModeV != pCreateInfo->addressModeW)) {
3086 skip |= LogPerformanceWarning(
3087 device, kVUID_BestPractices_CreateSampler_DifferentWrappingModes,
3088 "%s Creating a sampler object with wrapping modes which do not match (U = %u, V = %u, W = %u). "
3089 "This may cause reduced performance even if only U (1D image) or U/V wrapping modes (2D "
3090 "image) are actually used. If you need different wrapping modes, disregard this warning.",
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -06003091 VendorSpecificTag(kBPVendorArm), pCreateInfo->addressModeU, pCreateInfo->addressModeV, pCreateInfo->addressModeW);
Attilio Provenzano02859b22020-02-27 14:17:28 +00003092 }
3093
3094 if ((pCreateInfo->minLod != 0.0f) || (pCreateInfo->maxLod < VK_LOD_CLAMP_NONE)) {
3095 skip |= LogPerformanceWarning(
3096 device, kVUID_BestPractices_CreateSampler_LodClamping,
3097 "%s Creating a sampler object with LOD clamping (minLod = %f, maxLod = %f). This may cause reduced performance. "
3098 "Instead of clamping LOD in the sampler, consider using an VkImageView which restricts the mip-levels, set minLod "
3099 "to 0.0, and maxLod to VK_LOD_CLAMP_NONE.",
3100 VendorSpecificTag(kBPVendorArm), pCreateInfo->minLod, pCreateInfo->maxLod);
3101 }
3102
3103 if (pCreateInfo->mipLodBias != 0.0f) {
3104 skip |=
3105 LogPerformanceWarning(device, kVUID_BestPractices_CreateSampler_LodBias,
3106 "%s Creating a sampler object with LOD bias != 0.0 (%f). This will lead to less efficient "
3107 "descriptors being created and may cause reduced performance.",
3108 VendorSpecificTag(kBPVendorArm), pCreateInfo->mipLodBias);
3109 }
3110
3111 if ((pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
3112 pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
3113 pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER) &&
3114 (pCreateInfo->borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK)) {
3115 skip |= LogPerformanceWarning(
3116 device, kVUID_BestPractices_CreateSampler_BorderClampColor,
3117 "%s Creating a sampler object with border clamping and borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK. "
3118 "This will lead to less efficient descriptors being created and may cause reduced performance. "
3119 "If possible, use VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK as the border color.",
3120 VendorSpecificTag(kBPVendorArm));
3121 }
3122
3123 if (pCreateInfo->unnormalizedCoordinates) {
3124 skip |= LogPerformanceWarning(
3125 device, kVUID_BestPractices_CreateSampler_UnnormalizedCoordinates,
3126 "%s Creating a sampler object with unnormalized coordinates. This will lead to less efficient "
3127 "descriptors being created and may cause reduced performance.",
3128 VendorSpecificTag(kBPVendorArm));
3129 }
3130
3131 if (pCreateInfo->anisotropyEnable) {
3132 skip |= LogPerformanceWarning(
3133 device, kVUID_BestPractices_CreateSampler_Anisotropy,
3134 "%s Creating a sampler object with anisotropy. This will lead to less efficient descriptors being created "
3135 "and may cause reduced performance.",
3136 VendorSpecificTag(kBPVendorArm));
3137 }
3138 }
3139
3140 return skip;
3141}
Sam Walls8e77e4f2020-03-16 20:47:40 +00003142
3143void BestPractices::PostTransformLRUCacheModel::resize(size_t size) { _entries.resize(size); }
3144
3145bool BestPractices::PostTransformLRUCacheModel::query_cache(uint32_t value) {
3146 // look for a cache hit
3147 auto hit = std::find_if(_entries.begin(), _entries.end(), [value](const CacheEntry& entry) { return entry.value == value; });
3148 if (hit != _entries.end()) {
3149 // mark the cache hit as being most recently used
3150 hit->age = iteration++;
3151 return true;
3152 }
3153
3154 // if there's no cache hit, we need to model the entry being inserted into the cache
3155 CacheEntry new_entry = {value, iteration};
3156 if (iteration < static_cast<uint32_t>(std::distance(_entries.begin(), _entries.end()))) {
3157 // if there is still space left in the cache, use the next available slot
3158 *(_entries.begin() + iteration) = new_entry;
3159 } else {
3160 // otherwise replace the least recently used cache entry
3161 auto lru = std::min_element(_entries.begin(), hit, [](const CacheEntry& a, const CacheEntry& b) { return a.age < b.age; });
3162 *lru = new_entry;
3163 }
3164 iteration++;
3165 return false;
3166}
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003167
3168bool BestPractices::PreCallValidateAcquireNextImageKHR(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout,
3169 VkSemaphore semaphore, VkFence fence, uint32_t* pImageIndex) const {
3170 const auto swapchain_data = GetSwapchainState(swapchain);
3171 bool skip = false;
3172 if (swapchain_data && swapchain_data->images.size() == 0) {
3173 skip |= LogWarning(swapchain, kVUID_Core_DrawState_SwapchainImagesNotFound,
3174 "vkAcquireNextImageKHR: No images found to acquire from. Application probably did not call "
3175 "vkGetSwapchainImagesKHR after swapchain creation.");
3176 }
3177 return skip;
3178}
3179
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003180void BestPractices::CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(CALL_STATE& call_state, bool no_pointer) {
3181 if (no_pointer) {
3182 if (UNCALLED == call_state) {
3183 call_state = QUERY_COUNT;
3184 }
3185 } else { // Save queue family properties
3186 call_state = QUERY_DETAILS;
3187 }
3188}
3189
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003190void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
3191 uint32_t* pQueueFamilyPropertyCount,
3192 VkQueueFamilyProperties* pQueueFamilyProperties) {
3193 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(physicalDevice, pQueueFamilyPropertyCount,
3194 pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003195 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003196 if (bp_pd_state) {
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003197 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
3198 nullptr == pQueueFamilyProperties);
3199 }
3200}
3201
3202void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
3203 uint32_t* pQueueFamilyPropertyCount,
3204 VkQueueFamilyProperties2* pQueueFamilyProperties) {
3205 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(physicalDevice, pQueueFamilyPropertyCount,
3206 pQueueFamilyProperties);
3207 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3208 if (bp_pd_state) {
3209 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
3210 nullptr == pQueueFamilyProperties);
3211 }
3212}
3213
3214void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(VkPhysicalDevice physicalDevice,
3215 uint32_t* pQueueFamilyPropertyCount,
3216 VkQueueFamilyProperties2* pQueueFamilyProperties) {
3217 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(physicalDevice, pQueueFamilyPropertyCount,
3218 pQueueFamilyProperties);
3219 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3220 if (bp_pd_state) {
3221 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
3222 nullptr == pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003223 }
3224}
3225
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003226void BestPractices::PostCallRecordGetPhysicalDeviceFeatures(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures* pFeatures) {
3227 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003228 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3229 if (bp_pd_state) {
3230 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3231 }
3232}
3233
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003234void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2(VkPhysicalDevice physicalDevice,
3235 VkPhysicalDeviceFeatures2* pFeatures) {
3236 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003237 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3238 if (bp_pd_state) {
3239 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3240 }
3241}
3242
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003243void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2KHR(VkPhysicalDevice physicalDevice,
3244 VkPhysicalDeviceFeatures2* pFeatures) {
3245 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2KHR(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003246 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3247 if (bp_pd_state) {
3248 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3249 }
3250}
3251
3252void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilitiesKHR(VkPhysicalDevice physicalDevice,
3253 VkSurfaceKHR surface,
3254 VkSurfaceCapabilitiesKHR* pSurfaceCapabilities,
3255 VkResult result) {
3256 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3257 if (bp_pd_state) {
3258 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3259 }
3260}
3261
3262void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2KHR(
3263 VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
3264 VkSurfaceCapabilities2KHR* pSurfaceCapabilities, VkResult result) {
3265 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3266 if (bp_pd_state) {
3267 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3268 }
3269}
3270
3271void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2EXT(VkPhysicalDevice physicalDevice,
3272 VkSurfaceKHR surface,
3273 VkSurfaceCapabilities2EXT* pSurfaceCapabilities,
3274 VkResult result) {
3275 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3276 if (bp_pd_state) {
3277 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3278 }
3279}
3280
3281void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice physicalDevice,
3282 VkSurfaceKHR surface, uint32_t* pPresentModeCount,
3283 VkPresentModeKHR* pPresentModes, VkResult result) {
3284 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
3285 if (bp_pd_data) {
3286 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfacePresentModesKHRState;
3287
3288 if (*pPresentModeCount) {
3289 if (call_state < QUERY_COUNT) {
3290 call_state = QUERY_COUNT;
3291 }
3292 }
3293 if (pPresentModes) {
3294 if (call_state < QUERY_DETAILS) {
3295 call_state = QUERY_DETAILS;
3296 }
3297 }
3298 }
3299}
3300
3301void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
3302 uint32_t* pSurfaceFormatCount,
3303 VkSurfaceFormatKHR* pSurfaceFormats, VkResult result) {
3304 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
3305 if (bp_pd_data) {
3306 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState;
3307
3308 if (*pSurfaceFormatCount) {
3309 if (call_state < QUERY_COUNT) {
3310 call_state = QUERY_COUNT;
3311 }
3312 }
3313 if (pSurfaceFormats) {
3314 if (call_state < QUERY_DETAILS) {
3315 call_state = QUERY_DETAILS;
3316 }
3317 }
3318 }
3319}
3320
3321void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormats2KHR(VkPhysicalDevice physicalDevice,
3322 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
3323 uint32_t* pSurfaceFormatCount,
3324 VkSurfaceFormat2KHR* pSurfaceFormats, VkResult result) {
3325 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
3326 if (bp_pd_data) {
3327 if (*pSurfaceFormatCount) {
3328 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_COUNT) {
3329 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_COUNT;
3330 }
3331 }
3332 if (pSurfaceFormats) {
3333 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_DETAILS) {
3334 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_DETAILS;
3335 }
3336 }
3337 }
3338}
3339
3340void BestPractices::ManualPostCallRecordGetPhysicalDeviceDisplayPlanePropertiesKHR(VkPhysicalDevice physicalDevice,
3341 uint32_t* pPropertyCount,
3342 VkDisplayPlanePropertiesKHR* pProperties,
3343 VkResult result) {
3344 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
3345 if (bp_pd_data) {
3346 if (*pPropertyCount) {
3347 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_COUNT) {
3348 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_COUNT;
3349 }
3350 }
3351 if (pProperties) {
3352 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_DETAILS) {
3353 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_DETAILS;
3354 }
3355 }
3356 }
3357}
3358
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003359void BestPractices::ManualPostCallRecordGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain,
3360 uint32_t* pSwapchainImageCount, VkImage* pSwapchainImages,
3361 VkResult result) {
Nathaniel Cesario39152e62021-07-02 13:04:16 -06003362 auto* swapchain_state = static_cast<SWAPCHAIN_STATE_BP*>(Get<SWAPCHAIN_NODE>(swapchain));
3363 if (swapchain_state && (pSwapchainImages || *pSwapchainImageCount)) {
3364 if (swapchain_state->vkGetSwapchainImagesKHRState < QUERY_DETAILS) {
3365 swapchain_state->vkGetSwapchainImagesKHRState = QUERY_DETAILS;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003366 }
3367 }
3368}
3369
3370void BestPractices::ManualPostCallRecordEnumeratePhysicalDevices(VkInstance instance, uint32_t* pPhysicalDeviceCount,
3371 VkPhysicalDevice* pPhysicalDevices, VkResult result) {
3372 if ((nullptr != pPhysicalDevices) && ((result == VK_SUCCESS || result == VK_INCOMPLETE))) {
3373 for (uint32_t i = 0; i < *pPhysicalDeviceCount; i++) {
3374 phys_device_bp_state_map.emplace(pPhysicalDevices[i], PHYSICAL_DEVICE_STATE_BP{});
3375 }
3376 }
3377}
3378
3379void BestPractices::ManualPostCallRecordCreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo*, const VkAllocationCallbacks*,
3380 VkDevice*, VkResult result) {
3381 if (VK_SUCCESS == result) {
3382 instance_device_bp_state = &phys_device_bp_state_map[gpu];
3383 }
3384}
3385
3386PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP(const VkPhysicalDevice& phys_device) {
3387 if (phys_device_bp_state_map.count(phys_device) > 0) {
3388 return &phys_device_bp_state_map.at(phys_device);
3389 } else {
3390 return nullptr;
3391 }
3392}
3393
3394const PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP(const VkPhysicalDevice& phys_device) const {
3395 if (phys_device_bp_state_map.count(phys_device) > 0) {
3396 return &phys_device_bp_state_map.at(phys_device);
3397 } else {
3398 return nullptr;
3399 }
3400}
3401
3402PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP() {
3403 auto bp_state = (reinterpret_cast<BestPractices*>(instance_state))->instance_device_bp_state;
3404 if (bp_state) {
3405 return bp_state;
3406 } else if (!bp_state && phys_device_bp_state_map.count(physical_device_state->phys_device) > 0) {
3407 return &phys_device_bp_state_map.at(physical_device_state->phys_device);
3408 } else {
3409 return nullptr;
3410 }
3411}
3412
3413const PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP() const {
3414 auto bp_state = (reinterpret_cast<BestPractices*>(instance_state))->instance_device_bp_state;
3415 if (bp_state) {
3416 return bp_state;
3417 } else if (!bp_state && phys_device_bp_state_map.count(physical_device_state->phys_device) > 0) {
3418 return &phys_device_bp_state_map.at(physical_device_state->phys_device);
3419 } else {
3420 return nullptr;
3421 }
3422}
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003423
3424void BestPractices::PreCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits, VkFence fence) {
3425 ValidationStateTracker::PreCallRecordQueueSubmit(queue, submitCount, pSubmits, fence);
3426
3427 QUEUE_STATE* queue_state = GetQueueState(queue);
3428 for (uint32_t submit = 0; submit < submitCount; submit++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02003429 const auto& submit_info = pSubmits[submit];
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003430 for (uint32_t cb_index = 0; cb_index < submit_info.commandBufferCount; cb_index++) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003431 auto* cb = GetCBState(submit_info.pCommandBuffers[cb_index]);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003432 for (auto &func : cb->queue_submit_functions) {
3433 func(this, queue_state);
3434 }
3435 }
3436 }
3437}