forked from intel/llvm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.cpp
2245 lines (2003 loc) · 88.1 KB
/
handler.cpp
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
//==-------- handler.cpp --- SYCL command group handler --------------------==//
//
// 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 "sycl/detail/helpers.hpp"
#include "ur_api.h"
#include <algorithm>
#include <detail/config.hpp>
#include <detail/global_handler.hpp>
#include <detail/graph_impl.hpp>
#include <detail/handler_impl.hpp>
#include <detail/helpers.hpp>
#include <detail/host_task.hpp>
#include <detail/image_impl.hpp>
#include <detail/kernel_bundle_impl.hpp>
#include <detail/kernel_impl.hpp>
#include <detail/queue_impl.hpp>
#include <detail/scheduler/commands.hpp>
#include <detail/scheduler/scheduler.hpp>
#include <detail/ur_info_code.hpp>
#include <detail/usm/usm_impl.hpp>
#include <sycl/detail/common.hpp>
#include <sycl/detail/helpers.hpp>
#include <sycl/detail/kernel_desc.hpp>
#include <sycl/detail/ur.hpp>
#include <sycl/event.hpp>
#include <sycl/handler.hpp>
#include <sycl/info/info_desc.hpp>
#include <sycl/stream.hpp>
#include "sycl/ext/oneapi/experimental/graph.hpp"
#include <sycl/ext/oneapi/bindless_images_memory.hpp>
#include <sycl/ext/oneapi/experimental/work_group_memory.hpp>
#include <sycl/ext/oneapi/memcpy2d.hpp>
namespace sycl {
inline namespace _V1 {
namespace detail {
const DeviceImplPtr &getDeviceImplFromHandler(handler &CGH) {
assert((CGH.MQueue || getSyclObjImpl(CGH)->MGraph) &&
"One of MQueue or MGraph should be nonnull!");
if (CGH.MQueue)
return CGH.MQueue->getDeviceImplPtr();
return getSyclObjImpl(CGH)->MGraph->getDeviceImplPtr();
}
bool isDeviceGlobalUsedInKernel(const void *DeviceGlobalPtr) {
DeviceGlobalMapEntry *DGEntry =
detail::ProgramManager::getInstance().getDeviceGlobalEntry(
DeviceGlobalPtr);
return DGEntry && !DGEntry->MImageIdentifiers.empty();
}
static ur_exp_image_copy_flags_t
getUrImageCopyFlags(sycl::usm::alloc SrcPtrType, sycl::usm::alloc DstPtrType) {
if (DstPtrType == sycl::usm::alloc::device) {
// Dest is on device
if (SrcPtrType == sycl::usm::alloc::device)
return UR_EXP_IMAGE_COPY_FLAG_DEVICE_TO_DEVICE;
if (SrcPtrType == sycl::usm::alloc::host ||
SrcPtrType == sycl::usm::alloc::unknown)
return UR_EXP_IMAGE_COPY_FLAG_HOST_TO_DEVICE;
throw sycl::exception(make_error_code(errc::invalid),
"Unknown copy source location");
}
if (DstPtrType == sycl::usm::alloc::host ||
DstPtrType == sycl::usm::alloc::unknown) {
// Dest is on host
if (SrcPtrType == sycl::usm::alloc::device)
return UR_EXP_IMAGE_COPY_FLAG_DEVICE_TO_HOST;
if (SrcPtrType == sycl::usm::alloc::host ||
SrcPtrType == sycl::usm::alloc::unknown)
return UR_EXP_IMAGE_COPY_FLAG_HOST_TO_HOST;
throw sycl::exception(make_error_code(errc::invalid),
"Unknown copy source location");
}
throw sycl::exception(make_error_code(errc::invalid),
"Unknown copy destination location");
}
void *getValueFromDynamicParameter(
ext::oneapi::experimental::detail::dynamic_parameter_base
&DynamicParamBase) {
return sycl::detail::getSyclObjImpl(DynamicParamBase)->getValue();
}
// Bindless image helpers
// Fill image type and return depth or array_size
static unsigned int
fill_image_type(const ext::oneapi::experimental::image_descriptor &Desc,
ur_image_desc_t &UrDesc) {
if (Desc.array_size > 1) {
// Image Array.
UrDesc.type =
Desc.height > 0 ? UR_MEM_TYPE_IMAGE2D_ARRAY : UR_MEM_TYPE_IMAGE1D_ARRAY;
// Cubemap.
UrDesc.type =
Desc.type == sycl::ext::oneapi::experimental::image_type::cubemap
? UR_MEM_TYPE_IMAGE_CUBEMAP_EXP
: Desc.type == sycl::ext::oneapi::experimental::image_type::gather
? UR_MEM_TYPE_IMAGE_GATHER_EXP
: UrDesc.type;
return Desc.array_size;
}
UrDesc.type = Desc.depth > 0 ? UR_MEM_TYPE_IMAGE3D
: (Desc.height > 0 ? UR_MEM_TYPE_IMAGE2D
: UR_MEM_TYPE_IMAGE1D);
return Desc.depth;
}
// Fill image format
static ur_image_format_t
fill_format(const ext::oneapi::experimental::image_descriptor &Desc) {
ur_image_format_t PiFormat;
PiFormat.channelType =
sycl::_V1::detail::convertChannelType(Desc.channel_type);
PiFormat.channelOrder = sycl::detail::convertChannelOrder(
sycl::_V1::ext::oneapi::experimental::detail::
get_image_default_channel_order(Desc.num_channels));
return PiFormat;
}
static void
verify_copy(const ext::oneapi::experimental::image_descriptor &SrcImgDesc,
const ext::oneapi::experimental::image_descriptor &DestImgDesc) {
if (SrcImgDesc.width != DestImgDesc.width ||
SrcImgDesc.height != DestImgDesc.height ||
SrcImgDesc.depth != DestImgDesc.depth) {
throw sycl::exception(make_error_code(errc::invalid),
"Copy Error: The source image and the destination "
"image must have equal dimensions!");
}
if (SrcImgDesc.num_channels != DestImgDesc.num_channels) {
throw sycl::exception(make_error_code(errc::invalid),
"Copy Error: The source image and the destination "
"image must have the same number of channels!");
}
}
static void
verify_sub_copy(const ext::oneapi::experimental::image_descriptor &SrcImgDesc,
sycl::range<3> SrcOffset,
const ext::oneapi::experimental::image_descriptor &DestImgDesc,
sycl::range<3> DestOffset, sycl::range<3> CopyExtent) {
auto isOutOfRange = [](const sycl::range<3> &range,
const sycl::range<3> &offset,
const sycl::range<3> ©Extent) {
sycl::range<3> result = (range > 0UL && ((offset + copyExtent) > range));
return (static_cast<bool>(result[0]) || static_cast<bool>(result[1]) ||
static_cast<bool>(result[2]));
};
sycl::range<3> SrcImageSize = {SrcImgDesc.width, SrcImgDesc.height,
SrcImgDesc.depth};
sycl::range<3> DestImageSize = {DestImgDesc.width, DestImgDesc.height,
DestImgDesc.depth};
if (isOutOfRange(SrcImageSize, SrcOffset, CopyExtent) ||
isOutOfRange(DestImageSize, DestOffset, CopyExtent)) {
throw sycl::exception(
make_error_code(errc::invalid),
"Copy Error: Image copy attempted to access out of bounds memory!");
}
if (SrcImgDesc.num_channels != DestImgDesc.num_channels) {
throw sycl::exception(make_error_code(errc::invalid),
"Copy Error: The source image and the destination "
"image must have the same number of channels!");
}
}
static ur_image_desc_t
fill_image_desc(const ext::oneapi::experimental::image_descriptor &ImgDesc) {
ur_image_desc_t UrDesc = {};
UrDesc.stype = UR_STRUCTURE_TYPE_IMAGE_DESC;
UrDesc.width = ImgDesc.width;
UrDesc.height = ImgDesc.height;
UrDesc.depth = ImgDesc.depth;
UrDesc.arraySize = ImgDesc.array_size;
return UrDesc;
}
static void
fill_copy_args(std::shared_ptr<detail::handler_impl> &impl,
const ext::oneapi::experimental::image_descriptor &SrcImgDesc,
const ext::oneapi::experimental::image_descriptor &DestImgDesc,
ur_exp_image_copy_flags_t ImageCopyFlags, size_t SrcPitch,
size_t DestPitch, sycl::range<3> SrcOffset = {0, 0, 0},
sycl::range<3> SrcExtent = {0, 0, 0},
sycl::range<3> DestOffset = {0, 0, 0},
sycl::range<3> DestExtent = {0, 0, 0},
sycl::range<3> CopyExtent = {0, 0, 0}) {
SrcImgDesc.verify();
DestImgDesc.verify();
// CopyExtent.size() should only be greater than 0 when sub-copy is occurring.
if (CopyExtent.size() == 0) {
detail::verify_copy(SrcImgDesc, DestImgDesc);
} else {
detail::verify_sub_copy(SrcImgDesc, SrcOffset, DestImgDesc, DestOffset,
CopyExtent);
}
ur_image_desc_t UrSrcDesc = detail::fill_image_desc(SrcImgDesc);
ur_image_desc_t UrDestDesc = detail::fill_image_desc(DestImgDesc);
ur_image_format_t UrSrcFormat = detail::fill_format(SrcImgDesc);
ur_image_format_t UrDestFormat = detail::fill_format(DestImgDesc);
auto ZCopyExtentComponent = detail::fill_image_type(SrcImgDesc, UrSrcDesc);
detail::fill_image_type(DestImgDesc, UrDestDesc);
impl->MSrcOffset = {SrcOffset[0], SrcOffset[1], SrcOffset[2]};
impl->MDestOffset = {DestOffset[0], DestOffset[1], DestOffset[2]};
impl->MSrcImageDesc = UrSrcDesc;
impl->MDstImageDesc = UrDestDesc;
impl->MSrcImageFormat = UrSrcFormat;
impl->MDstImageFormat = UrDestFormat;
impl->MImageCopyFlags = ImageCopyFlags;
if (CopyExtent.size() != 0) {
impl->MCopyExtent = {CopyExtent[0], CopyExtent[1], CopyExtent[2]};
} else {
impl->MCopyExtent = {SrcImgDesc.width, SrcImgDesc.height,
ZCopyExtentComponent};
}
if (SrcExtent.size() != 0) {
impl->MSrcImageDesc.width = SrcExtent[0];
impl->MSrcImageDesc.height = SrcExtent[1];
impl->MSrcImageDesc.depth = SrcExtent[2];
}
if (DestExtent.size() != 0) {
impl->MDstImageDesc.width = DestExtent[0];
impl->MDstImageDesc.height = DestExtent[1];
impl->MDstImageDesc.depth = DestExtent[2];
}
if (impl->MImageCopyFlags == UR_EXP_IMAGE_COPY_FLAG_HOST_TO_DEVICE) {
impl->MSrcImageDesc.rowPitch = 0;
impl->MDstImageDesc.rowPitch = DestPitch;
} else if (impl->MImageCopyFlags == UR_EXP_IMAGE_COPY_FLAG_DEVICE_TO_HOST) {
impl->MSrcImageDesc.rowPitch = SrcPitch;
impl->MDstImageDesc.rowPitch = 0;
} else {
impl->MSrcImageDesc.rowPitch = SrcPitch;
impl->MDstImageDesc.rowPitch = DestPitch;
}
}
static void
fill_copy_args(std::shared_ptr<detail::handler_impl> &impl,
const ext::oneapi::experimental::image_descriptor &Desc,
ur_exp_image_copy_flags_t ImageCopyFlags,
sycl::range<3> SrcOffset = {0, 0, 0},
sycl::range<3> SrcExtent = {0, 0, 0},
sycl::range<3> DestOffset = {0, 0, 0},
sycl::range<3> DestExtent = {0, 0, 0},
sycl::range<3> CopyExtent = {0, 0, 0}) {
fill_copy_args(impl, Desc, Desc, ImageCopyFlags, 0 /*SrcPitch*/,
0 /*DestPitch*/, SrcOffset, SrcExtent, DestOffset, DestExtent,
CopyExtent);
}
static void
fill_copy_args(std::shared_ptr<detail::handler_impl> &impl,
const ext::oneapi::experimental::image_descriptor &Desc,
ur_exp_image_copy_flags_t ImageCopyFlags, size_t SrcPitch,
size_t DestPitch, sycl::range<3> SrcOffset = {0, 0, 0},
sycl::range<3> SrcExtent = {0, 0, 0},
sycl::range<3> DestOffset = {0, 0, 0},
sycl::range<3> DestExtent = {0, 0, 0},
sycl::range<3> CopyExtent = {0, 0, 0}) {
fill_copy_args(impl, Desc, Desc, ImageCopyFlags, SrcPitch, DestPitch,
SrcOffset, SrcExtent, DestOffset, DestExtent, CopyExtent);
}
static void
fill_copy_args(std::shared_ptr<detail::handler_impl> &impl,
const ext::oneapi::experimental::image_descriptor &SrcImgDesc,
const ext::oneapi::experimental::image_descriptor &DestImgDesc,
ur_exp_image_copy_flags_t ImageCopyFlags,
sycl::range<3> SrcOffset = {0, 0, 0},
sycl::range<3> SrcExtent = {0, 0, 0},
sycl::range<3> DestOffset = {0, 0, 0},
sycl::range<3> DestExtent = {0, 0, 0},
sycl::range<3> CopyExtent = {0, 0, 0}) {
fill_copy_args(impl, SrcImgDesc, DestImgDesc, ImageCopyFlags, 0 /*SrcPitch*/,
0 /*DestPitch*/, SrcOffset, SrcExtent, DestOffset, DestExtent,
CopyExtent);
}
} // namespace detail
handler::handler(std::shared_ptr<detail::queue_impl> Queue,
bool CallerNeedsEvent)
: handler(Queue, Queue, nullptr, CallerNeedsEvent) {}
handler::handler(std::shared_ptr<detail::queue_impl> Queue,
std::shared_ptr<detail::queue_impl> PrimaryQueue,
std::shared_ptr<detail::queue_impl> SecondaryQueue,
bool CallerNeedsEvent)
: impl(std::make_shared<detail::handler_impl>(std::move(PrimaryQueue),
std::move(SecondaryQueue),
CallerNeedsEvent)),
MQueue(std::move(Queue)) {}
handler::handler(
std::shared_ptr<ext::oneapi::experimental::detail::graph_impl> Graph)
: impl(std::make_shared<detail::handler_impl>(std::move(Graph))) {}
// Sets the submission state to indicate that an explicit kernel bundle has been
// set. Throws a sycl::exception with errc::invalid if the current state
// indicates that a specialization constant has been set.
void handler::setStateExplicitKernelBundle() {
impl->setStateExplicitKernelBundle();
}
// Sets the submission state to indicate that a specialization constant has been
// set. Throws a sycl::exception with errc::invalid if the current state
// indicates that an explicit kernel bundle has been set.
void handler::setStateSpecConstSet() { impl->setStateSpecConstSet(); }
// Returns true if the submission state is EXPLICIT_KERNEL_BUNDLE_STATE and
// false otherwise.
bool handler::isStateExplicitKernelBundle() const {
return impl->isStateExplicitKernelBundle();
}
// Returns a shared_ptr to the kernel_bundle.
// If there is no kernel_bundle created:
// returns newly created kernel_bundle if Insert is true
// returns shared_ptr(nullptr) if Insert is false
std::shared_ptr<detail::kernel_bundle_impl>
handler::getOrInsertHandlerKernelBundle(bool Insert) const {
if (!impl->MKernelBundle && Insert) {
auto Ctx =
impl->MGraph ? impl->MGraph->getContext() : MQueue->get_context();
auto Dev = impl->MGraph ? impl->MGraph->getDevice() : MQueue->get_device();
impl->MKernelBundle = detail::getSyclObjImpl(
get_kernel_bundle<bundle_state::input>(Ctx, {Dev}, {}));
}
return impl->MKernelBundle;
}
// Sets kernel bundle to the provided one.
void handler::setHandlerKernelBundle(
const std::shared_ptr<detail::kernel_bundle_impl> &NewKernelBundleImpPtr) {
impl->MKernelBundle = NewKernelBundleImpPtr;
}
void handler::setHandlerKernelBundle(kernel Kernel) {
// Kernel may not have an associated kernel bundle if it is created from a
// program. As such, apply getSyclObjImpl directly on the kernel, i.e. not
// the other way around: getSyclObjImp(Kernel->get_kernel_bundle()).
std::shared_ptr<detail::kernel_bundle_impl> KernelBundleImpl =
detail::getSyclObjImpl(Kernel)->get_kernel_bundle();
setHandlerKernelBundle(KernelBundleImpl);
}
event handler::finalize() {
// This block of code is needed only for reduction implementation.
// It is harmless (does nothing) for everything else.
if (MIsFinalized)
return MLastEvent;
MIsFinalized = true;
// According to 4.7.6.9 of SYCL2020 spec, if a placeholder accessor is passed
// to a command without being bound to a command group, an exception should
// be thrown.
{
for (const auto &arg : impl->MArgs) {
if (arg.MType != detail::kernel_param_kind_t::kind_accessor)
continue;
detail::Requirement *AccImpl =
static_cast<detail::Requirement *>(arg.MPtr);
if (AccImpl->MIsPlaceH) {
auto It = std::find(impl->CGData.MRequirements.begin(),
impl->CGData.MRequirements.end(), AccImpl);
if (It == impl->CGData.MRequirements.end())
throw sycl::exception(make_error_code(errc::kernel_argument),
"placeholder accessor must be bound by calling "
"handler::require() before it can be used.");
// Check associated accessors
bool AccFound = false;
for (detail::ArgDesc &Acc : impl->MAssociatedAccesors) {
if (Acc.MType == detail::kernel_param_kind_t::kind_accessor &&
static_cast<detail::Requirement *>(Acc.MPtr) == AccImpl) {
AccFound = true;
break;
}
}
if (!AccFound) {
throw sycl::exception(make_error_code(errc::kernel_argument),
"placeholder accessor must be bound by calling "
"handler::require() before it can be used.");
}
}
}
}
const auto &type = getType();
if (type == detail::CGType::Kernel) {
// If there were uses of set_specialization_constant build the kernel_bundle
std::shared_ptr<detail::kernel_bundle_impl> KernelBundleImpPtr =
getOrInsertHandlerKernelBundle(/*Insert=*/false);
if (KernelBundleImpPtr) {
// Make sure implicit non-interop kernel bundles have the kernel
if (!KernelBundleImpPtr->isInterop() &&
!impl->isStateExplicitKernelBundle()) {
auto Dev =
impl->MGraph ? impl->MGraph->getDevice() : MQueue->get_device();
kernel_id KernelID =
detail::ProgramManager::getInstance().getSYCLKernelID(
MKernelName.c_str());
bool KernelInserted = KernelBundleImpPtr->add_kernel(KernelID, Dev);
// If kernel was not inserted and the bundle is in input mode we try
// building it and trying to find the kernel in executable mode
if (!KernelInserted &&
KernelBundleImpPtr->get_bundle_state() == bundle_state::input) {
auto KernelBundle =
detail::createSyclObjFromImpl<kernel_bundle<bundle_state::input>>(
KernelBundleImpPtr);
kernel_bundle<bundle_state::executable> ExecKernelBundle =
build(KernelBundle);
KernelBundleImpPtr = detail::getSyclObjImpl(ExecKernelBundle);
setHandlerKernelBundle(KernelBundleImpPtr);
KernelInserted = KernelBundleImpPtr->add_kernel(KernelID, Dev);
}
// If the kernel was not found in executable mode we throw an exception
if (!KernelInserted)
throw sycl::exception(make_error_code(errc::runtime),
"Failed to add kernel to kernel bundle.");
}
switch (KernelBundleImpPtr->get_bundle_state()) {
case bundle_state::input: {
// Underlying level expects kernel_bundle to be in executable state
kernel_bundle<bundle_state::executable> ExecBundle = build(
detail::createSyclObjFromImpl<kernel_bundle<bundle_state::input>>(
KernelBundleImpPtr));
KernelBundleImpPtr = detail::getSyclObjImpl(ExecBundle);
setHandlerKernelBundle(KernelBundleImpPtr);
break;
}
case bundle_state::executable:
// Nothing to do
break;
case bundle_state::object:
case bundle_state::ext_oneapi_source:
assert(0 && "Expected that the bundle is either in input or executable "
"states.");
break;
}
}
if (MQueue && !impl->MGraph && !impl->MSubgraphNode &&
!MQueue->hasCommandGraph() && !impl->CGData.MRequirements.size() &&
!MStreamStorage.size() &&
detail::Scheduler::areEventsSafeForSchedulerBypass(
impl->CGData.MEvents, MQueue->getContextImplPtr())) {
// if user does not add a new dependency to the dependency graph, i.e.
// the graph is not changed, then this faster path is used to submit
// kernel bypassing scheduler and avoiding CommandGroup, Command objects
// creation.
std::vector<ur_event_handle_t> RawEvents =
detail::Command::getUrEvents(impl->CGData.MEvents, MQueue, false);
detail::EventImplPtr NewEvent;
#ifdef XPTI_ENABLE_INSTRUMENTATION
// uint32_t StreamID, uint64_t InstanceID, xpti_td* TraceEvent,
int32_t StreamID = xptiRegisterStream(detail::SYCL_STREAM_NAME);
auto [CmdTraceEvent, InstanceID] = emitKernelInstrumentationData(
StreamID, MKernel, MCodeLoc, impl->MIsTopCodeLoc, MKernelName.c_str(),
MQueue, impl->MNDRDesc, KernelBundleImpPtr, impl->MArgs);
auto EnqueueKernel = [&, CmdTraceEvent = CmdTraceEvent,
InstanceID = InstanceID]() {
#else
auto EnqueueKernel = [&]() {
#endif
#ifdef XPTI_ENABLE_INSTRUMENTATION
detail::emitInstrumentationGeneral(StreamID, InstanceID, CmdTraceEvent,
xpti::trace_task_begin, nullptr);
#endif
const detail::RTDeviceBinaryImage *BinImage = nullptr;
if (detail::SYCLConfig<detail::SYCL_JIT_AMDGCN_PTX_KERNELS>::get()) {
std::tie(BinImage, std::ignore) =
detail::retrieveKernelBinary(MQueue, MKernelName.c_str());
assert(BinImage && "Failed to obtain a binary image.");
}
enqueueImpKernel(MQueue, impl->MNDRDesc, impl->MArgs,
KernelBundleImpPtr, MKernel, MKernelName.c_str(),
RawEvents, NewEvent, nullptr, impl->MKernelCacheConfig,
impl->MKernelIsCooperative,
impl->MKernelUsesClusterLaunch,
impl->MKernelWorkGroupMemorySize, BinImage);
#ifdef XPTI_ENABLE_INSTRUMENTATION
// Emit signal only when event is created
if (NewEvent != nullptr) {
detail::emitInstrumentationGeneral(
StreamID, InstanceID, CmdTraceEvent, xpti::trace_signal,
static_cast<const void *>(NewEvent->getHandle()));
}
detail::emitInstrumentationGeneral(StreamID, InstanceID, CmdTraceEvent,
xpti::trace_task_end, nullptr);
#endif
};
bool DiscardEvent = (MQueue->MDiscardEvents || !impl->MEventNeeded) &&
MQueue->supportsDiscardingPiEvents();
if (DiscardEvent) {
// Kernel only uses assert if it's non interop one
bool KernelUsesAssert =
!(MKernel && MKernel->isInterop()) &&
detail::ProgramManager::getInstance().kernelUsesAssert(
MKernelName.c_str());
DiscardEvent = !KernelUsesAssert;
}
if (DiscardEvent) {
EnqueueKernel();
const auto &EventImpl = detail::getSyclObjImpl(MLastEvent);
EventImpl->setStateDiscarded();
} else {
NewEvent = detail::getSyclObjImpl(MLastEvent);
NewEvent->setQueue(MQueue);
NewEvent->setWorkerQueue(MQueue);
NewEvent->setContextImpl(MQueue->getContextImplPtr());
NewEvent->setStateIncomplete();
NewEvent->setSubmissionTime();
EnqueueKernel();
NewEvent->setEnqueued();
// connect returned event with dependent events
if (!MQueue->isInOrder()) {
NewEvent->getPreparedDepsEvents() = impl->CGData.MEvents;
NewEvent->cleanDepEventsThroughOneLevel();
}
}
return MLastEvent;
}
}
std::unique_ptr<detail::CG> CommandGroup;
switch (type) {
case detail::CGType::Kernel: {
// Copy kernel name here instead of move so that it's available after
// running of this method by reductions implementation. This allows for
// assert feature to check if kernel uses assertions
CommandGroup.reset(new detail::CGExecKernel(
std::move(impl->MNDRDesc), std::move(MHostKernel), std::move(MKernel),
std::move(impl->MKernelBundle), std::move(impl->CGData),
std::move(impl->MArgs), MKernelName.c_str(), std::move(MStreamStorage),
std::move(impl->MAuxiliaryResources), getType(),
impl->MKernelCacheConfig, impl->MKernelIsCooperative,
impl->MKernelUsesClusterLaunch, impl->MKernelWorkGroupMemorySize,
MCodeLoc));
break;
}
case detail::CGType::CopyAccToPtr:
case detail::CGType::CopyPtrToAcc:
case detail::CGType::CopyAccToAcc:
CommandGroup.reset(
new detail::CGCopy(getType(), MSrcPtr, MDstPtr, std::move(impl->CGData),
std::move(impl->MAuxiliaryResources), MCodeLoc));
break;
case detail::CGType::Fill:
CommandGroup.reset(new detail::CGFill(std::move(MPattern), MDstPtr,
std::move(impl->CGData), MCodeLoc));
break;
case detail::CGType::UpdateHost:
CommandGroup.reset(
new detail::CGUpdateHost(MDstPtr, std::move(impl->CGData), MCodeLoc));
break;
case detail::CGType::CopyUSM:
CommandGroup.reset(new detail::CGCopyUSM(
MSrcPtr, MDstPtr, MLength, std::move(impl->CGData), MCodeLoc));
break;
case detail::CGType::FillUSM:
CommandGroup.reset(new detail::CGFillUSM(std::move(MPattern), MDstPtr,
MLength, std::move(impl->CGData),
MCodeLoc));
break;
case detail::CGType::PrefetchUSM:
CommandGroup.reset(new detail::CGPrefetchUSM(
MDstPtr, MLength, std::move(impl->CGData), MCodeLoc));
break;
case detail::CGType::AdviseUSM:
CommandGroup.reset(new detail::CGAdviseUSM(MDstPtr, MLength, impl->MAdvice,
std::move(impl->CGData),
getType(), MCodeLoc));
break;
case detail::CGType::Copy2DUSM:
CommandGroup.reset(new detail::CGCopy2DUSM(
MSrcPtr, MDstPtr, impl->MSrcPitch, impl->MDstPitch, impl->MWidth,
impl->MHeight, std::move(impl->CGData), MCodeLoc));
break;
case detail::CGType::Fill2DUSM:
CommandGroup.reset(new detail::CGFill2DUSM(
std::move(MPattern), MDstPtr, impl->MDstPitch, impl->MWidth,
impl->MHeight, std::move(impl->CGData), MCodeLoc));
break;
case detail::CGType::Memset2DUSM:
CommandGroup.reset(new detail::CGMemset2DUSM(
MPattern[0], MDstPtr, impl->MDstPitch, impl->MWidth, impl->MHeight,
std::move(impl->CGData), MCodeLoc));
break;
case detail::CGType::EnqueueNativeCommand:
case detail::CGType::CodeplayHostTask: {
auto context = impl->MGraph
? detail::getSyclObjImpl(impl->MGraph->getContext())
: MQueue->getContextImplPtr();
CommandGroup.reset(new detail::CGHostTask(
std::move(impl->MHostTask), MQueue, context, std::move(impl->MArgs),
std::move(impl->CGData), getType(), MCodeLoc));
break;
}
case detail::CGType::Barrier:
case detail::CGType::BarrierWaitlist: {
if (auto GraphImpl = getCommandGraph(); GraphImpl != nullptr) {
impl->CGData.MEvents.insert(std::end(impl->CGData.MEvents),
std::begin(impl->MEventsWaitWithBarrier),
std::end(impl->MEventsWaitWithBarrier));
// Barrier node is implemented as an empty node in Graph
// but keep the barrier type to help managing dependencies
setType(detail::CGType::Barrier);
CommandGroup.reset(new detail::CG(detail::CGType::Barrier,
std::move(impl->CGData), MCodeLoc));
} else {
CommandGroup.reset(new detail::CGBarrier(
std::move(impl->MEventsWaitWithBarrier), impl->MEventMode,
std::move(impl->CGData), getType(), MCodeLoc));
}
break;
}
case detail::CGType::ProfilingTag: {
CommandGroup.reset(
new detail::CGProfilingTag(std::move(impl->CGData), MCodeLoc));
break;
}
case detail::CGType::CopyToDeviceGlobal: {
CommandGroup.reset(new detail::CGCopyToDeviceGlobal(
MSrcPtr, MDstPtr, impl->MIsDeviceImageScoped, MLength, impl->MOffset,
std::move(impl->CGData), MCodeLoc));
break;
}
case detail::CGType::CopyFromDeviceGlobal: {
CommandGroup.reset(new detail::CGCopyFromDeviceGlobal(
MSrcPtr, MDstPtr, impl->MIsDeviceImageScoped, MLength, impl->MOffset,
std::move(impl->CGData), MCodeLoc));
break;
}
case detail::CGType::ReadWriteHostPipe: {
CommandGroup.reset(new detail::CGReadWriteHostPipe(
impl->HostPipeName, impl->HostPipeBlocking, impl->HostPipePtr,
impl->HostPipeTypeSize, impl->HostPipeRead, std::move(impl->CGData),
MCodeLoc));
break;
}
case detail::CGType::ExecCommandBuffer: {
std::shared_ptr<ext::oneapi::experimental::detail::graph_impl> ParentGraph =
MQueue ? MQueue->getCommandGraph() : impl->MGraph;
// If a parent graph is set that means we are adding or recording a subgraph
// and we don't want to actually execute this command graph submission.
if (ParentGraph) {
ext::oneapi::experimental::detail::graph_impl::WriteLock ParentLock;
if (MQueue) {
ParentLock = ext::oneapi::experimental::detail::graph_impl::WriteLock(
ParentGraph->MMutex);
}
impl->CGData.MRequirements = impl->MExecGraph->getRequirements();
// Here we are using the CommandGroup without passing a CommandBuffer to
// pass the exec_graph_impl and event dependencies. Since this subgraph CG
// will not be executed this is fine.
CommandGroup.reset(new sycl::detail::CGExecCommandBuffer(
nullptr, impl->MExecGraph, std::move(impl->CGData)));
} else {
event GraphCompletionEvent =
impl->MExecGraph->enqueue(MQueue, std::move(impl->CGData));
MLastEvent = GraphCompletionEvent;
return MLastEvent;
}
} break;
case detail::CGType::CopyImage:
CommandGroup.reset(new detail::CGCopyImage(
MSrcPtr, MDstPtr, impl->MSrcImageDesc, impl->MDstImageDesc,
impl->MSrcImageFormat, impl->MDstImageFormat, impl->MImageCopyFlags,
impl->MSrcOffset, impl->MDestOffset, impl->MCopyExtent,
std::move(impl->CGData), MCodeLoc));
break;
case detail::CGType::SemaphoreWait:
CommandGroup.reset(
new detail::CGSemaphoreWait(impl->MExternalSemaphore, impl->MWaitValue,
std::move(impl->CGData), MCodeLoc));
break;
case detail::CGType::SemaphoreSignal:
CommandGroup.reset(new detail::CGSemaphoreSignal(
impl->MExternalSemaphore, impl->MSignalValue, std::move(impl->CGData),
MCodeLoc));
break;
case detail::CGType::AsyncAlloc:
CommandGroup.reset(new detail::CGAsyncAlloc(
impl->MAllocSize, impl->MMemPool, impl->MAsyncAllocEvent,
std::move(impl->CGData), MCodeLoc));
break;
case detail::CGType::AsyncFree:
CommandGroup.reset(new detail::CGAsyncFree(
impl->MFreePtr, std::move(impl->CGData), MCodeLoc));
break;
case detail::CGType::None:
CommandGroup.reset(new detail::CG(detail::CGType::None,
std::move(impl->CGData), MCodeLoc));
break;
}
if (!CommandGroup)
throw exception(make_error_code(errc::runtime),
"Internal Error. Command group cannot be constructed.");
// Propagate MIsTopCodeLoc state to CommandGroup.
// Will be used for XPTI payload generation for CG's related events.
CommandGroup->MIsTopCodeLoc = impl->MIsTopCodeLoc;
// If there is a graph associated with the handler we are in the explicit
// graph mode, so we store the CG instead of submitting it to the scheduler,
// so it can be retrieved by the graph later.
if (impl->MGraph) {
impl->MGraphNodeCG = std::move(CommandGroup);
return detail::createSyclObjFromImpl<event>(
std::make_shared<detail::event_impl>());
}
// If the queue has an associated graph then we need to take the CG and pass
// it to the graph to create a node, rather than submit it to the scheduler.
if (auto GraphImpl = MQueue->getCommandGraph(); GraphImpl) {
auto EventImpl = std::make_shared<detail::event_impl>();
EventImpl->setSubmittedQueue(MQueue);
std::shared_ptr<ext::oneapi::experimental::detail::node_impl> NodeImpl =
nullptr;
// GraphImpl is read and written in this scope so we lock this graph
// with full priviledges.
ext::oneapi::experimental::detail::graph_impl::WriteLock Lock(
GraphImpl->MMutex);
ext::oneapi::experimental::node_type NodeType =
impl->MUserFacingNodeType != ext::oneapi::experimental::node_type::empty
? impl->MUserFacingNodeType
: ext::oneapi::experimental::detail::getNodeTypeFromCG(getType());
// Create a new node in the graph representing this command-group
if (MQueue->isInOrder()) {
// In-order queues create implicit linear dependencies between nodes.
// Find the last node added to the graph from this queue, so our new
// node can set it as a predecessor.
std::vector<std::shared_ptr<ext::oneapi::experimental::detail::node_impl>>
Deps;
if (auto DependentNode = GraphImpl->getLastInorderNode(MQueue)) {
Deps.push_back(std::move(DependentNode));
}
NodeImpl = GraphImpl->add(NodeType, std::move(CommandGroup), Deps);
// If we are recording an in-order queue remember the new node, so it
// can be used as a dependency for any more nodes recorded from this
// queue.
GraphImpl->setLastInorderNode(MQueue, NodeImpl);
} else {
auto LastBarrierRecordedFromQueue = GraphImpl->getBarrierDep(MQueue);
std::vector<std::shared_ptr<ext::oneapi::experimental::detail::node_impl>>
Deps;
if (LastBarrierRecordedFromQueue) {
Deps.push_back(LastBarrierRecordedFromQueue);
}
NodeImpl = GraphImpl->add(NodeType, std::move(CommandGroup), Deps);
if (NodeImpl->MCGType == sycl::detail::CGType::Barrier) {
GraphImpl->setBarrierDep(MQueue, NodeImpl);
}
}
// Associate an event with this new node and return the event.
GraphImpl->addEventForNode(EventImpl, std::move(NodeImpl));
return detail::createSyclObjFromImpl<event>(EventImpl);
}
detail::EventImplPtr Event = detail::Scheduler::getInstance().addCG(
std::move(CommandGroup), std::move(MQueue), impl->MEventNeeded);
MLastEvent = detail::createSyclObjFromImpl<event>(Event);
return MLastEvent;
}
void handler::addReduction(const std::shared_ptr<const void> &ReduObj) {
impl->MAuxiliaryResources.push_back(ReduObj);
}
void handler::associateWithHandlerCommon(detail::AccessorImplPtr AccImpl,
int AccTarget) {
if (getCommandGraph() &&
static_cast<detail::SYCLMemObjT *>(AccImpl->MSYCLMemObj)
->needsWriteBack()) {
throw sycl::exception(make_error_code(errc::invalid),
"Accessors to buffers which have write_back enabled "
"are not allowed to be used in command graphs.");
}
detail::Requirement *Req = AccImpl.get();
if (Req->MAccessMode != sycl::access_mode::read) {
auto SYCLMemObj = static_cast<detail::SYCLMemObjT *>(Req->MSYCLMemObj);
SYCLMemObj->handleWriteAccessorCreation();
}
// Add accessor to the list of requirements.
if (Req->MAccessRange.size() != 0)
impl->CGData.MRequirements.push_back(Req);
// Store copy of the accessor.
impl->CGData.MAccStorage.push_back(std::move(AccImpl));
// Add an accessor to the handler list of associated accessors.
// For associated accessors index does not means nothing.
impl->MAssociatedAccesors.emplace_back(
detail::kernel_param_kind_t::kind_accessor, Req, AccTarget, /*index*/ 0);
}
void handler::associateWithHandler(detail::AccessorBaseHost *AccBase,
access::target AccTarget) {
associateWithHandlerCommon(detail::getSyclObjImpl(*AccBase),
static_cast<int>(AccTarget));
}
void handler::associateWithHandler(
detail::UnsampledImageAccessorBaseHost *AccBase, image_target AccTarget) {
associateWithHandlerCommon(detail::getSyclObjImpl(*AccBase),
static_cast<int>(AccTarget));
}
void handler::associateWithHandler(
detail::SampledImageAccessorBaseHost *AccBase, image_target AccTarget) {
associateWithHandlerCommon(detail::getSyclObjImpl(*AccBase),
static_cast<int>(AccTarget));
}
static void addArgsForGlobalAccessor(detail::Requirement *AccImpl, size_t Index,
size_t &IndexShift, int Size,
bool IsKernelCreatedFromSource,
size_t GlobalSize,
std::vector<detail::ArgDesc> &Args,
bool isESIMD) {
using detail::kernel_param_kind_t;
if (AccImpl->PerWI)
AccImpl->resize(GlobalSize);
Args.emplace_back(kernel_param_kind_t::kind_accessor, AccImpl, Size,
Index + IndexShift);
// TODO ESIMD currently does not suport offset, memory and access ranges -
// accessor::init for ESIMD-mode accessor has a single field, translated
// to a single kernel argument set above.
if (!isESIMD && !IsKernelCreatedFromSource) {
// Dimensionality of the buffer is 1 when dimensionality of the
// accessor is 0.
const size_t SizeAccField =
sizeof(size_t) * (AccImpl->MDims == 0 ? 1 : AccImpl->MDims);
++IndexShift;
Args.emplace_back(kernel_param_kind_t::kind_std_layout,
&AccImpl->MAccessRange[0], SizeAccField,
Index + IndexShift);
++IndexShift;
Args.emplace_back(kernel_param_kind_t::kind_std_layout,
&AccImpl->MMemoryRange[0], SizeAccField,
Index + IndexShift);
++IndexShift;
Args.emplace_back(kernel_param_kind_t::kind_std_layout,
&AccImpl->MOffset[0], SizeAccField, Index + IndexShift);
}
}
void handler::processArg(void *Ptr, const detail::kernel_param_kind_t &Kind,
const int Size, const size_t Index, size_t &IndexShift,
bool IsKernelCreatedFromSource, bool IsESIMD) {
using detail::kernel_param_kind_t;
switch (Kind) {
case kernel_param_kind_t::kind_std_layout:
case kernel_param_kind_t::kind_pointer: {
addArg(Kind, Ptr, Size, Index + IndexShift);
break;
}
case kernel_param_kind_t::kind_stream: {
// Stream contains several accessors inside.
stream *S = static_cast<stream *>(Ptr);
detail::AccessorBaseHost *GBufBase =
static_cast<detail::AccessorBaseHost *>(&S->GlobalBuf);
detail::AccessorImplPtr GBufImpl = detail::getSyclObjImpl(*GBufBase);
detail::Requirement *GBufReq = GBufImpl.get();
addArgsForGlobalAccessor(
GBufReq, Index, IndexShift, Size, IsKernelCreatedFromSource,
impl->MNDRDesc.GlobalSize.size(), impl->MArgs, IsESIMD);
++IndexShift;
detail::AccessorBaseHost *GOffsetBase =
static_cast<detail::AccessorBaseHost *>(&S->GlobalOffset);
detail::AccessorImplPtr GOfssetImpl = detail::getSyclObjImpl(*GOffsetBase);
detail::Requirement *GOffsetReq = GOfssetImpl.get();
addArgsForGlobalAccessor(
GOffsetReq, Index, IndexShift, Size, IsKernelCreatedFromSource,
impl->MNDRDesc.GlobalSize.size(), impl->MArgs, IsESIMD);
++IndexShift;
detail::AccessorBaseHost *GFlushBase =
static_cast<detail::AccessorBaseHost *>(&S->GlobalFlushBuf);
detail::AccessorImplPtr GFlushImpl = detail::getSyclObjImpl(*GFlushBase);
detail::Requirement *GFlushReq = GFlushImpl.get();
size_t GlobalSize = impl->MNDRDesc.GlobalSize.size();
// If work group size wasn't set explicitly then it must be recieved
// from kernel attribute or set to default values.
// For now we can't get this attribute here.
// So we just suppose that WG size is always default for stream.
// TODO adjust MNDRDesc when device image contains kernel's attribute
if (GlobalSize == 0) {
// Suppose that work group size is 1 for every dimension
GlobalSize = impl->MNDRDesc.NumWorkGroups.size();
}
addArgsForGlobalAccessor(GFlushReq, Index, IndexShift, Size,
IsKernelCreatedFromSource, GlobalSize, impl->MArgs,
IsESIMD);
++IndexShift;
addArg(kernel_param_kind_t::kind_std_layout, &S->FlushBufferSize,
sizeof(S->FlushBufferSize), Index + IndexShift);
break;
}
case kernel_param_kind_t::kind_accessor: {
// For args kind of accessor Size is information about accessor.
// The first 11 bits of Size encodes the accessor target.
const access::target AccTarget =
static_cast<access::target>(Size & AccessTargetMask);
switch (AccTarget) {
case access::target::device:
case access::target::constant_buffer: {
detail::Requirement *AccImpl = static_cast<detail::Requirement *>(Ptr);
addArgsForGlobalAccessor(
AccImpl, Index, IndexShift, Size, IsKernelCreatedFromSource,
impl->MNDRDesc.GlobalSize.size(), impl->MArgs, IsESIMD);
break;
}
case access::target::local: {
detail::LocalAccessorImplHost *LAcc =
static_cast<detail::LocalAccessorImplHost *>(Ptr);
range<3> &Size = LAcc->MSize;
const int Dims = LAcc->MDims;
int SizeInBytes = LAcc->MElemSize;
for (int I = 0; I < Dims; ++I)
SizeInBytes *= Size[I];
// Some backends do not accept zero-sized local memory arguments, so we
// make it a minimum allocation of 1 byte.
SizeInBytes = std::max(SizeInBytes, 1);
impl->MArgs.emplace_back(kernel_param_kind_t::kind_std_layout, nullptr,
SizeInBytes, Index + IndexShift);
// TODO ESIMD currently does not suport MSize field passing yet
// accessor::init for ESIMD-mode accessor has a single field, translated
// to a single kernel argument set above.
if (!IsESIMD && !IsKernelCreatedFromSource) {
++IndexShift;
const size_t SizeAccField = (Dims == 0 ? 1 : Dims) * sizeof(Size[0]);
addArg(kernel_param_kind_t::kind_std_layout, &Size, SizeAccField,
Index + IndexShift);
++IndexShift;
addArg(kernel_param_kind_t::kind_std_layout, &Size, SizeAccField,
Index + IndexShift);
++IndexShift;
addArg(kernel_param_kind_t::kind_std_layout, &Size, SizeAccField,
Index + IndexShift);
}
break;