forked from intel/llvm
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcommands.cpp
3749 lines (3306 loc) · 146 KB
/
commands.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
//
// 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 "ur_api.h"
#include <detail/error_handling/error_handling.hpp>
#include <detail/context_impl.hpp>
#include <detail/event_impl.hpp>
#include <detail/helpers.hpp>
#include <detail/host_pipe_map_entry.hpp>
#include <detail/kernel_bundle_impl.hpp>
#include <detail/kernel_impl.hpp>
#include <detail/kernel_info.hpp>
#include <detail/memory_manager.hpp>
#include <detail/program_manager/program_manager.hpp>
#include <detail/queue_impl.hpp>
#include <detail/sampler_impl.hpp>
#include <detail/scheduler/commands.hpp>
#include <detail/scheduler/scheduler.hpp>
#include <detail/stream_impl.hpp>
#include <detail/xpti_registry.hpp>
#include <sycl/access/access.hpp>
#include <sycl/backend_types.hpp>
#include <sycl/detail/cg_types.hpp>
#include <sycl/detail/helpers.hpp>
#include <sycl/detail/kernel_desc.hpp>
#include <sycl/sampler.hpp>
#include <cassert>
#include <optional>
#include <string>
#include <vector>
#ifdef __has_include
#if __has_include(<cxxabi.h>)
#define __SYCL_ENABLE_GNU_DEMANGLING
#include <cstdlib>
#include <cxxabi.h>
#include <memory>
#endif
#endif
#ifdef XPTI_ENABLE_INSTRUMENTATION
#include "xpti/xpti_trace_framework.hpp"
#include <detail/xpti_registry.hpp>
#endif
namespace sycl {
inline namespace _V1 {
namespace detail {
// MemoryManager:: calls return void and throw exception in case of failure.
// enqueueImp is expected to return status, not exception to correctly handle
// submission error.
template <typename MemOpFuncT, typename... MemOpArgTs>
ur_result_t callMemOpHelper(MemOpFuncT &MemOpFunc, MemOpArgTs &&...MemOpArgs) {
try {
MemOpFunc(std::forward<MemOpArgTs>(MemOpArgs)...);
} catch (sycl::exception &e) {
return static_cast<ur_result_t>(get_ur_error(e));
}
return UR_RESULT_SUCCESS;
}
template <typename MemOpRet, typename MemOpFuncT, typename... MemOpArgTs>
ur_result_t callMemOpHelperRet(MemOpRet &MemOpResult, MemOpFuncT &MemOpFunc,
MemOpArgTs &&...MemOpArgs) {
try {
MemOpResult = MemOpFunc(std::forward<MemOpArgTs>(MemOpArgs)...);
} catch (sycl::exception &e) {
return static_cast<ur_result_t>(get_ur_error(e));
}
return UR_RESULT_SUCCESS;
}
#ifdef XPTI_ENABLE_INSTRUMENTATION
// Global graph for the application
extern xpti::trace_event_data_t *GSYCLGraphEvent;
static bool CurrentCodeLocationValid() {
detail::tls_code_loc_t Tls;
auto CodeLoc = Tls.query();
auto FileName = CodeLoc.fileName();
auto FunctionName = CodeLoc.functionName();
return (FileName && FileName[0] != '\0') ||
(FunctionName && FunctionName[0] != '\0');
}
void emitInstrumentationGeneral(uint32_t StreamID, uint64_t InstanceID,
xpti_td *TraceEvent, uint16_t Type,
const void *Addr) {
if (!(xptiCheckTraceEnabled(StreamID, Type) && TraceEvent))
return;
// Trace event notifier that emits a Type event
xptiNotifySubscribers(StreamID, Type, detail::GSYCLGraphEvent,
static_cast<xpti_td *>(TraceEvent), InstanceID, Addr);
}
static size_t deviceToID(const device &Device) {
return reinterpret_cast<size_t>(getSyclObjImpl(Device)->getHandleRef());
}
static void addDeviceMetadata(xpti_td *TraceEvent, const QueueImplPtr &Queue) {
xpti::addMetadata(TraceEvent, "sycl_device_type",
queueDeviceToString(Queue.get()));
if (Queue) {
xpti::addMetadata(TraceEvent, "sycl_device",
deviceToID(Queue->get_device()));
xpti::addMetadata(TraceEvent, "sycl_device_name",
getSyclObjImpl(Queue->get_device())->getDeviceName());
}
}
static unsigned long long getQueueID(const QueueImplPtr &Queue) {
return Queue ? Queue->getQueueID() : 0;
}
#endif
static ContextImplPtr getContext(const QueueImplPtr &Queue) {
if (Queue)
return Queue->getContextImplPtr();
return nullptr;
}
#ifdef __SYCL_ENABLE_GNU_DEMANGLING
struct DemangleHandle {
char *p;
DemangleHandle(char *ptr) : p(ptr) {}
DemangleHandle(const DemangleHandle &) = delete;
DemangleHandle &operator=(const DemangleHandle &) = delete;
~DemangleHandle() { std::free(p); }
};
static std::string demangleKernelName(std::string Name) {
int Status = -1; // some arbitrary value to eliminate the compiler warning
DemangleHandle result(abi::__cxa_demangle(Name.c_str(), NULL, NULL, &Status));
return (Status == 0) ? result.p : Name;
}
#else
static std::string demangleKernelName(std::string Name) { return Name; }
#endif
static std::string accessModeToString(access::mode Mode) {
switch (Mode) {
case access::mode::read:
return "read";
case access::mode::write:
return "write";
case access::mode::read_write:
return "read_write";
case access::mode::discard_write:
return "discard_write";
case access::mode::discard_read_write:
return "discard_read_write";
default:
return "unknown";
}
}
#ifdef XPTI_ENABLE_INSTRUMENTATION
// Using the command group type to create node types for the asynchronous task
// graph modeling
static std::string commandToNodeType(Command::CommandType Type) {
switch (Type) {
case Command::CommandType::RUN_CG:
return "command_group_node";
case Command::CommandType::COPY_MEMORY:
return "memory_transfer_node";
case Command::CommandType::ALLOCA:
return "memory_allocation_node";
case Command::CommandType::ALLOCA_SUB_BUF:
return "sub_buffer_creation_node";
case Command::CommandType::RELEASE:
return "memory_deallocation_node";
case Command::CommandType::MAP_MEM_OBJ:
return "memory_transfer_node";
case Command::CommandType::UNMAP_MEM_OBJ:
return "memory_transfer_node";
case Command::CommandType::UPDATE_REQUIREMENT:
return "host_acc_create_buffer_lock_node";
case Command::CommandType::EMPTY_TASK:
return "host_acc_destroy_buffer_release_node";
default:
return "unknown_node";
}
}
// Using the names being generated and the string are subject to change to
// something more meaningful to end-users as this will be visible in analysis
// tools that subscribe to this data
static std::string commandToName(Command::CommandType Type) {
switch (Type) {
case Command::CommandType::RUN_CG:
return "Command Group Action";
case Command::CommandType::COPY_MEMORY:
return "Memory Transfer (Copy)";
case Command::CommandType::ALLOCA:
return "Memory Allocation";
case Command::CommandType::ALLOCA_SUB_BUF:
return "Sub Buffer Creation";
case Command::CommandType::RELEASE:
return "Memory Deallocation";
case Command::CommandType::MAP_MEM_OBJ:
return "Memory Transfer (Map)";
case Command::CommandType::UNMAP_MEM_OBJ:
return "Memory Transfer (Unmap)";
case Command::CommandType::UPDATE_REQUIREMENT:
return "Host Accessor Creation/Buffer Lock";
case Command::CommandType::EMPTY_TASK:
return "Host Accessor Destruction/Buffer Lock Release";
default:
return "Unknown Action";
}
}
#endif
std::vector<ur_event_handle_t>
Command::getUrEvents(const std::vector<EventImplPtr> &EventImpls,
const QueueImplPtr &CommandQueue, bool IsHostTaskCommand) {
std::vector<ur_event_handle_t> RetUrEvents;
for (auto &EventImpl : EventImpls) {
auto Handle = EventImpl->getHandle();
if (Handle == nullptr)
continue;
// Do not add redundant event dependencies for in-order queues.
// At this stage dependency is definitely ur task and need to check if
// current one is a host task. In this case we should not skip ur event due
// to different sync mechanisms for different task types on in-order queue.
if (CommandQueue && EventImpl->getWorkerQueue() == CommandQueue &&
CommandQueue->isInOrder() && !IsHostTaskCommand)
continue;
RetUrEvents.push_back(Handle);
}
return RetUrEvents;
}
std::vector<ur_event_handle_t>
Command::getUrEvents(const std::vector<EventImplPtr> &EventImpls) const {
return getUrEvents(EventImpls, MWorkerQueue, isHostTask());
}
// This function is implemented (duplicating getUrEvents a lot) as short term
// solution for the issue that barrier with wait list could not
// handle empty ur event handles when kernel is enqueued on host task
// completion.
std::vector<ur_event_handle_t>
Command::getUrEventsBlocking(const std::vector<EventImplPtr> &EventImpls,
bool HasEventMode) const {
std::vector<ur_event_handle_t> RetUrEvents;
for (auto &EventImpl : EventImpls) {
// Throwaway events created with empty constructor will not have a context
// (which is set lazily) calling getContextImpl() would set that
// context, which we wish to avoid as it is expensive.
// Skip host task and NOP events also.
if (EventImpl->isDefaultConstructed() || EventImpl->isHost() ||
EventImpl->isNOP())
continue;
// If command has not been enqueued then we have to enqueue it.
// It may happen if async enqueue in a host task is involved.
// Interoperability events are special cases and they are not enqueued, as
// they don't have an associated queue and command.
if (!EventImpl->isInterop() && !EventImpl->isEnqueued()) {
if (!EventImpl->getCommand() ||
!static_cast<Command *>(EventImpl->getCommand())->producesPiEvent())
continue;
std::vector<Command *> AuxCmds;
Scheduler::getInstance().enqueueCommandForCG(EventImpl, AuxCmds,
BLOCKING);
}
// Do not add redundant event dependencies for in-order queues.
// At this stage dependency is definitely ur task and need to check if
// current one is a host task. In this case we should not skip pi event due
// to different sync mechanisms for different task types on in-order queue.
// If the resulting event is supposed to have a specific event mode,
// redundant events may still differ from the resulting event, so they are
// kept.
if (!HasEventMode && MWorkerQueue &&
EventImpl->getWorkerQueue() == MWorkerQueue &&
MWorkerQueue->isInOrder() && !isHostTask())
continue;
RetUrEvents.push_back(EventImpl->getHandle());
}
return RetUrEvents;
}
bool Command::isHostTask() const {
return (MType == CommandType::RUN_CG) /* host task has this type also */ &&
((static_cast<const ExecCGCommand *>(this))->getCG().getType() ==
CGType::CodeplayHostTask);
}
bool Command::isFusable() const {
if ((MType != CommandType::RUN_CG)) {
return false;
}
const auto &CG = (static_cast<const ExecCGCommand &>(*this)).getCG();
return (CG.getType() == CGType::Kernel) &&
(!static_cast<const CGExecKernel &>(CG).MKernelIsCooperative) &&
(!static_cast<const CGExecKernel &>(CG).MKernelUsesClusterLaunch);
}
static void flushCrossQueueDeps(const std::vector<EventImplPtr> &EventImpls,
const QueueImplPtr &Queue) {
for (auto &EventImpl : EventImpls) {
EventImpl->flushIfNeeded(Queue);
}
}
namespace {
struct EnqueueNativeCommandData {
sycl::interop_handle ih;
std::function<void(interop_handle)> func;
};
void InteropFreeFunc(ur_queue_handle_t, void *InteropData) {
auto *Data = reinterpret_cast<EnqueueNativeCommandData *>(InteropData);
return Data->func(Data->ih);
}
} // namespace
class DispatchHostTask {
ExecCGCommand *MThisCmd;
std::vector<interop_handle::ReqToMem> MReqToMem;
std::vector<ur_mem_handle_t> MReqUrMem;
bool waitForEvents() const {
std::map<const AdapterPtr, std::vector<EventImplPtr>>
RequiredEventsPerAdapter;
for (const EventImplPtr &Event : MThisCmd->MPreparedDepsEvents) {
const AdapterPtr &Adapter = Event->getAdapter();
RequiredEventsPerAdapter[Adapter].push_back(Event);
}
// wait for dependency device events
// FIXME Current implementation of waiting for events will make the thread
// 'sleep' until all of dependency events are complete. We need a bit more
// sophisticated waiting mechanism to allow to utilize this thread for any
// other available job and resume once all required events are ready.
for (auto &AdapterWithEvents : RequiredEventsPerAdapter) {
std::vector<ur_event_handle_t> RawEvents =
MThisCmd->getUrEvents(AdapterWithEvents.second);
if (RawEvents.size() == 0)
continue;
try {
AdapterWithEvents.first->call<UrApiKind::urEventWait>(RawEvents.size(),
RawEvents.data());
} catch (const sycl::exception &) {
MThisCmd->MEvent->getSubmittedQueue()->reportAsyncException(
std::current_exception());
return false;
} catch (...) {
MThisCmd->MEvent->getSubmittedQueue()->reportAsyncException(
std::current_exception());
return false;
}
}
// Wait for dependency host events.
// Host events can't throw exceptions so don't try to catch it.
for (const EventImplPtr &Event : MThisCmd->MPreparedHostDepsEvents) {
Event->waitInternal();
}
return true;
}
public:
DispatchHostTask(ExecCGCommand *ThisCmd,
std::vector<interop_handle::ReqToMem> ReqToMem,
std::vector<ur_mem_handle_t> ReqUrMem)
: MThisCmd{ThisCmd}, MReqToMem(std::move(ReqToMem)),
MReqUrMem(std::move(ReqUrMem)) {}
void operator()() const {
assert(MThisCmd->getCG().getType() == CGType::CodeplayHostTask);
CGHostTask &HostTask = static_cast<CGHostTask &>(MThisCmd->getCG());
#ifdef XPTI_ENABLE_INSTRUMENTATION
// Host task is executed async and in a separate thread that do not allow to
// use code location data stored in TLS. So we keep submission code location
// as Command field and put it here to TLS so that thrown exception could
// query and report it.
std::unique_ptr<detail::tls_code_loc_t> AsyncCodeLocationPtr;
if (xptiTraceEnabled() && !CurrentCodeLocationValid()) {
AsyncCodeLocationPtr.reset(
new detail::tls_code_loc_t(MThisCmd->MSubmissionCodeLocation));
}
#endif
if (!waitForEvents()) {
std::exception_ptr EPtr = std::make_exception_ptr(sycl::exception(
make_error_code(errc::runtime),
std::string("Couldn't wait for host-task's dependencies")));
MThisCmd->MEvent->getSubmittedQueue()->reportAsyncException(EPtr);
// reset host-task's lambda and quit
HostTask.MHostTask.reset();
Scheduler::getInstance().NotifyHostTaskCompletion(MThisCmd);
return;
}
try {
// we're ready to call the user-defined lambda now
if (HostTask.MHostTask->isInteropTask()) {
assert(HostTask.MQueue &&
"Host task submissions should have an associated queue");
interop_handle IH{MReqToMem, HostTask.MQueue,
HostTask.MQueue->getDeviceImplPtr(),
HostTask.MQueue->getContextImplPtr()};
// TODO: should all the backends that support this entry point use this
// for host task?
auto &Queue = HostTask.MQueue;
bool NativeCommandSupport = false;
Queue->getAdapter()->call<UrApiKind::urDeviceGetInfo>(
detail::getSyclObjImpl(Queue->get_device())->getHandleRef(),
UR_DEVICE_INFO_ENQUEUE_NATIVE_COMMAND_SUPPORT_EXP,
sizeof(NativeCommandSupport), &NativeCommandSupport, nullptr);
if (NativeCommandSupport) {
EnqueueNativeCommandData CustomOpData{
IH, HostTask.MHostTask->MInteropTask};
// We are assuming that we have already synchronized with the HT's
// dependent events, and that the user will synchronize before the end
// of the HT lambda. As such we don't pass in any events, or ask for
// one back.
//
// This entry point is needed in order to migrate memory across
// devices in the same context for CUDA and HIP backends
Queue->getAdapter()->call<UrApiKind::urEnqueueNativeCommandExp>(
HostTask.MQueue->getHandleRef(), InteropFreeFunc, &CustomOpData,
MReqUrMem.size(), MReqUrMem.data(), nullptr, 0, nullptr, nullptr);
} else {
HostTask.MHostTask->call(MThisCmd->MEvent->getHostProfilingInfo(),
IH);
}
} else
HostTask.MHostTask->call(MThisCmd->MEvent->getHostProfilingInfo());
} catch (...) {
auto CurrentException = std::current_exception();
#ifdef XPTI_ENABLE_INSTRUMENTATION
// sycl::exception emit tracing of message with code location if
// available. For other types of exception we need to explicitly trigger
// tracing by calling TraceEventXPTI.
if (xptiTraceEnabled()) {
try {
rethrow_exception(CurrentException);
} catch (const sycl::exception &) {
// it is already traced, nothing to care about
} catch (const std::exception &StdException) {
GlobalHandler::instance().TraceEventXPTI(StdException.what());
} catch (...) {
GlobalHandler::instance().TraceEventXPTI(
"Host task lambda thrown non standard exception");
}
}
#endif
MThisCmd->MEvent->getSubmittedQueue()->reportAsyncException(
CurrentException);
}
HostTask.MHostTask.reset();
#ifdef XPTI_ENABLE_INSTRUMENTATION
// Host Task is done, clear its submittion location to not interfere with
// following dependent kernels submission.
AsyncCodeLocationPtr.reset();
#endif
try {
// If we enqueue blocked users - ur level could throw exception that
// should be treated as async now.
Scheduler::getInstance().NotifyHostTaskCompletion(MThisCmd);
} catch (...) {
auto CurrentException = std::current_exception();
MThisCmd->MEvent->getSubmittedQueue()->reportAsyncException(
CurrentException);
}
}
};
void Command::waitForPreparedHostEvents() const {
for (const EventImplPtr &HostEvent : MPreparedHostDepsEvents)
HostEvent->waitInternal();
}
void Command::waitForEvents(QueueImplPtr Queue,
std::vector<EventImplPtr> &EventImpls,
ur_event_handle_t &Event) {
#ifndef NDEBUG
for (const EventImplPtr &Event : EventImpls)
assert(!Event->isHost() &&
"Only non-host events are expected to be waited for here");
#endif
if (!EventImpls.empty()) {
if (!Queue) {
// Host queue can wait for events from different contexts, i.e. it may
// contain events with different contexts in its MPreparedDepsEvents.
// OpenCL 2.1 spec says that clWaitForEvents will return
// CL_INVALID_CONTEXT if events specified in the list do not belong to
// the same context. Thus we split all the events into per-context map.
// An example. We have two queues for the same CPU device: Q1, Q2. Thus
// we will have two different contexts for the same CPU device: C1, C2.
// Also we have default host queue. This queue is accessible via
// Scheduler. Now, let's assume we have three different events: E1(C1),
// E2(C1), E3(C2). The command's MPreparedDepsEvents will contain all
// three events (E1, E2, E3). Now, if urEventWait is called for all
// three events we'll experience failure with CL_INVALID_CONTEXT 'cause
// these events refer to different contexts.
std::map<context_impl *, std::vector<EventImplPtr>>
RequiredEventsPerContext;
for (const EventImplPtr &Event : EventImpls) {
ContextImplPtr Context = Event->getContextImpl();
assert(Context.get() &&
"Only non-host events are expected to be waited for here");
RequiredEventsPerContext[Context.get()].push_back(Event);
}
for (auto &CtxWithEvents : RequiredEventsPerContext) {
std::vector<ur_event_handle_t> RawEvents =
getUrEvents(CtxWithEvents.second);
if (!RawEvents.empty()) {
CtxWithEvents.first->getAdapter()->call<UrApiKind::urEventWait>(
RawEvents.size(), RawEvents.data());
}
}
} else {
std::vector<ur_event_handle_t> RawEvents = getUrEvents(EventImpls);
flushCrossQueueDeps(EventImpls, MWorkerQueue);
const AdapterPtr &Adapter = Queue->getAdapter();
if (MEvent != nullptr)
MEvent->setHostEnqueueTime();
Adapter->call<UrApiKind::urEnqueueEventsWait>(
Queue->getHandleRef(), RawEvents.size(), &RawEvents[0], &Event);
}
}
}
/// It is safe to bind MPreparedDepsEvents and MPreparedHostDepsEvents
/// references to event_impl class members because Command
/// should not outlive the event connected to it.
Command::Command(
CommandType Type, QueueImplPtr Queue,
ur_exp_command_buffer_handle_t CommandBuffer,
const std::vector<ur_exp_command_buffer_sync_point_t> &SyncPoints)
: MQueue(std::move(Queue)),
MEvent(std::make_shared<detail::event_impl>(MQueue)),
MPreparedDepsEvents(MEvent->getPreparedDepsEvents()),
MPreparedHostDepsEvents(MEvent->getPreparedHostDepsEvents()), MType(Type),
MCommandBuffer(CommandBuffer), MSyncPointDeps(SyncPoints) {
MWorkerQueue = MQueue;
MEvent->setWorkerQueue(MWorkerQueue);
MEvent->setSubmittedQueue(MWorkerQueue);
MEvent->setCommand(this);
if (MQueue)
MEvent->setContextImpl(MQueue->getContextImplPtr());
MEvent->setStateIncomplete();
MEnqueueStatus = EnqueueResultT::SyclEnqueueReady;
#ifdef XPTI_ENABLE_INSTRUMENTATION
if (!xptiTraceEnabled())
return;
// Obtain the stream ID so all commands can emit traces to that stream
MStreamID = xptiRegisterStream(SYCL_STREAM_NAME);
#endif
}
void Command::emitInstrumentationDataProxy() {
#ifdef XPTI_ENABLE_INSTRUMENTATION
emitInstrumentationData();
#endif
}
/// Method takes in void * for the address as adding a template function to
/// the command group object maybe undesirable.
/// @param Cmd The command object of the source of the edge
/// @param ObjAddr The address that defines the edge dependency; it is the
/// event address when the edge is for an event and a memory object address if
/// it is due to an accessor
/// @param Prefix Contains "event" if the dependency is an edge and contains
/// the access mode to the buffer if it is due to an accessor
/// @param IsCommand True if the dependency has a command object as the
/// source, false otherwise
void Command::emitEdgeEventForCommandDependence(
Command *Cmd, void *ObjAddr, bool IsCommand,
std::optional<access::mode> AccMode) {
#ifdef XPTI_ENABLE_INSTRUMENTATION
// Bail early if either the source or the target node for the given
// dependency is undefined or NULL
constexpr uint16_t NotificationTraceType = xpti::trace_edge_create;
if (!(xptiCheckTraceEnabled(MStreamID, NotificationTraceType) &&
MTraceEvent && Cmd && Cmd->MTraceEvent))
return;
// If all the information we need for creating an edge event is available,
// then go ahead with creating it; if not, bail early!
xpti::utils::StringHelper SH;
std::string AddressStr = SH.addressAsString<void *>(ObjAddr);
std::string Prefix = AccMode ? accessModeToString(AccMode.value()) : "Event";
std::string TypeString = SH.nameWithAddressString(Prefix, AddressStr);
// Create an edge with the dependent buffer address for which a command
// object has been created as one of the properties of the edge
xpti::payload_t Payload(TypeString.c_str(), MAddress);
uint64_t EdgeInstanceNo;
xpti_td *EdgeEvent =
xptiMakeEvent(TypeString.c_str(), &Payload, xpti::trace_graph_event,
xpti_at::active, &EdgeInstanceNo);
if (EdgeEvent) {
xpti_td *SrcEvent = static_cast<xpti_td *>(Cmd->MTraceEvent);
xpti_td *TgtEvent = static_cast<xpti_td *>(MTraceEvent);
EdgeEvent->source_id = SrcEvent->unique_id;
EdgeEvent->target_id = TgtEvent->unique_id;
if (IsCommand) {
xpti::addMetadata(EdgeEvent, "access_mode",
static_cast<int>(AccMode.value()));
xpti::addMetadata(EdgeEvent, "memory_object",
reinterpret_cast<size_t>(ObjAddr));
} else {
xpti::addMetadata(EdgeEvent, "event", reinterpret_cast<size_t>(ObjAddr));
}
xptiNotifySubscribers(MStreamID, NotificationTraceType,
detail::GSYCLGraphEvent, EdgeEvent, EdgeInstanceNo,
nullptr);
}
// General comment - None of these are serious errors as the instrumentation
// layer MUST be tolerant of errors. If we need to let the end user know, we
// throw exceptions in the future
#endif
}
/// Creates an edge when the dependency is due to an event.
/// @param Cmd The command object of the source of the edge
/// @param UrEventAddr The address that defines the edge dependency, which in
/// this case is an event
void Command::emitEdgeEventForEventDependence(Command *Cmd,
ur_event_handle_t &UrEventAddr) {
#ifdef XPTI_ENABLE_INSTRUMENTATION
// If we have failed to create an event to represent the Command, then we
// cannot emit an edge event. Bail early!
if (!(xptiCheckTraceEnabled(MStreamID) && MTraceEvent))
return;
if (Cmd && Cmd->MTraceEvent) {
// If the event is associated with a command, we use this command's trace
// event as the source of edge, hence modeling the control flow
emitEdgeEventForCommandDependence(Cmd, (void *)UrEventAddr, false);
return;
}
if (UrEventAddr) {
xpti::utils::StringHelper SH;
std::string AddressStr = SH.addressAsString<ur_event_handle_t>(UrEventAddr);
// This is the case when it is a OCL event enqueued by the user or another
// event is registered by the runtime as a dependency The dependency on
// this occasion is an OCL event; so we build a virtual node in the graph
// with the event as the metadata for the node
std::string NodeName = SH.nameWithAddressString("virtual_node", AddressStr);
// Node name is "virtual_node[<event_addr>]"
xpti::payload_t VNPayload(NodeName.c_str(), MAddress);
uint64_t VNodeInstanceNo;
xpti_td *NodeEvent =
xptiMakeEvent(NodeName.c_str(), &VNPayload, xpti::trace_graph_event,
xpti_at::active, &VNodeInstanceNo);
// Emit the virtual node first
xpti::addMetadata(NodeEvent, "kernel_name", NodeName);
xptiNotifySubscribers(MStreamID, xpti::trace_node_create,
detail::GSYCLGraphEvent, NodeEvent, VNodeInstanceNo,
nullptr);
// Create a new event for the edge
std::string EdgeName = SH.nameWithAddressString("Event", AddressStr);
xpti::payload_t EdgePayload(EdgeName.c_str(), MAddress);
uint64_t EdgeInstanceNo;
xpti_td *EdgeEvent =
xptiMakeEvent(EdgeName.c_str(), &EdgePayload, xpti::trace_graph_event,
xpti_at::active, &EdgeInstanceNo);
if (EdgeEvent && NodeEvent) {
// Source node represents the event and this event needs to be completed
// before target node can execute
xpti_td *TgtEvent = static_cast<xpti_td *>(MTraceEvent);
EdgeEvent->source_id = NodeEvent->unique_id;
EdgeEvent->target_id = TgtEvent->unique_id;
xpti::addMetadata(EdgeEvent, "event",
reinterpret_cast<size_t>(UrEventAddr));
xptiNotifySubscribers(MStreamID, xpti::trace_edge_create,
detail::GSYCLGraphEvent, EdgeEvent, EdgeInstanceNo,
nullptr);
}
return;
}
#endif
}
uint64_t Command::makeTraceEventProlog(void *MAddress) {
uint64_t CommandInstanceNo = 0;
#ifdef XPTI_ENABLE_INSTRUMENTATION
if (!xptiCheckTraceEnabled(MStreamID))
return CommandInstanceNo;
MTraceEventPrologComplete = true;
// Setup the member variables with information needed for event notification
MCommandNodeType = commandToNodeType(MType);
MCommandName = commandToName(MType);
xpti::utils::StringHelper SH;
MAddressString = SH.addressAsString<void *>(MAddress);
std::string CommandString =
SH.nameWithAddressString(MCommandName, MAddressString);
xpti::payload_t p(CommandString.c_str(), MAddress);
xpti_td *CmdTraceEvent =
xptiMakeEvent(CommandString.c_str(), &p, xpti::trace_graph_event,
xpti_at::active, &CommandInstanceNo);
MInstanceID = CommandInstanceNo;
if (CmdTraceEvent) {
MTraceEvent = (void *)CmdTraceEvent;
// If we are seeing this event again, then the instance ID will be greater
// than 1; in the previous implementation, we would skip sending a
// notifications for subsequent instances. With the new implementation, we
// will send a notification for each instance as this allows for mutable
// metadata entries for multiple visits to the same code location and
// maintaining data integrity.
}
#endif
return CommandInstanceNo;
}
void Command::makeTraceEventEpilog() {
#ifdef XPTI_ENABLE_INSTRUMENTATION
constexpr uint16_t NotificationTraceType = xpti::trace_node_create;
if (!(xptiCheckTraceEnabled(MStreamID, NotificationTraceType) && MTraceEvent))
return;
assert(MTraceEventPrologComplete);
xptiNotifySubscribers(MStreamID, NotificationTraceType,
detail::GSYCLGraphEvent,
static_cast<xpti_td *>(MTraceEvent), MInstanceID,
static_cast<const void *>(MCommandNodeType.c_str()));
#endif
}
Command *Command::processDepEvent(EventImplPtr DepEvent, const DepDesc &Dep,
std::vector<Command *> &ToCleanUp) {
const ContextImplPtr &WorkerContext = getWorkerContext();
// 1. Non-host events can be ignored if they are not fully initialized.
// 2. Some types of commands do not produce UR events after they are
// enqueued (e.g. alloca). Note that we can't check the ur event to make that
// distinction since the command might still be unenqueued at this point.
bool PiEventExpected =
(!DepEvent->isHost() && !DepEvent->isDefaultConstructed());
if (auto *DepCmd = static_cast<Command *>(DepEvent->getCommand()))
PiEventExpected &= DepCmd->producesPiEvent();
if (!PiEventExpected) {
// call to waitInternal() is in waitForPreparedHostEvents() as it's called
// from enqueue process functions
MPreparedHostDepsEvents.push_back(DepEvent);
return nullptr;
}
Command *ConnectionCmd = nullptr;
ContextImplPtr DepEventContext = DepEvent->getContextImpl();
// If contexts don't match we'll connect them using host task
if (DepEventContext != WorkerContext && WorkerContext) {
Scheduler::GraphBuilder &GB = Scheduler::getInstance().MGraphBuilder;
ConnectionCmd = GB.connectDepEvent(this, DepEvent, Dep, ToCleanUp);
} else
MPreparedDepsEvents.push_back(std::move(DepEvent));
return ConnectionCmd;
}
ContextImplPtr Command::getWorkerContext() const {
if (!MQueue)
return nullptr;
return MQueue->getContextImplPtr();
}
bool Command::producesPiEvent() const { return true; }
bool Command::supportsPostEnqueueCleanup() const { return true; }
bool Command::readyForCleanup() const {
return MLeafCounter == 0 &&
MEnqueueStatus == EnqueueResultT::SyclEnqueueSuccess;
}
Command *Command::addDep(DepDesc NewDep, std::vector<Command *> &ToCleanUp) {
Command *ConnectionCmd = nullptr;
if (NewDep.MDepCommand) {
ConnectionCmd =
processDepEvent(NewDep.MDepCommand->getEvent(), NewDep, ToCleanUp);
}
// ConnectionCmd insertion builds the following dependency structure:
// this -> emptyCmd (for ConnectionCmd) -> ConnectionCmd -> NewDep
// that means that this and NewDep are already dependent
if (!ConnectionCmd) {
MDeps.push_back(NewDep);
if (NewDep.MDepCommand)
NewDep.MDepCommand->addUser(this);
}
#ifdef XPTI_ENABLE_INSTRUMENTATION
emitEdgeEventForCommandDependence(NewDep.MDepCommand,
(void *)NewDep.MDepRequirement->MSYCLMemObj,
true, NewDep.MDepRequirement->MAccessMode);
#endif
return ConnectionCmd;
}
Command *Command::addDep(EventImplPtr Event,
std::vector<Command *> &ToCleanUp) {
#ifdef XPTI_ENABLE_INSTRUMENTATION
// We need this for just the instrumentation, so guarding it will prevent
// unused variable warnings when instrumentation is turned off
Command *Cmd = (Command *)Event->getCommand();
ur_event_handle_t UrEventAddr = Event->getHandle();
// Now make an edge for the dependent event
emitEdgeEventForEventDependence(Cmd, UrEventAddr);
#endif
return processDepEvent(std::move(Event), DepDesc{nullptr, nullptr, nullptr},
ToCleanUp);
}
void Command::emitEnqueuedEventSignal(const ur_event_handle_t UrEventAddr) {
#ifdef XPTI_ENABLE_INSTRUMENTATION
emitInstrumentationGeneral(
MStreamID, MInstanceID, static_cast<xpti_td *>(MTraceEvent),
xpti::trace_signal, static_cast<const void *>(UrEventAddr));
#endif
std::ignore = UrEventAddr;
}
void Command::emitInstrumentation(uint16_t Type, const char *Txt) {
#ifdef XPTI_ENABLE_INSTRUMENTATION
return emitInstrumentationGeneral(MStreamID, MInstanceID,
static_cast<xpti_td *>(MTraceEvent), Type,
static_cast<const void *>(Txt));
#else
std::ignore = Type;
std::ignore = Txt;
#endif
}
bool Command::enqueue(EnqueueResultT &EnqueueResult, BlockingT Blocking,
std::vector<Command *> &ToCleanUp) {
#ifdef XPTI_ENABLE_INSTRUMENTATION
// If command is enqueued from host task thread - it will not have valid
// submission code location set. So we set it manually to properly trace
// failures if ur level report any.
std::unique_ptr<detail::tls_code_loc_t> AsyncCodeLocationPtr;
if (xptiTraceEnabled() && !CurrentCodeLocationValid()) {
AsyncCodeLocationPtr.reset(
new detail::tls_code_loc_t(MSubmissionCodeLocation));
}
#endif
// Exit if already enqueued
if (MEnqueueStatus == EnqueueResultT::SyclEnqueueSuccess)
return true;
// If the command is blocked from enqueueing
if (MIsBlockable && MEnqueueStatus == EnqueueResultT::SyclEnqueueBlocked) {
// Exit if enqueue type is not blocking
if (!Blocking) {
EnqueueResult = EnqueueResultT(EnqueueResultT::SyclEnqueueBlocked, this);
return false;
}
#ifdef XPTI_ENABLE_INSTRUMENTATION
// Scoped trace event notifier that emits a barrier begin and barrier end
// event, which models the barrier while enqueuing along with the blocked
// reason, as determined by the scheduler
std::string Info = "enqueue.barrier[";
Info += std::string(getBlockReason()) + "]";
emitInstrumentation(xpti::trace_barrier_begin, Info.c_str());
#endif
// Wait if blocking
while (MEnqueueStatus == EnqueueResultT::SyclEnqueueBlocked)
;
#ifdef XPTI_ENABLE_INSTRUMENTATION
emitInstrumentation(xpti::trace_barrier_end, Info.c_str());
#endif
}
std::lock_guard<std::mutex> Lock(MEnqueueMtx);
// Exit if the command is already enqueued
if (MEnqueueStatus == EnqueueResultT::SyclEnqueueSuccess)
return true;
#ifdef XPTI_ENABLE_INSTRUMENTATION
emitInstrumentation(xpti::trace_task_begin, nullptr);
#endif
if (MEnqueueStatus == EnqueueResultT::SyclEnqueueFailed) {
EnqueueResult = EnqueueResultT(EnqueueResultT::SyclEnqueueFailed, this);
return false;
}
// Command status set to "failed" beforehand, so this command
// has already been marked as "failed" if enqueueImp throws an exception.
// This will avoid execution of the same failed command twice.
MEnqueueStatus = EnqueueResultT::SyclEnqueueFailed;
MShouldCompleteEventIfPossible = true;
ur_result_t Res = enqueueImp();
if (UR_RESULT_SUCCESS != Res)
EnqueueResult =
EnqueueResultT(EnqueueResultT::SyclEnqueueFailed, this, Res);
else {
MEvent->setEnqueued();
if (MShouldCompleteEventIfPossible && !MEvent->isDiscarded() &&
(MEvent->isHost() || MEvent->getHandle() == nullptr))
MEvent->setComplete();
// Consider the command is successfully enqueued if return code is
// UR_RESULT_SUCCESS
MEnqueueStatus = EnqueueResultT::SyclEnqueueSuccess;
if (MLeafCounter == 0 && supportsPostEnqueueCleanup() &&
!SYCLConfig<SYCL_DISABLE_EXECUTION_GRAPH_CLEANUP>::get() &&
!SYCLConfig<SYCL_DISABLE_POST_ENQUEUE_CLEANUP>::get()) {
assert(!MMarkedForCleanup);
MMarkedForCleanup = true;
ToCleanUp.push_back(this);
}
}
// Emit this correlation signal before the task end
emitEnqueuedEventSignal(MEvent->getHandle());
#ifdef XPTI_ENABLE_INSTRUMENTATION
emitInstrumentation(xpti::trace_task_end, nullptr);
#endif
return MEnqueueStatus == EnqueueResultT::SyclEnqueueSuccess;
}
void Command::resolveReleaseDependencies(std::set<Command *> &DepList) {
#ifdef XPTI_ENABLE_INSTRUMENTATION
assert(MType == CommandType::RELEASE && "Expected release command");
if (!MTraceEvent)
return;
// The current command is the target node for all dependencies as the source
// nodes have to be completed first before the current node can begin to
// execute; these edges model control flow
xpti_td *TgtTraceEvent = static_cast<xpti_td *>(MTraceEvent);
// We have all the Commands that must be completed before the release
// command can be enqueued; here we'll find the command that is an Alloca
// with the same SYCLMemObject address and create a dependency line (edge)
// between them in our sematic modeling
for (auto &Item : DepList) {
if (Item->MTraceEvent && Item->MAddress == MAddress) {
xpti::utils::StringHelper SH;
std::string AddressStr = SH.addressAsString<void *>(MAddress);
std::string TypeString =
"Edge:" + SH.nameWithAddressString(commandToName(MType), AddressStr);
// Create an edge with the dependent buffer address being one of the
// properties of the edge
xpti::payload_t p(TypeString.c_str(), MAddress);
uint64_t EdgeInstanceNo;
xpti_td *EdgeEvent =
xptiMakeEvent(TypeString.c_str(), &p, xpti::trace_graph_event,
xpti_at::active, &EdgeInstanceNo);
if (EdgeEvent) {
xpti_td *SrcTraceEvent = static_cast<xpti_td *>(Item->MTraceEvent);
EdgeEvent->target_id = TgtTraceEvent->unique_id;
EdgeEvent->source_id = SrcTraceEvent->unique_id;
xpti::addMetadata(EdgeEvent, "memory_object",
reinterpret_cast<size_t>(MAddress));
xptiNotifySubscribers(MStreamID, xpti::trace_edge_create,
detail::GSYCLGraphEvent, EdgeEvent,
EdgeInstanceNo, nullptr);
}
}
}
#endif
}
const char *Command::getBlockReason() const {
switch (MBlockReason) {
case BlockReason::HostAccessor:
return "A Buffer is locked by the host accessor";
case BlockReason::HostTask: