Repository navigation
Expand file tree
/
Copy pathDraw.cpp
More file actions
3947 lines (3791 loc) · 251 KB
/
Copy pathDraw.cpp
File metadata and controls
3947 lines (3791 loc) · 251 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
#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp"
#include "prx/libSceAgcDriver/Graphics/include/MultisampleTarget.hpp"
#include "prx/libSceAgcDriver/Graphics/include/ColorTargetTransfer.hpp"
#include "prx/libSceAgcDriver/Graphics/include/GpuColorTransfer.hpp"
#include "prx/libSceAgcDriver/Graphics/include/VertexInput.hpp"
#include "prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp"
#include "prx/libSceAgcDriver/Graphics/include/DccMetadata.hpp"
#include "prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp"
#include "prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp"
#include "prx/libSceAgcDriver/Graphics/include/SampleOrder.hpp"
#include "prx/libSceAgcDriver/Graphics/include/TextureFormat.hpp"
#include "prx/libSceAgcDriver/Graphics/include/UnitShadow.hpp"
#include "prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp"
#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp"
#include "prx/libSceAgcDriver/Execution/include/CaptureTrace.hpp"
#include "prx/libSceAgcDriver/Execution/include/PerformanceTimer.hpp"
#include "prx/libSceAgcDriver/Execution/include/Mutex.hpp"
#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp"
#include "ThreadOwned.hpp"
#include "prx/libc/include/General.hpp"
#include "prx/libc/include/GuestAllocations.hpp"
#include "Optimization/include/Optimization/ShaderStageInputInfo.hpp"
#include "SpirvBackend/SpirvAnalysis.hpp"
#include "ThreadOwned.hpp"
#include "prx/libc/include/HostThreadLocal.hpp"
#include <algorithm>
#include <array>
#include <atomic>
#include <chrono>
#include <cmath>
#include <functional>
#include <optional>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <cstring>
#include <limits>
#include <map>
#include <memory>
#include <mutex>
#include <set>
#include <unordered_map>
#include <utility>
namespace AgcDriver::Graphics {
namespace {
struct PixelFunctionLdsPool {
Context context{};
VkBuffer buffer = VK_NULL_HANDLE;
VkDeviceMemory memory = VK_NULL_HANDLE;
VkDescriptorPool descriptorPool = VK_NULL_HANDLE;
VkDescriptorSet set = VK_NULL_HANDLE;
VkDescriptorSetLayout empty = VK_NULL_HANDLE;
VkDescriptorSetLayout bufferLayout = VK_NULL_HANDLE;
std::uint32_t* header = nullptr;
std::uint32_t subgroupSize = 0;
std::uint32_t slots = 0;
bool announced = false;
};
std::mutex& PixelLdsMutex() {
static std::mutex mutex;
return mutex;
}
std::unordered_map<VkDevice, PixelFunctionLdsPool>& PixelLdsPools() {
static std::unordered_map<VkDevice, PixelFunctionLdsPool> pools;
return pools;
}
struct MeshWindowPool {
Context context{};
VkBuffer buffer = VK_NULL_HANDLE;
VkDeviceMemory memory = VK_NULL_HANDLE;
VkDescriptorPool descriptorPool = VK_NULL_HANDLE;
VkDescriptorSet set = VK_NULL_HANDLE;
VkDescriptorSetLayout layout = VK_NULL_HANDLE;
};
std::mutex& MeshWindowMutex() {
static std::mutex mutex;
return mutex;
}
std::unordered_map<VkDevice, MeshWindowPool>& MeshWindowPools() {
static std::unordered_map<VkDevice, MeshWindowPool> pools;
return pools;
}
void DestroyMeshWindow(MeshWindowPool& pool) {
if (pool.descriptorPool != VK_NULL_HANDLE) pool.context.Function<PFN_vkDestroyDescriptorPool>("vkDestroyDescriptorPool")(pool.context.device, pool.descriptorPool, nullptr);
if (pool.buffer != VK_NULL_HANDLE) pool.context.Function<PFN_vkDestroyBuffer>("vkDestroyBuffer")(pool.context.device, pool.buffer, nullptr);
if (pool.memory != VK_NULL_HANDLE) pool.context.Function<PFN_vkFreeMemory>("vkFreeMemory")(pool.context.device, pool.memory, nullptr);
if (pool.layout != VK_NULL_HANDLE) pool.context.Function<PFN_vkDestroyDescriptorSetLayout>("vkDestroyDescriptorSetLayout")(pool.context.device, pool.layout, nullptr);
pool = MeshWindowPool{};
}
void DestroyPixelFunctionLds(PixelFunctionLdsPool& pool) {
if (pool.header != nullptr) pool.context.Function<PFN_vkUnmapMemory>("vkUnmapMemory")(pool.context.device, pool.memory);
if (pool.descriptorPool != VK_NULL_HANDLE) pool.context.Function<PFN_vkDestroyDescriptorPool>("vkDestroyDescriptorPool")(pool.context.device, pool.descriptorPool, nullptr);
if (pool.buffer != VK_NULL_HANDLE) pool.context.Function<PFN_vkDestroyBuffer>("vkDestroyBuffer")(pool.context.device, pool.buffer, nullptr);
if (pool.memory != VK_NULL_HANDLE) pool.context.Function<PFN_vkFreeMemory>("vkFreeMemory")(pool.context.device, pool.memory, nullptr);
if (pool.bufferLayout != VK_NULL_HANDLE) pool.context.Function<PFN_vkDestroyDescriptorSetLayout>("vkDestroyDescriptorSetLayout")(pool.context.device, pool.bufferLayout, nullptr);
if (pool.empty != VK_NULL_HANDLE) pool.context.Function<PFN_vkDestroyDescriptorSetLayout>("vkDestroyDescriptorSetLayout")(pool.context.device, pool.empty, nullptr);
pool.header = nullptr;
pool.descriptorPool = VK_NULL_HANDLE;
pool.set = VK_NULL_HANDLE;
pool.buffer = VK_NULL_HANDLE;
pool.memory = VK_NULL_HANDLE;
pool.bufferLayout = VK_NULL_HANDLE;
pool.empty = VK_NULL_HANDLE;
}
}
PixelFunctionLdsLayouts PixelFunctionLdsSetLayouts(const Context& context) {
std::lock_guard lock(PixelLdsMutex());
auto& pool = PixelLdsPools()[context.device];
if (pool.bufferLayout == VK_NULL_HANDLE) {
pool.context = context;
VkDescriptorSetLayoutCreateInfo emptyInfo{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO};
Check(context.Function<PFN_vkCreateDescriptorSetLayout>("vkCreateDescriptorSetLayout")(context.device, &emptyInfo, nullptr, &pool.empty), "vkCreateDescriptorSetLayout pixel function LDS empty");
const VkDescriptorSetLayoutBinding binding{0u, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1u, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr};
VkDescriptorSetLayoutCreateInfo info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO};
info.bindingCount = 1u;
info.pBindings = &binding;
Check(context.Function<PFN_vkCreateDescriptorSetLayout>("vkCreateDescriptorSetLayout")(context.device, &info, nullptr, &pool.bufferLayout), "vkCreateDescriptorSetLayout pixel function LDS");
}
return {pool.empty, pool.bufferLayout};
}
void PreparePixelFunctionLds(const Context& context, VkCommandBuffer commands, std::uint32_t subgroupSize) {
const auto operations = VK_SUBGROUP_FEATURE_BASIC_BIT | VK_SUBGROUP_FEATURE_BALLOT_BIT;
Require((context.subgroup.supportedStages & VK_SHADER_STAGE_FRAGMENT_BIT) != 0 && (context.subgroup.supportedOperations & operations) == operations, "pixel function LDS needs fragment subgroup elect, ballot and broadcast");
Require(subgroupSize != 0u && subgroupSize == context.subgroup.subgroupSize, "pixel function LDS subgroup size does not match the device");
std::lock_guard lock(PixelLdsMutex());
auto& pool = PixelLdsPools()[context.device];
Require(pool.bufferLayout != VK_NULL_HANDLE, "pixel function LDS descriptor set layout was not created");
if (pool.buffer == VK_NULL_HANDLE) {
const auto stride = static_cast<std::uint64_t>(subgroupSize) * ShaderRecompiler::FunctionLdsDwordLimit * 4ull;
const auto budget = std::min<std::uint64_t>(context.limits.maxStorageBufferRange, 2ull << 30);
Require(budget > 16ull + stride, "pixel function LDS does not fit in the device storage buffer range");
pool.slots = static_cast<std::uint32_t>((budget - 16ull) / stride);
pool.subgroupSize = subgroupSize;
const auto bytes = 16ull + stride * pool.slots;
VkBufferCreateInfo bufferInfo{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
bufferInfo.size = bytes;
bufferInfo.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
Check(context.Function<PFN_vkCreateBuffer>("vkCreateBuffer")(context.device, &bufferInfo, nullptr, &pool.buffer), "vkCreateBuffer pixel function LDS");
VkMemoryRequirements requirements{};
context.Function<PFN_vkGetBufferMemoryRequirements>("vkGetBufferMemoryRequirements")(context.device, pool.buffer, &requirements);
VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
allocation.allocationSize = requirements.size;
constexpr auto hostCoherent = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
constexpr auto deviceLocalHost = hostCoherent | VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
std::optional<std::uint32_t> deviceLocalType;
std::optional<std::uint32_t> hostOnlyType;
for (std::uint32_t i = 0; i < context.memory.memoryTypeCount; ++i) {
if ((requirements.memoryTypeBits & (1u << i)) == 0) continue;
const auto flags = context.memory.memoryTypes[i].propertyFlags;
const auto heap = context.memory.memoryTypes[i].heapIndex;
if (!deviceLocalType && (flags & deviceLocalHost) == deviceLocalHost && context.memory.memoryHeaps[heap].size >= requirements.size) {
deviceLocalType = i;
}
if (!hostOnlyType && (flags & hostCoherent) == hostCoherent && (flags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) == 0) {
hostOnlyType = i;
}
}
const auto hostType = hostOnlyType.value_or(context.MemoryType(requirements.memoryTypeBits, hostCoherent));
allocation.memoryTypeIndex = deviceLocalType.value_or(hostType);
auto allocated = context.Function<PFN_vkAllocateMemory>("vkAllocateMemory")(context.device, &allocation, nullptr, &pool.memory);
if (allocated != VK_SUCCESS && deviceLocalType && allocation.memoryTypeIndex == *deviceLocalType && hostType != *deviceLocalType) {
allocation.memoryTypeIndex = hostType;
allocated = context.Function<PFN_vkAllocateMemory>("vkAllocateMemory")(context.device, &allocation, nullptr, &pool.memory);
}
if (allocated != VK_SUCCESS) {
context.Function<PFN_vkDestroyBuffer>("vkDestroyBuffer")(context.device, pool.buffer, nullptr);
pool.buffer = VK_NULL_HANDLE;
pool.memory = VK_NULL_HANDLE;
Check(allocated, "vkAllocateMemory pixel function LDS");
}
Check(context.Function<PFN_vkBindBufferMemory>("vkBindBufferMemory")(context.device, pool.buffer, pool.memory, 0), "vkBindBufferMemory pixel function LDS");
Check(context.Function<PFN_vkMapMemory>("vkMapMemory")(context.device, pool.memory, 0, 16, 0, reinterpret_cast<void**>(&pool.header)), "vkMapMemory pixel function LDS");
pool.header[0] = 0u;
pool.header[1] = 0u;
pool.header[2] = pool.slots;
const VkDescriptorPoolSize size{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1u};
VkDescriptorPoolCreateInfo poolInfo{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO};
poolInfo.maxSets = 1u;
poolInfo.poolSizeCount = 1u;
poolInfo.pPoolSizes = &size;
Check(context.Function<PFN_vkCreateDescriptorPool>("vkCreateDescriptorPool")(context.device, &poolInfo, nullptr, &pool.descriptorPool), "vkCreateDescriptorPool pixel function LDS");
VkDescriptorSetAllocateInfo sets{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO};
sets.descriptorPool = pool.descriptorPool;
sets.descriptorSetCount = 1u;
sets.pSetLayouts = &pool.bufferLayout;
Check(context.Function<PFN_vkAllocateDescriptorSets>("vkAllocateDescriptorSets")(context.device, &sets, &pool.set), "vkAllocateDescriptorSets pixel function LDS");
const VkDescriptorBufferInfo buffer{pool.buffer, 0, bytes};
VkWriteDescriptorSet write{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET};
write.dstSet = pool.set;
write.dstBinding = 0u;
write.descriptorCount = 1u;
write.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
write.pBufferInfo = &buffer;
context.Function<PFN_vkUpdateDescriptorSets>("vkUpdateDescriptorSets")(context.device, 1u, &write, 0u, nullptr);
std::fprintf(stderr, "[gpu] pixel function LDS pool: %u subgroups, %llu MiB, stride %u lanes\n", pool.slots, static_cast<unsigned long long>(bytes >> 20u), subgroupSize);
pool.announced = true;
}
Require(pool.subgroupSize == subgroupSize, "pixel function LDS subgroup size does not match the pool");
const VkMemoryBarrier beforeFill{VK_STRUCTURE_TYPE_MEMORY_BARRIER, nullptr, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT};
context.Resolved(&DeviceFunctions::cmdPipelineBarrier, "vkCmdPipelineBarrier")(commands, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1, &beforeFill, 0, nullptr, 0, nullptr);
context.Resolved(&DeviceFunctions::cmdFillBuffer, "vkCmdFillBuffer")(commands, pool.buffer, 0, 4, 0u);
const VkMemoryBarrier afterFill{VK_STRUCTURE_TYPE_MEMORY_BARRIER, nullptr, VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT};
context.Resolved(&DeviceFunctions::cmdPipelineBarrier, "vkCmdPipelineBarrier")(commands, VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 1, &afterFill, 0, nullptr, 0, nullptr);
}
bool UsesMeshWindow(std::span<const CompiledShader> shaders) {
return std::ranges::any_of(shaders, [](const CompiledShader& shader) { return shader.program != nullptr && shader.program->meshWindowBuffer; });
}
VkDescriptorSetLayout MeshWindowSetLayout(const Context& context) {
std::lock_guard lock(MeshWindowMutex());
auto& pool = MeshWindowPools()[context.device];
if (pool.layout == VK_NULL_HANDLE) {
pool.context = context;
const VkDescriptorSetLayoutBinding binding{0u, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1u, VK_SHADER_STAGE_MESH_BIT_EXT, nullptr};
VkDescriptorSetLayoutCreateInfo info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO};
info.bindingCount = 1u;
info.pBindings = &binding;
Check(context.Function<PFN_vkCreateDescriptorSetLayout>("vkCreateDescriptorSetLayout")(context.device, &info, nullptr, &pool.layout), "vkCreateDescriptorSetLayout mesh window");
}
return pool.layout;
}
void PrepareMeshWindow(const Context& context) {
std::lock_guard lock(MeshWindowMutex());
auto& pool = MeshWindowPools()[context.device];
Require(pool.layout != VK_NULL_HANDLE, "mesh window descriptor set layout was not created");
if (pool.set != VK_NULL_HANDLE) return;
try {
const auto bytes = (static_cast<std::uint64_t>(ShaderRecompiler::MeshWindowHeaderDwords) + static_cast<std::uint64_t>(ShaderRecompiler::MeshWindowSlots) * ShaderRecompiler::MeshWindowSlotDwords) * 4ull;
Require(bytes <= context.limits.maxStorageBufferRange, "mesh window pool does not fit in the device storage buffer range");
VkBufferCreateInfo bufferInfo{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
bufferInfo.size = bytes;
bufferInfo.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
Check(context.Function<PFN_vkCreateBuffer>("vkCreateBuffer")(context.device, &bufferInfo, nullptr, &pool.buffer), "vkCreateBuffer mesh window");
VkMemoryRequirements requirements{};
context.Function<PFN_vkGetBufferMemoryRequirements>("vkGetBufferMemoryRequirements")(context.device, pool.buffer, &requirements);
VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
allocation.allocationSize = requirements.size;
allocation.memoryTypeIndex = context.MemoryType(requirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
Check(context.Function<PFN_vkAllocateMemory>("vkAllocateMemory")(context.device, &allocation, nullptr, &pool.memory), "vkAllocateMemory mesh window");
Check(context.Function<PFN_vkBindBufferMemory>("vkBindBufferMemory")(context.device, pool.buffer, pool.memory, 0), "vkBindBufferMemory mesh window");
const VkDescriptorPoolSize size{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1u};
VkDescriptorPoolCreateInfo poolInfo{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO};
poolInfo.maxSets = 1u;
poolInfo.poolSizeCount = 1u;
poolInfo.pPoolSizes = &size;
Check(context.Function<PFN_vkCreateDescriptorPool>("vkCreateDescriptorPool")(context.device, &poolInfo, nullptr, &pool.descriptorPool), "vkCreateDescriptorPool mesh window");
VkDescriptorSetAllocateInfo sets{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO};
sets.descriptorPool = pool.descriptorPool;
sets.descriptorSetCount = 1u;
sets.pSetLayouts = &pool.layout;
VkDescriptorSet set = VK_NULL_HANDLE;
Check(context.Function<PFN_vkAllocateDescriptorSets>("vkAllocateDescriptorSets")(context.device, &sets, &set), "vkAllocateDescriptorSets mesh window");
const VkDescriptorBufferInfo buffer{pool.buffer, 0, bytes};
VkWriteDescriptorSet write{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET};
write.dstSet = set;
write.dstBinding = 0u;
write.descriptorCount = 1u;
write.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
write.pBufferInfo = &buffer;
context.Function<PFN_vkUpdateDescriptorSets>("vkUpdateDescriptorSets")(context.device, 1u, &write, 0u, nullptr);
CommandBatch batch(context);
const auto commands = batch.Handle();
context.Function<PFN_vkCmdFillBuffer>("vkCmdFillBuffer")(commands, pool.buffer, 0, ShaderRecompiler::MeshWindowHeaderDwords * 4u, 0u);
const VkMemoryBarrier afterFill{VK_STRUCTURE_TYPE_MEMORY_BARRIER, nullptr, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT};
context.Function<PFN_vkCmdPipelineBarrier>("vkCmdPipelineBarrier")(commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1, &afterFill, 0, nullptr, 0, nullptr);
batch.SubmitAndWait();
pool.set = set;
std::fprintf(stderr, "[gpu] mesh window pool: %u workgroup slots, %llu MiB\n", ShaderRecompiler::MeshWindowSlots, static_cast<unsigned long long>(bytes >> 20u));
} catch (...) {
const auto layout = pool.layout;
pool.layout = VK_NULL_HANDLE;
DestroyMeshWindow(pool);
pool.context = context;
pool.layout = layout;
throw;
}
}
void BindMeshWindow(const Context& context, VkCommandBuffer commands, VkPipelineLayout layout) {
std::lock_guard lock(MeshWindowMutex());
const auto& pool = MeshWindowPools().at(context.device);
Require(pool.set != VK_NULL_HANDLE, "mesh window buffer was not prepared");
context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, layout, ShaderRecompiler::MeshWindowDescriptorSet, 1, &pool.set, 0, nullptr);
}
void ReleaseMeshWindow(VkDevice device) {
std::lock_guard lock(MeshWindowMutex());
const auto found = MeshWindowPools().find(device);
if (found == MeshWindowPools().end()) return;
DestroyMeshWindow(found->second);
MeshWindowPools().erase(found);
}
std::uint32_t PixelFunctionLdsSubgroup(std::span<const CompiledShader> shaders) {
std::uint32_t subgroup = 0u;
for (const auto& shader : shaders) {
if (shader.program != nullptr && shader.program->functionLdsBuffer) subgroup = shader.program->hostSubgroupSize;
}
return subgroup;
}
void BindPixelFunctionLds(const Context& context, VkCommandBuffer commands, VkPipelineLayout layout) {
std::lock_guard lock(PixelLdsMutex());
const auto& pool = PixelLdsPools().at(context.device);
Require(pool.set != VK_NULL_HANDLE, "pixel function LDS buffer was not prepared");
context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, layout, ShaderRecompiler::PixelFunctionLdsDescriptorSet, 1, &pool.set, 0, nullptr);
}
void CheckPixelFunctionLds(const Context& context) {
std::lock_guard lock(PixelLdsMutex());
const auto found = PixelLdsPools().find(context.device);
if (found == PixelLdsPools().end() || found->second.header == nullptr) return;
const auto exhausted = found->second.header[1] != 0u;
found->second.header[1] = 0u;
if (exhausted) throw std::runtime_error("AGC graphics: pixel function LDS subgroup slots exhausted");
}
void ReleasePixelFunctionLds(VkDevice device) {
std::lock_guard lock(PixelLdsMutex());
const auto found = PixelLdsPools().find(device);
if (found == PixelLdsPools().end()) return;
DestroyPixelFunctionLds(found->second);
PixelLdsPools().erase(found);
}
std::uint64_t DrawRenderPassKey(const Context& context, const State& state, std::span<const VkImageView> targetViews) {
std::uint64_t key = 14695981039346656037ull;
const auto mix = [&](std::uint64_t value) {
key ^= value;
key *= 1099511628211ull;
};
for (const auto view : targetViews) mix(reinterpret_cast<std::uint64_t>(view));
if (state.blends.size() != state.colors.size()) {
mix(state.blends.size());
for (const auto& color : state.colors) mix(color.exportIndex);
}
for (const auto& color : state.colors) {
if (color.partialWriteMask != 0u) mix(0x6d65726765000000ull | color.exportIndex);
}
mix(state.renderExtent.width);
mix(state.renderExtent.height);
mix(state.samples);
mix(state.mergedCoverage);
mix(state.truncatedCoverage);
mix(state.customSampleLocations);
if (state.customSampleLocations) {
mix(state.sampleLocationGrid);
for (const auto location : state.sampleLocations) mix(location);
}
if (!context.provokingVertexModePerPipeline) mix(state.provokingVertexMode);
if (state.rasterizerDiscard) mix(0x6469736361726400ull);
return key;
}
namespace {
GuestTextureResource ArraySurfaceForTarget(const ColorTarget& color) {
Require(color.arrayLastSlice != 0, "the color target is not a view of a 2D array");
auto surface = SurfaceForTarget(color);
surface.baseAddress = color.arrayAddress;
surface.width = color.surfaceExtent.width;
surface.height = color.surfaceExtent.height;
surface.depthOrLastArray = color.arrayLastSlice;
surface.dimension = TextureDimension::k2DArray;
return surface;
}
}
namespace {
bool writesDepthTarget(const State& state) {
return state.depthWrite || (state.stencilTest && (state.stencilFront.writeMask != 0u || state.stencilBack.writeMask != 0u));
}
std::size_t colorKeyCount(const ColorTarget& color, std::size_t bytes) {
if (color.mipCount != 1 || color.depth != 1 || !color.dccPipeAligned) return DccKeyBytes(bytes);
return DccKeyCount(ColorTextureTileMode(color.tileMode), color.elementBytes, color.extent.width, color.extent.height, bytes);
}
std::array<std::byte, 16> clearTexel(const ColorTarget& color, DccKeys keys) {
std::array<std::byte, 16> texel{};
const auto elementBytes = static_cast<std::size_t>(color.elementBytes);
Require(elementBytes != 0 && elementBytes <= texel.size(), "unexpected color element size");
if (keys == DccKeys::ClearRegister) {
Require(elementBytes <= sizeof(color.clearWords), "the DCC register clear of a texel over 64 bits is not modeled");
std::memcpy(texel.data(), color.clearWords.data(), elementBytes);
} else {
Require(FillDccClear(color.format, keys, color.dccAlphaOnMsb, std::span(texel.data(), elementBytes)), "the target's format has no encoding of its DCC clear code");
}
return texel;
}
bool clearToTexel(StorageTexture& image, const std::array<std::byte, 16>& texel, std::uint32_t elementBytes, const char*& refusal, bool allowRegisterClear = false) {
std::array<std::byte, 16> repeated{};
for (std::size_t offset = 0; offset + elementBytes <= repeated.size(); offset += elementBytes) std::memcpy(repeated.data() + offset, texel.data(), elementBytes);
std::array<std::uint32_t, 4> pattern{};
std::memcpy(pattern.data(), repeated.data(), repeated.size());
return image.FillClear(std::span<const std::uint32_t, 4>(pattern), StorageTexture::WholeImage, refusal, allowRegisterClear);
}
void writeTexels(const ColorTarget& color, const std::array<std::byte, 16>& texel) {
const auto elementBytes = static_cast<std::size_t>(color.elementBytes);
std::vector<std::byte> texels(color.bytes);
for (std::size_t offset = 0; offset + elementBytes <= texels.size(); offset += elementBytes) std::memcpy(texels.data() + offset, texel.data(), elementBytes);
GuestMemory::Write(color.address, texels);
}
void storeClearTexels(const Context& context, const ColorTarget& color, const std::array<std::byte, 16>& texel) {
StorageTexture::FlushPending(color.address, color.bytes, nullptr, "fast-clear materialization");
const auto keys = ReadDccKeys(color.dccAddress, color.bytes);
if (!IsDccClear(keys)) return;
writeTexels(color, keys == DccKeys::ClearRegister ? texel : clearTexel(color, keys));
MarkDccUncompressed(context, color.dccAddress, color.bytes, colorKeyCount(color, color.bytes));
}
void storeSingleTexels(const Context& context, const ColorTarget& color) {
Require(color.tileMode != ColorTileMode::Linear, "comp-to-single DCC keys of a linear color target");
const ColorTargetLayout surface(color.extent.width, color.extent.height, color.tileMode, color.elementBytes, color.pipeBankXor);
Require(surface.Bytes() == color.bytes, "comp-to-single DCC keys over a color target whose layout differs from its surface");
StorageTexture::FlushPending(color.address, color.bytes, nullptr, "comp-to-single expansion");
std::vector<std::byte> texels(color.bytes);
GuestMemory::Read(color.address, texels, surface.Alignment());
constexpr std::size_t BlockBytes = 256;
for (std::uint32_t y = 0; y < color.extent.height; ++y) {
for (std::uint32_t x = 0; x < color.extent.width; ++x) {
const auto offset = surface.Offset(x, y);
const auto first = offset / BlockBytes * BlockBytes;
if (offset != first) std::memcpy(texels.data() + offset, texels.data() + first, color.elementBytes);
}
}
GuestMemory::Write(color.address, texels, surface.Alignment());
MarkDccUncompressed(context, color.dccAddress, color.bytes, colorKeyCount(color, color.bytes));
}
void materializeRegisterClear(const Context& context, const ColorTarget& color, StorageTexture& resident) {
if (color.dccAddress == 0 || resident.Descriptor().dccAddress != color.dccAddress) return;
if (ProvedCurrentDccKeys(color.dccAddress, color.bytes, resident.TargetKeyProof()) != DccKeys::ClearRegister) return;
const auto texel = clearTexel(color, DccKeys::ClearRegister);
const char* refusal = nullptr;
const bool pendingKeysKnown = KnownPendingDccKeys(color.dccAddress, color.bytes) == DccKeys::ClearRegister;
bool cleared = clearToTexel(resident, texel, color.elementBytes, refusal, pendingKeysKnown);
const auto keyBytes = static_cast<std::size_t>(color.bytes / 256);
if (!cleared && keyBytes != 0) {
if (auto* recorder = Recorder::Active(); recorder != nullptr && recorder->PendingWriteOverlaps(color.dccAddress, keyBytes)) {
Recorder::CountSync(2);
recorder->SyncThrough(color.dccAddress, keyBytes);
if (CurrentDccKeys(color.dccAddress, color.bytes) != DccKeys::ClearRegister) return;
cleared = clearToTexel(resident, texel, color.elementBytes, refusal);
}
}
if (cleared) {
MarkDccUncompressed(context, color.dccAddress, color.bytes, colorKeyCount(color, color.bytes));
return;
}
storeClearTexels(context, color, texel);
resident.Refresh();
}
enum class CmaskState { Expanded, Cleared, Partial };
struct CmaskProof {
std::size_t bytes = 0;
std::uint64_t generation = 0;
};
AgcDriver::Mutex& cmaskProofMutex() {
static AgcDriver::Mutex mutex;
return mutex;
}
std::unordered_map<std::uint64_t, CmaskProof>& cmaskProofs() {
static std::unordered_map<std::uint64_t, CmaskProof> proofs;
return proofs;
}
bool cmaskProved(std::uint64_t address, std::size_t bytes) {
if (GuestMemory::CollectWrites(address, bytes) == 0) return false;
std::lock_guard lock(cmaskProofMutex());
const auto found = cmaskProofs().find(address);
return found != cmaskProofs().end() && found->second.bytes == bytes && !GuestMemory::StoredOver(address, bytes, found->second.generation);
}
void proveCmask(std::uint64_t address, std::size_t bytes, std::uint64_t generation) {
std::lock_guard lock(cmaskProofMutex());
if (generation == 0) cmaskProofs().erase(address);
else cmaskProofs()[address] = {bytes, generation};
}
void requireCmaskCodes(std::uint32_t codes) {
Require((codes & 1u) == 0, "a CMASK fast clear of a DCC color target, whose clear belongs in its DCC keys, was recorded");
}
CmaskState readCmask(const ColorTarget& color, const CmaskLayout& layout, std::vector<std::uint32_t>& cleared) {
const auto address = color.cmaskAddress;
const auto bytes = layout.Bytes();
const bool locked = GuestMemory::GpuMutex().HeldByThisThread();
auto* recorder = Recorder::Active();
if (locked && recorder != nullptr && recorder->PendingWriteOverlaps(address, bytes)) {
Recorder::CountSync(2);
recorder->SyncThrough(address, bytes);
}
if (AnyShadowedOverlaps(address, bytes)) {
Require(locked, "a CMASK under a unit shadow must be read under the device lock");
PublishShadow(address, bytes, PublishScope::Whole, PublishReason::Keys);
if (recorder != nullptr) {
Recorder::CountSync(2);
recorder->Sync();
}
}
std::vector<std::byte> mask(bytes);
GuestMemory::Read(address, mask, CmaskLayout::Alignment);
const auto uniform = [&](std::byte value) { return std::all_of(mask.begin(), mask.end(), [&](std::byte entry) { return entry == value; }); };
if (color.coverageSamples > color.samples) {
for (std::uint32_t tileY = 0; tileY < layout.TilesY(); ++tileY) {
for (std::uint32_t tileX = 0; tileX < layout.TilesX(); ++tileX) {
const auto nibble = layout.Nibble(tileX, tileY);
const auto code = (std::to_integer<std::uint32_t>(mask[nibble / 2u]) >> ((nibble % 2u) * 4u)) & 0xfu;
if (code != 0u && (code >> 2u) != 3u) {
char text[128];
std::snprintf(text, sizeof(text), "AGC graphics: CMASK code 0x%x of a one-fragment color target is not implemented", code);
throw std::runtime_error(text);
}
}
}
}
if (uniform(std::byte{0xff})) return CmaskState::Expanded;
if (uniform(std::byte{0})) return CmaskState::Cleared;
for (std::uint32_t tileY = 0; tileY < layout.TilesY(); ++tileY) {
for (std::uint32_t tileX = 0; tileX < layout.TilesX(); ++tileX) {
const auto nibble = layout.Nibble(tileX, tileY);
const auto code = (std::to_integer<std::uint32_t>(mask[nibble / 2u]) >> ((nibble % 2u) * 4u)) & 0xfu;
if (code == 0u) cleared.push_back(tileY * layout.TilesX() + tileX);
}
}
if (cleared.empty()) return CmaskState::Expanded;
if (cleared.size() == static_cast<std::size_t>(layout.TilesX()) * layout.TilesY()) return CmaskState::Cleared;
return CmaskState::Partial;
}
void storeCmaskClearTexels(const ColorTarget& color, const CmaskLayout& layout, const std::vector<std::uint32_t>* tiles, const std::array<std::byte, 16>& texel) {
StorageTexture::FlushPending(color.address, color.bytes, nullptr, "fast-clear materialization");
const ColorTargetLayout surface(color.extent.width, color.extent.height, color.tileMode, color.elementBytes);
Require(surface.Bytes() == color.bytes, "CMASK fast clear over a color target whose layout differs from its surface");
std::vector<std::byte> texels(surface.Bytes());
GuestMemory::Read(color.address, texels, surface.Alignment());
const auto fill = [&](std::uint32_t tile) {
const auto x0 = (tile % layout.TilesX()) * 8u;
const auto y0 = (tile / layout.TilesX()) * 8u;
for (auto y = y0; y < std::min(y0 + 8u, color.extent.height); ++y) {
for (auto x = x0; x < std::min(x0 + 8u, color.extent.width); ++x) std::memcpy(texels.data() + surface.Offset(x, y), texel.data(), color.elementBytes);
}
};
if (tiles != nullptr) {
for (const auto tile : *tiles) fill(tile);
} else {
for (std::uint32_t tile = 0; tile < layout.TilesX() * layout.TilesY(); ++tile) fill(tile);
}
GuestMemory::Write(color.address, texels, surface.Alignment());
}
void recordCmaskClear(const Context& context, Recorder& recorder, const HostImport& import, const ColorTarget& color, const CmaskLayout& layout, const std::shared_ptr<StorageTexture>& resident, VkImageView view) {
const auto address = color.cmaskAddress;
const auto bytes = layout.Bytes();
StorageTexture::FlushPending(address, bytes, nullptr, "fast-clear materialization");
if (AnyShadowedOverlaps(address, bytes)) PublishShadow(address, bytes, PublishScope::Whole, PublishReason::Keys);
recorder.FlushKeyStoresOverlapping(address, bytes);
const auto commands = recorder.Commands();
if (resident != nullptr && !resident->Cached()) recorder.KeepBytes(resident.get(), static_cast<std::size_t>(resident->BudgetBytes()));
recorder.Keep(resident);
context.detiler->DispatchCmaskClear(commands, import.buffer, HostImportOffset(import, address), bytes, view, color.extent.width, color.extent.height, color.elementBytes, color.clearWords, color.dccAddress == 0);
recorder.NotePendingWrite(address, bytes);
proveCmask(address, bytes, GuestMemory::MarkWritten(address, bytes));
}
bool materializeCmaskClear(const Context& context, const ColorTarget& color, const std::shared_ptr<StorageTexture>& resident) {
if (color.cmaskAddress == 0) return false;
if (context.detiler != nullptr) requireCmaskCodes(context.detiler->CmaskErrors());
const CmaskLayout layout(color.extent.width, color.extent.height);
const auto bytes = layout.Bytes();
Require(color.cmaskBytes == bytes, "CMASK size differs from the color target's CMASK layout");
if (cmaskProved(color.cmaskAddress, bytes)) return false;
if (color.coverageSamples > color.samples) {
std::vector<std::uint32_t> codes;
static_cast<void>(readCmask(color, layout, codes));
}
auto* recorder = Recorder::Active();
if (resident != nullptr && context.detiler != nullptr && recorder != nullptr && GuestMemory::GpuMutex().HeldByThisThread()) {
const auto* import = HostImportFor(context, color.cmaskAddress, bytes);
const auto view = import != nullptr ? resident->ElementView() : VK_NULL_HANDLE;
if (view != VK_NULL_HANDLE) {
recordCmaskClear(context, *recorder, *import, color, layout, resident, view);
return true;
}
}
const auto collected = GuestMemory::CollectWrites(color.cmaskAddress, bytes);
std::vector<std::uint32_t> cleared;
const auto state = readCmask(color, layout, cleared);
if (state == CmaskState::Expanded) {
proveCmask(color.cmaskAddress, bytes, collected);
return false;
}
Require(color.dccAddress == 0, "CMASK fast clear of a DCC color target, whose clear belongs in its DCC keys");
const auto texel = clearTexel(color, DccKeys::ClearRegister);
const char* refusal = nullptr;
const bool filled = state == CmaskState::Cleared && color.mipCount == 1 && resident != nullptr && clearToTexel(*resident, texel, color.elementBytes, refusal);
if (!filled) {
storeCmaskClearTexels(color, layout, state == CmaskState::Cleared ? nullptr : &cleared, texel);
if (resident != nullptr) resident->Refresh();
}
const std::vector<std::byte> expanded(bytes, std::byte{0xff});
GuestMemory::Write(color.cmaskAddress, expanded, CmaskLayout::Alignment);
proveCmask(color.cmaskAddress, bytes, GuestMemory::CollectWrites(color.cmaskAddress, bytes));
return filled;
}
void imageBarrier(const Context& context, VkCommandBuffer commands, VkImage image, VkImageLayout oldLayout, VkImageLayout newLayout, VkPipelineStageFlags sourceStage, VkPipelineStageFlags destinationStage, VkAccessFlags sourceAccess, VkAccessFlags destinationAccess, VkImageSubresourceRange subresources = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}) {
VkImageMemoryBarrier barrier{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER};
barrier.srcAccessMask = sourceAccess;
barrier.dstAccessMask = destinationAccess;
barrier.oldLayout = oldLayout;
barrier.newLayout = newLayout;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.image = image;
barrier.subresourceRange = subresources;
context.Resolved(&DeviceFunctions::cmdPipelineBarrier, "vkCmdPipelineBarrier")(commands, sourceStage, destinationStage, 0, 0, nullptr, 0, nullptr, 1, &barrier);
}
void memoryBarrier(const Context& context, VkCommandBuffer commands, VkPipelineStageFlags sourceStage, VkPipelineStageFlags destinationStage, VkAccessFlags sourceAccess, VkAccessFlags destinationAccess) {
const VkMemoryBarrier barrier{VK_STRUCTURE_TYPE_MEMORY_BARRIER, nullptr, sourceAccess, destinationAccess};
context.Resolved(&DeviceFunctions::cmdPipelineBarrier, "vkCmdPipelineBarrier")(commands, sourceStage, destinationStage, 0, 1, &barrier, 0, nullptr, 0, nullptr);
}
// The color surface as one untailed SW_64KB_R_X mip for the GPU detiler, with tightly packed linear rows.
TileMipLayout ColorTargetMip(const ColorTarget& color, const ColorTargetLayout& layout) {
TileMipLayout mip{};
mip.width = color.extent.width;
mip.height = color.extent.height;
mip.blocksPerRow = layout.BlocksPerRow();
mip.pitchBytes = color.extent.width * color.elementBytes;
mip.tiledSize = layout.Bytes();
mip.linearSize = layout.LinearBytes();
return mip;
}
// APS5_PROFILE_DRAW: per-draw phase timers in microseconds (a recorded draw's phases are far below
// the millisecond the old print rounded to), totalled over 10 s in the [draws] line.
enum DrawPhase : std::size_t { PhaseValidate, PhaseVertex, PhaseSetup, PhaseReadTarget, PhasePrepare, PhaseLookup, PhaseResources, PhasePipeline, PhaseRecord, PhaseKeep, PhaseSync, PhaseWriteBack, PhaseDescribe, PhaseCount };
constexpr std::array<const char*, PhaseCount> DrawPhaseNames{"validate", "vertex", "setup", "readTarget", "prepare", "lookup", "resources", "pipeline", "record", "keep", "sync", "writeBack", "describe"};
// Why a draw did not go into the recorder without a wait (counted in the [draws] line): its targets
// are not all resident, no recorder is active, a switch (APS5_SYNC_DRAWS, APS5_DUMP_TARGETS,
// APS5_SYNC_COMPLETION_DRAWS) forced it, or its completion work writes copied guest buffers or
// releases an address-based build's lease, which the CPU must not outrun (see `recorded` in Draw).
enum SyncReason : std::size_t { SyncNone, SyncNotResident, SyncNoRecorder, SyncDisabled, SyncCopiedWrites, SyncLease, SyncCount };
constexpr std::array<const char*, SyncCount> SyncReasonNames{"none", "non-resident target", "no recorder", "disabled", "copied writes", "lease"};
constexpr std::size_t IndirectPathCount = static_cast<std::size_t>(IndirectDrawPath::Count);
constexpr std::array<const char*, IndirectPathCount> IndirectDrawPathNames{"gpu-side", "patched SGPR not folded", "fetch offset unknown", "non-vertex path", "GE_INDX_OFFSET", "draw index", "vertex range too large", "feature gap", "pending image results", "pending label or copied write", "not imported", "disabled", "index range not fully readable", "index limit unknown"};
// What became of one draw, for the totals.
struct DrawOutcome {
// In the recorder; `waited` when the recorder was synced right after (copied writes or a lease).
bool recorded = false;
bool waited = false;
bool completion = false;
// A recorded draw began a render pass of its own, or continued the previous draw's.
bool passBegun = false;
bool passContinued = false;
PassBreak passBreak = PassBreak::Continued;
bool keyStoresFlushed = false;
bool storesFlushed = false;
bool addressDraw = false;
SyncReason reason = SyncNone;
// Shader validation memo (see CachedFragmentOutputs).
bool validateMemoized = false;
bool validateHit = false;
// A build that acquired the allocation registry lease (BDA), whose cost sits outside the
// build's own sub-phases.
bool addressBased = false;
// Resident target lookups, and those that took a millisecond or more. Whether a slow one
// re-uploaded the image or just walked its pages under contention is not visible from here
// (StorageTexture::Version advances on every MarkDirty as well as on an upload, and Generation
// is stamped afresh by every write-watch walk): the [texture] line's "reused" and "direct
// uploads" counters and APS5_TRACE_UPLOAD name the actual uploads.
std::uint64_t targetLookups = 0;
std::uint64_t slowLookups = 0;
double slowLookupUs = 0;
// The lookups by whether the draw's scissor covers the whole target (an area-scoped proof
// would change nothing for those), the pages their write-watch collects walked and their time.
std::uint64_t fullScissorLookups = 0;
std::uint64_t partialLookups = 0;
std::uint64_t pagesWalked = 0;
double lookupUs = 0;
// How the draw's resources came about (DrawKind), for the per-kind averages.
std::size_t kind = 0;
// The flush hook's fence waits made inside this draw (index and vertex reads, the target
// lookups' flushes, the build's texture lookups): nested in the draw's GpuMutex hold, so they
// are the part of the hold that is waiting rather than working. The draw's own syncs (a
// recorded-then-waited draw's recorder Sync, a synchronous draw's SubmitAndWait) are kept apart
// in ownSyncUs: those wait by design and would otherwise count as nested hook waits.
double hookWaitUs = 0;
double ownSyncUs = 0;
};
// The resources of a draw: a recipe hit (reserved for the draw recipe step), a resource-cache
// template hit, a build, or an address-based (BDA) build.
enum DrawKind : std::size_t { KindRecipeHit, KindTemplateHit, KindBuild, KindBda, KindCount };
constexpr std::array<const char*, KindCount> DrawKindNames{"recipe hit", "template hit", "build", "BDA"};
struct DrawProfile {
AgcDriver::Mutex mutex;
std::array<double, KindCount> kindUs{};
std::array<std::uint64_t, KindCount> kindCounts{};
std::uint64_t fullScissorLookups = 0;
std::uint64_t partialLookups = 0;
std::uint64_t pagesWalked = 0;
double lookupUs = 0;
std::array<double, PhaseCount> totalsUs{};
// The longest single draw's time per phase, and the longest draw: the [lock] line's 'draw'
// hold max (tens of ms against an average well under a millisecond) needs a phase name.
std::array<double, PhaseCount> maxUs{};
double maxDrawUs = 0;
double hookWaitUs = 0;
double maxHookWaitUs = 0;
double ownSyncUs = 0;
// The resources build's sub-phases (ShaderResources::Timing) of draws only; dispatches report
// theirs in the [resources] line. `other` is the rest of the build (prepareAddressBindings:
// the registry lease and snapshots of an address-based build, the BDA table, the layout
// lookup), and how much of it address-based builds account for.
double bindingsUs = 0;
double uploadUs = 0;
double descriptorsUs = 0;
double otherUs = 0;
double addressOtherUs = 0;
std::uint64_t addressBuilds = 0;
std::uint64_t draws = 0;
std::uint64_t recorded = 0;
std::uint64_t waited = 0;
// Recorded draws whose write-back (BDA fault check) runs as a completion action instead of
// making the draw synchronous (see APS5_SYNC_COMPLETION_DRAWS).
std::uint64_t completion = 0;
// Render passes recorded draws began, and draws that continued the previous draw's pass.
std::uint64_t passesBegun = 0;
std::uint64_t passesContinued = 0;
std::array<DrawPassCounts, 2> passTotals{};
std::array<std::uint64_t, PassBreakCount> passBreaks{};
std::array<std::uint64_t, PassBreakCount> reportedPassBreaks{};
std::array<std::uint64_t, SyncCount> reasons{};
// The CPU inside Graphics::Draw, split by outcome: a synchronous draw costs ten times a recorded
// one, so one average would only show the synchronous population.
double recordedUs = 0;
double waitedUs = 0;
double synchronousUs = 0;
std::uint64_t targetLookups = 0;
std::uint64_t slowLookups = 0;
double slowLookupUs = 0;
// Resource cache outcomes: hits, misses (built and inserted when reusable), entries that failed
// Revalidate, and draws that could not use the cache (synchronous, no variant id, or disabled).
// Which key words the misses differ in is the cache's own "[rescache] miss churn" line
// (ResourceCache::noteMiss compares each miss with the last key of the same variants).
std::uint64_t cacheHits = 0;
std::uint64_t cacheMisses = 0;
std::uint64_t cacheInvalidated = 0;
std::uint64_t uncacheable = 0;
// Shader validation memo (see CachedFragmentOutputs).
std::uint64_t validateHits = 0;
std::uint64_t validateMisses = 0;
// Draw recipe outcomes (DrawWithRecipe): hits, and misses by DrawRecipeMiss.
std::uint64_t recipeHits = 0;
std::array<std::uint64_t, static_cast<std::size_t>(DrawRecipeMiss::Count)> recipeMisses{};
// Indirect draws by path (IndirectDrawPath), the GPU-side ones whose records were rewritten
// with a constant, and the time of the CPU record reads (their syncs).
std::array<std::uint64_t, IndirectPathCount> indirect{};
std::uint64_t indirectRewritten = 0;
std::uint64_t indirectEmpty = 0;
double indirectReadUs = 0;
// Draw packets that drew nothing, by DrawSkip, and their time.
std::array<std::uint64_t, static_cast<std::size_t>(DrawSkip::Count)> skips{};
std::array<double, static_cast<std::size_t>(DrawSkip::Count)> skipUs{};
std::chrono::steady_clock::time_point lastReport = std::chrono::steady_clock::now();
};
constexpr std::array<const char*, static_cast<std::size_t>(DrawSkip::Count)> DrawSkipNames{"nothing to draw", "prechecked", "thrown"};
DrawProfile& Profile() {
static DrawProfile profile;
return profile;
}
// Adds one draw's phases to the totals and prints the [draws] and [rescache] lines every 10 s.
void reportDraw(const std::array<double, PhaseCount>& us, const ShaderResources::BuildTiming* built, const DrawOutcome& outcome) {
auto& profile = Profile();
std::lock_guard lock(profile.mutex);
double drawUs = 0;
for (std::size_t i = 0; i < PhaseCount; ++i) {
profile.totalsUs[i] += us[i];
profile.maxUs[i] = std::max(profile.maxUs[i], us[i]);
drawUs += us[i];
}
profile.maxDrawUs = std::max(profile.maxDrawUs, drawUs);
profile.hookWaitUs += outcome.hookWaitUs;
profile.maxHookWaitUs = std::max(profile.maxHookWaitUs, outcome.hookWaitUs);
profile.ownSyncUs += outcome.ownSyncUs;
if (built != nullptr) {
profile.bindingsUs += built->bindingsMs * 1000.0;
profile.uploadUs += built->uploadMs * 1000.0;
profile.descriptorsUs += built->descriptorsMs * 1000.0;
const auto other = std::max(0.0, us[PhaseResources] - (built->bindingsMs + built->uploadMs + built->descriptorsMs) * 1000.0);
profile.otherUs += other;
if (outcome.addressBased) {
profile.addressOtherUs += other;
++profile.addressBuilds;
}
}
++profile.draws;
if (outcome.recorded) ++(outcome.waited ? profile.waited : profile.recorded);
if (outcome.completion) ++profile.completion;
if (outcome.passBegun) ++profile.passesBegun;
if (outcome.passBegun) ++profile.passBreaks[static_cast<std::size_t>(outcome.passBreak)];
if (outcome.passContinued) ++profile.passesContinued;
if (outcome.recorded) {
auto& totals = profile.passTotals[outcome.addressDraw ? 1 : 0];
++totals.draws;
if (outcome.passBegun) ++totals.passesBegun;
if (outcome.passContinued) ++totals.passesContinued;
if (outcome.keyStoresFlushed) ++totals.keyStoreFlushes;
if (outcome.storesFlushed) ++totals.storeFlushes;
}
++profile.reasons[outcome.reason];
(outcome.recorded ? (outcome.waited ? profile.waitedUs : profile.recordedUs) : profile.synchronousUs) += drawUs;
profile.targetLookups += outcome.targetLookups;
profile.slowLookups += outcome.slowLookups;
profile.slowLookupUs += outcome.slowLookupUs;
profile.fullScissorLookups += outcome.fullScissorLookups;
profile.partialLookups += outcome.partialLookups;
profile.pagesWalked += outcome.pagesWalked;
profile.lookupUs += outcome.lookupUs;
if (outcome.kind < KindCount) {
++profile.kindCounts[outcome.kind];
profile.kindUs[outcome.kind] += drawUs;
}
if (outcome.validateMemoized) ++(outcome.validateHit ? profile.validateHits : profile.validateMisses);
const auto now = std::chrono::steady_clock::now();
if (now - profile.lastReport < std::chrono::seconds(10)) return;
profile.lastReport = now;
const auto synchronous = profile.draws - profile.recorded - profile.waited;
const auto average = [](double total, std::uint64_t count) { return count != 0 ? total / static_cast<double>(count) : 0.0; };
char line[2048];
int n = std::snprintf(line, sizeof(line), "[draws] %llu draws over 10 s (%llu recorded avg %.0f us, of them %llu with completion; %llu recorded then waited avg %.0f us; %llu synchronous avg %.0f us; render passes %llu begun", static_cast<unsigned long long>(profile.draws), static_cast<unsigned long long>(profile.recorded), average(profile.recordedUs, profile.recorded), static_cast<unsigned long long>(profile.completion), static_cast<unsigned long long>(profile.waited), average(profile.waitedUs, profile.waited), static_cast<unsigned long long>(synchronous), average(profile.synchronousUs, synchronous), static_cast<unsigned long long>(profile.passesBegun));
const auto room = [&] { return n > 0 && static_cast<std::size_t>(n) < sizeof(line); };
bool listed = false;
for (std::size_t i = 1; i < PassBreakCount && room(); ++i) {
const auto count = profile.passBreaks[i] - profile.reportedPassBreaks[i];
if (count == 0) continue;
n += std::snprintf(line + n, sizeof(line) - static_cast<std::size_t>(n), "%s%s %llu", listed ? ", " : " (", PassBreakNames[i], static_cast<unsigned long long>(count));
listed = true;
}
if (room()) n += std::snprintf(line + n, sizeof(line) - static_cast<std::size_t>(n), "%s, %llu draws continued one; waited or synchronous because:", listed ? ")" : "", static_cast<unsigned long long>(profile.passesContinued));
for (std::size_t i = SyncNone + 1; i < SyncCount && room(); ++i) {
if (profile.reasons[i] != 0) n += std::snprintf(line + n, sizeof(line) - static_cast<std::size_t>(n), " %s %llu", SyncReasonNames[i], static_cast<unsigned long long>(profile.reasons[i]));
}
if (room()) n += std::snprintf(line + n, sizeof(line) - static_cast<std::size_t>(n), "):");
for (std::size_t i = 0; i < PhaseCount && room(); ++i) {
if (profile.totalsUs[i] <= 0) continue;
n += std::snprintf(line + n, sizeof(line) - static_cast<std::size_t>(n), " %s=%.1fms", DrawPhaseNames[i], profile.totalsUs[i] / 1000.0);
if (i == PhaseResources && room()) n += std::snprintf(line + n, sizeof(line) - static_cast<std::size_t>(n), " (bindings %.1f, upload %.1f, descriptors %.1f, other %.1f of which %.1f in %llu address-based builds)", profile.bindingsUs / 1000.0, profile.uploadUs / 1000.0, profile.descriptorsUs / 1000.0, profile.otherUs / 1000.0, profile.addressOtherUs / 1000.0, static_cast<unsigned long long>(profile.addressBuilds));
if (i == PhaseReadTarget && room()) n += std::snprintf(line + n, sizeof(line) - static_cast<std::size_t>(n), " (%llu resident lookups, %llu of them >= 1 ms = %.1f; target lookups: full-scissor %llu / partial %llu / pages walked %llu / %.0f us)", static_cast<unsigned long long>(profile.targetLookups), static_cast<unsigned long long>(profile.slowLookups), profile.slowLookupUs / 1000.0, static_cast<unsigned long long>(profile.fullScissorLookups), static_cast<unsigned long long>(profile.partialLookups), static_cast<unsigned long long>(profile.pagesWalked), profile.lookupUs);
}
if (room()) n += std::snprintf(line + n, sizeof(line) - static_cast<std::size_t>(n), "; per kind (avg us, count):");
for (std::size_t kind = 0; kind < KindCount && room(); ++kind) {
n += std::snprintf(line + n, sizeof(line) - static_cast<std::size_t>(n), " %s %.0f (%llu)", DrawKindNames[kind], average(profile.kindUs[kind], profile.kindCounts[kind]), static_cast<unsigned long long>(profile.kindCounts[kind]));
}
// The longest draw and the longest single phase of any draw (which phase a long 'draw' hold
// was), plus the hook waits nested inside the draws.
if (room()) n += std::snprintf(line + n, sizeof(line) - static_cast<std::size_t>(n), "; longest draw %.1f ms, longest phase of any draw:", profile.maxDrawUs / 1000.0);
for (std::size_t i = 0; i < PhaseCount && room(); ++i) {
if (profile.maxUs[i] < 500.0) continue;
n += std::snprintf(line + n, sizeof(line) - static_cast<std::size_t>(n), " %s %.1f", DrawPhaseNames[i], profile.maxUs[i] / 1000.0);
}
if (room()) n += std::snprintf(line + n, sizeof(line) - static_cast<std::size_t>(n), "; hook waits inside draws %.1f ms (max %.1f; the draws' own syncs, %.1f ms, not counted)", profile.hookWaitUs / 1000.0, profile.maxHookWaitUs / 1000.0, profile.ownSyncUs / 1000.0);
std::uint64_t indirectCpu = 0;
for (std::size_t i = 1; i < IndirectPathCount; ++i) indirectCpu += profile.indirect[i];
if ((profile.indirect[0] != 0 || indirectCpu != 0 || profile.indirectEmpty != 0) && room()) {
n += std::snprintf(line + n, sizeof(line) - static_cast<std::size_t>(n), "; indirect: gpu-side %llu (%llu rewritten), cpu-side %llu (", static_cast<unsigned long long>(profile.indirect[0]), static_cast<unsigned long long>(profile.indirectRewritten), static_cast<unsigned long long>(indirectCpu));
for (std::size_t i = 1; i < IndirectPathCount && room(); ++i) {
if (profile.indirect[i] != 0) n += std::snprintf(line + n, sizeof(line) - static_cast<std::size_t>(n), " %s %llu", IndirectDrawPathNames[i], static_cast<unsigned long long>(profile.indirect[i]));
}
if (room()) n += std::snprintf(line + n, sizeof(line) - static_cast<std::size_t>(n), "), empty skipped before their stages %llu, argument reads %.1f ms", static_cast<unsigned long long>(profile.indirectEmpty), profile.indirectReadUs / 1000.0);
}
if (room()) n += std::snprintf(line + n, sizeof(line) - static_cast<std::size_t>(n), "; skipped packets:");
for (std::size_t i = 0; i < profile.skips.size() && room(); ++i) {
n += std::snprintf(line + n, sizeof(line) - static_cast<std::size_t>(n), " %s %llu in %.1f ms", DrawSkipNames[i], static_cast<unsigned long long>(profile.skips[i]), profile.skipUs[i] / 1000.0);
}
if (room()) n += std::snprintf(line + n, sizeof(line) - static_cast<std::size_t>(n), "; recipe hits %llu, misses by reason:", static_cast<unsigned long long>(profile.recipeHits));
for (std::size_t i = 1; i < profile.recipeMisses.size() && room(); ++i) {
n += std::snprintf(line + n, sizeof(line) - static_cast<std::size_t>(n), " %s %llu", DrawRecipeMissName(static_cast<DrawRecipeMiss>(i)), static_cast<unsigned long long>(profile.recipeMisses[i]));
}
AgcDriver::ProfilePrint_nid_no_patch("%s\n", line);
AgcDriver::ProfilePrint_nid_no_patch("[rescache] draws: %llu hits, %llu misses, %llu invalidated, %llu uncacheable; validation memo %llu hits / %llu misses (which key words the misses differ in: the miss churn line)\n", static_cast<unsigned long long>(profile.cacheHits), static_cast<unsigned long long>(profile.cacheMisses), static_cast<unsigned long long>(profile.cacheInvalidated), static_cast<unsigned long long>(profile.uncacheable), static_cast<unsigned long long>(profile.validateHits), static_cast<unsigned long long>(profile.validateMisses));
profile.totalsUs.fill(0);
profile.maxUs.fill(0);
profile.maxDrawUs = profile.hookWaitUs = profile.maxHookWaitUs = profile.ownSyncUs = 0;
profile.bindingsUs = profile.uploadUs = profile.descriptorsUs = profile.otherUs = profile.addressOtherUs = 0;
profile.addressBuilds = 0;
profile.draws = profile.recorded = profile.waited = profile.completion = 0;
profile.passesBegun = profile.passesContinued = 0;
profile.reportedPassBreaks = profile.passBreaks;
profile.reasons.fill(0);
profile.recordedUs = profile.waitedUs = profile.synchronousUs = 0;
profile.targetLookups = profile.slowLookups = 0;
profile.slowLookupUs = 0;
profile.fullScissorLookups = profile.partialLookups = profile.pagesWalked = 0;
profile.lookupUs = 0;
profile.kindUs.fill(0);
profile.kindCounts.fill(0);
profile.cacheHits = profile.cacheMisses = profile.cacheInvalidated = profile.uncacheable = 0;
profile.validateHits = profile.validateMisses = 0;
profile.recipeHits = 0;
profile.recipeMisses.fill(0);
profile.indirect.fill(0);
profile.indirectRewritten = 0;
profile.indirectReadUs = 0;
profile.skips.fill(0);
profile.skipUs.fill(0);
}
void countCache(std::uint64_t DrawProfile::*counter) {
static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr;
if (!profile) return;
auto& stats = Profile();
std::lock_guard lock(stats.mutex);
++(stats.*counter);
}
}
// ValidateShaders decodes every SPIR-V instruction of every stage on every draw. Its outcome depends
// only on the stages' compiled variants (a variant id names identical SPIR-V and binding layout),
// their push constant placement and vertex attribute shapes, and the state fields it checks, so the
// fragment output set is remembered by exactly those. Nothing here is keyed by pointer: the results
// a draw hands in live in a per-draw vector. A stage without a variant id is validated as before,
// except the rect-list control and evaluation stages, which are generated from the vertex and
// fragment results the key already names (the pipeline key treats them the same way). `memoized`
// says whether the memo applied, `hit` whether it answered. APS5_NO_VALIDATE_CACHE=1 validates
// every draw.
bool ValidationKey(const Context& context, std::span<const CompiledShader> shaders, const State& state, std::vector<std::uint64_t>& key) {
using Stage = ShaderRecompiler::ShaderStage;
static const bool disabled = std::getenv("APS5_NO_VALIDATE_CACHE") != nullptr;
const auto add = [&](auto value) { key.push_back(static_cast<std::uint64_t>(value)); };
bool keyed = !disabled;
if (keyed) {
key.reserve(40 + shaders.size() * 12);
add(shaders.size());
const bool patches = BarycentricPatches(state, shaders);
add(patches ? static_cast<std::uint64_t>(state.provokingVertexMode) + 1u : 0u);
for (const auto& shader : shaders) {
Require(shader.program != nullptr, "missing compiled shader");
const auto& program = *shader.program;
const bool generated = ((state.rectList || patches) && (shader.stage == Stage::TessellationControl || shader.stage == Stage::TessellationEvaluation)) || shader.stage == Stage::Geometry;
if (!generated && program.PipelineVariantId() == 0) {
keyed = false;
break;
}
add(shader.stage);
add(generated ? std::uint64_t{0} : program.PipelineVariantId());
add(shader.pushConstantOffset);
add(program.pushConstants.size());
add(program.bdaAbiVersion);
add(program.vertexAttributes.size());
for (const auto& attribute : program.vertexAttributes) {
add(attribute.location);
add(attribute.components);
add(attribute.fetchIndex);
add(attribute.formatComponents);
// The data format bits of the V# decide the attribute's signature.
add((attribute.resource.fields[3] >> 12u) & 0x7fu);
}
}
}
if (keyed) {
add(state.stages.path);
add(state.rectList);