aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/libs/cxxsupp/openmp/kmp_dispatch.cpp
blob: 8dccef616aabc0f4331db2b0abe5223093f9e0b9 (plain) (blame)
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
/*
 * kmp_dispatch.cpp: dynamic scheduling - iteration initialization and dispatch.
 */


//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.txt for details.
//
//===----------------------------------------------------------------------===//


/*
 * Dynamic scheduling initialization and dispatch.
 *
 * NOTE: __kmp_nth is a constant inside of any dispatch loop, however
 *       it may change values between parallel regions.  __kmp_max_nth
 *       is the largest value __kmp_nth may take, 1 is the smallest.
 *
 */

/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */

#include "kmp.h"
#include "kmp_i18n.h"
#include "kmp_itt.h"
#include "kmp_str.h"
#include "kmp_error.h"
#include "kmp_stats.h"
#if KMP_OS_WINDOWS && KMP_ARCH_X86
    #include <float.h>
#endif

#if OMPT_SUPPORT
#include "ompt-internal.h"
#include "ompt-specific.h"
#endif

/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */

// template for type limits
template< typename T >
struct i_maxmin {
    static const T mx;
    static const T mn;
};
template<>
struct i_maxmin< int > {
    static const int mx = 0x7fffffff;
    static const int mn = 0x80000000;
};
template<>
struct i_maxmin< unsigned int > {
    static const unsigned int mx = 0xffffffff;
    static const unsigned int mn = 0x00000000;
};
template<>
struct i_maxmin< long long > {
    static const long long mx = 0x7fffffffffffffffLL;
    static const long long mn = 0x8000000000000000LL;
};
template<>
struct i_maxmin< unsigned long long > {
    static const unsigned long long mx = 0xffffffffffffffffLL;
    static const unsigned long long mn = 0x0000000000000000LL;
};
//-------------------------------------------------------------------------

#ifdef KMP_STATIC_STEAL_ENABLED

    // replaces dispatch_private_info{32,64} structures and dispatch_private_info{32,64}_t types
    template< typename T >
    struct dispatch_private_infoXX_template {
        typedef typename traits_t< T >::unsigned_t  UT;
        typedef typename traits_t< T >::signed_t    ST;
        UT count;                // unsigned
        T  ub;
        /* Adding KMP_ALIGN_CACHE here doesn't help / can hurt performance */
        T  lb;
        ST st;                   // signed
        UT tc;                   // unsigned
        T  static_steal_counter; // for static_steal only; maybe better to put after ub

        /* parm[1-4] are used in different ways by different scheduling algorithms */

        // KMP_ALIGN( 32 ) ensures ( if the KMP_ALIGN macro is turned on )
        //    a) parm3 is properly aligned and
        //    b) all parm1-4 are in the same cache line.
        // Because of parm1-4 are used together, performance seems to be better
        // if they are in the same line (not measured though).

        struct KMP_ALIGN( 32 ) { // compiler does not accept sizeof(T)*4
            T  parm1;
            T  parm2;
            T  parm3;
            T  parm4;
        };

        UT ordered_lower; // unsigned
        UT ordered_upper; // unsigned
        #if KMP_OS_WINDOWS
        T  last_upper;
        #endif /* KMP_OS_WINDOWS */
    };

#else /* KMP_STATIC_STEAL_ENABLED */

    // replaces dispatch_private_info{32,64} structures and dispatch_private_info{32,64}_t types
    template< typename T >
    struct dispatch_private_infoXX_template {
        typedef typename traits_t< T >::unsigned_t  UT;
        typedef typename traits_t< T >::signed_t    ST;
        T  lb;
        T  ub;
        ST st;            // signed
        UT tc;            // unsigned

        T  parm1;
        T  parm2;
        T  parm3;
        T  parm4;

        UT count;         // unsigned

        UT ordered_lower; // unsigned
        UT ordered_upper; // unsigned
        #if KMP_OS_WINDOWS
	T  last_upper;
        #endif /* KMP_OS_WINDOWS */
    };

#endif /* KMP_STATIC_STEAL_ENABLED */

// replaces dispatch_private_info structure and dispatch_private_info_t type
template< typename T >
struct KMP_ALIGN_CACHE dispatch_private_info_template {
    // duplicate alignment here, otherwise size of structure is not correct in our compiler
    union KMP_ALIGN_CACHE private_info_tmpl {
        dispatch_private_infoXX_template< T > p;
        dispatch_private_info64_t             p64;
    } u;
    enum sched_type schedule;  /* scheduling algorithm */
    kmp_uint32      ordered;   /* ordered clause specified */
    kmp_uint32      ordered_bumped;
    kmp_int32   ordered_dummy[KMP_MAX_ORDERED-3]; // to retain the structure size after making order
    dispatch_private_info * next; /* stack of buffers for nest of serial regions */
    kmp_uint32      nomerge;   /* don't merge iters if serialized */
    kmp_uint32      type_size;
    enum cons_type  pushed_ws;
};


// replaces dispatch_shared_info{32,64} structures and dispatch_shared_info{32,64}_t types
template< typename UT >
struct dispatch_shared_infoXX_template {
    /* chunk index under dynamic, number of idle threads under static-steal;
       iteration index otherwise */
    volatile UT     iteration;
    volatile UT     num_done;
    volatile UT     ordered_iteration;
    UT   ordered_dummy[KMP_MAX_ORDERED-1]; // to retain the structure size making ordered_iteration scalar
};

// replaces dispatch_shared_info structure and dispatch_shared_info_t type
template< typename UT >
struct dispatch_shared_info_template {
    // we need union here to keep the structure size
    union shared_info_tmpl {
        dispatch_shared_infoXX_template< UT >  s;
        dispatch_shared_info64_t               s64;
    } u;
    volatile kmp_uint32     buffer_index;
};

/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */

#undef USE_TEST_LOCKS

// test_then_add template (general template should NOT be used)
template< typename T >
static __forceinline T
test_then_add( volatile T *p, T d ) { KMP_ASSERT(0); };

template<>
__forceinline kmp_int32
test_then_add< kmp_int32 >( volatile kmp_int32 *p, kmp_int32 d )
{
    kmp_int32 r;
    r = KMP_TEST_THEN_ADD32( p, d );
    return r;
}

template<>
__forceinline kmp_int64
test_then_add< kmp_int64 >( volatile kmp_int64 *p, kmp_int64 d )
{
    kmp_int64 r;
    r = KMP_TEST_THEN_ADD64( p, d );
    return r;
}

// test_then_inc_acq template (general template should NOT be used)
template< typename T >
static __forceinline T
test_then_inc_acq( volatile T *p ) { KMP_ASSERT(0); };

template<>
__forceinline kmp_int32
test_then_inc_acq< kmp_int32 >( volatile kmp_int32 *p )
{
    kmp_int32 r;
    r = KMP_TEST_THEN_INC_ACQ32( p );
    return r;
}

template<>
__forceinline kmp_int64
test_then_inc_acq< kmp_int64 >( volatile kmp_int64 *p )
{
    kmp_int64 r;
    r = KMP_TEST_THEN_INC_ACQ64( p );
    return r;
}

// test_then_inc template (general template should NOT be used)
template< typename T >
static __forceinline T
test_then_inc( volatile T *p ) { KMP_ASSERT(0); };

template<>
__forceinline kmp_int32
test_then_inc< kmp_int32 >( volatile kmp_int32 *p )
{
    kmp_int32 r;
    r = KMP_TEST_THEN_INC32( p );
    return r;
}

template<>
__forceinline kmp_int64
test_then_inc< kmp_int64 >( volatile kmp_int64 *p )
{
    kmp_int64 r;
    r = KMP_TEST_THEN_INC64( p );
    return r;
}

// compare_and_swap template (general template should NOT be used)
template< typename T >
static __forceinline kmp_int32
compare_and_swap( volatile T *p, T c, T s ) { KMP_ASSERT(0); };

template<>
__forceinline kmp_int32
compare_and_swap< kmp_int32 >( volatile kmp_int32 *p, kmp_int32 c, kmp_int32 s )
{
    return KMP_COMPARE_AND_STORE_REL32( p, c, s );
}

template<>
__forceinline kmp_int32
compare_and_swap< kmp_int64 >( volatile kmp_int64 *p, kmp_int64 c, kmp_int64 s )
{
    return KMP_COMPARE_AND_STORE_REL64( p, c, s );
}

/*
    Spin wait loop that first does pause, then yield.
    Waits until function returns non-zero when called with *spinner and check.
    Does NOT put threads to sleep.
#if USE_ITT_BUILD
    Arguments:
        obj -- is higher-level synchronization object to report to ittnotify. It is used to report
            locks consistently. For example, if lock is acquired immediately, its address is
            reported to ittnotify via KMP_FSYNC_ACQUIRED(). However, it lock cannot be acquired
            immediately and lock routine calls to KMP_WAIT_YIELD(), the later should report the same
            address, not an address of low-level spinner.
#endif // USE_ITT_BUILD
*/
template< typename UT >
// ToDo: make inline function (move to header file for icl)
static UT  // unsigned 4- or 8-byte type
__kmp_wait_yield( volatile UT * spinner,
                  UT            checker,
                  kmp_uint32 (* pred)( UT, UT )
                  USE_ITT_BUILD_ARG(void        * obj)    // Higher-level synchronization object, or NULL.
                  )
{
    // note: we may not belong to a team at this point
    volatile UT         * spin          = spinner; 
             UT           check         = checker; 
             kmp_uint32   spins; 
             kmp_uint32 (*f) ( UT, UT ) = pred; 
             UT           r; 

    KMP_FSYNC_SPIN_INIT( obj, (void*) spin );
    KMP_INIT_YIELD( spins );
    // main wait spin loop
    while(!f(r = *spin, check))
    {
        KMP_FSYNC_SPIN_PREPARE( obj );
        /* GEH - remove this since it was accidentally introduced when kmp_wait was split.
           It causes problems with infinite recursion because of exit lock */
        /* if ( TCR_4(__kmp_global.g.g_done) && __kmp_global.g.g_abort)
            __kmp_abort_thread(); */

        // if we are oversubscribed,
        // or have waited a bit (and KMP_LIBRARY=throughput, then yield
        // pause is in the following code
        KMP_YIELD( TCR_4(__kmp_nth) > __kmp_avail_proc );
        KMP_YIELD_SPIN( spins );
    }
    KMP_FSYNC_SPIN_ACQUIRED( obj );
    return r;
}

template< typename UT >
static kmp_uint32 __kmp_eq( UT value, UT checker) {
    return value == checker;
}

template< typename UT >
static kmp_uint32 __kmp_neq( UT value, UT checker) {
    return value != checker;
}

template< typename UT >
static kmp_uint32 __kmp_lt( UT value, UT checker) {
    return value < checker;
}

template< typename UT >
static kmp_uint32 __kmp_ge( UT value, UT checker) {
    return value >= checker;
}

template< typename UT >
static kmp_uint32 __kmp_le( UT value, UT checker) {
    return value <= checker;
}


/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */

static void
__kmp_dispatch_deo_error( int *gtid_ref, int *cid_ref, ident_t *loc_ref )
{
    kmp_info_t *th;

    KMP_DEBUG_ASSERT( gtid_ref );

    if ( __kmp_env_consistency_check ) {
        th = __kmp_threads[*gtid_ref];
        if ( th -> th.th_root -> r.r_active
          && ( th -> th.th_dispatch -> th_dispatch_pr_current -> pushed_ws != ct_none ) ) {
#if KMP_USE_DYNAMIC_LOCK
            __kmp_push_sync( *gtid_ref, ct_ordered_in_pdo, loc_ref, NULL, 0 );
#else
            __kmp_push_sync( *gtid_ref, ct_ordered_in_pdo, loc_ref, NULL );
#endif
        }
    }
}

template< typename UT >
static void
__kmp_dispatch_deo( int *gtid_ref, int *cid_ref, ident_t *loc_ref )
{
    typedef typename traits_t< UT >::signed_t    ST;
    dispatch_private_info_template< UT > * pr;

    int gtid = *gtid_ref;
//    int  cid = *cid_ref;
    kmp_info_t *th = __kmp_threads[ gtid ];
    KMP_DEBUG_ASSERT( th -> th.th_dispatch );

    KD_TRACE(100, ("__kmp_dispatch_deo: T#%d called\n", gtid ) );
    if ( __kmp_env_consistency_check ) {
        pr = reinterpret_cast< dispatch_private_info_template< UT >* >
            ( th -> th.th_dispatch -> th_dispatch_pr_current );
        if ( pr -> pushed_ws != ct_none ) {
#if KMP_USE_DYNAMIC_LOCK
            __kmp_push_sync( gtid, ct_ordered_in_pdo, loc_ref, NULL, 0 );
#else
            __kmp_push_sync( gtid, ct_ordered_in_pdo, loc_ref, NULL );
#endif
        }
    }

    if ( ! th -> th.th_team -> t.t_serialized ) {
        dispatch_shared_info_template< UT >  * sh = reinterpret_cast< dispatch_shared_info_template< UT >* >
            ( th -> th.th_dispatch -> th_dispatch_sh_current );
        UT  lower;

        if ( ! __kmp_env_consistency_check ) {
                pr = reinterpret_cast< dispatch_private_info_template< UT >* >
                    ( th -> th.th_dispatch -> th_dispatch_pr_current );
        }
        lower = pr->u.p.ordered_lower;

        #if ! defined( KMP_GOMP_COMPAT )
            if ( __kmp_env_consistency_check ) {
                if ( pr->ordered_bumped ) {
                    struct cons_header *p = __kmp_threads[ gtid ]->th.th_cons;
                    __kmp_error_construct2(
                        kmp_i18n_msg_CnsMultipleNesting,
                        ct_ordered_in_pdo, loc_ref,
                        & p->stack_data[ p->w_top ]
                    );
                }
            }
        #endif /* !defined(KMP_GOMP_COMPAT) */

        KMP_MB();
        #ifdef KMP_DEBUG
        {
            const char * buff;
            // create format specifiers before the debug output
            buff = __kmp_str_format(
                "__kmp_dispatch_deo: T#%%d before wait: ordered_iter:%%%s lower:%%%s\n",
                traits_t< UT >::spec, traits_t< UT >::spec );
            KD_TRACE(1000, ( buff, gtid, sh->u.s.ordered_iteration, lower ) );
            __kmp_str_free( &buff );
        }
        #endif

        __kmp_wait_yield< UT >( &sh->u.s.ordered_iteration, lower, __kmp_ge< UT >
                                USE_ITT_BUILD_ARG( NULL )
                                );
        KMP_MB();  /* is this necessary? */
        #ifdef KMP_DEBUG
        {
            const char * buff;
            // create format specifiers before the debug output
            buff = __kmp_str_format(
                "__kmp_dispatch_deo: T#%%d after wait: ordered_iter:%%%s lower:%%%s\n",
                traits_t< UT >::spec, traits_t< UT >::spec );
            KD_TRACE(1000, ( buff, gtid, sh->u.s.ordered_iteration, lower ) );
            __kmp_str_free( &buff );
        }
        #endif
    }
    KD_TRACE(100, ("__kmp_dispatch_deo: T#%d returned\n", gtid ) );
}

static void
__kmp_dispatch_dxo_error( int *gtid_ref, int *cid_ref, ident_t *loc_ref )
{
    kmp_info_t *th;

    if ( __kmp_env_consistency_check ) {
        th = __kmp_threads[*gtid_ref];
        if ( th -> th.th_dispatch -> th_dispatch_pr_current -> pushed_ws != ct_none ) {
            __kmp_pop_sync( *gtid_ref, ct_ordered_in_pdo, loc_ref );
        }
    }
}

template< typename UT >
static void
__kmp_dispatch_dxo( int *gtid_ref, int *cid_ref, ident_t *loc_ref )
{
    typedef typename traits_t< UT >::signed_t    ST;
    dispatch_private_info_template< UT > * pr;

    int gtid = *gtid_ref;
//    int  cid = *cid_ref;
    kmp_info_t *th = __kmp_threads[ gtid ];
    KMP_DEBUG_ASSERT( th -> th.th_dispatch );

    KD_TRACE(100, ("__kmp_dispatch_dxo: T#%d called\n", gtid ) );
    if ( __kmp_env_consistency_check ) {
        pr = reinterpret_cast< dispatch_private_info_template< UT >* >
            ( th -> th.th_dispatch -> th_dispatch_pr_current );
        if ( pr -> pushed_ws != ct_none ) {
            __kmp_pop_sync( gtid, ct_ordered_in_pdo, loc_ref );
        }
    }

    if ( ! th -> th.th_team -> t.t_serialized ) {
        dispatch_shared_info_template< UT >  * sh = reinterpret_cast< dispatch_shared_info_template< UT >* >
            ( th -> th.th_dispatch -> th_dispatch_sh_current );

        if ( ! __kmp_env_consistency_check ) {
            pr = reinterpret_cast< dispatch_private_info_template< UT >* >
                ( th -> th.th_dispatch -> th_dispatch_pr_current );
        }

        KMP_FSYNC_RELEASING( & sh->u.s.ordered_iteration );
        #if ! defined( KMP_GOMP_COMPAT )
            if ( __kmp_env_consistency_check ) {
                if ( pr->ordered_bumped != 0 ) {
                    struct cons_header *p = __kmp_threads[ gtid ]->th.th_cons;
                    /* How to test it? - OM */
                    __kmp_error_construct2(
                        kmp_i18n_msg_CnsMultipleNesting,
                        ct_ordered_in_pdo, loc_ref,
                        & p->stack_data[ p->w_top ]
                    );
                }
            }
        #endif /* !defined(KMP_GOMP_COMPAT) */

        KMP_MB();       /* Flush all pending memory write invalidates.  */

        pr->ordered_bumped += 1;

        KD_TRACE(1000, ("__kmp_dispatch_dxo: T#%d bumping ordered ordered_bumped=%d\n",
                        gtid, pr->ordered_bumped ) );

        KMP_MB();       /* Flush all pending memory write invalidates.  */

        /* TODO use general release procedure? */
        test_then_inc< ST >( (volatile ST *) & sh->u.s.ordered_iteration );

        KMP_MB();       /* Flush all pending memory write invalidates.  */
    }
    KD_TRACE(100, ("__kmp_dispatch_dxo: T#%d returned\n", gtid ) );
}

/* Computes and returns x to the power of y, where y must a non-negative integer */
template< typename UT >
static __forceinline long double
__kmp_pow(long double x, UT y) {
    long double s=1.0L;

    KMP_DEBUG_ASSERT(x > 0.0 && x < 1.0);
    //KMP_DEBUG_ASSERT(y >= 0); // y is unsigned
    while(y) {
        if ( y & 1 )
            s *= x;
        x *= x;
        y >>= 1;
    }
    return s;
}

/* Computes and returns the number of unassigned iterations after idx chunks have been assigned
   (the total number of unassigned iterations in chunks with index greater than or equal to idx).
   __forceinline seems to be broken so that if we __forceinline this function, the behavior is wrong
   (one of the unit tests, sch_guided_analytical_basic.cpp, fails)
*/
template< typename T >
static __inline typename traits_t< T >::unsigned_t
__kmp_dispatch_guided_remaining(
    T                                  tc,
    typename traits_t< T >::floating_t base,
    typename traits_t< T >::unsigned_t idx
) {
    /* Note: On Windows* OS on IA-32 architecture and Intel(R) 64, at
       least for ICL 8.1, long double arithmetic may not really have
       long double precision, even with /Qlong_double.  Currently, we
       workaround that in the caller code, by manipulating the FPCW for
       Windows* OS on IA-32 architecture.  The lack of precision is not
       expected to be a correctness issue, though.
    */
    typedef typename traits_t< T >::unsigned_t  UT;

    long double x = tc * __kmp_pow< UT >(base, idx);
    UT r = (UT) x;
    if ( x == r )
        return r;
    return r + 1;
}

// Parameters of the guided-iterative algorithm:
//   p2 = n * nproc * ( chunk + 1 )  // point of switching to dynamic
//   p3 = 1 / ( n * nproc )          // remaining iterations multiplier
// by default n = 2. For example with n = 3 the chunks distribution will be more flat.
// With n = 1 first chunk is the same as for static schedule, e.g. trip / nproc.
static int guided_int_param = 2;
static double guided_flt_param = 0.5;// = 1.0 / guided_int_param;

// UT - unsigned flavor of T, ST - signed flavor of T,
// DBL - double if sizeof(T)==4, or long double if sizeof(T)==8
template< typename T >
static void
__kmp_dispatch_init(
    ident_t                        * loc,
    int                              gtid,
    enum sched_type                  schedule,
    T                                lb,
    T                                ub,
    typename traits_t< T >::signed_t st,
    typename traits_t< T >::signed_t chunk,
    int                              push_ws
) {
    typedef typename traits_t< T >::unsigned_t  UT;
    typedef typename traits_t< T >::signed_t    ST;
    typedef typename traits_t< T >::floating_t  DBL;
    static const int ___kmp_size_type = sizeof( UT );

    int                                            active;
    T                                              tc;
    kmp_info_t *                                   th;
    kmp_team_t *                                   team;
    kmp_uint32                                     my_buffer_index;
    dispatch_private_info_template< T >          * pr;
    dispatch_shared_info_template< UT > volatile * sh;

    KMP_BUILD_ASSERT( sizeof( dispatch_private_info_template< T > ) == sizeof( dispatch_private_info ) );
    KMP_BUILD_ASSERT( sizeof( dispatch_shared_info_template< UT > ) == sizeof( dispatch_shared_info ) );

    if ( ! TCR_4( __kmp_init_parallel ) )
        __kmp_parallel_initialize();

#if INCLUDE_SSC_MARKS
    SSC_MARK_DISPATCH_INIT();
#endif
    #ifdef KMP_DEBUG
    {
        const char * buff;
        // create format specifiers before the debug output
        buff = __kmp_str_format(
            "__kmp_dispatch_init: T#%%d called: schedule:%%d chunk:%%%s lb:%%%s ub:%%%s st:%%%s\n",
            traits_t< ST >::spec, traits_t< T >::spec, traits_t< T >::spec, traits_t< ST >::spec );
        KD_TRACE(10, ( buff, gtid, schedule, chunk, lb, ub, st ) );
        __kmp_str_free( &buff );
    }
    #endif
    /* setup data */
    th     = __kmp_threads[ gtid ];
    team   = th -> th.th_team;
    active = ! team -> t.t_serialized;
    th->th.th_ident = loc;

#if USE_ITT_BUILD
    kmp_uint64 cur_chunk = chunk;
    int itt_need_metadata_reporting = __itt_metadata_add_ptr && __kmp_forkjoin_frames_mode == 3 &&
        KMP_MASTER_GTID(gtid) &&
#if OMP_40_ENABLED
        th->th.th_teams_microtask == NULL &&
#endif
        team->t.t_active_level == 1;
#endif
    if ( ! active ) {
        pr = reinterpret_cast< dispatch_private_info_template< T >* >
            ( th -> th.th_dispatch -> th_disp_buffer ); /* top of the stack */
    } else {
        KMP_DEBUG_ASSERT( th->th.th_dispatch ==
                &th->th.th_team->t.t_dispatch[th->th.th_info.ds.ds_tid] );

        my_buffer_index = th->th.th_dispatch->th_disp_index ++;

        /* What happens when number of threads changes, need to resize buffer? */
        pr = reinterpret_cast< dispatch_private_info_template< T >  * >
            ( &th -> th.th_dispatch -> th_disp_buffer[ my_buffer_index % KMP_MAX_DISP_BUF ] );
        sh = reinterpret_cast< dispatch_shared_info_template< UT > volatile * >
            ( &team -> t.t_disp_buffer[ my_buffer_index % KMP_MAX_DISP_BUF ] );
    }

    /* Pick up the nomerge/ordered bits from the scheduling type */
    if ( (schedule >= kmp_nm_lower) && (schedule < kmp_nm_upper) ) {
        pr->nomerge = TRUE;
        schedule = (enum sched_type)(((int)schedule) - (kmp_nm_lower - kmp_sch_lower));
    } else {
        pr->nomerge = FALSE;
    }
    pr->type_size = ___kmp_size_type; // remember the size of variables
    if ( kmp_ord_lower & schedule ) {
        pr->ordered = TRUE;
        schedule = (enum sched_type)(((int)schedule) - (kmp_ord_lower - kmp_sch_lower));
    } else {
        pr->ordered = FALSE;
    }

    if ( schedule == kmp_sch_static ) {
        schedule = __kmp_static;
    } else {
        if ( schedule == kmp_sch_runtime ) {
            // Use the scheduling specified by OMP_SCHEDULE (or __kmp_sch_default if not specified)
            schedule = team -> t.t_sched.r_sched_type;
            // Detail the schedule if needed (global controls are differentiated appropriately)
            if ( schedule == kmp_sch_guided_chunked ) {
                schedule = __kmp_guided;
            } else if ( schedule == kmp_sch_static ) {
                schedule = __kmp_static;
            }
            // Use the chunk size specified by OMP_SCHEDULE (or default if not specified)
            chunk = team -> t.t_sched.chunk;
#if USE_ITT_BUILD
            cur_chunk = chunk;
#endif
            #ifdef KMP_DEBUG
            {
                const char * buff;
                // create format specifiers before the debug output
                buff = __kmp_str_format(
                    "__kmp_dispatch_init: T#%%d new: schedule:%%d chunk:%%%s\n",
                    traits_t< ST >::spec );
                KD_TRACE(10, ( buff, gtid, schedule, chunk ) );
                __kmp_str_free( &buff );
            }
            #endif
        } else {
            if ( schedule == kmp_sch_guided_chunked ) {
                schedule = __kmp_guided;
            }
            if ( chunk <= 0 ) {
                chunk = KMP_DEFAULT_CHUNK;
            }
        }

        if ( schedule == kmp_sch_auto ) {
            // mapping and differentiation: in the __kmp_do_serial_initialize()
            schedule = __kmp_auto;
            #ifdef KMP_DEBUG
            {
                const char * buff;
                // create format specifiers before the debug output
                buff = __kmp_str_format(
                    "__kmp_dispatch_init: kmp_sch_auto: T#%%d new: schedule:%%d chunk:%%%s\n",
                    traits_t< ST >::spec );
                KD_TRACE(10, ( buff, gtid, schedule, chunk ) );
                __kmp_str_free( &buff );
            }
            #endif
        }

        /* guided analytical not safe for too many threads */
        if ( team->t.t_nproc > 1<<20 && schedule == kmp_sch_guided_analytical_chunked ) {
            schedule = kmp_sch_guided_iterative_chunked;
            KMP_WARNING( DispatchManyThreads );
        }
        pr->u.p.parm1 = chunk;
    }
    KMP_ASSERT2( (kmp_sch_lower < schedule && schedule < kmp_sch_upper),
                "unknown scheduling type" );

    pr->u.p.count = 0;

    if ( __kmp_env_consistency_check ) {
        if ( st == 0 ) {
            __kmp_error_construct(
                kmp_i18n_msg_CnsLoopIncrZeroProhibited,
                ( pr->ordered ? ct_pdo_ordered : ct_pdo ), loc
            );
        }
    }

    tc = ( ub - lb + st );
    if ( st != 1 ) {
        if ( st < 0 ) {
            if ( lb < ub ) {
                tc = 0;            // zero-trip
            } else {   // lb >= ub
                tc = (ST)tc / st;  // convert to signed division
            }
        } else {       // st > 0
            if ( ub < lb ) {
                tc = 0;            // zero-trip
            } else {   // lb >= ub
                tc /= st;
            }
        }
    } else if ( ub < lb ) {        // st == 1
        tc = 0;                    // zero-trip
    }

    // Any half-decent optimizer will remove this test when the blocks are empty since the macros expand to nothing
    // when statistics are disabled.
    if (schedule == __kmp_static)
    {
        KMP_COUNT_BLOCK(OMP_FOR_static);
        KMP_COUNT_VALUE(FOR_static_iterations, tc);
    }
    else
    {
        KMP_COUNT_BLOCK(OMP_FOR_dynamic);
        KMP_COUNT_VALUE(FOR_dynamic_iterations, tc);
    }

    pr->u.p.lb = lb;
    pr->u.p.ub = ub;
    pr->u.p.st = st;
    pr->u.p.tc = tc;

    #if KMP_OS_WINDOWS
    pr->u.p.last_upper = ub + st;
    #endif /* KMP_OS_WINDOWS */

    /* NOTE: only the active parallel region(s) has active ordered sections */

    if ( active ) {
        if ( pr->ordered == 0 ) {
            th -> th.th_dispatch -> th_deo_fcn = __kmp_dispatch_deo_error;
            th -> th.th_dispatch -> th_dxo_fcn = __kmp_dispatch_dxo_error;
        } else {
            pr->ordered_bumped = 0;

            pr->u.p.ordered_lower = 1;
            pr->u.p.ordered_upper = 0;

            th -> th.th_dispatch -> th_deo_fcn = __kmp_dispatch_deo< UT >;
            th -> th.th_dispatch -> th_dxo_fcn = __kmp_dispatch_dxo< UT >;
        }
    }

    if ( __kmp_env_consistency_check ) {
        enum cons_type ws = pr->ordered ? ct_pdo_ordered : ct_pdo;
        if ( push_ws ) {
            __kmp_push_workshare( gtid, ws, loc );
            pr->pushed_ws = ws;
        } else {
            __kmp_check_workshare( gtid, ws, loc );
            pr->pushed_ws = ct_none;
        }
    }

    switch ( schedule ) {
    #if  ( KMP_STATIC_STEAL_ENABLED && KMP_ARCH_X86_64 )
    case kmp_sch_static_steal:
        {
            T nproc = team->t.t_nproc;
            T ntc, init;

            KD_TRACE(100, ("__kmp_dispatch_init: T#%d kmp_sch_static_steal case\n", gtid ) );

            ntc = (tc % chunk ? 1 : 0) + tc / chunk;
            if ( nproc > 1 && ntc >= nproc ) {
                T id = __kmp_tid_from_gtid(gtid);
                T small_chunk, extras;

                small_chunk = ntc / nproc;
                extras = ntc % nproc;

                init = id * small_chunk + ( id < extras ? id : extras );
                pr->u.p.count = init;
                pr->u.p.ub = init + small_chunk + ( id < extras ? 1 : 0 );

                pr->u.p.parm2 = lb;
                //pr->pfields.parm3 = 0; // it's not used in static_steal
                pr->u.p.parm4 = id;
                pr->u.p.st = st;
                break;
            } else {
                KD_TRACE(100, ("__kmp_dispatch_init: T#%d falling-through to kmp_sch_static_balanced\n",
                               gtid ) );
                schedule = kmp_sch_static_balanced;
                /* too few iterations: fall-through to kmp_sch_static_balanced */
            } // if
            /* FALL-THROUGH to static balanced */
        } // case
    #endif
    case kmp_sch_static_balanced:
        {
            T nproc = team->t.t_nproc;
            T init, limit;

            KD_TRACE(100, ("__kmp_dispatch_init: T#%d kmp_sch_static_balanced case\n",
                            gtid ) );

            if ( nproc > 1 ) {
                T id = __kmp_tid_from_gtid(gtid);

                if ( tc < nproc ) {
                    if ( id < tc ) {
                        init = id;
                        limit = id;
                        pr->u.p.parm1 = (id == tc - 1);  /* parm1 stores *plastiter */
                    } else {
                        pr->u.p.count = 1;  /* means no more chunks to execute */
                        pr->u.p.parm1 = FALSE;
                        break;
                    }
                } else {
                    T small_chunk = tc / nproc;
                    T extras = tc % nproc;
                    init = id * small_chunk + (id < extras ? id : extras);
                    limit = init + small_chunk - (id < extras ? 0 : 1);
                    pr->u.p.parm1 = (id == nproc - 1);
                }
            } else {
                if ( tc > 0 ) {
                    init = 0;
                    limit = tc - 1;
                    pr->u.p.parm1 = TRUE;
                } else {
                    // zero trip count
                    pr->u.p.count = 1;  /* means no more chunks to execute */
                    pr->u.p.parm1 = FALSE;
                    break;
                }
            }
#if USE_ITT_BUILD
            // Calculate chunk for metadata report
            if ( itt_need_metadata_reporting )
                cur_chunk = limit - init + 1;
#endif
            if ( st == 1 ) {
                pr->u.p.lb = lb + init;
                pr->u.p.ub = lb + limit;
            } else {
                T ub_tmp = lb + limit * st;   // calculated upper bound, "ub" is user-defined upper bound
                pr->u.p.lb = lb + init * st;
                // adjust upper bound to "ub" if needed, so that MS lastprivate will match it exactly
                if ( st > 0 ) {
                    pr->u.p.ub = ( ub_tmp + st > ub ? ub : ub_tmp );
                } else {
                    pr->u.p.ub = ( ub_tmp + st < ub ? ub : ub_tmp );
                }
            }
            if ( pr->ordered ) {
                pr->u.p.ordered_lower = init;
                pr->u.p.ordered_upper = limit;
            }
            break;
        } // case
    case kmp_sch_guided_iterative_chunked :
        {
            T nproc = team->t.t_nproc;
            KD_TRACE(100,("__kmp_dispatch_init: T#%d kmp_sch_guided_iterative_chunked case\n",gtid));

            if ( nproc > 1 ) {
                if ( (2L * chunk + 1 ) * nproc >= tc ) {
                    /* chunk size too large, switch to dynamic */
                    schedule = kmp_sch_dynamic_chunked;
                } else {
                    // when remaining iters become less than parm2 - switch to dynamic
                    pr->u.p.parm2 = guided_int_param * nproc * ( chunk + 1 );
                    *(double*)&pr->u.p.parm3 = guided_flt_param / nproc;   // may occupy parm3 and parm4
                }
            } else {
                KD_TRACE(100,("__kmp_dispatch_init: T#%d falling-through to kmp_sch_static_greedy\n",gtid));
                schedule = kmp_sch_static_greedy;
                /* team->t.t_nproc == 1: fall-through to kmp_sch_static_greedy */
                KD_TRACE(100,("__kmp_dispatch_init: T#%d kmp_sch_static_greedy case\n",gtid));
                pr->u.p.parm1 = tc;
            } // if
        } // case
        break;
    case kmp_sch_guided_analytical_chunked:
        {
            T nproc = team->t.t_nproc;
            KD_TRACE(100, ("__kmp_dispatch_init: T#%d kmp_sch_guided_analytical_chunked case\n", gtid));

            if ( nproc > 1 ) {
                if ( (2L * chunk + 1 ) * nproc >= tc ) {
                    /* chunk size too large, switch to dynamic */
                    schedule = kmp_sch_dynamic_chunked;
                } else {
                    /* commonly used term: (2 nproc - 1)/(2 nproc) */
                    DBL x;

                    #if KMP_OS_WINDOWS && KMP_ARCH_X86
                    /* Linux* OS already has 64-bit computation by default for
		       long double, and on Windows* OS on Intel(R) 64,
		       /Qlong_double doesn't work.  On Windows* OS
		       on IA-32 architecture, we need to set precision to
		       64-bit instead of the default 53-bit. Even though long
		       double doesn't work on Windows* OS on Intel(R) 64, the
		       resulting lack of precision is not expected to impact
		       the correctness of the algorithm, but this has not been
		       mathematically proven.
                    */
                    // save original FPCW and set precision to 64-bit, as
                    // Windows* OS on IA-32 architecture defaults to 53-bit
                    unsigned int oldFpcw = _control87(0,0);
                    _control87(_PC_64,_MCW_PC); // 0,0x30000
                    #endif
                    /* value used for comparison in solver for cross-over point */
                    long double target = ((long double)chunk * 2 + 1) * nproc / tc;

                    /* crossover point--chunk indexes equal to or greater than
		       this point switch to dynamic-style scheduling */
                    UT   cross;

                    /* commonly used term: (2 nproc - 1)/(2 nproc) */
                    x = (long double)1.0 - (long double)0.5 / nproc;

                    #ifdef KMP_DEBUG
                    { // test natural alignment
                        struct _test_a {
                            char a;
                            union {
                                char b;
                                DBL  d;
                            };
                        } t;
                        ptrdiff_t natural_alignment = (ptrdiff_t)&t.b - (ptrdiff_t)&t - (ptrdiff_t)1;
                        //__kmp_warn( " %llx %llx %lld", (long long)&t.d, (long long)&t, (long long)natural_alignment );
                        KMP_DEBUG_ASSERT( ( ( (ptrdiff_t)&pr->u.p.parm3 ) & ( natural_alignment ) ) == 0 );
                    }
                    #endif // KMP_DEBUG

                    /* save the term in thread private dispatch structure */
                    *(DBL*)&pr->u.p.parm3 = x;

                    /* solve for the crossover point to the nearest integer i for which C_i <= chunk */
                    {
                        UT          left, right, mid;
                        long double p;

                        /* estimate initial upper and lower bound */

                        /* doesn't matter what value right is as long as it is positive, but
                           it affects performance of the solver
                        */
                        right = 229;
                        p = __kmp_pow< UT >(x,right);
                        if ( p > target ) {
                            do{
                                p *= p;
                                right <<= 1;
                            } while(p>target && right < (1<<27));
                            left = right >> 1; /* lower bound is previous (failed) estimate of upper bound */
                        } else {
                            left = 0;
                        }

                        /* bisection root-finding method */
                        while ( left + 1 < right ) {
                            mid = (left + right) / 2;
                            if ( __kmp_pow< UT >(x,mid) > target ) {
                                left = mid;
                            } else {
                                right = mid;
                            }
                        } // while
                        cross = right;
                    }
                    /* assert sanity of computed crossover point */
                    KMP_ASSERT(cross && __kmp_pow< UT >(x, cross - 1) > target && __kmp_pow< UT >(x, cross) <= target);

                    /* save the crossover point in thread private dispatch structure */
                    pr->u.p.parm2 = cross;

                    // C75803
                    #if ( ( KMP_OS_LINUX || KMP_OS_WINDOWS ) && KMP_ARCH_X86 ) && ( ! defined( KMP_I8 ) )
                        #define GUIDED_ANALYTICAL_WORKAROUND (*( DBL * )&pr->u.p.parm3)
                    #else
                        #define GUIDED_ANALYTICAL_WORKAROUND (x)
                    #endif
                    /* dynamic-style scheduling offset */
                    pr->u.p.count = tc - __kmp_dispatch_guided_remaining(tc, GUIDED_ANALYTICAL_WORKAROUND, cross) - cross * chunk;
                    #if KMP_OS_WINDOWS && KMP_ARCH_X86
                        // restore FPCW
                        _control87(oldFpcw,_MCW_PC);
                    #endif
                } // if
            } else {
                KD_TRACE(100, ("__kmp_dispatch_init: T#%d falling-through to kmp_sch_static_greedy\n",
                               gtid ) );
                schedule = kmp_sch_static_greedy;
                /* team->t.t_nproc == 1: fall-through to kmp_sch_static_greedy */
                pr->u.p.parm1 = tc;
            } // if
        } // case
        break;
    case kmp_sch_static_greedy:
        KD_TRACE(100,("__kmp_dispatch_init: T#%d kmp_sch_static_greedy case\n",gtid));
            pr->u.p.parm1 = ( team -> t.t_nproc > 1 ) ?
                ( tc + team->t.t_nproc - 1 ) / team->t.t_nproc :
                tc;
        break;
    case kmp_sch_static_chunked :
    case kmp_sch_dynamic_chunked :
        if ( pr->u.p.parm1 <= 0 ) {
            pr->u.p.parm1 = KMP_DEFAULT_CHUNK;
        }
        KD_TRACE(100,("__kmp_dispatch_init: T#%d kmp_sch_static_chunked/kmp_sch_dynamic_chunked cases\n", gtid));
        break;
    case kmp_sch_trapezoidal :
        {
            /* TSS: trapezoid self-scheduling, minimum chunk_size = parm1 */

            T parm1, parm2, parm3, parm4;
            KD_TRACE(100, ("__kmp_dispatch_init: T#%d kmp_sch_trapezoidal case\n", gtid ) );

            parm1 = chunk;

            /* F : size of the first cycle */
            parm2 = ( tc / (2 * team->t.t_nproc) );

            if ( parm2 < 1 ) {
                parm2 = 1;
            }

            /* L : size of the last cycle.  Make sure the last cycle
             *     is not larger than the first cycle.
             */
            if ( parm1 < 1 ) {
                parm1 = 1;
            } else if ( parm1 > parm2 ) {
                parm1 = parm2;
            }

            /* N : number of cycles */
            parm3 = ( parm2 + parm1 );
            parm3 = ( 2 * tc + parm3 - 1) / parm3;

            if ( parm3 < 2 ) {
                parm3 = 2;
            }

            /* sigma : decreasing incr of the trapezoid */
            parm4 = ( parm3 - 1 );
            parm4 = ( parm2 - parm1 ) / parm4;

            // pointless check, because parm4 >= 0 always
            //if ( parm4 < 0 ) {
            //    parm4 = 0;
            //}

            pr->u.p.parm1 = parm1;
            pr->u.p.parm2 = parm2;
            pr->u.p.parm3 = parm3;
            pr->u.p.parm4 = parm4;
        } // case
        break;

    default:
        {
            __kmp_msg(
                kmp_ms_fatal,                        // Severity
                KMP_MSG( UnknownSchedTypeDetected ), // Primary message
                KMP_HNT( GetNewerLibrary ),          // Hint
                __kmp_msg_null                       // Variadic argument list terminator
            );
        }
        break;
    } // switch
    pr->schedule = schedule;
    if ( active ) {
        /* The name of this buffer should be my_buffer_index when it's free to use it */

        KD_TRACE(100, ("__kmp_dispatch_init: T#%d before wait: my_buffer_index:%d sh->buffer_index:%d\n",
                        gtid, my_buffer_index, sh->buffer_index) );
        __kmp_wait_yield< kmp_uint32 >( & sh->buffer_index, my_buffer_index, __kmp_eq< kmp_uint32 >
                                        USE_ITT_BUILD_ARG( NULL )
                                        );
            // Note: KMP_WAIT_YIELD() cannot be used there: buffer index and my_buffer_index are
            // *always* 32-bit integers.
        KMP_MB();  /* is this necessary? */
        KD_TRACE(100, ("__kmp_dispatch_init: T#%d after wait: my_buffer_index:%d sh->buffer_index:%d\n",
                        gtid, my_buffer_index, sh->buffer_index) );

        th -> th.th_dispatch -> th_dispatch_pr_current = (dispatch_private_info_t*) pr;
        th -> th.th_dispatch -> th_dispatch_sh_current = (dispatch_shared_info_t*)  sh;
#if USE_ITT_BUILD
        if ( pr->ordered ) {
            __kmp_itt_ordered_init( gtid );
        }; // if
        // Report loop metadata
        if ( itt_need_metadata_reporting ) {
            // Only report metadata by master of active team at level 1
            kmp_uint64 schedtype = 0;
            switch ( schedule ) {
            case kmp_sch_static_chunked:
            case kmp_sch_static_balanced:// Chunk is calculated in the switch above
                break;
            case kmp_sch_static_greedy:
                cur_chunk = pr->u.p.parm1;
                break;
            case kmp_sch_dynamic_chunked:
                schedtype = 1;
                break;
            case kmp_sch_guided_iterative_chunked:
            case kmp_sch_guided_analytical_chunked:
                schedtype = 2;
                break;
            default:
//            Should we put this case under "static"?
//            case kmp_sch_static_steal:
                schedtype = 3;
                break;
            }
            __kmp_itt_metadata_loop(loc, schedtype, tc, cur_chunk);
        }
#endif /* USE_ITT_BUILD */
    }; // if

    #ifdef KMP_DEBUG
    {
        const char * buff;
        // create format specifiers before the debug output
        buff = __kmp_str_format(
            "__kmp_dispatch_init: T#%%d returning: schedule:%%d ordered:%%%s lb:%%%s ub:%%%s" \
            " st:%%%s tc:%%%s count:%%%s\n\tordered_lower:%%%s ordered_upper:%%%s" \
            " parm1:%%%s parm2:%%%s parm3:%%%s parm4:%%%s\n",
            traits_t< UT >::spec, traits_t< T >::spec, traits_t< T >::spec,
            traits_t< ST >::spec, traits_t< UT >::spec, traits_t< UT >::spec,
            traits_t< UT >::spec, traits_t< UT >::spec, traits_t< T >::spec,
            traits_t< T >::spec, traits_t< T >::spec, traits_t< T >::spec );
        KD_TRACE(10, ( buff,
            gtid, pr->schedule, pr->ordered, pr->u.p.lb, pr->u.p.ub,
            pr->u.p.st, pr->u.p.tc, pr->u.p.count,
            pr->u.p.ordered_lower, pr->u.p.ordered_upper, pr->u.p.parm1,
            pr->u.p.parm2, pr->u.p.parm3, pr->u.p.parm4 ) );
        __kmp_str_free( &buff );
    }
    #endif
    #if ( KMP_STATIC_STEAL_ENABLED )
    if ( ___kmp_size_type < 8 ) {
      // It cannot be guaranteed that after execution of a loop with some other schedule kind
      // all the parm3 variables will contain the same value.
      // Even if all parm3 will be the same, it still exists a bad case like using 0 and 1
      // rather than program life-time increment.
      // So the dedicated variable is required. The 'static_steal_counter' is used.
      if( schedule == kmp_sch_static_steal ) {
        // Other threads will inspect this variable when searching for a victim.
        // This is a flag showing that other threads may steal from this thread since then.
        volatile T * p = &pr->u.p.static_steal_counter;
        *p = *p + 1;
      }
    }
    #endif // ( KMP_STATIC_STEAL_ENABLED && USE_STEALING )

#if OMPT_SUPPORT && OMPT_TRACE
    if (ompt_enabled &&
        ompt_callbacks.ompt_callback(ompt_event_loop_begin)) {
        ompt_team_info_t *team_info = __ompt_get_teaminfo(0, NULL);
        ompt_task_info_t *task_info = __ompt_get_taskinfo(0);
        ompt_callbacks.ompt_callback(ompt_event_loop_begin)(
            team_info->parallel_id, task_info->task_id, team_info->microtask);
    }
#endif
}

/*
 * For ordered loops, either __kmp_dispatch_finish() should be called after
 * every iteration, or __kmp_dispatch_finish_chunk() should be called after
 * every chunk of iterations.  If the ordered section(s) were not executed
 * for this iteration (or every iteration in this chunk), we need to set the
 * ordered iteration counters so that the next thread can proceed.
 */
template< typename UT >
static void
__kmp_dispatch_finish( int gtid, ident_t *loc )
{
    typedef typename traits_t< UT >::signed_t ST;
    kmp_info_t *th = __kmp_threads[ gtid ];

    KD_TRACE(100, ("__kmp_dispatch_finish: T#%d called\n", gtid ) );
    if ( ! th -> th.th_team -> t.t_serialized ) {

        dispatch_private_info_template< UT > * pr =
            reinterpret_cast< dispatch_private_info_template< UT >* >
            ( th->th.th_dispatch->th_dispatch_pr_current );
        dispatch_shared_info_template< UT > volatile * sh =
            reinterpret_cast< dispatch_shared_info_template< UT >volatile* >
            ( th->th.th_dispatch->th_dispatch_sh_current );
        KMP_DEBUG_ASSERT( pr );
        KMP_DEBUG_ASSERT( sh );
        KMP_DEBUG_ASSERT( th->th.th_dispatch ==
                 &th->th.th_team->t.t_dispatch[th->th.th_info.ds.ds_tid] );

        if ( pr->ordered_bumped ) {
            KD_TRACE(1000, ("__kmp_dispatch_finish: T#%d resetting ordered_bumped to zero\n",
                            gtid ) );
            pr->ordered_bumped = 0;
        } else {
            UT lower = pr->u.p.ordered_lower;

            #ifdef KMP_DEBUG
            {
                const char * buff;
                // create format specifiers before the debug output
                buff = __kmp_str_format(
                    "__kmp_dispatch_finish: T#%%d before wait: ordered_iteration:%%%s lower:%%%s\n",
                    traits_t< UT >::spec, traits_t< UT >::spec );
                KD_TRACE(1000, ( buff, gtid, sh->u.s.ordered_iteration, lower ) );
                __kmp_str_free( &buff );
            }
            #endif

            __kmp_wait_yield< UT >(&sh->u.s.ordered_iteration, lower, __kmp_ge< UT >
                                   USE_ITT_BUILD_ARG(NULL)
                                   );
            KMP_MB();  /* is this necessary? */
            #ifdef KMP_DEBUG
            {
                const char * buff;
                // create format specifiers before the debug output
                buff = __kmp_str_format(
                    "__kmp_dispatch_finish: T#%%d after wait: ordered_iteration:%%%s lower:%%%s\n",
                    traits_t< UT >::spec, traits_t< UT >::spec );
                KD_TRACE(1000, ( buff, gtid, sh->u.s.ordered_iteration, lower ) );
                __kmp_str_free( &buff );
            }
            #endif

            test_then_inc< ST >( (volatile ST *) & sh->u.s.ordered_iteration );
        } // if
    } // if
    KD_TRACE(100, ("__kmp_dispatch_finish: T#%d returned\n", gtid ) );
}

#ifdef KMP_GOMP_COMPAT

template< typename UT >
static void
__kmp_dispatch_finish_chunk( int gtid, ident_t *loc )
{
    typedef typename traits_t< UT >::signed_t ST;
    kmp_info_t *th = __kmp_threads[ gtid ];

    KD_TRACE(100, ("__kmp_dispatch_finish_chunk: T#%d called\n", gtid ) );
    if ( ! th -> th.th_team -> t.t_serialized ) {
//        int cid;
        dispatch_private_info_template< UT > * pr =
            reinterpret_cast< dispatch_private_info_template< UT >* >
            ( th->th.th_dispatch->th_dispatch_pr_current );
        dispatch_shared_info_template< UT > volatile * sh =
            reinterpret_cast< dispatch_shared_info_template< UT >volatile* >
            ( th->th.th_dispatch->th_dispatch_sh_current );
        KMP_DEBUG_ASSERT( pr );
        KMP_DEBUG_ASSERT( sh );
        KMP_DEBUG_ASSERT( th->th.th_dispatch ==
                 &th->th.th_team->t.t_dispatch[th->th.th_info.ds.ds_tid] );

//        for (cid = 0; cid < KMP_MAX_ORDERED; ++cid) {
            UT lower = pr->u.p.ordered_lower;
            UT upper = pr->u.p.ordered_upper;
            UT inc = upper - lower + 1;

            if ( pr->ordered_bumped == inc ) {
                KD_TRACE(1000, ("__kmp_dispatch_finish: T#%d resetting ordered_bumped to zero\n",
                  gtid ) );
                pr->ordered_bumped = 0;
            } else {
                inc -= pr->ordered_bumped;

                #ifdef KMP_DEBUG
                {
                    const char * buff;
                    // create format specifiers before the debug output
                    buff = __kmp_str_format(
                        "__kmp_dispatch_finish_chunk: T#%%d before wait: " \
                        "ordered_iteration:%%%s lower:%%%s upper:%%%s\n",
                        traits_t< UT >::spec, traits_t< UT >::spec, traits_t< UT >::spec );
                    KD_TRACE(1000, ( buff, gtid, sh->u.s.ordered_iteration, lower, upper ) );
                    __kmp_str_free( &buff );
                }
                #endif

                __kmp_wait_yield< UT >(&sh->u.s.ordered_iteration, lower, __kmp_ge< UT >
                                       USE_ITT_BUILD_ARG(NULL)
                                       );

                KMP_MB();  /* is this necessary? */
                KD_TRACE(1000, ("__kmp_dispatch_finish_chunk: T#%d resetting ordered_bumped to zero\n",
                  gtid ) );
                pr->ordered_bumped = 0;
//!!!!! TODO check if the inc should be unsigned, or signed???
                #ifdef KMP_DEBUG
                {
                    const char * buff;
                    // create format specifiers before the debug output
                    buff = __kmp_str_format(
                        "__kmp_dispatch_finish_chunk: T#%%d after wait: " \
                        "ordered_iteration:%%%s inc:%%%s lower:%%%s upper:%%%s\n",
                        traits_t< UT >::spec, traits_t< UT >::spec, traits_t< UT >::spec, traits_t< UT >::spec );
                    KD_TRACE(1000, ( buff, gtid, sh->u.s.ordered_iteration, inc, lower, upper ) );
                    __kmp_str_free( &buff );
                }
                #endif

                test_then_add< ST >( (volatile ST *) & sh->u.s.ordered_iteration, inc);
            }
//        }
    }
    KD_TRACE(100, ("__kmp_dispatch_finish_chunk: T#%d returned\n", gtid ) );
}

#endif /* KMP_GOMP_COMPAT */

/* Define a macro for exiting __kmp_dispatch_next(). If status is 0
 * (no more work), then tell OMPT the loop is over. In some cases
 * kmp_dispatch_fini() is not called. */
#if OMPT_SUPPORT && OMPT_TRACE
#define OMPT_LOOP_END                                                          \
    if (status == 0) {                                                         \
        if (ompt_enabled &&                     \
            ompt_callbacks.ompt_callback(ompt_event_loop_end)) {               \
            ompt_team_info_t *team_info = __ompt_get_teaminfo(0, NULL);        \
            ompt_task_info_t *task_info = __ompt_get_taskinfo(0);              \
            ompt_callbacks.ompt_callback(ompt_event_loop_end)(                 \
                team_info->parallel_id, task_info->task_id);                   \
        }                                                                      \
    }
#else
#define OMPT_LOOP_END // no-op
#endif

template< typename T >
static int
__kmp_dispatch_next(
    ident_t *loc, int gtid, kmp_int32 *p_last, T *p_lb, T *p_ub, typename traits_t< T >::signed_t *p_st
) {

    typedef typename traits_t< T >::unsigned_t  UT;
    typedef typename traits_t< T >::signed_t    ST;
    typedef typename traits_t< T >::floating_t  DBL;
#if ( KMP_STATIC_STEAL_ENABLED && KMP_ARCH_X86_64 )
    static const int ___kmp_size_type = sizeof( UT );
#endif

    // This is potentially slightly misleading, schedule(runtime) will appear here even if the actual runtme schedule
    // is static. (Which points out a disadavantage of schedule(runtime): even when static scheduling is used it costs
    // more than a compile time choice to use static scheduling would.)
    KMP_TIME_BLOCK(FOR_dynamic_scheduling);

    int                                   status;
    dispatch_private_info_template< T > * pr;
    kmp_info_t                          * th   = __kmp_threads[ gtid ];
    kmp_team_t                          * team = th -> th.th_team;

    KMP_DEBUG_ASSERT( p_lb && p_ub && p_st ); // AC: these cannot be NULL
    #ifdef KMP_DEBUG
    {
        const char * buff;
        // create format specifiers before the debug output
        buff = __kmp_str_format(
            "__kmp_dispatch_next: T#%%d called p_lb:%%%s p_ub:%%%s p_st:%%%s p_last: %%p\n",
            traits_t< T >::spec, traits_t< T >::spec, traits_t< ST >::spec );
        KD_TRACE(1000, ( buff, gtid, *p_lb, *p_ub, p_st ? *p_st : 0, p_last ) );
        __kmp_str_free( &buff );
    }
    #endif

    if ( team -> t.t_serialized ) {
        /* NOTE: serialize this dispatch becase we are not at the active level */
        pr = reinterpret_cast< dispatch_private_info_template< T >* >
            ( th -> th.th_dispatch -> th_disp_buffer ); /* top of the stack */
        KMP_DEBUG_ASSERT( pr );

        if ( (status = (pr->u.p.tc != 0)) == 0 ) {
            *p_lb = 0;
            *p_ub = 0;
//            if ( p_last != NULL )
//                *p_last = 0;
            if ( p_st != NULL )
                *p_st = 0;
            if ( __kmp_env_consistency_check ) {
                if ( pr->pushed_ws != ct_none ) {
                    pr->pushed_ws = __kmp_pop_workshare( gtid, pr->pushed_ws, loc );
                }
            }
        } else if ( pr->nomerge ) {
            kmp_int32 last;
            T         start;
            UT        limit, trip, init;
            ST        incr;
            T         chunk = pr->u.p.parm1;

            KD_TRACE(100, ("__kmp_dispatch_next: T#%d kmp_sch_dynamic_chunked case\n", gtid ) );

            init = chunk * pr->u.p.count++;
            trip = pr->u.p.tc - 1;

            if ( (status = (init <= trip)) == 0 ) {
                *p_lb = 0;
                *p_ub = 0;
//                if ( p_last != NULL )
//                    *p_last = 0;
                if ( p_st != NULL )
                    *p_st = 0;
                if ( __kmp_env_consistency_check ) {
                    if ( pr->pushed_ws != ct_none ) {
                        pr->pushed_ws = __kmp_pop_workshare( gtid, pr->pushed_ws, loc );
                    }
                }
            } else {
                start = pr->u.p.lb;
                limit = chunk + init - 1;
                incr  = pr->u.p.st;

                if ( (last = (limit >= trip)) != 0 ) {
                    limit = trip;
                    #if KMP_OS_WINDOWS
                    pr->u.p.last_upper = pr->u.p.ub;
                    #endif /* KMP_OS_WINDOWS */
                }
                if ( p_last != NULL )
                    *p_last = last;
                if ( p_st != NULL )
                    *p_st = incr;
                if ( incr == 1 ) {
                    *p_lb = start + init;
                    *p_ub = start + limit;
                } else {
                    *p_lb = start + init * incr;
                    *p_ub = start + limit * incr;
                }

                if ( pr->ordered ) {
                    pr->u.p.ordered_lower = init;
                    pr->u.p.ordered_upper = limit;
                    #ifdef KMP_DEBUG
                    {
                        const char * buff;
                        // create format specifiers before the debug output
                        buff = __kmp_str_format(
                            "__kmp_dispatch_next: T#%%d ordered_lower:%%%s ordered_upper:%%%s\n",
                            traits_t< UT >::spec, traits_t< UT >::spec );
                        KD_TRACE(1000, ( buff, gtid, pr->u.p.ordered_lower, pr->u.p.ordered_upper ) );
                        __kmp_str_free( &buff );
                    }
                    #endif
                } // if
            } // if
        } else {
            pr->u.p.tc = 0;
            *p_lb = pr->u.p.lb;
            *p_ub = pr->u.p.ub;
            #if KMP_OS_WINDOWS
            pr->u.p.last_upper = *p_ub;
            #endif /* KMP_OS_WINDOWS */
            if ( p_last != NULL )
                *p_last = TRUE;
            if ( p_st != NULL )
                *p_st = pr->u.p.st;
        } // if
        #ifdef KMP_DEBUG
        {
            const char * buff;
            // create format specifiers before the debug output
            buff = __kmp_str_format(
                "__kmp_dispatch_next: T#%%d serialized case: p_lb:%%%s " \
                "p_ub:%%%s p_st:%%%s p_last:%%p %%d  returning:%%d\n",
                traits_t< T >::spec, traits_t< T >::spec, traits_t< ST >::spec );
            KD_TRACE(10, ( buff, gtid, *p_lb, *p_ub, *p_st, p_last, *p_last, status) );
            __kmp_str_free( &buff );
        }
        #endif
#if INCLUDE_SSC_MARKS
        SSC_MARK_DISPATCH_NEXT();
#endif
        OMPT_LOOP_END;
        return status;
    } else {
        kmp_int32 last = 0;
        dispatch_shared_info_template< UT > *sh;
        T         start;
        ST        incr;
        UT        limit, trip, init;

        KMP_DEBUG_ASSERT( th->th.th_dispatch ==
                &th->th.th_team->t.t_dispatch[th->th.th_info.ds.ds_tid] );

        pr = reinterpret_cast< dispatch_private_info_template< T >* >
            ( th->th.th_dispatch->th_dispatch_pr_current );
        KMP_DEBUG_ASSERT( pr );
        sh = reinterpret_cast< dispatch_shared_info_template< UT >* >
            ( th->th.th_dispatch->th_dispatch_sh_current );
        KMP_DEBUG_ASSERT( sh );

        if ( pr->u.p.tc == 0 ) {
            // zero trip count
            status = 0;
        } else {
            switch (pr->schedule) {
            #if ( KMP_STATIC_STEAL_ENABLED && KMP_ARCH_X86_64 )
            case kmp_sch_static_steal:
                {
                    T chunk = pr->u.p.parm1;

                    KD_TRACE(100, ("__kmp_dispatch_next: T#%d kmp_sch_static_steal case\n", gtid) );

                    trip = pr->u.p.tc - 1;

                    if ( ___kmp_size_type > 4 ) {
                        // Other threads do not look into the data of this thread,
                        //  so it's not necessary to make volatile casting.
                        init   = ( pr->u.p.count )++;
                        status = ( init < (UT)pr->u.p.ub );
                    } else {
                        typedef union {
                            struct {
                                UT count;
                                T  ub;
                            } p;
                            kmp_int64 b;
                        } union_i4;
                        // All operations on 'count' or 'ub' must be combined atomically together.
                        // stealing implemented only for 4-byte indexes
                        {
                            union_i4 vold, vnew;
                            vold.b = *( volatile kmp_int64 * )(&pr->u.p.count);
                            vnew = vold;
                            vnew.p.count++;
                            while( ! KMP_COMPARE_AND_STORE_ACQ64(
                                        ( volatile kmp_int64* )&pr->u.p.count,
                                        *VOLATILE_CAST(kmp_int64 *)&vold.b,
                                        *VOLATILE_CAST(kmp_int64 *)&vnew.b ) ) {
                                KMP_CPU_PAUSE();
                                vold.b = *( volatile kmp_int64 * )(&pr->u.p.count);
                                vnew = vold;
                                vnew.p.count++;
                            }
                            vnew = vold;
                            init   = vnew.p.count;
                            status = ( init < (UT)vnew.p.ub ) ;
                        }

                        if( !status ) {
                            kmp_info_t   **other_threads = team->t.t_threads;
                            int          while_limit = 10;
                            int          while_index = 0;

                            // TODO: algorithm of searching for a victim
                            // should be cleaned up and measured
                            while ( ( !status ) && ( while_limit != ++while_index ) ) {
                                union_i4  vold, vnew;
                                kmp_int32 remaining; // kmp_int32 because KMP_I4 only
                                T         victimIdx    = pr->u.p.parm4;
                                T         oldVictimIdx = victimIdx;
                                dispatch_private_info_template< T > * victim;

                                do {
                                    if( !victimIdx ) {
                                        victimIdx = team->t.t_nproc - 1;
                                    } else {
                                        --victimIdx;
                                    }
                                    victim = reinterpret_cast< dispatch_private_info_template< T >* >
                                        ( other_threads[victimIdx]->th.th_dispatch->th_dispatch_pr_current );
                                } while ( (victim == NULL || victim == pr) && oldVictimIdx != victimIdx );
                                // TODO: think about a proper place of this test
                                if ( ( !victim ) ||
                                   ( (*( volatile T * )&victim->u.p.static_steal_counter) !=
                                     (*( volatile T * )&pr->u.p.static_steal_counter) ) ) {
                                    // TODO: delay would be nice
                                    continue;
                                    // the victim is not ready yet to participate in stealing
                                    // because the victim is still in kmp_init_dispatch
                                }
                                if ( oldVictimIdx == victimIdx ) {
                                    break;
                                }
                                pr->u.p.parm4 = victimIdx;

                                while( 1 ) {
                                    vold.b = *( volatile kmp_int64 * )( &victim->u.p.count );
                                    vnew = vold;

                                    KMP_DEBUG_ASSERT( (vnew.p.ub - 1) * (UT)chunk <= trip );
                                    if ( vnew.p.count >= (UT)vnew.p.ub || (remaining = vnew.p.ub - vnew.p.count) < 4 ) {
                                        break;
                                    }
                                    vnew.p.ub -= (remaining >> 2);
                                    KMP_DEBUG_ASSERT((vnew.p.ub - 1) * (UT)chunk <= trip);
                                    #pragma warning( push )
                                    // disable warning on pointless comparison of unsigned with 0
                                    #pragma warning( disable: 186 )
                                        KMP_DEBUG_ASSERT(vnew.p.ub >= 0);
                                    #pragma warning( pop )
                                    // TODO: Should this be acquire or release?
                                    if ( KMP_COMPARE_AND_STORE_ACQ64(
                                            ( volatile kmp_int64 * )&victim->u.p.count,
                                            *VOLATILE_CAST(kmp_int64 *)&vold.b,
                                            *VOLATILE_CAST(kmp_int64 *)&vnew.b ) ) {
                                        status = 1;
                                        while_index = 0;
                                        // now update own count and ub
                                        #if KMP_ARCH_X86
                                        // stealing executed on non-KMP_ARCH_X86 only
                                            // Atomic 64-bit write on ia32 is
                                            // unavailable, so we do this in steps.
                                            //     This code is not tested.
                                            init = vold.p.count;
                                            pr->u.p.ub = 0;
                                            pr->u.p.count = init + 1;
                                            pr->u.p.ub = vnew.p.count;
                                        #else
                                            init = vnew.p.ub;
                                            vold.p.count = init + 1;
                                            // TODO: is it safe and enough?
                                            *( volatile kmp_int64 * )(&pr->u.p.count) = vold.b;
                                        #endif // KMP_ARCH_X86
                                        break;
                                    } // if
                                KMP_CPU_PAUSE();
                                } // while (1)
                            } // while
                        } // if
                    } // if
                    if ( !status ) {
                        *p_lb = 0;
                        *p_ub = 0;
                        if ( p_st != NULL ) *p_st = 0;
                    } else {
                        start = pr->u.p.parm2;
                        init *= chunk;
                        limit = chunk + init - 1;
                        incr  = pr->u.p.st;

                        KMP_DEBUG_ASSERT(init <= trip);
                        if ( (last = (limit >= trip)) != 0 )
                            limit = trip;
                        if ( p_st != NULL ) *p_st = incr;

                        if ( incr == 1 ) {
                            *p_lb = start + init;
                            *p_ub = start + limit;
                        } else {
                            *p_lb = start + init * incr;
                            *p_ub = start + limit * incr;
                        }

                        if ( pr->ordered ) {
                            pr->u.p.ordered_lower = init;
                            pr->u.p.ordered_upper = limit;
                            #ifdef KMP_DEBUG
                            {
                                const char * buff;
                                // create format specifiers before the debug output
                                buff = __kmp_str_format(
                                    "__kmp_dispatch_next: T#%%d ordered_lower:%%%s ordered_upper:%%%s\n",
                                    traits_t< UT >::spec, traits_t< UT >::spec );
                                KD_TRACE(1000, ( buff, gtid, pr->u.p.ordered_lower, pr->u.p.ordered_upper ) );
                                __kmp_str_free( &buff );
                            }
                            #endif
                        } // if
                    } // if
                    break;
                } // case
            #endif // ( KMP_STATIC_STEAL_ENABLED && KMP_ARCH_X86_64 )
            case kmp_sch_static_balanced:
                {
                    KD_TRACE(100, ("__kmp_dispatch_next: T#%d kmp_sch_static_balanced case\n", gtid) );
                    if ( (status = !pr->u.p.count) != 0 ) {  /* check if thread has any iteration to do */
                        pr->u.p.count = 1;
                        *p_lb = pr->u.p.lb;
                        *p_ub = pr->u.p.ub;
                        last = pr->u.p.parm1;
                        if ( p_st != NULL )
                            *p_st = pr->u.p.st;
                    } else {  /* no iterations to do */
                        pr->u.p.lb = pr->u.p.ub + pr->u.p.st;
                    }
                    if ( pr->ordered ) {
                        #ifdef KMP_DEBUG
                        {
                            const char * buff;
                            // create format specifiers before the debug output
                            buff = __kmp_str_format(
                                "__kmp_dispatch_next: T#%%d ordered_lower:%%%s ordered_upper:%%%s\n",
                                traits_t< UT >::spec, traits_t< UT >::spec );
                            KD_TRACE(1000, ( buff, gtid, pr->u.p.ordered_lower, pr->u.p.ordered_upper ) );
                            __kmp_str_free( &buff );
                        }
                        #endif
                    } // if
                } // case
                break;
            case kmp_sch_static_greedy:  /* original code for kmp_sch_static_greedy was merged here */
            case kmp_sch_static_chunked:
                {
                    T parm1;

                    KD_TRACE(100, ("__kmp_dispatch_next: T#%d kmp_sch_static_[affinity|chunked] case\n",
                                   gtid ) );
                    parm1 = pr->u.p.parm1;

                    trip  = pr->u.p.tc - 1;
                    init  = parm1 * (pr->u.p.count + __kmp_tid_from_gtid(gtid));

                    if ( (status = (init <= trip)) != 0 ) {
                        start = pr->u.p.lb;
                        incr  = pr->u.p.st;
                        limit = parm1 + init - 1;

                        if ( (last = (limit >= trip)) != 0 )
                            limit = trip;

                        if ( p_st != NULL ) *p_st = incr;

                        pr->u.p.count += team->t.t_nproc;

                        if ( incr == 1 ) {
                            *p_lb = start + init;
                            *p_ub = start + limit;
                        }
                        else {
                            *p_lb = start + init * incr;
                            *p_ub = start + limit * incr;
                        }

                        if ( pr->ordered ) {
                            pr->u.p.ordered_lower = init;
                            pr->u.p.ordered_upper = limit;
                            #ifdef KMP_DEBUG
                            {
                                const char * buff;
                                // create format specifiers before the debug output
                                buff = __kmp_str_format(
                                    "__kmp_dispatch_next: T#%%d ordered_lower:%%%s ordered_upper:%%%s\n",
                                    traits_t< UT >::spec, traits_t< UT >::spec );
                                KD_TRACE(1000, ( buff, gtid, pr->u.p.ordered_lower, pr->u.p.ordered_upper ) );
                                __kmp_str_free( &buff );
                            }
                            #endif
                        } // if
                    } // if
                } // case
                break;

            case kmp_sch_dynamic_chunked:
                {
                    T chunk = pr->u.p.parm1;

                    KD_TRACE(100, ("__kmp_dispatch_next: T#%d kmp_sch_dynamic_chunked case\n",
                                   gtid ) );

                    init = chunk * test_then_inc_acq< ST >((volatile ST *) & sh->u.s.iteration );
                    trip = pr->u.p.tc - 1;

                    if ( (status = (init <= trip)) == 0 ) {
                        *p_lb = 0;
                        *p_ub = 0;
                        if ( p_st != NULL ) *p_st = 0;
                    } else {
                        start = pr->u.p.lb;
                        limit = chunk + init - 1;
                        incr  = pr->u.p.st;

                        if ( (last = (limit >= trip)) != 0 )
                            limit = trip;

                        if ( p_st != NULL ) *p_st = incr;

                        if ( incr == 1 ) {
                            *p_lb = start + init;
                            *p_ub = start + limit;
                        } else {
                            *p_lb = start + init * incr;
                            *p_ub = start + limit * incr;
                        }

                        if ( pr->ordered ) {
                            pr->u.p.ordered_lower = init;
                            pr->u.p.ordered_upper = limit;
                            #ifdef KMP_DEBUG
                            {
                                const char * buff;
                                // create format specifiers before the debug output
                                buff = __kmp_str_format(
                                    "__kmp_dispatch_next: T#%%d ordered_lower:%%%s ordered_upper:%%%s\n",
                                    traits_t< UT >::spec, traits_t< UT >::spec );
                                KD_TRACE(1000, ( buff, gtid, pr->u.p.ordered_lower, pr->u.p.ordered_upper ) );
                                __kmp_str_free( &buff );
                            }
                            #endif
                        } // if
                    } // if
                } // case
                break;

            case kmp_sch_guided_iterative_chunked:
                {
                    T  chunkspec = pr->u.p.parm1;
                    KD_TRACE(100,
                        ("__kmp_dispatch_next: T#%d kmp_sch_guided_chunked iterative case\n",gtid));
                    trip  = pr->u.p.tc;
                    // Start atomic part of calculations
                    while(1) {
                        ST  remaining;             // signed, because can be < 0
                        init = sh->u.s.iteration;  // shared value
                        remaining = trip - init;
                        if ( remaining <= 0 ) {    // AC: need to compare with 0 first
                            // nothing to do, don't try atomic op
                            status = 0;
                            break;
                        }
                        if ( (T)remaining < pr->u.p.parm2 ) { // compare with K*nproc*(chunk+1), K=2 by default
                            // use dynamic-style shcedule
                            // atomically inrement iterations, get old value
                            init = test_then_add<ST>( (ST*)&sh->u.s.iteration, (ST)chunkspec );
                            remaining = trip - init;
                            if (remaining <= 0) {
                                status = 0;    // all iterations got by other threads
                            } else {
                                // got some iterations to work on
                                status = 1;
                                if ( (T)remaining > chunkspec ) {
                                    limit = init + chunkspec - 1;
                                } else {
                                    last = 1;   // the last chunk
                                    limit = init + remaining - 1;
                                } // if
                            } // if
                            break;
                        } // if
                        limit = init + (UT)( remaining * *(double*)&pr->u.p.parm3 ); // divide by K*nproc
                        if ( compare_and_swap<ST>( (ST*)&sh->u.s.iteration, (ST)init, (ST)limit ) ) {
                            // CAS was successful, chunk obtained
                            status = 1;
                            --limit;
                            break;
                        } // if
                    } // while
                    if ( status != 0 ) {
                        start = pr->u.p.lb;
                        incr = pr->u.p.st;
                        if ( p_st != NULL )
                            *p_st = incr;
                        *p_lb = start + init * incr;
                        *p_ub = start + limit * incr;
                        if ( pr->ordered ) {
                            pr->u.p.ordered_lower = init;
                            pr->u.p.ordered_upper = limit;
                            #ifdef KMP_DEBUG
                            {
                                const char * buff;
                                // create format specifiers before the debug output
                                buff = __kmp_str_format(
                                    "__kmp_dispatch_next: T#%%d ordered_lower:%%%s ordered_upper:%%%s\n",
                                    traits_t< UT >::spec, traits_t< UT >::spec );
                                KD_TRACE(1000, ( buff, gtid, pr->u.p.ordered_lower, pr->u.p.ordered_upper ) );
                                __kmp_str_free( &buff );
                            }
                            #endif
                        } // if
                    } else {
                        *p_lb = 0;
                        *p_ub = 0;
                        if ( p_st != NULL )
                            *p_st = 0;
                    } // if
                } // case
                break;

            case kmp_sch_guided_analytical_chunked:
                {
                    T   chunkspec = pr->u.p.parm1;
                    UT chunkIdx;
    #if KMP_OS_WINDOWS && KMP_ARCH_X86
                    /* for storing original FPCW value for Windows* OS on
		       IA-32 architecture 8-byte version */
                    unsigned int oldFpcw;
                    unsigned int fpcwSet = 0;
    #endif
                    KD_TRACE(100, ("__kmp_dispatch_next: T#%d kmp_sch_guided_chunked analytical case\n",
                                   gtid ) );

                    trip  = pr->u.p.tc;

                    KMP_DEBUG_ASSERT(team->t.t_nproc > 1);
                    KMP_DEBUG_ASSERT((2UL * chunkspec + 1) * (UT)team->t.t_nproc < trip);

                    while(1) { /* this while loop is a safeguard against unexpected zero chunk sizes */
                        chunkIdx = test_then_inc_acq< ST >((volatile ST *) & sh->u.s.iteration );
                        if ( chunkIdx >= (UT)pr->u.p.parm2 ) {
                            --trip;
                            /* use dynamic-style scheduling */
                            init = chunkIdx * chunkspec + pr->u.p.count;
                            /* need to verify init > 0 in case of overflow in the above calculation */
                            if ( (status = (init > 0 && init <= trip)) != 0 ) {
                                limit = init + chunkspec -1;

                                if ( (last = (limit >= trip)) != 0 )
                                    limit = trip;
                            }
                            break;
                        } else {
                            /* use exponential-style scheduling */
                            /* The following check is to workaround the lack of long double precision on Windows* OS.
                               This check works around the possible effect that init != 0 for chunkIdx == 0.
                             */
    #if KMP_OS_WINDOWS && KMP_ARCH_X86
                            /* If we haven't already done so, save original
			       FPCW and set precision to 64-bit, as Windows* OS
			       on IA-32 architecture defaults to 53-bit */
                            if ( !fpcwSet ) {
                                oldFpcw = _control87(0,0);
                                _control87(_PC_64,_MCW_PC);
                                fpcwSet = 0x30000;
                            }
    #endif
                            if ( chunkIdx ) {
                                init = __kmp_dispatch_guided_remaining< T >(
                                           trip, *( DBL * )&pr->u.p.parm3, chunkIdx );
                                KMP_DEBUG_ASSERT(init);
                                init = trip - init;
                            } else
                                init = 0;
                            limit = trip - __kmp_dispatch_guided_remaining< T >(
                                               trip, *( DBL * )&pr->u.p.parm3, chunkIdx + 1 );
                            KMP_ASSERT(init <= limit);
                            if ( init < limit ) {
                                KMP_DEBUG_ASSERT(limit <= trip);
                                --limit;
                                status = 1;
                                break;
                            } // if
                        } // if
                    } // while (1)
    #if KMP_OS_WINDOWS && KMP_ARCH_X86
                    /* restore FPCW if necessary
                       AC: check fpcwSet flag first because oldFpcw can be uninitialized here
                    */
                    if ( fpcwSet && ( oldFpcw & fpcwSet ) )
                        _control87(oldFpcw,_MCW_PC);
    #endif
                    if ( status != 0 ) {
                        start = pr->u.p.lb;
                        incr = pr->u.p.st;
                        if ( p_st != NULL )
                            *p_st = incr;
                        *p_lb = start + init * incr;
                        *p_ub = start + limit * incr;
                        if ( pr->ordered ) {
                            pr->u.p.ordered_lower = init;
                            pr->u.p.ordered_upper = limit;
                            #ifdef KMP_DEBUG
                            {
                                const char * buff;
                                // create format specifiers before the debug output
                                buff = __kmp_str_format(
                                    "__kmp_dispatch_next: T#%%d ordered_lower:%%%s ordered_upper:%%%s\n",
                                    traits_t< UT >::spec, traits_t< UT >::spec );
                                KD_TRACE(1000, ( buff, gtid, pr->u.p.ordered_lower, pr->u.p.ordered_upper ) );
                                __kmp_str_free( &buff );
                            }
                            #endif
                        }
                    } else {
                        *p_lb = 0;
                        *p_ub = 0;
                        if ( p_st != NULL )
                            *p_st = 0;
                    }
                } // case
                break;

            case kmp_sch_trapezoidal:
                {
                    UT   index;
                    T    parm2 = pr->u.p.parm2;
                    T    parm3 = pr->u.p.parm3;
                    T    parm4 = pr->u.p.parm4;
                    KD_TRACE(100, ("__kmp_dispatch_next: T#%d kmp_sch_trapezoidal case\n",
                                   gtid ) );

                    index = test_then_inc< ST >( (volatile ST *) & sh->u.s.iteration );

                    init = ( index * ( (2*parm2) - (index-1)*parm4 ) ) / 2;
                    trip = pr->u.p.tc - 1;

                    if ( (status = ((T)index < parm3 && init <= trip)) == 0 ) {
                        *p_lb = 0;
                        *p_ub = 0;
                        if ( p_st != NULL ) *p_st = 0;
                    } else {
                        start = pr->u.p.lb;
                        limit = ( (index+1) * ( 2*parm2 - index*parm4 ) ) / 2 - 1;
                        incr  = pr->u.p.st;

                        if ( (last = (limit >= trip)) != 0 )
                            limit = trip;

                        if ( p_st != NULL ) *p_st = incr;

                        if ( incr == 1 ) {
                            *p_lb = start + init;
                            *p_ub = start + limit;
                        } else {
                            *p_lb = start + init * incr;
                            *p_ub = start + limit * incr;
                        }

                        if ( pr->ordered ) {
                            pr->u.p.ordered_lower = init;
                            pr->u.p.ordered_upper = limit;
                            #ifdef KMP_DEBUG
                            {
                                const char * buff;
                                // create format specifiers before the debug output
                                buff = __kmp_str_format(
                                    "__kmp_dispatch_next: T#%%d ordered_lower:%%%s ordered_upper:%%%s\n",
                                    traits_t< UT >::spec, traits_t< UT >::spec );
                                KD_TRACE(1000, ( buff, gtid, pr->u.p.ordered_lower, pr->u.p.ordered_upper ) );
                                __kmp_str_free( &buff );
                            }
                            #endif
                        } // if
                    } // if
                } // case
                break;
            default:
                {
                    status = 0; // to avoid complaints on uninitialized variable use
                    __kmp_msg(
                        kmp_ms_fatal,                        // Severity
                        KMP_MSG( UnknownSchedTypeDetected ), // Primary message
                        KMP_HNT( GetNewerLibrary ),          // Hint
                        __kmp_msg_null                       // Variadic argument list terminator
                    );
                }
                break;
            } // switch
        } // if tc == 0;

        if ( status == 0 ) {
            UT   num_done;

            num_done = test_then_inc< ST >( (volatile ST *) & sh->u.s.num_done );
            #ifdef KMP_DEBUG
            {
                const char * buff;
                // create format specifiers before the debug output
                buff = __kmp_str_format(
                    "__kmp_dispatch_next: T#%%d increment num_done:%%%s\n",
                    traits_t< UT >::spec );
                KD_TRACE(100, ( buff, gtid, sh->u.s.num_done ) );
                __kmp_str_free( &buff );
            }
            #endif

            if ( (ST)num_done == team->t.t_nproc-1 ) {
                /* NOTE: release this buffer to be reused */

                KMP_MB();       /* Flush all pending memory write invalidates.  */

                sh->u.s.num_done = 0;
                sh->u.s.iteration = 0;

                /* TODO replace with general release procedure? */
                if ( pr->ordered ) {
                    sh->u.s.ordered_iteration = 0;
                }

                KMP_MB();       /* Flush all pending memory write invalidates.  */

                sh -> buffer_index += KMP_MAX_DISP_BUF;
                KD_TRACE(100, ("__kmp_dispatch_next: T#%d change buffer_index:%d\n",
                                gtid, sh->buffer_index) );

                KMP_MB();       /* Flush all pending memory write invalidates.  */

            } // if
            if ( __kmp_env_consistency_check ) {
                if ( pr->pushed_ws != ct_none ) {
                    pr->pushed_ws = __kmp_pop_workshare( gtid, pr->pushed_ws, loc );
                }
            }

            th -> th.th_dispatch -> th_deo_fcn = NULL;
            th -> th.th_dispatch -> th_dxo_fcn = NULL;
            th -> th.th_dispatch -> th_dispatch_sh_current = NULL;
            th -> th.th_dispatch -> th_dispatch_pr_current = NULL;
        } // if (status == 0)
#if KMP_OS_WINDOWS
        else if ( last ) {
            pr->u.p.last_upper = pr->u.p.ub;
        }
#endif /* KMP_OS_WINDOWS */
        if ( p_last != NULL && status != 0 )
            *p_last = last;
    } // if

    #ifdef KMP_DEBUG
    {
        const char * buff;
        // create format specifiers before the debug output
        buff = __kmp_str_format(
            "__kmp_dispatch_next: T#%%d normal case: " \
            "p_lb:%%%s p_ub:%%%s p_st:%%%s p_last:%%p  returning:%%d\n",
            traits_t< T >::spec, traits_t< T >::spec, traits_t< ST >::spec );
        KD_TRACE(10, ( buff, gtid, *p_lb, *p_ub, p_st ? *p_st : 0, p_last, status ) );
        __kmp_str_free( &buff );
    }
    #endif
#if INCLUDE_SSC_MARKS
    SSC_MARK_DISPATCH_NEXT();
#endif
    OMPT_LOOP_END;
    return status;
}

template< typename T >
static void
__kmp_dist_get_bounds(
    ident_t                          *loc,
    kmp_int32                         gtid,
    kmp_int32                        *plastiter,
    T                                *plower,
    T                                *pupper,
    typename traits_t< T >::signed_t  incr
) {
    typedef typename traits_t< T >::unsigned_t  UT;
    typedef typename traits_t< T >::signed_t    ST;
    kmp_uint32  team_id; 
    kmp_uint32  nteams; 
    UT          trip_count; 
    kmp_team_t *team; 
    kmp_info_t * th;

    KMP_DEBUG_ASSERT( plastiter && plower && pupper );
    KE_TRACE( 10, ("__kmpc_dist_get_bounds called (%d)\n", gtid));
    #ifdef KMP_DEBUG
    {
        const char * buff;
        // create format specifiers before the debug output
        buff = __kmp_str_format( "__kmpc_dist_get_bounds: T#%%d liter=%%d "\
            "iter=(%%%s, %%%s, %%%s) signed?<%s>\n",
            traits_t< T >::spec, traits_t< T >::spec, traits_t< ST >::spec,
            traits_t< T >::spec );
        KD_TRACE(100, ( buff, gtid, *plastiter, *plower, *pupper, incr ) );
        __kmp_str_free( &buff );
    }
    #endif

    if( __kmp_env_consistency_check ) {
        if( incr == 0 ) {
            __kmp_error_construct( kmp_i18n_msg_CnsLoopIncrZeroProhibited, ct_pdo, loc );
        }
        if( incr > 0 ? (*pupper < *plower) : (*plower < *pupper) ) {
            // The loop is illegal.
            // Some zero-trip loops maintained by compiler, e.g.:
            //   for(i=10;i<0;++i) // lower >= upper - run-time check
            //   for(i=0;i>10;--i) // lower <= upper - run-time check
            //   for(i=0;i>10;++i) // incr > 0       - compile-time check
            //   for(i=10;i<0;--i) // incr < 0       - compile-time check
            // Compiler does not check the following illegal loops:
            //   for(i=0;i<10;i+=incr) // where incr<0
            //   for(i=10;i>0;i-=incr) // where incr<0
            __kmp_error_construct( kmp_i18n_msg_CnsLoopIncrIllegal, ct_pdo, loc );
        }
    }
    th = __kmp_threads[gtid];
    team = th->th.th_team;
    #if OMP_40_ENABLED
    KMP_DEBUG_ASSERT(th->th.th_teams_microtask);   // we are in the teams construct
    nteams = th->th.th_teams_size.nteams;
    #endif
    team_id = team->t.t_master_tid;
    KMP_DEBUG_ASSERT(nteams == team->t.t_parent->t.t_nproc);

    // compute global trip count
    if( incr == 1 ) {
        trip_count = *pupper - *plower + 1;
    } else if(incr == -1) {
        trip_count = *plower - *pupper + 1;
    } else {
        trip_count = (ST)(*pupper - *plower) / incr + 1; // cast to signed to cover incr<0 case
    }

    if( trip_count <= nteams ) {
        KMP_DEBUG_ASSERT(
            __kmp_static == kmp_sch_static_greedy || \
            __kmp_static == kmp_sch_static_balanced
        ); // Unknown static scheduling type.
        // only some teams get single iteration, others get nothing
        if( team_id < trip_count ) {
            *pupper = *plower = *plower + team_id * incr;
        } else {
            *plower = *pupper + incr; // zero-trip loop
        }
        if( plastiter != NULL )
            *plastiter = ( team_id == trip_count - 1 );
    } else {
        if( __kmp_static == kmp_sch_static_balanced ) {
            UT chunk = trip_count / nteams; 
            UT extras = trip_count % nteams; 
            *plower += incr * ( team_id * chunk + ( team_id < extras ? team_id : extras ) );
            *pupper = *plower + chunk * incr - ( team_id < extras ? 0 : incr );
            if( plastiter != NULL )
                *plastiter = ( team_id == nteams - 1 );
        } else {
            T chunk_inc_count = 
                ( trip_count / nteams + ( ( trip_count % nteams ) ? 1 : 0) ) * incr;
            T upper = *pupper; 
            KMP_DEBUG_ASSERT( __kmp_static == kmp_sch_static_greedy );
                // Unknown static scheduling type.
            *plower += team_id * chunk_inc_count;
            *pupper = *plower + chunk_inc_count - incr;
            // Check/correct bounds if needed
            if( incr > 0 ) {
                if( *pupper < *plower )
                    *pupper = i_maxmin< T >::mx;
                if( plastiter != NULL )
                    *plastiter = *plower <= upper && *pupper > upper - incr;
                if( *pupper > upper )
                    *pupper = upper; // tracker C73258
            } else {
                if( *pupper > *plower )
                    *pupper = i_maxmin< T >::mn;
                if( plastiter != NULL )
                    *plastiter = *plower >= upper && *pupper < upper - incr;
                if( *pupper < upper )
                    *pupper = upper; // tracker C73258
            }
        }
    }
}

//-----------------------------------------------------------------------------------------
// Dispatch routines
//    Transfer call to template< type T >
//    __kmp_dispatch_init( ident_t *loc, int gtid, enum sched_type schedule,
//                         T lb, T ub, ST st, ST chunk )
extern "C" {

/*!
@ingroup WORK_SHARING
@{
@param loc Source location
@param gtid Global thread id
@param schedule Schedule type
@param lb  Lower bound
@param ub  Upper bound
@param st  Step (or increment if you prefer)
@param chunk The chunk size to block with

This function prepares the runtime to start a dynamically scheduled for loop, saving the loop arguments.
These functions are all identical apart from the types of the arguments.
*/

void
__kmpc_dispatch_init_4( ident_t *loc, kmp_int32 gtid, enum sched_type schedule,
                        kmp_int32 lb, kmp_int32 ub, kmp_int32 st, kmp_int32 chunk )
{
    KMP_DEBUG_ASSERT( __kmp_init_serial );
    __kmp_dispatch_init< kmp_int32 >( loc, gtid, schedule, lb, ub, st, chunk, true );
}
/*!
See @ref __kmpc_dispatch_init_4
*/
void
__kmpc_dispatch_init_4u( ident_t *loc, kmp_int32 gtid, enum sched_type schedule,
                        kmp_uint32 lb, kmp_uint32 ub, kmp_int32 st, kmp_int32 chunk )
{
    KMP_DEBUG_ASSERT( __kmp_init_serial );
    __kmp_dispatch_init< kmp_uint32 >( loc, gtid, schedule, lb, ub, st, chunk, true );
}

/*!
See @ref __kmpc_dispatch_init_4
*/
void
__kmpc_dispatch_init_8( ident_t *loc, kmp_int32 gtid, enum sched_type schedule,
                        kmp_int64 lb, kmp_int64 ub,
                        kmp_int64 st, kmp_int64 chunk )
{
    KMP_DEBUG_ASSERT( __kmp_init_serial );
    __kmp_dispatch_init< kmp_int64 >( loc, gtid, schedule, lb, ub, st, chunk, true );
}

/*!
See @ref __kmpc_dispatch_init_4
*/
void
__kmpc_dispatch_init_8u( ident_t *loc, kmp_int32 gtid, enum sched_type schedule,
                         kmp_uint64 lb, kmp_uint64 ub,
                         kmp_int64 st, kmp_int64 chunk )
{
    KMP_DEBUG_ASSERT( __kmp_init_serial );
    __kmp_dispatch_init< kmp_uint64 >( loc, gtid, schedule, lb, ub, st, chunk, true );
}

/*!
See @ref __kmpc_dispatch_init_4

Difference from __kmpc_dispatch_init set of functions is these functions
are called for composite distribute parallel for construct. Thus before
regular iterations dispatching we need to calc per-team iteration space.

These functions are all identical apart from the types of the arguments.
*/
void
__kmpc_dist_dispatch_init_4( ident_t *loc, kmp_int32 gtid, enum sched_type schedule,
    kmp_int32 *p_last, kmp_int32 lb, kmp_int32 ub, kmp_int32 st, kmp_int32 chunk )
{
    KMP_DEBUG_ASSERT( __kmp_init_serial );
    __kmp_dist_get_bounds< kmp_int32 >( loc, gtid, p_last, &lb, &ub, st );
    __kmp_dispatch_init< kmp_int32 >( loc, gtid, schedule, lb, ub, st, chunk, true );
}

void
__kmpc_dist_dispatch_init_4u( ident_t *loc, kmp_int32 gtid, enum sched_type schedule,
    kmp_int32 *p_last, kmp_uint32 lb, kmp_uint32 ub, kmp_int32 st, kmp_int32 chunk )
{
    KMP_DEBUG_ASSERT( __kmp_init_serial );
    __kmp_dist_get_bounds< kmp_uint32 >( loc, gtid, p_last, &lb, &ub, st );
    __kmp_dispatch_init< kmp_uint32 >( loc, gtid, schedule, lb, ub, st, chunk, true );
}

void
__kmpc_dist_dispatch_init_8( ident_t *loc, kmp_int32 gtid, enum sched_type schedule,
    kmp_int32 *p_last, kmp_int64 lb, kmp_int64 ub, kmp_int64 st, kmp_int64 chunk )
{
    KMP_DEBUG_ASSERT( __kmp_init_serial );
    __kmp_dist_get_bounds< kmp_int64 >( loc, gtid, p_last, &lb, &ub, st );
    __kmp_dispatch_init< kmp_int64 >( loc, gtid, schedule, lb, ub, st, chunk, true );
}

void
__kmpc_dist_dispatch_init_8u( ident_t *loc, kmp_int32 gtid, enum sched_type schedule,
    kmp_int32 *p_last, kmp_uint64 lb, kmp_uint64 ub, kmp_int64 st, kmp_int64 chunk )
{
    KMP_DEBUG_ASSERT( __kmp_init_serial );
    __kmp_dist_get_bounds< kmp_uint64 >( loc, gtid, p_last, &lb, &ub, st );
    __kmp_dispatch_init< kmp_uint64 >( loc, gtid, schedule, lb, ub, st, chunk, true );
}

/*!
@param loc Source code location
@param gtid Global thread id
@param p_last Pointer to a flag set to one if this is the last chunk or zero otherwise
@param p_lb   Pointer to the lower bound for the next chunk of work
@param p_ub   Pointer to the upper bound for the next chunk of work
@param p_st   Pointer to the stride for the next chunk of work
@return one if there is work to be done, zero otherwise

Get the next dynamically allocated chunk of work for this thread.
If there is no more work, then the lb,ub and stride need not be modified.
*/
int
__kmpc_dispatch_next_4( ident_t *loc, kmp_int32 gtid, kmp_int32 *p_last,
                        kmp_int32 *p_lb, kmp_int32 *p_ub, kmp_int32 *p_st )
{
    return __kmp_dispatch_next< kmp_int32 >( loc, gtid, p_last, p_lb, p_ub, p_st );
}

/*!
See @ref __kmpc_dispatch_next_4
*/
int
__kmpc_dispatch_next_4u( ident_t *loc, kmp_int32 gtid, kmp_int32 *p_last,
                        kmp_uint32 *p_lb, kmp_uint32 *p_ub, kmp_int32 *p_st )
{
    return __kmp_dispatch_next< kmp_uint32 >( loc, gtid, p_last, p_lb, p_ub, p_st );
}

/*!
See @ref __kmpc_dispatch_next_4
*/
int
__kmpc_dispatch_next_8( ident_t *loc, kmp_int32 gtid, kmp_int32 *p_last,
                        kmp_int64 *p_lb, kmp_int64 *p_ub, kmp_int64 *p_st )
{
    return __kmp_dispatch_next< kmp_int64 >( loc, gtid, p_last, p_lb, p_ub, p_st );
}

/*!
See @ref __kmpc_dispatch_next_4
*/
int
__kmpc_dispatch_next_8u( ident_t *loc, kmp_int32 gtid, kmp_int32 *p_last,
                        kmp_uint64 *p_lb, kmp_uint64 *p_ub, kmp_int64 *p_st )
{
    return __kmp_dispatch_next< kmp_uint64 >( loc, gtid, p_last, p_lb, p_ub, p_st );
}

/*!
@param loc Source code location
@param gtid Global thread id

Mark the end of a dynamic loop.
*/
void
__kmpc_dispatch_fini_4( ident_t *loc, kmp_int32 gtid )
{
    __kmp_dispatch_finish< kmp_uint32 >( gtid, loc );
}

/*!
See @ref __kmpc_dispatch_fini_4
*/
void
__kmpc_dispatch_fini_8( ident_t *loc, kmp_int32 gtid )
{
    __kmp_dispatch_finish< kmp_uint64 >( gtid, loc );
}

/*!
See @ref __kmpc_dispatch_fini_4
*/
void
__kmpc_dispatch_fini_4u( ident_t *loc, kmp_int32 gtid )
{
    __kmp_dispatch_finish< kmp_uint32 >( gtid, loc );
}

/*!
See @ref __kmpc_dispatch_fini_4
*/
void
__kmpc_dispatch_fini_8u( ident_t *loc, kmp_int32 gtid )
{
    __kmp_dispatch_finish< kmp_uint64 >( gtid, loc );
}
/*! @} */

//-----------------------------------------------------------------------------------------
//Non-template routines from kmp_dispatch.c used in other sources

kmp_uint32 __kmp_eq_4( kmp_uint32 value, kmp_uint32 checker) {
    return value == checker;
}

kmp_uint32 __kmp_neq_4( kmp_uint32 value, kmp_uint32 checker) {
    return value != checker;
}

kmp_uint32 __kmp_lt_4( kmp_uint32 value, kmp_uint32 checker) {
    return value < checker;
}

kmp_uint32 __kmp_ge_4( kmp_uint32 value, kmp_uint32 checker) {
    return value >= checker;
}

kmp_uint32 __kmp_le_4( kmp_uint32 value, kmp_uint32 checker) {
    return value <= checker;
}
kmp_uint32 __kmp_eq_8( kmp_uint64 value, kmp_uint64 checker) {
    return value == checker;
}

kmp_uint32 __kmp_neq_8( kmp_uint64 value, kmp_uint64 checker) {
    return value != checker;
}

kmp_uint32 __kmp_lt_8( kmp_uint64 value, kmp_uint64 checker) {
    return value < checker;
}

kmp_uint32 __kmp_ge_8( kmp_uint64 value, kmp_uint64 checker) {
    return value >= checker;
}

kmp_uint32 __kmp_le_8( kmp_uint64 value, kmp_uint64 checker) {
    return value <= checker;
}

kmp_uint32
__kmp_wait_yield_4(volatile kmp_uint32 * spinner,
                   kmp_uint32            checker,
                   kmp_uint32 (* pred)( kmp_uint32, kmp_uint32 )
                   , void        * obj    // Higher-level synchronization object, or NULL.
                   )
{
    // note: we may not belong to a team at this point
    volatile kmp_uint32         * spin          = spinner; 
             kmp_uint32           check         = checker; 
             kmp_uint32   spins; 
             kmp_uint32 (*f) ( kmp_uint32, kmp_uint32 ) = pred; 
             kmp_uint32           r; 

    KMP_FSYNC_SPIN_INIT( obj, (void*) spin );
    KMP_INIT_YIELD( spins );
    // main wait spin loop
    while(!f(r = TCR_4(*spin), check)) {
        KMP_FSYNC_SPIN_PREPARE( obj );
        /* GEH - remove this since it was accidentally introduced when kmp_wait was split.
           It causes problems with infinite recursion because of exit lock */
        /* if ( TCR_4(__kmp_global.g.g_done) && __kmp_global.g.g_abort)
            __kmp_abort_thread(); */

        /* if we have waited a bit, or are oversubscribed, yield */
        /* pause is in the following code */
        KMP_YIELD( TCR_4(__kmp_nth) > __kmp_avail_proc );
        KMP_YIELD_SPIN( spins );
    }
    KMP_FSYNC_SPIN_ACQUIRED( obj );
    return r;
}

kmp_uint64
__kmp_wait_yield_8( volatile kmp_uint64 * spinner,
                    kmp_uint64            checker,
                    kmp_uint32 (* pred)( kmp_uint64, kmp_uint64 )
                    , void        * obj    // Higher-level synchronization object, or NULL.
                    )
{
    // note: we may not belong to a team at this point
    volatile kmp_uint64         * spin          = spinner; 
             kmp_uint64           check         = checker; 
             kmp_uint32   spins; 
             kmp_uint32 (*f) ( kmp_uint64, kmp_uint64 ) = pred; 
             kmp_uint64           r; 

    KMP_FSYNC_SPIN_INIT( obj, (void*) spin );
    KMP_INIT_YIELD( spins );
    // main wait spin loop
    while(!f(r = *spin, check))
    {
        KMP_FSYNC_SPIN_PREPARE( obj );
        /* GEH - remove this since it was accidentally introduced when kmp_wait was split.
           It causes problems with infinite recursion because of exit lock */
        /* if ( TCR_4(__kmp_global.g.g_done) && __kmp_global.g.g_abort)
            __kmp_abort_thread(); */

        // if we are oversubscribed,
        // or have waited a bit (and KMP_LIBARRY=throughput, then yield
        // pause is in the following code
        KMP_YIELD( TCR_4(__kmp_nth) > __kmp_avail_proc );
        KMP_YIELD_SPIN( spins );
    }
    KMP_FSYNC_SPIN_ACQUIRED( obj );
    return r;
}

} // extern "C"

#ifdef KMP_GOMP_COMPAT

void
__kmp_aux_dispatch_init_4( ident_t *loc, kmp_int32 gtid, enum sched_type schedule,
                           kmp_int32 lb, kmp_int32 ub, kmp_int32 st,
                           kmp_int32 chunk, int push_ws )
{
    __kmp_dispatch_init< kmp_int32 >( loc, gtid, schedule, lb, ub, st, chunk,
                                      push_ws );
}

void
__kmp_aux_dispatch_init_4u( ident_t *loc, kmp_int32 gtid, enum sched_type schedule,
                            kmp_uint32 lb, kmp_uint32 ub, kmp_int32 st,
                            kmp_int32 chunk, int push_ws )
{
    __kmp_dispatch_init< kmp_uint32 >( loc, gtid, schedule, lb, ub, st, chunk,
                                       push_ws );
}

void
__kmp_aux_dispatch_init_8( ident_t *loc, kmp_int32 gtid, enum sched_type schedule,
                           kmp_int64 lb, kmp_int64 ub, kmp_int64 st,
                           kmp_int64 chunk, int push_ws )
{
    __kmp_dispatch_init< kmp_int64 >( loc, gtid, schedule, lb, ub, st, chunk,
                                      push_ws );
}

void
__kmp_aux_dispatch_init_8u( ident_t *loc, kmp_int32 gtid, enum sched_type schedule,
                            kmp_uint64 lb, kmp_uint64 ub, kmp_int64 st,
                            kmp_int64 chunk, int push_ws )
{
    __kmp_dispatch_init< kmp_uint64 >( loc, gtid, schedule, lb, ub, st, chunk,
                                       push_ws );
}

void
__kmp_aux_dispatch_fini_chunk_4( ident_t *loc, kmp_int32 gtid )
{
    __kmp_dispatch_finish_chunk< kmp_uint32 >( gtid, loc );
}

void
__kmp_aux_dispatch_fini_chunk_8( ident_t *loc, kmp_int32 gtid )
{
    __kmp_dispatch_finish_chunk< kmp_uint64 >( gtid, loc );
}

void
__kmp_aux_dispatch_fini_chunk_4u( ident_t *loc, kmp_int32 gtid )
{
    __kmp_dispatch_finish_chunk< kmp_uint32 >( gtid, loc );
}

void
__kmp_aux_dispatch_fini_chunk_8u( ident_t *loc, kmp_int32 gtid )
{
    __kmp_dispatch_finish_chunk< kmp_uint64 >( gtid, loc );
}

#endif /* KMP_GOMP_COMPAT */

/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */