forked from kpet/clvk
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdevice.cpp
More file actions
1064 lines (922 loc) · 40.2 KB
/
Copy pathdevice.cpp
File metadata and controls
1064 lines (922 loc) · 40.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2018 The clvk authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <fstream>
#include "config.hpp"
#include "device.hpp"
#include "init.hpp"
#include "log.hpp"
#include "memory.hpp"
constexpr VkMemoryPropertyFlags cvk_device::buffer_supported_memory_types[];
constexpr VkMemoryPropertyFlags cvk_device::image_supported_memory_types[];
cvk_device* cvk_device::create(cvk_platform* platform, VkInstance instance,
VkPhysicalDevice pdev, bool is_default) {
cvk_device* device = new cvk_device(platform, pdev, is_default);
if (!device->init(instance)) {
delete device;
return nullptr;
}
return device;
}
void cvk_device::init_vulkan_properties(VkInstance instance) {
cvk_info("Getting Vulkan device properties");
m_device_id_properties.sType =
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES_KHR;
m_driver_properties.sType =
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES_KHR;
m_pci_bus_info_properties.sType =
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PCI_BUS_INFO_PROPERTIES_EXT;
m_subgroup_properties.sType =
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_PROPERTIES;
#define VER_EXT_PROP(ver, ext, prop) \
{ver, ext, reinterpret_cast<VkBaseOutStructure*>(&prop)}
std::vector<std::tuple<uint32_t, const char*, VkBaseOutStructure*>>
coreversion_extension_properties = {
VER_EXT_PROP(VK_MAKE_VERSION(1, 1, 0), nullptr,
m_device_id_properties),
VER_EXT_PROP(VK_MAKE_VERSION(1, 2, 0),
VK_KHR_DRIVER_PROPERTIES_EXTENSION_NAME,
m_driver_properties),
VER_EXT_PROP(0, VK_EXT_PCI_BUS_INFO_EXTENSION_NAME,
m_pci_bus_info_properties),
VER_EXT_PROP(VK_MAKE_VERSION(1, 1, 0), nullptr,
m_subgroup_properties),
};
#undef VER_EXT_PROP
VkBaseOutStructure* pNext = nullptr;
for (auto& ver_ext_prop : coreversion_extension_properties) {
auto corever = std::get<0>(ver_ext_prop);
auto ext = std::get<1>(ver_ext_prop);
auto prop = std::get<2>(ver_ext_prop);
if ((corever != 0) && (m_properties.apiVersion >= corever)) {
prop->pNext = pNext;
pNext = prop;
} else if ((ext != nullptr) && is_vulkan_extension_enabled(ext)) {
prop->pNext = pNext;
pNext = prop;
}
}
VkPhysicalDeviceProperties2KHR properties;
properties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2_KHR;
properties.pNext = pNext;
auto func = GET_INSTANCE_PROC(instance, vkGetPhysicalDeviceProperties2KHR);
if (!func) {
cvk_fatal(
"Failed to get pointer to vkGetPhysicalDeviceProperties2KHR()");
}
func(m_pdev, &properties);
}
void cvk_device::init_clvk_runtime_behaviors() {
#define SET_DEVICE_PROPERTY(option) \
do { \
if (config.option.set) { \
m_##option = config.option; \
} else { \
m_##option = m_clvk_properties->get_##option(); \
} \
cvk_info_fn(#option ": %u", m_##option); \
} while (0)
SET_DEVICE_PROPERTY(max_cmd_batch_size);
SET_DEVICE_PROPERTY(max_first_cmd_batch_size);
SET_DEVICE_PROPERTY(max_cmd_group_size);
SET_DEVICE_PROPERTY(max_first_cmd_group_size);
#undef SET_DEVICE_PROPERTY
}
void cvk_device::init_driver_behaviors() {
cvk_info("Initialising driver behaviors");
// Disable all driver-specific behaviors by default
m_driver_behaviors = 0;
if (is_vulkan_extension_enabled(VK_KHR_DRIVER_PROPERTIES_EXTENSION_NAME) ||
m_properties.apiVersion >= VK_MAKE_VERSION(1, 2, 0)) {
// Log basic information about the target Vulkan device
cvk_info(" driverName = %s", m_driver_properties.driverName);
cvk_info(" driverInfo = %s", m_driver_properties.driverInfo);
cvk_info(" conformanceVersion = %d.%d.%d.%d",
m_driver_properties.conformanceVersion.major,
m_driver_properties.conformanceVersion.minor,
m_driver_properties.conformanceVersion.subminor,
m_driver_properties.conformanceVersion.patch);
// Select behaviors based on the target Vulkan device and driver version
if (m_driver_properties.driverID == VK_DRIVER_ID_ARM_PROPRIETARY_KHR) {
// Workaround for resource management bug on Mali GPUs.
// TODO: Make this conditional on the driver version when this is
// fixed in the driver.
m_driver_behaviors |= use_reset_command_buffer_bit;
}
} else {
cvk_warn("The VK_KHR_driver_properties extension is not supported.");
cvk_warn("Using default Vulkan driver behaviors.");
}
// List driver behaviors
cvk_info("Driver behaviors:");
#define PRINT_BEHAVIOR(name) \
cvk_info(" %s = %s", #name, (m_driver_behaviors & name) ? "true" : "false")
PRINT_BEHAVIOR(use_reset_command_buffer_bit);
#undef PRINT_BEHAVIOR
}
bool cvk_device::init_queues(uint32_t* num_queues, uint32_t* queue_family) {
// Get number of queue families
uint32_t num_families;
vkGetPhysicalDeviceQueueFamilyProperties(m_pdev, &num_families, nullptr);
cvk_info(
"Physical device (%s) has %u queue families:",
vulkan_physical_device_type_string(m_properties.deviceType).c_str(),
num_families);
// Get their properties
std::vector<VkQueueFamilyProperties> families(num_families);
vkGetPhysicalDeviceQueueFamilyProperties(m_pdev, &num_families,
families.data());
// Look for suitable queues
bool found_queues = false;
*num_queues = 0;
for (uint32_t i = 0; i < num_families; i++) {
cvk_info(" queue family %u: %2u queues | %s", i,
families[i].queueCount,
vulkan_queue_flags_string(families[i].queueFlags).c_str());
if (!found_queues && (families[i].queueFlags & VK_QUEUE_COMPUTE_BIT)) {
*queue_family = i;
*num_queues = families[i].queueCount;
found_queues = true;
}
}
if (!found_queues) {
cvk_error("Could not find a suitable queue family for this device");
return false;
}
// Initialise the queue allocator
m_vulkan_queue_alloc_index = 0;
return true;
}
bool cvk_device::init_extensions() {
uint32_t numext;
VkResult res =
vkEnumerateDeviceExtensionProperties(m_pdev, nullptr, &numext, nullptr);
CVK_VK_CHECK_ERROR_RET(
res, false, "Failed to get the number of device extension properties");
cvk_info("%u extensions are supported", numext);
std::vector<VkExtensionProperties> extensions(numext);
res = vkEnumerateDeviceExtensionProperties(m_pdev, nullptr, &numext,
extensions.data());
CVK_VK_CHECK_ERROR_RET(res, false,
"Could not enumerate device extension properties");
std::vector<const char*> desired_extensions{
VK_KHR_8BIT_STORAGE_EXTENSION_NAME,
VK_KHR_16BIT_STORAGE_EXTENSION_NAME,
VK_KHR_DRIVER_PROPERTIES_EXTENSION_NAME,
VK_KHR_SHADER_FLOAT16_INT8_EXTENSION_NAME,
VK_KHR_SHADER_NON_SEMANTIC_INFO_EXTENSION_NAME,
VK_KHR_UNIFORM_BUFFER_STANDARD_LAYOUT_EXTENSION_NAME,
VK_KHR_VARIABLE_POINTERS_EXTENSION_NAME,
VK_EXT_CALIBRATED_TIMESTAMPS_EXTENSION_NAME,
VK_EXT_PCI_BUS_INFO_EXTENSION_NAME,
VK_KHR_SHADER_FLOAT_CONTROLS_EXTENSION_NAME,
VK_KHR_VULKAN_MEMORY_MODEL_EXTENSION_NAME,
VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME,
VK_KHR_BUFFER_DEVICE_ADDRESS_EXTENSION_NAME,
};
if (m_properties.apiVersion < VK_MAKE_VERSION(1, 2, 0)) {
desired_extensions.push_back(VK_KHR_SPIRV_1_4_EXTENSION_NAME);
desired_extensions.push_back(
VK_KHR_SHADER_SUBGROUP_EXTENDED_TYPES_EXTENSION_NAME);
}
if (m_properties.apiVersion < VK_MAKE_VERSION(1, 1, 0)) {
m_vulkan_device_extensions.push_back(
VK_KHR_STORAGE_BUFFER_STORAGE_CLASS_EXTENSION_NAME);
} else {
desired_extensions.push_back(
VK_KHR_STORAGE_BUFFER_STORAGE_CLASS_EXTENSION_NAME);
}
for (size_t i = 0; i < numext; i++) {
cvk_info(" %s, spec version %u", extensions[i].extensionName,
extensions[i].specVersion);
for (auto name : desired_extensions) {
if (!strcmp(name, extensions[i].extensionName)) {
m_vulkan_device_extensions.push_back(name);
cvk_info(" ENABLING");
break;
}
}
}
return true;
}
void cvk_device::init_features(VkInstance instance) {
cvk_info("Initialising features");
// Query supported features.
m_features_ubo_stdlayout.sType =
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_UNIFORM_BUFFER_STANDARD_LAYOUT_FEATURES_KHR;
m_features_float16_int8.sType =
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_FLOAT16_INT8_FEATURES_KHR;
m_features_variable_pointer.sType =
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTERS_FEATURES_KHR;
m_features_8bit_storage.sType =
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_8BIT_STORAGE_FEATURES_KHR;
m_features_16bit_storage.sType =
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_16BIT_STORAGE_FEATURES_KHR;
m_features_shader_subgroup_extended_types.sType =
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_SUBGROUP_EXTENDED_TYPES_FEATURES_KHR;
m_features_vulkan_memory_model.sType =
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_MEMORY_MODEL_FEATURES;
m_features_buffer_device_address.sType =
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BUFFER_DEVICE_ADDRESS_FEATURES_KHR;
std::vector<std::tuple<uint32_t, const char*, VkBaseOutStructure*>>
coreversion_extension_features = {
#define VER_EXT_FEAT(ver, ext, feat) \
{ver, ext, reinterpret_cast<VkBaseOutStructure*>(&feat)}
VER_EXT_FEAT(VK_MAKE_VERSION(1, 2, 0),
VK_KHR_UNIFORM_BUFFER_STANDARD_LAYOUT_EXTENSION_NAME,
m_features_ubo_stdlayout),
VER_EXT_FEAT(VK_MAKE_VERSION(1, 2, 0),
VK_KHR_SHADER_FLOAT16_INT8_EXTENSION_NAME,
m_features_float16_int8),
VER_EXT_FEAT(VK_MAKE_VERSION(1, 1, 0),
VK_KHR_VARIABLE_POINTERS_EXTENSION_NAME,
m_features_variable_pointer),
VER_EXT_FEAT(VK_MAKE_VERSION(1, 2, 0),
VK_KHR_8BIT_STORAGE_EXTENSION_NAME,
m_features_8bit_storage),
VER_EXT_FEAT(VK_MAKE_VERSION(1, 1, 0),
VK_KHR_16BIT_STORAGE_EXTENSION_NAME,
m_features_16bit_storage),
VER_EXT_FEAT(VK_MAKE_VERSION(1, 2, 0),
VK_KHR_SHADER_SUBGROUP_EXTENDED_TYPES_EXTENSION_NAME,
m_features_shader_subgroup_extended_types),
VER_EXT_FEAT(VK_MAKE_VERSION(1, 2, 0),
VK_KHR_VULKAN_MEMORY_MODEL_EXTENSION_NAME,
m_features_vulkan_memory_model),
VER_EXT_FEAT(VK_MAKE_VERSION(1, 2, 0),
VK_KHR_BUFFER_DEVICE_ADDRESS_EXTENSION_NAME,
m_features_buffer_device_address),
#undef VER_EXT_FEAT
};
VkBaseOutStructure* pNext = nullptr;
for (auto& ver_ext_feat : coreversion_extension_features) {
auto corever = std::get<0>(ver_ext_feat);
auto ext = std::get<1>(ver_ext_feat);
auto feat = std::get<2>(ver_ext_feat);
if ((corever != 0) && (m_properties.apiVersion >= corever)) {
feat->pNext = pNext;
pNext = feat;
} else if ((ext != nullptr) && is_vulkan_extension_enabled(ext)) {
feat->pNext = pNext;
pNext = feat;
}
}
VkPhysicalDeviceFeatures2 supported_features;
supported_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
supported_features.pNext = pNext;
if (m_properties.apiVersion < VK_MAKE_VERSION(1, 1, 0)) {
// Use the extension on Vulkan 1.0 platforms
auto func = reinterpret_cast<PFN_vkGetPhysicalDeviceFeatures2KHR>(
vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceFeatures2KHR"));
if (!func) {
cvk_fatal(
"Failed to get pointer to vkGetPhysicalDeviceFeatures2KHR()");
}
func(m_pdev, &supported_features);
} else {
vkGetPhysicalDeviceFeatures2(m_pdev, &supported_features);
}
// Log supported features
cvk_info("8-bit storage: SSBO = %d, UBO = %d, Push constants = %d",
m_features_8bit_storage.storageBuffer8BitAccess,
m_features_8bit_storage.uniformAndStorageBuffer8BitAccess,
m_features_8bit_storage.storagePushConstant8);
cvk_info("16-bit storage: SSBO = %d, UBO = %d, Push constants = %d",
m_features_16bit_storage.storageBuffer16BitAccess,
m_features_16bit_storage.uniformAndStorageBuffer16BitAccess,
m_features_16bit_storage.storagePushConstant16);
cvk_info(
"subgroup extended types: %d",
m_features_shader_subgroup_extended_types.shaderSubgroupExtendedTypes);
// Selectively enable core features.
if (supported_features.features.shaderInt16) {
m_features.features.shaderInt16 = VK_TRUE;
}
if (supported_features.features.shaderInt64) {
m_features.features.shaderInt64 = VK_TRUE;
}
if (supported_features.features.shaderFloat64) {
m_features.features.shaderFloat64 = VK_TRUE;
}
if (supported_features.features.shaderStorageImageReadWithoutFormat) {
m_features.features.shaderStorageImageReadWithoutFormat = VK_TRUE;
}
if (supported_features.features.shaderStorageImageWriteWithoutFormat) {
m_features.features.shaderStorageImageWriteWithoutFormat = VK_TRUE;
}
// All queried extended features are enabled when supported.
m_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
m_features.pNext = pNext;
}
void cvk_device::init_compiler_options() {
m_device_compiler_options = "";
if (!devices_support_images()) {
m_device_compiler_options += " -images=0 ";
}
// 8-bit storage capability restrictions.
if (device_8bit_storage_features().storageBuffer8BitAccess == VK_FALSE) {
m_device_compiler_options += " -no-8bit-storage=ssbo ";
}
if (device_8bit_storage_features().uniformAndStorageBuffer8BitAccess ==
VK_FALSE) {
m_device_compiler_options += " -no-8bit-storage=ubo ";
}
if (device_8bit_storage_features().storagePushConstant8 == VK_FALSE) {
m_device_compiler_options += " -no-8bit-storage=pushconstant ";
}
// 16-bit storage capability restrictions.
if (device_16bit_storage_features().storageBuffer16BitAccess == VK_FALSE) {
m_device_compiler_options += " -no-16bit-storage=ssbo ";
}
if (device_16bit_storage_features().uniformAndStorageBuffer16BitAccess ==
VK_FALSE) {
m_device_compiler_options += " -no-16bit-storage=ubo ";
}
if (device_16bit_storage_features().storagePushConstant16 == VK_FALSE) {
m_device_compiler_options += " -no-16bit-storage=pushconstant ";
}
// Types support
if (!supports_fp16()) {
m_device_compiler_options += " -fp16=0 ";
}
if (!supports_fp64()) {
m_device_compiler_options += " -fp64=0 ";
}
if (supports_int8()) {
m_device_compiler_options += " -int8 ";
m_device_compiler_options += " -rewrite-packed-structs ";
}
if (supports_ubo_stdlayout()) {
m_device_compiler_options += " -std430-ubo-layout ";
}
if (supports_non_uniform_decoration()) {
m_device_compiler_options += " -decorate-nonuniform ";
}
// Device specific options
m_device_compiler_options +=
" " + m_clvk_properties->get_compile_options() + " ";
m_device_compiler_options += " -arch=" + config.spirv_arch() + " ";
if (config.physical_addressing()) {
m_device_compiler_options += " -physical-storage-buffers ";
}
// Builtin options
auto native_builtins = m_clvk_properties->get_native_builtins();
if (!native_builtins.empty()) {
std::string builtin_list = "";
for (const auto& builtin : native_builtins) {
builtin_list += builtin + ",";
}
m_device_compiler_options +=
" --use-native-builtins=" + builtin_list + " ";
}
// Select target SPIR-V version
m_device_compiler_options += " -spv-version=";
switch (vulkan_spirv_env()) {
default:
case SPV_ENV_VULKAN_1_0:
m_device_compiler_options += "1.0 ";
break;
case SPV_ENV_VULKAN_1_1:
m_device_compiler_options += "1.3 ";
break;
case SPV_ENV_VULKAN_1_1_SPIRV_1_4:
m_device_compiler_options += "1.4 ";
break;
case SPV_ENV_VULKAN_1_2:
m_device_compiler_options += "1.5 ";
break;
case SPV_ENV_VULKAN_1_3:
m_device_compiler_options += "1.6 ";
break;
}
// Limits
m_device_compiler_options +=
" -max-pushconstant-size=" +
std::to_string(vulkan_max_push_constants_size()) + " ";
m_device_compiler_options +=
" -max-ubo-size=" + std::to_string(vulkan_max_uniform_buffer_range()) +
" ";
m_device_compiler_options += " -global-offset ";
m_device_compiler_options += " -long-vector ";
m_device_compiler_options += " -module-constants-in-storage-buffer ";
m_device_compiler_options += " -cl-arm-non-uniform-work-group-size ";
}
void cvk_device::build_extension_ils_list() {
m_extensions = {
// Start with required extensions
MAKE_NAME_VERSION(1, 0, 0, "cl_khr_global_int32_base_atomics"),
MAKE_NAME_VERSION(1, 0, 0, "cl_khr_global_int32_extended_atomics"),
MAKE_NAME_VERSION(1, 0, 0, "cl_khr_local_int32_base_atomics"),
MAKE_NAME_VERSION(1, 0, 0, "cl_khr_local_int32_extended_atomics"),
MAKE_NAME_VERSION(1, 0, 0, "cl_khr_byte_addressable_store"),
// Add always supported extensions
MAKE_NAME_VERSION(1, 0, 0, "cl_khr_extended_versioning"),
MAKE_NAME_VERSION(1, 0, 0, "cl_khr_create_command_queue"),
MAKE_NAME_VERSION(1, 0, 0, "cl_khr_il_program"),
MAKE_NAME_VERSION(1, 0, 0, "cl_khr_spirv_no_integer_wrap_decoration"),
MAKE_NAME_VERSION(1, 0, 0, "cl_arm_non_uniform_work_group_size"),
MAKE_NAME_VERSION(1, 0, 0, "cl_khr_suggested_local_work_size"),
MAKE_NAME_VERSION(1, 0, 0, "cl_khr_3d_image_writes"),
};
if (m_properties.apiVersion >= VK_MAKE_VERSION(1, 1, 0)) {
m_extensions.push_back(
MAKE_NAME_VERSION(1, 0, 0, "cl_khr_device_uuid"));
VkSubgroupFeatureFlags required_subgroup_ops =
VK_SUBGROUP_FEATURE_BASIC_BIT | VK_SUBGROUP_FEATURE_ARITHMETIC_BIT;
if ((m_subgroup_properties.supportedOperations &
required_subgroup_ops) == required_subgroup_ops &&
(m_features_shader_subgroup_extended_types
.shaderSubgroupExtendedTypes == VK_TRUE)) {
m_has_subgroups_support = true;
}
}
// Enable cl_khr_fp16 if we have 16-bit storage and shaderFloat16
if ((is_vulkan_extension_enabled(VK_KHR_16BIT_STORAGE_EXTENSION_NAME) &&
m_features_16bit_storage.storageBuffer16BitAccess) &&
(is_vulkan_extension_enabled(
VK_KHR_SHADER_FLOAT16_INT8_EXTENSION_NAME) &&
m_features_float16_int8.shaderFloat16)) {
m_has_fp16_support = true;
m_extensions.push_back(MAKE_NAME_VERSION(1, 0, 0, "cl_khr_fp16"));
}
// Enable 8-bit integer support if possible
if ((is_vulkan_extension_enabled(VK_KHR_8BIT_STORAGE_EXTENSION_NAME) &&
m_features_8bit_storage.storageBuffer8BitAccess) &&
(is_vulkan_extension_enabled(
VK_KHR_SHADER_FLOAT16_INT8_EXTENSION_NAME) &&
m_features_float16_int8.shaderInt8)) {
m_has_int8_support = true;
}
// Report cl_khr_pci_bus_info if VK_EXT_pci_bus_info is supported
if (is_vulkan_extension_enabled(VK_EXT_PCI_BUS_INFO_EXTENSION_NAME)) {
m_extensions.push_back(
MAKE_NAME_VERSION(1, 0, 0, "cl_khr_pci_bus_info"));
}
// Build extension string
for (auto& ext : m_extensions) {
m_extension_string += ext.name;
m_extension_string += " ";
}
// Build list of ILs
m_ils = {
MAKE_NAME_VERSION(1, 0, 0, "SPIR-V"),
};
for (auto& il : m_ils) {
m_ils_string += il.name;
m_ils_string += "_";
m_ils_string += std::to_string(CL_VERSION_MAJOR(il.version));
m_ils_string += ".";
m_ils_string += std::to_string(CL_VERSION_MINOR(il.version));
m_ils_string += " ";
}
// Build list of supported OpenCL C versions
m_opencl_c_versions = {
MAKE_NAME_VERSION(1, 0, 0, "OpenCL C"),
MAKE_NAME_VERSION(1, 1, 0, "OpenCL C"),
MAKE_NAME_VERSION(1, 2, 0, "OpenCL C"),
MAKE_NAME_VERSION(3, 0, 0, "OpenCL C"),
};
// Build list of supported OpenCL C features
m_opencl_c_features = {
MAKE_NAME_VERSION(3, 0, 0, "__opencl_c_images"),
MAKE_NAME_VERSION(3, 0, 0, "__opencl_c_read_write_images"),
MAKE_NAME_VERSION(3, 0, 0, "__opencl_c_3d_image_writes"),
};
if (supports_atomic_order_acq_rel()) {
m_opencl_c_features.push_back(
MAKE_NAME_VERSION(3, 0, 0, "__opencl_c_atomic_order_acq_rel"));
}
if (supports_atomic_scope_device()) {
m_opencl_c_features.push_back(
MAKE_NAME_VERSION(3, 0, 0, "__opencl_c_atomic_scope_device"));
}
if (supports_subgroups()) {
m_opencl_c_features.push_back(
MAKE_NAME_VERSION(3, 0, 0, "__opencl_c_subgroups"));
}
if (m_features.features.shaderInt64) {
m_opencl_c_features.push_back(
MAKE_NAME_VERSION(3, 0, 0, "__opencl_c_int64"));
}
if (m_features.features.shaderFloat64) {
m_has_fp64_support = true;
m_opencl_c_features.push_back(
MAKE_NAME_VERSION(3, 0, 0, "__opencl_c_fp64"));
}
}
bool cvk_device::create_vulkan_queues_and_device(uint32_t num_queues,
uint32_t queue_family) {
cvk_info("Creating Vulkan device and queues");
// Give all queues the same priority
std::vector<float> queuePriorities(num_queues, 1.0f);
VkDeviceQueueCreateInfo queueCreateInfo = {
VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
nullptr,
0, // flags
queue_family,
num_queues, // queueCount
queuePriorities.data()};
// Create logical device
const VkDeviceCreateInfo createInfo = {
VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, // sType
&m_features, // pNext
0, // flags
1, // queueCreateInfoCount
&queueCreateInfo, // pQueueCreateInfos,
0, // enabledLayerCount
nullptr, // ppEnabledLayerNames
static_cast<uint32_t>(
m_vulkan_device_extensions.size()), // enabledExtensionCount
m_vulkan_device_extensions.data(), // ppEnabledExtensionNames
nullptr, // pEnabledFeatures
};
VkResult res = vkCreateDevice(m_pdev, &createInfo, nullptr, &m_dev);
CVK_VK_CHECK_ERROR_RET(res, false, "Failed to create a device");
// Construct the queue wrappers now that our queues exist
m_vulkan_queues.reserve(num_queues);
for (auto i = 0U; i < num_queues; i++) {
VkQueue queue;
vkGetDeviceQueue(m_dev, queue_family, i, &queue);
m_vulkan_queues.emplace_back(queue, queue_family);
}
return true;
}
bool cvk_device::init_time_management(VkInstance instance) {
if (is_vulkan_extension_enabled(
VK_EXT_CALIBRATED_TIMESTAMPS_EXTENSION_NAME)) {
auto func = GET_INSTANCE_PROC(
instance, vkGetPhysicalDeviceCalibrateableTimeDomainsEXT);
uint32_t num_time_domains;
VkResult res;
res = func(m_pdev, &num_time_domains, nullptr);
if (res != VK_SUCCESS) {
cvk_error(
"Can't get number of available calibrateable time domains");
return false;
}
cvk_info("Device supports %u calibrateable time domains",
num_time_domains);
std::vector<VkTimeDomainEXT> supported_time_domains(num_time_domains);
res = func(m_pdev, &num_time_domains, supported_time_domains.data());
if (res != VK_SUCCESS) {
cvk_error("Can't get list of available calibrateable time domains");
return false;
}
bool has_device = false;
bool has_monotonic = false;
for (auto td : supported_time_domains) {
cvk_info(" %s",
vulkan_calibrateable_time_domain_string(td).c_str());
if (td == VK_TIME_DOMAIN_CLOCK_MONOTONIC_EXT) {
has_monotonic = true;
}
if (td == VK_TIME_DOMAIN_DEVICE_EXT) {
has_device = true;
}
}
if (has_device && has_monotonic) {
m_has_timer_support = true;
m_vkfns.vkGetCalibratedTimestampsEXT =
GET_INSTANCE_PROC(instance, vkGetCalibratedTimestampsEXT);
}
}
if (!m_has_timer_support) {
cvk_warn("This device does not support VK_EXT_calibrated_timestamps or "
"it does not support the required "
"VK_TIME_DOMAIN_CLOCK_MONOTONIC_EXT and "
"VK_TIME_DOMAIN_DEVICE_EXT time domains");
cvk_warn("clGetHostTimer and clGetDeviceAndHostTimer will not work");
cvk_warn("Command queue profiling will suffer from limitations");
}
return true;
}
// Returns the pipeline cache file path for a given SPIR-V SHA-1 hash.
// If pipeline cache serialization is not enabled, an empty string is returned.
std::string
cvk_device::get_pipeline_cache_filename(const cvk_sha1_hash& sha1) const {
if (config.cache_dir().empty()) {
return "";
}
// The pipeline cache file path is:
// ${CLVK_CACHE_DIR}/clvk-pipeline-cache.<UUID>.<SHA1>.bin
std::string cache_path = config.cache_dir;
cache_path += "/";
cache_path += "clvk-pipeline-cache.";
cache_path += to_hex_string(m_properties.pipelineCacheUUID, VK_UUID_SIZE);
cache_path += ".";
cache_path += to_hex_string(reinterpret_cast<const uint8_t*>(sha1.data()),
SHA1_DIGEST_NUM_BYTES);
cache_path += ".bin";
return cache_path;
}
bool cvk_device::get_pipeline_cache(const std::vector<uint32_t>& spirv,
VkPipelineCache& pipeline_cache) {
std::lock_guard<std::mutex> lock(m_pipeline_cache_mutex);
pipeline_cache = VK_NULL_HANDLE;
// Compute SHA-1 hash of the SPIR-V binary
cvk_sha1_hash sha1 =
cvk_sha1(spirv.data(), spirv.size() * sizeof(uint32_t));
// Check the in-memory cache of pipeline caches
if (m_pipeline_caches.count(sha1)) {
pipeline_cache = m_pipeline_caches.at(sha1);
return true;
}
std::vector<char> cache_data;
// Load pipeline cache data from file if this is enabled
std::string cache_path = get_pipeline_cache_filename(sha1);
if (!cache_path.empty()) {
cvk_info("Looking for pipeline cache at %s", cache_path.c_str());
std::ifstream cache_file(cache_path, std::ios::in | std::ios::binary);
if (cache_file.is_open()) {
// Get the size of the pipeline cache file
cache_file.seekg(0, std::ios::end);
uint32_t size = cache_file.tellg();
cache_file.seekg(0, std::ios::beg);
// Load the pipeline cache data into memory
cache_data.resize(size);
cache_file.read(cache_data.data(), size);
if (!cache_file.good()) {
cvk_warn("Failed to read pipeline cache data");
cache_data.clear();
}
} else {
cvk_warn("Failed to open pipeline cache file");
}
}
// Create pipeline cache
VkPipelineCacheCreateInfo pipelineCacheCreateInfo = {
VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO,
nullptr, // pNext
0, // flags
cache_data.size(), // initialDataSize
cache_data.data(), // pInitialData
};
VkResult res = vkCreatePipelineCache(m_dev, &pipelineCacheCreateInfo,
nullptr, &pipeline_cache);
if (res != VK_SUCCESS) {
cvk_error("Could not create pipeline cache.");
return false;
}
// Add pipeline cache to the in-memory cache
m_pipeline_caches[sha1] = pipeline_cache;
return cache_data.size() != 0;
}
void cvk_device::save_pipeline_cache(
const cvk_sha1_hash& sha1, const VkPipelineCache& pipeline_cache) const {
VkResult res;
std::string cache_path = get_pipeline_cache_filename(sha1);
if (cache_path.empty()) {
return;
}
// Retrieve the pipeline cache data from the Vulkan implementation
size_t size;
res = vkGetPipelineCacheData(m_dev, pipeline_cache, &size, nullptr);
if (res != VK_SUCCESS) {
cvk_error("Failed to retrieve pipeline cache size");
return;
}
std::vector<char> cache_data(size);
res =
vkGetPipelineCacheData(m_dev, pipeline_cache, &size, cache_data.data());
if (res != VK_SUCCESS) {
cvk_error("Failed to retrieve pipeline cache data");
return;
}
cvk_info("Writing %lu bytes of pipeline cache data to file", size);
// Write the pipeline cache data to file
std::ofstream cache_file(cache_path, std::ios::out | std::ios::binary);
if (!cache_file.is_open()) {
cvk_error("Failed to open pipeline cache file for writing: %s",
cache_path.c_str());
return;
}
cache_file.write(cache_data.data(), size);
if (!cache_file.good()) {
cvk_error("Failed to write pipeline cache data");
}
}
void cvk_device::init_spirv_environment() {
if (m_properties.apiVersion < VK_MAKE_VERSION(1, 1, 0)) {
m_vulkan_spirv_env = SPV_ENV_VULKAN_1_0;
} else if (m_properties.apiVersion < VK_MAKE_VERSION(1, 2, 0)) {
if (is_vulkan_extension_enabled(VK_KHR_SPIRV_1_4_EXTENSION_NAME)) {
m_vulkan_spirv_env = SPV_ENV_VULKAN_1_1_SPIRV_1_4;
} else {
m_vulkan_spirv_env = SPV_ENV_VULKAN_1_1;
}
} else if (m_properties.apiVersion < VK_MAKE_VERSION(1, 3, 0)) {
m_vulkan_spirv_env = SPV_ENV_VULKAN_1_2;
} else {
// Assume 1.3
m_vulkan_spirv_env = SPV_ENV_VULKAN_1_3;
}
cvk_info("Vulkan SPIR-V environment: %s",
spvTargetEnvDescription(m_vulkan_spirv_env));
}
void cvk_device::log_limits_and_memory_information() {
// Print relevant device limits
const VkPhysicalDeviceLimits& limits = vulkan_limits();
cvk_info("Device's resources per stage limits:");
cvk_info(" total = %u", limits.maxPerStageResources);
cvk_info(" uniform buffers = %u",
limits.maxPerStageDescriptorUniformBuffers);
cvk_info(" storage buffers = %u",
limits.maxPerStageDescriptorStorageBuffers);
cvk_info("Device's max buffer size = %s",
pretty_size(limits.maxStorageBufferRange).c_str());
cvk_info("Device's max uniform buffer size = %s",
pretty_size(limits.maxUniformBufferRange).c_str());
cvk_info("Device's max push constant size = %s",
pretty_size(limits.maxPushConstantsSize).c_str());
cvk_info("Device's execution capabilities:");
cvk_info(" Max work-group count: {%u,%u,%u}",
limits.maxComputeWorkGroupCount[0],
limits.maxComputeWorkGroupCount[1],
limits.maxComputeWorkGroupCount[2]);
cvk_info(" Max invocations per work-group: %u",
limits.maxComputeWorkGroupInvocations);
cvk_info(" Max work-group size: {%u,%u,%u}",
limits.maxComputeWorkGroupSize[0],
limits.maxComputeWorkGroupSize[1],
limits.maxComputeWorkGroupSize[2]);
// Print memoy information
cvk_info("Device has %u memory types:", m_mem_properties.memoryTypeCount);
for (uint32_t i = 0; i < m_mem_properties.memoryTypeCount; i++) {
VkMemoryType memtype = m_mem_properties.memoryTypes[i];
auto heapsize = m_mem_properties.memoryHeaps[memtype.heapIndex].size;
cvk_info(
" %u: heap = %u, %s | %s", i, memtype.heapIndex,
pretty_size(heapsize).c_str(),
vulkan_memory_property_flags_string(memtype.propertyFlags).c_str());
}
cvk_info("Device has %u memory heaps:", m_mem_properties.memoryHeapCount);
for (uint32_t i = 0; i < m_mem_properties.memoryHeapCount; i++) {
VkMemoryHeap memheap = m_mem_properties.memoryHeaps[i];
cvk_info(" %u: %s | %s", i, pretty_size(memheap.size).c_str(),
vulkan_memory_property_flags_string(memheap.flags).c_str());
}
}
bool cvk_device::init(VkInstance instance) {
cvk_info("Initialising device %s", m_properties.deviceName);
cvk_info(" API Version: %s",
vulkan_version_string(m_properties.apiVersion).c_str());
uint32_t num_queues, queue_family;
if (!init_queues(&num_queues, &queue_family)) {
return false;
}
if (!init_extensions()) {
return false;
}
init_clvk_runtime_behaviors();
init_vulkan_properties(instance);
init_driver_behaviors();
init_features(instance);
build_extension_ils_list();
if (!init_time_management(instance)) {
return false;
}
if (!create_vulkan_queues_and_device(num_queues, queue_family)) {
return false;
}
init_spirv_environment();
log_limits_and_memory_information();
// Must be done last as it relies on info set up in several of the above.
init_compiler_options();
return true;
}
bool cvk_device::supports_capability(spv::Capability capability) const {
switch (capability) {
// Capabilities required by all Vulkan implementations:
case spv::CapabilityShader:
case spv::CapabilitySampled1D:
case spv::CapabilityImage1D:
case spv::CapabilityImageQuery:
case spv::CapabilityImageBuffer:
return true;
// Optional capabilities:
case spv::CapabilityFloat16:
return m_features_float16_int8.shaderFloat16;
case spv::CapabilityFloat64:
return m_features.features.shaderFloat64;
case spv::CapabilityInt8:
return m_features_float16_int8.shaderInt8;
case spv::CapabilityInt16:
return m_features.features.shaderInt16;
case spv::CapabilityInt64:
return m_features.features.shaderInt64;
case spv::CapabilityStorageImageReadWithoutFormat:
return m_features.features.shaderStorageImageReadWithoutFormat;
case spv::CapabilityStorageImageWriteWithoutFormat:
return m_features.features.shaderStorageImageWriteWithoutFormat;
case spv::CapabilityVariablePointers:
return m_features_variable_pointer.variablePointers;
case spv::CapabilityVariablePointersStorageBuffer:
return m_features_variable_pointer.variablePointersStorageBuffer;
case spv::CapabilityGroupNonUniform:
return m_subgroup_properties.supportedOperations &
VK_SUBGROUP_FEATURE_BASIC_BIT;
case spv::CapabilityGroupNonUniformVote:
return m_subgroup_properties.supportedOperations &
VK_SUBGROUP_FEATURE_VOTE_BIT;
case spv::CapabilityGroupNonUniformArithmetic:
return m_subgroup_properties.supportedOperations &
VK_SUBGROUP_FEATURE_ARITHMETIC_BIT;
case spv::CapabilityGroupNonUniformBallot:
return m_subgroup_properties.supportedOperations &
VK_SUBGROUP_FEATURE_BALLOT_BIT;
case spv::CapabilityVulkanMemoryModel:
return m_features_vulkan_memory_model.vulkanMemoryModel;
case spv::CapabilityShaderNonUniform:
return supports_non_uniform_decoration();
case spv::CapabilityPhysicalStorageBufferAddresses:
return m_features_buffer_device_address.bufferDeviceAddress;
// Capabilities that have not yet been mapped to Vulkan features:
default:
cvk_warn_fn("Capability %d not yet mapped to a feature.", capability);
return false;
}
}
void cvk_device::select_work_group_size(
const std::array<uint32_t, 3>& global_size,
std::array<uint32_t, 3>& local_size) const {
// Start at (1,1,1), which is always valid.
local_size = {1, 1, 1};
// Cap the total work-group size to the Vulkan device's limit.
uint32_t max_size = m_properties.limits.maxComputeWorkGroupInvocations;
// Further cap the total size to 64, as this is expected to be a
// reasonable size on many devices.
max_size = std::min(max_size, UINT32_C(64));
// TODO: We should also take into account the total number of
// work-groups that would be launched, to ensure the device is fully
// utilized for smaller global work sizes.
// Increase the work-group size until we hit device limits.
bool changed;
do {
changed = false;