summaryrefslogtreecommitdiff
path: root/liboffloadmic/runtime/offload_myo_host.cpp
blob: 621494906413c247a677c8b64df2660da128d96d (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
/*
    Copyright (c) 2014-2015 Intel Corporation.  All Rights Reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions
    are met:

      * Redistributions of source code must retain the above copyright
        notice, this list of conditions and the following disclaimer.
      * Redistributions in binary form must reproduce the above copyright
        notice, this list of conditions and the following disclaimer in the
        documentation and/or other materials provided with the distribution.
      * Neither the name of Intel Corporation nor the names of its
        contributors may be used to endorse or promote products derived
        from this software without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
    A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
    HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/


#if defined(LINUX) || defined(FREEBSD)
#include <mm_malloc.h>
#endif

#include "offload_myo_host.h"
#include <errno.h>
#include <malloc.h>
#include "offload_host.h"
//#include "offload_util.h"

#define MYO_VERSION1    "MYO_1.0"

extern "C" void __cilkrts_cilk_for_32(void*, void*, uint32_t, int32_t);
extern "C" void __cilkrts_cilk_for_64(void*, void*, uint64_t, int32_t);

#ifndef TARGET_WINNT
#pragma weak __cilkrts_cilk_for_32
#pragma weak __cilkrts_cilk_for_64
#endif // TARGET_WINNT

static void __offload_myoProcessDeferredTables();

class MyoWrapper {
public:
    MyoWrapper() : m_lib_handle(0), m_is_available(false)
    {}

    bool is_available() const {
        return m_is_available;
    }

    bool LoadLibrary(void);

    // unloads the library
    void UnloadLibrary(void) {
//        if (m_lib_handle != 0) {
//            DL_close(m_lib_handle);
//            m_lib_handle = 0;
//        }
    }

    // Wrappers for MYO client functions
    void LibInit(void *arg, void *func) const {
        OFFLOAD_DEBUG_TRACE_1(4, 0, c_offload_myoinit,
                                 "%s(%p, %p)\n", __func__, arg, func);
        CheckResult(__func__, m_lib_init(arg, func));
    }

    void LibFini(void) const {
        OFFLOAD_DEBUG_TRACE_1(4, 0, c_offload_myofini, "%s()\n", __func__);
        m_lib_fini();
    }

    void* SharedMalloc(size_t size) const {
        OFFLOAD_DEBUG_TRACE_1(4, 0, c_offload_myosharedmalloc,
                                 "%s(%lld)\n", __func__, size);
        return m_shared_malloc(size);
    }

    void SharedFree(void *ptr) const {
        OFFLOAD_DEBUG_TRACE_1(4, 0, c_offload_myosharedfree,
                                 "%s(%p)\n", __func__, ptr);
        m_shared_free(ptr);
    }

    void* SharedAlignedMalloc(size_t size, size_t align) const {
        OFFLOAD_DEBUG_TRACE_1(4, 0, c_offload_myosharedalignedmalloc,
                                 "%s(%lld, %lld)\n", __func__, size, align);
        return m_shared_aligned_malloc(size, align);
    }

    void SharedAlignedFree(void *ptr) const {
        OFFLOAD_DEBUG_TRACE_1(4, 0, c_offload_myosharedalignedfree,
                              "%s(%p)\n", __func__, ptr);
        m_shared_aligned_free(ptr);
    }

    void Acquire(void) const {
        OFFLOAD_DEBUG_TRACE_1(4, 0, c_offload_myoacquire,
                              "%s()\n", __func__);
        CheckResult(__func__, m_acquire());
    }

    void Release(void) const {
        OFFLOAD_DEBUG_TRACE_1(4, 0, c_offload_myorelease,
                            "%s()\n", __func__);
        CheckResult(__func__, m_release());
    }

    void HostVarTablePropagate(void *table, int num_entries) const {
        OFFLOAD_DEBUG_TRACE(4, "%s(%p, %d)\n", __func__, table, num_entries);
        CheckResult(__func__, m_host_var_table_propagate(table, num_entries));
    }

    void HostFptrTableRegister(void *table, int num_entries,
                               int ordered) const {
        OFFLOAD_DEBUG_TRACE_1(4, 0, c_offload_myoregister,
                            "%s(%p, %d, %d)\n", __func__, table,
                            num_entries, ordered);
        CheckResult(__func__,
                    m_host_fptr_table_register(table, num_entries, ordered));
    }

    void RemoteThunkCall(void *thunk, void *args, int device) {
        OFFLOAD_DEBUG_TRACE(4, "%s(%p, %p, %d)\n", __func__, thunk, args,
                            device);
        CheckResult(__func__, m_remote_thunk_call(thunk, args, device));
    }

    MyoiRFuncCallHandle RemoteCall(const char *func, void *args, int device) const {
        OFFLOAD_DEBUG_TRACE(4, "%s(%s, %p, %d)\n", __func__, func, args,
                            device);
        return m_remote_call(func, args, device);
    }

    void GetResult(MyoiRFuncCallHandle handle) const {
        OFFLOAD_DEBUG_TRACE(4, "%s(%p)\n", __func__, handle);
        CheckResult(__func__, m_get_result(handle));
    }

    bool PostInitFuncSupported() const {
        OFFLOAD_DEBUG_TRACE(4, "%s()\n", __func__);
        if (m_feature_available) {
            return m_feature_available(MYO_FEATURE_POST_LIB_INIT) ==
                       MYO_SUCCESS;
        } else {
            return false;
        }
    }

    void CreateVtableArena();

    MyoArena GetVtableArena()const {
        return m_vtable_arena;
    }

    void ArenaCreate(
        MyoOwnershipType ownership,
        int consistency,
        MyoArena* arena
    ) const
    {
        OFFLOAD_DEBUG_TRACE(4, "%s(%d, %d, %p)\n",
            __func__, ownership, consistency, arena);
        CheckResult(__func__, m_arena_create(ownership, consistency, arena));
    }

    void* SharedAlignedArenaMalloc(
        MyoArena arena,
        size_t size,
        size_t align
    ) const
    {
        OFFLOAD_DEBUG_TRACE_1(4, 0, c_offload_myosharedalignedarenamalloc,
                                 "%s(%u, %lld, %lld)\n",
                                 __func__, arena, size, align);
        return m_arena_aligned_malloc(arena, size, align);
    }

    void* SharedAlignedArenaFree(
        MyoArena arena,
        void* ptr
    ) const
    {
        OFFLOAD_DEBUG_TRACE_1(4, 0, c_offload_myosharedalignedarenafree,
                                 "%s(%u, %p)\n", __func__, arena, ptr);
        return m_arena_aligned_free(arena, ptr);
    }

    void ArenaAcquire(
        MyoArena arena
    ) const
    {
        OFFLOAD_DEBUG_TRACE_1(4, 0, c_offload_myoarenaacquire,
                              "%s()\n", __func__);
        CheckResult(__func__, m_arena_acquire(arena));
    }

    void ArenaRelease(
        MyoArena arena
    ) const
    {
        OFFLOAD_DEBUG_TRACE_1(4, 0, c_offload_myoarenarelease,
                            "%s()\n", __func__);
        CheckResult(__func__, m_arena_release(arena));
    }

private:
    void CheckResult(const char *func, MyoError error) const {
        if (error != MYO_SUCCESS) {
             LIBOFFLOAD_ERROR(c_myowrapper_checkresult, func, error);
            exit(1);
        }
    }

private:
    void*    m_lib_handle;
    bool     m_is_available;
    int      m_post_init_func;
    MyoArena m_vtable_arena;

    // pointers to functions from myo library
    MyoError (*m_lib_init)(void*, void*);
    void     (*m_lib_fini)(void);
    void*    (*m_shared_malloc)(size_t);
    void     (*m_shared_free)(void*);
    void*    (*m_shared_aligned_malloc)(size_t, size_t);
    void     (*m_shared_aligned_free)(void*);
    MyoError (*m_acquire)(void);
    MyoError (*m_release)(void);
    MyoError (*m_host_var_table_propagate)(void*, int);
    MyoError (*m_host_fptr_table_register)(void*, int, int);
    MyoError (*m_remote_thunk_call)(void*, void*, int);
    MyoiRFuncCallHandle (*m_remote_call)(const char*, void*, int);
    MyoError (*m_get_result)(MyoiRFuncCallHandle);
    MyoError (*m_arena_create)(MyoOwnershipType, int, MyoArena*);
    void*    (*m_arena_aligned_malloc)(MyoArena, size_t, size_t);
    void*    (*m_arena_aligned_free)(MyoArena, void*);
    MyoError (*m_arena_acquire)(MyoArena);
    MyoError (*m_arena_release)(MyoArena);
    // Placeholder until MYO headers support enum type for feature
    MyoError (*m_feature_available)(int feature);
};

DLL_LOCAL bool MyoWrapper::LoadLibrary(void)
{
#ifndef TARGET_WINNT
    const char *lib_name = "libmyo-client.so";
#else // TARGET_WINNT
    const char *lib_name = "myo-client.dll";
#endif // TARGET_WINNT

    OFFLOAD_DEBUG_TRACE(2, "Loading MYO library %s ...\n", lib_name);

    m_lib_handle = DL_open(lib_name);
    if (m_lib_handle == 0) {
        OFFLOAD_DEBUG_TRACE(2, "Failed to load the library. errno = %d\n",
                            errno);
        return false;
    }

    m_lib_init = (MyoError (*)(void*, void*))
        DL_sym(m_lib_handle, "myoiLibInit", MYO_VERSION1);
    if (m_lib_init == 0) {
        OFFLOAD_DEBUG_TRACE(2, "Failed to find %s in MYO library\n",
                            "myoiLibInit");
        UnloadLibrary();
        return false;
    }

    m_lib_fini = (void (*)(void))
        DL_sym(m_lib_handle, "myoiLibFini", MYO_VERSION1);
    if (m_lib_fini == 0) {
        OFFLOAD_DEBUG_TRACE(2, "Failed to find %s in MYO library\n",
                            "myoiLibFini");
        UnloadLibrary();
        return false;
    }

    m_shared_malloc = (void* (*)(size_t))
        DL_sym(m_lib_handle, "myoSharedMalloc", MYO_VERSION1);
    if (m_shared_malloc == 0) {
        OFFLOAD_DEBUG_TRACE(2, "Failed to find %s in MYO library\n",
                            "myoSharedMalloc");
        UnloadLibrary();
        return false;
    }

    m_shared_free = (void (*)(void*))
        DL_sym(m_lib_handle, "myoSharedFree", MYO_VERSION1);
    if (m_shared_free == 0) {
        OFFLOAD_DEBUG_TRACE(2, "Failed to find %s in MYO library\n",
                            "myoSharedFree");
        UnloadLibrary();
        return false;
    }

    m_shared_aligned_malloc = (void* (*)(size_t, size_t))
        DL_sym(m_lib_handle, "myoSharedAlignedMalloc", MYO_VERSION1);
    if (m_shared_aligned_malloc == 0) {
        OFFLOAD_DEBUG_TRACE(2, "Failed to find %s in MYO library\n",
                            "myoSharedAlignedMalloc");
        UnloadLibrary();
        return false;
    }

    m_shared_aligned_free = (void (*)(void*))
        DL_sym(m_lib_handle, "myoSharedAlignedFree", MYO_VERSION1);
    if (m_shared_aligned_free == 0) {
        OFFLOAD_DEBUG_TRACE(2, "Failed to find %s in MYO library\n",
                            "myoSharedAlignedFree");
        UnloadLibrary();
        return false;
    }

    m_acquire = (MyoError (*)(void))
        DL_sym(m_lib_handle, "myoAcquire", MYO_VERSION1);
    if (m_acquire == 0) {
        OFFLOAD_DEBUG_TRACE(2, "Failed to find %s in MYO library\n",
                            "myoAcquire");
        UnloadLibrary();
        return false;
    }

    m_release = (MyoError (*)(void))
        DL_sym(m_lib_handle, "myoRelease", MYO_VERSION1);
    if (m_release == 0) {
        OFFLOAD_DEBUG_TRACE(2, "Failed to find %s in MYO library\n",
                            "myoRelease");
        UnloadLibrary();
        return false;
    }

    m_host_var_table_propagate = (MyoError (*)(void*, int))
        DL_sym(m_lib_handle, "myoiHostVarTablePropagate", MYO_VERSION1);
    if (m_host_var_table_propagate == 0) {
        OFFLOAD_DEBUG_TRACE(2, "Failed to find %s in MYO library\n",
                            "myoiHostVarTablePropagate");
        UnloadLibrary();
        return false;
    }

    m_host_fptr_table_register = (MyoError (*)(void*, int, int))
        DL_sym(m_lib_handle, "myoiHostFptrTableRegister", MYO_VERSION1);
    if (m_host_fptr_table_register == 0) {
        OFFLOAD_DEBUG_TRACE(2, "Failed to find %s in MYO library\n",
                            "myoiHostFptrTableRegister");
        UnloadLibrary();
        return false;
    }

    m_remote_thunk_call = (MyoError (*)(void*, void*, int))
        DL_sym(m_lib_handle, "myoiRemoteThunkCall", MYO_VERSION1);
    if (m_remote_thunk_call == 0) {
        OFFLOAD_DEBUG_TRACE(2, "Failed to find %s in MYO library\n",
                            "myoiRemoteThunkCall");
        UnloadLibrary();
        return false;
    }

    m_remote_call = (MyoiRFuncCallHandle (*)(const char*, void*, int))
        DL_sym(m_lib_handle, "myoiRemoteCall", MYO_VERSION1);
    if (m_remote_call == 0) {
        OFFLOAD_DEBUG_TRACE(2, "Failed to find %s in MYO library\n",
                            "myoiRemoteCall");
        UnloadLibrary();
        return false;
    }

    m_get_result = (MyoError (*)(MyoiRFuncCallHandle))
        DL_sym(m_lib_handle, "myoiGetResult", MYO_VERSION1);
    if (m_get_result == 0) {
        OFFLOAD_DEBUG_TRACE(2, "Failed to find %s in MYO library\n",
                            "myoiGetResult");
        UnloadLibrary();
        return false;
    }

    m_arena_create = (MyoError (*)(MyoOwnershipType, int, MyoArena*))
        DL_sym(m_lib_handle, "myoArenaCreate", MYO_VERSION1);
    if (m_arena_create == 0) {
        OFFLOAD_DEBUG_TRACE(2, "Failed to find %s in MYO library\n",
                            "myoArenaCreate");
        UnloadLibrary();
        return false;
    }

    m_arena_aligned_malloc = (void* (*)(MyoArena, size_t, size_t))
        DL_sym(m_lib_handle, "myoArenaAlignedMalloc", MYO_VERSION1);
    if (m_arena_aligned_malloc == 0) {
        OFFLOAD_DEBUG_TRACE(2, "Failed to find %s in MYO library\n",
                            "myoArenaAlignedMalloc");
        UnloadLibrary();
        return false;
    }

    m_arena_aligned_free = (void* (*)(MyoArena, void*))
        DL_sym(m_lib_handle, "myoArenaAlignedFree", MYO_VERSION1);
    if (m_arena_aligned_free == 0) {
        OFFLOAD_DEBUG_TRACE(2, "Failed to find %s in MYO library\n",
                            "myoArenaAlignedFree");
        UnloadLibrary();
        return false;
    }

    m_arena_acquire = (MyoError (*)(MyoArena))
        DL_sym(m_lib_handle, "myoArenaAcquire", MYO_VERSION1);
    if (m_acquire == 0) {
        OFFLOAD_DEBUG_TRACE(2, "Failed to find %s in MYO library\n",
                            "myoArenaAcquire");
        UnloadLibrary();
        return false;
    }

    m_arena_release = (MyoError (*)(MyoArena))
        DL_sym(m_lib_handle, "myoArenaRelease", MYO_VERSION1);
    if (m_release == 0) {
        OFFLOAD_DEBUG_TRACE(2, "Failed to find %s in MYO library\n",
                            "myoArenaRelease");
        UnloadLibrary();
        return false;
    }

    // Check for "feature-available" API added in MPSS 3.3.
    // Not finding it is not an error.
    m_feature_available = (MyoError (*)(int))
        DL_sym(m_lib_handle, "myoiSupportsFeature", MYO_VERSION1);
    if (m_feature_available == 0) {
        OFFLOAD_DEBUG_TRACE(2, "Failed to find %s in MYO library\n",
                            "myoiSupportsFeature");
    }    

    OFFLOAD_DEBUG_TRACE(2, "The library was successfully loaded\n");

    // Create arena if supported
    CreateVtableArena();
    OFFLOAD_DEBUG_TRACE(3, "Vtable arena created\n");

    m_is_available = true;

    return true;
}

static bool myo_is_available;
static MyoWrapper myo_wrapper;

void MyoWrapper::CreateVtableArena()
{
    MyoArena* vtable_arena;

    // Check if this MYO supports arenas for vtables
    if (myo_wrapper.PostInitFuncSupported()) {
        // Create arena for vtables
	    vtable_arena = (MyoArena *)myo_wrapper.SharedMalloc(sizeof(MyoArena));
        myo_wrapper.ArenaCreate(
            MYO_ARENA_OURS, MYO_NO_CONSISTENCY, vtable_arena);
        m_vtable_arena = *vtable_arena;
        OFFLOAD_DEBUG_TRACE(4, "created arena = %d\n", m_vtable_arena);
    } else {
        m_vtable_arena = 0;
    }
}

struct MyoTable
{
    MyoTable(SharedTableEntry *tab, int len) : var_tab(tab), var_tab_len(len)
    {}

    SharedTableEntry*   var_tab;
    int                 var_tab_len;
};

typedef std::list<MyoTable> MyoTableList;
static MyoTableList __myo_table_list;
static mutex_t      __myo_table_lock;
static bool         __myo_tables = false;

static void __offload_myo_shared_vtable_process(SharedTableEntry *entry);
static void __offload_myo_shared_table_process(SharedTableEntry *entry);
static void __offload_myo_shared_init_table_process(InitTableEntry* entry);
static void __offload_myo_fptr_table_process(FptrTableEntry *entry);
static void __offload_propagate_shared_vars();

static void __offload_myoLoadLibrary_once(void)
{
    if (__offload_init_library()) {
        myo_wrapper.LoadLibrary();
    }
}

static bool __offload_myoLoadLibrary(void)
{
    OFFLOAD_DEBUG_TRACE(4, "__offload_myoLoadLibrary\n");
    static OffloadOnceControl ctrl = OFFLOAD_ONCE_CONTROL_INIT;
    __offload_run_once(&ctrl, __offload_myoLoadLibrary_once);

    return myo_wrapper.is_available();
}

static void __offload_myoInit_once(void)
{
    if (!__offload_myoLoadLibrary()) {
        return;
    }

    // initialize all devices
    for (int i = 0; i < mic_engines_total; i++) {
        mic_engines[i].init();
    }

    // load and initialize MYO library
    OFFLOAD_DEBUG_TRACE(2, "Initializing MYO library ...\n");

    COIEVENT events[MIC_ENGINES_MAX];

    // One entry per device + 
    // A pair of entries for the Host postInit func +
    // A pair of entries for the MIC postInit func +
    // end marker
    MyoiUserParams params[MIC_ENGINES_MAX+5];

    // Load target library to all devices and
    // create libinit parameters for all devices
    for (int i = 0; i < mic_engines_total; i++) {
        mic_engines[i].init_myo(&events[i]);

        params[i].type = MYOI_USERPARAMS_DEVID;
        params[i].nodeid = mic_engines[i].get_physical_index() + 1;
        OFFLOAD_DEBUG_TRACE(2, "params[%d] = { %d, %d }\n",
            i, params[i].type, params[i].nodeid);
    }

    // Check if V2 myoLibInit is available
    if (myo_wrapper.PostInitFuncSupported()) {
        // Set the host post libInit function indicator
        params[mic_engines_total].type =
            MYOI_USERPARAMS_POST_MYO_LIB_INIT_FUNC;
        params[mic_engines_total].nodeid =
            MYOI_USERPARAMS_POST_MYO_LIB_INIT_FUNC_HOST_NODE;
        OFFLOAD_DEBUG_TRACE(2, "params[%d] = { %d, %d }\n",
            mic_engines_total,
            params[mic_engines_total].type, params[mic_engines_total].nodeid);
    
        // Set the host post libInit host function address
        ((MyoiUserParamsPostLibInit*)(&params[mic_engines_total+1]))->
            postLibInitHostFuncAddress =
                (void (*)())&__offload_propagate_shared_vars;
        OFFLOAD_DEBUG_TRACE(2, "params[%d] = { %p }\n",
            mic_engines_total+1,
            ((MyoiUserParamsPostLibInit*)(&params[mic_engines_total+1]))->
                postLibInitHostFuncAddress);
    
        // Set the target post libInit function indicator
        params[mic_engines_total+2].type =
            MYOI_USERPARAMS_POST_MYO_LIB_INIT_FUNC;
        params[mic_engines_total+2].nodeid =
            MYOI_USERPARAMS_POST_MYO_LIB_INIT_FUNC_ALL_NODES;
    
        // Set the target post libInit target function name
        ((MyoiUserParamsPostLibInit*)(&params[mic_engines_total+3]))->
            postLibInitRemoveFuncName = "--vtable_initializer--";
        OFFLOAD_DEBUG_TRACE(2, "params[%d] = { %s }\n",
            mic_engines_total+3,
            ((MyoiUserParamsPostLibInit*)(&params[mic_engines_total+1]))->
                postLibInitRemoveFuncName);
    
        params[mic_engines_total+4].type = MYOI_USERPARAMS_LAST_MSG;
        params[mic_engines_total+4].nodeid = 0;
        OFFLOAD_DEBUG_TRACE(2, "params[%d] = { %d, %d }\n",
            mic_engines_total+4,
            params[mic_engines_total+4].type,
            params[mic_engines_total+4].nodeid);
    } else {
        params[mic_engines_total].type = MYOI_USERPARAMS_LAST_MSG;
        params[mic_engines_total].nodeid = 0;
        OFFLOAD_DEBUG_TRACE(2, "params[%d] = { %d, %d }\n",
            mic_engines_total,
            params[mic_engines_total].type, params[mic_engines_total].nodeid);
    }

    // initialize myo runtime on host
    myo_wrapper.LibInit(params, 0);

    // wait for the target init calls to finish
    COIRESULT res;
    res = COI::EventWait(mic_engines_total, events, -1, 1, 0, 0);
    if (res != COI_SUCCESS) {
        LIBOFFLOAD_ERROR(c_event_wait, res);
        exit(1);
    }

    myo_is_available = true;
    OFFLOAD_DEBUG_TRACE(2, "setting myo_is_available=%d\n", myo_is_available);

    OFFLOAD_DEBUG_TRACE(2, "Initializing MYO library ... done\n");
}

static bool __offload_myoInit(void)
{
    static OffloadOnceControl ctrl = OFFLOAD_ONCE_CONTROL_INIT;
    __offload_run_once(&ctrl, __offload_myoInit_once);

    // Check if using V1 myoLibInit
    if (!myo_wrapper.PostInitFuncSupported()) {
        __offload_propagate_shared_vars();
    }

    return myo_is_available;
}

static void __offload_propagate_shared_vars()
{
    // Propagate pending shared var tables
    if (__myo_tables) {
        mutex_locker_t locker(__myo_table_lock);

        if (__myo_tables) {
            //  Give tables with MYO so it can propagate to target
            for(MyoTableList::const_iterator it = __myo_table_list.begin();
                it != __myo_table_list.end(); ++it) {
#ifdef TARGET_WINNT
                for (SharedTableEntry *entry = it->var_tab;
                     entry->varName != MYO_TABLE_END_MARKER(); entry++) {
                    if (entry->varName == 0) {
                        continue;
                    }
                    myo_wrapper.HostVarTablePropagate(entry, 1);
                    OFFLOAD_DEBUG_TRACE(2, "HostVarTablePropagate(%s, 1)\n",
                        entry->varName);
                }
#else // TARGET_WINNT
                myo_wrapper.HostVarTablePropagate(it->var_tab,
                                                  it->var_tab_len);
#endif // TARGET_WINNT
            }

            __myo_table_list.clear();
            __myo_tables = false;
        }
    }
}

static bool shared_table_entries(
    SharedTableEntry *entry
)
{
    OFFLOAD_DEBUG_TRACE(3, "%s(%p)\n", __func__, entry);

    for (; entry->varName != MYO_TABLE_END_MARKER(); entry++) {
#ifdef TARGET_WINNT
        if (entry->varName == 0) {
            continue;
        }
#endif // TARGET_WINNT

        return true;
    }

    return false;
}

static bool fptr_table_entries(
    FptrTableEntry *entry
)
{
    OFFLOAD_DEBUG_TRACE(3, "%s(%p)\n", __func__, entry);

    for (; entry->funcName != MYO_TABLE_END_MARKER(); entry++) {
#ifdef TARGET_WINNT
        if (entry->funcName == 0) {
            continue;
        }
#endif // TARGET_WINNT

        return true;
    }

    return false;
}

extern "C" void __offload_myoRegisterTables(
    InitTableEntry* init_table,
    SharedTableEntry *shared_table,
    FptrTableEntry *fptr_table
)
{
    // check whether we need to initialize MYO library. It is
    // initialized only if at least one myo table is not empty
    if (shared_table_entries(shared_table) || fptr_table_entries(fptr_table)) {
        // make sure myo library is loaded
        __offload_myoLoadLibrary();

        // register tables
        __offload_myo_shared_table_process(shared_table);
        __offload_myo_fptr_table_process(fptr_table);
        __offload_myo_shared_init_table_process(init_table);
    }
}

extern "C" bool __offload_myoProcessTables(
    const void* image,
    MYOInitTableList::Node *init_table,
    MYOVarTableList::Node  *shared_table,
    MYOVarTableList::Node  *shared_vtable,
    MYOFuncTableList::Node *fptr_table
)
{
    OFFLOAD_DEBUG_TRACE(3, "%s\n", __func__);

    // Collect the tables in this .dll/.so
    __offload_myoRegisterTables1(
        init_table, shared_table, shared_vtable, fptr_table);

    // Now check what type of module we are dealing with
    if (__offload_target_image_is_executable(image)) {
        OFFLOAD_DEBUG_TRACE(2, "Main encountered\n");
        OFFLOAD_DEBUG_TRACE(2, "MYO initialization not deferred\n");
        // MYO tables across dlls have been collected
        // Now init MYO and process the tables
        __offload_myoProcessDeferredTables();
        // Return true to indicate that atexit needs to be calld by ofldbegin
        return true;
    } else {
        // This is a shared library, either auto-loaded or dynamically loaded
        // If __target_exe is set, then main has started running
        if (__target_exe != 0) {
            // Main is running: this is a dynamic load of a shared library
            // Finish processing the tables in this library
            OFFLOAD_DEBUG_TRACE(2,
                "Dynamically loaded shared library encountered\n");
            OFFLOAD_DEBUG_TRACE(2,
                "MYO initialization not deferred\n");
            __offload_myoProcessDeferredTables();
        } else {
            // Main is not running: this is an auto-loaded shared library
            // Tables have been collected, nothing else to do
            OFFLOAD_DEBUG_TRACE(2,
                "Auto-loaded shared library encountered\n");
            OFFLOAD_DEBUG_TRACE(2, "Deferring initialization of MYO\n");
        }
        return false;
    }
}

// Process contents of all Var tables
void MYOVarTableList::process()
{
    OFFLOAD_DEBUG_TRACE(2, "Process MYO Var tables:\n");

    m_lock.lock();

    for (Node *n = m_head; n != 0; n = n->next) {
        __offload_myo_shared_table_process(
            (SharedTableEntry*)n->table.entries);
    }
    for (Node *n = m_head; n != 0; n = n->next) {
        remove_table(n);
    }

    m_lock.unlock();
}

// Process contents of all Var tables
void MYOVarTableList::process_vtable()
{
    OFFLOAD_DEBUG_TRACE(2, "Process MYO Vtable tables:\n");

    m_lock.lock();

    for (Node *n = m_head; n != 0; n = n->next) {
        __offload_myo_shared_vtable_process(
            (SharedTableEntry*)n->table.entries);
    }
    for (Node *n = m_head; n != 0; n = n->next) {
        remove_table(n);
    }

    m_lock.unlock();
}

// Process contents of all Func tables
void MYOFuncTableList::process()
{
    OFFLOAD_DEBUG_TRACE(2, "Process MYO Func tables:\n");

    m_lock.lock();

    for (Node *n = m_head; n != 0; n = n->next) {
        __offload_myo_fptr_table_process(
            (FptrTableEntry*)n->table.entries);
    }
    for (Node *n = m_head; n != 0; n = n->next) {
        remove_table(n);
    }

    m_lock.unlock();
}

// Process contents of all Init tables
void MYOInitTableList::process()
{
    OFFLOAD_DEBUG_TRACE(2, "Process MYO Init tables:\n");

    m_lock.lock();

    for (Node *n = m_head; n != 0; n = n->next) {
        __offload_myo_shared_init_table_process(
            (InitTableEntry*)n->table.entries);
    }
    for (Node *n = m_head; n != 0; n = n->next) {
        remove_table(n);
    }

    m_lock.unlock();
}

static void __offload_myoProcessDeferredTables()
{
    OFFLOAD_DEBUG_TRACE(3, "%s()\n", __func__);

    // Debug dumps of MYO tables
    if (console_enabled >= 2) {
        __offload_myo_var_tables.dump();
        __offload_myo_vtable_tables.dump();
        __offload_myo_func_tables.dump();
        __offload_myo_init_tables.dump();
    }

    if (!__offload_myo_var_tables.is_empty() ||
        !__offload_myo_vtable_tables.is_empty() ||
        !__offload_myo_func_tables.is_empty() ||
        !__offload_myo_init_tables.is_empty())
    {
        OFFLOAD_DEBUG_TRACE(3, "MYO usage detected in program\n");

        // Make sure myo library is loaded
        __offload_myoLoadLibrary();
        OFFLOAD_DEBUG_TRACE(3, "Initialized MYO\n");

        __offload_myo_var_tables.process();
        __offload_myo_vtable_tables.process_vtable();
        __offload_myo_func_tables.process();
        __offload_myo_init_tables.process();
        OFFLOAD_DEBUG_TRACE(3, "Finished processing MYO tables\n");
    } else {
        OFFLOAD_DEBUG_TRACE(3,
            "MYO tables are empty; Will not initialize MYO\n");
    }
}

DLL_LOCAL void __offload_myoFini(void)
{
    if (myo_is_available) {
        OFFLOAD_DEBUG_TRACE(3, "%s\n", __func__);

        COIEVENT events[MIC_ENGINES_MAX];

        // kick off myoiLibFini calls on all devices
        for (int i = 0; i < mic_engines_total; i++) {
            mic_engines[i].fini_myo(&events[i]);
        }

        // cleanup myo runtime on host
        myo_wrapper.LibFini();

        // wait for the target fini calls to finish
        COIRESULT res;
        res = COI::EventWait(mic_engines_total, events, -1, 1, 0, 0);
        if (res != COI_SUCCESS) {
            LIBOFFLOAD_ERROR(c_event_wait, res);
            exit(1);
        }
    }
}

static void __offload_myo_shared_table_process(
    SharedTableEntry *entry
)
{
    OFFLOAD_DEBUG_TRACE(3, "%s(%p)\n", __func__, entry);

    SharedTableEntry *start = entry;
    int entries = 0;

    // allocate shared memory for vars
    for (; entry->varName != MYO_TABLE_END_MARKER(); entry++) {
#ifdef TARGET_WINNT
        if (entry->varName == 0) {
            OFFLOAD_DEBUG_TRACE(4,
                "skip registering a NULL MyoSharedTable entry\n");
            continue;
        }
#endif // TARGET_WINNT

        OFFLOAD_DEBUG_TRACE(4, "registering MyoSharedTable entry for %s @%p\n",
                            entry->varName, entry);

        // Invoke the function to create shared memory
        reinterpret_cast<void(*)(void)>(entry->sharedAddr)();
        entries++;
    }

    // and table to the list if it is not empty
    if (entries > 0) {
        mutex_locker_t locker(__myo_table_lock);
        __myo_table_list.push_back(MyoTable(start, entries));
        __myo_tables = true;
    }
}

static void __offload_myo_shared_vtable_process(
    SharedTableEntry *entry
)
{
    SharedTableEntry *start = entry;
    int entries = 0;

    OFFLOAD_DEBUG_TRACE(3, "%s(%p)\n", __func__, entry);

    // allocate shared memory for vtables
    for (; entry->varName != MYO_TABLE_END_MARKER(); entry++) {
#ifdef TARGET_WINNT
        if (entry->varName == 0) {
            OFFLOAD_DEBUG_TRACE(4,
                "skip registering a NULL MyoSharedVTable entry\n");
            continue;
        }
#endif // TARGET_WINNT

        OFFLOAD_DEBUG_TRACE(4,
            "registering MyoSharedVTable entry for %s @%p\n",
                            entry->varName, entry);

        // Invoke the function to create shared memory
        reinterpret_cast<void(*)(MyoArena)>(entry->sharedAddr)(
                                                myo_wrapper.GetVtableArena());
        entries++;
    }

    // add table to the list if it is not empty
    if (entries > 0) {
        mutex_locker_t locker(__myo_table_lock);
        __myo_table_list.push_back(MyoTable(start, entries));
        __myo_tables = true;
    }
}

void __offload_myo_shared_init_table_process(InitTableEntry* entry)
{
    OFFLOAD_DEBUG_TRACE(3, "%s(%p)\n", __func__, entry);

#ifdef TARGET_WINNT
    for (; entry->funcName != MYO_TABLE_END_MARKER(); entry++) {
        if (entry->funcName == 0) {
            OFFLOAD_DEBUG_TRACE(4,
                "skip registering a NULL MyoSharedInit entry\n");
            continue;
        }

        //  Invoke the function to init the shared memory
        OFFLOAD_DEBUG_TRACE(4, "execute MyoSharedInit routine for %s\n",
            entry->funcName);
        entry->func(myo_wrapper.GetVtableArena());
    }
#else // TARGET_WINNT
    for (; entry->func != 0; entry++) {
        // Invoke the function to init the shared memory
        entry->func(myo_wrapper.GetVtableArena());
    }
#endif // TARGET_WINNT
}

static void __offload_myo_fptr_table_process(
    FptrTableEntry *entry
)
{
    OFFLOAD_DEBUG_TRACE(3, "%s(%p)\n", __func__, entry);

    FptrTableEntry *start = entry;
    int entries = 0;

    for (; entry->funcName != MYO_TABLE_END_MARKER(); entry++) {
#ifdef TARGET_WINNT
        if (entry->funcName == 0) {
            OFFLOAD_DEBUG_TRACE(4,
                "skip registering a NULL MyoFptrTable entry\n");
            continue;
        }
#endif // TARGET_WINNT

        if (!myo_wrapper.is_available()) {
            *(static_cast<void**>(entry->localThunkAddr)) = entry->funcAddr;
        }

        OFFLOAD_DEBUG_TRACE(4, "registering MyoFptrTable entry for %s @%p\n",
                            entry->funcName, entry);

#ifdef TARGET_WINNT
        if (myo_wrapper.is_available()) {
            myo_wrapper.HostFptrTableRegister(entry, 1, false);
        }
#endif // TARGET_WINNT

        entries++;
    }

#ifndef TARGET_WINNT
    if (myo_wrapper.is_available() && entries > 0) {
        myo_wrapper.HostFptrTableRegister(start, entries, false);
    }
#endif // TARGET_WINNT
}

extern "C" int __offload_myoIsAvailable(int target_number)
{
    OFFLOAD_DEBUG_TRACE(3, "%s(%d)\n", __func__, target_number);

    if (target_number >= -2) {
        bool is_default_number = (target_number == -2);

        if (__offload_myoInit()) {
            if (target_number >= 0) {
                // User provided the device number
                int num = target_number % mic_engines_total;

                // reserve device in ORSL
                target_number = ORSL::reserve(num) ? num : -1;
            }
            else {
                // try to use device 0
                target_number = ORSL::reserve(0) ? 0 : -1;
            }

            // make sure device is initialized
            if (target_number >= 0) {
                mic_engines[target_number].init();
            }
        }
        else {
            // fallback to CPU
            target_number = -1;
        }

        if (target_number < 0 && !is_default_number) {
            LIBOFFLOAD_ERROR(c_device_is_not_available);
            exit(1);
        }
    }
    else {
        LIBOFFLOAD_ERROR(c_invalid_device_number);
        exit(1);
    }

    return target_number;
}

extern "C" void __offload_myoiRemoteIThunkCall(
    void *thunk,
    void *arg,
    int target_number
)
{
    OFFLOAD_DEBUG_TRACE(3, "%s(%p, %p, %d)\n", __func__, thunk, arg,
                        target_number);

    myo_wrapper.Release();
    myo_wrapper.RemoteThunkCall(thunk, arg, target_number);
    myo_wrapper.Acquire();

    ORSL::release(target_number);
}

extern "C" void* _Offload_shared_malloc(size_t size)
{
    OFFLOAD_DEBUG_TRACE(3, "%s(%lld)\n", __func__, size);

    if (__offload_myoLoadLibrary()) {
        return myo_wrapper.SharedMalloc(size);
    }
    else {
        return malloc(size);
    }
}

extern "C" void _Offload_shared_free(void *ptr)
{
    OFFLOAD_DEBUG_TRACE(3, "%s(%p)\n", __func__, ptr);

    if (__offload_myoLoadLibrary()) {
        myo_wrapper.SharedFree(ptr);
    }
    else {
        free(ptr);
    }
}

extern "C" void* _Offload_shared_aligned_malloc(size_t size, size_t align)
{
    OFFLOAD_DEBUG_TRACE(3, "%s(%lld, %lld)\n", __func__, size, align);

    if (__offload_myoLoadLibrary()) {
        return myo_wrapper.SharedAlignedMalloc(size, align);
    }
    else {
        if (align < sizeof(void*)) {
            align = sizeof(void*);
        }
        return _mm_malloc(size, align);
    }
}

extern "C" void _Offload_shared_aligned_free(void *ptr)
{
    OFFLOAD_DEBUG_TRACE(3, "%s(%p)\n", __func__, ptr);

    if (__offload_myoLoadLibrary()) {
        myo_wrapper.SharedAlignedFree(ptr);
    }
    else {
        _mm_free(ptr);
    }
}

extern "C" void _Offload_shared_arena_create(
    MyoOwnershipType ownership,
    int consistency,
    MyoArena* arena
)
{
    OFFLOAD_DEBUG_TRACE(3, "%s(%d, %d, %p)\n",
        __func__, ownership, consistency, arena);

    if (__offload_myoLoadLibrary()) {
        myo_wrapper.ArenaCreate(ownership, consistency, arena);
    }
}

extern "C" void* _Offload_shared_aligned_arena_malloc(
    MyoArena arena,
    size_t size,
    size_t align
)
{
    OFFLOAD_DEBUG_TRACE(3, "%s(%u, %lld, %lld)\n",
        __func__, arena, size, align);

    if (__offload_myoLoadLibrary()) {
        void *p = myo_wrapper.SharedAlignedArenaMalloc(arena, size, align);
        OFFLOAD_DEBUG_TRACE(3, "%s(%u, %lld, %lld)->%p\n",
            __func__, arena, size, align, p);
        return p;
    }
    else {
        if (align < sizeof(void*)) {
            align = sizeof(void*);
        }
        return _mm_malloc(size, align);
    }
}

extern "C" void _Offload_shared_aligned_arena_free(
    MyoArena arena,
    void *ptr
)
{
    OFFLOAD_DEBUG_TRACE(3, "%s(%u, %p)\n", __func__, arena, ptr);

    if (__offload_myoLoadLibrary()) {
        myo_wrapper.SharedAlignedArenaFree(arena, ptr);
    }
    else {
        _mm_free(ptr);
    }
}

extern "C" void _Offload_shared_arena_acquire(
    MyoArena arena
)
{
    OFFLOAD_DEBUG_TRACE(3, "%s(%u)\n", __func__, arena);

    if (__offload_myoLoadLibrary()) {
        myo_wrapper.ArenaAcquire(arena);
    }
}

extern "C" void _Offload_shared_arena_release(
    MyoArena arena
)
{
    OFFLOAD_DEBUG_TRACE(3, "%s(%u)\n", __func__, arena);

    if (__offload_myoLoadLibrary()) {
        myo_wrapper.ArenaRelease(arena);
    }
}

extern "C" void __intel_cilk_for_32_offload(
    int size,
    void (*copy_constructor)(void*, void*),
    int target_number,
    void *raddr,
    void *closure_object,
    unsigned int iters,
    unsigned int grain_size)
{
    OFFLOAD_DEBUG_TRACE(3, "%s\n", __func__);

    target_number = __offload_myoIsAvailable(target_number);
    if (target_number >= 0) {
        struct S {
            void *M1;
            unsigned int M2;
            unsigned int M3;
            char closure[];
        } *args;

        args = (struct S*) _Offload_shared_malloc(sizeof(struct S) + size);
        if (args == NULL)
          LIBOFFLOAD_ERROR(c_malloc);
        args->M1 = raddr;
        args->M2 = iters;
        args->M3 = grain_size;

        if (copy_constructor == 0) {
            memcpy(args->closure, closure_object, size);
        }
        else {
            copy_constructor(args->closure, closure_object);
        }

        myo_wrapper.Release();
        myo_wrapper.GetResult(
            myo_wrapper.RemoteCall("__intel_cilk_for_32_offload",
                                   args, target_number)
        );
        myo_wrapper.Acquire();

        _Offload_shared_free(args);

        ORSL::release(target_number);
    }
    else {
        __cilkrts_cilk_for_32(raddr,
                              closure_object,
                              iters,
                              grain_size);
    }
}

extern "C" void __intel_cilk_for_64_offload(
    int size,
    void (*copy_constructor)(void*, void*),
    int target_number,
    void *raddr,
    void *closure_object,
    uint64_t iters,
    uint64_t grain_size)
{
    OFFLOAD_DEBUG_TRACE(3, "%s\n", __func__);

    target_number = __offload_myoIsAvailable(target_number);
    if (target_number >= 0) {
        struct S {
            void *M1;
            uint64_t M2;
            uint64_t M3;
            char closure[];
        } *args;

        args = (struct S*) _Offload_shared_malloc(sizeof(struct S) + size);
        if (args == NULL)
          LIBOFFLOAD_ERROR(c_malloc);
        args->M1 = raddr;
        args->M2 = iters;
        args->M3 = grain_size;

        if (copy_constructor == 0) {
            memcpy(args->closure, closure_object, size);
        }
        else {
            copy_constructor(args->closure, closure_object);
        }

        myo_wrapper.Release();
        myo_wrapper.GetResult(
            myo_wrapper.RemoteCall("__intel_cilk_for_64_offload", args,
                                   target_number)
        );
        myo_wrapper.Acquire();

        _Offload_shared_free(args);

        ORSL::release(target_number);
    }
    else {
        __cilkrts_cilk_for_64(raddr,
                              closure_object,
                              iters,
                              grain_size);
    }
}