-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathMTLDevice.cpp
More file actions
3335 lines (2928 loc) · 131 KB
/
Copy pathMTLDevice.cpp
File metadata and controls
3335 lines (2928 loc) · 131 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
//===- MTL/MTLDevice.cpp - Metal Device -----------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
#define NS_PRIVATE_IMPLEMENTATION
#define CA_PRIVATE_IMPLEMENTATION
#define MTL_PRIVATE_IMPLEMENTATION
#include "Foundation/Foundation.hpp"
#include "Metal/Metal.hpp"
#include "QuartzCore/QuartzCore.hpp"
#define IR_RUNTIME_METALCPP
#define IR_PRIVATE_IMPLEMENTATION
#include "metal_irconverter.h"
#include "metal_irconverter_runtime.h"
// ir_raytracing.h depends on types defined in metal_irconverter_runtime.h —
// keep this include in its own block so clang-format won't sort it above.
#include "ir_raytracing.h"
#include "API/Device.h"
#include "API/Encoder.h"
#include "API/FormatConversion.h"
#include "MTLDescriptorHeap.h"
#include "MTLResources.h"
#include "MTLTopLevelArgumentBuffer.h"
#include "Support/Pipeline.h"
#include "llvm/ADT/ScopeExit.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/FormatVariadic.h"
#include "llvm/Support/JSON.h"
#include "llvm/Support/raw_ostream.h"
#include "../Util.h"
#include <algorithm>
#include <memory>
using namespace offloadtest;
static llvm::Error toError(NS::Error *Err) {
if (!Err)
return llvm::Error::success();
const std::error_code EC =
std::error_code(static_cast<int>(Err->code()), std::system_category());
llvm::SmallString<256> ErrMsg;
llvm::raw_svector_ostream OS(ErrMsg);
OS << Err->localizedDescription()->utf8String() << ": ";
OS << Err->localizedFailureReason()->utf8String();
return llvm::createStringError(EC, ErrMsg);
}
static llvm::Error toError(const IRError *Err, llvm::StringRef Context) {
if (!Err)
return llvm::Error::success();
const uint32_t Code = IRErrorGetCode(Err);
if (IRErrorCodeNoError == Code)
return llvm::Error::success();
const std::error_code EC =
std::error_code(static_cast<int>(Code), std::generic_category());
llvm::SmallString<64> ErrMsg;
llvm::raw_svector_ostream OS(ErrMsg);
OS << Context << ": ";
switch (Code) {
#define IR_ERR(x) \
case x: \
OS << #x; \
break;
IR_ERR(IRErrorCodeShaderRequiresRootSignature);
IR_ERR(IRErrorCodeUnrecognizedRootSignatureDescriptor);
IR_ERR(IRErrorCodeUnrecognizedParameterTypeInRootSignature);
IR_ERR(IRErrorCodeResourceNotReferencedByRootSignature);
IR_ERR(IRErrorCodeShaderIncompatibleWithDualSourceBlending);
IR_ERR(IRErrorCodeUnsupportedWaveSize);
IR_ERR(IRErrorCodeUnsupportedInstruction);
IR_ERR(IRErrorCodeCompilationError);
IR_ERR(IRErrorCodeFailedToSynthesizeStageInFunction);
IR_ERR(IRErrorCodeFailedToSynthesizeStreamOutFunction);
IR_ERR(IRErrorCodeFailedToSynthesizeIndirectIntersectionFunction);
IR_ERR(IRErrorCodeUnableToVerifyModule);
IR_ERR(IRErrorCodeUnableToLinkModule);
IR_ERR(IRErrorCodeUnrecognizedDXILHeader);
IR_ERR(IRErrorCodeInvalidRaytracingAttribute);
IR_ERR(IRErrorCodeNullHullShaderInputOutputMismatch);
IR_ERR(IRErrorCodeInvalidRaytracingUserAttributeSize);
IR_ERR(IRErrorCodeIncorrectHitgroupType);
IR_ERR(IRErrorCodeFP64Usage);
IR_ERR(IRErrorCodeUnknown);
default:
break;
#undef IR_ERR
}
return llvm::createStringError(EC, ErrMsg);
}
#define MTLFormats(FMT) \
if (Channels == 1) \
return MTL::PixelFormatR##FMT; \
if (Channels == 2) \
return MTL::PixelFormatRG##FMT; \
if (Channels == 4) \
return MTL::PixelFormatRGBA##FMT;
static MTL::PixelFormat getMTLFormat(DataFormat Format, int Channels) {
switch (Format) {
case DataFormat::Int32:
MTLFormats(32Sint) break;
case DataFormat::Float32:
MTLFormats(32Float) break;
case DataFormat::UInt64:
case DataFormat::Int64:
if (Channels == 1)
return MTL::PixelFormatRG32Uint;
if (Channels == 2)
return MTL::PixelFormatRGBA32Uint;
llvm_unreachable("Unsupported channel count for 64-bit format");
default:
llvm_unreachable("Unsupported Resource format specified");
}
return MTL::PixelFormatInvalid;
}
static IRShaderStage getShaderStage(Stages Stage) {
switch (Stage) {
case Stages::Compute:
return IRShaderStageCompute;
case Stages::Vertex:
return IRShaderStageVertex;
case Stages::Hull:
llvm_unreachable("Hull shaders are not supported on Metal.");
case Stages::Domain:
llvm_unreachable("Domain shaders are not supported on Metal.");
case Stages::Geometry:
llvm_unreachable("Geometry shaders are not supported on Metal.");
case Stages::Pixel:
return IRShaderStageFragment;
case Stages::Amplification:
return IRShaderStageAmplification;
case Stages::Mesh:
return IRShaderStageMesh;
case Stages::RayGeneration:
return IRShaderStageRayGeneration;
case Stages::Miss:
return IRShaderStageMiss;
case Stages::ClosestHit:
return IRShaderStageClosestHit;
case Stages::AnyHit:
return IRShaderStageAnyHit;
case Stages::Intersection:
return IRShaderStageIntersection;
case Stages::Callable:
return IRShaderStageCallable;
}
llvm_unreachable("All cases handled");
}
namespace {
struct MTLDeleter {
template <typename T> void operator()(T *Arg) const {
if (Arg)
Arg->release();
}
};
template <typename T> using MTLPtr = std::unique_ptr<T, MTLDeleter>;
template <auto Fn> struct IRDeleter {
template <typename T> constexpr void operator()(T *Arg) const { Fn(Arg); }
};
using IRCompilerPtr = std::unique_ptr<IRCompiler, IRDeleter<IRCompilerDestroy>>;
using IRObjectPtr = std::unique_ptr<IRObject, IRDeleter<IRObjectDestroy>>;
using IRRootSignaturePtr =
std::unique_ptr<IRRootSignature, IRDeleter<IRRootSignatureDestroy>>;
using IRMetalLibBinaryPtr =
std::unique_ptr<IRMetalLibBinary, IRDeleter<IRMetalLibBinaryDestroy>>;
using IRShaderReflectionPtr =
std::unique_ptr<IRShaderReflection, IRDeleter<IRShaderReflectionDestroy>>;
using IRErrorPtr = std::unique_ptr<IRError, IRDeleter<IRErrorDestroy>>;
struct MetalIR {
IRMetalLibBinaryPtr Binary;
IRShaderReflectionPtr Reflection;
};
class MTLFence : public offloadtest::Fence {
public:
MTLFence(MTL::SharedEvent *Event, llvm::StringRef Name)
: Name(Name), Event(Event) {}
std::string Name;
MTL::SharedEvent *Event;
static llvm::Expected<std::unique_ptr<MTLFence>>
create(MTL::Device *Device, llvm::StringRef Name) {
MTL::SharedEvent *Event = Device->newSharedEvent();
if (!Event)
return llvm::createStringError(std::errc::device_or_resource_busy,
"Failed to create shared event.");
return std::make_unique<MTLFence>(Event, Name);
}
~MTLFence() {
if (Event)
Event->release();
}
uint64_t getFenceValue() override { return Event->signaledValue(); }
llvm::Error waitForCompletion(uint64_t SignalValue) override {
if (!Event->waitUntilSignaledValue(SignalValue, UINT64_MAX))
return llvm::createStringError(std::errc::timed_out,
"Timed out waiting on shared event.");
return llvm::Error::success();
}
};
class MTLQueue : public offloadtest::Queue {
public:
using Queue::submit;
MTL::CommandQueue *Queue;
std::unique_ptr<MTLFence> SubmitFence;
uint64_t FenceCounter = 0;
// Batches of command buffers submitted to the GPU that may still be
// in-flight. 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;
MTLQueue(MTL::CommandQueue *Queue, std::unique_ptr<MTLFence> SubmitFence)
: Queue(Queue), SubmitFence(std::move(SubmitFence)) {}
~MTLQueue() override {
if (Queue)
Queue->release();
}
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 llvm::createStringError(
std::errc::not_supported,
"Metal backend does not yet support tile mappings.");
}
llvm::Expected<offloadtest::SubmitResult>
updateTileMappings(offloadtest::Texture & /*Resource*/,
llvm::ArrayRef<TileMapping> /*Mappings*/) override {
return llvm::createStringError(
std::errc::not_supported,
"Metal backend does not yet support tile mappings.");
}
};
class MTLPipelineState : public offloadtest::PipelineState {
public:
std::string Name;
IRRootSignaturePtr RootSig;
std::unique_ptr<MTLTopLevelArgumentBuffer> ArgBuffer;
MTL::ComputePipelineState *ComputePipeline = nullptr;
MTL::RenderPipelineState *RenderPipeline = nullptr;
// Compute pipeline only state. Threadgroup size comes from numthreads() in
// the HLSL source and is captured from shader reflection at pipeline
// creation, so dispatch() doesn't need to re-query reflection each time.
MTL::Size ThreadsPerGroup = MTL::Size(1, 1, 1);
// Rasterization pipeline only state.
// These are part of the pipeline in DX and VK, but dynamic state in Metal.
// To have a shared API we store these here and set the state when the
// pipeline is used.
MTL::DepthStencilState *DepthStencilState = nullptr;
MTL::CullMode CullMode = MTL::CullModeNone;
MTL::Size MeshThreadsPerThreadgroup{1, 1, 1};
MTL::Size ObjectThreadsPerThreadgroup{1, 1, 1};
// True for pipelines created via createPipelineRT; mirrors the VK / DX
// backends' IsRayTracing flag so classof can downcast safely.
bool IsRayTracing = false;
MTLPipelineState(llvm::StringRef Name, IRRootSignaturePtr RootSig,
std::unique_ptr<MTLTopLevelArgumentBuffer> ArgBuffer,
MTL::ComputePipelineState *ComputePipeline,
MTL::Size ThreadsPerGroup)
: offloadtest::PipelineState(GPUAPI::Metal), Name(Name),
RootSig(std::move(RootSig)), ArgBuffer(std::move(ArgBuffer)),
ComputePipeline(ComputePipeline), ThreadsPerGroup(ThreadsPerGroup) {}
MTLPipelineState(llvm::StringRef Name, IRRootSignaturePtr RootSig,
std::unique_ptr<MTLTopLevelArgumentBuffer> ArgBuffer,
MTL::RenderPipelineState *RenderPipeline,
MTL::DepthStencilState *DepthStencilState,
MTL::CullMode CullMode,
MTL::Size MeshThreadsPerThreadgroup = {1, 1, 1},
MTL::Size ObjectThreadsPerThreadgroup = {1, 1, 1})
: offloadtest::PipelineState(GPUAPI::Metal), Name(Name),
RootSig(std::move(RootSig)), ArgBuffer(std::move(ArgBuffer)),
RenderPipeline(RenderPipeline), DepthStencilState(DepthStencilState),
CullMode(CullMode),
MeshThreadsPerThreadgroup(MeshThreadsPerThreadgroup),
ObjectThreadsPerThreadgroup(ObjectThreadsPerThreadgroup) {}
~MTLPipelineState() override {
if (ComputePipeline)
ComputePipeline->release();
if (RenderPipeline)
RenderPipeline->release();
if (DepthStencilState)
DepthStencilState->release();
}
static bool classof(const offloadtest::PipelineState *B) {
return B->getAPI() == GPUAPI::Metal;
}
protected:
// RT subclass constructor — keeps Compute/RenderPipeline null while sharing
// the rest of the layout (Name, root signature, argument buffer).
MTLPipelineState(llvm::StringRef Name, IRRootSignaturePtr RootSig,
std::unique_ptr<MTLTopLevelArgumentBuffer> ArgBuffer,
bool IsRT)
: offloadtest::PipelineState(GPUAPI::Metal), Name(Name),
RootSig(std::move(RootSig)), ArgBuffer(std::move(ArgBuffer)),
IsRayTracing(IsRT) {}
};
/// Ray tracing pipeline state. Layered on top of MTLPipelineState so the
/// existing argument-buffer / root-signature plumbing keeps working; adds the
/// raygen compute pipeline (held in ComputePipeline) plus the
/// IRShaderIdentifier records the SBT builder needs to populate per-record
/// entries.
///
/// The Metal RT path goes through `metal_irconverter`:
/// • each entry point is compiled to a Metal IR function;
/// • raygen is compiled as a kernel (IRRayGenerationCompilationKernel) so
/// it becomes the compute function of the pipeline;
/// • miss / closest-hit / any-hit / intersection / callable are compiled as
/// visible functions, attached to the pipeline via LinkedFunctions, and
/// looked up by name in a MTLVisibleFunctionTable;
/// • the SBT records IRShaderIdentifier values whose `shaderHandle` is the
/// slot in that visible function table.
class MTLRayTracingPipelineState : public MTLPipelineState {
public:
// ResourceID-based callable tables wired into IRDispatchRaysArgument.
MTL::VisibleFunctionTable *VFT = nullptr;
MTL::IntersectionFunctionTable *IFT = nullptr;
// Per shader entry / hit-group: pre-built IRShaderIdentifier the SBT
// builder memcpys into each record. Keys are EntryPoint strings for
// raygen / miss / callable shaders and HitGroup.Name for hit groups.
llvm::StringMap<IRShaderIdentifier> ShaderIdentifiers;
// Keep the per-stage Metal libraries / functions alive as long as the
// pipeline owns the visible-function-table indices that reference them.
llvm::SmallVector<MTL::Library *> Libraries;
llvm::SmallVector<MTL::Function *> Functions;
MTLRayTracingPipelineState(llvm::StringRef Name, IRRootSignaturePtr RootSig,
std::unique_ptr<MTLTopLevelArgumentBuffer> ArgBuf)
: MTLPipelineState(Name, std::move(RootSig), std::move(ArgBuf),
/*IsRT=*/true) {}
~MTLRayTracingPipelineState() override {
if (VFT)
VFT->release();
if (IFT)
IFT->release();
for (MTL::Function *F : Functions)
if (F)
F->release();
for (MTL::Library *L : Libraries)
if (L)
L->release();
}
static bool classof(const offloadtest::PipelineState *B) {
if (B->getAPI() != GPUAPI::Metal)
return false;
return static_cast<const MTLPipelineState *>(B)->IsRayTracing;
}
};
/// Metal-side shader binding table. There is no `MTLShaderBindingTable` in
/// the Metal API — the irconverter runtime expects the four SBT regions to be
/// laid out as `IRShaderIdentifier` records in a single buffer whose ranges
/// are referenced from an `IRDispatchRaysArgument` struct at dispatch time.
class MTLShaderBindingTable : public offloadtest::ShaderBindingTable {
public:
MTL::Buffer *Buffer = nullptr;
IRVirtualAddressRange RayGenRegion{};
IRVirtualAddressRangeAndStride MissRegion{};
IRVirtualAddressRangeAndStride HitGroupRegion{};
IRVirtualAddressRangeAndStride CallableRegion{};
MTLShaderBindingTable(MTL::Buffer *Buf, IRVirtualAddressRange RG,
IRVirtualAddressRangeAndStride MS,
IRVirtualAddressRangeAndStride HG,
IRVirtualAddressRangeAndStride CL)
: offloadtest::ShaderBindingTable(GPUAPI::Metal), Buffer(Buf),
RayGenRegion(RG), MissRegion(MS), HitGroupRegion(HG),
CallableRegion(CL) {}
~MTLShaderBindingTable() override {
if (Buffer)
Buffer->release();
}
static bool classof(const offloadtest::ShaderBindingTable *S) {
return S->getAPI() == GPUAPI::Metal;
}
};
class MTLBuffer : public offloadtest::Buffer {
public:
MTL::Buffer *Buf;
std::string Name;
BufferCreateDesc Desc;
size_t SizeInBytes;
MTLBuffer(MTL::Buffer *Buf, llvm::StringRef Name, BufferCreateDesc Desc,
size_t SizeInBytes)
: offloadtest::Buffer(GPUAPI::Metal), Buf(Buf), Name(Name), Desc(Desc),
SizeInBytes(SizeInBytes) {}
MTLBuffer(const MTLBuffer &) = delete;
MTLBuffer(MTLBuffer &&) = delete;
MTLBuffer &operator=(const MTLBuffer &) = delete;
MTLBuffer &operator=(MTLBuffer &&) = delete;
size_t getSizeInBytes() const override { return SizeInBytes; }
size_t querySparseTileSizeInBytes(const Device &Dev) const override;
llvm::Expected<void *> map() override {
if (Desc.Location == MemoryLocation::GpuOnly)
return llvm::createStringError(std::errc::invalid_argument,
"Cannot map a GpuOnly buffer.");
return Buf->contents();
}
void unmap() override {
// Managed storage (CpuToGpu) requires an explicit didModifyRange to
// propagate CPU-side writes to the GPU. Shared storage (GpuToCpu) is
// coherent and needs no action.
if (Desc.Location == MemoryLocation::CpuToGpu)
Buf->didModifyRange(NS::Range::Make(0, SizeInBytes));
}
~MTLBuffer() override {
if (Buf)
Buf->release();
}
const BufferCreateDesc &getDesc() const override { return Desc; }
static bool classof(const offloadtest::Buffer *B) {
return B->getAPI() == GPUAPI::Metal;
}
};
class MTLTexture : public offloadtest::Texture {
public:
MTL::Texture *Tex;
std::string Name;
TextureCreateDesc Desc;
MTLTexture(MTL::Texture *Tex, llvm::StringRef Name, TextureCreateDesc Desc)
: offloadtest::Texture(GPUAPI::Metal), Tex(Tex), Name(Name), Desc(Desc) {}
~MTLTexture() override {
if (Tex)
Tex->release();
}
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::Metal;
}
};
/// Metal has no standalone render-pass object: render pass info lives on
/// MTLRenderPassDescriptor and is consumed when a render command encoder
/// is created. We therefore just stash the descriptor for the encoder to
/// translate later.
class MTLRenderPass final : public offloadtest::RenderPass {
public:
offloadtest::RenderPassDesc Desc;
explicit MTLRenderPass(offloadtest::RenderPassDesc Desc)
: RenderPass(GPUAPI::Metal), Desc(std::move(Desc)) {}
static bool classof(const offloadtest::RenderPass *RP) {
return RP->getAPI() == GPUAPI::Metal;
}
};
class MTLDevice; // forward decl — defined below in this same anon ns
class MTLCommandBuffer : public offloadtest::CommandBuffer {
public:
MTL::CommandBuffer *CmdBuffer = nullptr;
/// Back-pointer to the owning device; used by encoders that need to
/// allocate scratch / instance buffers for AS builds.
MTLDevice *Dev = nullptr;
/// 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<MTLCommandBuffer>>
create(MTL::CommandQueue *Queue) {
auto CB = std::unique_ptr<MTLCommandBuffer>(new MTLCommandBuffer());
CB->CmdBuffer = Queue->commandBuffer();
if (!CB->CmdBuffer)
return llvm::createStringError(std::errc::device_or_resource_busy,
"Failed to create Metal command buffer.");
return CB;
}
~MTLCommandBuffer() override = default;
static bool classof(const CommandBuffer *CB) {
return CB->getKind() == GPUAPI::Metal;
}
llvm::Expected<std::unique_ptr<offloadtest::ComputeEncoder>>
createComputeEncoder() override;
llvm::Expected<std::unique_ptr<offloadtest::RenderEncoder>>
createRenderEncoder(const offloadtest::RenderPassBeginDesc &Desc) override;
private:
MTLCommandBuffer() : CommandBuffer(GPUAPI::Metal) {}
};
class MetalAccelerationStructure : public offloadtest::AccelerationStructure {
public:
MTL::AccelerationStructure *AccelStruct;
MetalAccelerationStructure(MTL::AccelerationStructure *AccelStruct,
const AccelerationStructureSizes &Sizes)
: offloadtest::AccelerationStructure(GPUAPI::Metal, Sizes),
AccelStruct(AccelStruct) {}
~MetalAccelerationStructure() override {
if (AccelStruct)
AccelStruct->release();
}
static bool classof(const offloadtest::AccelerationStructure *AS) {
return AS->getAPI() == GPUAPI::Metal;
}
};
llvm::Expected<offloadtest::SubmitResult> MTLQueue::submit(
llvm::SmallVector<std::unique_ptr<offloadtest::CommandBuffer>> CBs) {
// Non-blocking: query how far the GPU has progressed and release
// command buffers from completed submissions.
{
const uint64_t Completed = SubmitFence->getFenceValue();
llvm::erase_if(InFlightBatches, [Completed](const InFlightBatch &B) {
return B.FenceValue <= Completed;
});
}
// Metal serial queues guarantee that command buffers execute in commit order,
// so no explicit wait on prior work is needed here.
const uint64_t SignalValue = ++FenceCounter;
for (size_t I = 0; I < CBs.size(); ++I) {
auto &MCB = llvm::cast<MTLCommandBuffer>(*CBs[I].get());
// Signal the submit fence when the last command buffer completes.
if (I == CBs.size() - 1)
MCB.CmdBuffer->encodeSignalEvent(SubmitFence->Event, SignalValue);
MCB.CmdBuffer->commit();
}
// Keep submitted command buffers alive until the GPU is done with them.
InFlightBatches.push_back({SignalValue, std::move(CBs)});
return offloadtest::SubmitResult{SubmitFence.get(), SignalValue};
}
class MTLComputeEncoder : public offloadtest::ComputeEncoder {
MTLCommandBuffer *CB = nullptr;
MTL::CommandBuffer *CmdBuffer;
MTL::ComputeCommandEncoder *ComputeEnc = nullptr;
MTL::BlitCommandEncoder *BlitEnc = nullptr;
/// Lazy AS encoder, created when batchBuildAS() is called and torn down at
/// the next encoder transition (via endEncodingImpl).
MTL::AccelerationStructureCommandEncoder *ASEnc = nullptr;
/// Accumulated barrier scope from commands recorded since the last barrier.
MTL::BarrierScope PendingScope = MTL::BarrierScope(0);
/// Record that a command touched the given resource types. The accumulated
/// scope is flushed as a memoryBarrier before the next command.
void addBarrierScope(MTL::BarrierScope Scope) { PendingScope |= Scope; }
void flushBarrier() {
if (ComputeEnc && PendingScope != MTL::BarrierScope(0)) {
ComputeEnc->memoryBarrier(PendingScope);
PendingScope = MTL::BarrierScope(0);
}
}
/// End the blit encoder if active, lazily (re-)create the compute encoder.
/// Metal requires a dedicated BlitCommandEncoder for copy operations. Metal 4
/// moves blit operations onto the compute encoder, removing this separation.
llvm::Error ensureComputeEncoder() {
if (ComputeEnc)
return llvm::Error::success();
endEncodingImpl();
ComputeEnc = CmdBuffer->computeCommandEncoder();
if (!ComputeEnc)
return llvm::createStringError(std::errc::device_or_resource_busy,
"Failed to create Metal compute encoder.");
ComputeEnc->pushDebugGroup(
NS::String::string("ComputeEncoder", NS::UTF8StringEncoding));
return llvm::Error::success();
}
/// End the compute encoder if active, lazily create the blit encoder.
llvm::Error ensureBlitEncoder() {
if (BlitEnc)
return llvm::Error::success();
endEncodingImpl();
BlitEnc = CmdBuffer->blitCommandEncoder();
if (!BlitEnc)
return llvm::createStringError(std::errc::device_or_resource_busy,
"Failed to create Metal blit encoder.");
return llvm::Error::success();
}
public:
MTLComputeEncoder(MTLCommandBuffer *CB, MTL::CommandBuffer *CmdBuffer,
MTL::ComputeCommandEncoder *Encoder)
: ComputeEncoder(GPUAPI::Metal), CB(CB), CmdBuffer(CmdBuffer),
ComputeEnc(Encoder) {}
~MTLComputeEncoder() override { endEncoding(); }
static bool classof(const CommandEncoder *E) {
return E->getAPI() == GPUAPI::Metal;
}
MTL::ComputeCommandEncoder *getNative() const { return ComputeEnc; }
MTL::CommandEncoder *getActiveEncoder() const {
if (ComputeEnc)
return ComputeEnc;
return BlitEnc;
}
void pushDebugGroup(llvm::StringRef Label) override {
if (auto *Enc = getActiveEncoder())
Enc->pushDebugGroup(
NS::String::string(Label.data(), NS::UTF8StringEncoding));
}
void popDebugGroup() override {
if (auto *Enc = getActiveEncoder())
Enc->popDebugGroup();
}
void insertDebugSignpost(llvm::StringRef Label) override {
if (auto *Enc = getActiveEncoder())
Enc->insertDebugSignpost(
NS::String::string(Label.data(), NS::UTF8StringEncoding));
}
llvm::Error dispatch(const offloadtest::PipelineState &PSO,
uint32_t GroupCountX, uint32_t GroupCountY,
uint32_t GroupCountZ) override {
const auto &MTLPSO = llvm::cast<MTLPipelineState>(PSO);
if (!MTLPSO.ComputePipeline)
return llvm::createStringError(
std::errc::invalid_argument,
"PipelineState bound to dispatch() is not a compute pipeline.");
if (auto Err = ensureComputeEncoder())
return Err;
flushBarrier();
insertDebugSignpost(llvm::formatv("Dispatch [{0},{1},{2}]", GroupCountX,
GroupCountY, GroupCountZ)
.str());
ComputeEnc->setComputePipelineState(MTLPSO.ComputePipeline);
const MTL::Size GridSize(MTLPSO.ThreadsPerGroup.width * GroupCountX,
MTLPSO.ThreadsPerGroup.height * GroupCountY,
MTLPSO.ThreadsPerGroup.depth * GroupCountZ);
ComputeEnc->dispatchThreads(GridSize, MTLPSO.ThreadsPerGroup);
addBarrierScope(MTL::BarrierScopeBuffers | MTL::BarrierScopeTextures);
return llvm::Error::success();
}
llvm::Error copyBufferToBuffer(offloadtest::Buffer &Src, size_t SrcOffset,
offloadtest::Buffer &Dst, size_t DstOffset,
size_t Size) override {
if (auto Err = ensureBlitEncoder())
return Err;
auto &MTLSrc = static_cast<MTLBuffer &>(Src);
auto &MTLDst = static_cast<MTLBuffer &>(Dst);
insertDebugSignpost(llvm::formatv("CopyBuffer {0}B", Size).str());
BlitEnc->copyFromBuffer(MTLSrc.Buf, SrcOffset, MTLDst.Buf, DstOffset, Size);
addBarrierScope(MTL::BarrierScopeBuffers);
return llvm::Error::success();
}
llvm::Error copyBufferToTexture(offloadtest::Buffer &Src,
offloadtest::Texture &Dst) override {
if (auto Err = ensureBlitEncoder())
return Err;
auto &MTLSrc = static_cast<MTLBuffer &>(Src);
auto &MTLDst = static_cast<MTLTexture &>(Dst);
// The upload buffer is laid out with a tightly packed row stride matching
// getTextureUploadRowStrideInBytes(), so the source bytes-per-row is the
// texture width times the element size.
const size_t ElemSize = getFormatSizeInBytes(MTLDst.Desc.Fmt);
const size_t RowBytes = MTLDst.Desc.Width * ElemSize;
const size_t ImageBytes = RowBytes * MTLDst.Desc.Height;
const MTL::Size CopySize(MTLDst.Desc.Width, MTLDst.Desc.Height, 1);
insertDebugSignpost(llvm::formatv("copyBufferToTexture {0} -> {1}",
MTLSrc.Name, MTLDst.Name)
.str());
BlitEnc->copyFromBuffer(MTLSrc.Buf, /*sourceOffset=*/0, RowBytes,
ImageBytes, CopySize, MTLDst.Tex,
/*destinationSlice=*/0, /*destinationLevel=*/0,
MTL::Origin(0, 0, 0));
addBarrierScope(MTL::BarrierScopeTextures);
return llvm::Error::success();
}
llvm::Error copyCounterToBuffer(offloadtest::Buffer &,
offloadtest::Buffer &) override {
return llvm::createStringError(
std::errc::not_supported,
"Counter buffers are not supported on the Metal backend.");
}
llvm::Error copyTextureToBuffer(offloadtest::Texture &Src,
offloadtest::Buffer &Dst) override {
if (auto Err = ensureBlitEncoder())
return Err;
auto &MTLSrc = static_cast<MTLTexture &>(Src);
auto &MTLDst = static_cast<MTLBuffer &>(Dst);
// The readback buffer is linear with a tightly packed row stride, so the
// destination bytes-per-row is the texture width times the element size.
const size_t ElemSize = getFormatSizeInBytes(MTLSrc.Desc.Fmt);
const size_t RowBytes = MTLSrc.Desc.Width * ElemSize;
const size_t ImageBytes = RowBytes * MTLSrc.Desc.Height;
const MTL::Size CopySize(MTLSrc.Desc.Width, MTLSrc.Desc.Height, 1);
insertDebugSignpost(llvm::formatv("copyTextureToBuffer {0} -> {1}",
MTLSrc.Name, MTLDst.Name)
.str());
BlitEnc->copyFromTexture(MTLSrc.Tex, /*sourceSlice=*/0, /*sourceLevel=*/0,
MTL::Origin(0, 0, 0), CopySize, MTLDst.Buf,
/*destinationOffset=*/0, RowBytes, ImageBytes);
addBarrierScope(MTL::BarrierScopeBuffers);
return llvm::Error::success();
}
// Defined out-of-line below — needs MTLDevice's full type for access to the
// MTL::Device handle (used to allocate scratch and instance buffers).
llvm::Error batchBuildAS(llvm::ArrayRef<ASBuildItem> Items) override;
// Dispatch threads using a raygen compute kernel synthesized by the
// irconverter. All bindings (descriptor heap, top-level argument buffer,
// IRDispatchRaysArgument at slot 3, visible/intersection function tables,
// and the SBT buffer) must already be set on the active compute encoder by
// the caller — this method only binds the pipeline state and issues the
// dispatch.
llvm::Error dispatchRays(const PipelineState &PSO, const ShaderBindingTable &,
uint32_t Width, uint32_t Height,
uint32_t Depth) override {
if (!llvm::isa<MTLRayTracingPipelineState>(&PSO))
return llvm::createStringError(
std::errc::invalid_argument,
"dispatchRays requires a RayTracing PipelineState.");
const auto &RTPSO = llvm::cast<MTLRayTracingPipelineState>(PSO);
if (!RTPSO.ComputePipeline)
return llvm::createStringError(
std::errc::invalid_argument,
"RayTracing PipelineState has no compute pipeline state.");
if (auto Err = ensureComputeEncoder())
return Err;
flushBarrier();
insertDebugSignpost(
llvm::formatv("DispatchRays [{0},{1},{2}]", Width, Height, Depth)
.str());
ComputeEnc->setComputePipelineState(RTPSO.ComputePipeline);
// DispatchRays(W, H, D) launches W*H*D rays; tid in the irconverter raygen
// kernel is the per-ray index. Pass grid as raw (W, H, D) and let Metal
// ceil-divide by ThreadsPerGroup to compute threadgroup count.
const MTL::Size GridSize(Width, Height, Depth);
ComputeEnc->dispatchThreads(GridSize, RTPSO.ThreadsPerGroup);
addBarrierScope(MTL::BarrierScopeBuffers | MTL::BarrierScopeTextures);
return llvm::Error::success();
}
/// Lazily transition into an AccelerationStructureCommandEncoder; mirrors
/// the existing compute↔blit lazy switch.
llvm::Error ensureASEncoder() {
if (ASEnc)
return llvm::Error::success();
endEncodingImpl();
ASEnc = CmdBuffer->accelerationStructureCommandEncoder();
if (!ASEnc)
return llvm::createStringError(
std::errc::device_or_resource_busy,
"Failed to create Metal acceleration-structure encoder.");
return llvm::Error::success();
}
void endEncodingImpl() override {
if (ComputeEnc) {
flushBarrier();
ComputeEnc->popDebugGroup();
ComputeEnc->endEncoding();
ComputeEnc = nullptr;
}
if (BlitEnc) {
BlitEnc->endEncoding();
BlitEnc = nullptr;
}
if (ASEnc) {
ASEnc->endEncoding();
ASEnc = nullptr;
}
}
};
llvm::Expected<std::unique_ptr<offloadtest::ComputeEncoder>>
MTLCommandBuffer::createComputeEncoder() {
MTL::ComputeCommandEncoder *NativeEncoder =
CmdBuffer->computeCommandEncoder();
if (!NativeEncoder)
return llvm::createStringError(
std::errc::device_or_resource_busy,
"Failed to create Metal compute command encoder.");
NativeEncoder->pushDebugGroup(
NS::String::string("ComputeEncoder", NS::UTF8StringEncoding));
return std::make_unique<MTLComputeEncoder>(this, CmdBuffer, NativeEncoder);
}
static MTL::LoadAction getMTLLoadAction(offloadtest::LoadAction Action) {
switch (Action) {
case offloadtest::LoadAction::Load:
return MTL::LoadActionLoad;
case offloadtest::LoadAction::Clear:
return MTL::LoadActionClear;
case offloadtest::LoadAction::DontCare:
return MTL::LoadActionDontCare;
}
llvm_unreachable("All LoadAction cases handled");
}
static MTL::StoreAction getMTLStoreAction(offloadtest::StoreAction Action) {
switch (Action) {
case offloadtest::StoreAction::Store:
return MTL::StoreActionStore;
case offloadtest::StoreAction::DontCare:
return MTL::StoreActionDontCare;
}
llvm_unreachable("All StoreAction cases handled");
}
class MTLRenderEncoder : public offloadtest::RenderEncoder {
MTL::RenderCommandEncoder *RenderEnc = nullptr;
// Encoder contract: viewport and scissor must both be set before
// drawInstanced().
bool ViewportSet = false;
bool ScissorSet = false;
public:
MTLRenderEncoder(MTL::RenderCommandEncoder *Enc)
: RenderEncoder(GPUAPI::Metal), RenderEnc(Enc) {}
MTLRenderEncoder(const MTLRenderEncoder &CB) = delete;
MTLRenderEncoder(MTLRenderEncoder &&CB) = delete;
MTLRenderEncoder &operator=(MTLRenderEncoder &CB) = delete;
MTLRenderEncoder &operator=(const MTLRenderEncoder &&CB) = delete;
~MTLRenderEncoder() override { endEncoding(); }
static bool classof(const CommandEncoder *E) {
return E->getAPI() == GPUAPI::Metal;
}
/// Access the underlying Metal encoder for state that the abstract
/// RenderEncoder API does not yet cover.
/// Returns nullptr after endEncoding().
MTL::RenderCommandEncoder *getNative() const { return RenderEnc; }
void pushDebugGroup(llvm::StringRef Label) override {
assert(RenderEnc);
RenderEnc->pushDebugGroup(
NS::String::string(Label.data(), NS::UTF8StringEncoding));
}
void popDebugGroup() override {
assert(RenderEnc);
RenderEnc->popDebugGroup();
}
void insertDebugSignpost(llvm::StringRef Label) override {
assert(RenderEnc);
RenderEnc->insertDebugSignpost(
NS::String::string(Label.data(), NS::UTF8StringEncoding));
}
void setViewport(const offloadtest::Viewport &VP) override {
RenderEnc->setViewport(MTL::Viewport{
static_cast<double>(VP.X), static_cast<double>(VP.Y),
static_cast<double>(VP.Width), static_cast<double>(VP.Height),
static_cast<double>(VP.MinDepth), static_cast<double>(VP.MaxDepth)});
ViewportSet = true;
}
void setScissor(const offloadtest::ScissorRect &Rect) override {
MTL::ScissorRect MTLRect;
MTLRect.x = static_cast<NS::UInteger>(Rect.X);
MTLRect.y = static_cast<NS::UInteger>(Rect.Y);
MTLRect.width = Rect.Width;
MTLRect.height = Rect.Height;
RenderEnc->setScissorRect(MTLRect);
ScissorSet = true;
}
void setVertexBuffer(uint32_t Slot, offloadtest::Buffer *VB, size_t Offset,
uint32_t /*Stride*/) override {
// Stride is needed in DX12 at binding time, ignore parameter here.
// Metal Shader Converter reserves low buffer indices for its own tables;
// vertex buffers start at kIRVertexBufferBindPoint. See
// https://developer.apple.com/metal/shader-converter/ ("Metal vertex
// fetch").
const NS::UInteger BufIdx = kIRVertexBufferBindPoint + Slot;
assert(Slot <
sizeof(IRRuntimeVertexBuffers) / sizeof(IRRuntimeVertexBuffer) &&
"Vertex buffer slot exceeds Metal Shader Converter limit");
assert(Slot == 0 && "Pipeline vertex descriptor only describes slot 0");
if (VB) {
auto &MTLVB = llvm::cast<MTLBuffer>(*VB);
RenderEnc->setVertexBuffer(MTLVB.Buf, Offset, BufIdx);
} else {
RenderEnc->setVertexBuffer(nullptr, 0, BufIdx);
}
}
llvm::Error drawInstanced(const offloadtest::PipelineState &PSO,
uint32_t VertexCount, uint32_t InstanceCount,
uint32_t FirstVertex,
uint32_t FirstInstance) override {
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 &MTLPSO = llvm::cast<MTLPipelineState>(PSO);
if (!MTLPSO.RenderPipeline)
return llvm::createStringError(
std::errc::invalid_argument,
"PipelineState bound to drawInstanced() is not a render pipeline.");
RenderEnc->setRenderPipelineState(MTLPSO.RenderPipeline);
if (MTLPSO.DepthStencilState)
RenderEnc->setDepthStencilState(MTLPSO.DepthStencilState);
RenderEnc->setCullMode(MTLPSO.CullMode);
// Match the DX/VK convention (CCW = front) hardcoded in those backends.
RenderEnc->setFrontFacingWinding(MTL::WindingCounterClockwise);
// IRRuntimeDrawPrimitives also sets the DrawParams / DrawInfo argument
// buffers that metal-irconverter consults for SV_VertexID and friends.
IRRuntimeDrawPrimitives(RenderEnc, MTL::PrimitiveTypeTriangle,
static_cast<NS::UInteger>(FirstVertex),