summaryrefslogtreecommitdiff
path: root/liboffloadmic/runtime/offload_host.cpp
blob: e52019dfb28e7733cba65fc506d160ccb27e4fba (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
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
/*
    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.
*/


// Forward declaration as the following 2 functions are declared as friend
// in offload_engine.h.
// CLANG does not like static to been after friend declaration.
static void __offload_init_library_once(void);
static void __offload_fini_library(void);

#include "offload_host.h"
#ifdef MYO_SUPPORT
#include "offload_myo_host.h"
#endif

#include <malloc.h>
#ifndef TARGET_WINNT
#include <alloca.h>
#include <elf.h>
#endif // TARGET_WINNT
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/stat.h>

#include <algorithm>
#include <bitset>

#if defined(HOST_WINNT)
#define PATH_SEPARATOR ";"
#else
#define PATH_SEPARATOR ":"
#endif

#define GET_OFFLOAD_NUMBER(timer_data) \
    timer_data? timer_data->offload_number : 0

static void (*task_completion_callback)(void *);

extern "C" {
#ifdef TARGET_WINNT
// Windows does not support imports from libraries without actually
// including them as dependence.  We don't want to include in the
// dependence since is it used only for Fortran when traceback is enabled.
// Chose to implement it with GetProcAddress.
#define FORTRAN_TRACE_BACK  win_for__continue_traceback
int win_for__continue_traceback( _Offload_result coi_offload_result )
{
    HINSTANCE hDLL;
    int (* TraceBackRoutine)(_Offload_result value);

    hDLL = LoadLibrary("libifcoremd.dll");
    if (hDLL != 0) {
        TraceBackRoutine = (int (*)(_Offload_result)) GetProcAddress(hDLL,
                                                 "for__continue_traceback");
        if (TraceBackRoutine != 0) {
            return TraceBackRoutine(coi_offload_result);
        }
        else {
            OFFLOAD_TRACE(3,
            "Cannot find for__continue_traceback routine in libifcorert.dll\n");
            exit(1);
        }
    }
    else {
        OFFLOAD_TRACE(3, "Cannot load libifcorert.dll\n");
        exit(1);
    }
    return 0;
}

#else // TARGET_WINNT

#define FORTRAN_TRACE_BACK for__continue_traceback

// for__continue_traceback is provided as a dummy to resolve link time symbols
// for C/C++ programs.  For Fortran the actual fortran library function in
// libifcore.so is used.
#pragma weak for__continue_traceback
int for__continue_traceback( _Offload_result coi_offload_result )
{
     OFFLOAD_TRACE(3,
          "liboffload function for_continue_traceback should not be called.\n");
     exit(1);
}
#endif //TARGET_WINNT
}  // extern "C"

#ifdef TARGET_WINNT
// Small subset of ELF declarations for Windows which is needed to compile
// this file. ELF header is used to understand what binary type is contained
// in the target image - shared library or executable.

typedef uint16_t Elf64_Half;
typedef uint32_t Elf64_Word;
typedef uint64_t Elf64_Addr;
typedef uint64_t Elf64_Off;

#define EI_NIDENT   16

#define ET_EXEC     2
#define ET_DYN      3

typedef struct
{
    unsigned char e_ident[EI_NIDENT];
    Elf64_Half    e_type;
    Elf64_Half    e_machine;
    Elf64_Word    e_version;
    Elf64_Addr    e_entry;
    Elf64_Off     e_phoff;
    Elf64_Off     e_shoff;
    Elf64_Word    e_flags;
    Elf64_Half    e_ehsize;
    Elf64_Half    e_phentsize;
    Elf64_Half    e_phnum;
    Elf64_Half    e_shentsize;
    Elf64_Half    e_shnum;
    Elf64_Half    e_shstrndx;
} Elf64_Ehdr;
#endif // TARGET_WINNT

// Host console and file logging
const char *prefix;
int console_enabled = 0;
int offload_number = 0;

static const char *htrace_envname = "H_TRACE";
static const char *offload_report_envname = "OFFLOAD_REPORT";
static const char *timer_envname = "H_TIME";

// location of offload_main executable
// To be used if the main application has no offload and is not built
// with -offload but dynamic library linked in has offload pragma
char*        mic_device_main = 0;

// DMA channel count used by COI and set via
// OFFLOAD_DMA_CHANNEL_COUNT environment variable
uint32_t mic_dma_channel_count;

// Trace information
static const char* vardesc_direction_as_string[] = {
    "NOCOPY",
    "IN",
    "OUT",
    "INOUT"
};
static const char* vardesc_type_as_string[] = {
    "unknown",
    "data",
    "data_ptr",
    "func_ptr",
    "void_ptr",
    "string_ptr",
    "dv",
    "dv_data",
    "dv_data_slice",
    "dv_ptr",
    "dv_ptr_data",
    "dv_ptr_data_slice",
    "cean_var",
    "cean_var_ptr",
    "c_data_ptr_array",
    "c_func_ptr_array",
    "c_void_ptr_array",
    "c_string_ptr_array"
};

Engine*         mic_engines = 0;
uint32_t        mic_engines_total = 0;
pthread_key_t   mic_thread_key;
MicEnvVar       mic_env_vars;
uint64_t        cpu_frequency = 0;

// MIC_STACKSIZE
uint32_t mic_stack_size = 12 * 1024 * 1024;

// MIC_BUFFERSIZE
uint64_t mic_buffer_size = 0;

// Preallocated 4K page memory size for buffers on MIC
uint64_t mic_4k_buffer_size = 0;

// Preallocated 2M page memory size for buffers on MIC
uint64_t mic_2m_buffer_size = 0;


// MIC_LD_LIBRARY_PATH
char* mic_library_path = 0;

// MIC_PROXY_IO
bool mic_proxy_io = true;

// MIC_PROXY_FS_ROOT
char* mic_proxy_fs_root = 0;

// Threshold for creating buffers with large pages. Buffer is created
// with large pages hint if its size exceeds the threshold value.
// By default large pages are disabled right now (by setting default
// value for threshold to MAX) due to HSD 4114629.
uint64_t __offload_use_2mb_buffers = 0xffffffffffffffffULL;
static const char *mic_use_2mb_buffers_envname  =
    "MIC_USE_2MB_BUFFERS";

static uint64_t __offload_use_async_buffer_write = 2 * 1024 * 1024;
static const char *mic_use_async_buffer_write_envname  =
    "MIC_USE_ASYNC_BUFFER_WRITE";

static uint64_t __offload_use_async_buffer_read = 2 * 1024 * 1024;
static const char *mic_use_async_buffer_read_envname  =
    "MIC_USE_ASYNC_BUFFER_READ";

// device initialization type
OffloadInitType __offload_init_type = c_init_on_offload_all;
static const char *offload_init_envname = "OFFLOAD_INIT";

// active wait
static bool __offload_active_wait = true;
static const char *offload_active_wait_envname = "OFFLOAD_ACTIVE_WAIT";

// OMP_DEFAULT_DEVICE
int __omp_device_num = 0;
static const char *omp_device_num_envname = "OMP_DEFAULT_DEVICE";

//OFFLOAD_PARALLEL_COPY
static bool __offload_parallel_copy = false;
static const char *parallel_copy_envname = "OFFLOAD_PARALLEL_COPY";

//Use COI interface for noncontiguous transfer if it exists.
static bool __offload_use_coi_noncontiguous_transfer = false;
static const char *use_coi_noncontiguous_transfer_envname =
                       "MIC_USE_COI_MULTI_D";

// The list of pending target libraries
static bool            __target_libs;
static TargetImageList __target_libs_list;
static mutex_t         __target_libs_lock;
static mutex_t         stack_alloc_lock;

// Target executable
TargetImage*           __target_exe;

// Print readable offload flags
static void trace_offload_flags(
    OffloadHostTimerData* timer_data,
    OffloadFlags offload_flags
)
{
    // Sized big enough for all flag names
    char fbuffer[256];
    bool first = true;
    if (!OFFLOAD_DO_TRACE && (console_enabled >= 1)) {
        sprintf(fbuffer, "   OffloadFlags=(");
        if (offload_flags.bits.fortran_traceback) {
            sprintf(fbuffer+strlen(fbuffer), "fortran_traceback");
            first = false;
        }
        if (offload_flags.bits.omp_async) {
            sprintf(fbuffer+strlen(fbuffer), first ? "omp_async" : ",omp_async");
            first = false;
        }
        OFFLOAD_DEBUG_TRACE_1(1,
            GET_OFFLOAD_NUMBER(timer_data), c_offload_init_func,
            "%s)\n", fbuffer);
    }
}

// Print readable varDesc flags
static void trace_varDesc_flags(
    OffloadHostTimerData* timer_data,
    varDescFlags offload_flags
)
{
    // SIzed big enough for all flag names
    char fbuffer[256];
    bool first = true;
    if (!OFFLOAD_DO_TRACE && (console_enabled >= 1)) {
        sprintf(fbuffer, "              varDescFlags=(");
        if (offload_flags.is_static) {
            sprintf(fbuffer+strlen(fbuffer), "is_static");
            first = false;
        }
        if (offload_flags.is_static_dstn) {
            sprintf(fbuffer+strlen(fbuffer),
                first ? "is_static_dstn" : ",is_static_dstn");
            first = false;
        }
        if (offload_flags.has_length) {
            sprintf(fbuffer+strlen(fbuffer),
                first ? "has_length" : ",has_length");
            first = false;
        }
        if (offload_flags.is_stack_buf) {
            sprintf(fbuffer+strlen(fbuffer),
                first ? "is_stack_buf" : ",is_stack_buf");
            first = false;
        }
        if (offload_flags.targetptr) {
            sprintf(fbuffer+strlen(fbuffer),
                first ? "targetptr" : ",targetptr");
            first = false;
        }
        if (offload_flags.preallocated) {
            sprintf(fbuffer+strlen(fbuffer),
                first ? "preallocated" : ",preallocated");
            first = false;
        }
        if (offload_flags.is_pointer) {
            sprintf(fbuffer+strlen(fbuffer),
                first ? "is_pointer" : ",is_pointer");
            first = false;
        }
        if (offload_flags.sink_addr) {
            sprintf(fbuffer+strlen(fbuffer),
                first ? "sink_addr" : ",sink_addr");
            first = false;
        }
        if (offload_flags.alloc_disp) {
            sprintf(fbuffer+strlen(fbuffer),
               first ? "alloc_disp" : ",alloc_disp");
            first = false;
        }
        if (offload_flags.is_noncont_src) {
            sprintf(fbuffer+strlen(fbuffer),
                first ? "is_noncont_src" : ",is_noncont_src");
            first = false;
        }
        if (offload_flags.is_noncont_dst) {
            sprintf(fbuffer+strlen(fbuffer),
                first ? "is_noncont_dst" : ",is_noncont_dst");
            first = false;
        }
        if (offload_flags.always_copy) {
            sprintf(fbuffer+strlen(fbuffer),
                first ? "always_copy" : ",always_copy");
            first = false;
        }
        if (offload_flags.always_delete) {
            sprintf(fbuffer+strlen(fbuffer),
                first ? "always_delete" : ",always_delete");
            first = false;
        }
        OFFLOAD_DEBUG_TRACE_1(1,
            GET_OFFLOAD_NUMBER(timer_data), c_offload_init_func,
            "%s)\n", fbuffer);
    }
}

static char * offload_get_src_base(void * ptr, uint8_t type)
{
    char *base;
    if (VAR_TYPE_IS_PTR(type)) {
        base = *static_cast<char**>(ptr);
    }
    else if (VAR_TYPE_IS_SCALAR(type)) {
        base = static_cast<char*>(ptr);
    }
    else if (VAR_TYPE_IS_DV_DATA_SLICE(type) || VAR_TYPE_IS_DV_DATA(type)) {
        ArrDesc *dvp;
        if (VAR_TYPE_IS_DV_DATA_SLICE(type)) {
            const Arr_Desc *ap = static_cast<const Arr_Desc*>(ptr);
            dvp = (type == c_dv_data_slice) ?
                  reinterpret_cast<ArrDesc*>(ap->base) :
                  *reinterpret_cast<ArrDesc**>(ap->base);
        }
        else {
            dvp = (type == c_dv_data) ?
                  static_cast<ArrDesc*>(ptr) :
                  *static_cast<ArrDesc**>(ptr);
        }
        base = reinterpret_cast<char*>(dvp->Base);
    }
    else {
        base = NULL;
    }
    return base;
}

void OffloadDescriptor::report_coi_error(error_types msg, COIRESULT res)
{
    // special case for the 'process died' error
    if (res == COI_PROCESS_DIED) {
        m_device.fini_process(true);
    }
    else {
        switch (msg) {
            case c_buf_create:
                if (res == COI_OUT_OF_MEMORY) {
                    msg = c_buf_create_out_of_mem;
                }
                /* fallthru */

            case c_buf_create_from_mem:
            case c_buf_get_address:
            case c_pipeline_create:
            case c_pipeline_run_func:
                LIBOFFLOAD_ERROR(msg, m_device.get_logical_index(), res);
                break;

            case c_buf_read:
            case c_buf_write:
            case c_buf_copy:
            case c_buf_map:
            case c_buf_unmap:
            case c_buf_destroy:
            case c_buf_set_state:
                LIBOFFLOAD_ERROR(msg, res);
                break;

            default:
                break;
        }
    }

    exit(1);
}

_Offload_result OffloadDescriptor::translate_coi_error(COIRESULT res) const
{
    switch (res) {
        case COI_SUCCESS:
            return OFFLOAD_SUCCESS;

        case COI_PROCESS_DIED:
            return OFFLOAD_PROCESS_DIED;

        case COI_OUT_OF_MEMORY:
            return OFFLOAD_OUT_OF_MEMORY;

        default:
            return OFFLOAD_ERROR;
    }
}

// is_targetptr == 0 && is_prealloc == 0 - allocation of pointer data;
// is_targetptr == 1 && is_prealloc == 0 - allocation of target memory:
//    allocate memory at target; use its value as base in target table.
// is_targetptr == 1 && is_prealloc == 1 - use preallocated target memory:
//    base - is address at target of preallocated memory; use its value as
//    base in target table.

bool OffloadDescriptor::alloc_ptr_data(
    PtrData* &ptr_data,
    void *base,
    int64_t disp,
    int64_t size,
    int64_t alloc_disp,
    int align,
    bool is_targptr,
    bool is_prealloc,
    bool pin
)
{
    // total length of base
    int64_t length = size;
    bool is_new;
    COIBUFFER targptr_buf;
    COIRESULT res;
    uint32_t buffer_flags = 0;
    char * base_disp = reinterpret_cast<char *>(base) + disp;

    // create buffer with large pages if data length exceeds
    // large page threshold
    if (length >= __offload_use_2mb_buffers) {
        buffer_flags = COI_OPTIMIZE_HUGE_PAGE_SIZE;
    }
    // Allocate memory at target for targetptr without preallocated as we need
    // its address as base argument in call to m_device.insert_ptr_data
    if (is_targptr && !is_prealloc) {
        length = alloc_disp ? length : size + disp;
        res = COI::BufferCreate(
            length,
            COI_BUFFER_NORMAL,
            buffer_flags,
            0,
            1,
            &m_device.get_process(),
            &targptr_buf);
        if (res != COI_SUCCESS) {
            if (m_status != 0) {
                m_status->result = translate_coi_error(res);
            }
            else if (m_is_mandatory) {
                report_coi_error(c_buf_create, res);
            }
            return false;
        }

        res = COI::BufferGetSinkAddress(
                       targptr_buf, reinterpret_cast<uint64_t *>(&base));
        if (res != COI_SUCCESS) {
            if (m_status != 0) {
                m_status->result = translate_coi_error(res);
            }
            else if (m_is_mandatory) {
                report_coi_error(c_buf_get_address, res);
            }
            return false;
        }
    }

    OFFLOAD_TRACE(3, "Creating association for data: addr %p, length %lld\n",
                  alloc_disp ? base : base_disp,
                  alloc_disp ? length : size + disp);
                  
    // add new entry

    ptr_data = is_targptr ?
               m_device.find_targetptr_data(base_disp) :
               m_device.find_ptr_data(base_disp);
    // if ptr_data is found just need to check it for overlapping
    if (ptr_data) {
        is_new = false;
        base = base_disp;
    }
    else {
        // If association is not found we must create it.
        length = alloc_disp ? length : size + disp;
        ptr_data = is_targptr ?
               m_device.insert_targetptr_data(base, length, is_new) :
               m_device.insert_ptr_data(base, length, is_new);
    }
    if (is_new) {

        OFFLOAD_TRACE(3, "Added new association\n");

        if (length > 0) {
            OffloadTimer timer(get_timer_data(), c_offload_host_alloc_buffers);

            // align should be a power of 2
            if (!pin && !is_targptr &&
                align > 0 && (align & (align - 1)) == 0) {
                // offset within mic_buffer. Can do offset optimization
                // only when source address alignment satisfies requested
                // alignment on the target (cq172736).
                if ((reinterpret_cast<intptr_t>(base) & (align - 1)) == 0) {
                    ptr_data->mic_offset =
                        reinterpret_cast<intptr_t>(base) & 4095;
                }
            }

            // buffer size and flags
            uint64_t buffer_size = length + ptr_data->mic_offset;

            // For targetptr there is no CPU buffer
            if (pin || !is_targptr) {
                // create CPU buffer
                OFFLOAD_DEBUG_TRACE_1(3,
                          GET_OFFLOAD_NUMBER(get_timer_data()),
                          c_offload_create_buf_host,
                          "Creating buffer from source memory %p, "
                          "length %lld\n", base, length);

                // result is not checked because we can continue without cpu
                // buffer. In this case we will use COIBufferRead/Write
                // instead of COIBufferCopy.

                COI::BufferCreateFromMemory(length,
                                        COI_BUFFER_NORMAL,
                                        0,
                                        base,
                                        1,
                                        &m_device.get_process(),
                                        &ptr_data->cpu_buf);
            }

            // create MIC buffer
            if (is_prealloc) {
                OFFLOAD_DEBUG_TRACE_1(3,
                          GET_OFFLOAD_NUMBER(get_timer_data()),
                          c_offload_create_buf_mic,
                          "Creating buffer from sink memory: size %lld, offset %d, "
                          "flags =0x%x\n", buffer_size,
                          ptr_data->mic_offset, buffer_flags);
                res = COI::BufferCreateFromMemory(ptr_data->cpu_addr.length(),
                                                  COI_BUFFER_NORMAL,
                                                  COI_SINK_MEMORY,
                                                  base,
                                                  1,
                                                  &m_device.get_process(),
                                                  &ptr_data->mic_buf);
                if (res != COI_SUCCESS) {
                    if (m_status != 0) {
                        m_status->result = translate_coi_error(res);
                    }
                    else if (m_is_mandatory) {
                        report_coi_error(c_buf_create, res);
                    }
                    ptr_data->alloc_ptr_data_lock.unlock();
                    return false;
                }
            }
            else if (is_targptr) {
                ptr_data->mic_buf = targptr_buf;
            }
            else if (!pin) {
                OFFLOAD_DEBUG_TRACE_1(3,
                          GET_OFFLOAD_NUMBER(get_timer_data()),
                          c_offload_create_buf_mic,
                          "Creating buffer for sink: size %lld, offset %d, "
                          "flags =0x%x\n", buffer_size,
                          ptr_data->mic_offset, buffer_flags);
                res = COI::BufferCreate(buffer_size,
                                        COI_BUFFER_NORMAL,
                                        buffer_flags,
                                        0,
                                        1,
                                        &m_device.get_process(),
                                        &ptr_data->mic_buf);
                if (res != COI_SUCCESS) {
                    if (m_status != 0) {
                        m_status->result = translate_coi_error(res);
                    }
                    else if (m_is_mandatory) {
                        report_coi_error(c_buf_create, res);
                    }
                    ptr_data->alloc_ptr_data_lock.unlock();
                    return false;
                }
            }

            if (!pin) {
                // make buffer valid on the device.
                res = COI::BufferSetState(ptr_data->mic_buf,
                    m_device.get_process(),
                    COI_BUFFER_VALID,
                    COI_BUFFER_NO_MOVE,
                    0, 0, 0);
                if (res != COI_SUCCESS) {
                    if (m_status != 0) {
                        m_status->result = translate_coi_error(res);
                    }
                    else if (m_is_mandatory) {
                        report_coi_error(c_buf_set_state, res);
                    }
                    ptr_data->alloc_ptr_data_lock.unlock();
                    return false;
                }

                res = COI::BufferSetState(ptr_data->mic_buf,
                    COI_PROCESS_SOURCE,
                    COI_BUFFER_INVALID,
                    COI_BUFFER_NO_MOVE,
                0, 0, 0);
                if (res != COI_SUCCESS) {
                    if (m_status != 0) {
                        m_status->result = translate_coi_error(res);
                    }
                    else if (m_is_mandatory) {
                        report_coi_error(c_buf_set_state, res);
                    }
                    ptr_data->alloc_ptr_data_lock.unlock();
                    return false;
                }
            }
        }
        ptr_data->alloc_disp = alloc_disp;
        ptr_data->alloc_ptr_data_lock.unlock();
    }
    else {
        mutex_locker_t locker(ptr_data->alloc_ptr_data_lock);

        OFFLOAD_TRACE(3, "Found existing association: addr %p, length %lld, "
                      "is_static %d\n",
                      ptr_data->cpu_addr.start(), ptr_data->cpu_addr.length(),
                      ptr_data->is_static);

        // This is not a new entry. Make sure that provided address range fits
        // into existing one.
        MemRange addr_range(base, length);
        if (!ptr_data->cpu_addr.contains(addr_range)) {
            LIBOFFLOAD_ERROR(c_bad_ptr_mem_alloc, base, length,
                           const_cast<void *>(ptr_data->cpu_addr.start()),
                           ptr_data->cpu_addr.length());
            exit(1);
        }

        // if the entry is associated with static data it may not have buffers
        // created because they are created on demand.
        if (ptr_data->is_static && !init_static_ptr_data(ptr_data)) {
            return false;
        }
    }

    return true;
}

bool OffloadDescriptor::find_ptr_data(
    PtrData* &ptr_data,
    void *in_base,
    int64_t disp,
    int64_t size,
    bool is_targetptr,
    bool report_error
)
{
    // total length of base
    int64_t length = size;
    char *base = reinterpret_cast<char *>(in_base) + disp;
    
    OFFLOAD_TRACE(3, "Looking for association for data: addr %p, "
                  "length %lld\n", base, length);

    // find existing association in pointer table
    ptr_data = is_targetptr ?
               m_device.find_targetptr_data(base) :
               m_device.find_ptr_data(base);
    if (ptr_data == 0) {
        if (report_error) {
            LIBOFFLOAD_ERROR(c_no_ptr_data, base);
            exit(1);
        }
        OFFLOAD_TRACE(3, "Association does not exist\n");
        return true;
    }

    OFFLOAD_TRACE(3, "Found association: base %p, length %lld, is_static %d\n",
                  ptr_data->cpu_addr.start(), ptr_data->cpu_addr.length(),
                  ptr_data->is_static);

    // make sure that provided address range fits into existing one
    MemRange addr_range(base, length);
    if (!ptr_data->cpu_addr.contains(addr_range)) {
        if (report_error) {
            LIBOFFLOAD_ERROR(c_bad_ptr_mem_range, base, length,
                           const_cast<void *>(ptr_data->cpu_addr.start()),
                           ptr_data->cpu_addr.length());
            exit(1);
        }
        OFFLOAD_TRACE(3, "Existing association partially overlaps with "
                      "data address range\n");
        ptr_data = 0;
        return true;
    }

    // if the entry is associated with static data it may not have buffers
    // created because they are created on demand.
    if (ptr_data->is_static && !init_static_ptr_data(ptr_data)) {
        return false;
    }

    return true;
}

bool OffloadDescriptor::init_static_ptr_data(PtrData *ptr_data)
{
    OffloadTimer timer(get_timer_data(), c_offload_host_alloc_buffers);

    if (ptr_data->cpu_buf == 0) {
        OFFLOAD_TRACE(3, "Creating buffer from source memory %llx\n",
                      ptr_data->cpu_addr.start());

        COIRESULT res = COI::BufferCreateFromMemory(
            ptr_data->cpu_addr.length(),
            COI_BUFFER_NORMAL,
            0,
            const_cast<void*>(ptr_data->cpu_addr.start()),
            1, &m_device.get_process(),
            &ptr_data->cpu_buf);

        if (res != COI_SUCCESS) {
            if (m_status != 0) {
                m_status->result = translate_coi_error(res);
                return false;
            }
            report_coi_error(c_buf_create_from_mem, res);
        }
    }

    if (ptr_data->mic_buf == 0) {
        OFFLOAD_TRACE(3, "Creating buffer from sink memory %llx\n",
                      ptr_data->mic_addr);

        COIRESULT res = COI::BufferCreateFromMemory(
            ptr_data->cpu_addr.length(),
            COI_BUFFER_NORMAL,
            COI_SINK_MEMORY,
            reinterpret_cast<void*>(ptr_data->mic_addr),
            1, &m_device.get_process(),
            &ptr_data->mic_buf);

        if (res != COI_SUCCESS) {
            if (m_status != 0) {
                m_status->result = translate_coi_error(res);
                return false;
            }
            report_coi_error(c_buf_create_from_mem, res);
        }
    }

    return true;
}

bool OffloadDescriptor::init_mic_address(PtrData *ptr_data)
{
    if (ptr_data->mic_buf != 0 && ptr_data->mic_addr == 0) {
        COIRESULT res = COI::BufferGetSinkAddress(ptr_data->mic_buf,
                                                  &ptr_data->mic_addr);
        if (res != COI_SUCCESS) {
            if (m_status != 0) {
                m_status->result = translate_coi_error(res);
            }
            else if (m_is_mandatory) {
                report_coi_error(c_buf_get_address, res);
            }
            return false;
        }
    }
    return true;
}

bool OffloadDescriptor::nullify_target_stack(
    COIBUFFER targ_buf,
    uint64_t size
)
{
    char * ptr = (char*)malloc(size);
    if (ptr == NULL)
      LIBOFFLOAD_ERROR(c_malloc);
    COIRESULT res;

    memset(ptr, 0, size);
    res = COI::BufferWrite(
        targ_buf,
        0,
        ptr,
        size,
        COI_COPY_UNSPECIFIED,
        0, 0, 0);
    free(ptr);
    if (res != COI_SUCCESS) {
        if (m_status != 0) {
            m_status->result = translate_coi_error(res);
            return false;
        }
        report_coi_error(c_buf_write, res);
    }
    return true;
}

bool OffloadDescriptor::offload_stack_memory_manager(
    const void * stack_begin,
    int  routine_id,
    int  buf_size,
    int  align,
    bool *is_new)
{
    mutex_locker_t locker(stack_alloc_lock);

    PersistData * new_el;
    PersistDataList::iterator it_begin = m_device.m_persist_list.begin();
    PersistDataList::iterator it_end;
    int erase = 0;
    uint64_t cur_thread_id = m_device.get_thread_id();

    *is_new = false;

    for (PersistDataList::iterator it = m_device.m_persist_list.begin();
        it != m_device.m_persist_list.end(); it++) {
        PersistData cur_el = *it;

        if (stack_begin > it->stack_cpu_addr) {
            // this stack data must be destroyed
            if (cur_thread_id == cur_el.thread_id) {
                m_destroy_stack.push_front(cur_el.stack_ptr_data);
                it_end = it;
                erase++;
            }
        }
        else if (stack_begin == it->stack_cpu_addr) {
            if (routine_id != it-> routine_id) {
                // this stack data must be destroyed
                m_destroy_stack.push_front(cur_el.stack_ptr_data);
                it_end = it;
                erase++;
                break;
            }
            else {
                // stack data is reused
                m_stack_ptr_data = it->stack_ptr_data;
                if (erase > 0) {
                    // all obsolete stack sections must be erased from the list
                    m_device.m_persist_list.erase(it_begin, ++it_end);

                    m_in_datalen +=
                        erase * sizeof(new_el->stack_ptr_data->mic_addr);
                }
                OFFLOAD_TRACE(3, "Reuse of stack buffer with addr %p\n",
                                 m_stack_ptr_data->mic_addr);
                return true;
            }
        }
        else if (stack_begin < it->stack_cpu_addr &&
                 cur_thread_id == cur_el.thread_id) {
            break;
        }
    }

    if (erase > 0) {
        // all obsolete stack sections must be erased from the list
        m_device.m_persist_list.erase(it_begin, ++it_end);
        m_in_datalen += erase * sizeof(new_el->stack_ptr_data->mic_addr);
    }
    // new stack table is created
    new_el = new PersistData(stack_begin, routine_id, buf_size, cur_thread_id);
    // create MIC buffer
    COIRESULT res;
    uint32_t buffer_flags = 0;

    // create buffer with large pages if data length exceeds
    // large page threshold
    if (buf_size >= __offload_use_2mb_buffers) {
        buffer_flags = COI_OPTIMIZE_HUGE_PAGE_SIZE;
    }
    res = COI::BufferCreate(buf_size,
        COI_BUFFER_NORMAL,
        buffer_flags,
        0,
        1,
        &m_device.get_process(),
        &new_el->stack_ptr_data->mic_buf);
    if (res != COI_SUCCESS) {
        if (m_status != 0) {
            m_status->result = translate_coi_error(res);
        }
        else if (m_is_mandatory) {
            report_coi_error(c_buf_create, res);
        }
        return false;
    }
    // make buffer valid on the device.
    res = COI::BufferSetState(new_el->stack_ptr_data->mic_buf,
        m_device.get_process(),
        COI_BUFFER_VALID,
        COI_BUFFER_NO_MOVE,
        0, 0, 0);
    if (res != COI_SUCCESS) {
        if (m_status != 0) {
            m_status->result = translate_coi_error(res);
        }
        else if (m_is_mandatory) {
            report_coi_error(c_buf_set_state, res);
        }
        return false;
    }
    res = COI::BufferSetState(new_el->stack_ptr_data->mic_buf,
        COI_PROCESS_SOURCE,
        COI_BUFFER_INVALID,
        COI_BUFFER_NO_MOVE,
        0, 0, 0);
    if (res != COI_SUCCESS) {
        if (m_status != 0) {
            m_status->result = translate_coi_error(res);
        }
        else if (m_is_mandatory) {
            report_coi_error(c_buf_set_state, res);
        }
        return false;
    }
    // persistence algorithm requires target stack initialy to be nullified
    if (!nullify_target_stack(new_el->stack_ptr_data->mic_buf, buf_size)) {
        return false;
    }

    m_stack_ptr_data = new_el->stack_ptr_data;
    init_mic_address(m_stack_ptr_data);
    OFFLOAD_TRACE(3, "Allocating stack buffer with addr %p\n",
                      m_stack_ptr_data->mic_addr);
    m_device.m_persist_list.push_front(*new_el);
    init_mic_address(new_el->stack_ptr_data);
    *is_new = true;
    return true;
}

bool OffloadDescriptor::setup_descriptors(
    VarDesc *vars,
    VarDesc2 *vars2,
    int vars_total,
    int entry_id,
    const void *stack_addr
)
{
    COIRESULT res;

    OffloadTimer timer(get_timer_data(), c_offload_host_setup_buffers);

    // make a copy of variable descriptors
    m_vars_total = vars_total;
    if (vars_total > 0) {
        m_vars = (VarDesc*) malloc(m_vars_total * sizeof(VarDesc));
        if (m_vars == NULL)
          LIBOFFLOAD_ERROR(c_malloc);
        memcpy(m_vars, vars, m_vars_total * sizeof(VarDesc));
        m_vars_extra = (VarExtra*) malloc(m_vars_total * sizeof(VarExtra));
        if (m_vars_extra == NULL)
          LIBOFFLOAD_ERROR(c_malloc);
    }

    // dependencies
    m_in_deps_allocated = m_vars_total + 1;   
    m_in_deps = (COIEVENT*) malloc(sizeof(COIEVENT) * m_in_deps_allocated);
    if (m_in_deps == NULL)
      LIBOFFLOAD_ERROR(c_malloc);
    if (m_vars_total > 0) {
        m_out_deps_allocated = m_vars_total;
        m_out_deps = (COIEVENT*) malloc(sizeof(COIEVENT) * m_out_deps_allocated);
        if (m_out_deps == NULL)
          LIBOFFLOAD_ERROR(c_malloc);
    }

    // copyin/copyout data length
    m_in_datalen = 0;
    m_out_datalen = 0;

    // First pass over variable descriptors
    // - Calculate size of the input and output non-pointer data
    // - Allocate buffers for input and output pointers
    for (int i = 0; i < m_vars_total; i++) {
        void*   alloc_base = NULL;
        int64_t alloc_disp = 0;
        int64_t alloc_size = 0;
        bool    src_is_for_mic = (m_vars[i].direction.out ||
                                  m_vars[i].into == NULL);

        const char *var_sname = "";
        if (vars2 != NULL && i < vars_total) {
            if (vars2[i].sname != NULL) {
                var_sname = vars2[i].sname;
            }
        }
        OFFLOAD_TRACE(2, "   VarDesc %d, var=%s, %s, %s\n",
            i, var_sname,
            vardesc_direction_as_string[m_vars[i].direction.bits],
            vardesc_type_as_string[m_vars[i].type.src]);
        if (vars2 != NULL && i < vars_total && vars2[i].dname != NULL) {
            OFFLOAD_TRACE(2, "              into=%s, %s\n", vars2[i].dname,
                vardesc_type_as_string[m_vars[i].type.dst]);
        }
        OFFLOAD_TRACE(2,
            "              type_src=%d, type_dstn=%d, direction=%d, "
            "alloc_if=%d, free_if=%d, align=%d, mic_offset=%d, flags=0x%x, "
            "offset=%lld, size=%lld, count/disp=%lld, ptr=%p, into=%p\n",
            m_vars[i].type.src,
            m_vars[i].type.dst,
            m_vars[i].direction.bits,
            m_vars[i].alloc_if,
            m_vars[i].free_if,
            m_vars[i].align,
            m_vars[i].mic_offset,
            m_vars[i].flags.bits,
            m_vars[i].offset,
            m_vars[i].size,
            m_vars[i].count,
            m_vars[i].ptr,
            m_vars[i].into);
        // If any varDesc flags bits set, show them
        if (console_enabled >= 1 && m_vars[i].flags.bits != 0) {
            trace_varDesc_flags(get_timer_data(), m_vars[i].flags);
        }

        // preallocated implies targetptr
        if (m_vars[i].flags.preallocated) {
            // targetptr preallocated alloc_if(1) may not be used with
            // an in clause
            if (m_vars[i].direction.in && m_vars[i].alloc_if) {
                LIBOFFLOAD_ERROR(c_in_with_preallocated);
                exit(1);
            }
            m_vars[i].flags.targetptr = 1;
        }
        if (m_vars[i].alloc != NULL) {
            // array descriptor
            const Arr_Desc *ap =
                static_cast<const Arr_Desc*>(m_vars[i].alloc);

            // debug dump
            ARRAY_DESC_DUMP("    ", "ALLOC", ap, 0, 1);

            __arr_data_offset_and_length(ap, alloc_disp, alloc_size);

            alloc_base = reinterpret_cast<void*>(ap->base);
        }

        m_vars_extra[i].alloc = m_vars[i].alloc;
        m_vars_extra[i].cpu_disp = 0;
        m_vars_extra[i].cpu_offset = 0;
        m_vars_extra[i].src_data = 0;
        m_vars_extra[i].read_rng_src = 0;
        m_vars_extra[i].read_rng_dst = 0;
        m_vars_extra[i].omp_last_event_type = c_last_not;        
        // flag is_arr_ptr_el is 1 only for var_descs generated
        // for c_data_ptr_array type
        if (i < vars_total) {
            m_vars_extra[i].is_arr_ptr_el = 0;
        }

        switch (m_vars[i].type.src) {
            case c_data_ptr_array:
                {
                    const Arr_Desc *ap;
                    const VarDesc3 *vd3 =
                        static_cast<const VarDesc3*>(m_vars[i].ptr);
                    int flags = vd3->array_fields;
                    OFFLOAD_TRACE(2,
                        "              pointer array flags = %04x\n", flags);
                    OFFLOAD_TRACE(2,
                        "              pointer array type is %s\n",
                        vardesc_type_as_string[flags & 0x3f]);
                    ap = static_cast<const Arr_Desc*>(vd3->ptr_array);
                    ARRAY_DESC_DUMP("              ", "ptr array", ap,
                                    m_vars[i].flags.is_pointer, 1);
                    if (m_vars[i].into) {
                        ap = static_cast<const Arr_Desc*>(m_vars[i].into);
                        ARRAY_DESC_DUMP(
                            "              ", "into array", ap, 0, 1);
                    }
                    if ((flags & (1<<flag_align_is_array)) != 0) {
                        ap = static_cast<const Arr_Desc*>(vd3->align_array);
                        ARRAY_DESC_DUMP(
                            "              ", "align array", ap, 0, 1);
                    }
                    if ((flags & (1<<flag_alloc_if_is_array)) != 0) {
                        ap = static_cast<const Arr_Desc*>(vd3->alloc_if_array);
                        ARRAY_DESC_DUMP(
                            "              ", "alloc_if array", ap, 0, 1);
                    }
                    if ((flags & (1<<flag_free_if_is_array)) != 0) {
                        ap = static_cast<const Arr_Desc*>(vd3->free_if_array);
                        ARRAY_DESC_DUMP(
                            "              ", "free_if array", ap, 0, 1);
                    }
                    if ((flags & (1<<flag_extent_start_is_array)) != 0) {
                        ap = static_cast<const Arr_Desc*>(vd3->extent_start);
                        ARRAY_DESC_DUMP(
                            "              ", "extent_start array", ap, 0, 1);
                    } else if ((flags &
                        (1<<flag_extent_start_is_scalar)) != 0) {
                        OFFLOAD_TRACE(2,
                            "              extent_start scalar = %d\n",
                            (int64_t)vd3->extent_start);
                    }
                    if ((flags & (1<<flag_extent_elements_is_array)) != 0) {
                        ap = static_cast<const Arr_Desc*>
                            (vd3->extent_elements);
                        ARRAY_DESC_DUMP("              ",
                                        "extent_elements array", ap, 0, 1);
                    } else if ((flags &
                        (1<<flag_extent_elements_is_scalar)) != 0) {
                        OFFLOAD_TRACE(2,
                            "              extent_elements scalar = %d\n",
                            (int64_t)vd3->extent_elements);
                    }
                    if ((flags & (1<<flag_into_start_is_array)) != 0) {
                        ap = static_cast<const Arr_Desc*>(vd3->into_start);
                        ARRAY_DESC_DUMP(
                            "              ", "into_start array", ap, 0, 1);
                    } else if ((flags &
                        (1<<flag_into_start_is_scalar)) != 0) {
                        OFFLOAD_TRACE(2,
                            "              into_start scalar = %d\n",
                            (int64_t)vd3->into_start);
                    }
                    if ((flags & (1<<flag_into_elements_is_array)) != 0) {
                        ap = static_cast<const Arr_Desc*>(vd3->into_elements);
                        ARRAY_DESC_DUMP(
                            "              ", "into_elements array", ap, 0, 1);
                    } else if ((flags &
                        (1<<flag_into_elements_is_scalar)) != 0) {
                        OFFLOAD_TRACE(2,
                            "              into_elements scalar = %d\n",
                            (int64_t)vd3->into_elements);
                    }
                    if ((flags & (1<<flag_alloc_start_is_array)) != 0) {
                        ap = static_cast<const Arr_Desc*>(vd3->alloc_start);
                        ARRAY_DESC_DUMP(
                            "              ", "alloc_start array", ap, 0, 1);
                    } else if ((flags &
                        (1<<flag_alloc_start_is_scalar)) != 0) {
                        OFFLOAD_TRACE(2,
                            "              alloc_start scalar = %d\n",
                            (int64_t)vd3->alloc_start);
                    }
                    if ((flags & (1<<flag_alloc_elements_is_array)) != 0) {
                        ap = static_cast<const Arr_Desc*>(vd3->alloc_elements);
                        ARRAY_DESC_DUMP("              ",
                                        "alloc_elements array", ap, 0, 1);
                    } else if ((flags &
                        (1<<flag_alloc_elements_is_scalar)) != 0) {
                        OFFLOAD_TRACE(2,
                            "              alloc_elements scalar = %d\n",
                            (int64_t)vd3->alloc_elements);
                    }
                }
                if (!gen_var_descs_for_pointer_array(i)) {
                    return false;
                }
                break;

            case c_data:
            case c_void_ptr:
            case c_cean_var:
                // In all uses later
                // VarDesc.size will have the length of the data to be
                // transferred
                // VarDesc.disp will have an offset from base
                if (m_vars[i].type.src == c_cean_var) {
                    // array descriptor
                    const Arr_Desc *ap =
                        static_cast<const Arr_Desc*>(m_vars[i].ptr);

                    // debug dump
                    ARRAY_DESC_DUMP("", "IN/OUT", ap, 0, !src_is_for_mic);

                    // offset and length are derived from the array descriptor
                    __arr_data_offset_and_length(ap, m_vars[i].disp,
                                                 m_vars[i].size);
                    if (!is_arr_desc_contiguous(ap)) {
                        m_vars[i].flags.is_noncont_src = 1;
                        m_vars_extra[i].read_rng_src =
                            init_read_ranges_arr_desc(ap);
                    }
                    // all necessary information about length and offset is
                    // transferred in var descriptor. There is no need to send
                    // array descriptor to the target side.
                    m_vars[i].ptr = reinterpret_cast<void*>(ap->base);
                }
                else {
                    m_vars[i].size *= m_vars[i].count;
                    m_vars[i].disp = 0;
                }

                if (m_vars[i].direction.bits) {
                    // make sure that transfer size > 0
                    if (m_vars[i].size <= 0) {
                        LIBOFFLOAD_ERROR(c_zero_or_neg_transfer_size);
                        exit(1);
                    }

                    if (m_vars[i].flags.is_static) {
                        PtrData *ptr_data;

                        // find data associated with variable
                        if (!find_ptr_data(ptr_data,
                                           m_vars[i].ptr,
                                           m_vars[i].disp,
                                           m_vars[i].size,
                                           false, false)) {
                            return false;
                        }

                        if (ptr_data != 0) {
                            // offset to base from the beginning of the buffer
                            // memory
                            m_vars[i].offset =
                                (char*) m_vars[i].ptr -
                                (char*) ptr_data->cpu_addr.start();
                        }
                        else {
                            m_vars[i].flags.is_static = false;
                            if (m_vars[i].into == NULL) {
                                m_vars[i].flags.is_static_dstn = false;
                            }
                        }
                        m_vars_extra[i].src_data = ptr_data;
                    }

                    if (m_is_openmp) {
                        if (m_vars[i].flags.is_static) {
                            // Static data is transferred either by omp target
                            // update construct which passes zeros for
                            // alloc_if and free_if or by always modifier.
                            if (!m_vars[i].flags.always_copy &&
                                (m_vars[i].alloc_if || m_vars[i].free_if)) {
                                m_vars[i].direction.bits = c_parameter_nocopy;
                            }
                        }
                        else {
                            AutoData *auto_data;
                            if (m_vars[i].alloc_if) {
                                auto_data = m_device.insert_auto_data(
                                    m_vars[i].ptr, m_vars[i].size);
                                auto_data->add_reference();
                            }
                            else {
                                // TODO: what should be done if var is not in
                                // the table?
                                auto_data = m_device.find_auto_data(
                                    m_vars[i].ptr);
                            }

                            // For automatic variables data is transferred:
                            // - if always modifier is used OR
                            // - if alloc_if == 0 && free_if == 0 OR
                            // - if reference count is 1
                            if (!m_vars[i].flags.always_copy &&
                                (m_vars[i].alloc_if || m_vars[i].free_if) &&
                                auto_data != 0 &&
                                auto_data->get_reference() != 1) {
                                m_vars[i].direction.bits = c_parameter_nocopy;
                            }

                            // save data for later use
                            m_vars_extra[i].auto_data = auto_data;
                        }
                    }

                    if (m_vars[i].direction.in &&
                        !m_vars[i].flags.is_static) {
                        m_in_datalen += m_vars[i].size;

                        // for non-static target destination defined as CEAN
                        // expression we pass to target its size and dist
                        if (m_vars[i].into == NULL &&
                            m_vars[i].type.src == c_cean_var) {
                            m_in_datalen += 2 * sizeof(uint64_t);
                        }
                        m_need_runfunction = true;
                    }
                    if (m_vars[i].direction.out &&
                        !m_vars[i].flags.is_static) {
                        m_out_datalen += m_vars[i].size;
                        m_need_runfunction = true;
                    }
                }
                break;

            case c_dv:
                if (m_vars[i].direction.bits ||
                    m_vars[i].alloc_if ||
                    m_vars[i].free_if) {
                    ArrDesc *dvp = static_cast<ArrDesc*>(m_vars[i].ptr);

                    // debug dump
                    __dv_desc_dump("IN/OUT", dvp);

                    // send dope vector contents excluding base
                    m_in_datalen += m_vars[i].size - sizeof(uint64_t);
                    m_need_runfunction = true;
                }
                break;

            case c_string_ptr:
                if ((m_vars[i].direction.bits ||
                     m_vars[i].alloc_if ||
                     m_vars[i].free_if) &&
                    m_vars[i].size == 0) {
                    m_vars[i].size = 1;
                    m_vars[i].count =
                        strlen(*static_cast<char**>(m_vars[i].ptr)) + 1;
                }
                /* fallthru */

            case c_data_ptr:
                if (m_vars[i].flags.is_stack_buf &&
                    !m_vars[i].direction.bits &&
                    m_vars[i].alloc_if) {
                    // this var_desc is for stack buffer
                    bool is_new;

                    if (!offload_stack_memory_manager(
                            stack_addr, entry_id,
                            m_vars[i].count, m_vars[i].align, &is_new)) {
                        return false;
                    }
                    if (is_new) {
                        m_compute_buffers.push_back(
                            m_stack_ptr_data->mic_buf);
                        m_device.m_persist_list.front().cpu_stack_addr =
                            static_cast<char*>(m_vars[i].ptr);
                    }
                    else {
                        m_vars[i].flags.sink_addr = 1;
                        m_in_datalen += sizeof(m_stack_ptr_data->mic_addr);
                    }
                    m_vars[i].size = m_destroy_stack.size();
                    m_vars_extra[i].src_data = m_stack_ptr_data;

                    // need to add or remove references for stack buffer at target
                    if (is_new || m_destroy_stack.size()) {
                        m_need_runfunction = true;
                    }

                    break;
                }
                /* fallthru */

            case c_cean_var_ptr:
            case c_dv_ptr:
                if (m_vars[i].type.src == c_cean_var_ptr) {
                    // array descriptor
                    const Arr_Desc *ap =
                        static_cast<const Arr_Desc*>(m_vars[i].ptr);

                    // debug dump
                    ARRAY_DESC_DUMP("", "IN/OUT", ap, 1, !src_is_for_mic);

                    // offset and length are derived from the array descriptor
                    __arr_data_offset_and_length(ap, m_vars[i].disp,
                                                 m_vars[i].size);

                    if (!is_arr_desc_contiguous(ap)) {
                        m_vars[i].flags.is_noncont_src = 1;
                        m_vars_extra[i].read_rng_src =
                            init_read_ranges_arr_desc(ap);
                    }
                    // all necessary information about length and offset is
                    // transferred in var descriptor. There is no need to send
                    // array descriptor to the target side.
                    m_vars[i].ptr = reinterpret_cast<void*>(ap->base);
                }
                else if (m_vars[i].type.src == c_dv_ptr) {
                    // need to send DV to the device unless it is 'nocopy'
                    if (m_vars[i].direction.bits ||
                        m_vars[i].alloc_if ||
                        m_vars[i].free_if) {
                        ArrDesc *dvp = *static_cast<ArrDesc**>(m_vars[i].ptr);

                        // debug dump
                        __dv_desc_dump("IN/OUT", dvp);

                        m_vars[i].direction.bits = c_parameter_in;
                    }

                    // no displacement
                    m_vars[i].disp = 0;
                }
                else {
                    // c_data_ptr or c_string_ptr
                    m_vars[i].size *= m_vars[i].count;
                    m_vars[i].disp = 0;
                }

                if (m_vars[i].direction.bits ||
                    m_vars[i].alloc_if ||
                    m_vars[i].free_if) {
                    PtrData *ptr_data;

                    // check that buffer length > 0
                    if (m_vars[i].alloc_if &&
                        m_vars[i].disp + m_vars[i].size <
                        (m_is_openmp ? 0 : 1)) {
                        LIBOFFLOAD_ERROR(c_zero_or_neg_ptr_len);
                        exit(1);
                    }

                    // base address
                    void *base = *static_cast<void**>(m_vars[i].ptr);

                    // allocate buffer if we have no INTO and don't need
                    // allocation for the ptr at target
                    if (src_is_for_mic) {
                        if (m_vars[i].flags.is_stack_buf) {
                            // for stack persistent objects ptr data is created
                            // by var_desc with number 0.
                            // Its ptr_data is stored at m_stack_ptr_data
                            ptr_data = m_stack_ptr_data;
                            m_vars[i].flags.sink_addr = 1;
                        }
                        else if (m_vars[i].alloc_if) {
                            if (m_vars[i].flags.preallocated) {
                                m_out_datalen += sizeof(void*);
                                m_need_runfunction = true;
                                break;
                            }
                            // add new entry
                            if (!alloc_ptr_data(
                                    ptr_data,
                                    reinterpret_cast<char *>(base) + alloc_disp,
                                    (alloc_base != NULL) ?
                                        alloc_disp : m_vars[i].disp,
                                    (alloc_base != NULL) ?
                                        alloc_size : m_vars[i].size,
                                    alloc_disp,
                                    (alloc_base != NULL) ?
                                        0 : m_vars[i].align,
                                    m_vars[i].flags.targetptr,
                                    0,
                                    m_vars[i].flags.pin)) {
                                return false;
                            }
                            if (m_vars[i].flags.targetptr) {
                                if (!init_mic_address(ptr_data)) {
                                    return false;
                                }
                                *static_cast<void**>(m_vars[i].ptr) = base =
                                  reinterpret_cast<void*>(ptr_data->mic_addr);
                            }
                            if (ptr_data->add_reference() == 0 &&
                                ptr_data->mic_buf != 0) {
                                // add buffer to the list of buffers that
                                // are passed to dispatch call
                                m_compute_buffers.push_back(
                                    ptr_data->mic_buf);
                            }
                            else if (!m_vars[i].flags.pin &&
                                     !m_vars[i].flags.preallocated) {
                                // will send buffer address to device
                                m_vars[i].flags.sink_addr = 1;
                            }

                            if (!m_vars[i].flags.pin &&
                                !ptr_data->is_static) {
                                // need to add reference for buffer
                                m_need_runfunction = true;
                            }
                        }
                        else {
                            bool error_if_not_found = true;
                            if (m_is_openmp) {
                                // For omp target update variable is ignored
                                // if it does not exist.
                                if (m_vars[i].flags.always_copy ||
                                    (!m_vars[i].alloc_if &&
                                     !m_vars[i].free_if)) {
                                    error_if_not_found = false;
                                }
                            }

                            // use existing association from pointer table
                            if (!find_ptr_data(ptr_data,
                                               base,
                                               m_vars[i].disp,
                                               m_vars[i].size,
                                               m_vars[i].flags.targetptr,
                                               error_if_not_found)) {
                                return false;
                            }

                            if (m_is_openmp) {
                                // make var nocopy if it does not exist
                                if (ptr_data == 0) {
                                    m_vars[i].direction.bits =
                                        c_parameter_nocopy;
                                }
                            }

                            if (ptr_data != 0) {
                                m_vars[i].flags.sink_addr = 1;
                            }
                        }

                        if (ptr_data != 0) {
                            if (m_is_openmp) {
                                // data is transferred only if
                                // alloc_if == 0 && free_if == 0
                                // or reference count is 1
                                if (!m_vars[i].flags.always_copy &&
                                    ((m_vars[i].alloc_if ||
                                      m_vars[i].free_if) &&
                                     ptr_data->get_reference() != 1)) {
                                    m_vars[i].direction.bits =
                                        c_parameter_nocopy;
                                }
                            }

                            if (ptr_data->alloc_disp != 0) {
                                m_vars[i].flags.alloc_disp = 1;
                                m_in_datalen += sizeof(alloc_disp);
                            }

                            if (m_vars[i].flags.sink_addr) {
                                // get buffers's address on the sink
                                if (!init_mic_address(ptr_data)) {
                                    return false;
                                }

                                m_in_datalen += sizeof(ptr_data->mic_addr);
                            }

                            if (!m_vars[i].flags.pin &&
                                !ptr_data->is_static && m_vars[i].free_if) {
                                // need to decrement buffer reference on target
                                m_need_runfunction = true;
                            }

                            // offset to base from the beginning of the buffer
                            // memory
                            m_vars[i].offset = (char*) base -
                                (char*) ptr_data->cpu_addr.start();

                            // copy other pointer properties to var descriptor
                            m_vars[i].mic_offset = ptr_data->mic_offset;
                            m_vars[i].flags.is_static = ptr_data->is_static;
                        }
                    }
                    else {
                        if (!find_ptr_data(ptr_data,
                                           base,
                                           m_vars[i].disp,
                                           m_vars[i].size,
                                           false, false)) {
                            return false;
                        }
                        if (ptr_data) {
                            m_vars[i].offset =
                                (char*) base -
                                (char*) ptr_data->cpu_addr.start();
                        }
                    }

                    // save pointer data
                    m_vars_extra[i].src_data = ptr_data;
                }
                break;

            case c_func_ptr:
                if (m_vars[i].direction.in) {
                    m_in_datalen += __offload_funcs.max_name_length();
                }
                if (m_vars[i].direction.out) {
                    m_out_datalen += __offload_funcs.max_name_length();
                }
                m_need_runfunction = true;
                break;

            case c_dv_data:
            case c_dv_ptr_data:
            case c_dv_data_slice:
            case c_dv_ptr_data_slice:
                ArrDesc *dvp;
                if (VAR_TYPE_IS_DV_DATA_SLICE(m_vars[i].type.src)) {
                    const Arr_Desc *ap;
                    ap = static_cast<const Arr_Desc*>(m_vars[i].ptr);

                    dvp = (m_vars[i].type.src == c_dv_data_slice) ?
                          reinterpret_cast<ArrDesc*>(ap->base) :
                          *reinterpret_cast<ArrDesc**>(ap->base);
                }
                else {
                    dvp = (m_vars[i].type.src == c_dv_data) ?
                          static_cast<ArrDesc*>(m_vars[i].ptr) :
                          *static_cast<ArrDesc**>(m_vars[i].ptr);
                }

                // if allocatable dope vector isn't allocated don't
                // transfer its data
                if (!__dv_is_allocated(dvp)) {
                    m_vars[i].direction.bits = c_parameter_nocopy;
                    m_vars[i].alloc_if = 0;
                    m_vars[i].free_if = 0;
                }
                if (m_vars[i].direction.bits ||
                    m_vars[i].alloc_if ||
                    m_vars[i].free_if) {
                    const Arr_Desc *ap;

                    if (VAR_TYPE_IS_DV_DATA_SLICE(m_vars[i].type.src)) {
                        ap = static_cast<const Arr_Desc*>(m_vars[i].ptr);

                        // debug dump
                        ARRAY_DESC_DUMP("", "IN/OUT", ap, 0, !src_is_for_mic);
                    }
                    if (!__dv_is_contiguous(dvp)) {
                        m_vars[i].flags.is_noncont_src = 1;
                        m_vars_extra[i].read_rng_src =
                            init_read_ranges_dv(dvp);
                    }

                    // size and displacement
                    if (VAR_TYPE_IS_DV_DATA_SLICE(m_vars[i].type.src)) {
                        // offset and length are derived from the
                        // array descriptor
                        __arr_data_offset_and_length(ap,
                                                     m_vars[i].disp,
                                                     m_vars[i].size);
                        if (m_vars[i].direction.bits) {
                            if (!is_arr_desc_contiguous(ap)) {
                                if (m_vars[i].flags.is_noncont_src) {
                                    LIBOFFLOAD_ERROR(c_slice_of_noncont_array);
                                    return false;
                                }
                                m_vars[i].flags.is_noncont_src = 1;
                                m_vars_extra[i].read_rng_src =
                                    init_read_ranges_arr_desc(ap);
                            }
                        }
                    }
                    else {
                        if (m_vars[i].flags.has_length) {
                            m_vars[i].size =
                                __dv_data_length(dvp, m_vars[i].count);
                        }
                        else {
                            m_vars[i].size = __dv_data_length(dvp);
                        }
                        m_vars[i].disp = 0;
                    }

                    // check that length >= 0
                    if (m_vars[i].alloc_if &&
                        (m_vars[i].disp + m_vars[i].size < 0)) {
                        LIBOFFLOAD_ERROR(c_zero_or_neg_ptr_len);
                        exit(1);
                    }

                    // base address
                    void *base = reinterpret_cast<void*>(dvp->Base);
                    PtrData *ptr_data;

                    // allocate buffer if we have no INTO and don't need
                    // allocation for the ptr at target
                    if (src_is_for_mic) {
                        if (m_vars[i].alloc_if) {
                            // add new entry
                            if (!alloc_ptr_data(
                                    ptr_data,
                                    reinterpret_cast<char *>(base) + alloc_disp,
                                    (alloc_base != NULL) ?
                                        alloc_disp : m_vars[i].disp,
                                    (alloc_base != NULL) ?
                                        alloc_size : m_vars[i].size,
                                    alloc_disp,
                                    (alloc_base != NULL) ?
                                        0 : m_vars[i].align,
                                    m_vars[i].flags.targetptr,
                                    m_vars[i].flags.preallocated,
                                    m_vars[i].flags.pin)) {
                                return false;
                            }

                            if (ptr_data->add_reference() == 0 &&
                                ptr_data->mic_buf != 0) {
                                // add buffer to the list of buffers
                                // that are passed to dispatch call
                                m_compute_buffers.push_back(
                                    ptr_data->mic_buf);
                            }
                            else {
                                // will send buffer address to device
                                m_vars[i].flags.sink_addr = 1;
                            }

                            if (!ptr_data->is_static) {
                                // need to add reference for buffer
                                m_need_runfunction = true;
                            }
                        }
                        else {
                            bool error_if_not_found = true;
                            if (m_is_openmp) {
                                // For omp target update variable is ignored
                                // if it does not exist.
                                if (m_vars[i].flags.always_copy ||
                                    (!m_vars[i].alloc_if &&
                                     !m_vars[i].free_if)) {
                                    error_if_not_found = false;
                                }
                            }

                            // use existing association from pointer table
                            if (!find_ptr_data(ptr_data,
                                               base,
                                               m_vars[i].disp,
                                               m_vars[i].size,
                                               m_vars[i].flags.targetptr,
                                               error_if_not_found)) {
                                return false;
                            }

                            if (m_is_openmp) {
                                // make var nocopy if it does not exist
                                if (ptr_data == 0) {
                                    m_vars[i].direction.bits =
                                        c_parameter_nocopy;
                                }
                            }

                            if (ptr_data != 0) {
                                // need to update base in dope vector on device
                                m_vars[i].flags.sink_addr = 1;
                            }
                        }

                        if (ptr_data != 0) {
                            if (m_is_openmp) {
                                // data is transferred if
                                // - if always modifier is used OR
                                // - if alloc_if == 0 && free_if == 0 OR
                                // - if reference count is 1
                                if (!m_vars[i].flags.always_copy &&
                                    (m_vars[i].alloc_if ||
                                     m_vars[i].free_if) &&
                                    ptr_data->get_reference() != 1) {
                                    m_vars[i].direction.bits =
                                        c_parameter_nocopy;
                                }
                            }

                            if (ptr_data->alloc_disp != 0) {
                                m_vars[i].flags.alloc_disp = 1;
                                m_in_datalen += sizeof(alloc_disp);
                            }

                            if (m_vars[i].flags.sink_addr) {
                                // get buffers's address on the sink
                                if (!init_mic_address(ptr_data)) {
                                    return false;
                                }

                                m_in_datalen += sizeof(ptr_data->mic_addr);
                            }

                            if (!ptr_data->is_static && m_vars[i].free_if) {
                                // need to decrement buffer reference on target
                                m_need_runfunction = true;
                            }

                            // offset to base from the beginning of the buffer
                            // memory
                            m_vars[i].offset =
                                (char*) base -
                                (char*) ptr_data->cpu_addr.start();

                            // copy other pointer properties to var descriptor
                            m_vars[i].mic_offset = ptr_data->mic_offset;
                            m_vars[i].flags.is_static = ptr_data->is_static;
                        }
                    }
                    else { // !src_is_for_mic
                        if (!find_ptr_data(ptr_data,
                                           base,
                                           m_vars[i].disp,
                                           m_vars[i].size,
                                           false, false)) {
                            return false;
                        }
                        m_vars[i].offset = !ptr_data ? 0 :
                                (char*) base -
                                (char*) ptr_data->cpu_addr.start();
                    }

                    // save pointer data
                    m_vars_extra[i].src_data = ptr_data;
                }
                break;

            default:
                LIBOFFLOAD_ERROR(c_unknown_var_type, m_vars[i].type.src);
                LIBOFFLOAD_ABORT;
        }
        if (m_vars[i].type.src == c_data_ptr_array) {
            continue;
        }

        if (src_is_for_mic && m_vars[i].flags.is_stack_buf) {
            m_vars[i].offset = static_cast<char*>(m_vars[i].ptr) -
                m_device.m_persist_list.front().cpu_stack_addr;
        }
        // if source is used at CPU save its offset and disp
        if (m_vars[i].into == NULL || m_vars[i].direction.in) {
            m_vars_extra[i].cpu_offset = m_vars[i].offset;
            m_vars_extra[i].cpu_disp   = m_vars[i].disp;
        }

        // If "into" is define we need to do the similar work for it
        if (!m_vars[i].into) {
            continue;
        }

        int64_t into_disp =0, into_offset = 0;

        switch (m_vars[i].type.dst) {
            case c_data_ptr_array:
                break;
            case c_data:
            case c_void_ptr:
            case c_cean_var: {
                int64_t size = m_vars[i].size;

                if (m_vars[i].type.dst == c_cean_var) {
                    // array descriptor
                    const Arr_Desc *ap =
                        static_cast<const Arr_Desc*>(m_vars[i].into);

                    // debug dump
                    ARRAY_DESC_DUMP("    ", "INTO", ap, 0, src_is_for_mic);

                    // offset and length are derived from the array descriptor
                    __arr_data_offset_and_length(ap, into_disp, size);

                    if (!is_arr_desc_contiguous(ap)) {
                        m_vars[i].flags.is_noncont_dst = 1;
                        m_vars_extra[i].read_rng_dst =
                            init_read_ranges_arr_desc(ap);
                        if (!cean_ranges_match(
                            m_vars_extra[i].read_rng_src,
                            m_vars_extra[i].read_rng_dst)) {
                            LIBOFFLOAD_ERROR(c_ranges_dont_match);
                            exit(1);
                        }
                    }
                    m_vars[i].into = reinterpret_cast<void*>(ap->base);
                }

                int64_t size_src = m_vars_extra[i].read_rng_src ?
                    cean_get_transf_size(m_vars_extra[i].read_rng_src) :
                    m_vars[i].size;
                int64_t size_dst = m_vars_extra[i].read_rng_dst ?
                    cean_get_transf_size(m_vars_extra[i].read_rng_dst) :
                    size;
                // It's supposed that "into" size must be not less
                // than src size
                if (size_src > size_dst) {
                    LIBOFFLOAD_ERROR(c_different_src_and_dstn_sizes,
                                     size_src, size_dst);
                    exit(1);
                }

                if (m_vars[i].direction.bits) {
                    if (m_vars[i].flags.is_static_dstn) {
                        PtrData *ptr_data;

                        // find data associated with variable
                        if (!find_ptr_data(ptr_data, m_vars[i].into,
                                           into_disp, size, false, false)) {
                            return false;
                        }
                        if (ptr_data != 0) {
                            // offset to base from the beginning of the buffer
                            // memory
                            into_offset =
                                (char*) m_vars[i].into -
                                (char*) ptr_data->cpu_addr.start();
                        }
                        else {
                            m_vars[i].flags.is_static_dstn = false;
                        }
                        m_vars_extra[i].dst_data = ptr_data;
                    }
                }

                if (m_vars[i].direction.in &&
                    !m_vars[i].flags.is_static_dstn) {
                    m_in_datalen += m_vars[i].size;

                    // for non-static target destination defined as CEAN
                    // expression we pass to target its size and dist
                    if (m_vars[i].type.dst == c_cean_var) {
                        m_in_datalen += 2 * sizeof(uint64_t);
                    }
                    m_need_runfunction = true;
                }
                break;
            }

            case c_dv:
                if (m_vars[i].direction.bits ||
                    m_vars[i].alloc_if ||
                    m_vars[i].free_if) {
                    ArrDesc *dvp = static_cast<ArrDesc*>(m_vars[i].into);

                    // debug dump
                    __dv_desc_dump("INTO", dvp);

                    // send dope vector contents excluding base
                    m_in_datalen += m_vars[i].size - sizeof(uint64_t);
                    m_need_runfunction = true;
                }
                break;

            case c_string_ptr:
            case c_data_ptr:
            case c_cean_var_ptr:
            case c_dv_ptr: {
                int64_t size = m_vars[i].size;

                if (m_vars[i].type.dst == c_cean_var_ptr) {
                    // array descriptor
                    const Arr_Desc *ap =
                        static_cast<const Arr_Desc*>(m_vars[i].into);

                    // debug dump
                    ARRAY_DESC_DUMP("    ", "INTO", ap, 1, src_is_for_mic);

                    // offset and length are derived from the array descriptor
                    __arr_data_offset_and_length(ap, into_disp, size);

                    if (!is_arr_desc_contiguous(ap)) {
                        m_vars[i].flags.is_noncont_src = 1;
                        m_vars_extra[i].read_rng_dst =
                            init_read_ranges_arr_desc(ap);
                        if (!cean_ranges_match(
                            m_vars_extra[i].read_rng_src,
                            m_vars_extra[i].read_rng_dst)) {
                            LIBOFFLOAD_ERROR(c_ranges_dont_match);
                        }
                    }
                    m_vars[i].into = reinterpret_cast<char**>(ap->base);
                }
                else if (m_vars[i].type.dst == c_dv_ptr) {
                    // need to send DV to the device unless it is 'nocopy'
                    if (m_vars[i].direction.bits ||
                        m_vars[i].alloc_if ||
                        m_vars[i].free_if) {
                        ArrDesc *dvp = *static_cast<ArrDesc**>(m_vars[i].into);

                        // debug dump
                        __dv_desc_dump("INTO", dvp);

                        m_vars[i].direction.bits = c_parameter_in;
                    }
                }

                int64_t size_src = m_vars_extra[i].read_rng_src ?
                    cean_get_transf_size(m_vars_extra[i].read_rng_src) :
                    m_vars[i].size;
                int64_t size_dst = m_vars_extra[i].read_rng_dst ?
                    cean_get_transf_size(m_vars_extra[i].read_rng_dst) :
                    size;
                // It's supposed that "into" size must be not less than
                // src size
                if (size_src > size_dst) {
                    LIBOFFLOAD_ERROR(c_different_src_and_dstn_sizes,
                                     size_src, size_dst);
                    exit(1);
                }

                if (m_vars[i].direction.bits) {
                    PtrData *ptr_data;

                    // base address
                    void *base = *static_cast<void**>(m_vars[i].into);

                    if (m_vars[i].direction.in) {
                        // allocate buffer
                        if (m_vars[i].flags.is_stack_buf) {
                            // for stack persistent objects ptr data is created
                            // by var_desc with number 0.
                            // Its ptr_data is stored at m_stack_ptr_data
                            ptr_data = m_stack_ptr_data;
                            m_vars[i].flags.sink_addr = 1;
                        }
                        else if (m_vars[i].alloc_if) {
                            if (m_vars[i].flags.preallocated) {
                                m_out_datalen += sizeof(void*);
                                m_need_runfunction = true;
                                break;
                            }
                            // add new entry
                            if (!alloc_ptr_data(
                                    ptr_data,
                                    reinterpret_cast<char *>(base) + alloc_disp,
                                    (alloc_base != NULL) ?
                                        alloc_disp : into_disp,
                                    (alloc_base != NULL) ?
                                        alloc_size : size,
                                    alloc_disp,
                                    (alloc_base != NULL) ?
                                        0 : m_vars[i].align,
                                    m_vars[i].flags.targetptr,
                                    m_vars[i].flags.preallocated,
                                    m_vars[i].flags.pin)) {
                                return false;
                            }
                            if (m_vars[i].flags.targetptr) {
                                if (!init_mic_address(ptr_data)) {
                                    return false;
                                }
                                *static_cast<void**>(m_vars[i].into) = base =
                                    reinterpret_cast<void*>(ptr_data->mic_addr);
                            }
                            if (ptr_data->add_reference() == 0 &&
                                ptr_data->mic_buf != 0) {
                                // add buffer to the list of buffers that
                                // are passed to dispatch call
                                m_compute_buffers.push_back(
                                    ptr_data->mic_buf);
                            }
                            else {
                                // will send buffer address to device
                                m_vars[i].flags.sink_addr = 1;
                            }

                            if (!ptr_data->is_static) {
                                // need to add reference for buffer
                                m_need_runfunction = true;
                            }
                        }
                        else {
                            // use existing association from pointer table
                            if (!find_ptr_data(ptr_data, base, into_disp,
                                    size, m_vars[i].flags.targetptr, true)) {
                                return false;
                            }
                            m_vars[i].flags.sink_addr = 1;
                        }

                        if (ptr_data->alloc_disp != 0) {
                            m_vars[i].flags.alloc_disp = 1;
                            m_in_datalen += sizeof(alloc_disp);
                        }

                        if (m_vars[i].flags.sink_addr) {
                            // get buffers's address on the sink
                            if (!init_mic_address(ptr_data)) {
                                return false;
                            }

                            m_in_datalen += sizeof(ptr_data->mic_addr);
                        }

                        if (!ptr_data->is_static && m_vars[i].free_if) {
                            // need to decrement buffer reference on target
                            m_need_runfunction = true;
                        }

                        // copy other pointer properties to var descriptor
                        m_vars[i].mic_offset = ptr_data->mic_offset;
                        m_vars[i].flags.is_static_dstn = ptr_data->is_static;
                    }
                    else {
                        if (!find_ptr_data(ptr_data,
                                           base,
                                           into_disp,
                                           m_vars[i].size,
                                           false, false)) {
                            return false;
                        }
                    }
                    if (ptr_data) {
                        into_offset = ptr_data ?
                            (char*) base -
                            (char*) ptr_data->cpu_addr.start() :
                            0;
                    }
                    // save pointer data
                    m_vars_extra[i].dst_data = ptr_data;
                }
                break;
            }

            case c_func_ptr:
                break;

            case c_dv_data:
            case c_dv_ptr_data:
            case c_dv_data_slice:
            case c_dv_ptr_data_slice:
                if (m_vars[i].direction.bits ||
                    m_vars[i].alloc_if ||
                    m_vars[i].free_if) {
                    const Arr_Desc *ap;
                    ArrDesc *dvp;
                    PtrData *ptr_data;
                    int64_t disp;
                    int64_t size;

                    if (VAR_TYPE_IS_DV_DATA_SLICE(m_vars[i].type.dst)) {
                        ap = static_cast<const Arr_Desc*>(m_vars[i].into);

                        // debug dump
                        ARRAY_DESC_DUMP("    ", "INTO", ap, 0, src_is_for_mic);

                        dvp = (m_vars[i].type.dst == c_dv_data_slice) ?
                              reinterpret_cast<ArrDesc*>(ap->base) :
                              *reinterpret_cast<ArrDesc**>(ap->base);
                    }
                    else {
                        dvp = (m_vars[i].type.dst == c_dv_data) ?
                              static_cast<ArrDesc*>(m_vars[i].into) :
                              *static_cast<ArrDesc**>(m_vars[i].into);
                    }
                    if (!__dv_is_contiguous(dvp)) {
                        m_vars[i].flags.is_noncont_dst = 1;
                        m_vars_extra[i].read_rng_dst =
                            init_read_ranges_dv(dvp);
                    }
                    // size and displacement
                    if (VAR_TYPE_IS_DV_DATA_SLICE(m_vars[i].type.dst)) {
                        // offset and length are derived from the array
                        // descriptor
                        __arr_data_offset_and_length(ap, into_disp, size);
                        if (m_vars[i].direction.bits) {
                            if (!is_arr_desc_contiguous(ap)) {
                                if (m_vars[i].flags.is_noncont_dst) {
                                    LIBOFFLOAD_ERROR(c_slice_of_noncont_array);
                                    return false;
                                }
                                m_vars[i].flags.is_noncont_dst = 1;
                                m_vars_extra[i].read_rng_dst =
                                    init_read_ranges_arr_desc(ap);
                                if (!cean_ranges_match(
                                    m_vars_extra[i].read_rng_src,
                                    m_vars_extra[i].read_rng_dst)) {
                                    LIBOFFLOAD_ERROR(c_ranges_dont_match);
                                }
                            }
                        }
                    }
                    else {
                        if (m_vars[i].flags.has_length) {
                            size = __dv_data_length(dvp, m_vars[i].count);
                        }
                        else {
                            size = __dv_data_length(dvp);
                        }
                        disp = 0;
                    }

                    int64_t size_src =
                        m_vars_extra[i].read_rng_src ?
                        cean_get_transf_size(m_vars_extra[i].read_rng_src) :
                        m_vars[i].size;
                    int64_t size_dst =
                        m_vars_extra[i].read_rng_dst ?
                        cean_get_transf_size(m_vars_extra[i].read_rng_dst) :
                        size;
                    // It's supposed that "into" size must be not less
                    // than src size
                    if (size_src > size_dst) {
                        LIBOFFLOAD_ERROR(c_different_src_and_dstn_sizes,
                            size_src, size_dst);
                        exit(1);
                    }

                    // base address
                    void *base = reinterpret_cast<void*>(dvp->Base);

                    // allocate buffer
                    if (m_vars[i].direction.in) {
                        if (m_vars[i].alloc_if) {
                            // add new entry
                            if (!alloc_ptr_data(
                                    ptr_data,
                                    reinterpret_cast<char *>(base) + alloc_disp,
                                    (alloc_base != NULL) ?
                                        alloc_disp : into_disp,
                                    (alloc_base != NULL) ?
                                        alloc_size : size,
                                    alloc_disp,
                                    (alloc_base != NULL) ?
                                        0 : m_vars[i].align,
                                    m_vars[i].flags.targetptr,
                                    m_vars[i].flags.preallocated,
                                    m_vars[i].flags.pin)) {
                                return false;
                            }
                            if (ptr_data->add_reference() == 0 &&
                                ptr_data->mic_buf !=0) {
                                // add buffer to the list of buffers
                                // that are passed to dispatch call
                                m_compute_buffers.push_back(
                                    ptr_data->mic_buf);
                            }
                            else {
                                // will send buffer address to device
                                m_vars[i].flags.sink_addr = 1;
                            }

                            if (!ptr_data->is_static) {
                                // need to add reference for buffer
                                m_need_runfunction = true;
                            }
                        }
                        else {
                            // use existing association from pointer table
                            if (!find_ptr_data(ptr_data, base, into_disp,
                                size, m_vars[i].flags.targetptr, true)) {
                                return false;
                            }

                            // need to update base in dope vector on device
                            m_vars[i].flags.sink_addr = 1;
                        }

                        if (ptr_data->alloc_disp != 0) {
                            m_vars[i].flags.alloc_disp = 1;
                            m_in_datalen += sizeof(alloc_disp);
                        }

                        if (m_vars[i].flags.sink_addr) {
                            // get buffers's address on the sink
                            if (!init_mic_address(ptr_data)) {
                                return false;
                            }
                            m_in_datalen += sizeof(ptr_data->mic_addr);
                        }

                        if (!ptr_data->is_static && m_vars[i].free_if) {
                            // need to decrement buffer reference on target
                            m_need_runfunction = true;
                        }

                        // offset to base from the beginning of the buffer
                        // memory
                        into_offset =
                            (char*) base - (char*) ptr_data->cpu_addr.start();

                        // copy other pointer properties to var descriptor
                        m_vars[i].mic_offset = ptr_data->mic_offset;
                        m_vars[i].flags.is_static_dstn = ptr_data->is_static;
                    }
                    else { // src_is_for_mic
                        if (!find_ptr_data(ptr_data,
                                           base,
                                           into_disp,
                                           size,
                                           false, false)) {
                            return false;
                        }
                        into_offset = !ptr_data ?
                            0 :
                            (char*) base - (char*) ptr_data->cpu_addr.start();
                    }

                    // save pointer data
                    m_vars_extra[i].dst_data = ptr_data;
                }
                break;

            default:
                LIBOFFLOAD_ERROR(c_unknown_var_type, m_vars[i].type.src);
                LIBOFFLOAD_ABORT;
        }
        // if into is used at CPU save its offset and disp
        if (m_vars[i].direction.out) {
            m_vars_extra[i].cpu_offset = into_offset;
            m_vars_extra[i].cpu_disp   = into_disp;
        }
        else {
            if (m_vars[i].flags.is_stack_buf) {
                into_offset = static_cast<char*>(m_vars[i].into) -
                    m_device.m_persist_list.front().cpu_stack_addr;
            }
            m_vars[i].offset = into_offset;
            m_vars[i].disp   = into_disp;
        }
    }

    return true;
}

bool OffloadDescriptor::setup_misc_data(const char *name)
{
    OffloadTimer timer(get_timer_data(), c_offload_host_setup_misc_data);

    // we can skip run functon call together with wait if offloaded
    // region is empty and there is no user defined non-pointer IN/OUT data
    if (m_need_runfunction) {
        // variable descriptors are sent as input data
        m_in_datalen += m_vars_total * sizeof(VarDesc);

        // timer data is sent as a part of the output data
        m_out_datalen += OFFLOAD_TIMER_DATALEN();

        // max from input data and output data length
        uint64_t data_len = m_in_datalen > m_out_datalen ? m_in_datalen :
                                                           m_out_datalen;

        // Misc data has the following layout
        //     <Function Descriptor>
        //     <Function Name>
        //     <In/Out Data>            (optional)
        //
        // We can transfer copyin/copyout data in misc/return data which can
        // be passed to run function call if its size does not exceed
        // COI_PIPELINE_MAX_IN_MISC_DATA_LEN. Otherwise we have to allocate
        // buffer for it.

        m_func_desc_size = sizeof(FunctionDescriptor) + strlen(name) + 1;
        m_func_desc_size = (m_func_desc_size + 7) & ~7;

        int misc_data_offset = 0;
        int misc_data_size = 0;
        if (data_len > 0) {
            if (m_func_desc_size +
                m_in_datalen <= COI_PIPELINE_MAX_IN_MISC_DATA_LEN &&
                m_out_datalen <= COI_PIPELINE_MAX_IN_MISC_DATA_LEN) {
                // use misc/return data for copyin/copyout
                misc_data_offset = m_func_desc_size;
                misc_data_size = data_len;
            }
            else {
                OffloadTimer timer_buf(get_timer_data(),
                                       c_offload_host_alloc_data_buffer);

                // send/receive data using buffer
                COIRESULT res = COI::BufferCreate(data_len,
                                                  COI_BUFFER_NORMAL,
                                                  0, 0,
                                                  1, &m_device.get_process(),
                                                  &m_inout_buf);
                if (res != COI_SUCCESS) {
                    if (m_status != 0) {
                        m_status->result = translate_coi_error(res);
                        return false;
                    }
                    report_coi_error(c_buf_create, res);
                }

                m_compute_buffers.push_back(m_inout_buf);
                m_destroy_buffers.push_back(m_inout_buf);
            }
        }

        // initialize function descriptor
        m_func_desc = (FunctionDescriptor*) calloc(1, m_func_desc_size
						      + misc_data_size);
        if (m_func_desc == NULL)
          LIBOFFLOAD_ERROR(c_malloc);
        m_func_desc->console_enabled = console_enabled;
        m_func_desc->timer_enabled = offload_report_enabled &&
            (timer_enabled || offload_report_level);
        m_func_desc->offload_report_level = offload_report_enabled ?
                                              offload_report_level : 0;
        m_func_desc->offload_number = GET_OFFLOAD_NUMBER(get_timer_data());
        m_func_desc->in_datalen = m_in_datalen;
        m_func_desc->out_datalen = m_out_datalen;
        m_func_desc->vars_num = m_vars_total;
        m_func_desc->data_offset = misc_data_offset;

        // append entry name
        strcpy(m_func_desc->data, name);
    }

    return true;
}

void OffloadDescriptor::setup_omp_async_info()
{
    OFFLOAD_TRACE(2, "setup_omp_async_info\n");
    OmpAsyncLastEventType event_type = m_need_runfunction ?
                                   c_last_runfunc : c_last_write;
    int last_in = m_need_runfunction ? 0 : -1;
    int i;

    for (i = m_vars_total - 1; i >=0; i--) {
                switch (m_vars[i].type.dst) {
                    case c_data:
                    case c_void_ptr:
                    case c_cean_var:
                        if (m_vars[i].direction.out &&
                            m_vars[i].flags.is_static_dstn) {
                            event_type = c_last_read;
                        }
                        else if (last_in < 0 && m_vars[i].direction.in &&
                            m_vars[i].flags.is_static_dstn) {
                            last_in = i;
                        }
                        break;
                    case c_string_ptr:
                    case c_data_ptr:
                    case c_cean_var_ptr:
                    case c_dv_ptr:
                    case c_dv_data:
                    case c_dv_ptr_data:
                    case c_dv_data_slice:
                    case c_dv_ptr_data_slice:
                    
                        if (m_vars[i].direction.out) {                        
                            event_type = c_last_read;
                        }
                        else if (last_in < 0 && m_vars[i].direction.in) {
                            last_in = i;
                        }
                        break;
                    default:
                        break;
                }
             if (event_type == c_last_read) {
                 break;
             }
        }
        
        if (event_type == c_last_read) {
            m_vars_extra[i].omp_last_event_type = c_last_read;
        }
        else if (event_type == c_last_write) {
            m_vars_extra[last_in].omp_last_event_type = c_last_write;        
        }
        m_omp_async_last_event_type = event_type;
    OFFLOAD_TRACE(2, "setup_omp_async_info: event_type=%d\n",
                  m_omp_async_last_event_type);
}

extern "C" {
    void offload_proxy_task_completed_ooo(
        COIEVENT e,
        const COIRESULT r,
        const void *info
    )
    {
	task_completion_callback ((void *) info);
    }
}

void OffloadDescriptor::register_omp_event_call_back(
    const COIEVENT *event,
    const void *info)
{
    OFFLOAD_TRACE(2, "register_omp_event_call_back(event=%p, info=%p)\n",
                  event, info);
    if (COI::EventRegisterCallback) {
        COI::EventRegisterCallback(
                 *event,
                 &offload_proxy_task_completed_ooo,
                 info, 0);
        OFFLOAD_TRACE(2,
            "COI::EventRegisterCallback found; callback registered\n");
    }
}
        
bool OffloadDescriptor::wait_dependencies(
    const void    **waits,
    int             num_waits,
    _Offload_stream handle
)
{
    OffloadTimer timer(get_timer_data(), c_offload_host_wait_deps);
    bool ret = true;
    OffloadDescriptor *task;
    if (num_waits == 0) {
        return true;
    }

    // wait for streams
    if (num_waits == -1) {
        Stream * stream;
        // some specific stream of the device
        if (handle != 0) {
            stream = Stream::find_stream(handle, false);

            // the stream was not created or was destroyed
            if (!stream) {
                LIBOFFLOAD_ERROR(c_offload_no_stream, m_device.get_logical_index());
                LIBOFFLOAD_ABORT;
            }
            task = stream->get_last_offload();

            // offload was completed by previous offload_wait pragma
            // or wait clause
            if (task == 0) {
                return true;
            }
            if (!task->offload_finish(0)) { //arg is 0 for is_traceback
                ret = false;
            }
            task->cleanup();
            stream->set_last_offload(NULL);
            delete task;
        }
        // all streams of the device or over all devices
        else {
            StreamMap stream_map = Stream::all_streams;
            for (StreamMap::iterator it = stream_map.begin();
                it != stream_map.end(); it++) {
                Stream * stream = it->second;

                if (!m_wait_all_devices &&
                    stream->get_device() != m_device.get_logical_index()) {
                    continue;
                }
                // get associated async task
                OffloadDescriptor *task = stream->get_last_offload();

                // offload was completed by offload_wait pragma or wait clause
                if (task == 0) {
                    continue;
                }
                if (!task->offload_finish(0)) { //arg is 0 for is_traceback
                    ret = false;
                }
                task->cleanup();
                stream->set_last_offload(NULL);
                delete task;
            }
            // no uncompleted streams
            return true;
        }
    }
    else {
        // if handle is equal to no_stream it's wait for signals
        for (int i = 0; i < num_waits; i++) {
            _Offload_stream stream_handle;
            Stream *stream;
            task = m_device.find_signal(waits[i], true);
            if (task == 0) {
                LIBOFFLOAD_ERROR(c_offload1, m_device.get_logical_index(),
                    waits[i]);
                LIBOFFLOAD_ABORT;
            }
            else if (task == SIGNAL_IS_REMOVED) {
                continue;
            }
            if (!task->offload_finish(0)) { //arg is 0 for is_traceback
                ret = false;
            }
            task->cleanup();
            // if the offload both has signal and is last offload of its
            // stream, we must wipe out the "last_offload" reference as
            // the offload already is finished.
            stream_handle = task->m_stream;
            if (stream_handle != -1) {
                stream = Stream::find_stream(stream_handle, false);
                if (stream && stream->get_last_offload() == task) {
                    stream->set_last_offload(NULL);
                }
            }
            delete task;
        }
    }
    return ret;
}

bool OffloadDescriptor::offload_wrap(
    const char *name,
    bool is_empty,
    VarDesc *vars,
    VarDesc2 *vars2,
    int vars_total,
    const void **waits,
    int num_waits,
    const void **signal,
    int entry_id,
    const void *stack_addr,
    OffloadFlags offload_flags
)
{
    OffloadWaitKind wait_kind = c_offload_wait_signal;
    bool is_traceback = offload_flags.bits.fortran_traceback;

    // define kind of wait if any;
    // there can be one off the following kind:
    // 1. c_offload_wait_signal for "offload_wait wait(signal)"
    // 2. c_offload_wait_stream for "offload_wait stream(stream)"
    // 3. c_offload_wait_all_streams for "offload_wait stream(0)"
    if (num_waits == -1) {
        wait_kind = (m_stream == 0) ?
                    c_offload_wait_all_streams :
                    c_offload_wait_stream;
    }
    char buf[35];
    const char *stream_str;

    if (m_stream == no_stream || num_waits >= 0) {
        stream_str = "none";
    }
    else if (m_stream == 0) {
        stream_str = "all";
    }
    else {
        sprintf(buf, "%#llx", m_stream);
        stream_str = buf;
    }

    if (signal == 0) {
        OFFLOAD_DEBUG_TRACE_1(1,
                      GET_OFFLOAD_NUMBER(get_timer_data()),
                      c_offload_init_func,
                      "Offload function %s, is_empty=%d, #varDescs=%d, "
                      "signal=none, stream=%s, #waits=%d%c",
                      name, is_empty, vars_total, stream_str, num_waits,
                      num_waits == 0 ? '\n' : ' ');
        // Breaks the norm of using OFFLOAD_DEBUG_TRACE to print the waits
        // since the number of waits is not fixed.
        if (!OFFLOAD_DO_TRACE && (console_enabled >= 1)) {
            if (num_waits) {
                printf("(");
                if (m_stream == no_stream) {
                    printf("%p", waits[0]);
                    for (int i = 1; i < num_waits; i++) {
                        printf(", %p", waits[i]);
                    }
                }
                else if (m_stream != 0) {
                    printf("%#x", m_stream);
                }
                else {
                    printf(" all streams");
                }
                printf(")");
            }
            printf("\n");
            fflush(NULL);
        }
        // stream in wait is reported further in OFFLOAD_REPORT for waits
        if (m_stream != no_stream && num_waits == 0) {
            OFFLOAD_REPORT(3, GET_OFFLOAD_NUMBER(get_timer_data()),
                           c_offload_stream,
                           "%d\n", m_stream);
        }
        OFFLOAD_REPORT(3, GET_OFFLOAD_NUMBER(get_timer_data()),
                      c_offload_signal,
                      "none %d\n", 0);
    }
    else {
        OFFLOAD_DEBUG_TRACE_1(1,
                      GET_OFFLOAD_NUMBER(get_timer_data()),
                      c_offload_init_func,
                      "Offload function %s, is_empty=%d, #varDescs=%d, "
                      "signal=%p, stream=%s, #waits=%d%c",
                      name, is_empty, vars_total, *signal, stream_str, num_waits,
                      num_waits == 0 ? '\n' : ' ');
        // Breaks the norm of using OFFLOAD_DEBUG_TRACE to print the waits
        // since the number of waits is not fixed.
        if (!OFFLOAD_DO_TRACE && (console_enabled >= 1)) {
            if (num_waits) {
                printf("(");
                if (m_stream == no_stream) {
                    printf("%p", waits[0]);
                    for (int i = 1; i < num_waits; i++) {
                        printf(", %p", waits[i]);
                    }
                    printf(")");
                }
                else if (m_stream != 0) {
                    printf("%#x", m_stream);
                }
                else {
                    printf(" all streams");
                }
                printf(")");
            }
            printf("\n");
            fflush(NULL);
        }
        // stream in wait is reported further in OFFLOAD_REPORT for waits
        if (m_stream != no_stream && num_waits == 0) {
            OFFLOAD_REPORT(3, GET_OFFLOAD_NUMBER(get_timer_data()),
                           c_offload_stream,
                           "%d\n", m_stream);
        }
        OFFLOAD_REPORT(3, GET_OFFLOAD_NUMBER(get_timer_data()),
                      c_offload_signal,
                      "%d\n", signal);
    }
    if (console_enabled >= 1 && offload_flags.flags != 0) {
        trace_offload_flags(get_timer_data(), offload_flags);
    }

    OFFLOAD_REPORT(3, GET_OFFLOAD_NUMBER(get_timer_data()),
                   c_offload_wait, "%d\n",
                   wait_kind, num_waits,
                   (wait_kind == c_offload_wait_signal) ?
                   waits :
                   reinterpret_cast<const void **>(m_stream));

    if (m_status != 0) {
        m_status->result = OFFLOAD_SUCCESS;
        m_status->device_number = m_device.get_logical_index();
    }

    m_initial_need_runfunction = m_need_runfunction = !is_empty;

    // wait for dependencies to finish
    if (!wait_dependencies(waits, num_waits, m_stream)) {
        cleanup();
        return false;
    }

    // setup buffers
    if (!setup_descriptors(vars, vars2, vars_total, entry_id, stack_addr)) {
        cleanup();
        return false;
    }

    if (offload_flags.bits.omp_async) {
        setup_omp_async_info();
    }
    
    // initiate send for pointers. Want to do it as early as possible.
    if (!send_pointer_data(signal != 0 || offload_flags.bits.omp_async,
                           signal)) {
        cleanup();
        return false;
    }

    // setup misc data for run function
    if (!setup_misc_data(name)) {
        cleanup();
        return false;
    }

    // gather copyin data into buffer
    if (!gather_copyin_data()) {
        cleanup();
        return false;
    }

    // Start the computation
    if (!compute(signal)) {
        cleanup();
        return false;
    }

    // initiate receive for pointers
    if (!receive_pointer_data(signal != 0 || offload_flags.bits.omp_async,
                              true, signal)) {
        cleanup();
        return false;
    }
    if (offload_flags.bits.omp_async) {
        return true;
    }
    // if there is a signal or stream save descriptor for the later use.
    // num_waits == -1 is for offload_wait and there is nothing to save
    if (num_waits != -1 && (signal != 0 || m_stream != no_stream)) {
        if (signal != 0) {
            m_device.add_signal(*signal, this);
        }

        if (m_stream != no_stream && m_stream != 0) {
            Stream* stream = Stream::find_stream(m_stream, false);
            if (stream) {
                stream->set_last_offload(this);
            }
            else {
                LIBOFFLOAD_ERROR(c_offload_no_stream, m_device.get_logical_index());
                LIBOFFLOAD_ABORT;
            }
        }
        // if there is a clause with alloc_if(1) and preallocated need to call
        // offload_finish after runfunction
        if (!m_preallocated_alloc) {
            return true;
        }
    }

    // wait for the offload to finish.
    if (!offload_finish(is_traceback)) {
        cleanup();
        return false;
    }

    cleanup();
    return true;
}

bool OffloadDescriptor::offload(
    const char *name,
    bool is_empty,
    VarDesc *vars,
    VarDesc2 *vars2,
    int vars_total,
    const void **waits,
    int num_waits,
    const void **signal,
    int entry_id,
    const void *stack_addr,
    OffloadFlags offload_flags
)
{
    bool res;
    res = offload_wrap(name, is_empty, vars, vars2, vars_total,
                       waits, num_waits, signal, entry_id,
                       stack_addr, offload_flags);
    if (res == false && !m_traceback_called) {
        if (offload_flags.bits.fortran_traceback) {
            OFFLOAD_TRACE(3,
                "Calling Fortran library to continue traceback from MIC\n");
            FORTRAN_TRACE_BACK(m_status->result);
            m_traceback_called = true;
        }
    }
    return res;
}

bool OffloadDescriptor::offload_finish(
    bool is_traceback
)
{
    COIRESULT res;

    // wait for compute dependencies to become signaled
    if (m_in_deps_total > 0) {
        OffloadTimer timer(get_timer_data(), c_offload_host_wait_compute);

        if (__offload_active_wait) {
            // keep CPU busy
            do {
                res = COI::EventWait(m_in_deps_total, m_in_deps, 0, 1, 0, 0);
            }
            while (res == COI_TIME_OUT_REACHED);
        }
        else {
            res = COI::EventWait(m_in_deps_total, m_in_deps, -1, 1, 0, 0);
        }

        if (res != COI_SUCCESS) {
            if (m_status != 0 && !m_traceback_called) {
                m_status->result = translate_coi_error(res);
                if (is_traceback) {
                    OFFLOAD_TRACE(3,
                    "Calling Fortran library to continue traceback from MIC\n");
                    FORTRAN_TRACE_BACK(m_status->result);
                    m_traceback_called = true;
                }
                return false;
            }

            if (is_traceback && !m_traceback_called) {
                OFFLOAD_TRACE(3,
                  "Calling Fortran library to continue traceback from MIC\n");
                FORTRAN_TRACE_BACK(OFFLOAD_ERROR);
                m_traceback_called = true;
            }

            report_coi_error(c_event_wait, res);
        }
    }

    // scatter copyout data received from target
    if (!scatter_copyout_data()) {
        return false;
    }

    if (m_out_with_preallocated &&
        !receive_pointer_data(m_out_deps_total > 0, false, NULL)) {
        cleanup();
        return false;
    }

    // wait for receive dependencies to become signaled
    if (m_out_deps_total > 0) {
        OffloadTimer timer(get_timer_data(), c_offload_host_wait_buffers_reads);

        if (__offload_active_wait) {
            // keep CPU busy
            do {
                res = COI::EventWait(m_out_deps_total, m_out_deps, 0, 1, 0, 0);
            }
            while (res == COI_TIME_OUT_REACHED);
        }
        else {
            res = COI::EventWait(m_out_deps_total, m_out_deps, -1, 1, 0, 0);
        }

        if (res != COI_SUCCESS) {
            if (m_status != 0) {
                m_status->result = translate_coi_error(res);
                return false;
            }
            report_coi_error(c_event_wait, res);
        }
    }

    // destroy buffers
    {
        OffloadTimer timer(get_timer_data(), c_offload_host_destroy_buffers);

        for (BufferList::const_iterator it = m_destroy_buffers.begin();
             it != m_destroy_buffers.end(); it++) {
            res = COI::BufferDestroy(*it);
            if (res != COI_SUCCESS) {
                if (m_status != 0) {
                    m_status->result = translate_coi_error(res);
                    return false;
                }
                report_coi_error(c_buf_destroy, res);
            }
        }
    }

    return true;
}

void OffloadDescriptor::cleanup()
{
    // release device in orsl
    ORSL::release(m_device.get_logical_index());

    OFFLOAD_TIMER_STOP(get_timer_data(), c_offload_host_total_offload);

    // report stuff
    Offload_Report_Epilog(get_timer_data());
}

bool OffloadDescriptor::is_signaled()
{
    bool signaled = true;
    COIRESULT res;

    // check compute and receive dependencies
    if (m_in_deps_total > 0) {
        res = COI::EventWait(m_in_deps_total, m_in_deps, 0, 1, 0, 0);
        signaled = signaled && (res == COI_SUCCESS);
    }
    if (m_out_deps_total > 0) {
        res = COI::EventWait(m_out_deps_total, m_out_deps, 0, 1, 0, 0);
        signaled = signaled && (res == COI_SUCCESS);
    }

    return signaled;
}

static Arr_Desc * make_arr_desc(
    void*   ptr_val,
    int64_t extent_start_val,
    int64_t extent_elements_val,
    int64_t size
)
{
    Arr_Desc *res;
    res = (Arr_Desc *)malloc(sizeof(Arr_Desc));
    if (res == NULL)
      LIBOFFLOAD_ERROR(c_malloc);
    res->base = reinterpret_cast<int64_t>(ptr_val);
    res->rank = 1;
    res->dim[0].size = size;
    res->dim[0].lindex = 0;
    res->dim[0].lower = extent_start_val;
    res->dim[0].upper = extent_elements_val + extent_start_val - 1;
    res->dim[0].stride = 1;
    return res;
}

// Send pointer data if source or destination or both of them are
// noncontiguous. There is guarantee that length of destination enough for
// transferred data.
bool OffloadDescriptor::send_noncontiguous_pointer_data(
    int i,
    PtrData* src_data,
    PtrData* dst_data,
    COIEVENT *event,
    uint64_t &data_sent,
    uint32_t in_deps_amount,
    COIEVENT *in_deps
    )
{
    int64_t offset_src, offset_dst;
    int64_t length_src, length_dst;
    int64_t length_src_cur, length_dst_cur;
    int64_t send_size;
    COIRESULT res;
    bool dst_is_empty = true;
    bool src_is_empty = true;

    data_sent = 0;

    // Set length_src and length_dst
    length_src = (m_vars_extra[i].read_rng_src) ?
        m_vars_extra[i].read_rng_src->range_size : m_vars[i].size;
    length_dst = !m_vars[i].into ? length_src :
                     (m_vars_extra[i].read_rng_dst) ?
                     m_vars_extra[i].read_rng_dst->range_size : m_vars[i].size;
    send_size = (length_src < length_dst) ? length_src : length_dst;

    // If BufferWriteMultiD is defined we can set values of required arguments
    // and transfer noncontiguous data via call to the COI routine.
    if (__offload_use_coi_noncontiguous_transfer && COI::BufferWriteMultiD) {
        struct Arr_Desc* arr_desc_dst;
        struct Arr_Desc* arr_desc_src;
        int64_t size_src, size_dst;
        char *base = offload_get_src_base(static_cast<char*>(m_vars[i].ptr),
            m_vars[i].type.src);
        COIBUFFER dst_buf = m_vars[i].into ?
            m_vars_extra[i].dst_data->mic_buf :
            m_vars_extra[i].src_data->mic_buf;

        offset_src = (m_vars_extra[i].read_rng_src)?
            m_vars_extra[i].read_rng_src->init_offset : m_vars_extra[i].cpu_disp;
        size_src = m_vars_extra[i].read_rng_src ?
            cean_get_transf_size(m_vars_extra[i].read_rng_src) :
            m_vars[i].size;

        offset_dst = (m_vars_extra[i].read_rng_dst)?
            m_vars_extra[i].read_rng_dst->init_offset : m_vars[i].disp;
        size_dst = m_vars_extra[i].read_rng_dst ?
            cean_get_transf_size(m_vars_extra[i].read_rng_dst) : m_vars[i].size;

        int64_t el_size = (!m_vars[i].into ||
            (m_vars_extra[i].read_rng_src && m_vars_extra[i].read_rng_dst)) ?
            1 :
            m_vars_extra[i].read_rng_src ?
            m_vars_extra[i].read_rng_src->arr_desc->dim[
                m_vars_extra[i].read_rng_src->arr_desc->rank - 1].size :
            m_vars_extra[i].read_rng_dst->arr_desc->dim[
                m_vars_extra[i].read_rng_dst->arr_desc->rank - 1].size;

        arr_desc_src = (m_vars_extra[i].read_rng_src) ?
                m_vars_extra[i].read_rng_src->arr_desc :
                make_arr_desc(NULL, // don't required for source
                    offset_src/el_size, size_src/el_size, el_size);

        arr_desc_dst = !m_vars[i].into ?
                arr_desc_src :
                (m_vars_extra[i].read_rng_dst) ?
                    m_vars_extra[i].read_rng_dst->arr_desc :
                    make_arr_desc(NULL,
                        offset_dst/el_size, size_src/el_size, el_size);

        int64_t alloc_disp = m_vars[i].into ?
                    m_vars_extra[i].dst_data->alloc_disp :
                    m_vars_extra[i].src_data->alloc_disp;

        arr_desc_src->base = reinterpret_cast<int64_t>(base);
        arr_desc_dst->base = 0;

        res = COI::BufferWriteMultiD(
            dst_buf,              // in_DestBuffer,
            m_device.get_process(),      // DestProcess,
            m_vars[i].offset + m_vars[i].mic_offset -
            alloc_disp,           // Offset
            (void*)arr_desc_dst,         // descriptor of DestArray
            (void*)arr_desc_src,         // descriptor of SrcArray
            COI_COPY_UNSPECIFIED, // Type
            in_deps_amount,       // Number of in Dependencies
            in_deps,              // array of in Dependencies
            event);               // out Dependency
        if (res != COI_SUCCESS) {
            if (m_status != 0) {
                m_status->result = translate_coi_error(res);
                return false;
            }
            report_coi_error(c_buf_copy, res);
        }
        return(true);
    }

    // if event is defined we must multiplate it for all contiguous intervals
    // that will be Copied/Write.
    // Take in account that we already have 1 event.
    if (event) {
        m_in_deps_allocated += (length_src / send_size) *
                                ((m_vars_extra[i].read_rng_src) ?
                                m_vars_extra[i].read_rng_src->range_max_number : 1) ;
        m_in_deps    =
            (COIEVENT*)realloc(m_in_deps, sizeof(COIEVENT) * m_in_deps_allocated);
        m_in_deps_total--; 
    }

    // consequently get contiguous ranges,
    // define corresponded destination offset and send data
    do {
        if (src_is_empty) {
            if (m_vars_extra[i].read_rng_src) {
                if (!get_next_range(m_vars_extra[i].read_rng_src,
                         &offset_src)) {
                    // source ranges are over - nothing to send
                    break;
                }
            }
            else if (data_sent == 0) {
                offset_src = m_vars_extra[i].cpu_disp;
            }
            else {
                break;
            }
            length_src_cur = length_src;
        }
        else {
            // if source is contiguous or its contiguous range is greater
            // than destination one
            offset_src += send_size;
        }
        length_src_cur -= send_size;
        src_is_empty = length_src_cur == 0;

        if (dst_is_empty) {
            if (m_vars[i].into) {
                if (m_vars_extra[i].read_rng_dst) {
                    if (!get_next_range(m_vars_extra[i].read_rng_dst,
                             &offset_dst)) {
                        // destination ranges are over
                        LIBOFFLOAD_ERROR(c_destination_is_over);
                        return false;
                    }
                }
                // into is contiguous.
                else {
                    offset_dst = m_vars[i].disp;
                }
                length_dst_cur = length_dst;
            }
            // same as source
            else {
                offset_dst = offset_src;
                length_dst_cur = length_src;
            }
        }
        else {
            // if destination is contiguous or its contiguous range is greater
            // than source one
            offset_dst += send_size;
        }
        length_dst_cur -= send_size;
        dst_is_empty = length_dst_cur == 0;
        
        if (event) {
            event =  &m_in_deps[m_in_deps_total++];
        }
        if (src_data != 0 && src_data->cpu_buf != 0) {
            res = COI::BufferCopy(
                dst_data->mic_buf,
                src_data->cpu_buf,
                m_vars[i].mic_offset +
                m_vars[i].offset + offset_dst,
                m_vars_extra[i].cpu_offset + offset_src,
                send_size,
                COI_COPY_UNSPECIFIED,
                in_deps_amount, in_deps,
                event);
            if (res != COI_SUCCESS) {
                if (m_status != 0) {
                    m_status->result = translate_coi_error(res);
                    return false;
                }
                report_coi_error(c_buf_copy, res);
            }
        }
        else {
            char *base = offload_get_src_base(m_vars[i].ptr,
                m_vars[i].type.src);

            res = COI::BufferWrite(
                dst_data->mic_buf,
                m_vars[i].mic_offset +
                m_vars[i].offset + offset_dst,
                base + offset_src,
                send_size,
                COI_COPY_UNSPECIFIED,
                in_deps_amount, in_deps,
                event);
            if (res != COI_SUCCESS) {
                if (m_status != 0) {
                    m_status->result = translate_coi_error(res);
                    return false;
                }
                report_coi_error(c_buf_write, res);
            }
        }
        data_sent += send_size;
    }
    while (true);
    return true;
}

bool OffloadDescriptor::send_pointer_data(bool is_async, void* info)
{
    OffloadTimer timer(get_timer_data(), c_offload_host_send_pointers);

    bool should_use_async_buffer_write = m_initial_need_runfunction;
    uint64_t ptr_sent = 0;
    COIRESULT res;
    uint32_t in_deps_amount = 0;
    COIEVENT *in_deps = NULL;

    // For offload_transfer and offload with empty body without signal:
    // - if there is only one buffer copy - send data synchronously
    // - if there are multiple buffer copy and
    // __offload_parallel_copy is false - send data synchronously
    // - if there are multiple buffer copy and
    // __offload_parallel_copy is true - send data asynchronously
    // It concerns only big size data - greater than __offload_use_async_buffer_write.
    // Data of size less than __offload_use_async_buffer_write are sent synchronously.
    // Synchronous transfer results in better performance in COI.
    // __offload_parallel_copy is false by default but can be changed
    // via environment variable OFFLOAD_PARALLEL_COPY
    if (!m_initial_need_runfunction && __offload_parallel_copy) {
        int big_size_count = 0;
        for (int i = 0; i < m_vars_total; i++) {
            if (m_vars[i].direction.in &&
                m_vars[i].size >= __offload_use_async_buffer_write) {
                switch (m_vars[i].type.dst) {
                    case c_data:
                    case c_void_ptr:
                    case c_cean_var:
                        if (m_vars[i].flags.is_static_dstn) {
                            big_size_count++;
                        }
                        break;
                    case c_string_ptr:
                    case c_data_ptr:
                    case c_cean_var_ptr:
                    case c_dv_ptr:
                    case c_dv_data:
                    case c_dv_ptr_data:
                    case c_dv_data_slice:
                    case c_dv_ptr_data_slice:
                        big_size_count++;
                        break;
                    default:
                        break;
                }
            }
        }
        if (big_size_count > 1) {
            should_use_async_buffer_write = true;
        }
    }

    if (m_stream != no_stream && m_vars_total != 0) {
       get_stream_in_dependencies(in_deps_amount, in_deps);
    }

    // Initiate send for pointer data
    for (int i = 0; i < m_vars_total; i++) {
        uint64_t sent_data = m_vars[i].size;
        uint32_t in_deps_amount_save;
        COIEVENT *in_deps_save;
                
        if (m_vars_extra[i].omp_last_event_type == c_last_write) {
            in_deps_amount_save = in_deps_amount;
            in_deps_save = in_deps;
            in_deps_amount = m_in_deps_total;
            if (in_deps_amount > 0) {
               in_deps = (COIEVENT*) malloc(sizeof(COIEVENT) * in_deps_amount);
               if (in_deps == NULL)
                   LIBOFFLOAD_ERROR(c_malloc);
               memcpy(in_deps, m_in_deps,in_deps_amount * sizeof(COIEVENT));
            }                
        }
        switch (m_vars[i].type.dst) {
            case c_data_ptr_array:
                break;
            case c_data:
            case c_void_ptr:
            case c_cean_var:
                if (m_vars[i].direction.in &&
                    m_vars[i].flags.is_static_dstn) {
                    COIEVENT *event =
                        (is_async ||
                         (should_use_async_buffer_write &&
                          m_vars[i].size >= __offload_use_async_buffer_write)) ?
                        &m_in_deps[m_in_deps_total++] : 0;
                    PtrData* dst_data = m_vars[i].into ?
                                            m_vars_extra[i].dst_data :
                                            m_vars_extra[i].src_data;
                    PtrData* src_data =
                        VAR_TYPE_IS_PTR(m_vars[i].type.src) ||
                        VAR_TYPE_IS_SCALAR(m_vars[i].type.src) &&
                        m_vars[i].flags.is_static ?
                           m_vars_extra[i].src_data : 0;

                    if (m_vars[i].flags.is_noncont_src ||
                        m_vars[i].flags.is_noncont_dst) {
                        if (!send_noncontiguous_pointer_data(
                                i, src_data, dst_data, event, sent_data,
                                in_deps_amount, in_deps)) {
                            return false;
                        }
                    }
                    else if (src_data != 0 && src_data->cpu_buf != 0) {
                        res = COI::BufferCopy(
                            dst_data->mic_buf,
                            src_data->cpu_buf,
                            m_vars[i].mic_offset +
                            m_vars[i].offset + m_vars[i].disp,
                            m_vars_extra[i].cpu_offset +
                            m_vars_extra[i].cpu_disp,
                            m_vars[i].size,
                            COI_COPY_UNSPECIFIED,
                            in_deps_amount, in_deps,
                            event);
                        if (res != COI_SUCCESS) {
                            if (m_status != 0) {
                                m_status->result = translate_coi_error(res);
                                return false;
                            }
                            report_coi_error(c_buf_copy, res);
                        }
                    }
                    else {
                        char *base = offload_get_src_base(m_vars[i].ptr,
                                                          m_vars[i].type.src);
                        res = COI::BufferWrite(
                            dst_data->mic_buf,
                            m_vars[i].mic_offset +
                            m_vars[i].offset + m_vars[i].disp,
                            base + m_vars_extra[i].cpu_disp,
                            m_vars[i].size,
                            COI_COPY_UNSPECIFIED,
                            in_deps_amount, in_deps,
                            event);
                        if (res != COI_SUCCESS) {
                            if (m_status != 0) {
                                m_status->result = translate_coi_error(res);
                                return false;
                            }
                            report_coi_error(c_buf_write, res);
                        }
                    }
                    ptr_sent += sent_data;
                }
                break;

            case c_string_ptr:
            case c_data_ptr:
            case c_cean_var_ptr:
            case c_dv_ptr:
                if (m_vars[i].direction.in && m_vars[i].size > 0) {
                    COIEVENT *event =
                        (is_async ||
                         (should_use_async_buffer_write &&
                          m_vars[i].size >= __offload_use_async_buffer_write)) ?
                        &m_in_deps[m_in_deps_total++] : 0;
                    PtrData* dst_data = m_vars[i].into ?
                                            m_vars_extra[i].dst_data :
                                            m_vars_extra[i].src_data;
                    PtrData* src_data =
                        VAR_TYPE_IS_PTR(m_vars[i].type.src) ||
                        VAR_TYPE_IS_SCALAR(m_vars[i].type.src) &&
                        m_vars[i].flags.is_static ?
                            m_vars_extra[i].src_data : 0;

                    if (m_vars[i].flags.is_noncont_src ||
                        m_vars[i].flags.is_noncont_dst) {
                        send_noncontiguous_pointer_data(
                            i, src_data, dst_data, event, sent_data,
                            in_deps_amount, in_deps);
                    }
                    else if (src_data != 0 && src_data->cpu_buf != 0) {
                        res = COI::BufferCopy(
                            dst_data->mic_buf,
                            src_data->cpu_buf,
                            m_vars[i].mic_offset +
                            m_vars[i].offset + m_vars[i].disp,
                            m_vars_extra[i].cpu_offset +
                            m_vars_extra[i].cpu_disp,
                            m_vars[i].size,
                            COI_COPY_UNSPECIFIED,
                            in_deps_amount, in_deps,
                            event);
                        if (res != COI_SUCCESS) {
                            if (m_status != 0) {
                                m_status->result = translate_coi_error(res);
                                return false;
                            }
                            report_coi_error(c_buf_copy, res);
                        }
                    }
                    else {
                        char *base = offload_get_src_base(m_vars[i].ptr,
                                                          m_vars[i].type.src);
                        res = COI::BufferWrite(
                            dst_data->mic_buf,
                            m_vars[i].mic_offset +
                            m_vars[i].offset + m_vars[i].disp,
                            base + m_vars_extra[i].cpu_disp,
                            m_vars[i].size,
                            COI_COPY_UNSPECIFIED,
                            in_deps_amount, in_deps,
                            event);
                        if (res != COI_SUCCESS) {
                            if (m_status != 0) {
                                m_status->result = translate_coi_error(res);
                                return false;
                            }
                            report_coi_error(c_buf_write, res);
                        }
                    }

                    ptr_sent += sent_data;
                }
                break;

            case c_dv_data:
            case c_dv_ptr_data:
                if (m_vars[i].direction.in &&
                    m_vars[i].size > 0) {
                    PtrData *ptr_data = m_vars[i].into ?
                                        m_vars_extra[i].dst_data :
                                        m_vars_extra[i].src_data;
                    PtrData* src_data = m_vars_extra[i].src_data;

                    COIEVENT *event =
                        (is_async ||
                         (should_use_async_buffer_write &&
                          m_vars[i].size >= __offload_use_async_buffer_write)) ?
                        &m_in_deps[m_in_deps_total++] : 0;

                    if (m_vars[i].flags.is_noncont_src ||
                        m_vars[i].flags.is_noncont_dst) {
                        send_noncontiguous_pointer_data(
                            i, src_data, ptr_data, event, sent_data,
                            in_deps_amount, in_deps);
                    }
                    else if (src_data && src_data->cpu_buf != 0) {
                        res = COI::BufferCopy(
                            ptr_data->mic_buf,
                            src_data->cpu_buf,
                            m_vars[i].offset + ptr_data->mic_offset +
                            m_vars[i].disp,
                            m_vars_extra[i].cpu_offset +
                            m_vars_extra[i].cpu_disp,
                            m_vars[i].size,
                            COI_COPY_UNSPECIFIED,
                            in_deps_amount, in_deps,
                            event);
                        if (res != COI_SUCCESS) {
                            if (m_status != 0) {
                                m_status->result = translate_coi_error(res);
                                return false;
                            }
                            report_coi_error(c_buf_copy, res);
                        }
                    }
                    else {
                        char *base = offload_get_src_base(m_vars[i].ptr,
                                                          m_vars[i].type.src);
                        res = COI::BufferWrite(
                            ptr_data->mic_buf,
                            ptr_data->mic_offset +
                            m_vars[i].offset + m_vars[i].disp,
                            base + m_vars_extra[i].cpu_disp,
                            m_vars[i].size,
                            COI_COPY_UNSPECIFIED,
                            in_deps_amount, in_deps,
                            event);
                        if (res != COI_SUCCESS) {
                            if (m_status != 0) {
                                m_status->result = translate_coi_error(res);
                                return false;
                            }
                            report_coi_error(c_buf_write, res);
                        }
                    }
                    ptr_sent += sent_data;
                }
                break;

            case c_dv_data_slice:
            case c_dv_ptr_data_slice:
                if (m_vars[i].direction.in &&
                    m_vars[i].size > 0) {
                    PtrData *dst_data = m_vars[i].into ?
                                        m_vars_extra[i].dst_data :
                                        m_vars_extra[i].src_data;
                    PtrData* src_data =
                        (VAR_TYPE_IS_PTR(m_vars[i].type.src) ||
                        VAR_TYPE_IS_DV_DATA(m_vars[i].type.src) ||
                        VAR_TYPE_IS_DV_DATA_SLICE(m_vars[i].type.src) ||
                        VAR_TYPE_IS_SCALAR(m_vars[i].type.src) &&
                        m_vars[i].flags.is_static) ?
                            m_vars_extra[i].src_data : 0;
                    COIEVENT *event =
                        (is_async ||
                         (should_use_async_buffer_write &&
                          m_vars[i].size >= __offload_use_async_buffer_write)) ?
                        &m_in_deps[m_in_deps_total++] : 0;
                    if (m_vars[i].flags.is_noncont_src ||
                        m_vars[i].flags.is_noncont_dst) {
                        send_noncontiguous_pointer_data(
                            i, src_data, dst_data, event, sent_data,
                            in_deps_amount, in_deps);
                    }
                    else if (src_data && src_data->cpu_buf != 0) {
                        res = COI::BufferCopy(
                            dst_data->mic_buf,
                            src_data->cpu_buf,
                            m_vars[i].offset +
                            dst_data->mic_offset +
                            m_vars[i].disp,
                            m_vars_extra[i].cpu_offset +
                            m_vars_extra[i].cpu_disp,
                            m_vars[i].size,
                            COI_COPY_UNSPECIFIED,
                            in_deps_amount, in_deps,
                            event);
                        if (res != COI_SUCCESS) {
                            if (m_status != 0) {
                                m_status->result = translate_coi_error(res);
                                return false;
                            }
                            report_coi_error(c_buf_copy, res);
                        }
                    }
                    else {
                        char *base = offload_get_src_base(m_vars[i].ptr,
                                                          m_vars[i].type.src);
                        res = COI::BufferWrite(
                            dst_data->mic_buf,
                            dst_data->mic_offset +
                            m_vars[i].offset + m_vars[i].disp,
                            base + m_vars_extra[i].cpu_disp,
                            m_vars[i].size,
                            COI_COPY_UNSPECIFIED,
                            in_deps_amount, in_deps,
                            event);
                        if (res != COI_SUCCESS) {
                            if (m_status != 0) {
                                m_status->result = translate_coi_error(res);
                                return false;
                            }
                            report_coi_error(c_buf_write, res);
                        }
                    }

                    ptr_sent += sent_data;
                }
                break;

            default:
                break;
        }
        if (m_vars_extra[i].omp_last_event_type == c_last_write) {
            in_deps_amount = in_deps_amount_save;
            in_deps = in_deps_save;
            register_omp_event_call_back(&m_in_deps[m_in_deps_total - 1], info);                
        }
        // alloc field isn't used at target.
        // We can reuse it for offset of array pointers.
        if (m_vars_extra[i].is_arr_ptr_el) {
            m_vars[i].ptr_arr_offset = m_vars_extra[i].ptr_arr_offset;
        }
    }

    if (m_status) {
        m_status->data_sent += ptr_sent;
    }

    OFFLOAD_TIMER_HOST_SDATA(get_timer_data(), ptr_sent);
    OFFLOAD_DEBUG_TRACE_1(1, GET_OFFLOAD_NUMBER(get_timer_data()),
                  c_offload_sent_pointer_data,
                  "Total pointer data sent to target: [%lld] bytes\n",
                  ptr_sent);

    return true;
}

bool OffloadDescriptor::gather_copyin_data()
{
    OffloadTimer timer(get_timer_data(), c_offload_host_gather_inputs);

    if (m_need_runfunction && m_in_datalen > 0) {
        COIMAPINSTANCE map_inst;
        char *data;

        // init marshaller
        if (m_inout_buf != 0) {
            OffloadTimer timer_map(get_timer_data(),
                                   c_offload_host_map_in_data_buffer);

            COIRESULT res = COI::BufferMap(m_inout_buf, 0, m_in_datalen,
                                           COI_MAP_WRITE_ENTIRE_BUFFER,
                                           0, 0, 0, &map_inst,
                                           reinterpret_cast<void**>(&data));
            if (res != COI_SUCCESS) {
                if (m_status != 0) {
                    m_status->result = translate_coi_error(res);
                    return false;
                }
                report_coi_error(c_buf_map, res);
            }
        }
        else {
            data = (char*) m_func_desc + m_func_desc->data_offset;
        }

        // send variable descriptors
        memcpy(data, m_vars, m_vars_total * sizeof(VarDesc));
        data += m_vars_total * sizeof(VarDesc);

        // init marshaller
        m_in.init_buffer(data, m_in_datalen);

        // Gather copy data into buffer
        for (int i = 0; i < m_vars_total; i++) {
            bool src_is_for_mic = (m_vars[i].direction.out ||
                                   m_vars[i].into == NULL);
            PtrData* ptr_data = src_is_for_mic ?
                                m_vars_extra[i].src_data :
                                m_vars_extra[i].dst_data;
            if (m_vars[i].flags.alloc_disp) {
                m_in.send_data(&ptr_data->alloc_disp,
                               sizeof(ptr_data->alloc_disp));
            }

            // send sink address to the target
            if (m_vars[i].flags.sink_addr) {
                m_in.send_data(&ptr_data->mic_addr,
                               sizeof(ptr_data->mic_addr));
            }

            switch (m_vars[i].type.dst) {
                case c_data_ptr_array:
                    break;
                case c_data:
                case c_void_ptr:
                case c_cean_var:
                    if (m_vars[i].direction.in &&
                        !m_vars[i].flags.is_static_dstn) {

                        char *ptr = offload_get_src_base(m_vars[i].ptr,
                                                         m_vars[i].type.src);
                        if (m_vars[i].type.dst == c_cean_var) {
                            // offset and length are derived from the array
                            // descriptor
                            int64_t size = m_vars[i].size;
                            int64_t disp = m_vars[i].disp;
                            m_in.send_data(reinterpret_cast<char*>(&size),
                                           sizeof(int64_t));
                            m_in.send_data(reinterpret_cast<char*>(&disp),
                                           sizeof(int64_t));
                        }

                        m_in.send_data(ptr + m_vars_extra[i].cpu_disp,
                                       m_vars[i].size);
                    }
                    break;

                case c_dv:
                    if (m_vars[i].direction.bits ||
                        m_vars[i].alloc_if ||
                        m_vars[i].free_if) {
                        // send dope vector excluding base
                        char *ptr = static_cast<char*>(m_vars[i].ptr);
                        m_in.send_data(ptr + sizeof(uint64_t),
                                       m_vars[i].size - sizeof(uint64_t));
                    }
                    break;

                case c_data_ptr:
                    // send to target addresses of obsolete
                    // stacks to be released
                    if (m_vars[i].flags.is_stack_buf &&
                        !m_vars[i].direction.bits &&
                        m_vars[i].alloc_if &&
                        m_vars[i].size != 0) {
                        for (PtrDataList::iterator it =
                            m_destroy_stack.begin();
                            it != m_destroy_stack.end(); it++) {
                            PtrData * ptr_data = *it;
                            m_in.send_data(&(ptr_data->mic_addr),
                                sizeof(ptr_data->mic_addr));
                        }
                    }
                    break;
                case c_func_ptr:
                    if (m_vars[i].direction.in) {
                        m_in.send_func_ptr(*((const void**) m_vars[i].ptr));
                    }
                    break;

                default:
                    break;
            }
        }

        if (m_status) {
            m_status->data_sent += m_in.get_tfr_size();
        }

        if (m_func_desc->data_offset == 0) {
            OffloadTimer timer_unmap(get_timer_data(),
                                     c_offload_host_unmap_in_data_buffer);
            COIRESULT res = COI::BufferUnmap(map_inst, 0, 0, 0);
            if (res != COI_SUCCESS) {
                if (m_status != 0) {
                    m_status->result = translate_coi_error(res);
                    return false;
                }
                report_coi_error(c_buf_unmap, res);
            }
        }
    }

    OFFLOAD_TIMER_HOST_SDATA(get_timer_data(), m_in.get_tfr_size());
    OFFLOAD_DEBUG_TRACE_1(1,
                  GET_OFFLOAD_NUMBER(get_timer_data()), c_offload_copyin_data,
                  "Total copyin data sent to target: [%lld] bytes\n",
                  m_in.get_tfr_size());

    return true;
}

bool OffloadDescriptor::compute(void *info)
{
    OffloadTimer timer(get_timer_data(), c_offload_host_start_compute);

    if (m_need_runfunction) {
        OFFLOAD_DEBUG_TRACE_1(2, GET_OFFLOAD_NUMBER(get_timer_data()),
                              c_offload_compute, "Compute task on MIC\n");

        void* misc = m_func_desc;
        int   misc_len = m_func_desc_size;
        void* ret = 0;
        int   ret_len = 0;

        if (m_func_desc->data_offset != 0) {
            misc_len += m_in_datalen;

            if (m_out_datalen > 0) {
                ret = (char*) m_func_desc + m_func_desc->data_offset;
                ret_len = m_out_datalen;
            }
        }

        // dispatch task
        COIRESULT res;
        COIEVENT event;
        uint32_t in_deps_amount = m_in_deps_total;
        COIEVENT *in_deps = m_in_deps_total > 0 ? m_in_deps : 0;

        if (0 == m_in_deps_total && m_stream != no_stream) {
            get_stream_in_dependencies(in_deps_amount, in_deps);
        }

        res = m_device.compute(m_stream,
                               m_compute_buffers,
                               misc, misc_len,
                               ret, ret_len,
                               in_deps_amount,
                               in_deps,
                               &event);

        if (res != COI_SUCCESS) {
            if (m_status != 0) {
                m_status->result = translate_coi_error(res);
                return false;
            }
            report_coi_error(c_pipeline_run_func, res);
        }

        if (m_omp_async_last_event_type == c_last_runfunc) {
            register_omp_event_call_back(&event, info);
        }

        m_in_deps_total = 1;
        m_in_deps[0] = event;
    }

    return true;
}

// receive pointer data if source or destination or both of them are
// noncontiguous. There is guarantee that length of destination enough for
// transferred data.
bool OffloadDescriptor::receive_noncontiguous_pointer_data(
    int i,
    COIBUFFER dst_buf,
    COIEVENT *event,
    uint64_t &received_data,
    uint32_t in_deps_amount,
    COIEVENT *in_deps
)
{
    int64_t offset_src, offset_dst;
    int64_t length_src, length_dst;
    int64_t length_src_cur, length_dst_cur;
    int64_t receive_size;
    COIRESULT res;
    bool dst_is_empty = true;
    bool src_is_empty = true;

    char *base = offload_get_src_base(
                     m_vars[i].into ?
                     static_cast<char*>(m_vars[i].into) :
                     static_cast<char*>(m_vars[i].ptr),
                     m_vars[i].type.dst);
    received_data = 0;

    // Set length_src and length_dst
    length_src = (m_vars_extra[i].read_rng_src) ?
        m_vars_extra[i].read_rng_src->range_size : m_vars[i].size;
    length_dst = !m_vars[i].into ? length_src :
                     (m_vars_extra[i].read_rng_dst) ?
                     m_vars_extra[i].read_rng_dst->range_size : m_vars[i].size;
    receive_size = (length_src < length_dst) ? length_src : length_dst;

    // If BufferReadMultiD is defined we can set values of required arguments
    // and transfer noncontiguous data via call to the COI routine.
    if (__offload_use_coi_noncontiguous_transfer && COI::BufferReadMultiD) {
        struct Arr_Desc* arr_desc_dst;
        struct Arr_Desc* arr_desc_src;
        int64_t size_src, size_dst;

        offset_src = (m_vars_extra[i].read_rng_src)?
            m_vars_extra[i].read_rng_src->init_offset : m_vars[i].disp;
        size_src = m_vars_extra[i].read_rng_src ?
            cean_get_transf_size(m_vars_extra[i].read_rng_src) :
            m_vars[i].size;

        offset_dst = (m_vars_extra[i].read_rng_dst)?
            m_vars_extra[i].read_rng_dst->init_offset : m_vars_extra[i].cpu_disp;
        size_dst = m_vars_extra[i].read_rng_dst ?
            cean_get_transf_size(m_vars_extra[i].read_rng_dst) : m_vars[i].size;

        int64_t el_size = (!m_vars[i].into ||
                           (m_vars_extra[i].read_rng_src &&
                            m_vars_extra[i].read_rng_dst)) ?
                            1 :
                            m_vars_extra[i].read_rng_src ?
                                m_vars_extra[i].read_rng_src->arr_desc->dim[
                m_vars_extra[i].read_rng_src->arr_desc->rank - 1].size :
        m_vars_extra[i].read_rng_dst->arr_desc->dim[
            m_vars_extra[i].read_rng_dst->arr_desc->rank - 1].size;
            arr_desc_src = (m_vars_extra[i].read_rng_src) ?
                m_vars_extra[i].read_rng_src->arr_desc :
            make_arr_desc(NULL, // don't required for source
                offset_src/el_size, size_src/el_size,
                el_size);
            arr_desc_dst = !m_vars[i].into ? arr_desc_src :
                (m_vars_extra[i].read_rng_dst) ?
                m_vars_extra[i].read_rng_dst->arr_desc :
            make_arr_desc(NULL,
                offset_dst/el_size, size_src/el_size, el_size);

            arr_desc_dst->base = reinterpret_cast<int64_t>(base);

            res = COI::BufferReadMultiD(
                m_vars_extra[i].src_data->mic_buf,      // SourceBuffer
                m_vars[i].offset + m_vars[i].mic_offset -
                m_vars_extra[i].src_data->alloc_disp,         // Offset
                (void*)arr_desc_dst,                 // descriptor of DestArray
                (void*)arr_desc_src,                 // descriptor of SrcArray
                COI_COPY_UNSPECIFIED,         // Type
                in_deps_amount,               // Number of in Dependencies
                in_deps,                      // array of in Dependencies
                event);                       // out Dependency
            if (res != COI_SUCCESS) {
                if (m_status != 0) {
                    m_status->result = translate_coi_error(res);
                    return false;
                }
                report_coi_error(c_buf_copy, res);
            }
            return(true);
    }
    // if event is defined we must multiplate for all contiguous intervals
    // that will be Copied/Read.
    // Take in account that we already have 1 event.
    if (event) {
        m_out_deps_allocated += (length_src / receive_size) *
                                ((m_vars_extra[i].read_rng_src) ?
                                m_vars_extra[i].read_rng_src->range_max_number : 1) ;
        m_out_deps    =
            (COIEVENT*)realloc(m_out_deps, sizeof(COIEVENT) * m_out_deps_allocated);
        m_out_deps_total--; 
    }
 
    // consequently get contiguous ranges,
    // define corresponded destination offset and receive data
    do {
        // get sorce offset
        if (src_is_empty) {
            if (m_vars_extra[i].read_rng_src) {
                if (!get_next_range(m_vars_extra[i].read_rng_src,
                         &offset_src)) {
                    // source ranges are over - nothing to send
                    break;
                }
            }
            else if (received_data == 0) {
                offset_src = m_vars[i].disp;
            }
            else {
                break;
            }
            length_src_cur = length_src;
        }
        else {
            // if source is contiguous or its contiguous range is greater
            // than destination one
            offset_src += receive_size;
        }
        length_src_cur -= receive_size;
        src_is_empty = length_src_cur == 0;

        // get destination offset
        if (dst_is_empty) {
            if (m_vars[i].into) {
                if (m_vars_extra[i].read_rng_dst) {
                    if (!get_next_range(m_vars_extra[i].read_rng_dst,
                             &offset_dst)) {
                        // destination ranges are over
                        LIBOFFLOAD_ERROR(c_destination_is_over);
                        return false;
                    }
                }
                // destination is contiguous.
                else {
                    offset_dst = m_vars_extra[i].cpu_disp;
                }
                length_dst_cur = length_dst;
            }
            // same as source
            else {
                offset_dst = offset_src;
                length_dst_cur = length_src;
            }
        }
        else {
            // if destination is contiguous or its contiguous range is greater
            // than source one
            offset_dst += receive_size;
        }
        length_dst_cur -= receive_size;
        dst_is_empty = length_dst_cur == 0;
        if (event) {
            event =  &m_out_deps[m_out_deps_total++];
        }
        if (dst_buf != 0) {
            res = COI::BufferCopy(
                dst_buf,
                m_vars_extra[i].src_data->mic_buf,
                m_vars_extra[i].cpu_offset + offset_dst,
                m_vars[i].offset + offset_src +
                m_vars[i].mic_offset,
                receive_size,
                COI_COPY_UNSPECIFIED,
                in_deps_amount,
                in_deps,
                event);
            if (res != COI_SUCCESS) {
                if (m_status != 0) {
                    m_status->result = translate_coi_error(res);
                    return false;
                }
                report_coi_error(c_buf_copy, res);
            }
        }
        else {
            res = COI::BufferRead(
                m_vars_extra[i].src_data->mic_buf,
                m_vars[i].offset + offset_src +
                m_vars[i].mic_offset,
                base + offset_dst,
                receive_size,
                COI_COPY_UNSPECIFIED,
                in_deps_amount,
                in_deps,
                event);
            if (res != COI_SUCCESS) {
                if (m_status != 0) {
                    m_status->result = translate_coi_error(res);
                    return false;
                }
                report_coi_error(c_buf_read, res);
            }
        }
        received_data += receive_size;
    }
    while (true);
    return true;
}

bool OffloadDescriptor::receive_pointer_data(bool is_async,
                                             bool first_run, void *info)
{
    OffloadTimer timer(get_timer_data(), c_offload_host_start_buffers_reads);

    bool should_use_async_buffer_read = m_initial_need_runfunction;
    uint64_t ptr_received = 0;
    COIRESULT res;

    // For offload_transfer and offload with empty body without signal:
    // - if there is only one buffer copy - get data synchronously
    // - if there are multiple buffer copy and
    //      __offload_parallel_copy is false - get data synchronously
    // - if there are multiple buffer copy
    //      and __offload_parallel_copy is true - get data asynchronously
    // It concerns only data with size greater than __offload_use_async_buffer_read.
    // Data of size less than __offload_use_async_buffer_read are received synchronously.
    // Synchronous transfer results in better performance in COI.
    // __offload_parallel_copy is false by default but can be changed
    // via environment variable OFFLOAD_PARALLEL_COPY
    if (!m_initial_need_runfunction && __offload_parallel_copy) {
        int big_size_count = 0;

        for (int i = 0; i < m_vars_total; i++) {
            if (m_vars[i].direction.out &&
                m_vars[i].size >= __offload_use_async_buffer_read) {
                // preallocated OUT only at second run
                if (first_run == m_vars[i].flags.preallocated) {
                    continue;
                }
                switch (m_vars[i].type.src) {
                    case c_data:
                    case c_void_ptr:
                    case c_cean_var:
                        if (m_vars[i].flags.is_static) {
                            big_size_count++;
                        }
                        break;
                    case c_string_ptr:
                    case c_data_ptr:
                    case c_cean_var_ptr:
                    case c_dv_data:
                    case c_dv_ptr_data:
                    case c_dv_data_slice:
                    case c_dv_ptr_data_slice:
                    case c_dv_ptr:
                        big_size_count++;
                        break;
                    default:
                        break;
                }
            }
        }
        if (big_size_count > 1) {
            should_use_async_buffer_read = true;
        }
    }
    uint32_t in_deps_amount = m_in_deps_total;
    COIEVENT *in_deps = m_in_deps_total > 0 ? m_in_deps : 0;

    if (0 == m_in_deps_total  &&
        m_stream != no_stream &&
        m_vars_total != 0) {
        get_stream_in_dependencies(in_deps_amount, in_deps);
    }

    for (int i = 0; i < m_vars_total; i++) {
        uint64_t received_data = m_vars[i].size;
        uint32_t in_deps_amount_save;
        COIEVENT *in_deps_save; 
              
         if (m_vars_extra[i].omp_last_event_type == c_last_read) {
            in_deps_amount_save = in_deps_amount;
            in_deps_save = in_deps;
            
            in_deps_amount += m_out_deps_total;
            if (in_deps_amount > 0) {
               in_deps = (COIEVENT*) malloc(sizeof(COIEVENT) * in_deps_amount);
               if (in_deps == NULL)
                   LIBOFFLOAD_ERROR(c_malloc);
               memcpy(in_deps, in_deps_save,
                      in_deps_amount_save * sizeof(COIEVENT));
               memcpy(in_deps + in_deps_amount_save * sizeof(COIEVENT),
                      m_out_deps,
                      m_out_deps_total * sizeof(COIEVENT));                      
            }                
        }   
        // At first run don't receive by preallocated target pointer as the
        //pointer value will be ready later after call to scatter_copyout_data
        if (first_run && m_vars[i].alloc_if && m_vars[i].flags.preallocated) {
            m_preallocated_alloc = true;
            // need one more call to OffloadDescriptor::receive_pointer_data
            if (m_vars[i].direction.out) {
                m_out_with_preallocated = true;
            }
            continue;
        }
        switch (m_vars[i].type.src) {
            case c_data_ptr_array:
                break;
            case c_data:
            case c_void_ptr:
            case c_cean_var:
                if (m_vars[i].direction.out &&
                    m_vars[i].flags.is_static) {
                    COIEVENT *event =
                        (is_async ||
                         m_in_deps_total > 0 ||
                         (should_use_async_buffer_read &&
                          m_vars[i].size >= __offload_use_async_buffer_read)) ?
                        &m_out_deps[m_out_deps_total++] : 0;
                    PtrData *ptr_data = NULL;
                    COIBUFFER dst_buf = NULL; // buffer at host
                    char *base;

                    if (VAR_TYPE_IS_PTR(m_vars[i].type.dst)) {
                        ptr_data = m_vars[i].into ?
                                   m_vars_extra[i].dst_data :
                                   m_vars_extra[i].src_data;
                    }
                    else if (VAR_TYPE_IS_SCALAR(m_vars[i].type.dst)) {
                        if (m_vars[i].flags.is_static_dstn) {
                            ptr_data = m_vars[i].into ?
                                       m_vars_extra[i].dst_data :
                                       m_vars_extra[i].src_data;
                        }
                    }
                    dst_buf = ptr_data ? ptr_data->cpu_buf : NULL;
                    if (dst_buf == NULL) {
                        base = offload_get_src_base(
                            m_vars[i].into ?
                            static_cast<char*>(m_vars[i].into) :
                            static_cast<char*>(m_vars[i].ptr),
                            m_vars[i].type.dst);
                    }

                    if (m_vars[i].flags.is_noncont_src ||
                        m_vars[i].flags.is_noncont_dst) {
                        receive_noncontiguous_pointer_data(
                            i, dst_buf, event, received_data,
                            in_deps_amount, in_deps);
                    }
                    else if (dst_buf != 0) {
                        res = COI::BufferCopy(
                            dst_buf,
                            m_vars_extra[i].src_data->mic_buf,
                            m_vars_extra[i].cpu_offset +
                            m_vars_extra[i].cpu_disp,
                            m_vars[i].offset + m_vars[i].disp,
                            m_vars[i].size,
                            COI_COPY_UNSPECIFIED,
                            in_deps_amount,
                            in_deps,
                            event);
                        if (res != COI_SUCCESS) {
                            if (m_status != 0) {
                                m_status->result = translate_coi_error(res);
                                return false;
                            }
                            report_coi_error(c_buf_copy, res);
                        }
                    }
                    else {
                       res = COI::BufferRead(
                            m_vars_extra[i].src_data->mic_buf,
                            m_vars[i].offset + m_vars[i].disp,
                            base + m_vars_extra[i].cpu_offset +
                            m_vars_extra[i].cpu_disp,
                            m_vars[i].size,
                            COI_COPY_UNSPECIFIED,
                            in_deps_amount,
                            in_deps,
                            event);
                        if (res != COI_SUCCESS) {
                            if (m_status != 0) {
                                m_status->result = translate_coi_error(res);
                                return false;
                            }
                            report_coi_error(c_buf_read, res);
                        }
                    }
                    ptr_received += received_data;
                }
                break;

            case c_string_ptr:
            case c_data_ptr:
            case c_cean_var_ptr:
            case c_dv_data:
            case c_dv_ptr_data:
            case c_dv_data_slice:
            case c_dv_ptr_data_slice:
            case c_dv_ptr: {
                COIBUFFER dst_buf = NULL; // buffer on host
                if (m_vars[i].direction.out && m_vars[i].size > 0) {
                    COIEVENT *event =
                        (is_async ||
                         m_in_deps_total > 0 ||
                         (should_use_async_buffer_read &&
                          m_vars[i].size >= __offload_use_async_buffer_read)) ?
                        &m_out_deps[m_out_deps_total++] : 0;

                    uint64_t dst_offset = 0;
                    char *base = static_cast<char*>(m_vars[i].ptr);

                    if (VAR_TYPE_IS_PTR(m_vars[i].type.dst)) {
                        PtrData *ptr_data = m_vars[i].into ?
                                            m_vars_extra[i].dst_data :
                                            m_vars_extra[i].src_data;
                        dst_buf = ptr_data ? ptr_data->cpu_buf : NULL;
                        if (dst_buf == NULL) {
                            base = m_vars[i].into ?
                                   *static_cast<char**>(m_vars[i].into) :
                                   *static_cast<char**>(m_vars[i].ptr);
                        }
                        dst_offset = m_vars_extra[i].cpu_offset +
                                     m_vars_extra[i].cpu_disp;
                    }
                    else if (VAR_TYPE_IS_SCALAR(m_vars[i].type.dst)) {
                        if (m_vars[i].flags.is_static_dstn) {
                            dst_buf = m_vars[i].into ?
                                        m_vars_extra[i].dst_data->cpu_buf :
                                        m_vars_extra[i].src_data->cpu_buf;
                        }
                        if (dst_buf == NULL) {
                            base = offload_get_src_base(
                                m_vars[i].into ?
                                static_cast<char*>(m_vars[i].into) :
                                static_cast<char*>(m_vars[i].ptr),
                                m_vars[i].type.dst);
                        }
                        dst_offset = m_vars_extra[i].cpu_offset +
                                     m_vars_extra[i].cpu_disp;
                    }
                    else if (VAR_TYPE_IS_DV_DATA(m_vars[i].type.dst) ||
                             VAR_TYPE_IS_DV_DATA_SLICE(m_vars[i].type.dst)) {
                        PtrData *ptr_data = m_vars[i].into != 0 ?
                                            m_vars_extra[i].dst_data :
                                            m_vars_extra[i].src_data;
                        dst_buf = ptr_data != 0 ? ptr_data->cpu_buf : 0;
                        if (dst_buf == NULL) {
                            base = offload_get_src_base(
                                m_vars[i].into ?
                                static_cast<char*>(m_vars[i].into) :
                                static_cast<char*>(m_vars[i].ptr),
                                m_vars[i].type.dst);

                        }
                        dst_offset = m_vars_extra[i].cpu_offset +
                                     m_vars_extra[i].cpu_disp;
                    }

                    if (m_vars[i].flags.is_noncont_src ||
                        m_vars[i].flags.is_noncont_dst) {
                        receive_noncontiguous_pointer_data(
                            i, dst_buf, event, received_data,
                            in_deps_amount,
                            in_deps);
                    }
                    else if (dst_buf != 0) {
                        res = COI::BufferCopy(
                            dst_buf,
                            m_vars_extra[i].src_data->mic_buf,
                            dst_offset,
                            m_vars[i].offset + m_vars[i].disp +
                                m_vars[i].mic_offset,
                            m_vars[i].size,
                            COI_COPY_UNSPECIFIED,
                            in_deps_amount,
                            in_deps,
                            event);
                        if (res != COI_SUCCESS) {
                            if (m_status != 0) {
                                m_status->result = translate_coi_error(res);
                                return false;
                            }
                            report_coi_error(c_buf_copy, res);
                        }
                    }
                    else {
                        res = COI::BufferRead(
                            m_vars_extra[i].src_data->mic_buf,
                            m_vars[i].offset + m_vars[i].disp +
                                m_vars[i].mic_offset,
                            base + dst_offset,
                            m_vars[i].size,
                            COI_COPY_UNSPECIFIED,
                            in_deps_amount,
                            in_deps,
                            event);
                        if (res != COI_SUCCESS) {
                            if (m_status != 0) {
                                m_status->result = translate_coi_error(res);
                                return false;
                            }
                            report_coi_error(c_buf_read, res);
                        }
                    }
                    ptr_received += received_data;
                }
                break;
            }

            default:
                break;
        }

        if (m_vars_extra[i].omp_last_event_type == c_last_read) {
            in_deps_amount = in_deps_amount_save;
            in_deps = in_deps_save;
            register_omp_event_call_back(&m_out_deps[m_out_deps_total - 1], info);                
        }
        // destroy buffers for obsolete stacks
        if (m_destroy_stack.size() != 0) {
            for (PtrDataList::iterator it = m_destroy_stack.begin();
                it != m_destroy_stack.end(); it++) {
                PtrData *ptr_data = *it;
                m_destroy_buffers.push_back(ptr_data->mic_buf);
                OFFLOAD_TRACE(3, "Removing stack buffer with addr %p\n",
                                  ptr_data->mic_addr);
            }
            m_destroy_stack.clear();
        }
        if (m_vars[i].free_if) {
            // remove association for automatic variables
            if (m_is_openmp && !m_vars[i].flags.is_static &&
                (m_vars[i].type.src == c_data ||
                 m_vars[i].type.src == c_void_ptr ||
                 m_vars[i].type.src == c_cean_var)) {
                AutoData *auto_data = m_vars_extra[i].auto_data;
                if (auto_data != 0) {
                    if (m_vars[i].flags.always_delete) {
                        auto_data->nullify_reference();
                    }
                    else if(auto_data->remove_reference() == 0) {
                        m_device.remove_auto_data(auto_data->cpu_addr.start());
                    }
                }
            }

            // destroy buffers
            if (m_vars[i].direction.out || m_vars[i].into == NULL) {
                if (!VAR_TYPE_IS_PTR(m_vars[i].type.src) &&
                    !VAR_TYPE_IS_DV_DATA_SLICE(m_vars[i].type.src) &&
                    !VAR_TYPE_IS_DV_DATA(m_vars[i].type.src)) {
                    continue;
                }

                PtrData *ptr_data = m_vars_extra[i].src_data;
                if (ptr_data->remove_reference() == 0) {
                    // destroy buffers
                    if (ptr_data->cpu_buf != 0) {
                        m_destroy_buffers.push_back(ptr_data->cpu_buf);
                    }
                    if (ptr_data->mic_buf != 0) {
                        m_destroy_buffers.push_back(ptr_data->mic_buf);
                    }
                    OFFLOAD_TRACE(3, "Removing association for addr %p\n",
                                  ptr_data->cpu_addr.start());

                    // remove association from map
                    if (m_vars[i].flags.targetptr) {
                        m_device.remove_targetptr_data(ptr_data->cpu_addr.start());
                    }
                    else {
                        m_device.remove_ptr_data(ptr_data->cpu_addr.start());
                    }
                }
            }
            else if (VAR_TYPE_IS_PTR(m_vars[i].type.dst) ||
                     VAR_TYPE_IS_DV_DATA_SLICE(m_vars[i].type.dst) ||
                     VAR_TYPE_IS_DV_DATA(m_vars[i].type.dst)) {
                PtrData *ptr_data = m_vars_extra[i].dst_data;
                if (ptr_data->remove_reference() == 0) {
                    // destroy buffers
                    if (ptr_data->cpu_buf != 0) {
                        m_destroy_buffers.push_back(ptr_data->cpu_buf);
                    }
                    if (ptr_data->mic_buf != 0) {
                        m_destroy_buffers.push_back(ptr_data->mic_buf);
                    }
                    OFFLOAD_TRACE(3, "Removing association for addr %p\n",
                                  ptr_data->cpu_addr.start());

                    // remove association from map
                    if (m_vars[i].flags.targetptr) {
                        m_device.remove_targetptr_data(ptr_data->cpu_addr.start());
                    }
                    else {
                        m_device.remove_ptr_data(ptr_data->cpu_addr.start());
                    }
                }
            }
        }
    }

    if (m_status) {
        m_status->data_received += ptr_received;
    }

    OFFLOAD_TIMER_HOST_RDATA(get_timer_data(), ptr_received);
    OFFLOAD_DEBUG_TRACE_1(1, GET_OFFLOAD_NUMBER(get_timer_data()),
                  c_offload_received_pointer_data,
                  "Total pointer data received from target: [%lld] bytes\n",
                  ptr_received);

    return true;
}

bool OffloadDescriptor::scatter_copyout_data()
{
    OffloadTimer timer(get_timer_data(), c_offload_host_scatter_outputs);

    if (m_need_runfunction && m_out_datalen > 0) {

        // total size that need to be transferred from target to host
        COIMAPINSTANCE map_inst;
        COIRESULT res;
        char *data;

        // output data buffer
        if (m_func_desc->data_offset == 0) {
            OffloadTimer timer_map(get_timer_data(),
                                   c_offload_host_map_out_data_buffer);

            COIRESULT res = COI::BufferMap(m_inout_buf, 0, m_out_datalen,
                                           COI_MAP_READ_ONLY, 0, 0, 0,
                                           &map_inst,
                                            reinterpret_cast<void**>(&data));
            if (res != COI_SUCCESS) {
                if (m_status != 0) {
                    m_status->result = translate_coi_error(res);
                    return false;
                }
                report_coi_error(c_buf_map, res);
            }
        }
        else {
            data = (char*) m_func_desc + m_func_desc->data_offset;
        }

        // get timing data
        OFFLOAD_TIMER_TARGET_DATA(get_timer_data(), data);
        data += OFFLOAD_TIMER_DATALEN();

        // initialize output marshaller
        m_out.init_buffer(data, m_out_datalen);

        for (int i = 0; i < m_vars_total; i++) {
            bool src_is_for_mic = (m_vars[i].direction.out ||
                                   m_vars[i].into == NULL);

            if (m_vars[i].type.src != c_data_ptr_array &&
                m_vars[i].flags.preallocated && m_vars[i].alloc_if) {
                PtrData *ptr_data;
                void *ptr_value;
                void ** cpu_ptr = src_is_for_mic ?
                                  reinterpret_cast<void**>(m_vars[i].ptr) :
                                  reinterpret_cast<void**>(m_vars[i].into);
                void*   alloc_base = NULL;
                int64_t alloc_disp = 0;
                int64_t alloc_size;
                if (m_vars_extra[i].alloc != NULL) {
                    // array descriptor
                    const Arr_Desc *ap =
                        static_cast<const Arr_Desc*>(m_vars_extra[i].alloc);

                    __arr_data_offset_and_length(ap, alloc_disp, alloc_size);

                    alloc_base = reinterpret_cast<void*>(ap->base);
                }

                // get pointer to target memory
                m_out.receive_data(&ptr_value, sizeof(void*));

                // add new entry
                if (!alloc_ptr_data(
                    ptr_data,
                    ptr_value,
                    (alloc_base != NULL) ?
                        alloc_disp : m_vars[i].disp,
                    (alloc_base != NULL) ?
                        alloc_size : m_vars[i].size,
                    alloc_disp,
                    0,
                    m_vars[i].flags.targetptr,
                    m_vars[i].flags.preallocated,
                    m_vars[i].flags.pin)) {
                    return false;
                }

                ptr_data->add_reference();
                *cpu_ptr = ptr_value;
                if (src_is_for_mic) {
                    m_vars_extra[i].src_data = ptr_data;
                }
                else {
                    m_vars_extra[i].dst_data = ptr_data;
                }
                m_vars[i].offset = (char*) ptr_value -
                                   (char*) ptr_data->cpu_addr.start();
            }

            switch (m_vars[i].type.src) {
                case c_data_ptr_array:
                    break;
                case c_data:
                case c_void_ptr:
                case c_cean_var:
                    if (m_vars[i].direction.out &&
                        !m_vars[i].flags.is_static) {

                        if (m_vars[i].into) {
                            char *ptr = offload_get_src_base(
                                static_cast<char*>(m_vars[i].into),
                                m_vars[i].type.dst);
                            m_out.receive_data(ptr + m_vars_extra[i].cpu_disp,
                                               m_vars[i].size);
                        }
                        else {
                            m_out.receive_data(
                                static_cast<char*>(m_vars[i].ptr) +
                                    m_vars_extra[i].cpu_disp,
                                m_vars[i].size);
                        }
                    }
                    break;

                case c_func_ptr:
                    if (m_vars[i].direction.out) {
                        m_out.receive_func_ptr((const void**) m_vars[i].ptr);
                    }
                    break;

                default:
                    break;
            }
        }

        if (m_status) {
            m_status->data_received += m_out.get_tfr_size();
        }

        if (m_func_desc->data_offset == 0) {
            OffloadTimer timer_unmap(get_timer_data(),
                                     c_offload_host_unmap_out_data_buffer);

            COIRESULT res = COI::BufferUnmap(map_inst, 0, 0, 0);
            if (res != COI_SUCCESS) {
                if (m_status != 0) {
                    m_status->result = translate_coi_error(res);
                    return false;
                }
                report_coi_error(c_buf_unmap, res);
            }
        }
    }

    OFFLOAD_TIMER_HOST_RDATA(get_timer_data(), m_out.get_tfr_size());
    OFFLOAD_TRACE(1, "Total copyout data received from target: [%lld] bytes\n",
                  m_out.get_tfr_size());

    return true;
}

static void get_arr_desc_numbers(
    const Arr_Desc *ap,
    int64_t el_size,
    int64_t &offset,
    int64_t &size,
    int     &el_number,
    CeanReadRanges* &ptr_ranges
)
{
    if (is_arr_desc_contiguous(ap)) {
        ptr_ranges = NULL;
        __arr_data_offset_and_length(ap, offset, size);
        el_number = size / el_size;
    }
    else {
        ptr_ranges = init_read_ranges_arr_desc(ap);
        el_number = (ptr_ranges->range_size / el_size) *
                    ptr_ranges->range_max_number;
        size = ptr_ranges->range_size;
    }
}

bool OffloadDescriptor::gen_var_descs_for_pointer_array(int i)
{
    int             pointers_number;
    int             tmp_val;
    int             new_index = m_vars_total;
    const Arr_Desc *ap;
    const VarDesc3 *vd3 = static_cast<const VarDesc3*>(m_vars[i].ptr);
    int             flags = vd3->array_fields;
    bool            src_is_for_mic = (m_vars[i].direction.out ||
                                      m_vars[i].into == NULL);

    ReadArrElements<void *>  ptr;
    ReadArrElements<void *>  into;
    ReadArrElements<int64_t> ext_start;
    ReadArrElements<int64_t> ext_elements;
    ReadArrElements<int64_t> align;
    ReadArrElements<int64_t> alloc_if;
    ReadArrElements<int64_t> free_if;
    ReadArrElements<int64_t> into_start;
    ReadArrElements<int64_t> into_elem;
    ReadArrElements<int64_t> alloc_start;
    ReadArrElements<int64_t> alloc_elem;


    ap = static_cast<const Arr_Desc*>(vd3->ptr_array);

    // "pointers_number" for total number of transferred pointers.
    // For each of them we create new var_desc and put it at the bottom
    // of the var_desc's array
    get_arr_desc_numbers(ap, sizeof(void *), ptr.offset, ptr.size,
        pointers_number, ptr.ranges);
    ptr.base = (m_vars[i].flags.is_pointer) ?
               *(reinterpret_cast<char**>(ap->base)) :
               reinterpret_cast<char*>(ap->base);

    // 2. prepare memory for new var_descs
    m_vars_total += pointers_number;
    m_vars       = (VarDesc*)realloc(m_vars, m_vars_total * sizeof(VarDesc));
    if (m_vars == NULL)
      LIBOFFLOAD_ERROR(c_malloc);
    m_vars_extra =
        (VarExtra*)realloc(m_vars_extra, m_vars_total * sizeof(VarExtra));
    if (m_vars_extra == NULL)
      LIBOFFLOAD_ERROR(c_malloc);
    m_in_deps    =
        (COIEVENT*)realloc(m_in_deps, sizeof(COIEVENT) * (m_vars_total + 1));
    if (m_in_deps == NULL)
      LIBOFFLOAD_ERROR(c_malloc);
    m_out_deps   =
        (COIEVENT*)realloc(m_out_deps, sizeof(COIEVENT) * m_vars_total);
    if (m_out_deps == NULL)
      LIBOFFLOAD_ERROR(c_malloc);

    // 3. Prepare for reading new var_desc's fields
    //    EXTENT START
    if ((flags & (1<<flag_extent_start_is_array)) != 0) {
        ap = static_cast<const Arr_Desc*>(vd3->extent_start);
        get_arr_desc_numbers(ap, ap->dim[ap->rank - 1].size, ext_start.offset,
            ext_start.size, tmp_val, ext_start.ranges);
        ext_start.base = reinterpret_cast<char*>(ap->base);
        ext_start.el_size = ap->dim[ap->rank - 1].size;

        if (tmp_val < pointers_number) {
            LIBOFFLOAD_ERROR(c_pointer_array_mismatch, "extent start");
            return false;
        }
    }
    else if ((flags & (1<<flag_extent_start_is_scalar)) != 0) {
        ext_start.val = (int64_t)vd3->extent_start;
    }
    else {
        ext_start.val = 0;
    }

    //    EXTENT ELEMENTS NUMBER
    if ((flags & (1<<flag_extent_elements_is_array)) != 0) {
        ap = static_cast<const Arr_Desc*>(vd3->extent_elements);
        get_arr_desc_numbers(ap, ap->dim[ap->rank - 1].size,
            ext_elements.offset, ext_elements.size,
            tmp_val, ext_elements.ranges);
        ext_elements.base = reinterpret_cast<char*>(ap->base);
        ext_elements.el_size = ap->dim[ap->rank - 1].size;

        if (tmp_val < pointers_number) {
            LIBOFFLOAD_ERROR(c_pointer_array_mismatch, "extent elements");
            return false;
        }
    }
    else if ((flags & (1<<flag_extent_elements_is_scalar)) != 0) {
        ext_elements.val = (int64_t)vd3->extent_elements;
    }
    else {
        ext_elements.val = m_vars[i].count;
    }

    //    ALLOC_IF
    if ((flags & (1<<flag_alloc_if_is_array)) != 0) {
        ap = static_cast<const Arr_Desc*>(vd3->alloc_if_array);
        get_arr_desc_numbers(ap, ap->dim[ap->rank - 1].size, alloc_if.offset,
            alloc_if.size, tmp_val, alloc_if.ranges);
        alloc_if.base = reinterpret_cast<char*>(ap->base);
        alloc_if.el_size = ap->dim[ap->rank - 1].size;

        if (tmp_val < pointers_number) {
            LIBOFFLOAD_ERROR(c_pointer_array_mismatch, "alloc_if");
            return false;
        }
    }
    else {
        alloc_if.val = m_vars[i].alloc_if;
    }

    //    FREE_IF
    if ((flags & (1<<flag_free_if_is_array)) != 0) {
        ap = static_cast<const Arr_Desc*>(vd3->free_if_array);
        get_arr_desc_numbers(ap, ap->dim[ap->rank - 1].size, free_if.offset,
            free_if.size, tmp_val, free_if.ranges);
        free_if.base = reinterpret_cast<char*>(ap->base);
        free_if.el_size = ap->dim[ap->rank - 1].size;

        if (tmp_val < pointers_number) {
            LIBOFFLOAD_ERROR(c_pointer_array_mismatch, "free_if");
            return false;
        }
    }
    else {
        free_if.val = m_vars[i].free_if;
    }

    //    ALIGN

    if ((flags & (1<<flag_align_is_array)) != 0) {
        ap = static_cast<const Arr_Desc*>(vd3->align_array);
        get_arr_desc_numbers(ap, ap->dim[ap->rank - 1].size, align.offset,
            align.size, tmp_val, align.ranges);
        align.base = reinterpret_cast<char*>(ap->base);
        align.el_size = ap->dim[ap->rank - 1].size;

        if (tmp_val < pointers_number) {
            LIBOFFLOAD_ERROR(c_pointer_array_mismatch, "align");
            return false;
        }
    }
    else {
        align.val = m_vars[i].align;
    }

    // 3.1 INTO

    if (m_vars[i].into) {
        ap = static_cast<const Arr_Desc*>(m_vars[i].into);
        get_arr_desc_numbers(ap, ap->dim[ap->rank - 1].size, into.offset,
            into.size, tmp_val, into.ranges);
        into.base = reinterpret_cast<char*>(ap->base);

        if (tmp_val < pointers_number) {
            LIBOFFLOAD_ERROR(c_pointer_array_mismatch, "into");
            return false;
        }
    }

    // 3.2 INTO_START

    if ((flags & (1<<flag_into_start_is_array)) != 0) {
        ap = static_cast<const Arr_Desc*>(vd3->into_start);
        get_arr_desc_numbers(ap, ap->dim[ap->rank - 1].size, into_start.offset,
            into_start.size, tmp_val, into_start.ranges);
        into_start.base = reinterpret_cast<char*>(ap->base);
        into_start.el_size = ap->dim[ap->rank - 1].size;

        if (tmp_val < pointers_number) {
            LIBOFFLOAD_ERROR(c_pointer_array_mismatch, "into_extent start");
            return false;
        }
    }
    else if ((flags & (1<<flag_into_start_is_scalar)) != 0) {
        into_start.val = (int64_t)vd3->into_start;
    }
    else {
        into_start.val = 0;
    }

    // 3.3 INTO_ELEMENTS

    if ((flags & (1<<flag_into_elements_is_array)) != 0) {
        ap = static_cast<const Arr_Desc*>(vd3->into_elements);
        get_arr_desc_numbers(ap, ap->dim[ap->rank - 1].size, into_elem.offset,
            into_elem.size, tmp_val, into_elem.ranges);
        into_elem.base = reinterpret_cast<char*>(ap->base);
        into_elem.el_size = ap->dim[ap->rank - 1].size;

        if (tmp_val < pointers_number) {
            LIBOFFLOAD_ERROR(c_pointer_array_mismatch, "into_extent elements");
            return false;
        }
    }
    else if ((flags & (1<<flag_into_elements_is_scalar)) != 0) {
        into_elem.val = (int64_t)vd3->into_elements;
    }
    else {
        into_elem.val = m_vars[i].count;
    }

    //    alloc_start

    if ((flags & (1<<flag_alloc_start_is_array)) != 0) {
        ap = static_cast<const Arr_Desc*>(vd3->alloc_start);
        get_arr_desc_numbers(ap, ap->dim[ap->rank - 1].size,
            alloc_start.offset, alloc_start.size, tmp_val,
            alloc_start.ranges);
        alloc_start.base = reinterpret_cast<char*>(ap->base);
        alloc_start.el_size = ap->dim[ap->rank - 1].size;

        if (tmp_val < pointers_number) {
            LIBOFFLOAD_ERROR(c_pointer_array_mismatch, "alloc_extent start");
            return false;
        }
    }
    else if ((flags & (1<<flag_alloc_start_is_scalar)) != 0) {
        alloc_start.val = (int64_t)vd3->alloc_start;
    }
    else {
        alloc_start.val = 0;
    }

    //    alloc_elem

    if ((flags & (1<<flag_alloc_elements_is_array)) != 0) {
        ap = static_cast<const Arr_Desc*>(vd3->alloc_elements);
        get_arr_desc_numbers(ap, ap->dim[ap->rank - 1].size, alloc_elem.offset,
            alloc_elem.size, tmp_val, alloc_elem.ranges);
        alloc_elem.base = reinterpret_cast<char*>(ap->base);
        alloc_elem.el_size = ap->dim[ap->rank - 1].size;
        if (tmp_val < pointers_number) {
            LIBOFFLOAD_ERROR(c_pointer_array_mismatch,
                             "alloc_extent elements");
            return false;
        }
    }
    else if ((flags & (1<<flag_alloc_elements_is_scalar)) != 0) {
        alloc_elem.val = (int64_t)vd3->alloc_elements;
    }
    else {
        alloc_elem.val = 0;
    }

    for (int k = 0; k < pointers_number; k++) {
        int type = flags & 0x3f;
        int type_src, type_dst;
        //  Get new values
        // type_src, type_dst
        type_src = type_dst = (type == c_data_ptr_array) ?
                              c_data_ptr   : (type == c_func_ptr_array) ?
                              c_func_ptr   : (type == c_void_ptr_array) ?
                              c_void_ptr   : (type == c_string_ptr_array) ?
                              c_string_ptr : 0;

        // Get ptr val
        if (!ptr.read_next(true)) {
            break;
        }
        else {
            ptr.val = (void*)(ptr.base + ptr.offset);
        }

        // !!! If we got error at phase of reading - it's an internal
        // !!! error, as we must detect mismatch before

        // Get into val
        if (m_vars[i].into) {
            if (!into.read_next(true)) {
                LIBOFFLOAD_ERROR(c_pointer_array_mismatch, "into");
                LIBOFFLOAD_ABORT;
            }
            else {
                into.val = (void*)(into.base + into.offset);
            }
        }

        // Get other components of the clause
        if (!ext_start.read_next(flags & (1<<flag_extent_start_is_array))) {
            LIBOFFLOAD_ERROR(c_pointer_array_mismatch, "extent start");
            LIBOFFLOAD_ABORT;
        }
        if (!ext_elements.read_next(
                flags & (1<<flag_extent_elements_is_array))) {
            LIBOFFLOAD_ERROR(c_pointer_array_mismatch, "extent elements");
            LIBOFFLOAD_ABORT;
        }
        if (!alloc_if.read_next(flags & (1<<flag_alloc_if_is_array))) {
            LIBOFFLOAD_ERROR(c_pointer_array_mismatch, "alloc_if");
            LIBOFFLOAD_ABORT;
        }
        if (!free_if.read_next(flags & (1<<flag_free_if_is_array))) {
            LIBOFFLOAD_ERROR(c_pointer_array_mismatch, "free_if");
            LIBOFFLOAD_ABORT;
        }
        if (!align.read_next(flags & (1<<flag_align_is_array))) {
            LIBOFFLOAD_ERROR(c_pointer_array_mismatch, "align");
            LIBOFFLOAD_ABORT;
        }
        if (!into_start.read_next(flags & (1<<flag_into_start_is_array))) {
            LIBOFFLOAD_ERROR(c_pointer_array_mismatch, "into_extent start");
            LIBOFFLOAD_ABORT;
        }
        if (!into_elem.read_next(flags & (1<<flag_into_elements_is_array))) {
            LIBOFFLOAD_ERROR(c_pointer_array_mismatch, "into_extent elements");
            LIBOFFLOAD_ABORT;
        }
        if (!alloc_start.read_next(flags & (1<<flag_alloc_start_is_array))) {
            LIBOFFLOAD_ERROR(c_pointer_array_mismatch, "alloc_extent start");
            LIBOFFLOAD_ABORT;
        }
        if (!alloc_elem.read_next(
                 flags & (1<<flag_alloc_elements_is_array))) {
            LIBOFFLOAD_ERROR(c_pointer_array_mismatch, "alloc_extent elements");
            LIBOFFLOAD_ABORT;
        }

        m_vars[new_index + k].direction.bits = m_vars[i].direction.bits;
        m_vars[new_index + k].alloc_if = alloc_if.val;
        m_vars[new_index + k].free_if = free_if.val;
        m_vars[new_index + k].align = align.val;
        m_vars[new_index + k].mic_offset = 0;
        m_vars[new_index + k].flags.bits = m_vars[i].flags.bits;
        m_vars[new_index + k].offset = 0;
        m_vars[new_index + k].size = m_vars[i].size;
        m_vars[new_index + k].flags.targetptr = m_vars[i].flags.targetptr;
        m_vars[new_index + k].flags.preallocated =
                                             m_vars[i].flags.preallocated;

        if (ext_start.val == 0) {
            m_vars[new_index + k].count = ext_elements.val;
            m_vars[new_index + k].ptr = ptr.val;
            if (type_src == c_string_ptr) {
                m_vars[new_index + k].size = 0;
            }
        }
        else {
            m_vars[new_index + k].count = 0;
            m_vars[new_index + k].ptr =
                static_cast<void*>(make_arr_desc(
                ptr.val,
                ext_start.val,
                ext_elements.val,
                m_vars[i].size));

            type_src = type_src == c_data_ptr ? c_cean_var_ptr :
                                   c_string_ptr ? c_cean_var_ptr :
                                   type_src;
            if (!m_vars[i].into) {
                type_dst = type_src;
            }
        }

        if (m_vars[i].into && into_elem.val != 0) {
            m_vars[new_index + k].into =
                static_cast<void*>(make_arr_desc(
                into.val,
                into_start.val,
                into_elem.val,
                m_vars[i].size));
            type_dst = (type == c_data_ptr_array) ? c_cean_var_ptr :
                       (type == c_string_ptr_array) ? c_cean_var_ptr :
                        type_src;
        }
        else {
            m_vars[new_index + k].into = NULL;
        }

        if (alloc_elem.val != 0) {
            m_vars[new_index + k].alloc =
                static_cast<void*>(make_arr_desc(
                ptr.val,
                alloc_start.val,
                alloc_elem.val,
                m_vars[i].size));
        }
        else {
            m_vars[new_index + k].alloc = NULL;
        }

        m_vars[new_index + k].type.src = type_src;
        m_vars[new_index + k].type.dst = type_dst;

        m_vars_extra[new_index + k].alloc = m_vars[new_index + k].alloc;
        m_vars_extra[new_index + k].is_arr_ptr_el = 1;
        m_vars_extra[new_index + k].ptr_arr_offset =
            src_is_for_mic ? ptr.offset : into.offset;
    }
    // count and alloc fields are useless at target. They can be reused
    // for pointer arrays.
    m_vars[i].count = pointers_number;
    m_vars[i].ptr_arr_offset = new_index;
    return true;
}

// Gets in dependencies of the previous offload via the stream "m_stream".
// Out argument in_deps_amount - address of amount of the dependencies
// Out argument in_deps - array of dependencies.
// Description of the dependencies scheme for streams :
// ----------------------------------------------------
// Every offload forms DAG consisted of 3 nodes:
// for in-transfers, runfunction and out-transfers.
// Every node has in-dependencies and out-dependencies
// Out-dependencies of previous node forms in-dependencies of current node.
// In-dependencies of 1-st node (of in-transfers) without streams is equal
// to NULL. For streams in-dependencies of 1-st node is equal to list of out
// dependencies of last node of previous offload via this stream.
// So we can say that DAGs of 2 consequent offloads via the same stream are
// connected by the way described above.
void OffloadDescriptor::get_stream_in_dependencies(
    uint32_t &in_deps_amount,
    COIEVENT* &in_deps
)
{
    if (m_stream != no_stream && m_stream != 0) {
        Stream * stream = Stream::find_stream(m_stream, false);
        if (!stream) {
            LIBOFFLOAD_ERROR(c_offload_no_stream,
                             m_device.get_logical_index());
            LIBOFFLOAD_ABORT;
        }
        OffloadDescriptor* offload = stream->get_last_offload();

        // if it's the first offload in the stream
        if (!offload) {
            return;
        }
        // if last offload has out-tranfers
        if (offload->m_out_deps_total) {
            in_deps_amount = offload->m_out_deps_total;
            in_deps = offload->m_out_deps;
        }
        // last offload only sends pointer data or run function or both of them
        // and has no out-transfers
        else if (offload->m_in_deps_total) {
            in_deps_amount = offload->m_in_deps_total;
            in_deps = offload->m_in_deps;
        }
    }
}

static void __offload_fini_library(void)
{
    OFFLOAD_DEBUG_TRACE(2, "Cleanup offload library ...\n");
    if (mic_engines_total > 0) {
        delete[] mic_engines;
        mic_engines_total = 0;

        if (mic_proxy_fs_root != 0) {
            free(mic_proxy_fs_root);
            mic_proxy_fs_root = 0;
        }

        if (mic_library_path != 0) {
            free(mic_library_path);
            mic_library_path = 0;
        }

        // destroy thread key
        thread_key_delete(mic_thread_key);
    }

    // unload COI library
    if (COI::is_available) {
        COI::fini();
    }

    OFFLOAD_DEBUG_TRACE(2, "Cleanup offload library ... done\n");
}

static void __offload_init_library_once(void)
{
    COIRESULT res;
    uint32_t num_devices;
    std::bitset<MIC_ENGINES_MAX> devices;
    prefix = report_get_message_str(c_report_host);

    // initialize trace
    const char *env_var = getenv(htrace_envname);
    if (env_var != 0 && *env_var != '\0') {
        int64_t new_val;
        if (__offload_parse_int_string(env_var, new_val)) {
            console_enabled = new_val & 0x0f;
        }
    }

    env_var = getenv(offload_report_envname);
    if (env_var != 0 && *env_var != '\0') {
        int64_t env_val;
        if (__offload_parse_int_string(env_var, env_val)) {
            if (env_val == OFFLOAD_REPORT_1 ||
                env_val == OFFLOAD_REPORT_2 ||
                env_val == OFFLOAD_REPORT_3) {
                offload_report_level = env_val;
            }
            else {
                LIBOFFLOAD_ERROR(c_invalid_env_report_value,
                                 offload_report_envname);
            }
        }
        else {
            LIBOFFLOAD_ERROR(c_invalid_env_var_int_value,
                             offload_report_envname);
        }
    }
    else if (!offload_report_level) {
        env_var = getenv(timer_envname);
        if (env_var != 0 && *env_var != '\0') {
            timer_enabled = atoi(env_var);
        }
    }

    // initialize COI
    if (!COI::init()) {
        return;
    }

    // get number of devices installed in the system
    res = COI::EngineGetCount(COI_ISA_MIC, &num_devices);
    if (res != COI_SUCCESS) {
        return;
    }

    if (num_devices > MIC_ENGINES_MAX) {
        num_devices = MIC_ENGINES_MAX;
    }

    // fill in the list of devices that can be used for offloading
    env_var = getenv("OFFLOAD_DEVICES");
    if (env_var != 0) {
        if (strcasecmp(env_var, "none") != 0) {
            // value is composed of comma separated physical device indexes
            char *buf = strdup(env_var);
	    if (buf == NULL)
	      LIBOFFLOAD_ERROR(c_malloc);
            char *str, *ptr;
            for (str = strtok_r(buf, ",", &ptr); str != 0;
                 str = strtok_r(0, ",", &ptr)) {
                // convert string to an int
                int64_t num;
                if (!__offload_parse_int_string(str, num)) {
                    LIBOFFLOAD_ERROR(c_mic_init5);

                    // fallback to using all installed devices
                    devices.reset();
                    for (int i = 0; i < num_devices; i++) {
                        devices.set(i);
                    }
                    break;
                }
                if (num < 0 || num >= num_devices) {
                    LIBOFFLOAD_ERROR(c_mic_init6, num);
                    continue;
                }
                devices.set(num);
            }
            free(buf);
        }
    }
    else {
        // use all available devices
        for (int i = 0; i < num_devices; i++) {
            COIENGINE engine;
            res = COI::EngineGetHandle(COI_ISA_MIC, i, &engine);
            if (res == COI_SUCCESS) {
                devices.set(i);
            }
        }
    }

    mic_engines_total = devices.count();

    // no need to continue if there are no devices to offload to
    if (mic_engines_total <= 0) {
        return;
    }

    // initialize indexes for available devices
    mic_engines = new Engine[mic_engines_total];
    for (int p_idx = 0, l_idx = 0; p_idx < num_devices; p_idx++) {
        if (devices[p_idx]) {
            mic_engines[l_idx].set_indexes(l_idx, p_idx);
            l_idx++;
        }
    }

    // Get DMA channel count to pass it to COI
    env_var = getenv("OFFLOAD_DMA_CHANNEL_COUNT");
    if (env_var != 0) {
        int64_t new_val;
        if (__offload_parse_int_string(env_var, new_val)) {
            mic_dma_channel_count = new_val;
        }
        else {
            LIBOFFLOAD_ERROR(c_invalid_env_var_value,
                             "OFFLOAD_DMA_CHANNEL_COUNT");
        }
    }

    // Set COI_HOST_THREAD_AFFINITY if OFFLOAD_HOST_THREAD_AFFINITY is set.
    // Use putenv instead of setenv as Windows has no setenv.
    // Note: putenv requires its argument can't be freed or modified.
    // So no free after call to putenv or elsewhere.
    env_var = getenv("OFFLOAD_HOST_THREAD_AFFINITY");
    if (env_var != 0) {
        char * new_env_var =
                   (char*) malloc(sizeof("COI_HOST_THREAD_AFFINITY=") +
                                  strlen(env_var));
	if (new_env_var == NULL)
	  LIBOFFLOAD_ERROR(c_malloc);
        sprintf(new_env_var, "COI_HOST_THREAD_AFFINITY=%s", env_var);
        putenv(new_env_var);
    }

    // library search path for device binaries
    env_var = getenv("MIC_LD_LIBRARY_PATH");
    if (env_var != 0) {
        mic_library_path = strdup(env_var);
	if (mic_library_path == NULL)
	  LIBOFFLOAD_ERROR(c_malloc);
    }


    // find target executable to be used if main application is not an
    // offload build application.
    const char *base_name = "offload_main";
    if (mic_library_path != 0) {
        char *buf = strdup(mic_library_path);
	if (buf == NULL)
	  LIBOFFLOAD_ERROR(c_malloc);
        char *try_name = (char*) alloca(strlen(mic_library_path) +
                strlen(base_name) + 2);
        char *dir, *ptr;

        for (dir = strtok_r(buf, PATH_SEPARATOR, &ptr); dir != 0;
             dir = strtok_r(0, PATH_SEPARATOR, &ptr)) {
            // compose a full path
            sprintf(try_name, "%s/%s", dir, base_name);

            // check if such file exists
            struct stat st;
            if (stat(try_name, &st) == 0 && S_ISREG(st.st_mode)) {
                mic_device_main = strdup(try_name);
		if (mic_device_main == NULL)
		  LIBOFFLOAD_ERROR(c_malloc);
                break;
            }
        }

        free(buf);
    }

    // memory size reserved for COI buffers
    env_var = getenv("MIC_BUFFERSIZE");
    if (env_var != 0) {
        uint64_t new_size;
        if (__offload_parse_size_string(env_var, new_size)) {
            mic_buffer_size = new_size;
        }
        else {
            LIBOFFLOAD_ERROR(c_invalid_env_var_value, "MIC_BUFFERSIZE");
        }
    }

    // memory size reserved for 4K pages for COI buffers
    env_var = getenv("MIC_4K_BUFFER_RESERVE_SIZE");
    if (env_var != 0) {
        uint64_t new_size;
        if (__offload_parse_size_string(env_var, new_size)) {
            mic_4k_buffer_size = new_size;
        }
        else {
            LIBOFFLOAD_ERROR(c_invalid_env_var_value, "MIC_4K_BUFFER_RESERVE_SIZE");
        }
    }

    // memory size reserved for 2M pages for COI buffers
    env_var = getenv("MIC_2M_BUFFER_RESERVE_SIZE");
    if (env_var != 0) {
        uint64_t new_size;
        if (__offload_parse_size_string(env_var, new_size)) {
            mic_2m_buffer_size = new_size;
        }
        else {
            LIBOFFLOAD_ERROR(c_invalid_env_var_value, "MIC_2M_BUFFER_RESERVE_SIZE");
        }
    }

    // determine stacksize for the pipeline on the device
    env_var = getenv("MIC_STACKSIZE");
    if (env_var != 0 && *env_var != '\0') {
        uint64_t new_size;
        if (__offload_parse_size_string(env_var, new_size) &&
            (new_size >= 16384) && ((new_size & 4095) == 0)) {
            mic_stack_size = new_size;
        }
        else {
            LIBOFFLOAD_ERROR(c_mic_init3);
        }
    }

    // proxy I/O
    env_var = getenv("MIC_PROXY_IO");
    if (env_var != 0 && *env_var != '\0') {
        int64_t new_val;
        if (__offload_parse_int_string(env_var, new_val)) {
            mic_proxy_io = new_val;
        }
        else {
            LIBOFFLOAD_ERROR(c_invalid_env_var_int_value, "MIC_PROXY_IO");
        }
    }
    env_var = getenv("MIC_PROXY_FS_ROOT");
    if (env_var != 0 && *env_var != '\0') {
        mic_proxy_fs_root = strdup(env_var);
	if (mic_proxy_fs_root == NULL)
	  LIBOFFLOAD_ERROR(c_malloc);
    }

    // Prepare environment for the target process using the following
    // rules
    // - If MIC_ENV_PREFIX is set then any environment variable on the
    //   host which has that prefix are copied to the device without
    //   the prefix.
    //   All other host environment variables are ignored.
    // - If MIC_ENV_PREFIX is not set or if MIC_ENV_PREFIX="" then host
    //   environment is duplicated.
    env_var = getenv("MIC_ENV_PREFIX");
    if (env_var != 0 && *env_var != '\0') {
        mic_env_vars.set_prefix(env_var);

        int len = strlen(env_var);
        for (int i = 0; environ[i] != 0; i++) {
            if (strncmp(environ[i], env_var, len) == 0 &&
                strncmp(environ[i], "MIC_LD_LIBRARY_PATH", 19) != 0 &&
                environ[i][len] != '=') {
                mic_env_vars.analyze_env_var(environ[i]);
            }
        }
    }

    // create key for thread data
    if (thread_key_create(&mic_thread_key, Engine::destroy_thread_data)) {
        LIBOFFLOAD_ERROR(c_mic_init4, errno);
        return;
    }

    // cpu frequency
    cpu_frequency = COI::PerfGetCycleFrequency();

    env_var = getenv(mic_use_2mb_buffers_envname);
    if (env_var != 0 && *env_var != '\0') {
        uint64_t new_size;
        if (__offload_parse_size_string(env_var, new_size)) {
            __offload_use_2mb_buffers = new_size;
        }
        else {
            LIBOFFLOAD_ERROR(c_invalid_env_var_value,
                             mic_use_2mb_buffers_envname);
        }
    }

    env_var = getenv(mic_use_async_buffer_write_envname);
    if (env_var != 0 && *env_var != '\0') {
        uint64_t new_size;
        if (__offload_parse_size_string(env_var, new_size)) {
            __offload_use_async_buffer_write = new_size;
        }
    }

    env_var = getenv(mic_use_async_buffer_read_envname);
    if (env_var != 0 && *env_var != '\0') {
        uint64_t new_size;
        if (__offload_parse_size_string(env_var, new_size)) {
            __offload_use_async_buffer_read = new_size;
        }
    }

    // mic initialization type
    env_var = getenv(offload_init_envname);
    if (env_var != 0 && *env_var != '\0') {
        if (strcmp(env_var, "on_offload") == 0) {
            __offload_init_type = c_init_on_offload;
        }
        else if (strcmp(env_var, "on_offload_all") == 0) {
            __offload_init_type = c_init_on_offload_all;
        }
        else if (strcmp(env_var, "on_start") == 0) {
            __offload_init_type = c_init_on_start;
        }
        else {
            LIBOFFLOAD_ERROR(c_invalid_env_var_value, offload_init_envname);
        }
    }

    // active wait
    env_var = getenv(offload_active_wait_envname);
    if (env_var != 0 && *env_var != '\0') {
        int64_t new_val;
        if (__offload_parse_int_string(env_var, new_val)) {
            __offload_active_wait = new_val;
        }
        else {
            LIBOFFLOAD_ERROR(c_invalid_env_var_int_value,
                             offload_active_wait_envname);
        }
    }

    // omp device num
    env_var = getenv(omp_device_num_envname);
    if (env_var != 0 && *env_var != '\0') {
        int64_t new_val;
        if (__offload_parse_int_string(env_var, new_val) && new_val >= 0) {
            __omp_device_num = new_val;
        }
        else {
            LIBOFFLOAD_ERROR(c_omp_invalid_device_num_env,
                             omp_device_num_envname);
        }
    }

    // parallel copy of offload_transfer
    env_var = getenv(parallel_copy_envname);
    if (env_var != 0 && *env_var != '\0') {
        int64_t new_val;
        if (__offload_parse_int_string(env_var, new_val) && new_val >= 0) {
            __offload_parallel_copy = new_val;
        }
        else {
            LIBOFFLOAD_ERROR(c_invalid_env_var_value,
                             parallel_copy_envname);
        }
    }

    // use COI interface for noncontiguous arrays transfer
    env_var = getenv(use_coi_noncontiguous_transfer_envname);
    if (env_var != 0 && *env_var != '\0') {
        uint64_t new_size;
        if (__offload_parse_size_string(env_var, new_size)) {
            __offload_use_coi_noncontiguous_transfer = new_size;
        }
        else {
            LIBOFFLOAD_ERROR(c_invalid_env_var_value,
                             use_coi_noncontiguous_transfer_envname);
        }
    }

    // init ORSL
    ORSL::init();
}

extern int __offload_init_library(void)
{
    // do one time intialization
    static OffloadOnceControl ctrl = OFFLOAD_ONCE_CONTROL_INIT;
    __offload_run_once(&ctrl, __offload_init_library_once);

    // offload is available if COI is available and the number of devices > 0
    bool is_available = COI::is_available && (mic_engines_total > 0);

    // register pending libraries if there are any
    if (is_available && __target_libs) {
        mutex_locker_t locker(__target_libs_lock);

        for (TargetImageList::iterator it = __target_libs_list.begin();
             it != __target_libs_list.end(); it++) {
            // Register library in COI
            COI::ProcessRegisterLibraries(1, &it->data, &it->size,
                                          &it->origin, &it->offset);

            // add lib to all engines
            for (int i = 0; i < mic_engines_total; i++) {
                mic_engines[i].add_lib(*it);
            }
        }

        __target_libs = false;
        __target_libs_list.clear();
    }

    return is_available;
}

extern "C" bool __offload_target_image_is_executable(const void *target_image)
{
    const struct Image *image = static_cast<const struct Image*>(target_image);

    // decode image
    const char *name = image->data;
    const void *data = image->data + strlen(image->data) + 1;

    // determine image type
    const Elf64_Ehdr *hdr = static_cast<const Elf64_Ehdr*>(data);
    return (hdr->e_type == ET_EXEC);
}

extern "C" bool __offload_register_image(const void *target_image)
{
    const struct Image *image = static_cast<const struct Image*>(target_image);

    // decode image
    const char *name = image->data;
    const void *data = image->data + strlen(image->data) + 1;
    uint64_t    size = image->size;
    char *origin     = (char *) malloc(strlen(image->data) + 1);
    uint64_t    offset = 0;
    const char *host_name = image->data;
    int        i;

    if (origin == NULL)
        LIBOFFLOAD_ERROR(c_malloc);

    // The origin name is the name of the file on the host
    // this is used by Vtune, since it is a fat binary we
    // use the host file name of the fat binary.
    // Driver prepends the host file name ending with "?"
    // to the image->data name so need to extract the string
    i = 0;
    while (*host_name != '\0'  && *host_name != '?') {
       origin[i] = *host_name;
       host_name++;
       i++;
    }
    origin[i] = '\0';
    // Implies the host name does not exist which really should
    // not occur. Allow this since only consumer is Vtune.
    if ((i == 0) || (*host_name != '?')) {
       free(origin);
       origin = 0;
    }

    // our actions depend on the image type
    const Elf64_Ehdr *hdr = static_cast<const Elf64_Ehdr*>(data);
    switch (hdr->e_type) {
        case ET_EXEC:
            // Each offload application is supposed to have only one target
            // image representing target executable.
            // No thread synchronization is required here as the initialization
            // code is always executed in a single thread.
            if (__target_exe != 0) {
                LIBOFFLOAD_ERROR(c_multiple_target_exes);
                exit(1);
            }
            __target_exe = new TargetImage(name, data, size, origin, offset);

            // Registration code for execs is always called from the context
            // of main and thus we can safely call any function here,
            // including LoadLibrary API on windows. This is the place where
            // we do the offload library initialization.
            if (__offload_init_library()) {
                // initialize engine if init_type is on_start
                if (__offload_init_type == c_init_on_start) {
                    for (int i = 0; i < mic_engines_total; i++) {
                        mic_engines[i].init();
                    }
                }
            }
            return mic_engines_total > 0;

        case ET_DYN:
        {
		char *fullname = origin;
                // We add the library to a list of pending libraries
                __target_libs_lock.lock();
                __target_libs = true;
                __target_libs_list.push_back(
                    TargetImage(name, data, size, fullname, offset));
                __target_libs_lock.unlock();
                // If __target_exe is set, then main has started running
                // If not main, then we can't do anything useful here
                // because this registration code is called from DllMain
                // context (on windows).
                if (__target_exe != 0) {
                    // There is no need to delay loading the library
                    if (!__offload_init_library()) {
                        // Couldn't validate library as a fat offload library
                        LIBOFFLOAD_ERROR(c_unknown_binary_type);
                        exit(1);
                    }
                }
            return true;
        }

        default:
            // something is definitely wrong, issue an error and exit
            LIBOFFLOAD_ERROR(c_unknown_binary_type);
            exit(1);
    }
}

extern "C" void __offload_unregister_image(const void *target_image)
{
    // Target image is packed as follows:
    //      8 bytes                - size of the target binary
    //      null-terminated string - binary name
    //      <size> bytes           - binary contents
    const struct Image {
         int64_t size;
         char data[];
    } *image = static_cast<const struct Image*>(target_image);

    // decode image
    const char *name = image->data;
    const void *data = image->data + strlen(image->data) + 1;

    // our actions depend on the image type
    const Elf64_Ehdr *hdr = static_cast<const Elf64_Ehdr*>(data);
    if (hdr->e_type == ET_EXEC) {
        // We are executing exec's desctructors.
        // It is time to do a library cleanup.
        if (timer_enabled) {
            Offload_Timer_Print();
        }

#ifdef MYO_SUPPORT
        __offload_myoFini();
#endif // MYO_SUPPORT

        __offload_fini_library();
    }
    else if (hdr->e_type == ET_DYN) {
        for (int i = 0; i < mic_engines_total; i++) {
           mic_engines[i].unload_library(data, name);
        }

    }
}

extern "C" void __offload_register_task_callback(void (*cb)(void *))
{
    task_completion_callback = cb;
}

// Runtime trace interface for user programs

void __offload_console_trace(int level)
{
    console_enabled = level;
}

// User-visible offload API

int _Offload_number_of_devices(void)
{
    __offload_init_library();
    return mic_engines_total;
}

int _Offload_get_device_number(void)
{
    return -1;
}

int _Offload_get_physical_device_number(void)
{
    return -1;
}

int _Offload_signaled(int index, void *signal)
{
    __offload_init_library();

    // check index value
    if (index < 0) {
        LIBOFFLOAD_ERROR(c_offload_signaled1, index);
        LIBOFFLOAD_ABORT;
    }

    index %= mic_engines_total;

    // find associated async task
    OffloadDescriptor *task =
        mic_engines[index].find_signal(signal, false);
    if (task == 0) {
        LIBOFFLOAD_ERROR(c_offload_signaled2, signal);
        LIBOFFLOAD_ABORT;
    }
    // if signal is removed by wait completing
    else if (task == SIGNAL_IS_REMOVED) {
        return (true);
    }
    return task->is_signaled();
}

void _Offload_report(int val)
{
    if (val == OFFLOAD_REPORT_ON ||
        val == OFFLOAD_REPORT_OFF) {
        offload_report_enabled = val;
    }
}

int _Offload_find_associated_mic_memory(
    int          target,
    const void*  cpu_addr,
    void**       cpu_base_addr,
    uint64_t*    buf_length,
    void**       mic_addr,
    uint64_t*    mic_buf_start_offset,
    int*         is_static
)
{
    __offload_init_library();

    // check target value
    if (target < 0) {
        LIBOFFLOAD_ERROR(c_offload_signaled1, target);
        LIBOFFLOAD_ABORT;
    }
    target %= mic_engines_total;

    // find existing association in pointer table
    PtrData* ptr_data = mic_engines[target].find_ptr_data(cpu_addr);
    if (ptr_data == 0) {
        OFFLOAD_TRACE(3, "Association does not exist\n");
        return 0;
    }

    OFFLOAD_TRACE(3, "Found association: base %p, length %lld, is_static %d\n",
                  ptr_data->cpu_addr.start(), ptr_data->cpu_addr.length(),
                  ptr_data->is_static);

    if (ptr_data->mic_buf != 0 && ptr_data->mic_addr == 0) {
        COIRESULT res = COI::BufferGetSinkAddress(ptr_data->mic_buf,
                                                  &ptr_data->mic_addr);
        if (res != COI_SUCCESS) {
            return 0;
        }
    }
    *cpu_base_addr = const_cast<void *>(ptr_data->cpu_addr.start());
    *buf_length = ptr_data->cpu_addr.length() - ptr_data->alloc_disp;
    *mic_addr = (void *)(ptr_data->mic_addr + ptr_data->mic_offset);
    *mic_buf_start_offset = ptr_data->alloc_disp;
    *is_static = ptr_data->is_static;
    return ptr_data->is_static ? 1 : ptr_data->get_reference();
}

_Offload_stream _Offload_stream_create(
    int device,           // MIC device number
    int number_of_cpus    // Cores allocated to the stream
    )
{
    __offload_init_library();

    // check target value
    if (device < 0) {
        LIBOFFLOAD_ERROR(c_offload_signaled1, device);
        LIBOFFLOAD_ABORT;
    }
    device %= mic_engines_total;

    // Create new stream and get its handle
    _Offload_stream handle = Stream::add_stream(device, number_of_cpus);
    if (handle == 0) {
        OFFLOAD_TRACE(3, "Can't create stream\n");
        return 0;
    }

    // create pipeline associated with the new stream
    mic_engines[device].get_pipeline(handle);

    return(handle);
}

int _Offload_stream_destroy(
    int             device,   // MIC device number
    _Offload_stream handle    // stream to destroy
    )
{
    __offload_init_library();

    // check target value
    if (device < 0) {
        LIBOFFLOAD_ERROR(c_offload_signaled1, device);
        LIBOFFLOAD_ABORT;
    }
    device %= mic_engines_total;

    mic_engines[device].stream_destroy(handle);

    return(true);
}

int _Offload_stream_completed(int device, _Offload_stream handler)
{
    __offload_init_library();

    // check index value
    if (device < 0) {
        LIBOFFLOAD_ERROR(c_offload_signaled1, device);
        LIBOFFLOAD_ABORT;
    }

    device %= mic_engines_total;

    // get stream
    Stream * stream;

    if (handler != 0) {
        stream =  Stream::find_stream(handler, false);

        // the stream was not created or was destroyed
        if (!stream) {
            LIBOFFLOAD_ERROR(c_offload_no_stream, device);
            LIBOFFLOAD_ABORT;
        }

        // find associated async task
        OffloadDescriptor *task = stream->get_last_offload();

        // offload was completed by offload_wait pragma or wait clause
        if (task == 0) {
            return(true);
        }
        return task->is_signaled();
    }
    // zero handler is for all streams at the device
    else {
        StreamMap stream_map = Stream::all_streams;
        for (StreamMap::iterator it = stream_map.begin();
            it != stream_map.end(); it++) {
            Stream * stream = it->second;
            // find associated async task
            OffloadDescriptor *task = stream->get_last_offload();

            // offload was completed by offload_wait pragma or wait clause
            if (task == 0) {
                return(true);
            }
            // if even one stream is not completed result is false
            if (!task->is_signaled()) {
                return false;
            }
        }
        // no uncompleted streams
        return true;
    }
}

// IDB support
int   __dbg_is_attached = 0;
int   __dbg_target_id = -1;
pid_t __dbg_target_so_pid = -1;
char  __dbg_target_exe_name[MAX_TARGET_NAME] = {0};
const int __dbg_api_major_version = 1;
const int __dbg_api_minor_version = 0;

void __dbg_target_so_loaded()
{
}
void __dbg_target_so_unloaded()
{
}