-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathDevice.cpp
More file actions
3655 lines (3183 loc) · 144 KB
/
Copy pathDevice.cpp
File metadata and controls
3655 lines (3183 loc) · 144 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
//===- DX/Device.cpp - DirectX Device API ---------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
//
//===----------------------------------------------------------------------===//
#include <wrl/client.h>
#include <cstdint>
#include <d3d12.h>
#include <d3dx12.h>
#include <dxcore.h>
#include <dxgiformat.h>
#include <dxguids.h>
#ifndef _WIN32
#include <poll.h>
#include <sys/eventfd.h>
#include <unistd.h>
#include <wsl/winadapter.h>
#endif
// The windows headers define these macros which conflict with the C++ standard
// library. Undefining them before including any LLVM C++ code prevents errors.
#undef max
#undef min
#include "API/Capabilities.h"
#include "API/Device.h"
#include "API/Encoder.h"
#include "API/FormatConversion.h"
#include "DXFeatures.h"
#include "Support/Pipeline.h"
#include "Support/WinError.h"
#include "DXResources.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Object/DXContainer.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/FormatVariadic.h"
#include "llvm/Support/Signals.h"
#include "../Util.h"
#include <atomic>
#include <codecvt>
#include <locale>
#include <mutex>
using namespace offloadtest;
using Microsoft::WRL::ComPtr;
using ID3D12DeviceX = ID3D12Device5;
using ID3D12GraphicsCommandListX = ID3D12GraphicsCommandList6;
template <> char CapabilityValueEnum<directx::ShaderModel>::ID = 0;
template <> char CapabilityValueEnum<directx::RootSignature>::ID = 0;
template <> char CapabilityValueEnum<directx::MeshShaderTier>::ID = 0;
template <> char CapabilityValueEnum<directx::RaytracingTier>::ID = 0;
static std::mutex SignalHandlerMutex;
static llvm::SmallVector<ID3D12DeviceX *> SignalHandlerDevices;
static void dumpD3DInfoQueues(void *) {
const std::lock_guard<std::mutex> Lock(SignalHandlerMutex);
for (ID3D12DeviceX *Device : SignalHandlerDevices) {
ComPtr<ID3D12InfoQueue> InfoQueue;
HRESULT HR = Device->QueryInterface(InfoQueue.GetAddressOf());
if (FAILED(HR)) {
llvm::errs() << "Failed to query D3D info queue\n";
continue;
}
for (int I = 0, E = InfoQueue->GetNumStoredMessages(); I < E; ++I) {
SIZE_T Len = 0;
HR = InfoQueue->GetMessage(I, NULL, &Len);
if (FAILED(HR)) {
llvm::errs() << "Failed to get message " << I
<< " from D3D info queue\n";
} else {
D3D12_MESSAGE *Msg = (D3D12_MESSAGE *)malloc(Len);
HR = InfoQueue->GetMessage(I, Msg, &Len);
llvm::errs() << "D3D: " << Msg->pDescription << "\n";
free(Msg);
}
}
}
}
// D3D12 requires the RowPitch in a placed subresource footprint (used for
// texture <-> buffer copies via CopyTextureRegion) to be a multiple of
// D3D12_TEXTURE_DATA_PITCH_ALIGNMENT (256 bytes). For textures whose natural
// row size (Width * elementSize) is already a multiple of 256, this is a
// no-op; for smaller rows it pads up.
static uint32_t getAlignedTexturePitch(uint32_t Width, uint32_t ElementSize) {
return llvm::alignTo(Width * ElementSize, D3D12_TEXTURE_DATA_PITCH_ALIGNMENT);
}
static D3D12_PRIMITIVE_TOPOLOGY_TYPE
getDXPrimitiveTopologyType(PrimitiveTopology Topology) {
switch (Topology) {
case PrimitiveTopology::TriangleList:
return D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
case PrimitiveTopology::PointList:
return D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT;
case PrimitiveTopology::PatchList:
return D3D12_PRIMITIVE_TOPOLOGY_TYPE_PATCH;
case PrimitiveTopology::LineList:
return D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE;
}
llvm_unreachable("All PrimitiveTopology cases handled");
}
static D3D_PRIMITIVE_TOPOLOGY
getDXPrimitiveTopology(PrimitiveTopology Topology,
std::optional<uint32_t> PatchControlPoints) {
switch (Topology) {
case PrimitiveTopology::TriangleList:
return D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
case PrimitiveTopology::PointList:
return D3D_PRIMITIVE_TOPOLOGY_POINTLIST;
case PrimitiveTopology::PatchList:
// _N_CONTROL_POINT_PATCHLIST enums are contiguous from 1..32.
assert(PatchControlPoints && *PatchControlPoints >= 1 &&
*PatchControlPoints <= 32);
return static_cast<D3D_PRIMITIVE_TOPOLOGY>(
D3D_PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST +
(*PatchControlPoints - 1));
case PrimitiveTopology::LineList:
return D3D_PRIMITIVE_TOPOLOGY_LINELIST;
}
llvm_unreachable("All PrimitiveTopology cases handled");
}
static uint64_t getAlignedTextureBufferSize(const CPUBuffer &B) {
const uint64_t AlignedPitch =
getAlignedTexturePitch(B.OutputProps.Width, B.getElementSize());
const uint64_t LastRowSize =
uint64_t(B.OutputProps.Width) * B.getElementSize();
return uint64_t(B.OutputProps.Height - 1) * AlignedPitch + LastRowSize;
}
static BufferUsage bufferUsageFromResourceKind(ResourceKind Kind) {
// Determine Buffer Usage
switch (Kind) {
case ResourceKind::Buffer:
case ResourceKind::StructuredBuffer:
case ResourceKind::ByteAddressBuffer:
case ResourceKind::RWBuffer:
case ResourceKind::RWStructuredBuffer:
case ResourceKind::RWByteAddressBuffer:
return BufferUsage::Storage;
case ResourceKind::ConstantBuffer:
return BufferUsage::ConstantBuffer;
case ResourceKind::Texture2D:
case ResourceKind::RWTexture2D:
case ResourceKind::Sampler:
case ResourceKind::SampledTexture2D:
case ResourceKind::AccelerationStructure:
llvm_unreachable("Invalid case, ResourceKind is not a buffer.");
}
llvm_unreachable("All ResourceKind cases handled");
}
static BufferShaderAccessType bufferShaderAccessTypeFromResourceKind(
const Resource &Resource, BufferShaderAccessTypeParams &OutParams) {
// Determine Buffer Access Type
switch (Resource.Kind) {
case ResourceKind::Buffer:
case ResourceKind::RWBuffer: {
auto FmtOrErr =
toFormat(Resource.BufferPtr->Format, Resource.BufferPtr->Channels);
if (!FmtOrErr) {
printf("Invalid format! FMT: %d, CHANNELS: %d\n",
Resource.BufferPtr->Format, Resource.BufferPtr->Channels);
assert(false && "Invalid format.");
}
OutParams.Fmt = *FmtOrErr;
return BufferShaderAccessType::Typed;
}
case ResourceKind::StructuredBuffer:
case ResourceKind::RWStructuredBuffer:
OutParams.StructureStride = Resource.BufferPtr->getElementSize();
return BufferShaderAccessType::Structured;
case ResourceKind::ByteAddressBuffer:
case ResourceKind::RWByteAddressBuffer:
case ResourceKind::ConstantBuffer:
return BufferShaderAccessType::Raw;
case ResourceKind::Texture2D:
case ResourceKind::RWTexture2D:
case ResourceKind::Sampler:
case ResourceKind::SampledTexture2D:
case ResourceKind::AccelerationStructure:
llvm_unreachable(
"Invalid case, non-buffers should have been filtered out.");
}
llvm_unreachable("All ResourceKind cases handled");
}
namespace {
class DXDevice;
class DXBuffer : public offloadtest::Buffer {
public:
ComPtr<ID3D12Resource> Buffer;
std::string Name;
BufferCreateDesc Desc;
size_t SizeInBytes;
uint64_t CounterOffsetInBytes;
// Contract: If a command on the command buffer needs a resource to be in a
// different state it should always transition it back to the PreferredState
// afterwards. The PreferredState is the state of the most common use case for
// that resource. This allows us to do state transitions without state
// tracking.
D3D12_RESOURCE_STATES PreferredState;
D3D12_CPU_DESCRIPTOR_HANDLE SRVHandle;
D3D12_CPU_DESCRIPTOR_HANDLE UAVHandle;
D3D12_CPU_DESCRIPTOR_HANDLE CBVHandle;
DXBuffer(ComPtr<ID3D12Resource> Buffer, llvm::StringRef Name,
BufferCreateDesc Desc, size_t SizeInBytes,
uint64_t CounterOffsetInBytes, D3D12_RESOURCE_STATES PreferredState,
D3D12_CPU_DESCRIPTOR_HANDLE SRVHandle,
D3D12_CPU_DESCRIPTOR_HANDLE UAVHandle,
D3D12_CPU_DESCRIPTOR_HANDLE CBVHandle)
: offloadtest::Buffer(GPUAPI::DirectX), Buffer(Buffer), Name(Name),
Desc(Desc), SizeInBytes(SizeInBytes),
CounterOffsetInBytes(CounterOffsetInBytes),
PreferredState(PreferredState), SRVHandle(SRVHandle),
UAVHandle(UAVHandle), CBVHandle(CBVHandle) {}
DXBuffer(const DXBuffer &) = delete;
DXBuffer(DXBuffer &&) = delete;
DXBuffer &operator=(const DXBuffer &) = delete;
DXBuffer &operator=(DXBuffer &&) = delete;
size_t getSizeInBytes() const override { return SizeInBytes; }
size_t querySparseTileSizeInBytes(const Device & /*Dev*/) const override {
return D3D12_TILED_RESOURCE_TILE_SIZE_IN_BYTES;
}
llvm::Expected<void *> map() override {
if (Desc.Location == MemoryLocation::GpuOnly)
return llvm::createStringError(std::errc::invalid_argument,
"Cannot map a GpuOnly buffer.");
void *Ptr = nullptr;
if (auto Err =
HR::toError(Buffer->Map(0, nullptr, &Ptr), "Failed to map buffer."))
return std::move(Err);
return Ptr;
}
void unmap() override { Buffer->Unmap(0, nullptr); }
const BufferCreateDesc &getDesc() const override { return Desc; }
static bool classof(const offloadtest::Buffer *B) {
return B->getAPI() == GPUAPI::DirectX;
}
};
class DXTexture : public offloadtest::Texture {
public:
ComPtr<ID3D12Resource> Resource;
// Contract: If a command on the command buffer needs a resource to be in a
// different state it should always transition it back to the PreferredState
// afterwards. The PreferredState is the state of the most common use case for
// that resource. This allows us to do state transitions without state
// tracking.
D3D12_RESOURCE_STATES PreferredState;
// Optional descriptors, depending on Desc.Usage.
// A zero ptr means no descriptor was created for that view type.
D3D12_CPU_DESCRIPTOR_HANDLE RTVHandle = {};
D3D12_CPU_DESCRIPTOR_HANDLE DSVHandle = {};
D3D12_CPU_DESCRIPTOR_HANDLE SRVHandle = {};
D3D12_CPU_DESCRIPTOR_HANDLE UAVHandle = {};
std::string Name;
TextureCreateDesc Desc;
DXTexture(ComPtr<ID3D12Resource> Resource, llvm::StringRef Name,
TextureCreateDesc Desc, D3D12_RESOURCE_STATES PreferredState,
D3D12_CPU_DESCRIPTOR_HANDLE SRVHandle,
D3D12_CPU_DESCRIPTOR_HANDLE UAVHandle)
: offloadtest::Texture(GPUAPI::DirectX), Resource(Resource),
PreferredState(PreferredState), SRVHandle(SRVHandle),
UAVHandle(UAVHandle), Name(Name), Desc(Desc) {}
TileShape querySparseTileShape(const Device &Dev) const override;
const TextureCreateDesc &getDesc() const override { return Desc; }
static bool classof(const offloadtest::Texture *T) {
return T->getAPI() == GPUAPI::DirectX;
}
};
class DXPipelineState : public offloadtest::PipelineState {
public:
std::string Name;
ComPtr<ID3D12RootSignature> RootSig;
ComPtr<ID3D12PipelineState> PSO;
// Only set for graphics pipelines.
std::optional<D3D_PRIMITIVE_TOPOLOGY> Topology;
// True for pipelines created via createPipelineRT — used by SBT / dispatch
// code to safely downcast to DXRayTracingPipelineState (parallel to
// VulkanPipelineState::IsRayTracing).
bool IsRayTracing = false;
DXPipelineState(llvm::StringRef Name, ComPtr<ID3D12RootSignature> RootSig,
ComPtr<ID3D12PipelineState> PSO,
std::optional<D3D_PRIMITIVE_TOPOLOGY> Topology,
bool IsRT = false)
: offloadtest::PipelineState(GPUAPI::DirectX), Name(Name),
RootSig(RootSig), PSO(PSO), Topology(Topology), IsRayTracing(IsRT) {}
static bool classof(const offloadtest::PipelineState *B) {
return B->getAPI() == GPUAPI::DirectX;
}
};
/// RT pipeline state: holds the ID3D12StateObject + cached
/// ID3D12StateObjectProperties for SBT identifier queries plus a
/// shader-name → identifier-pointer map. The `void *` identifiers are
/// owned by Properties — keep it alive for the SBT's lifetime.
class DXRayTracingPipelineState : public DXPipelineState {
public:
ComPtr<ID3D12StateObject> StateObject;
ComPtr<ID3D12StateObjectProperties> Properties;
llvm::StringMap<const void *> ShaderIdentifiers;
DXRayTracingPipelineState(llvm::StringRef Name,
ComPtr<ID3D12RootSignature> RootSig,
ComPtr<ID3D12StateObject> SO,
ComPtr<ID3D12StateObjectProperties> Props)
: DXPipelineState(Name, RootSig, /*PSO=*/nullptr, std::nullopt,
/*IsRT=*/true),
StateObject(SO), Properties(Props) {}
static bool classof(const offloadtest::PipelineState *B) {
if (B->getAPI() != GPUAPI::DirectX)
return false;
return static_cast<const DXPipelineState *>(B)->IsRayTracing;
}
};
class DXShaderBindingTable : public offloadtest::ShaderBindingTable {
public:
ComPtr<ID3D12Resource> Buffer;
// Pre-built ranges for D3D12_DISPATCH_RAYS_DESC. Sizes are zero for
// empty regions; raygen is a single record so it uses the no-stride
// variant.
D3D12_GPU_VIRTUAL_ADDRESS_RANGE RayGenRange{};
D3D12_GPU_VIRTUAL_ADDRESS_RANGE_AND_STRIDE MissRange{};
D3D12_GPU_VIRTUAL_ADDRESS_RANGE_AND_STRIDE HitGroupRange{};
D3D12_GPU_VIRTUAL_ADDRESS_RANGE_AND_STRIDE CallableRange{};
DXShaderBindingTable(ComPtr<ID3D12Resource> Buf,
D3D12_GPU_VIRTUAL_ADDRESS_RANGE RG,
D3D12_GPU_VIRTUAL_ADDRESS_RANGE_AND_STRIDE MS,
D3D12_GPU_VIRTUAL_ADDRESS_RANGE_AND_STRIDE HG,
D3D12_GPU_VIRTUAL_ADDRESS_RANGE_AND_STRIDE CL)
: offloadtest::ShaderBindingTable(GPUAPI::DirectX), Buffer(Buf),
RayGenRange(RG), MissRange(MS), HitGroupRange(HG), CallableRange(CL) {}
static bool classof(const offloadtest::ShaderBindingTable *S) {
return S->getAPI() == GPUAPI::DirectX;
}
};
class DXAccelerationStructure : public offloadtest::AccelerationStructure {
public:
ComPtr<ID3D12Resource> Resource;
D3D12_CPU_DESCRIPTOR_HANDLE SRVHandle;
DXAccelerationStructure(ComPtr<ID3D12Resource> Resource,
const AccelerationStructureSizes &Sizes)
: offloadtest::AccelerationStructure(GPUAPI::DirectX, Sizes),
Resource(Resource) {}
D3D12_GPU_VIRTUAL_ADDRESS getGPUVirtualAddress() const {
return Resource->GetGPUVirtualAddress();
}
static bool classof(const offloadtest::AccelerationStructure *AS) {
return AS->getAPI() == GPUAPI::DirectX;
}
};
class DXFence : public offloadtest::Fence {
public:
#ifdef _WIN32
DXFence(ComPtr<ID3D12Fence> Fence, HANDLE Event, llvm::StringRef Name)
#else // WSL
DXFence(ComPtr<ID3D12Fence> Fence, int Event, llvm::StringRef Name)
#endif
: Name(Name), Fence(Fence), Event(Event) {
}
std::string Name;
ComPtr<ID3D12Fence> Fence;
#ifdef _WIN32
HANDLE Event;
#else // WSL
int Event;
#endif
static llvm::Expected<std::unique_ptr<DXFence>> create(ID3D12DeviceX *Device,
llvm::StringRef Name) {
ComPtr<ID3D12Fence> Fence;
if (auto Err = HR::toError(
Device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&Fence)),
"Failed to create Fence."))
return Err;
#ifdef _WIN32
HANDLE Event = CreateEventA(nullptr, false, false, nullptr);
if (!Event)
#else // WSL
int Event = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
if (Event == -1)
#endif
return llvm::createStringError(std::errc::device_or_resource_busy,
"Failed to create event.");
return std::make_unique<DXFence>(Fence, Event, Name);
}
~DXFence() {
#ifdef _WIN32
CloseHandle(Event);
#else // WSL
close(Event);
#endif
}
uint64_t getFenceValue() override { return Fence->GetCompletedValue(); }
llvm::Error waitForCompletion(uint64_t SignalValue) override {
if (Fence->GetCompletedValue() >= SignalValue)
return llvm::Error::success();
#ifdef _WIN32
if (auto Err = HR::toError(Fence->SetEventOnCompletion(SignalValue, Event),
"Failed to register end event."))
return Err;
WaitForSingleObject(Event, INFINITE);
#else // WSL
if (auto Err =
HR::toError(Fence->SetEventOnCompletion(
SignalValue, reinterpret_cast<HANDLE>(Event)),
"Failed to register end event."))
return Err;
pollfd PollEvent;
PollEvent.fd = Event;
PollEvent.events = POLLIN;
PollEvent.revents = 0;
if (poll(&PollEvent, 1, -1) == -1)
return llvm::createStringError(
std::error_code(errno, std::system_category()), strerror(errno));
#endif
return llvm::Error::success();
}
};
class DXMemoryHeap : public offloadtest::MemoryHeap {
public:
DXMemoryHeap(ComPtr<ID3D12Heap> Heap, llvm::StringRef Name)
: offloadtest::MemoryHeap(GPUAPI::DirectX), Name(Name), Heap(Heap) {}
std::string Name;
ComPtr<ID3D12Heap> Heap;
static bool classof(const offloadtest::MemoryHeap *H) {
return H->getAPI() == GPUAPI::DirectX;
}
static llvm::Expected<std::unique_ptr<DXMemoryHeap>>
create(ID3D12DeviceX *Device, llvm::StringRef Name, size_t SizeInBytes) {
D3D12_HEAP_DESC HeapDesc = {};
HeapDesc.Properties = CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT);
HeapDesc.Alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT;
// Heap sizes must be a multiple of the placement alignment (64KB), which
// is also the tiled-resource tile size.
HeapDesc.SizeInBytes =
llvm::alignTo(SizeInBytes, D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT);
HeapDesc.Flags = D3D12_HEAP_FLAG_ALLOW_ALL_BUFFERS_AND_TEXTURES;
ComPtr<ID3D12Heap> Heap;
if (auto Err =
HR::toError(Device->CreateHeap(&HeapDesc, IID_PPV_ARGS(&Heap)),
"Failed to create memory heap."))
return Err;
const std::wstring WStr(Name.begin(), Name.end());
Heap->SetName(WStr.c_str());
return std::make_unique<DXMemoryHeap>(Heap, Name);
}
};
class DXQueue : public offloadtest::Queue {
public:
using Queue::submit;
ComPtr<ID3D12CommandQueue> Queue;
std::unique_ptr<DXFence> SubmitFence;
uint64_t FenceCounter = 0;
// Batches of command buffers submitted to the GPU that may still be
// in-flight. The ID3D12CommandAllocator owns the backing memory for
// recorded commands, so it must outlive GPU execution. Each batch
// records the fence value it signals so we can non-blockingly query
// progress and release completed batches.
struct InFlightBatch {
uint64_t FenceValue;
llvm::SmallVector<std::unique_ptr<offloadtest::CommandBuffer>> CBs;
};
llvm::SmallVector<InFlightBatch> InFlightBatches;
DXQueue(ComPtr<ID3D12CommandQueue> Queue,
std::unique_ptr<DXFence> SubmitFence)
: Queue(Queue), SubmitFence(std::move(SubmitFence)) {}
DXQueue(DXQueue &&) = default;
~DXQueue() override {}
static llvm::Expected<DXQueue>
createGraphicsQueue(ComPtr<ID3D12DeviceX> Device) {
const D3D12_COMMAND_QUEUE_DESC Desc = {D3D12_COMMAND_LIST_TYPE_DIRECT, 0,
D3D12_COMMAND_QUEUE_FLAG_NONE, 0};
ComPtr<ID3D12CommandQueue> CmdQueue;
if (auto Err = HR::toError(
Device->CreateCommandQueue(&Desc, IID_PPV_ARGS(&CmdQueue)),
"Failed to create command queue."))
return Err;
auto FenceOrErr = DXFence::create(Device.Get(), "QueueSubmitFence");
if (!FenceOrErr)
return FenceOrErr.takeError();
return DXQueue(CmdQueue, std::move(*FenceOrErr));
}
llvm::Expected<offloadtest::SubmitResult>
submit(llvm::SmallVector<std::unique_ptr<offloadtest::CommandBuffer>> CBs)
override;
llvm::Expected<offloadtest::SubmitResult>
updateTileMappings(offloadtest::Buffer &Resource,
llvm::ArrayRef<TileMapping> Mappings) override {
return updateTileMappingsImpl(llvm::cast<DXBuffer>(Resource).Buffer.Get(),
Mappings);
}
llvm::Expected<offloadtest::SubmitResult>
updateTileMappings(offloadtest::Texture &Resource,
llvm::ArrayRef<TileMapping> Mappings) override {
return updateTileMappingsImpl(
llvm::cast<DXTexture>(Resource).Resource.Get(), Mappings);
}
// Shared tile-mapping path for buffers and textures: they differ only in how
// a TileRegion maps onto the underlying ID3D12Resource, so both variants
// resolve to a native resource and funnel through here.
llvm::Expected<offloadtest::SubmitResult>
updateTileMappingsImpl(ID3D12Resource *Resource,
llvm::ArrayRef<TileMapping> Mappings) {
for (const TileMapping &M : Mappings) {
const D3D12_TILED_RESOURCE_COORDINATE StartCoord = {
M.Region.TileOffsetX, M.Region.TileOffsetY, M.Region.TileOffsetZ,
M.Region.Subresource};
D3D12_TILE_REGION_SIZE RegionSize = {};
RegionSize.Width = M.Region.NumTilesX;
RegionSize.Height = static_cast<UINT16>(M.Region.NumTilesY);
RegionSize.Depth = static_cast<UINT16>(M.Region.NumTilesZ);
// A box is only needed for multi-dimensional (texture) regions; a buffer
// is always a single linear run of tiles along X.
RegionSize.UseBox = M.Region.NumTilesY > 1 || M.Region.NumTilesZ > 1;
RegionSize.NumTiles =
M.Region.NumTilesX * M.Region.NumTilesY * M.Region.NumTilesZ;
// A null heap unbinds the region (reads return zero); otherwise bind it
// to the heap starting at BackingTileOffset.
ID3D12Heap *Heap = nullptr;
D3D12_TILE_RANGE_FLAGS RangeFlag = D3D12_TILE_RANGE_FLAG_NULL;
UINT HeapRangeStartOffset = 0;
if (M.Backing) {
Heap = llvm::cast<DXMemoryHeap>(M.Backing)->Heap.Get();
RangeFlag = D3D12_TILE_RANGE_FLAG_NONE;
HeapRangeStartOffset = static_cast<UINT>(M.BackingTileOffset);
}
const UINT RangeTileCount = RegionSize.NumTiles;
Queue->UpdateTileMappings(Resource, 1, &StartCoord, &RegionSize, Heap, 1,
&RangeFlag, &HeapRangeStartOffset,
&RangeTileCount, D3D12_TILE_MAPPING_FLAG_NONE);
}
// UpdateTileMappings runs on the queue timeline (not a command list), so
// signal the submit fence afterwards exactly like submit() does.
const uint64_t CurrentCounter = ++FenceCounter;
if (auto Err =
HR::toError(Queue->Signal(SubmitFence->Fence.Get(), CurrentCounter),
"Failed to signal after tile mapping update."))
return Err;
return offloadtest::SubmitResult{SubmitFence.get(), CurrentCounter};
}
};
class DXDevice; // forward decl — defined below in this same anon ns
class DXCommandBuffer : public offloadtest::CommandBuffer {
public:
ComPtr<ID3D12CommandAllocator> Allocator;
ComPtr<ID3D12GraphicsCommandListX> CmdList;
/// Back-pointer to the owning device. Used by encoders that need access to
/// device-level resources (e.g. allocating AS scratch buffers).
DXDevice *Dev = nullptr;
/// Whether a UAV barrier is pending from a prior compute command.
bool PendingUAVBarrier = false;
llvm::SmallVector<D3D12_RESOURCE_BARRIER> PendingTransitions;
/// Buffers that must outlive command-buffer submission (e.g. AS scratch
/// and TLAS instance buffers used during builds).
llvm::SmallVector<std::unique_ptr<offloadtest::Buffer>> KeepAliveOwned;
static llvm::Expected<std::unique_ptr<DXCommandBuffer>>
create(ComPtr<ID3D12DeviceX> Device) {
auto CB = std::unique_ptr<DXCommandBuffer>(new DXCommandBuffer());
if (auto Err = HR::toError(
Device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT,
IID_PPV_ARGS(&CB->Allocator)),
"Failed to create command allocator."))
return Err;
if (auto Err = HR::toError(
Device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT,
CB->Allocator.Get(), nullptr,
IID_PPV_ARGS(&CB->CmdList)),
"Failed to create command list."))
return Err;
return CB;
}
~DXCommandBuffer() override = default;
static bool classof(const CommandBuffer *CB) {
return CB->getKind() == GPUAPI::DirectX;
}
void addPendingUAVBarrier() { PendingUAVBarrier = true; }
void addResourceTransition(ID3D12Resource *Resource,
D3D12_RESOURCE_STATES StateBefore,
D3D12_RESOURCE_STATES StateAfter) {
for (auto TransIt = PendingTransitions.begin(),
End = PendingTransitions.end();
TransIt != End; ++TransIt) {
if (TransIt->Transition.pResource != Resource)
continue;
assert(StateBefore == TransIt->Transition.StateAfter);
if (StateAfter == TransIt->Transition.StateBefore) {
// We actually need the resource to be in the original state!
// Remove the transition from the list of Pending Transitions.
PendingTransitions.erase(TransIt);
// NOTE: This could cause an execution barrier issue since legacy
// barriers don't allow us to express execution barriers, cache
// flushes, and layout transitions separately.
// As a workaround we add a UAV barrier so an execution barrier and
// cache flush is inserted.
addPendingUAVBarrier();
} else {
TransIt->Transition.StateAfter = StateAfter;
}
return;
}
PendingTransitions.push_back(CD3DX12_RESOURCE_BARRIER::Transition(
Resource, StateBefore, StateAfter));
}
void flushBarrier() {
if (PendingUAVBarrier) {
PendingTransitions.push_back(CD3DX12_RESOURCE_BARRIER::UAV(nullptr));
PendingUAVBarrier = false;
}
if (!PendingTransitions.empty()) {
CmdList->ResourceBarrier(PendingTransitions.size(),
PendingTransitions.data());
PendingTransitions.clear();
}
}
llvm::Expected<std::unique_ptr<offloadtest::ComputeEncoder>>
createComputeEncoder() override;
llvm::Expected<std::unique_ptr<offloadtest::RenderEncoder>>
createRenderEncoder(const offloadtest::RenderPassBeginDesc &Desc) override;
private:
DXCommandBuffer() : CommandBuffer(GPUAPI::DirectX) {}
};
struct DescriptorAllocator {
ComPtr<ID3D12DescriptorHeap> Heap;
std::atomic<uint32_t> NextIndex{0};
uint32_t DescIncSize;
uint32_t Capacity;
static llvm::Expected<DescriptorAllocator>
create(ID3D12DeviceX *Device, D3D12_DESCRIPTOR_HEAP_TYPE Type,
uint32_t Capacity) {
ComPtr<ID3D12DescriptorHeap> Heap;
const D3D12_DESCRIPTOR_HEAP_DESC HeapDesc = {
Type, Capacity, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0};
if (auto Err = HR::toError(
Device->CreateDescriptorHeap(&HeapDesc, IID_PPV_ARGS(&Heap)),
"Failed to create descriptor heap for DescriptorAllocator."))
return Err;
const uint32_t DescIncSize = Device->GetDescriptorHandleIncrementSize(Type);
return DescriptorAllocator(Heap, DescIncSize, Capacity);
}
llvm::Expected<D3D12_CPU_DESCRIPTOR_HANDLE> allocate() {
// TODO(manon): Use a better allocator that can also free descriptors.
const uint32_t Index = NextIndex.fetch_add(1, std::memory_order_relaxed);
if (Index >= Capacity)
return llvm::createStringError(std::errc::not_enough_memory,
"Descriptor heap allocator exhausted.");
D3D12_CPU_DESCRIPTOR_HANDLE Handle =
Heap->GetCPUDescriptorHandleForHeapStart();
Handle.ptr += Index * DescIncSize;
return Handle;
}
DescriptorAllocator(DescriptorAllocator &&Other)
: Heap(std::move(Other.Heap)),
NextIndex(Other.NextIndex.load(std::memory_order_relaxed)),
DescIncSize(Other.DescIncSize), Capacity(Other.Capacity) {}
DescriptorAllocator &operator=(DescriptorAllocator &&) = delete;
DescriptorAllocator(const DescriptorAllocator &) = delete;
DescriptorAllocator &operator=(const DescriptorAllocator &) = delete;
DescriptorAllocator(ComPtr<ID3D12DescriptorHeap> Heap, uint32_t DescIncSize,
uint32_t Capacity)
: Heap(Heap), DescIncSize(DescIncSize), Capacity(Capacity) {}
};
class DXComputeEncoder : public offloadtest::ComputeEncoder {
DXCommandBuffer &CB;
void addUAVBarrier() {
CB.addPendingUAVBarrier();
CB.flushBarrier();
}
public:
DXComputeEncoder(DXCommandBuffer &CB)
: ComputeEncoder(GPUAPI::DirectX), CB(CB) {}
~DXComputeEncoder() override { endEncoding(); }
static bool classof(const CommandEncoder *E) {
return E->getAPI() == GPUAPI::DirectX;
}
// D3D12 debug labels require WinPixEventRuntime for the proper event
// encoding. Without it, BeginEvent/EndEvent/SetMarker with metadata type 0
// crash the D3D12 debug layer, so leave these as no-ops for now.
void pushDebugGroup(llvm::StringRef Label) override {}
void popDebugGroup() override {}
void insertDebugSignpost(llvm::StringRef Label) override {}
llvm::Error dispatch(const offloadtest::PipelineState &PSO,
uint32_t GroupCountX, uint32_t GroupCountY,
uint32_t GroupCountZ) override {
const auto &DXPSO = llvm::cast<DXPipelineState>(PSO);
addUAVBarrier();
insertDebugSignpost(llvm::formatv("Dispatch [{0},{1},{2}]", GroupCountX,
GroupCountY, GroupCountZ)
.str());
CB.CmdList->SetPipelineState(DXPSO.PSO.Get());
CB.CmdList->Dispatch(GroupCountX, GroupCountY, GroupCountZ);
return llvm::Error::success();
}
llvm::Error copyBufferToBuffer(offloadtest::Buffer &Src, size_t SrcOffset,
offloadtest::Buffer &Dst, size_t DstOffset,
size_t Size) override {
auto &DXSrc = static_cast<DXBuffer &>(Src);
auto &DXDst = static_cast<DXBuffer &>(Dst);
// NOTE: Edge case in case of all the following being the case
// - multiple calls of copyBufferToBuffer with the same Dst Buffer
// - The Dst Buffer having a PreferredState of
// D3D12_RESOURCE_STATE_COPY_DEST
// - Each Src Buffer having a PreferredState of
// D3D12_RESOURCE_STATE_COPY_SOURCE
// In that case no barrier would be emitted
// and a race condition would occur. There are ways to solve this with
// legacy barriers, but switching to enhanced barriers is a better solution
// to this problem.
if (DXSrc.PreferredState != D3D12_RESOURCE_STATE_COPY_SOURCE)
CB.addResourceTransition(DXSrc.Buffer.Get(), DXSrc.PreferredState,
D3D12_RESOURCE_STATE_COPY_SOURCE);
if (DXDst.PreferredState != D3D12_RESOURCE_STATE_COPY_DEST)
CB.addResourceTransition(DXDst.Buffer.Get(), DXDst.PreferredState,
D3D12_RESOURCE_STATE_COPY_DEST);
CB.flushBarrier();
insertDebugSignpost(llvm::formatv("CopyBuffer {0}B", Size).str());
CB.CmdList->CopyBufferRegion(DXDst.Buffer.Get(), DstOffset,
DXSrc.Buffer.Get(), SrcOffset, Size);
if (DXSrc.PreferredState != D3D12_RESOURCE_STATE_COPY_SOURCE)
CB.addResourceTransition(DXSrc.Buffer.Get(),
D3D12_RESOURCE_STATE_COPY_SOURCE,
DXSrc.PreferredState);
if (DXDst.PreferredState != D3D12_RESOURCE_STATE_COPY_DEST)
CB.addResourceTransition(DXDst.Buffer.Get(),
D3D12_RESOURCE_STATE_COPY_DEST,
DXDst.PreferredState);
return llvm::Error::success();
}
llvm::Error copyBufferToTexture(Buffer &Src, Texture &Dst) override {
auto &DXSrc = llvm::cast<DXBuffer>(Src);
auto &DXDst = llvm::cast<DXTexture>(Dst);
if (DXSrc.PreferredState != D3D12_RESOURCE_STATE_COPY_SOURCE)
CB.addResourceTransition(DXSrc.Buffer.Get(), DXSrc.PreferredState,
D3D12_RESOURCE_STATE_COPY_SOURCE);
if (DXDst.PreferredState != D3D12_RESOURCE_STATE_COPY_DEST)
CB.addResourceTransition(DXDst.Resource.Get(), DXDst.PreferredState,
D3D12_RESOURCE_STATE_COPY_DEST);
CB.flushBarrier();
const uint32_t ElementSize = getFormatSizeInBytes(DXDst.Desc.Fmt);
const D3D12_PLACED_SUBRESOURCE_FOOTPRINT Footprint{
0,
CD3DX12_SUBRESOURCE_FOOTPRINT(
getDXGIFormat(DXDst.Desc.Fmt), DXDst.Desc.Width, DXDst.Desc.Height,
1, getAlignedTexturePitch(DXDst.Desc.Width, ElementSize))};
const CD3DX12_TEXTURE_COPY_LOCATION DstLoc(DXDst.Resource.Get(), 0);
const CD3DX12_TEXTURE_COPY_LOCATION SrcLoc(DXSrc.Buffer.Get(), Footprint);
CB.CmdList->CopyTextureRegion(&DstLoc, 0, 0, 0, &SrcLoc, nullptr);
if (DXSrc.PreferredState != D3D12_RESOURCE_STATE_COPY_SOURCE)
CB.addResourceTransition(DXSrc.Buffer.Get(),
D3D12_RESOURCE_STATE_COPY_SOURCE,
DXSrc.PreferredState);
if (DXDst.PreferredState != D3D12_RESOURCE_STATE_COPY_DEST)
CB.addResourceTransition(DXDst.Resource.Get(),
D3D12_RESOURCE_STATE_COPY_DEST,
DXDst.PreferredState);
return llvm::Error::success();
}
llvm::Error copyCounterToBuffer(offloadtest::Buffer &Src,
offloadtest::Buffer &Dst) override {
auto &DXSrc = llvm::cast<DXBuffer>(Src);
auto &DXDst = llvm::cast<DXBuffer>(Dst);
if (!DXSrc.Desc.HasCounter)
return llvm::createStringError(
"Counter resource passed does not hvae a counter.");
if (DXSrc.PreferredState != D3D12_RESOURCE_STATE_COPY_SOURCE)
CB.addResourceTransition(DXSrc.Buffer.Get(), DXSrc.PreferredState,
D3D12_RESOURCE_STATE_COPY_SOURCE);
if (DXDst.PreferredState != D3D12_RESOURCE_STATE_COPY_DEST)
CB.addResourceTransition(DXDst.Buffer.Get(), DXDst.PreferredState,
D3D12_RESOURCE_STATE_COPY_DEST);
CB.flushBarrier();
insertDebugSignpost("copyCounterToBuffer 4B");
CB.CmdList->CopyBufferRegion(DXDst.Buffer.Get(), 0, DXSrc.Buffer.Get(),
DXSrc.CounterOffsetInBytes, sizeof(uint32_t));
if (DXSrc.PreferredState != D3D12_RESOURCE_STATE_COPY_SOURCE)
CB.addResourceTransition(DXSrc.Buffer.Get(),
D3D12_RESOURCE_STATE_COPY_SOURCE,
DXSrc.PreferredState);
if (DXDst.PreferredState != D3D12_RESOURCE_STATE_COPY_DEST)
CB.addResourceTransition(DXDst.Buffer.Get(),
D3D12_RESOURCE_STATE_COPY_DEST,
DXDst.PreferredState);
return llvm::Error::success();
}
llvm::Error copyTextureToBuffer(Texture &Src, Buffer &Dst) override {
auto &DXSrc = llvm::cast<DXTexture>(Src);
auto &DXDst = llvm::cast<DXBuffer>(Dst);
if (DXSrc.PreferredState != D3D12_RESOURCE_STATE_COPY_SOURCE)
CB.addResourceTransition(DXSrc.Resource.Get(), DXSrc.PreferredState,
D3D12_RESOURCE_STATE_COPY_SOURCE);
if (DXDst.PreferredState != D3D12_RESOURCE_STATE_COPY_DEST)
CB.addResourceTransition(DXDst.Buffer.Get(), DXDst.PreferredState,
D3D12_RESOURCE_STATE_COPY_DEST);
CB.flushBarrier();
const uint32_t ElementSize = getFormatSizeInBytes(DXSrc.Desc.Fmt);
const D3D12_PLACED_SUBRESOURCE_FOOTPRINT Footprint{
0,
CD3DX12_SUBRESOURCE_FOOTPRINT(
getDXGIFormat(DXSrc.Desc.Fmt), DXSrc.Desc.Width, DXSrc.Desc.Height,
1, getAlignedTexturePitch(DXSrc.Desc.Width, ElementSize))};
const CD3DX12_TEXTURE_COPY_LOCATION DstLoc(DXDst.Buffer.Get(), Footprint);
const CD3DX12_TEXTURE_COPY_LOCATION SrcLoc(DXSrc.Resource.Get(), 0);
CB.CmdList->CopyTextureRegion(&DstLoc, 0, 0, 0, &SrcLoc, nullptr);
if (DXSrc.PreferredState != D3D12_RESOURCE_STATE_COPY_SOURCE)
CB.addResourceTransition(DXSrc.Resource.Get(),
D3D12_RESOURCE_STATE_COPY_SOURCE,
DXSrc.PreferredState);
if (DXDst.PreferredState != D3D12_RESOURCE_STATE_COPY_DEST)
CB.addResourceTransition(DXDst.Buffer.Get(),
D3D12_RESOURCE_STATE_COPY_DEST,
DXDst.PreferredState);
return llvm::Error::success();
}
// Defined out-of-line below — needs DXDevice's full type for access to the
// ID3D12Device5 entry point and helper allocators.
llvm::Error batchBuildAS(llvm::ArrayRef<ASBuildItem> Items) override;
// Defined out-of-line below — needs DXDevice's full type for access to
// Device5 and the DXRayTracingPipelineState definition.
llvm::Error dispatchRays(const PipelineState &PSO,
const ShaderBindingTable &SBT, uint32_t Width,
uint32_t Height, uint32_t Depth) override;
void endEncodingImpl() override { popDebugGroup(); }
};
llvm::Expected<std::unique_ptr<offloadtest::ComputeEncoder>>
DXCommandBuffer::createComputeEncoder() {
auto Enc = std::make_unique<DXComputeEncoder>(*this);
Enc->pushDebugGroup("ComputeEncoder");
return Enc;
}
class DXRenderPass final : public offloadtest::RenderPass {
public:
offloadtest::RenderPassDesc Desc;
explicit DXRenderPass(offloadtest::RenderPassDesc Desc)
: RenderPass(GPUAPI::DirectX), Desc(std::move(Desc)) {}
static bool classof(const offloadtest::RenderPass *RP) {
return RP->getAPI() == GPUAPI::DirectX;
}
};
class DXRenderEncoder : public offloadtest::RenderEncoder {
DXCommandBuffer &CB;
offloadtest::RenderPassBeginDesc Desc;
// Encoder contract: viewport and scissor must both be set before draw().
bool ViewportSet = false;
bool ScissorSet = false;
llvm::Error bindCommonDrawState(const offloadtest::PipelineState &PSO) {
if (!ViewportSet)
return llvm::createStringError(std::errc::invalid_argument,
"Viewport must be set before drawing.");
if (!ScissorSet)
return llvm::createStringError(std::errc::invalid_argument,
"Scissor must be set before drawing.");
const auto &DXPSO = llvm::cast<DXPipelineState>(PSO);
CB.CmdList->SetGraphicsRootSignature(DXPSO.RootSig.Get());
CB.CmdList->SetPipelineState(DXPSO.PSO.Get());
// Mesh-shader pipelines bypass the input assembler and carry no IA
// topology; only bind one when the pipeline actually has one.