aboutsummaryrefslogtreecommitdiff
path: root/gcc/fortran/gfortran.texi
blob: e7ffc294dc81324115fc932615faec56725cdccf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
\input texinfo  @c -*-texinfo-*-
@c %**start of header
@setfilename gfortran.info
@set copyrights-gfortran 1999-2023

@include gcc-common.texi

@settitle The GNU Fortran Compiler

@c Create a separate index for command line options
@defcodeindex op
@c Merge the standard indexes into a single one.
@syncodeindex fn cp
@syncodeindex vr cp
@syncodeindex ky cp
@syncodeindex pg cp
@syncodeindex tp cp

@c TODO: The following "Part" definitions are included here temporarily
@c until they are incorporated into the official Texinfo distribution.
@c They borrow heavily from Texinfo's \unnchapentry definitions.

@tex
\gdef\part#1#2{%
  \pchapsepmacro
  \gdef\thischapter{}
  \begingroup
    \vglue\titlepagetopglue
    \titlefonts \rm
    \leftline{Part #1:@* #2}
    \vskip4pt \hrule height 4pt width \hsize \vskip4pt
  \endgroup
  \writetocentry{part}{#2}{#1}
}
\gdef\blankpart{%
  \writetocentry{blankpart}{}{}
}
% Part TOC-entry definition for summary contents.
\gdef\dosmallpartentry#1#2#3#4{%
  \vskip .5\baselineskip plus.2\baselineskip
  \begingroup
    \let\rm=\bf \rm
    \tocentry{Part #2: #1}{\doshortpageno\bgroup#4\egroup}
  \endgroup
}
\gdef\dosmallblankpartentry#1#2#3#4{%
  \vskip .5\baselineskip plus.2\baselineskip
}
% Part TOC-entry definition for regular contents.  This has to be
% equated to an existing entry to not cause problems when the PDF
% outline is created.
\gdef\dopartentry#1#2#3#4{%
  \unnchapentry{Part #2: #1}{}{#3}{#4}
}
\gdef\doblankpartentry#1#2#3#4{}
@end tex

@c %**end of header

@c Use with @@smallbook.

@c %** start of document

@c Cause even numbered pages to be printed on the left hand side of
@c the page and odd numbered pages to be printed on the right hand
@c side of the page.  Using this, you can print on both sides of a
@c sheet of paper and have the text on the same part of the sheet.

@c The text on right hand pages is pushed towards the right hand
@c margin and the text on left hand pages is pushed toward the left
@c hand margin.
@c (To provide the reverse effect, set bindingoffset to -0.75in.)

@c @tex
@c \global\bindingoffset=0.75in
@c \global\normaloffset =0.75in
@c @end tex

@copying
Copyright @copyright{} @value{copyrights-gfortran} Free Software Foundation, Inc.

Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with the
Invariant Sections being ``Funding Free Software'', the Front-Cover
Texts being (a) (see below), and with the Back-Cover Texts being (b)
(see below).  A copy of the license is included in the section entitled
``GNU Free Documentation License''.

(a) The FSF's Front-Cover Text is:

     A GNU Manual

(b) The FSF's Back-Cover Text is:

     You have freedom to copy and modify this GNU Manual, like GNU
     software.  Copies published by the Free Software Foundation raise
     funds for GNU development.
@end copying

@ifinfo
@dircategory Software development
@direntry
* gfortran: (gfortran).                  The GNU Fortran Compiler.
@end direntry
This file documents the use and the internals of
the GNU Fortran compiler, (@command{gfortran}).

Published by the Free Software Foundation
51 Franklin Street, Fifth Floor
Boston, MA 02110-1301 USA

@insertcopying
@end ifinfo


@setchapternewpage odd
@titlepage
@title Using GNU Fortran
@versionsubtitle
@author The @t{gfortran} team
@page
@vskip 0pt plus 1filll
Published by the Free Software Foundation@*
51 Franklin Street, Fifth Floor@*
Boston, MA 02110-1301, USA@*
@c Last printed ??ber, 19??.@*
@c Printed copies are available for $? each.@*
@c ISBN ???
@sp 1
@insertcopying
@end titlepage

@c TODO: The following "Part" definitions are included here temporarily
@c until they are incorporated into the official Texinfo distribution.

@tex
\global\let\partentry=\dosmallpartentry
\global\let\blankpartentry=\dosmallblankpartentry
@end tex
@summarycontents

@tex
\global\let\partentry=\dopartentry
\global\let\blankpartentry=\doblankpartentry
@end tex
@contents

@page

@c ---------------------------------------------------------------------
@c TexInfo table of contents.
@c ---------------------------------------------------------------------

@ifnottex
@node Top
@top Introduction
@cindex Introduction

This manual documents the use of @command{gfortran},
the GNU Fortran compiler.  You can find in this manual how to invoke
@command{gfortran}, as well as its features and incompatibilities.

@ifset DEVELOPMENT
@emph{Warning:} This document, and the compiler it describes, are still
under development.  While efforts are made to keep it up-to-date, it might
not accurately reflect the status of the most recent GNU Fortran compiler.
@end ifset

@comment
@comment  When you add a new menu item, please keep the right hand
@comment  aligned to the same column.  Do not use tabs.  This provides
@comment  better formatting.
@comment
@menu
* Introduction::

Part I: Invoking GNU Fortran
* Invoking GNU Fortran:: Command options supported by @command{gfortran}.
* Runtime::              Influencing runtime behavior with environment variables.

Part II: Language Reference
* Compiler Characteristics::      User-visible implementation details.
* Extensions::                    Language extensions implemented by GNU Fortran.
* Mixed-Language Programming::    Interoperability with C
* Coarray Programming::
* Intrinsic Procedures:: Intrinsic procedures supported by GNU Fortran.
* Intrinsic Modules::    Intrinsic modules supported by GNU Fortran.

* Contributing::         How you can help.
* Copying::              GNU General Public License says
                         how you can copy and share GNU Fortran.
* GNU Free Documentation License::
                         How you can copy and share this manual.
* Funding::              How to help assure continued work for free software.
* Option Index::         Index of command line options
* Keyword Index::        Index of concepts
@end menu
@end ifnottex

@c ---------------------------------------------------------------------
@c Introduction
@c ---------------------------------------------------------------------

@node Introduction
@chapter Introduction

@c The following duplicates the text on the TexInfo table of contents.
@iftex
This manual documents the use of @command{gfortran}, the GNU Fortran
compiler.  You can find in this manual how to invoke @command{gfortran},
as well as its features and incompatibilities.

@ifset DEVELOPMENT
@emph{Warning:} This document, and the compiler it describes, are still
under development.  While efforts are made to keep it up-to-date, it
might not accurately reflect the status of the most recent GNU Fortran
compiler.
@end ifset
@end iftex

@menu
* About GNU Fortran::    What you should know about the GNU Fortran compiler.
* GNU Fortran and GCC::  You can compile Fortran, C, or other programs.
* Standards::            Standards supported by GNU Fortran.
@end menu


@c ---------------------------------------------------------------------
@c About GNU Fortran
@c ---------------------------------------------------------------------

@node About GNU Fortran
@section About GNU Fortran

The GNU Fortran compiler is the successor to @command{g77}, the
Fortran 77 front end included in GCC prior to version 4 (released in
2005).  While it is backward-compatible with most @command{g77}
extensions and command-line options, @command{gfortran} is a completely new
implemention designed to support more modern dialects of Fortran.
GNU Fortran implements the Fortran 77, 90 and 95 standards
completely, most of the Fortran 2003 and 2008 standards, and some
features from the 2018 standard.  It also implements several extensions
including OpenMP and OpenACC support for parallel programming.

The GNU Fortran compiler passes the
@uref{http://www.fortran-2000.com/ArnaudRecipes/fcvs21_f95.html,
NIST Fortran 77 Test Suite}, and produces acceptable results on the
@uref{https://www.netlib.org/lapack/faq.html, LAPACK Test Suite}.
It also provides respectable performance on
the @uref{https://polyhedron.com/?page_id=175,
Polyhedron Fortran compiler benchmarks} and the
@uref{https://www.netlib.org/benchmark/livermore,
Livermore Fortran Kernels test}.  It has been used to compile a number of
large real-world programs, including
@uref{http://hirlam.org/, the HARMONIE and HIRLAM weather forecasting code} and
@uref{https://github.com/dylan-jayatilaka/tonto,
the Tonto quantum chemistry package}; see
@url{https://gcc.gnu.org/@/wiki/@/GfortranApps} for an extended list.

GNU Fortran provides the following functionality:

@itemize @bullet
@item
Read a program, stored in a file and containing @dfn{source code}
instructions written in Fortran 77.

@item
Translate the program into instructions a computer
can carry out more quickly than it takes to translate the
original Fortran instructions.
The result after compilation of a program is
@dfn{machine code},
which is efficiently translated and processed
by a machine such as your computer.
Humans usually are not as good writing machine code
as they are at writing Fortran (or C++, Ada, or Java),
because it is easy to make tiny mistakes writing machine code.

@item
Provide information about the reasons why
the compiler may be unable to create a binary from the source code,
for example if the source code is flawed.
The Fortran language standards require that the compiler can point out
mistakes in your code.
An incorrect usage of the language causes an @dfn{error message}.

The compiler also attempts to diagnose cases where your
program contains a correct usage of the language,
but instructs the computer to do something questionable.
This kind of diagnostic message is called a @dfn{warning message}.

@item
Provide optional information about the translation passes
from the source code to machine code.
This can help you to find the cause of
certain bugs which may not be obvious in the source code,
but may be more easily found at a lower level compiler output.
It also helps developers to find bugs in the compiler itself.

@item
Provide information in the generated machine code that can
make it easier to find bugs in the program (using a debugging tool,
called a @dfn{debugger}, such as the GNU Debugger @command{gdb}).

@item
Locate and gather machine code already generated to
perform actions requested by statements in the program.
This machine code is organized into @dfn{modules} and is located
and @dfn{linked} to the user program.
@end itemize

The GNU Fortran compiler consists of several components:

@itemize @bullet
@item
A version of the @command{gcc} command
(which also might be installed as the system's @command{cc} command)
that also understands and accepts Fortran source code.
The @command{gcc} command is the @dfn{driver} program for
all the languages in the GNU Compiler Collection (GCC);
With @command{gcc},
you can compile the source code of any language for
which a front end is available in GCC.

@item
The @command{gfortran} command itself,
which also might be installed as the
system's @command{f95} command.
@command{gfortran} is just another driver program,
but specifically for the Fortran compiler only.
The primary difference between the @command{gcc} and @command{gfortran}
commands is that the latter automatically links the correct libraries
to your program.

@item
A collection of run-time libraries.
These libraries contain the machine code needed to support
capabilities of the Fortran language that are not directly
provided by the machine code generated by the
@command{gfortran} compilation phase,
such as intrinsic functions and subroutines,
and routines for interaction with files and the operating system.
@c and mechanisms to spawn,
@c unleash and pause threads in parallelized code.

@item
The Fortran compiler itself, (@command{f951}).
This is the GNU Fortran parser and code generator,
linked to and interfaced with the GCC backend library.
@command{f951} ``translates'' the source code to
assembler code.  You would typically not use this
program directly;
instead, the @command{gcc} or @command{gfortran} driver
programs call it for you.
@end itemize


@c ---------------------------------------------------------------------
@c GNU Fortran and GCC
@c ---------------------------------------------------------------------

@node GNU Fortran and GCC
@section GNU Fortran and GCC
@cindex GNU Compiler Collection
@cindex GCC

GNU Fortran is a part of GCC, the @dfn{GNU Compiler Collection}.  GCC
consists of a collection of front ends for various languages, which
translate the source code into a language-independent form called
@dfn{GENERIC}.  This is then processed by a common middle end which
provides optimization, and then passed to one of a collection of back
ends which generate code for different computer architectures and
operating systems.

Functionally, this is implemented with a driver program (@command{gcc})
which provides the command-line interface for the compiler.  It calls
the relevant compiler front-end program (e.g., @command{f951} for
Fortran) for each file in the source code, and then calls the assembler
and linker as appropriate to produce the compiled output.  In a copy of
GCC that has been compiled with Fortran language support enabled,
@command{gcc} recognizes files with @file{.f}, @file{.for}, @file{.ftn},
@file{.f90}, @file{.f95}, @file{.f03} and @file{.f08} extensions as
Fortran source code, and compiles it accordingly.  A @command{gfortran}
driver program is also provided, which is identical to @command{gcc}
except that it automatically links the Fortran runtime libraries into the
compiled program.

Source files with @file{.f}, @file{.for}, @file{.fpp}, @file{.ftn}, @file{.F},
@file{.FOR}, @file{.FPP}, and @file{.FTN} extensions are treated as fixed form.
Source files with @file{.f90}, @file{.f95}, @file{.f03}, @file{.f08},
@file{.F90}, @file{.F95}, @file{.F03} and @file{.F08} extensions are
treated as free form.  The capitalized versions of either form are run
through preprocessing.  Source files with the lower case @file{.fpp}
extension are also run through preprocessing.

This manual specifically documents the Fortran front end, which handles
the programming language's syntax and semantics.  The aspects of GCC
that relate to the optimization passes and the back-end code generation
are documented in the GCC manual; see
@ref{Top,,Introduction,gcc,Using the GNU Compiler Collection (GCC)}.
The two manuals together provide a complete reference for the GNU
Fortran compiler.

@c ---------------------------------------------------------------------
@c Standards
@c ---------------------------------------------------------------------

@node Standards
@section Standards
@cindex Standards

@menu
* Fortran 95 status::
* Fortran 2003 status::
* Fortran 2008 status::
* Fortran 2018 status::
@end menu

Fortran is developed by the Working Group 5 of Sub-Committee 22 of the
Joint Technical Committee 1 of the International Organization for
Standardization and the International Electrotechnical Commission (IEC).
This group is known as @uref{http://www.nag.co.uk/sc22wg5/, WG5}.
Official Fortran standard documents are available for purchase
from ISO; a collection of free documents (typically final drafts) are
also available on the @uref{https://gcc.gnu.org/wiki/GFortranStandards, wiki}.

The GNU Fortran compiler implements ISO/IEC 1539:1997 (Fortran 95).
As such, it can also compile essentially all standard-compliant
Fortran 90 and Fortran 77 programs.  It also supports the ISO/IEC
TR-15581 enhancements to allocatable arrays.

GNU Fortran also supports almost all of ISO/IEC 1539-1:2004
(Fortran 2003) and ISO/IEC 1539-1:2010 (Fortran 2008).
It has partial support for features introduced in ISO/IEC
1539:2018 (Fortran 2018), the most recent version of the Fortran
language standard, including full support for the Technical Specification
@code{Further Interoperability of Fortran with C} (ISO/IEC TS 29113:2012).
More details on support for these standards can be
found in the following sections of the documentation.

Additionally, the GNU Fortran compilers supports the OpenMP specification
(version 4.5 and partial support of the features of the 5.0 version,
@url{https://openmp.org/@/specifications/}).
There also is support for the OpenACC specification (targeting
version 2.6, @uref{https://www.openacc.org/}).  See
@uref{https://gcc.gnu.org/wiki/OpenACC} for more information.

@node Fortran 95 status
@subsection Fortran 95 status
@cindex Varying length strings
@cindex strings, varying length
@cindex conditional compilation

The Fortran 95 standard specifies in Part 2 (ISO/IEC 1539-2:2000)
varying length character strings.  While GNU Fortran currently does not
support such strings directly, there exist two Fortran implementations
for them, which work with GNU Fortran. One can be found at
@uref{http://user.astro.wisc.edu/~townsend/static.php?ref=iso-varying-string}.

Deferred-length character strings of Fortran 2003 supports part of
the features of @code{ISO_VARYING_STRING} and should be considered as
replacement. (Namely, allocatable or pointers of the type
@code{character(len=:)}.)

Part 3 of the Fortran 95 standard (ISO/IEC 1539-3:1998) defines
Conditional Compilation, which is not widely used and not directly
supported by the GNU Fortran compiler.  You can use the program coco
to preprocess such files (@uref{http://www.daniellnagle.com/coco.html}).

@node Fortran 2003 status
@subsection Fortran 2003 status

GNU Fortran implements the Fortran 2003 (ISO/IEC 1539-1:2004) standard
except for finalization support, which is incomplete.
See the
@uref{https://gcc.gnu.org/wiki/Fortran2003, wiki page} for a full list
of new features introduced by Fortran 2003 and their implementation status.

@node Fortran 2008 status
@subsection Fortran 2008 status

The GNU Fortran compiler supports almost all features of Fortran 2008;
the @uref{https://gcc.gnu.org/wiki/Fortran2008Status, wiki}
has some information about the current implementation status.
In particular, the following are not yet supported:

@itemize @bullet
@item
@code{DO CONCURRENT} and @code{FORALL} do not recognize a
type-spec in the loop header.

@item
The change to permit any constant expression in subscripts and
nested implied-do limits in a @code{DATA} statement has not been implemented.
@end itemize


@node Fortran 2018 status
@subsection Fortran 2018 status

Fortran 2018 (ISO/IEC 1539:2018) is the most recent version
of the Fortran language standard.  GNU Fortran implements some of the
new features of this standard:

@itemize @bullet
@item
All Fortran 2018 features derived from ISO/IEC TS 29113:2012,
``Further Interoperability of Fortran with C'', are supported by GNU Fortran.
This includes assumed-type and assumed-rank objects and
the @code{SELECT RANK} construct as well as the parts relating to
@code{BIND(C)} functions.
See also @ref{Further Interoperability of Fortran with C}.

@item
GNU Fortran supports a subset of features derived from ISO/IEC TS 18508:2015,
``Additional Parallel Features in Fortran'':

@itemize @bullet
@item
The new atomic ADD, CAS, FETCH and ADD/OR/XOR, OR and XOR intrinsics.

@item
The @code{CO_MIN} and @code{CO_MAX} and @code{SUM} reduction intrinsics,
and the @code{CO_BROADCAST} and @code{CO_REDUCE} intrinsic, except that those
do not support polymorphic types or types with allocatable, pointer or
polymorphic components.

@item
Events (@code{EVENT POST}, @code{EVENT WAIT}, @code{EVENT_QUERY}).

@item
Failed images (@code{FAIL IMAGE}, @code{IMAGE_STATUS},
@code{FAILED_IMAGES}, @code{STOPPED_IMAGES}).

@end itemize

@item
An @code{ERROR STOP} statement is permitted in a @code{PURE}
procedure.

@item
GNU Fortran supports the @code{IMPLICIT NONE} statement with an
@code{implicit-none-spec-list}.

@item
The behavior of the @code{INQUIRE} statement with the @code{RECL=}
specifier now conforms to Fortran 2018.

@end itemize


@c =====================================================================
@c PART I: INVOCATION REFERENCE
@c =====================================================================

@tex
\part{I}{Invoking GNU Fortran}
@end tex

@c ---------------------------------------------------------------------
@c Compiler Options
@c ---------------------------------------------------------------------

@include invoke.texi


@c ---------------------------------------------------------------------
@c Runtime
@c ---------------------------------------------------------------------

@node Runtime
@chapter Runtime:  Influencing runtime behavior with environment variables
@cindex environment variable

The behavior of the @command{gfortran} can be influenced by
environment variables.

Malformed environment variables are silently ignored.

@menu
* TMPDIR:: Directory for scratch files
* GFORTRAN_STDIN_UNIT:: Unit number for standard input
* GFORTRAN_STDOUT_UNIT:: Unit number for standard output
* GFORTRAN_STDERR_UNIT:: Unit number for standard error
* GFORTRAN_UNBUFFERED_ALL:: Do not buffer I/O for all units
* GFORTRAN_UNBUFFERED_PRECONNECTED:: Do not buffer I/O for preconnected units.
* GFORTRAN_SHOW_LOCUS::  Show location for runtime errors
* GFORTRAN_OPTIONAL_PLUS:: Print leading + where permitted
* GFORTRAN_LIST_SEPARATOR::  Separator for list output
* GFORTRAN_CONVERT_UNIT::  Set conversion for unformatted I/O
* GFORTRAN_ERROR_BACKTRACE:: Show backtrace on run-time errors
* GFORTRAN_FORMATTED_BUFFER_SIZE:: Buffer size for formatted files
* GFORTRAN_UNFORMATTED_BUFFER_SIZE:: Buffer size for unformatted files
@end menu

@node TMPDIR
@section @env{TMPDIR}---Directory for scratch files

When opening a file with @code{STATUS='SCRATCH'}, GNU Fortran tries to
create the file in one of the potential directories by testing each
directory in the order below.

@enumerate
@item
The environment variable @env{TMPDIR}, if it exists.

@item
On the MinGW target, the directory returned by the @code{GetTempPath}
function. Alternatively, on the Cygwin target, the @env{TMP} and
@env{TEMP} environment variables, if they exist, in that order.

@item
The @code{P_tmpdir} macro if it is defined, otherwise the directory
@file{/tmp}.
@end enumerate

@node GFORTRAN_STDIN_UNIT
@section @env{GFORTRAN_STDIN_UNIT}---Unit number for standard input

This environment variable can be used to select the unit number
preconnected to standard input.  This must be a positive integer.
The default value is 5.

@node GFORTRAN_STDOUT_UNIT
@section @env{GFORTRAN_STDOUT_UNIT}---Unit number for standard output

This environment variable can be used to select the unit number
preconnected to standard output.  This must be a positive integer.
The default value is 6.

@node GFORTRAN_STDERR_UNIT
@section @env{GFORTRAN_STDERR_UNIT}---Unit number for standard error

This environment variable can be used to select the unit number
preconnected to standard error.  This must be a positive integer.
The default value is 0.

@node GFORTRAN_UNBUFFERED_ALL
@section @env{GFORTRAN_UNBUFFERED_ALL}---Do not buffer I/O on all units

This environment variable controls whether all I/O is unbuffered.  If
the first letter is @samp{y}, @samp{Y} or @samp{1}, all I/O is
unbuffered.  This will slow down small sequential reads and writes.  If
the first letter is @samp{n}, @samp{N} or @samp{0}, I/O is buffered.
This is the default.

@node GFORTRAN_UNBUFFERED_PRECONNECTED
@section @env{GFORTRAN_UNBUFFERED_PRECONNECTED}---Do not buffer I/O on preconnected units

The environment variable named @env{GFORTRAN_UNBUFFERED_PRECONNECTED} controls
whether I/O on a preconnected unit (i.e.@: STDOUT or STDERR) is unbuffered.  If
the first letter is @samp{y}, @samp{Y} or @samp{1}, I/O is unbuffered.  This
will slow down small sequential reads and writes.  If the first letter
is @samp{n}, @samp{N} or @samp{0}, I/O is buffered.  This is the default.

@node GFORTRAN_SHOW_LOCUS
@section @env{GFORTRAN_SHOW_LOCUS}---Show location for runtime errors

If the first letter is @samp{y}, @samp{Y} or @samp{1}, filename and
line numbers for runtime errors are printed.  If the first letter is
@samp{n}, @samp{N} or @samp{0}, do not print filename and line numbers
for runtime errors.  The default is to print the location.

@node GFORTRAN_OPTIONAL_PLUS
@section @env{GFORTRAN_OPTIONAL_PLUS}---Print leading + where permitted

If the first letter is @samp{y}, @samp{Y} or @samp{1},
a plus sign is printed
where permitted by the Fortran standard.  If the first letter
is @samp{n}, @samp{N} or @samp{0}, a plus sign is not printed
in most cases.  Default is not to print plus signs.

@node GFORTRAN_LIST_SEPARATOR
@section @env{GFORTRAN_LIST_SEPARATOR}---Separator for list output

This environment variable specifies the separator when writing
list-directed output.  It may contain any number of spaces and
at most one comma.  If you specify this on the command line,
be sure to quote spaces, as in
@smallexample
$ GFORTRAN_LIST_SEPARATOR='  ,  ' ./a.out
@end smallexample
when @command{a.out} is the compiled Fortran program that you want to run.
Default is a single space.

@node GFORTRAN_CONVERT_UNIT
@section @env{GFORTRAN_CONVERT_UNIT}---Set conversion for unformatted I/O

By setting the @env{GFORTRAN_CONVERT_UNIT} variable, it is possible
to change the representation of data for unformatted files.
The syntax for the @env{GFORTRAN_CONVERT_UNIT} variable for
most systems is:
@smallexample
GFORTRAN_CONVERT_UNIT: mode | mode ';' exception | exception ;
mode: 'native' | 'swap' | 'big_endian' | 'little_endian' ;
exception: mode ':' unit_list | unit_list ;
unit_list: unit_spec | unit_list unit_spec ;
unit_spec: INTEGER | INTEGER '-' INTEGER ;
@end smallexample
The variable consists of an optional default mode, followed by
a list of optional exceptions, which are separated by semicolons
from the preceding default and each other.  Each exception consists
of a format and a comma-separated list of units.  Valid values for
the modes are the same as for the @code{CONVERT} specifier:

@itemize @w{}
@item @code{NATIVE} Use the native format.  This is the default.
@item @code{SWAP} Swap between little- and big-endian.
@item @code{LITTLE_ENDIAN} Use the little-endian format
for unformatted files.
@item @code{BIG_ENDIAN} Use the big-endian format for unformatted files.
@end itemize
For POWER systems which support @option{-mabi=ieeelongdouble},
there are additional options, which can be combined with the
others with commas. Those are
@itemize @w{}
@item @code{R16_IEEE} Use IEEE 128-bit format for @code{REAL(KIND=16)}.
@item @code{R16_IBM} Use IBM @code{long double} format for
@code{REAL(KIND=16)}.
@end itemize
A missing mode for an exception is taken to mean @code{BIG_ENDIAN}.
Examples of values for @env{GFORTRAN_CONVERT_UNIT} are:
@itemize @w{}
@item @code{'big_endian'}  Do all unformatted I/O in big_endian mode.
@item @code{'little_endian;native:10-20,25'}  Do all unformatted I/O
in little_endian mode, except for units 10 to 20 and 25, which are in
native format.
@item @code{'10-20'}  Units 10 to 20 are big-endian, the rest is native.
@item @code{'big_endian,r16_ibm'} Do all unformatted I/O in big-endian
mode and use IBM long double for output of @code{REAL(KIND=16)} values.
@end itemize

Setting the environment variables should be done on the command
line or via the @command{export}
command for @command{sh}-compatible shells and via @command{setenv}
for @command{csh}-compatible shells.

Example for @command{sh}:
@smallexample
$ gfortran foo.f90
$ GFORTRAN_CONVERT_UNIT='big_endian;native:10-20' ./a.out
@end smallexample

Example code for @command{csh}:
@smallexample
% gfortran foo.f90
% setenv GFORTRAN_CONVERT_UNIT 'big_endian;native:10-20'
% ./a.out
@end smallexample

Using anything but the native representation for unformatted data
carries a significant speed overhead.  If speed in this area matters
to you, it is best if you use this only for data that needs to be
portable.

@xref{CONVERT specifier}, for an alternative way to specify the
data representation for unformatted files.  @xref{Runtime Options}, for
setting a default data representation for the whole program.  The
@code{CONVERT} specifier overrides the @option{-fconvert} compile options.

@emph{Note that the values specified via the GFORTRAN_CONVERT_UNIT
environment variable will override the CONVERT specifier in the
open statement}.  This is to give control over data formats to
users who do not have the source code of their program available.

@node GFORTRAN_ERROR_BACKTRACE
@section @env{GFORTRAN_ERROR_BACKTRACE}---Show backtrace on run-time errors

If the @env{GFORTRAN_ERROR_BACKTRACE} variable is set to @samp{y},
@samp{Y} or @samp{1} (only the first letter is relevant) then a
backtrace is printed when a serious run-time error occurs.  To disable
the backtracing, set the variable to @samp{n}, @samp{N}, @samp{0}.
Default is to print a backtrace unless the @option{-fno-backtrace}
compile option was used.

@node GFORTRAN_FORMATTED_BUFFER_SIZE
@section @env{GFORTRAN_FORMATTED_BUFFER_SIZE}---Set buffer size for formatted I/O

The @env{GFORTRAN_FORMATTED_BUFFER_SIZE} environment variable
specifies buffer size in bytes to be used for formatted output.
The default value is 8192.

@node GFORTRAN_UNFORMATTED_BUFFER_SIZE
@section @env{GFORTRAN_UNFORMATTED_BUFFER_SIZE}---Set buffer size for unformatted I/O

The @env{GFORTRAN_UNFORMATTED_BUFFER_SIZE} environment variable
specifies buffer size in bytes to be used for unformatted output.
The default value is 131072.

@c =====================================================================
@c PART II: LANGUAGE REFERENCE
@c =====================================================================

@tex
\part{II}{Language Reference}
@end tex



@c ---------------------------------------------------------------------
@c Compiler Characteristics
@c ---------------------------------------------------------------------

@node Compiler Characteristics
@chapter Compiler Characteristics

This chapter describes certain characteristics of the GNU Fortran
compiler, that are not specified by the Fortran standard, but which
might in some way or another become visible to the programmer.

@menu
* KIND Type Parameters::
* Internal representation of LOGICAL variables::
* Evaluation of logical expressions::
* MAX and MIN intrinsics with REAL NaN arguments::
* Thread-safety of the runtime library::
* Data consistency and durability::
* Files opened without an explicit ACTION= specifier::
* File operations on symbolic links::
* File format of unformatted sequential files::
* Asynchronous I/O::
* Behavior on integer overflow::
@end menu


@node KIND Type Parameters
@section KIND Type Parameters
@cindex kind

The @code{KIND} type parameters supported by GNU Fortran for the primitive
data types are:

@table @code

@item INTEGER
1, 2, 4, 8*, 16*, default: 4**

@item LOGICAL
1, 2, 4, 8*, 16*, default: 4**

@item REAL
4, 8, 10*, 16*, default: 4***

@item COMPLEX
4, 8, 10*, 16*, default: 4***

@item DOUBLE PRECISION
4, 8, 10*, 16*, default: 8***

@item CHARACTER
1, 4, default: 1

@end table

@noindent
* not available on all systems @*
** unless @option{-fdefault-integer-8} is used @*
*** unless @option{-fdefault-real-8} is used (see @ref{Fortran Dialect Options})

@noindent
The @code{KIND} value matches the storage size in bytes, except for
@code{COMPLEX} where the storage size is twice as much (or both real and
imaginary part are a real value of the given size).  It is recommended to use
the @ref{SELECTED_CHAR_KIND}, @ref{SELECTED_INT_KIND} and
@ref{SELECTED_REAL_KIND} intrinsics or the @code{INT8}, @code{INT16},
@code{INT32}, @code{INT64}, @code{REAL32}, @code{REAL64}, and @code{REAL128}
parameters of the @code{ISO_FORTRAN_ENV} module instead of the concrete values.
The available kind parameters can be found in the constant arrays
@code{CHARACTER_KINDS}, @code{INTEGER_KINDS}, @code{LOGICAL_KINDS} and
@code{REAL_KINDS} in the @ref{ISO_FORTRAN_ENV} module.  For C interoperability,
the kind parameters of the @ref{ISO_C_BINDING} module should be used.


@node Internal representation of LOGICAL variables
@section Internal representation of LOGICAL variables
@cindex logical, variable representation

The Fortran standard does not specify how variables of @code{LOGICAL}
type are represented, beyond requiring that @code{LOGICAL} variables
of default kind have the same storage size as default @code{INTEGER}
and @code{REAL} variables.  The GNU Fortran internal representation is
as follows.

A @code{LOGICAL(KIND=N)} variable is represented as an
@code{INTEGER(KIND=N)} variable, however, with only two permissible
values: @code{1} for @code{.TRUE.} and @code{0} for
@code{.FALSE.}.  Any other integer value results in undefined behavior.

See also @ref{Argument passing conventions} and @ref{Interoperability with C}.


@node Evaluation of logical expressions
@section Evaluation of logical expressions

The Fortran standard does not require the compiler to evaluate all parts of an
expression, if they do not contribute to the final result.  For logical
expressions with @code{.AND.} or @code{.OR.} operators, in particular, GNU
Fortran will optimize out function calls (even to impure functions) if the
result of the expression can be established without them.  However, since not
all compilers do that, and such an optimization can potentially modify the
program flow and subsequent results, GNU Fortran throws warnings for such
situations with the @option{-Wfunction-elimination} flag.


@node MAX and MIN intrinsics with REAL NaN arguments
@section MAX and MIN intrinsics with REAL NaN arguments
@cindex MAX, MIN, NaN

The Fortran standard does not specify what the result of the
@code{MAX} and @code{MIN} intrinsics are if one of the arguments is a
@code{NaN}.  Accordingly, the GNU Fortran compiler does not specify
that either, as this allows for faster and more compact code to be
generated.  If the programmer wishes to take some specific action in
case one of the arguments is a @code{NaN}, it is necessary to
explicitly test the arguments before calling @code{MAX} or @code{MIN},
e.g. with the @code{IEEE_IS_NAN} function from the intrinsic module
@code{IEEE_ARITHMETIC}.


@node Thread-safety of the runtime library
@section Thread-safety of the runtime library
@cindex thread-safety, threads

GNU Fortran can be used in programs with multiple threads, e.g.@: by
using OpenMP, by calling OS thread handling functions via the
@code{ISO_C_BINDING} facility, or by GNU Fortran compiled library code
being called from a multi-threaded program.

The GNU Fortran runtime library, (@code{libgfortran}), supports being
called concurrently from multiple threads with the following
exceptions.

During library initialization, the C @code{getenv} function is used,
which need not be thread-safe.  Similarly, the @code{getenv}
function is used to implement the @code{GET_ENVIRONMENT_VARIABLE} and
@code{GETENV} intrinsics.  It is the responsibility of the user to
ensure that the environment is not being updated concurrently when any
of these actions are taking place.

The @code{EXECUTE_COMMAND_LINE} and @code{SYSTEM} intrinsics are
implemented with the @code{system} function, which need not be
thread-safe.  It is the responsibility of the user to ensure that
@code{system} is not called concurrently.

For platforms not supporting thread-safe POSIX functions, further
functionality might not be thread-safe.  For details, please consult
the documentation for your operating system.

The GNU Fortran runtime library uses various C library functions that
depend on the locale, such as @code{strtod} and @code{snprintf}.  In
order to work correctly in locale-aware programs that set the locale
using @code{setlocale}, the locale is reset to the default ``C''
locale while executing a formatted @code{READ} or @code{WRITE}
statement.  On targets supporting the POSIX 2008 per-thread locale
functions (e.g. @code{newlocale}, @code{uselocale},
@code{freelocale}), these are used and thus the global locale set
using @code{setlocale} or the per-thread locales in other threads are
not affected.  However, on targets lacking this functionality, the
global LC_NUMERIC locale is set to ``C'' during the formatted I/O.
Thus, on such targets it's not safe to call @code{setlocale}
concurrently from another thread while a Fortran formatted I/O
operation is in progress.  Also, other threads doing something
dependent on the LC_NUMERIC locale might not work correctly if a
formatted I/O operation is in progress in another thread.

@node Data consistency and durability
@section Data consistency and durability
@cindex consistency, durability

This section contains a brief overview of data and metadata
consistency and durability issues when doing I/O.

With respect to durability, GNU Fortran makes no effort to ensure that
data is committed to stable storage. If this is required, the GNU
Fortran programmer can use the intrinsic @code{FNUM} to retrieve the
low level file descriptor corresponding to an open Fortran unit. Then,
using e.g. the @code{ISO_C_BINDING} feature, one can call the
underlying system call to flush dirty data to stable storage, such as
@code{fsync} on POSIX, @code{_commit} on MingW, or @code{fcntl(fd,
F_FULLSYNC, 0)} on macOS. The following example shows how to call
fsync:

@smallexample
  ! Declare the interface for POSIX fsync function
  interface
    function fsync (fd) bind(c,name="fsync")
    use iso_c_binding, only: c_int
      integer(c_int), value :: fd
      integer(c_int) :: fsync
    end function fsync
  end interface

  ! Variable declaration
  integer :: ret

  ! Opening unit 10
  open (10,file="foo")

  ! ...
  ! Perform I/O on unit 10
  ! ...

  ! Flush and sync
  flush(10)
  ret = fsync(fnum(10))

  ! Handle possible error
  if (ret /= 0) stop "Error calling FSYNC"
@end smallexample

With respect to consistency, for regular files GNU Fortran uses
buffered I/O in order to improve performance. This buffer is flushed
automatically when full and in some other situations, e.g. when
closing a unit. It can also be explicitly flushed with the
@code{FLUSH} statement. Also, the buffering can be turned off with the
@code{GFORTRAN_UNBUFFERED_ALL} and
@code{GFORTRAN_UNBUFFERED_PRECONNECTED} environment variables. Special
files, such as terminals and pipes, are always unbuffered. Sometimes,
however, further things may need to be done in order to allow other
processes to see data that GNU Fortran has written, as follows.

The Windows platform supports a relaxed metadata consistency model,
where file metadata is written to the directory lazily. This means
that, for instance, the @code{dir} command can show a stale size for a
file. One can force a directory metadata update by closing the unit,
or by calling @code{_commit} on the file descriptor. Note, though,
that @code{_commit} will force all dirty data to stable storage, which
is often a very slow operation.

The Network File System (NFS) implements a relaxed consistency model
called open-to-close consistency. Closing a file forces dirty data and
metadata to be flushed to the server, and opening a file forces the
client to contact the server in order to revalidate cached
data. @code{fsync} will also force a flush of dirty data and metadata
to the server. Similar to @code{open} and @code{close}, acquiring and
releasing @code{fcntl} file locks, if the server supports them, will
also force cache validation and flushing dirty data and metadata.


@node Files opened without an explicit ACTION= specifier
@section Files opened without an explicit ACTION= specifier
@cindex open, action

The Fortran standard says that if an @code{OPEN} statement is executed
without an explicit @code{ACTION=} specifier, the default value is
processor dependent.  GNU Fortran behaves as follows:

@enumerate
@item Attempt to open the file with @code{ACTION='READWRITE'}
@item If that fails, try to open with @code{ACTION='READ'}
@item If that fails, try to open with @code{ACTION='WRITE'}
@item If that fails, generate an error
@end enumerate


@node File operations on symbolic links
@section File operations on symbolic links
@cindex file, symbolic link

This section documents the behavior of GNU Fortran for file operations on
symbolic links, on systems that support them.

@itemize

@item Results of INQUIRE statements of the ``inquire by file'' form will
relate to the target of the symbolic link. For example,
@code{INQUIRE(FILE="foo",EXIST=ex)} will set @var{ex} to @var{.true.} if
@var{foo} is a symbolic link pointing to an existing file, and @var{.false.}
if @var{foo} points to an non-existing file (``dangling'' symbolic link).

@item Using the @code{OPEN} statement with a @code{STATUS="NEW"} specifier
on a symbolic link will result in an error condition, whether the symbolic
link points to an existing target or is dangling.

@item If a symbolic link was connected, using the @code{CLOSE} statement
with a @code{STATUS="DELETE"} specifier will cause the symbolic link itself
to be deleted, not its target.

@end itemize

@node File format of unformatted sequential files
@section File format of unformatted sequential files
@cindex file, unformatted sequential
@cindex unformatted sequential
@cindex sequential, unformatted
@cindex record marker
@cindex subrecord

Unformatted sequential files are stored as logical records using
record markers.  Each logical record consists of one of more
subrecords.

Each subrecord consists of a leading record marker, the data written
by the user program, and a trailing record marker.  The record markers
are four-byte integers by default, and eight-byte integers if the
@option{-fmax-subrecord-length=8} option (which exists for backwards
compability only) is in effect.

The representation of the record markers is that of unformatted files
given with the @option{-fconvert} option, the @ref{CONVERT specifier}
in an open statement or the @ref{GFORTRAN_CONVERT_UNIT} environment
variable.

The maximum number of bytes of user data in a subrecord is 2147483639
(2 GiB - 9) for a four-byte record marker.  This limit can be lowered
with the @option{-fmax-subrecord-length} option, although this is
rarely useful. If the length of a logical record exceeds this limit,
the data is distributed among several subrecords.

The absolute of the number stored in the record markers is the number
of bytes of user data in the corresponding subrecord.  If the leading
record marker of a subrecord contains a negative number, another
subrecord follows the current one.  If the trailing record marker
contains a negative number, then there is a preceding subrecord.

In the most simple case, with only one subrecord per logical record,
both record markers contain the number of bytes of user data in the
record.

The format for unformatted sequential data can be duplicated using
unformatted stream, as shown in the example program for an unformatted
record containing a single subrecord:

@smallexample
program main
  use iso_fortran_env, only: int32
  implicit none
  integer(int32) :: i
  real, dimension(10) :: a, b
  call random_number(a)
  open (10,file='test.dat',form='unformatted',access='stream')
  inquire (iolength=i) a
  write (10) i, a, i
  close (10)
  open (10,file='test.dat',form='unformatted')
  read (10) b
  if (all (a == b)) print *,'success!'
end program main
@end smallexample

@node Asynchronous I/O
@section Asynchronous I/O
@cindex input/output, asynchronous
@cindex asynchronous I/O

Asynchronous I/O is supported if the program is linked against the
POSIX thread library. If that is not the case, all I/O is performed
as synchronous. On systems which do not support pthread condition
variables, such as AIX, I/O is also performed as synchronous.

On some systems, such as Darwin or Solaris, the POSIX thread library
is always linked in, so asynchronous I/O is always performed. On other
sytems, such as Linux, it is necessary to specify @option{-pthread},
@option{-lpthread} or @option{-fopenmp} during the linking step.

@c ---------------------------------------------------------------------
@c Extensions
@c ---------------------------------------------------------------------

@c Maybe this chapter should be merged with the 'Standards' section,
@c whenever that is written :-)

@node Behavior on integer overflow
@section Behavior on integer overflow
@cindex integer overflow
@cindex overflow handling

Integer overflow is prohibited by the Fortran standard.  The behavior
of gfortran on integer overflow is undefined by default.  Traditional
code, like linear congruential pseudo-random number generators in old
programs that rely on specific, non-standard behavior may generate
unexpected results.  The @option{-fsanitize=undefined} option can be
used to detect such code at runtime.

It is recommended to use the intrinsic subroutine @code{RANDOM_NUMBER}
for random number generators or, if the old behavior is desired, to
use the @option{-fwrapv} option.  Note that this option can impact
performance.

@node Extensions
@chapter Extensions
@cindex extensions

The two sections below detail the extensions to standard Fortran that are
implemented in GNU Fortran, as well as some of the popular or
historically important extensions that are not (or not yet) implemented.
For the latter case, we explain the alternatives available to GNU Fortran
users, including replacement by standard-conforming code or GNU
extensions.

@menu
* Extensions implemented in GNU Fortran::
* Extensions not implemented in GNU Fortran::
@end menu


@node Extensions implemented in GNU Fortran
@section Extensions implemented in GNU Fortran
@cindex extensions, implemented

GNU Fortran implements a number of extensions over standard Fortran.
This chapter contains information on their syntax and meaning.  There
are currently two categories of GNU Fortran extensions, those that
provide functionality beyond that provided by any standard, and those
that are supported by GNU Fortran purely for backward compatibility
with legacy compilers.  By default, @option{-std=gnu} allows the
compiler to accept both types of extensions, but to warn about the use
of the latter.  Specifying either @option{-std=f95},
@option{-std=f2003}, @option{-std=f2008}, or @option{-std=f2018}
disables both types of extensions, and @option{-std=legacy} allows
both without warning.  The special compile flag @option{-fdec} enables
additional compatibility extensions along with those enabled by
@option{-std=legacy}.

@menu
* Old-style kind specifications::
* Old-style variable initialization::
* Extensions to namelist::
* X format descriptor without count field::
* Commas in FORMAT specifications::
* Missing period in FORMAT specifications::
* Default widths for F@comma{} G and I format descriptors::
* I/O item lists::
* @code{Q} exponent-letter::
* BOZ literal constants::
* Real array indices::
* Unary operators::
* Implicitly convert LOGICAL and INTEGER values::
* Hollerith constants support::
* Character conversion::
* Cray pointers::
* CONVERT specifier::
* OpenMP::
* OpenACC::
* Argument list functions::
* Read/Write after EOF marker::
* STRUCTURE and RECORD::
* UNION and MAP::
* Type variants for integer intrinsics::
* AUTOMATIC and STATIC attributes::
* Extended math intrinsics::
* Form feed as whitespace::
* TYPE as an alias for PRINT::
* %LOC as an rvalue::
* .XOR. operator::
* Bitwise logical operators::
* Extended I/O specifiers::
* Legacy PARAMETER statements::
* Default exponents::
@end menu

@node Old-style kind specifications
@subsection Old-style kind specifications
@cindex kind, old-style

GNU Fortran allows old-style kind specifications in declarations.  These
look like:
@smallexample
      TYPESPEC*size x,y,z
@end smallexample
@noindent
where @code{TYPESPEC} is a basic type (@code{INTEGER}, @code{REAL},
etc.), and where @code{size} is a byte count corresponding to the
storage size of a valid kind for that type.  (For @code{COMPLEX}
variables, @code{size} is the total size of the real and imaginary
parts.)  The statement then declares @code{x}, @code{y} and @code{z} to
be of type @code{TYPESPEC} with the appropriate kind.  This is
equivalent to the standard-conforming declaration
@smallexample
      TYPESPEC(k) x,y,z
@end smallexample
@noindent
where @code{k} is the kind parameter suitable for the intended precision.  As
kind parameters are implementation-dependent, use the @code{KIND},
@code{SELECTED_INT_KIND} and @code{SELECTED_REAL_KIND} intrinsics to retrieve
the correct value, for instance @code{REAL*8 x} can be replaced by:
@smallexample
INTEGER, PARAMETER :: dbl = KIND(1.0d0)
REAL(KIND=dbl) :: x
@end smallexample

@node Old-style variable initialization
@subsection Old-style variable initialization

GNU Fortran allows old-style initialization of variables of the
form:
@smallexample
      INTEGER i/1/,j/2/
      REAL x(2,2) /3*0.,1./
@end smallexample
The syntax for the initializers is as for the @code{DATA} statement, but
unlike in a @code{DATA} statement, an initializer only applies to the
variable immediately preceding the initialization.  In other words,
something like @code{INTEGER I,J/2,3/} is not valid.  This style of
initialization is only allowed in declarations without double colons
(@code{::}); the double colons were introduced in Fortran 90, which also
introduced a standard syntax for initializing variables in type
declarations.

Examples of standard-conforming code equivalent to the above example
are:
@smallexample
! Fortran 90
      INTEGER :: i = 1, j = 2
      REAL :: x(2,2) = RESHAPE((/0.,0.,0.,1./),SHAPE(x))
! Fortran 77
      INTEGER i, j
      REAL x(2,2)
      DATA i/1/, j/2/, x/3*0.,1./
@end smallexample

Note that variables which are explicitly initialized in declarations
or in @code{DATA} statements automatically acquire the @code{SAVE}
attribute.

@node Extensions to namelist
@subsection Extensions to namelist
@cindex Namelist

GNU Fortran fully supports the Fortran 95 standard for namelist I/O
including array qualifiers, substrings and fully qualified derived types.
The output from a namelist write is compatible with namelist read.  The
output has all names in upper case and indentation to column 1 after the
namelist name.  Two extensions are permitted:

Old-style use of @samp{$} instead of @samp{&}
@smallexample
$MYNML
 X(:)%Y(2) = 1.0 2.0 3.0
 CH(1:4) = "abcd"
$END
@end smallexample

It should be noted that the default terminator is @samp{/} rather than
@samp{&END}.

Querying of the namelist when inputting from stdin.  After at least
one space, entering @samp{?} sends to stdout the namelist name and the names of
the variables in the namelist:
@smallexample
 ?

&mynml
 x
 x%y
 ch
&end
@end smallexample

Entering @samp{=?} outputs the namelist to stdout, as if
@code{WRITE(*,NML = mynml)} had been called:
@smallexample
=?

&MYNML
 X(1)%Y=  0.000000    ,  1.000000    ,  0.000000    ,
 X(2)%Y=  0.000000    ,  2.000000    ,  0.000000    ,
 X(3)%Y=  0.000000    ,  3.000000    ,  0.000000    ,
 CH=abcd,  /
@end smallexample

To aid this dialog, when input is from stdin, errors send their
messages to stderr and execution continues, even if @code{IOSTAT} is set.

@code{PRINT} namelist is permitted.  This causes an error if
@option{-std=f95} is used.
@smallexample
PROGRAM test_print
  REAL, dimension (4)  ::  x = (/1.0, 2.0, 3.0, 4.0/)
  NAMELIST /mynml/ x
  PRINT mynml
END PROGRAM test_print
@end smallexample

Expanded namelist reads are permitted.  This causes an error if
@option{-std=f95} is used.  In the following example, the first element
of the array will be given the value 0.00 and the two succeeding
elements will be given the values 1.00 and 2.00.
@smallexample
&MYNML
  X(1,1) = 0.00 , 1.00 , 2.00
/
@end smallexample

When writing a namelist, if no @code{DELIM=} is specified, by default a
double quote is used to delimit character strings. If -std=F95, F2003,
or F2008, etc, the delim status is set to 'none'.  Defaulting to
quotes ensures that namelists with character strings can be subsequently
read back in accurately.

@node X format descriptor without count field
@subsection @code{X} format descriptor without count field

To support legacy codes, GNU Fortran permits the count field of the
@code{X} edit descriptor in @code{FORMAT} statements to be omitted.
When omitted, the count is implicitly assumed to be one.

@smallexample
       PRINT 10, 2, 3
10     FORMAT (I1, X, I1)
@end smallexample

@node Commas in FORMAT specifications
@subsection Commas in @code{FORMAT} specifications

To support legacy codes, GNU Fortran allows the comma separator
to be omitted immediately before and after character string edit
descriptors in @code{FORMAT} statements.  A comma with no following format
descriptor is permitted if the @option{-fdec-blank-format-item} is given on
the command line. This is considered non-conforming code and is
discouraged.

@smallexample
       PRINT 10, 2, 3
10     FORMAT ('FOO='I1' BAR='I2)
       print 20, 5, 6
20     FORMAT (I3, I3,)
@end smallexample


@node Missing period in FORMAT specifications
@subsection Missing period in @code{FORMAT} specifications

To support legacy codes, GNU Fortran allows missing periods in format
specifications if and only if @option{-std=legacy} is given on the
command line.  This is considered non-conforming code and is
discouraged.

@smallexample
       REAL :: value
       READ(*,10) value
10     FORMAT ('F4')
@end smallexample

@node Default widths for F@comma{} G and I format descriptors
@subsection Default widths for @code{F}, @code{G} and @code{I} format descriptors

To support legacy codes, GNU Fortran allows width to be omitted from format
specifications if and only if @option{-fdec-format-defaults} is given on the
command line.  Default widths will be used. This is considered non-conforming
code and is discouraged.

@smallexample
       REAL :: value1
       INTEGER :: value2
       WRITE(*,10) value1, value1, value2
10     FORMAT ('F, G, I')
@end smallexample


@node I/O item lists
@subsection I/O item lists
@cindex I/O item lists

To support legacy codes, GNU Fortran allows the input item list
of the @code{READ} statement, and the output item lists of the
@code{WRITE} and @code{PRINT} statements, to start with a comma.

@node @code{Q} exponent-letter
@subsection @code{Q} exponent-letter
@cindex @code{Q} exponent-letter

GNU Fortran accepts real literal constants with an exponent-letter
of @code{Q}, for example, @code{1.23Q45}.  The constant is interpreted
as a @code{REAL(16)} entity on targets that support this type.  If
the target does not support @code{REAL(16)} but has a @code{REAL(10)}
type, then the real-literal-constant will be interpreted as a
@code{REAL(10)} entity.  In the absence of @code{REAL(16)} and
@code{REAL(10)}, an error will occur.

@node BOZ literal constants
@subsection BOZ literal constants
@cindex BOZ literal constants

Besides decimal constants, Fortran also supports binary (@code{b}),
octal (@code{o}) and hexadecimal (@code{z}) integer constants.  The
syntax is: @samp{prefix quote digits quote}, where the prefix is
either @code{b}, @code{o} or @code{z}, quote is either @code{'} or
@code{"} and the digits are @code{0} or @code{1} for binary,
between @code{0} and @code{7} for octal, and between @code{0} and
@code{F} for hexadecimal.  (Example: @code{b'01011101'}.)

Up to Fortran 95, BOZ literal constants were only allowed to initialize
integer variables in DATA statements.  Since Fortran 2003 BOZ literal
constants are also allowed as actual arguments to the @code{REAL},
@code{DBLE}, @code{INT} and @code{CMPLX} intrinsic functions.
The BOZ literal constant is simply a string of bits, which is padded
or truncated as needed, during conversion to a numeric type.  The 
Fortran standard states that the treatment of the sign bit is processor
dependent.  Gfortran interprets the sign bit as a user would expect.

As a deprecated extension, GNU Fortran allows hexadecimal BOZ literal
constants to be specified using the @code{X} prefix.  That the BOZ literal
constant can also be specified by adding a suffix to the string, for
example, @code{Z'ABC'} and @code{'ABC'X} are equivalent.  Additionally,
as extension, BOZ literals are permitted in some contexts outside of
@code{DATA} and the intrinsic functions listed in the Fortran standard.
Use @option{-fallow-invalid-boz} to enable the extension.

@node Real array indices
@subsection Real array indices
@cindex array, indices of type real

As an extension, GNU Fortran allows the use of @code{REAL} expressions
or variables as array indices.

@node Unary operators
@subsection Unary operators
@cindex operators, unary

As an extension, GNU Fortran allows unary plus and unary minus operators
to appear as the second operand of binary arithmetic operators without
the need for parenthesis.

@smallexample
       X = Y * -Z
@end smallexample

@node Implicitly convert LOGICAL and INTEGER values
@subsection Implicitly convert @code{LOGICAL} and @code{INTEGER} values
@cindex conversion, to integer
@cindex conversion, to logical

As an extension for backwards compatibility with other compilers, GNU
Fortran allows the implicit conversion of @code{LOGICAL} values to
@code{INTEGER} values and vice versa.  When converting from a
@code{LOGICAL} to an @code{INTEGER}, @code{.FALSE.} is interpreted as
zero, and @code{.TRUE.} is interpreted as one.  When converting from
@code{INTEGER} to @code{LOGICAL}, the value zero is interpreted as
@code{.FALSE.} and any nonzero value is interpreted as @code{.TRUE.}.

@smallexample
        LOGICAL :: l
        l = 1
@end smallexample
@smallexample
        INTEGER :: i
        i = .TRUE.
@end smallexample

However, there is no implicit conversion of @code{INTEGER} values in
@code{if}-statements, nor of @code{LOGICAL} or @code{INTEGER} values
in I/O operations.

@node Hollerith constants support
@subsection Hollerith constants support
@cindex Hollerith constants

GNU Fortran supports Hollerith constants in assignments, @code{DATA}
statements, function and subroutine arguments. A Hollerith constant is
written as a string of characters preceded by an integer constant 
indicating the character count, and the letter @code{H} or
@code{h}, and stored in bytewise fashion in a numeric (@code{INTEGER},
@code{REAL}, or @code{COMPLEX}), @code{LOGICAL} or @code{CHARACTER} variable.
The constant will be padded with spaces or truncated to fit the size of
the variable in which it is stored.

Examples of valid uses of Hollerith constants:
@smallexample
      complex*16 x(2)
      data x /16Habcdefghijklmnop, 16Hqrstuvwxyz012345/
      x(1) = 16HABCDEFGHIJKLMNOP
      call foo (4h abc)
@end smallexample

Examples of Hollerith constants:
@smallexample
      integer*4 a
      a = 0H         ! Invalid, at least one character is needed.
      a = 4HAB12     ! Valid
      a = 8H12345678 ! Valid, but the Hollerith constant will be truncated.
      a = 3Hxyz      ! Valid, but the Hollerith constant will be padded.
@end smallexample

In general, Hollerith constants were used to provide a rudimentary
facility for handling character strings in early Fortran compilers,
prior to the introduction of @code{CHARACTER} variables in Fortran 77;
in those cases, the standard-compliant equivalent is to convert the
program to use proper character strings.  On occasion, there may be a
case where the intent is specifically to initialize a numeric variable
with a given byte sequence.  In these cases, the same result can be
obtained by using the @code{TRANSFER} statement, as in this example.
@smallexample
      integer(kind=4) :: a
      a = transfer ("abcd", a)     ! equivalent to: a = 4Habcd
@end smallexample

The use of the @option{-fdec} option extends support of Hollerith constants
to comparisons:
@smallexample
      integer*4 a
      a = 4hABCD
      if (a .ne. 4habcd) then
        write(*,*) "no match"
      end if
@end smallexample

Supported types are numeric (@code{INTEGER}, @code{REAL}, or @code{COMPLEX}),
and @code{CHARACTER}.

@node Character conversion
@subsection Character conversion
@cindex conversion, to character

Allowing character literals to be used in a similar way to Hollerith constants
is a non-standard extension.  This feature is enabled using
-fdec-char-conversions and only applies to character literals of @code{kind=1}.

Character literals can be used in @code{DATA} statements and assignments with
numeric (@code{INTEGER}, @code{REAL}, or @code{COMPLEX}) or @code{LOGICAL}
variables. Like Hollerith constants they are copied byte-wise fashion. The
constant will be padded with spaces or truncated to fit the size of the
variable in which it is stored.

Examples:
@smallexample
      integer*4 x
      data x / 'abcd' /

      x = 'A'       ! Will be padded.
      x = 'ab1234'  ! Will be truncated.
@end smallexample


@node Cray pointers
@subsection Cray pointers
@cindex pointer, Cray

Cray pointers are part of a non-standard extension that provides a
C-like pointer in Fortran.  This is accomplished through a pair of
variables: an integer "pointer" that holds a memory address, and a
"pointee" that is used to dereference the pointer.

Pointer/pointee pairs are declared in statements of the form:
@smallexample
        pointer ( <pointer> , <pointee> )
@end smallexample
or,
@smallexample
        pointer ( <pointer1> , <pointee1> ), ( <pointer2> , <pointee2> ), ...
@end smallexample
The pointer is an integer that is intended to hold a memory address.
The pointee may be an array or scalar.
If an assumed-size array is permitted within the scoping unit, a
pointee can be an assumed-size array.
That is, the last dimension may be left unspecified by using a @code{*}
in place of a value. A pointee cannot be an assumed shape array.
No space is allocated for the pointee.

The pointee may have its type declared before or after the pointer
statement, and its array specification (if any) may be declared
before, during, or after the pointer statement.  The pointer may be
declared as an integer prior to the pointer statement.  However, some
machines have default integer sizes that are different than the size
of a pointer, and so the following code is not portable:
@smallexample
        integer ipt
        pointer (ipt, iarr)
@end smallexample
If a pointer is declared with a kind that is too small, the compiler
will issue a warning; the resulting binary will probably not work
correctly, because the memory addresses stored in the pointers may be
truncated.  It is safer to omit the first line of the above example;
if explicit declaration of ipt's type is omitted, then the compiler
will ensure that ipt is an integer variable large enough to hold a
pointer.

Pointer arithmetic is valid with Cray pointers, but it is not the same
as C pointer arithmetic.  Cray pointers are just ordinary integers, so
the user is responsible for determining how many bytes to add to a
pointer in order to increment it.  Consider the following example:
@smallexample
        real target(10)
        real pointee(10)
        pointer (ipt, pointee)
        ipt = loc (target)
        ipt = ipt + 1
@end smallexample
The last statement does not set @code{ipt} to the address of
@code{target(1)}, as it would in C pointer arithmetic.  Adding @code{1}
to @code{ipt} just adds one byte to the address stored in @code{ipt}.

Any expression involving the pointee will be translated to use the
value stored in the pointer as the base address.

To get the address of elements, this extension provides an intrinsic
function @code{LOC()}.  The @code{LOC()} function is equivalent to the
@code{&} operator in C, except the address is cast to an integer type:
@smallexample
        real ar(10)
        pointer(ipt, arpte(10))
        real arpte
        ipt = loc(ar)  ! Makes arpte is an alias for ar
        arpte(1) = 1.0 ! Sets ar(1) to 1.0
@end smallexample
The pointer can also be set by a call to the @code{MALLOC} intrinsic
(see @ref{MALLOC}).

Cray pointees often are used to alias an existing variable.  For
example:
@smallexample
        integer target(10)
        integer iarr(10)
        pointer (ipt, iarr)
        ipt = loc(target)
@end smallexample
As long as @code{ipt} remains unchanged, @code{iarr} is now an alias for
@code{target}.  The optimizer, however, will not detect this aliasing, so
it is unsafe to use @code{iarr} and @code{target} simultaneously.  Using
a pointee in any way that violates the Fortran aliasing rules or
assumptions is illegal.  It is the user's responsibility to avoid doing
this; the compiler works under the assumption that no such aliasing
occurs.

Cray pointers will work correctly when there is no aliasing (i.e., when
they are used to access a dynamically allocated block of memory), and
also in any routine where a pointee is used, but any variable with which
it shares storage is not used.  Code that violates these rules may not
run as the user intends.  This is not a bug in the optimizer; any code
that violates the aliasing rules is illegal.  (Note that this is not
unique to GNU Fortran; any Fortran compiler that supports Cray pointers
will ``incorrectly'' optimize code with illegal aliasing.)

There are a number of restrictions on the attributes that can be applied
to Cray pointers and pointees.  Pointees may not have the
@code{ALLOCATABLE}, @code{INTENT}, @code{OPTIONAL}, @code{DUMMY},
@code{TARGET}, @code{INTRINSIC}, or @code{POINTER} attributes.  Pointers
may not have the @code{DIMENSION}, @code{POINTER}, @code{TARGET},
@code{ALLOCATABLE}, @code{EXTERNAL}, or @code{INTRINSIC} attributes, nor
may they be function results.  Pointees may not occur in more than one
pointer statement.  A pointee cannot be a pointer.  Pointees cannot occur
in equivalence, common, or data statements.

A Cray pointer may also point to a function or a subroutine.  For
example, the following excerpt is valid:
@smallexample
  implicit none
  external sub
  pointer (subptr,subpte)
  external subpte
  subptr = loc(sub)
  call subpte()
  [...]
  subroutine sub
  [...]
  end subroutine sub
@end smallexample

A pointer may be modified during the course of a program, and this
will change the location to which the pointee refers.  However, when
pointees are passed as arguments, they are treated as ordinary
variables in the invoked function.  Subsequent changes to the pointer
will not change the base address of the array that was passed.

@node CONVERT specifier
@subsection @code{CONVERT} specifier
@cindex @code{CONVERT} specifier

GNU Fortran allows the conversion of unformatted data between little-
and big-endian representation to facilitate moving of data
between different systems.  The conversion can be indicated with
the @code{CONVERT} specifier on the @code{OPEN} statement.
@xref{GFORTRAN_CONVERT_UNIT}, for an alternative way of specifying
the data format via an environment variable.

Valid values for @code{CONVERT} on most systems are:
@itemize @w{}
@item @code{CONVERT='NATIVE'} Use the native format.  This is the default.
@item @code{CONVERT='SWAP'} Swap between little- and big-endian.
@item @code{CONVERT='LITTLE_ENDIAN'} Use the little-endian representation
for unformatted files.
@item @code{CONVERT='BIG_ENDIAN'} Use the big-endian representation for
unformatted files.
@end itemize
On POWER systems which support @option{-mabi=ieeelongdouble},
there are additional options, which can be combined with the others
with commas. Those are
@itemize @w{}
@item @code{CONVERT='R16_IEEE'} Use IEEE 128-bit format for
@code{REAL(KIND=16)}.
@item @code{CONVERT='R16_IBM'} Use IBM @code{long double} format for
real@code{REAL(KIND=16)}.
@end itemize

Using the option could look like this:
@smallexample
  open(file='big.dat',form='unformatted',access='sequential', &
       convert='big_endian')
@end smallexample

The value of the conversion can be queried by using
@code{INQUIRE(CONVERT=ch)}.  The values returned are
@code{'BIG_ENDIAN'} and @code{'LITTLE_ENDIAN'}.

@code{CONVERT} works between big- and little-endian for
@code{INTEGER} values of all supported kinds and for @code{REAL}
on IEEE systems of kinds 4 and 8.  Conversion between different
``extended double'' types on different architectures such as
m68k and x86_64, which GNU Fortran
supports as @code{REAL(KIND=10)} and @code{REAL(KIND=16)}, will
probably not work.

@emph{Note that the values specified via the GFORTRAN_CONVERT_UNIT
environment variable will override the CONVERT specifier in the
open statement}.  This is to give control over data formats to
users who do not have the source code of their program available.

Using anything but the native representation for unformatted data
carries a significant speed overhead.  If speed in this area matters
to you, it is best if you use this only for data that needs to be
portable.

@node OpenMP
@subsection OpenMP
@cindex OpenMP

OpenMP (Open Multi-Processing) is an application programming
interface (API) that supports multi-platform shared memory
multiprocessing programming in C/C++ and Fortran on many
architectures, including Unix and Microsoft Windows platforms.
It consists of a set of compiler directives, library routines,
and environment variables that influence run-time behavior.

GNU Fortran strives to be compatible to the
@uref{https://openmp.org/specifications/,
OpenMP Application Program Interface v4.5}.

To enable the processing of the OpenMP directive @code{!$omp} in
free-form source code; the @code{c$omp}, @code{*$omp} and @code{!$omp}
directives in fixed form; the @code{!$} conditional compilation sentinels
in free form; and the @code{c$}, @code{*$} and @code{!$} sentinels
in fixed form, @command{gfortran} needs to be invoked with the
@option{-fopenmp}.  This also arranges for automatic linking of the
GNU Offloading and Multi Processing Runtime Library
@ref{Top,,libgomp,libgomp,GNU Offloading and Multi Processing Runtime
Library}.

The OpenMP Fortran runtime library routines are provided both in a
form of a Fortran 90 module named @code{omp_lib} and in a form of
a Fortran @code{include} file named @file{omp_lib.h}.

An example of a parallelized loop taken from Appendix A.1 of
the OpenMP Application Program Interface v2.5:
@smallexample
SUBROUTINE A1(N, A, B)
  INTEGER I, N
  REAL B(N), A(N)
!$OMP PARALLEL DO !I is private by default
  DO I=2,N
    B(I) = (A(I) + A(I-1)) / 2.0
  ENDDO
!$OMP END PARALLEL DO
END SUBROUTINE A1
@end smallexample

Please note:
@itemize
@item
@option{-fopenmp} implies @option{-frecursive}, i.e., all local arrays
will be allocated on the stack.  When porting existing code to OpenMP,
this may lead to surprising results, especially to segmentation faults
if the stacksize is limited.

@item
On glibc-based systems, OpenMP enabled applications cannot be statically
linked due to limitations of the underlying pthreads-implementation.  It
might be possible to get a working solution if
@command{-Wl,--whole-archive -lpthread -Wl,--no-whole-archive} is added
to the command line.  However, this is not supported by @command{gcc} and
thus not recommended.
@end itemize

@node OpenACC
@subsection OpenACC
@cindex OpenACC

OpenACC is an application programming interface (API) that supports
offloading of code to accelerator devices.  It consists of a set of
compiler directives, library routines, and environment variables that
influence run-time behavior.

GNU Fortran strives to be compatible to the
@uref{https://www.openacc.org/, OpenACC Application Programming
Interface v2.6}.

To enable the processing of the OpenACC directive @code{!$acc} in
free-form source code; the @code{c$acc}, @code{*$acc} and @code{!$acc}
directives in fixed form; the @code{!$} conditional compilation
sentinels in free form; and the @code{c$}, @code{*$} and @code{!$}
sentinels in fixed form, @command{gfortran} needs to be invoked with
the @option{-fopenacc}.  This also arranges for automatic linking of
the GNU Offloading and Multi Processing Runtime Library
@ref{Top,,libgomp,libgomp,GNU Offloading and Multi Processing Runtime
Library}.

The OpenACC Fortran runtime library routines are provided both in a
form of a Fortran 90 module named @code{openacc} and in a form of a
Fortran @code{include} file named @file{openacc_lib.h}.

@node Argument list functions
@subsection Argument list functions @code{%VAL}, @code{%REF} and @code{%LOC}
@cindex argument list functions
@cindex @code{%VAL}
@cindex @code{%REF}
@cindex @code{%LOC}

GNU Fortran supports argument list functions @code{%VAL}, @code{%REF}
and @code{%LOC} statements, for backward compatibility with g77.
It is recommended that these should be used only for code that is
accessing facilities outside of GNU Fortran, such as operating system
or windowing facilities.  It is best to constrain such uses to isolated
portions of a program--portions that deal specifically and exclusively
with low-level, system-dependent facilities.  Such portions might well
provide a portable interface for use by the program as a whole, but are
themselves not portable, and should be thoroughly tested each time they
are rebuilt using a new compiler or version of a compiler.

@code{%VAL} passes a scalar argument by value, @code{%REF} passes it by
reference and @code{%LOC} passes its memory location.  Since gfortran
already passes scalar arguments by reference, @code{%REF} is in effect
a do-nothing.  @code{%LOC} has the same effect as a Fortran pointer.

An example of passing an argument by value to a C subroutine foo.:
@smallexample
C
C prototype      void foo_ (float x);
C
      external foo
      real*4 x
      x = 3.14159
      call foo (%VAL (x))
      end
@end smallexample

For details refer to the g77 manual
@uref{https://gcc.gnu.org/@/onlinedocs/@/gcc-3.4.6/@/g77/@/index.html#Top}.

Also, @code{c_by_val.f} and its partner @code{c_by_val.c} of the
GNU Fortran testsuite are worth a look.

@node Read/Write after EOF marker
@subsection Read/Write after EOF marker
@cindex @code{EOF}
@cindex @code{BACKSPACE}
@cindex @code{REWIND}

Some legacy codes rely on allowing @code{READ} or @code{WRITE} after the
EOF file marker in order to find the end of a file. GNU Fortran normally
rejects these codes with a run-time error message and suggests the user
consider @code{BACKSPACE} or @code{REWIND} to properly position
the file before the EOF marker.  As an extension, the run-time error may
be disabled using -std=legacy.


@node STRUCTURE and RECORD
@subsection @code{STRUCTURE} and @code{RECORD}
@cindex @code{STRUCTURE}
@cindex @code{RECORD}

Record structures are a pre-Fortran-90 vendor extension to create
user-defined aggregate data types.  Support for record structures in GNU
Fortran can be enabled with the @option{-fdec-structure} compile flag.
If you have a choice, you should instead use Fortran 90's ``derived types'',
which have a different syntax.

In many cases, record structures can easily be converted to derived types.
To convert, replace @code{STRUCTURE /}@var{structure-name}@code{/}
by @code{TYPE} @var{type-name}.  Additionally, replace
@code{RECORD /}@var{structure-name}@code{/} by
@code{TYPE(}@var{type-name}@code{)}. Finally, in the component access,
replace the period (@code{.}) by the percent sign (@code{%}).

Here is an example of code using the non portable record structure syntax:

@example
! Declaring a structure named ``item'' and containing three fields:
! an integer ID, an description string and a floating-point price.
STRUCTURE /item/
  INTEGER id
  CHARACTER(LEN=200) description
  REAL price
END STRUCTURE

! Define two variables, an single record of type ``item''
! named ``pear'', and an array of items named ``store_catalog''
RECORD /item/ pear, store_catalog(100)

! We can directly access the fields of both variables
pear.id = 92316
pear.description = "juicy D'Anjou pear"
pear.price = 0.15
store_catalog(7).id = 7831
store_catalog(7).description = "milk bottle"
store_catalog(7).price = 1.2

! We can also manipulate the whole structure
store_catalog(12) = pear
print *, store_catalog(12)
@end example

@noindent
This code can easily be rewritten in the Fortran 90 syntax as following:

@example
! ``STRUCTURE /name/ ... END STRUCTURE'' becomes
! ``TYPE name ... END TYPE''
TYPE item
  INTEGER id
  CHARACTER(LEN=200) description
  REAL price
END TYPE

! ``RECORD /name/ variable'' becomes ``TYPE(name) variable''
TYPE(item) pear, store_catalog(100)

! Instead of using a dot (.) to access fields of a record, the
! standard syntax uses a percent sign (%)
pear%id = 92316
pear%description = "juicy D'Anjou pear"
pear%price = 0.15
store_catalog(7)%id = 7831
store_catalog(7)%description = "milk bottle"
store_catalog(7)%price = 1.2

! Assignments of a whole variable do not change
store_catalog(12) = pear
print *, store_catalog(12)
@end example

@noindent
GNU Fortran implements STRUCTURES like derived types with the following
rules and exceptions:

@itemize @bullet
@item Structures act like derived types with the @code{SEQUENCE} attribute.
Otherwise they may contain no specifiers.

@item Structures may contain a special field with the name @code{%FILL}.
This will create an anonymous component which cannot be accessed but occupies
space just as if a component of the same type was declared in its place, useful
for alignment purposes.  As an example, the following structure will consist
of at least sixteen bytes:

@smallexample
structure /padded/
  character(4) start
  character(8) %FILL
  character(4) end
end structure
@end smallexample

@item Structures may share names with other symbols. For example, the following
is invalid for derived types, but valid for structures:

@smallexample
structure /header/
  ! ...
end structure
record /header/ header
@end smallexample

@item Structure types may be declared nested within another parent structure.
The syntax is:
@smallexample
structure /type-name/
    ...
    structure [/<type-name>/] <field-list>
...
@end smallexample

The type name may be ommitted, in which case the structure type itself is
anonymous, and other structures of the same type cannot be instantiated. The
following shows some examples:

@example
structure /appointment/
  ! nested structure definition: app_time is an array of two 'time'
  structure /time/ app_time (2)
    integer(1) hour, minute
  end structure
  character(10) memo
end structure

! The 'time' structure is still usable
record /time/ now
now = time(5, 30)

...

structure /appointment/
  ! anonymous nested structure definition
  structure start, end
    integer(1) hour, minute
  end structure
  character(10) memo
end structure
@end example

@item Structures may contain @code{UNION} blocks. For more detail see the
section on @ref{UNION and MAP}.

@item Structures support old-style initialization of components, like
those described in @ref{Old-style variable initialization}. For array
initializers, an initializer may contain a repeat specification of the form
@code{<literal-integer> * <constant-initializer>}. The value of the integer
indicates the number of times to repeat the constant initializer when expanding
the initializer list.
@end itemize

@node UNION and MAP
@subsection @code{UNION} and @code{MAP}
@cindex @code{UNION}
@cindex @code{MAP}

Unions are an old vendor extension which were commonly used with the
non-standard @ref{STRUCTURE and RECORD} extensions. Use of @code{UNION} and
@code{MAP} is automatically enabled with @option{-fdec-structure}.

A @code{UNION} declaration occurs within a structure; within the definition of
each union is a number of @code{MAP} blocks. Each @code{MAP} shares storage
with its sibling maps (in the same union), and the size of the union is the
size of the largest map within it, just as with unions in C. The major
difference is that component references do not indicate which union or map the
component is in (the compiler gets to figure that out).

Here is a small example:
@smallexample
structure /myunion/
union
  map
    character(2) w0, w1, w2
  end map
  map
    character(6) long
  end map
end union
end structure

record /myunion/ rec
! After this assignment...
rec.long = 'hello!'

! The following is true:
! rec.w0 === 'he'
! rec.w1 === 'll'
! rec.w2 === 'o!'
@end smallexample

The two maps share memory, and the size of the union is ultimately six bytes:

@example
0    1    2    3    4   5   6     Byte offset
-------------------------------
|    |    |    |    |    |    |
-------------------------------

^    W0   ^    W1   ^    W2   ^
 \-------/ \-------/ \-------/

^             LONG            ^
 \---------------------------/
@end example

Following is an example mirroring the layout of an Intel x86_64 register:

@example
structure /reg/
  union ! U0                ! rax
    map
      character(16) rx
    end map
    map
      character(8) rh         ! rah
      union ! U1
        map
          character(8) rl     ! ral
        end map
        map
          character(8) ex     ! eax
        end map
        map
          character(4) eh     ! eah
          union ! U2
            map
              character(4) el ! eal
            end map
            map
              character(4) x  ! ax
            end map
            map
              character(2) h  ! ah
              character(2) l  ! al
            end map
          end union
        end map
      end union
    end map
  end union
end structure
record /reg/ a

! After this assignment...
a.rx     =     'AAAAAAAA.BBB.C.D'

! The following is true:
a.rx === 'AAAAAAAA.BBB.C.D'
a.rh === 'AAAAAAAA'
a.rl ===         '.BBB.C.D'
a.ex ===         '.BBB.C.D'
a.eh ===         '.BBB'
a.el ===             '.C.D'
a.x  ===             '.C.D'
a.h  ===             '.C'
a.l  ===               '.D'
@end example

@node Type variants for integer intrinsics
@subsection Type variants for integer intrinsics
@cindex intrinsics, integer

Similar to the D/C prefixes to real functions to specify the input/output
types, GNU Fortran offers B/I/J/K prefixes to integer functions for
compatibility with DEC programs. The types implied by each are:

@example
@code{B} - @code{INTEGER(kind=1)}
@code{I} - @code{INTEGER(kind=2)}
@code{J} - @code{INTEGER(kind=4)}
@code{K} - @code{INTEGER(kind=8)}
@end example

GNU Fortran supports these with the flag @option{-fdec-intrinsic-ints}.
Intrinsics for which prefixed versions are available and in what form are noted
in @ref{Intrinsic Procedures}. The complete list of supported intrinsics is
here:

@multitable @columnfractions .2 .2 .2 .2 .2

@headitem Intrinsic @tab B @tab I @tab J @tab K

@item @code{@ref{ABS}}
  @tab @code{BABS} @tab @code{IIABS} @tab @code{JIABS} @tab @code{KIABS}
@item @code{@ref{BTEST}}
  @tab @code{BBTEST} @tab @code{BITEST} @tab @code{BJTEST} @tab @code{BKTEST}
@item @code{@ref{IAND}}
  @tab @code{BIAND} @tab @code{IIAND} @tab @code{JIAND} @tab @code{KIAND}
@item @code{@ref{IBCLR}}
  @tab @code{BBCLR} @tab @code{IIBCLR} @tab @code{JIBCLR} @tab @code{KIBCLR}
@item @code{@ref{IBITS}}
  @tab @code{BBITS} @tab @code{IIBITS} @tab @code{JIBITS} @tab @code{KIBITS}
@item @code{@ref{IBSET}}
  @tab @code{BBSET} @tab @code{IIBSET} @tab @code{JIBSET} @tab @code{KIBSET}
@item @code{@ref{IEOR}}
  @tab @code{BIEOR} @tab @code{IIEOR} @tab @code{JIEOR} @tab @code{KIEOR}
@item @code{@ref{IOR}}
  @tab @code{BIOR} @tab @code{IIOR} @tab @code{JIOR} @tab @code{KIOR}
@item @code{@ref{ISHFT}}
  @tab @code{BSHFT} @tab @code{IISHFT} @tab @code{JISHFT} @tab @code{KISHFT}
@item @code{@ref{ISHFTC}}
  @tab @code{BSHFTC} @tab @code{IISHFTC} @tab @code{JISHFTC} @tab @code{KISHFTC}
@item @code{@ref{MOD}}
  @tab @code{BMOD} @tab @code{IMOD} @tab @code{JMOD} @tab @code{KMOD}
@item @code{@ref{NOT}}
  @tab @code{BNOT} @tab @code{INOT} @tab @code{JNOT} @tab @code{KNOT}
@item @code{@ref{REAL}}
  @tab @code{--} @tab @code{FLOATI} @tab @code{FLOATJ} @tab @code{FLOATK}
@end multitable

@node AUTOMATIC and STATIC attributes
@subsection @code{AUTOMATIC} and @code{STATIC} attributes
@cindex variable attributes
@cindex @code{AUTOMATIC}
@cindex @code{STATIC}

With @option{-fdec-static} GNU Fortran supports the DEC extended attributes
@code{STATIC} and @code{AUTOMATIC} to provide explicit specification of entity
storage.  These follow the syntax of the Fortran standard @code{SAVE} attribute.

@code{STATIC} is exactly equivalent to @code{SAVE}, and specifies that
an entity should be allocated in static memory.  As an example, @code{STATIC}
local variables will retain their values across multiple calls to a function.

Entities marked @code{AUTOMATIC} will be stack automatic whenever possible.
@code{AUTOMATIC} is the default for local variables smaller than
@option{-fmax-stack-var-size}, unless @option{-fno-automatic} is given.  This
attribute overrides @option{-fno-automatic}, @option{-fmax-stack-var-size}, and
blanket @code{SAVE} statements.


Examples:

@example
subroutine f
  integer, automatic :: i  ! automatic variable
  integer x, y             ! static variables
  save
  ...
endsubroutine
@end example
@example
subroutine f
  integer a, b, c, x, y, z
  static :: x
  save y
  automatic z, c
  ! a, b, c, and z are automatic
  ! x and y are static
endsubroutine
@end example
@example
! Compiled with -fno-automatic
subroutine f
  integer a, b, c, d
  automatic :: a
  ! a is automatic; b, c, and d are static
endsubroutine
@end example

@node Extended math intrinsics
@subsection Extended math intrinsics
@cindex intrinsics, math
@cindex intrinsics, trigonometric functions

GNU Fortran supports an extended list of mathematical intrinsics with the
compile flag @option{-fdec-math} for compatability with legacy code.
These intrinsics are described fully in @ref{Intrinsic Procedures} where it is
noted that they are extensions and should be avoided whenever possible.

Specifically, @option{-fdec-math} enables the @ref{COTAN} intrinsic, and
trigonometric intrinsics which accept or produce values in degrees instead of
radians.  Here is a summary of the new intrinsics:

@multitable @columnfractions .5 .5
@headitem Radians @tab Degrees
@item @code{@ref{ACOS}}   @tab @code{@ref{ACOSD}}*
@item @code{@ref{ASIN}}   @tab @code{@ref{ASIND}}*
@item @code{@ref{ATAN}}   @tab @code{@ref{ATAND}}*
@item @code{@ref{ATAN2}}  @tab @code{@ref{ATAN2D}}*
@item @code{@ref{COS}}    @tab @code{@ref{COSD}}*
@item @code{@ref{COTAN}}* @tab @code{@ref{COTAND}}*
@item @code{@ref{SIN}}    @tab @code{@ref{SIND}}*
@item @code{@ref{TAN}}    @tab @code{@ref{TAND}}*
@end multitable

* Enabled with @option{-fdec-math}.

For advanced users, it may be important to know the implementation of these
functions. They are simply wrappers around the standard radian functions, which
have more accurate builtin versions. These functions convert their arguments
(or results) to degrees (or radians) by taking the value modulus 360 (or 2*pi)
and then multiplying it by a constant radian-to-degree (or degree-to-radian)
factor, as appropriate. The factor is computed at compile-time as 180/pi (or
pi/180).

@node Form feed as whitespace
@subsection Form feed as whitespace
@cindex form feed whitespace

Historically, legacy compilers allowed insertion of form feed characters ('\f',
ASCII 0xC) at the beginning of lines for formatted output to line printers,
though the Fortran standard does not mention this. GNU Fortran supports the
interpretation of form feed characters in source as whitespace for
compatibility.

@node TYPE as an alias for PRINT
@subsection TYPE as an alias for PRINT
@cindex type alias print
For compatibility, GNU Fortran will interpret @code{TYPE} statements as
@code{PRINT} statements with the flag @option{-fdec}.  With this flag asserted,
the following two examples are equivalent:

@smallexample
TYPE *, 'hello world'
@end smallexample

@smallexample
PRINT *, 'hello world'
@end smallexample

@node %LOC as an rvalue
@subsection %LOC as an rvalue
@cindex LOC
Normally @code{%LOC} is allowed only in parameter lists.  However the intrinsic
function @code{LOC} does the same thing, and is usable as the right-hand-side of
assignments. For compatibility, GNU Fortran supports the use of @code{%LOC} as
an alias for the builtin @code{LOC} with @option{-std=legacy}.  With this
feature enabled the following two examples are equivalent:

@smallexample
integer :: i, l
l = %loc(i)
call sub(l)
@end smallexample

@smallexample
integer :: i
call sub(%loc(i))
@end smallexample

@node .XOR. operator
@subsection .XOR. operator
@cindex operators, xor

GNU Fortran supports @code{.XOR.} as a logical operator with @code{-std=legacy}
for compatibility with legacy code. @code{.XOR.} is equivalent to
@code{.NEQV.}. That is, the output is true if and only if the inputs differ.

@node Bitwise logical operators
@subsection Bitwise logical operators
@cindex logical, bitwise

With @option{-fdec}, GNU Fortran relaxes the type constraints on
logical operators to allow integer operands, and performs the corresponding
bitwise operation instead.  This flag is for compatibility only, and should be
avoided in new code.  Consider:

@smallexample
  INTEGER :: i, j
  i = z'33'
  j = z'cc'
  print *, i .AND. j
@end smallexample

In this example, compiled with @option{-fdec}, GNU Fortran will
replace the @code{.AND.} operation with a call to the intrinsic
@code{@ref{IAND}} function, yielding the bitwise-and of @code{i} and @code{j}.

Note that this conversion will occur if at least one operand is of integral
type.  As a result, a logical operand will be converted to an integer when the
other operand is an integer in a logical operation.  In this case,
@code{.TRUE.} is converted to @code{1} and @code{.FALSE.} to @code{0}.

Here is the mapping of logical operator to bitwise intrinsic used with
@option{-fdec}:

@multitable @columnfractions .25 .25 .5
@headitem Operator @tab Intrinsic @tab Bitwise operation
@item @code{.NOT.} @tab @code{@ref{NOT}} @tab complement
@item @code{.AND.} @tab @code{@ref{IAND}} @tab intersection
@item @code{.OR.} @tab @code{@ref{IOR}} @tab union
@item @code{.NEQV.} @tab @code{@ref{IEOR}} @tab exclusive or
@item @code{.EQV.} @tab @code{@ref{NOT}(@ref{IEOR})} @tab complement of exclusive or
@end multitable

@node Extended I/O specifiers
@subsection Extended I/O specifiers
@cindex @code{CARRIAGECONTROL}
@cindex @code{READONLY}
@cindex @code{SHARE}
@cindex @code{SHARED}
@cindex @code{NOSHARED}
@cindex I/O specifiers

GNU Fortran supports the additional legacy I/O specifiers
@code{CARRIAGECONTROL}, @code{READONLY}, and @code{SHARE} with the
compile flag @option{-fdec}, for compatibility.

@table @code
@item CARRIAGECONTROL
The @code{CARRIAGECONTROL} specifier allows a user to control line
termination settings between output records for an I/O unit. The specifier has
no meaning for readonly files. When @code{CARRAIGECONTROL} is specified upon
opening a unit for formatted writing, the exact @code{CARRIAGECONTROL} setting
determines what characters to write between output records. The syntax is:

@smallexample
OPEN(..., CARRIAGECONTROL=cc)
@end smallexample

Where @emph{cc} is a character expression that evaluates to one of the
following values:

@multitable @columnfractions .2 .8
@item @code{'LIST'} @tab One line feed between records (default)
@item @code{'FORTRAN'} @tab Legacy interpretation of the first character (see below)
@item @code{'NONE'} @tab No separator between records
@end multitable

With @code{CARRIAGECONTROL='FORTRAN'}, when a record is written, the first
character of the input record is not written, and instead determines the output
record separator as follows:

@multitable @columnfractions .3 .3 .4
@headitem Leading character @tab Meaning @tab Output separating character(s)
@item @code{'+'} @tab Overprinting @tab Carriage return only
@item @code{'-'} @tab New line @tab Line feed and carriage return
@item @code{'0'} @tab Skip line @tab Two line feeds and carriage return
@item @code{'1'} @tab New page @tab Form feed and carriage return
@item @code{'$'} @tab Prompting @tab Line feed (no carriage return)
@item @code{CHAR(0)} @tab Overprinting (no advance) @tab None
@end multitable

@item READONLY
The @code{READONLY} specifier may be given upon opening a unit, and is
equivalent to specifying @code{ACTION='READ'}, except that the file may not be
deleted on close (i.e. @code{CLOSE} with @code{STATUS="DELETE"}). The syntax
is:

@smallexample
@code{OPEN(..., READONLY)}
@end smallexample

@item SHARE
The @code{SHARE} specifier allows system-level locking on a unit upon opening
it for controlled access from multiple processes/threads. The @code{SHARE}
specifier has several forms:

@smallexample
OPEN(..., SHARE=sh)
OPEN(..., SHARED)
OPEN(..., NOSHARED)
@end smallexample

Where @emph{sh} in the first form is a character expression that evaluates to
a value as seen in the table below. The latter two forms are aliases
for particular values of @emph{sh}:

@multitable @columnfractions .3 .3 .4
@headitem Explicit form @tab Short form @tab Meaning
@item @code{SHARE='DENYRW'} @tab @code{NOSHARED} @tab Exclusive (write) lock
@item @code{SHARE='DENYNONE'} @tab @code{SHARED} @tab Shared (read) lock
@end multitable

In general only one process may hold an exclusive (write) lock for a given file
at a time, whereas many processes may hold shared (read) locks for the same
file.

The behavior of locking may vary with your operating system. On POSIX systems,
locking is implemented with @code{fcntl}. Consult your corresponding operating
system's manual pages for further details. Locking via @code{SHARE=} is not
supported on other systems.

@end table

@node Legacy PARAMETER statements
@subsection Legacy PARAMETER statements
@cindex PARAMETER

For compatibility, GNU Fortran supports legacy PARAMETER statements without
parentheses with @option{-std=legacy}.  A warning is emitted if used with
@option{-std=gnu}, and an error is acknowledged with a real Fortran standard
flag (@option{-std=f95}, etc...).  These statements take the following form:

@smallexample
implicit real (E)
parameter e = 2.718282
real c
parameter c = 3.0e8
@end smallexample

@node Default exponents
@subsection Default exponents
@cindex exponent

For compatibility, GNU Fortran supports a default exponent of zero in real
constants with @option{-fdec}.  For example, @code{9e} would be
interpreted as @code{9e0}, rather than an error.


@node Extensions not implemented in GNU Fortran
@section Extensions not implemented in GNU Fortran
@cindex extensions, not implemented

The long history of the Fortran language, its wide use and broad
userbase, the large number of different compiler vendors and the lack of
some features crucial to users in the first standards have lead to the
existence of a number of important extensions to the language.  While
some of the most useful or popular extensions are supported by the GNU
Fortran compiler, not all existing extensions are supported.  This section
aims at listing these extensions and offering advice on how best make
code that uses them running with the GNU Fortran compiler.

@c More can be found here:
@c   -- https://gcc.gnu.org/onlinedocs/gcc-3.4.6/g77/Missing-Features.html
@c   -- the list of Fortran and libgfortran bugs closed as WONTFIX:
@c      http://tinyurl.com/2u4h5y

@menu
* ENCODE and DECODE statements::
* Variable FORMAT expressions::
@c * TYPE and ACCEPT I/O Statements::
@c * DEFAULTFILE, DISPOSE and RECORDTYPE I/O specifiers::
@c * Omitted arguments in procedure call::
* Alternate complex function syntax::
* Volatile COMMON blocks::
* OPEN( ... NAME=)::
* Q edit descriptor::
@end menu

@node ENCODE and DECODE statements
@subsection @code{ENCODE} and @code{DECODE} statements
@cindex @code{ENCODE}
@cindex @code{DECODE}

GNU Fortran does not support the @code{ENCODE} and @code{DECODE}
statements.  These statements are best replaced by @code{READ} and
@code{WRITE} statements involving internal files (@code{CHARACTER}
variables and arrays), which have been part of the Fortran standard since
Fortran 77.  For example, replace a code fragment like

@smallexample
      INTEGER*1 LINE(80)
      REAL A, B, C
c     ... Code that sets LINE
      DECODE (80, 9000, LINE) A, B, C
 9000 FORMAT (1X, 3(F10.5))
@end smallexample

@noindent
with the following:

@smallexample
      CHARACTER(LEN=80) LINE
      REAL A, B, C
c     ... Code that sets LINE
      READ (UNIT=LINE, FMT=9000) A, B, C
 9000 FORMAT (1X, 3(F10.5))
@end smallexample

Similarly, replace a code fragment like

@smallexample
      INTEGER*1 LINE(80)
      REAL A, B, C
c     ... Code that sets A, B and C
      ENCODE (80, 9000, LINE) A, B, C
 9000 FORMAT (1X, 'OUTPUT IS ', 3(F10.5))
@end smallexample

@noindent
with the following:

@smallexample
      CHARACTER(LEN=80) LINE
      REAL A, B, C
c     ... Code that sets A, B and C
      WRITE (UNIT=LINE, FMT=9000) A, B, C
 9000 FORMAT (1X, 'OUTPUT IS ', 3(F10.5))
@end smallexample


@node Variable FORMAT expressions
@subsection Variable @code{FORMAT} expressions
@cindex @code{FORMAT}

A variable @code{FORMAT} expression is format statement which includes
angle brackets enclosing a Fortran expression: @code{FORMAT(I<N>)}.  GNU
Fortran does not support this legacy extension.  The effect of variable
format expressions can be reproduced by using the more powerful (and
standard) combination of internal output and string formats.  For example,
replace a code fragment like this:

@smallexample
      WRITE(6,20) INT1
 20   FORMAT(I<N+1>)
@end smallexample

@noindent
with the following:

@smallexample
c     Variable declaration
      CHARACTER(LEN=20) FMT
c
c     Other code here...
c
      WRITE(FMT,'("(I", I0, ")")') N+1
      WRITE(6,FMT) INT1
@end smallexample

@noindent
or with:

@smallexample
c     Variable declaration
      CHARACTER(LEN=20) FMT
c
c     Other code here...
c
      WRITE(FMT,*) N+1
      WRITE(6,"(I" // ADJUSTL(FMT) // ")") INT1
@end smallexample


@node Alternate complex function syntax
@subsection Alternate complex function syntax
@cindex Complex function

Some Fortran compilers, including @command{g77}, let the user declare
complex functions with the syntax @code{COMPLEX FUNCTION name*16()}, as
well as @code{COMPLEX*16 FUNCTION name()}.  Both are non-standard, legacy
extensions.  @command{gfortran} accepts the latter form, which is more
common, but not the former.


@node Volatile COMMON blocks
@subsection Volatile @code{COMMON} blocks
@cindex @code{VOLATILE}
@cindex @code{COMMON}

Some Fortran compilers, including @command{g77}, let the user declare
@code{COMMON} with the @code{VOLATILE} attribute. This is
invalid standard Fortran syntax and is not supported by
@command{gfortran}.  Note that @command{gfortran} accepts
@code{VOLATILE} variables in @code{COMMON} blocks since revision 4.3.


@node OPEN( ... NAME=)
@subsection @code{OPEN( ... NAME=)}
@cindex @code{NAME}

Some Fortran compilers, including @command{g77}, let the user declare
@code{OPEN( ... NAME=)}. This is
invalid standard Fortran syntax and is not supported by
@command{gfortran}.  @code{OPEN( ... NAME=)} should be replaced
with @code{OPEN( ... FILE=)}.

@node Q edit descriptor
@subsection @code{Q} edit descriptor
@cindex @code{Q} edit descriptor

Some Fortran compilers provide the @code{Q} edit descriptor, which
transfers the number of characters left within an input record into an
integer variable.

A direct replacement of the @code{Q} edit descriptor is not available
in @command{gfortran}.  How to replicate its functionality using
standard-conforming code depends on what the intent of the original
code is.

Options to replace @code{Q} may be to read the whole line into a
character variable and then counting the number of non-blank
characters left using @code{LEN_TRIM}.  Another method may be to use
formatted stream, read the data up to the position where the @code{Q}
descriptor occurred, use @code{INQUIRE} to get the file position,
count the characters up to the next @code{NEW_LINE} and then start
reading from the position marked previously.


@c ---------------------------------------------------------------------
@c ---------------------------------------------------------------------
@c Mixed-Language Programming
@c ---------------------------------------------------------------------

@node Mixed-Language Programming
@chapter Mixed-Language Programming
@cindex Interoperability
@cindex Mixed-language programming

@menu
* Interoperability with C::
* GNU Fortran Compiler Directives::
* Non-Fortran Main Program::
* Naming and argument-passing conventions::
@end menu

This chapter is about mixed-language interoperability, but also
applies if you link Fortran code compiled by different compilers.  In
most cases, use of the C Binding features of the Fortran 2003 and
later standards is sufficient.

For example, it is possible to mix Fortran code with C++ code as well
as C, if you declare the interface functions as @code{extern "C"} on
the C++ side and @code{BIND(C)} on the Fortran side, and follow the
rules for interoperability with C.  Note that you cannot manipulate
C++ class objects in Fortran or vice versa except as opaque pointers.

You can use the @command{gfortran} command to link both Fortran and
non-Fortran code into the same program, or you can use @command{gcc}
or @command{g++} if you also add an explicit @option{-lgfortran} option
to link with the Fortran library.  If your main program is written in
C or some other language instead of Fortran, see
@ref{Non-Fortran Main Program}, below.

@node Interoperability with C
@section Interoperability with C
@cindex interoperability with C
@cindex C interoperability

@menu
* Intrinsic Types::
* Derived Types and struct::
* Interoperable Global Variables::
* Interoperable Subroutines and Functions::
* Working with C Pointers::
* Further Interoperability of Fortran with C::
@end menu

Since Fortran 2003 (ISO/IEC 1539-1:2004(E)) there is a
standardized way to generate procedure and derived-type
declarations and global variables that are interoperable with C
(ISO/IEC 9899:1999).  The @code{BIND(C)} attribute has been added
to inform the compiler that a symbol shall be interoperable with C;
also, some constraints are added.  Note, however, that not
all C features have a Fortran equivalent or vice versa.  For instance,
neither C's unsigned integers nor C's functions with variable number
of arguments have an equivalent in Fortran.

Note that array dimensions are reversely ordered in C and that arrays in
C always start with index 0 while in Fortran they start by default with
1.  Thus, an array declaration @code{A(n,m)} in Fortran matches
@code{A[m][n]} in C and accessing the element @code{A(i,j)} matches
@code{A[j-1][i-1]}.  The element following @code{A(i,j)} (C: @code{A[j-1][i-1]};
assuming @math{i < n}) in memory is @code{A(i+1,j)} (C: @code{A[j-1][i]}).

@node Intrinsic Types
@subsection Intrinsic Types
@cindex C intrinsic type interoperability
@cindex intrinsic type interoperability with C
@cindex interoperability, intrinsic type

In order to ensure that exactly the same variable type and kind is used
in C and Fortran, you should use the named constants for kind parameters
that are defined in the @code{ISO_C_BINDING} intrinsic module.
That module contains named constants of character type representing
the escaped special characters in C, such as newline.
For a list of the constants, see @ref{ISO_C_BINDING}.

For logical types, please note that the Fortran standard only guarantees
interoperability between C99's @code{_Bool} and Fortran's @code{C_Bool}-kind
logicals and C99 defines that @code{true} has the value 1 and @code{false}
the value 0.  Using any other integer value with GNU Fortran's @code{LOGICAL}
(with any kind parameter) gives an undefined result.  (Passing other integer
values than 0 and 1 to GCC's @code{_Bool} is also undefined, unless the
integer is explicitly or implicitly casted to @code{_Bool}.)

@node Derived Types and struct
@subsection Derived Types and struct
@cindex C derived type and struct interoperability
@cindex derived type interoperability with C
@cindex interoperability, derived type and struct

For compatibility of derived types with @code{struct}, use
the @code{BIND(C)} attribute in the type declaration.  For instance, the
following type declaration

@smallexample
 USE ISO_C_BINDING
 TYPE, BIND(C) :: myType
   INTEGER(C_INT) :: i1, i2
   INTEGER(C_SIGNED_CHAR) :: i3
   REAL(C_DOUBLE) :: d1
   COMPLEX(C_FLOAT_COMPLEX) :: c1
   CHARACTER(KIND=C_CHAR) :: str(5)
 END TYPE
@end smallexample

@noindent
matches the following @code{struct} declaration in C

@smallexample
 struct @{
   int i1, i2;
   /* Note: "char" might be signed or unsigned.  */
   signed char i3;
   double d1;
   float _Complex c1;
   char str[5];
 @} myType;
@end smallexample

Derived types with the C binding attribute shall not have the @code{sequence}
attribute, type parameters, the @code{extends} attribute, nor type-bound
procedures.  Every component must be of interoperable type and kind and may not
have the @code{pointer} or @code{allocatable} attribute.  The names of the
components are irrelevant for interoperability.

As there exist no direct Fortran equivalents, neither unions nor structs
with bit field or variable-length array members are interoperable.

@node Interoperable Global Variables
@subsection Interoperable Global Variables
@cindex C variable interoperability
@cindex variable interoperability with C
@cindex interoperability, variable

Variables can be made accessible from C using the C binding attribute,
optionally together with specifying a binding name.  Those variables
have to be declared in the declaration part of a @code{MODULE},
be of interoperable type, and have neither the @code{pointer} nor
the @code{allocatable} attribute.

@smallexample
  MODULE m
    USE myType_module
    USE ISO_C_BINDING
    integer(C_INT), bind(C, name="_MyProject_flags") :: global_flag
    type(myType), bind(C) :: tp
  END MODULE
@end smallexample

Here, @code{_MyProject_flags} is the case-sensitive name of the variable
as seen from C programs while @code{global_flag} is the case-insensitive
name as seen from Fortran.  If no binding name is specified, as for
@var{tp}, the C binding name is the (lowercase) Fortran binding name.
If a binding name is specified, only a single variable may be after the
double colon.  Note of warning: You cannot use a global variable to
access @var{errno} of the C library as the C standard allows it to be
a macro.  Use the @code{IERRNO} intrinsic (GNU extension) instead.

@node Interoperable Subroutines and Functions
@subsection Interoperable Subroutines and Functions
@cindex C procedure interoperability
@cindex procedure interoperability with C
@cindex function interoperability with C
@cindex subroutine interoperability with C
@cindex interoperability, subroutine and function

Subroutines and functions have to have the @code{BIND(C)} attribute to
be compatible with C.  The dummy argument declaration is relatively
straightforward.  However, one needs to be careful because C uses
call-by-value by default while Fortran behaves usually similar to
call-by-reference.  Furthermore, strings and pointers are handled
differently.

To pass a variable by value, use the @code{VALUE} attribute.
Thus, the following C prototype

@smallexample
@code{int func(int i, int *j)}
@end smallexample

@noindent
matches the Fortran declaration

@smallexample
  integer(c_int) function func(i,j)
    use iso_c_binding, only: c_int
    integer(c_int), VALUE :: i
    integer(c_int) :: j
@end smallexample

Note that pointer arguments also frequently need the @code{VALUE} attribute,
see @ref{Working with C Pointers}.

Strings are handled quite differently in C and Fortran.  In C a string
is a @code{NUL}-terminated array of characters while in Fortran each string
has a length associated with it and is thus not terminated (by e.g.
@code{NUL}).  For example, if you want to use the following C function,

@smallexample
  #include <stdio.h>
  void print_C(char *string) /* equivalent: char string[]  */
  @{
     printf("%s\n", string);
  @}
@end smallexample

@noindent
to print ``Hello World'' from Fortran, you can call it using

@smallexample
  use iso_c_binding, only: C_CHAR, C_NULL_CHAR
  interface
    subroutine print_c(string) bind(C, name="print_C")
      use iso_c_binding, only: c_char
      character(kind=c_char) :: string(*)
    end subroutine print_c
  end interface
  call print_c(C_CHAR_"Hello World"//C_NULL_CHAR)
@end smallexample

As the example shows, you need to ensure that the
string is @code{NUL} terminated.  Additionally, the dummy argument
@var{string} of @code{print_C} is a length-one assumed-size
array; using @code{character(len=*)} is not allowed.  The example
above uses @code{c_char_"Hello World"} to ensure the string
literal has the right type; typically the default character
kind and @code{c_char} are the same and thus @code{"Hello World"}
is equivalent.  However, the standard does not guarantee this.

The use of strings is now further illustrated using the C library
function @code{strncpy}, whose prototype is

@smallexample
  char *strncpy(char *restrict s1, const char *restrict s2, size_t n);
@end smallexample

@noindent
The function @code{strncpy} copies at most @var{n} characters from
string @var{s2} to @var{s1} and returns @var{s1}.  In the following
example, we ignore the return value:

@smallexample
  use iso_c_binding
  implicit none
  character(len=30) :: str,str2
  interface
    ! Ignore the return value of strncpy -> subroutine
    ! "restrict" is always assumed if we do not pass a pointer
    subroutine strncpy(dest, src, n) bind(C)
      import
      character(kind=c_char),  intent(out) :: dest(*)
      character(kind=c_char),  intent(in)  :: src(*)
      integer(c_size_t), value, intent(in) :: n
    end subroutine strncpy
  end interface
  str = repeat('X',30) ! Initialize whole string with 'X'
  call strncpy(str, c_char_"Hello World"//C_NULL_CHAR, &
               len(c_char_"Hello World",kind=c_size_t))
  print '(a)', str ! prints: "Hello WorldXXXXXXXXXXXXXXXXXXX"
  end
@end smallexample

The intrinsic procedures are described in @ref{Intrinsic Procedures}.

@node Working with C Pointers
@subsection Working with C Pointers
@cindex C pointers
@cindex pointers, C

C pointers are represented in Fortran via the special opaque derived
type @code{type(c_ptr)} (with private components).  C pointers are distinct
from Fortran objects with the @code{POINTER} attribute.  Thus one needs to
use intrinsic conversion procedures to convert from or to C pointers.
For some applications, using an assumed type (@code{TYPE(*)}) can be
an alternative to a C pointer, and you can also use library routines
to access Fortran pointers from C.  See @ref{Further Interoperability
of Fortran with C}.

Here is an example of using C pointers in Fortran:

@smallexample
  use iso_c_binding
  type(c_ptr) :: cptr1, cptr2
  integer, target :: array(7), scalar
  integer, pointer :: pa(:), ps
  cptr1 = c_loc(array(1)) ! The programmer needs to ensure that the
                          ! array is contiguous if required by the C
                          ! procedure
  cptr2 = c_loc(scalar)
  call c_f_pointer(cptr2, ps)
  call c_f_pointer(cptr2, pa, shape=[7])
@end smallexample

When converting C to Fortran arrays, the one-dimensional @code{SHAPE} argument
has to be passed.

If a pointer is a dummy argument of an interoperable procedure, it usually
has to be declared using the @code{VALUE} attribute.  @code{void*}
matches @code{TYPE(C_PTR), VALUE}, while @code{TYPE(C_PTR)} alone
matches @code{void**}.

Procedure pointers are handled analogously to pointers; the C type is
@code{TYPE(C_FUNPTR)} and the intrinsic conversion procedures are
@code{C_F_PROCPOINTER} and @code{C_FUNLOC}.

Let us consider two examples of actually passing a procedure pointer from
C to Fortran and vice versa.  Note that these examples are also very
similar to passing ordinary pointers between both languages. First,
consider this code in C:

@smallexample
/* Procedure implemented in Fortran.  */
void get_values (void (*)(double));

/* Call-back routine we want called from Fortran.  */
void
print_it (double x)
@{
  printf ("Number is %f.\n", x);
@}

/* Call Fortran routine and pass call-back to it.  */
void
foobar ()
@{
  get_values (&print_it);
@}
@end smallexample

A matching implementation for @code{get_values} in Fortran, that correctly
receives the procedure pointer from C and is able to call it, is given
in the following @code{MODULE}:

@smallexample
MODULE m
  IMPLICIT NONE

  ! Define interface of call-back routine.
  ABSTRACT INTERFACE
    SUBROUTINE callback (x)
      USE, INTRINSIC :: ISO_C_BINDING
      REAL(KIND=C_DOUBLE), INTENT(IN), VALUE :: x
    END SUBROUTINE callback
  END INTERFACE

CONTAINS

  ! Define C-bound procedure.
  SUBROUTINE get_values (cproc) BIND(C)
    USE, INTRINSIC :: ISO_C_BINDING
    TYPE(C_FUNPTR), INTENT(IN), VALUE :: cproc

    PROCEDURE(callback), POINTER :: proc

    ! Convert C to Fortran procedure pointer.
    CALL C_F_PROCPOINTER (cproc, proc)

    ! Call it.
    CALL proc (1.0_C_DOUBLE)
    CALL proc (-42.0_C_DOUBLE)
    CALL proc (18.12_C_DOUBLE)
  END SUBROUTINE get_values

END MODULE m
@end smallexample

Next, we want to call a C routine that expects a procedure pointer argument
and pass it a Fortran procedure (which clearly must be interoperable!).
Again, the C function may be:

@smallexample
int
call_it (int (*func)(int), int arg)
@{
  return func (arg);
@}
@end smallexample

It can be used as in the following Fortran code:

@smallexample
MODULE m
  USE, INTRINSIC :: ISO_C_BINDING
  IMPLICIT NONE

  ! Define interface of C function.
  INTERFACE
    INTEGER(KIND=C_INT) FUNCTION call_it (func, arg) BIND(C)
      USE, INTRINSIC :: ISO_C_BINDING
      TYPE(C_FUNPTR), INTENT(IN), VALUE :: func
      INTEGER(KIND=C_INT), INTENT(IN), VALUE :: arg
    END FUNCTION call_it
  END INTERFACE

CONTAINS

  ! Define procedure passed to C function.
  ! It must be interoperable!
  INTEGER(KIND=C_INT) FUNCTION double_it (arg) BIND(C)
    INTEGER(KIND=C_INT), INTENT(IN), VALUE :: arg
    double_it = arg + arg
  END FUNCTION double_it

  ! Call C function.
  SUBROUTINE foobar ()
    TYPE(C_FUNPTR) :: cproc
    INTEGER(KIND=C_INT) :: i

    ! Get C procedure pointer.
    cproc = C_FUNLOC (double_it)

    ! Use it.
    DO i = 1_C_INT, 10_C_INT
      PRINT *, call_it (cproc, i)
    END DO
  END SUBROUTINE foobar

END MODULE m
@end smallexample

@node Further Interoperability of Fortran with C
@subsection Further Interoperability of Fortran with C
@cindex Further Interoperability of Fortran with C
@cindex TS 29113
@cindex array descriptor
@cindex dope vector
@cindex assumed-type
@cindex assumed-rank

GNU Fortran implements the Technical Specification ISO/IEC TS
29113:2012, which extends the interoperability support of Fortran 2003
and Fortran 2008 and is now part of the 2018 Fortran standard.
Besides removing some restrictions and constraints, the Technical
Specification adds assumed-type (@code{TYPE(*)}) and assumed-rank
(@code{DIMENSION(..)}) variables and allows for interoperability of
assumed-shape, assumed-rank, and deferred-shape arrays, as well as
allocatables and pointers.  Objects of these types are passed to
@code{BIND(C)} functions as descriptors with a standard interface,
declared in the header file @code{<ISO_Fortran_binding.h>}.

Note: Currently, GNU Fortran does not use internally the array descriptor
(dope vector) as specified in the Technical Specification, but uses
an array descriptor with different fields in functions without the
@code{BIND(C)} attribute.  Arguments to functions marked @code{BIND(C)}
are converted to the specified form.  If you need to access GNU Fortran's
internal array descriptor, you can use the Chasm Language Interoperability
Tools, @url{http://chasm-interop.sourceforge.net/}.

@node GNU Fortran Compiler Directives
@section GNU Fortran Compiler Directives

@menu
* ATTRIBUTES directive::
* UNROLL directive::
* BUILTIN directive::
* IVDEP directive::
* VECTOR directive::
* NOVECTOR directive::
@end menu

@node ATTRIBUTES directive
@subsection ATTRIBUTES directive

The Fortran standard describes how a conforming program shall
behave; however, the exact implementation is not standardized.  In order
to allow the user to choose specific implementation details, compiler
directives can be used to set attributes of variables and procedures
which are not part of the standard.  Whether a given attribute is
supported and its exact effects depend on both the operating system and
on the processor; see
@ref{Top,,C Extensions,gcc,Using the GNU Compiler Collection (GCC)}
for details.

For procedures and procedure pointers, the following attributes can
be used to change the calling convention:

@itemize
@item @code{CDECL} -- standard C calling convention
@item @code{STDCALL} -- convention where the called procedure pops the stack
@item @code{FASTCALL} -- part of the arguments are passed via registers
instead using the stack
@end itemize

Besides changing the calling convention, the attributes also influence
the decoration of the symbol name, e.g., by a leading underscore or by
a trailing at-sign followed by the number of bytes on the stack.  When
assigning a procedure to a procedure pointer, both should use the same
calling convention.

On some systems, procedures and global variables (module variables and
@code{COMMON} blocks) need special handling to be accessible when they
are in a shared library.  The following attributes are available:

@itemize
@item @code{DLLEXPORT} -- provide a global pointer to a pointer in the DLL
@item @code{DLLIMPORT} -- reference the function or variable using a
global pointer
@end itemize

For dummy arguments, the @code{NO_ARG_CHECK} attribute can be used; in
other compilers, it is also known as @code{IGNORE_TKR}.  For dummy arguments
with this attribute actual arguments of any type and kind (similar to
@code{TYPE(*)}), scalars and arrays of any rank (no equivalent
in Fortran standard) are accepted.  As with @code{TYPE(*)}, the argument
is unlimited polymorphic and no type information is available.
Additionally, the argument may only be passed to dummy arguments
with the @code{NO_ARG_CHECK} attribute and as argument to the
@code{PRESENT} intrinsic function and to @code{C_LOC} of the
@code{ISO_C_BINDING} module.

Variables with @code{NO_ARG_CHECK} attribute shall be of assumed-type
(@code{TYPE(*)}; recommended) or of type @code{INTEGER}, @code{LOGICAL},
@code{REAL} or @code{COMPLEX}. They shall not have the @code{ALLOCATE},
@code{CODIMENSION}, @code{INTENT(OUT)}, @code{POINTER} or @code{VALUE}
attribute; furthermore, they shall be either scalar or of assumed-size
(@code{dimension(*)}). As @code{TYPE(*)}, the @code{NO_ARG_CHECK} attribute
requires an explicit interface.

@itemize
@item @code{NO_ARG_CHECK} -- disable the type, kind and rank checking
@item @code{DEPRECATED} -- print a warning when using a such-tagged
deprecated procedure, variable or parameter; the warning can be suppressed
with @option{-Wno-deprecated-declarations}.
@item @code{NOINLINE} -- prevent inlining given function.
@item @code{NORETURN} -- add a hint that a given function cannot return.
@item @code{WEAK} -- emit the declaration of an external symbol as a weak
symbol rather than a global.  This is primarily useful in defining library
functions that can be overridden in user code, though it can also be used with
non-function declarations.  The overriding symbol must have the same type as
the weak symbol.
@end itemize


The attributes are specified using the syntax

@code{!GCC$ ATTRIBUTES} @var{attribute-list} @code{::} @var{variable-list}

where in free-form source code only whitespace is allowed before @code{!GCC$}
and in fixed-form source code @code{!GCC$}, @code{cGCC$} or @code{*GCC$} shall
start in the first column.

For procedures, the compiler directives shall be placed into the body
of the procedure; for variables and procedure pointers, they shall be in
the same declaration part as the variable or procedure pointer.


@node UNROLL directive
@subsection UNROLL directive

The syntax of the directive is

@code{!GCC$ unroll N}

You can use this directive to control how many times a loop should be unrolled.
It must be placed immediately before a @code{DO} loop and applies only to the
loop that follows.  N is an integer constant specifying the unrolling factor.
The values of 0 and 1 block any unrolling of the loop.


@node BUILTIN directive
@subsection BUILTIN directive

The syntax of the directive is

@code{!GCC$ BUILTIN (B) attributes simd FLAGS IF('target')}

You can use this directive to define which middle-end built-ins provide vector
implementations.  @code{B} is name of the middle-end built-in.  @code{FLAGS}
are optional and must be either "(inbranch)" or "(notinbranch)".
@code{IF} statement is optional and is used to filter multilib ABIs
for the built-in that should be vectorized.  Example usage:

@smallexample
!GCC$ builtin (sinf) attributes simd (notinbranch) if('x86_64')
@end smallexample

The purpose of the directive is to provide an API among the GCC compiler and
the GNU C Library which would define vector implementations of math routines.


@node IVDEP directive
@subsection IVDEP directive

The syntax of the directive is

@code{!GCC$ ivdep}

This directive tells the compiler to ignore vector dependencies in the
following loop.  It must be placed immediately before a @code{DO} loop
and applies only to the loop that follows.

Sometimes the compiler may not have sufficient information to decide
whether a particular loop is vectorizable due to potential
dependencies between iterations.  The purpose of the directive is to
tell the compiler that vectorization is safe.

This directive is intended for annotation of existing code.  For new
code it is recommended to consider OpenMP SIMD directives as potential
alternative.


@node VECTOR directive
@subsection VECTOR directive

The syntax of the directive is

@code{!GCC$ vector}

This directive tells the compiler to vectorize the following loop.  It
must be placed immediately before a @code{DO} loop and applies only to
the loop that follows.


@node NOVECTOR directive
@subsection NOVECTOR directive

The syntax of the directive is

@code{!GCC$ novector}

This directive tells the compiler to not vectorize the following loop.
It must be placed immediately before a @code{DO} loop and applies only
to the loop that follows.


@node Non-Fortran Main Program
@section Non-Fortran Main Program

@menu
* _gfortran_set_args:: Save command-line arguments
* _gfortran_set_options:: Set library option flags
* _gfortran_set_convert:: Set endian conversion
* _gfortran_set_record_marker:: Set length of record markers
* _gfortran_set_fpe:: Set when a Floating Point Exception should be raised
* _gfortran_set_max_subrecord_length:: Set subrecord length
@end menu

Even if you are doing mixed-language programming, it is very
likely that you do not need to know or use the information in this
section.  Since it is about the internal structure of GNU Fortran,
it may also change in GCC minor releases.

When you compile a @code{PROGRAM} with GNU Fortran, a function
with the name @code{main} (in the symbol table of the object file)
is generated, which initializes the libgfortran library and then
calls the actual program which uses the name @code{MAIN__}, for
historic reasons.  If you link GNU Fortran compiled procedures
to, e.g., a C or C++ program or to a Fortran program compiled by
a different compiler, the libgfortran library is not initialized
and thus a few intrinsic procedures do not work properly, e.g.
those for obtaining the command-line arguments.

Therefore, if your @code{PROGRAM} is not compiled with
GNU Fortran and the GNU Fortran compiled procedures require
intrinsics relying on the library initialization, you need to
initialize the library yourself.  Using the default options,
gfortran calls @code{_gfortran_set_args} and
@code{_gfortran_set_options}.  The initialization of the former
is needed if the called procedures access the command line
(and for backtracing); the latter sets some flags based on the
standard chosen or to enable backtracing.  In typical programs,
it is not necessary to call any initialization function.

If your @code{PROGRAM} is compiled with GNU Fortran, you shall
not call any of the following functions.  The libgfortran
initialization functions are shown in C syntax but using C
bindings they are also accessible from Fortran.


@node _gfortran_set_args
@subsection @code{_gfortran_set_args} --- Save command-line arguments
@fnindex _gfortran_set_args
@cindex libgfortran initialization, set_args

@table @asis
@item @emph{Description}:
@code{_gfortran_set_args} saves the command-line arguments; this
initialization is required if any of the command-line intrinsics
is called.  Additionally, it shall be called if backtracing is
enabled (see @code{_gfortran_set_options}).

@item @emph{Syntax}:
@code{void _gfortran_set_args (int argc, char *argv[])}

@item @emph{Arguments}:
@multitable @columnfractions .15 .70
@item @var{argc} @tab number of command line argument strings
@item @var{argv} @tab the command-line argument strings; argv[0]
is the pathname of the executable itself.
@end multitable

@item @emph{Example}:
@smallexample
int main (int argc, char *argv[])
@{
  /* Initialize libgfortran.  */
  _gfortran_set_args (argc, argv);
  return 0;
@}
@end smallexample
@end table


@node _gfortran_set_options
@subsection @code{_gfortran_set_options} --- Set library option flags
@fnindex _gfortran_set_options
@cindex libgfortran initialization, set_options

@table @asis
@item @emph{Description}:
@code{_gfortran_set_options} sets several flags related to the Fortran
standard to be used, whether backtracing should be enabled
and whether range checks should be performed.  The syntax allows for
upward compatibility since the number of passed flags is specified; for
non-passed flags, the default value is used.  See also
@pxref{Code Gen Options}.  Please note that not all flags are actually
used.

@item @emph{Syntax}:
@code{void _gfortran_set_options (int num, int options[])}

@item @emph{Arguments}:
@multitable @columnfractions .15 .70
@item @var{num} @tab number of options passed
@item @var{argv} @tab The list of flag values
@end multitable

@item @emph{option flag list}:
@multitable @columnfractions .15 .70
@item @var{option}[0] @tab Allowed standard; can give run-time errors
if e.g. an input-output edit descriptor is invalid in a given
standard.  Possible values are (bitwise or-ed) @code{GFC_STD_F77} (1),
@code{GFC_STD_F95_OBS} (2), @code{GFC_STD_F95_DEL} (4),
@code{GFC_STD_F95} (8), @code{GFC_STD_F2003} (16), @code{GFC_STD_GNU}
(32), @code{GFC_STD_LEGACY} (64), @code{GFC_STD_F2008} (128),
@code{GFC_STD_F2008_OBS} (256), @code{GFC_STD_F2008_TS} (512),
@code{GFC_STD_F2018} (1024), @code{GFC_STD_F2018_OBS} (2048), and
@code{GFC_STD=F2018_DEL} (4096). Default: @code{GFC_STD_F95_OBS |
GFC_STD_F95_DEL | GFC_STD_F95 | GFC_STD_F2003 | GFC_STD_F2008 |
GFC_STD_F2008_TS | GFC_STD_F2008_OBS | GFC_STD_F77 | GFC_STD_F2018 |
GFC_STD_F2018_OBS | GFC_STD_F2018_DEL | GFC_STD_GNU | GFC_STD_LEGACY}.
@item @var{option}[1] @tab Standard-warning flag; prints a warning to
standard error.  Default: @code{GFC_STD_F95_DEL | GFC_STD_LEGACY}.
@item @var{option}[2] @tab If non zero, enable pedantic checking.
Default: off.
@item @var{option}[3] @tab Unused.
@item @var{option}[4] @tab If non zero, enable backtracing on run-time
errors.  Default: off. (Default in the compiler: on.)
Note: Installs a signal handler and requires command-line
initialization using @code{_gfortran_set_args}.
@item @var{option}[5] @tab If non zero, supports signed zeros.
Default: enabled.
@item @var{option}[6] @tab Enables run-time checking.  Possible values
are (bitwise or-ed): GFC_RTCHECK_BOUNDS (1), GFC_RTCHECK_ARRAY_TEMPS (2),
GFC_RTCHECK_RECURSION (4), GFC_RTCHECK_DO (8), GFC_RTCHECK_POINTER (16),
GFC_RTCHECK_MEM (32), GFC_RTCHECK_BITS (64).
Default: disabled.
@item @var{option}[7] @tab Unused.
@item @var{option}[8] @tab Show a warning when invoking @code{STOP} and
@code{ERROR STOP} if a floating-point exception occurred. Possible values
are (bitwise or-ed) @code{GFC_FPE_INVALID} (1), @code{GFC_FPE_DENORMAL} (2),
@code{GFC_FPE_ZERO} (4), @code{GFC_FPE_OVERFLOW} (8),
@code{GFC_FPE_UNDERFLOW} (16), @code{GFC_FPE_INEXACT} (32). Default: None (0).
(Default in the compiler: @code{GFC_FPE_INVALID | GFC_FPE_DENORMAL |
GFC_FPE_ZERO | GFC_FPE_OVERFLOW | GFC_FPE_UNDERFLOW}.)
@end multitable

@item @emph{Example}:
@smallexample
  /* Use gfortran 4.9 default options.  */
  static int options[] = @{68, 511, 0, 0, 1, 1, 0, 0, 31@};
  _gfortran_set_options (9, &options);
@end smallexample
@end table


@node _gfortran_set_convert
@subsection @code{_gfortran_set_convert} --- Set endian conversion
@fnindex _gfortran_set_convert
@cindex libgfortran initialization, set_convert

@table @asis
@item @emph{Description}:
@code{_gfortran_set_convert} set the representation of data for
unformatted files.

@item @emph{Syntax}:
@code{void _gfortran_set_convert (int conv)}

@item @emph{Arguments}:
@multitable @columnfractions .15 .70
@item @var{conv} @tab Endian conversion, possible values:
GFC_CONVERT_NATIVE (0, default), GFC_CONVERT_SWAP (1),
GFC_CONVERT_BIG (2), GFC_CONVERT_LITTLE (3).
@end multitable

@item @emph{Example}:
@smallexample
int main (int argc, char *argv[])
@{
  /* Initialize libgfortran.  */
  _gfortran_set_args (argc, argv);
  _gfortran_set_convert (1);
  return 0;
@}
@end smallexample
@end table


@node _gfortran_set_record_marker
@subsection @code{_gfortran_set_record_marker} --- Set length of record markers
@fnindex _gfortran_set_record_marker
@cindex libgfortran initialization, set_record_marker

@table @asis
@item @emph{Description}:
@code{_gfortran_set_record_marker} sets the length of record markers
for unformatted files.

@item @emph{Syntax}:
@code{void _gfortran_set_record_marker (int val)}

@item @emph{Arguments}:
@multitable @columnfractions .15 .70
@item @var{val} @tab Length of the record marker; valid values
are 4 and 8.  Default is 4.
@end multitable

@item @emph{Example}:
@smallexample
int main (int argc, char *argv[])
@{
  /* Initialize libgfortran.  */
  _gfortran_set_args (argc, argv);
  _gfortran_set_record_marker (8);
  return 0;
@}
@end smallexample
@end table


@node _gfortran_set_fpe
@subsection @code{_gfortran_set_fpe} --- Enable floating point exception traps
@fnindex _gfortran_set_fpe
@cindex libgfortran initialization, set_fpe

@table @asis
@item @emph{Description}:
@code{_gfortran_set_fpe} enables floating point exception traps for
the specified exceptions.  On most systems, this will result in a
SIGFPE signal being sent and the program being aborted.

@item @emph{Syntax}:
@code{void _gfortran_set_fpe (int val)}

@item @emph{Arguments}:
@multitable @columnfractions .15 .70
@item @var{option}[0] @tab IEEE exceptions.  Possible values are
(bitwise or-ed) zero (0, default) no trapping,
@code{GFC_FPE_INVALID} (1), @code{GFC_FPE_DENORMAL} (2),
@code{GFC_FPE_ZERO} (4), @code{GFC_FPE_OVERFLOW} (8),
@code{GFC_FPE_UNDERFLOW} (16), and @code{GFC_FPE_INEXACT} (32).
@end multitable

@item @emph{Example}:
@smallexample
int main (int argc, char *argv[])
@{
  /* Initialize libgfortran.  */
  _gfortran_set_args (argc, argv);
  /* FPE for invalid operations such as SQRT(-1.0).  */
  _gfortran_set_fpe (1);
  return 0;
@}
@end smallexample
@end table


@node _gfortran_set_max_subrecord_length
@subsection @code{_gfortran_set_max_subrecord_length} --- Set subrecord length
@fnindex _gfortran_set_max_subrecord_length
@cindex libgfortran initialization, set_max_subrecord_length

@table @asis
@item @emph{Description}:
@code{_gfortran_set_max_subrecord_length} set the maximum length
for a subrecord.  This option only makes sense for testing and
debugging of unformatted I/O.

@item @emph{Syntax}:
@code{void _gfortran_set_max_subrecord_length (int val)}

@item @emph{Arguments}:
@multitable @columnfractions .15 .70
@item @var{val} @tab the maximum length for a subrecord;
the maximum permitted value is 2147483639, which is also
the default.
@end multitable

@item @emph{Example}:
@smallexample
int main (int argc, char *argv[])
@{
  /* Initialize libgfortran.  */
  _gfortran_set_args (argc, argv);
  _gfortran_set_max_subrecord_length (8);
  return 0;
@}
@end smallexample
@end table


@node Naming and argument-passing conventions
@section Naming and argument-passing conventions

This section gives an overview about the naming convention of procedures
and global variables and about the argument passing conventions used by
GNU Fortran.  If a C binding has been specified, the naming convention
and some of the argument-passing conventions change.  If possible,
mixed-language and mixed-compiler projects should use the better defined
C binding for interoperability.  See @pxref{Interoperability with C}.

@menu
* Naming conventions::
* Argument passing conventions::
@end menu


@node Naming conventions
@subsection Naming conventions

According the Fortran standard, valid Fortran names consist of a letter
between @code{A} to @code{Z}, @code{a} to @code{z}, digits @code{0},
@code{1} to @code{9} and underscores (@code{_}) with the restriction
that names may only start with a letter.  As vendor extension, the
dollar sign (@code{$}) is additionally permitted with the option
@option{-fdollar-ok}, but not as first character and only if the
target system supports it.

By default, the procedure name is the lower-cased Fortran name with an
appended underscore (@code{_}); using @option{-fno-underscoring} no
underscore is appended while @code{-fsecond-underscore} appends two
underscores.  Depending on the target system and the calling convention,
the procedure might be additionally dressed; for instance, on 32bit
Windows with @code{stdcall}, an at-sign @code{@@} followed by an integer
number is appended.  For the changing the calling convention, see
@pxref{GNU Fortran Compiler Directives}.

For common blocks, the same convention is used, i.e. by default an
underscore is appended to the lower-cased Fortran name.  Blank commons
have the name @code{__BLNK__}.

For procedures and variables declared in the specification space of a
module, the name is formed by @code{__}, followed by the lower-cased
module name, @code{_MOD_}, and the lower-cased Fortran name.  Note that
no underscore is appended.


@node Argument passing conventions
@subsection Argument passing conventions

Subroutines do not return a value (matching C99's @code{void}) while
functions either return a value as specified in the platform ABI or
the result variable is passed as hidden argument to the function and
no result is returned.  A hidden result variable is used when the
result variable is an array or of type @code{CHARACTER}.

Arguments are passed according to the platform ABI. In particular,
complex arguments might not be compatible to a struct with two real
components for the real and imaginary part. The argument passing
matches the one of C99's @code{_Complex}.  Functions with scalar
complex result variables return their value and do not use a
by-reference argument.  Note that with the @option{-ff2c} option,
the argument passing is modified and no longer completely matches
the platform ABI.  Some other Fortran compilers use @code{f2c}
semantic by default; this might cause problems with
interoperablility.

GNU Fortran passes most arguments by reference, i.e. by passing a
pointer to the data.  Note that the compiler might use a temporary
variable into which the actual argument has been copied, if required
semantically (copy-in/copy-out).

For arguments with @code{ALLOCATABLE} and @code{POINTER}
attribute (including procedure pointers), a pointer to the pointer
is passed such that the pointer address can be modified in the
procedure.

For dummy arguments with the @code{VALUE} attribute: Scalar arguments
of the type @code{INTEGER}, @code{LOGICAL}, @code{REAL} and
@code{COMPLEX} are passed by value according to the platform ABI.
(As vendor extension and not recommended, using @code{%VAL()} in the
call to a procedure has the same effect.) For @code{TYPE(C_PTR)} and
procedure pointers, the pointer itself is passed such that it can be
modified without affecting the caller.
@c FIXME: Document how VALUE is handled for CHARACTER, TYPE,
@c CLASS and arrays, i.e. whether the copy-in is done in the caller
@c or in the callee.

For Boolean (@code{LOGICAL}) arguments, please note that GCC expects
only the integer value 0 and 1.  If a GNU Fortran @code{LOGICAL}
variable contains another integer value, the result is undefined.
As some other Fortran compilers use @math{-1} for @code{.TRUE.},
extra care has to be taken -- such as passing the value as
@code{INTEGER}.  (The same value restriction also applies to other
front ends of GCC, e.g. to GCC's C99 compiler for @code{_Bool}
or GCC's Ada compiler for @code{Boolean}.)

For arguments of @code{CHARACTER} type, the character length is passed
as a hidden argument at the end of the argument list, except when the
corresponding dummy argument is declared as @code{TYPE(*)}.  For
deferred-length strings, the value is passed by reference, otherwise
by value.  The character length has the C type @code{size_t} (or
@code{INTEGER(kind=C_SIZE_T)} in Fortran).  Note that this is
different to older versions of the GNU Fortran compiler, where the
type of the hidden character length argument was a C @code{int}.  In
order to retain compatibility with older versions, one can e.g. for
the following Fortran procedure

@smallexample
subroutine fstrlen (s, a)
   character(len=*) :: s
   integer :: a
   print*, len(s)
end subroutine fstrlen
@end smallexample

define the corresponding C prototype as follows:

@smallexample
#if __GNUC__ > 7
typedef size_t fortran_charlen_t;
#else
typedef int fortran_charlen_t;
#endif

void fstrlen_ (char*, int*, fortran_charlen_t);
@end smallexample

In order to avoid such compiler-specific details, for new code it is
instead recommended to use the ISO_C_BINDING feature.

Note with C binding, @code{CHARACTER(len=1)} result variables are
returned according to the platform ABI and no hidden length argument
is used for dummy arguments; with @code{VALUE}, those variables are
passed by value.

For @code{OPTIONAL} dummy arguments, an absent argument is denoted
by a NULL pointer, except for scalar dummy arguments of intrinsic type
which have the @code{VALUE} attribute.  For those, a hidden Boolean
argument (@code{logical(kind=C_bool),value}) is used to indicate
whether the argument is present.

Arguments which are assumed-shape, assumed-rank or deferred-rank
arrays or, with @option{-fcoarray=lib}, allocatable scalar coarrays use
an array descriptor.  All other arrays pass the address of the
first element of the array.  With @option{-fcoarray=lib}, the token
and the offset belonging to nonallocatable coarrays dummy arguments
are passed as hidden argument along the character length hidden
arguments.  The token is an opaque pointer identifying the coarray
and the offset is a passed-by-value integer of kind @code{C_PTRDIFF_T},
denoting the byte offset between the base address of the coarray and
the passed scalar or first element of the passed array.

The arguments are passed in the following order
@itemize @bullet
@item Result variable, when the function result is passed by reference
@item Character length of the function result, if it is a of type
@code{CHARACTER} and no C binding is used
@item The arguments in the order in which they appear in the Fortran
declaration
@item The present status for optional arguments with value attribute,
which are internally passed by value
@item The character length and/or coarray token and offset for the first
argument which is a @code{CHARACTER} or a nonallocatable coarray dummy
argument, followed by the hidden arguments of the next dummy argument
of such a type
@end itemize


@c ---------------------------------------------------------------------
@c Coarray Programming
@c ---------------------------------------------------------------------

@node Coarray Programming
@chapter Coarray Programming
@cindex Coarrays

@menu
* Type and enum ABI Documentation::
* Function ABI Documentation::
@end menu


@node Type and enum ABI Documentation
@section Type and enum ABI Documentation

@menu
* caf_token_t::
* caf_register_t::
* caf_deregister_t::
* caf_reference_t::
* caf_team_t::
@end menu

@node caf_token_t
@subsection @code{caf_token_t}

Typedef of type @code{void *} on the compiler side. Can be any data
type on the library side.

@node caf_register_t
@subsection @code{caf_register_t}

Indicates which kind of coarray variable should be registered.

@verbatim
typedef enum caf_register_t {
  CAF_REGTYPE_COARRAY_STATIC,
  CAF_REGTYPE_COARRAY_ALLOC,
  CAF_REGTYPE_LOCK_STATIC,
  CAF_REGTYPE_LOCK_ALLOC,
  CAF_REGTYPE_CRITICAL,
  CAF_REGTYPE_EVENT_STATIC,
  CAF_REGTYPE_EVENT_ALLOC,
  CAF_REGTYPE_COARRAY_ALLOC_REGISTER_ONLY,
  CAF_REGTYPE_COARRAY_ALLOC_ALLOCATE_ONLY
}
caf_register_t;
@end verbatim

The values @code{CAF_REGTYPE_COARRAY_ALLOC_REGISTER_ONLY} and
@code{CAF_REGTYPE_COARRAY_ALLOC_ALLOCATE_ONLY} are for allocatable components
in derived type coarrays only.  The first one sets up the token without
allocating memory for allocatable component.  The latter one only allocates the
memory for an allocatable component in a derived type coarray.  The token
needs to be setup previously by the REGISTER_ONLY.  This allows to have
allocatable components un-allocated on some images.  The status whether an
allocatable component is allocated on a remote image can be queried by
@code{_caf_is_present} which used internally by the @code{ALLOCATED}
intrinsic.

@node caf_deregister_t
@subsection @code{caf_deregister_t}

@verbatim
typedef enum caf_deregister_t {
  CAF_DEREGTYPE_COARRAY_DEREGISTER,
  CAF_DEREGTYPE_COARRAY_DEALLOCATE_ONLY
}
caf_deregister_t;
@end verbatim

Allows to specify the type of deregistration of a coarray object.  The
@code{CAF_DEREGTYPE_COARRAY_DEALLOCATE_ONLY} flag is only allowed for
allocatable components in derived type coarrays.

@node caf_reference_t
@subsection @code{caf_reference_t}

The structure used for implementing arbitrary reference chains.
A @code{CAF_REFERENCE_T} allows to specify a component reference or any kind
of array reference of any rank supported by gfortran.  For array references all
kinds as known by the compiler/Fortran standard are supported indicated by
a @code{MODE}.

@verbatim
typedef enum caf_ref_type_t {
  /* Reference a component of a derived type, either regular one or an
     allocatable or pointer type.  For regular ones idx in caf_reference_t is
     set to -1.  */
  CAF_REF_COMPONENT,
  /* Reference an allocatable array.  */
  CAF_REF_ARRAY,
  /* Reference a non-allocatable/non-pointer array.  I.e., the coarray object
     has no array descriptor associated and the addressing is done
     completely using the ref.  */
  CAF_REF_STATIC_ARRAY
} caf_ref_type_t;
@end verbatim

@verbatim
typedef enum caf_array_ref_t {
  /* No array ref.  This terminates the array ref.  */
  CAF_ARR_REF_NONE = 0,
  /* Reference array elements given by a vector.  Only for this mode
     caf_reference_t.u.a.dim[i].v is valid.  */
  CAF_ARR_REF_VECTOR,
  /* A full array ref (:).  */
  CAF_ARR_REF_FULL,
  /* Reference a range on elements given by start, end and stride.  */
  CAF_ARR_REF_RANGE,
  /* Only a single item is referenced given in the start member.  */
  CAF_ARR_REF_SINGLE,
  /* An array ref of the kind (i:), where i is an arbitrary valid index in the
     array.  The index i is given in the start member.  */
  CAF_ARR_REF_OPEN_END,
  /* An array ref of the kind (:i), where the lower bound of the array ref
     is given by the remote side.  The index i is given in the end member.  */
  CAF_ARR_REF_OPEN_START
} caf_array_ref_t;
@end verbatim

@verbatim
/* References to remote components of a derived type.  */
typedef struct caf_reference_t {
  /* A pointer to the next ref or NULL.  */
  struct caf_reference_t *next;
  /* The type of the reference.  */
  /* caf_ref_type_t, replaced by int to allow specification in fortran FE.  */
  int type;
  /* The size of an item referenced in bytes.  I.e. in an array ref this is
     the factor to advance the array pointer with to get to the next item.
     For component refs this gives just the size of the element referenced.  */
  size_t item_size;
  union {
    struct {
      /* The offset (in bytes) of the component in the derived type.
         Unused for allocatable or pointer components.  */
      ptrdiff_t offset;
      /* The offset (in bytes) to the caf_token associated with this
         component.  NULL, when not allocatable/pointer ref.  */
      ptrdiff_t caf_token_offset;
    } c;
    struct {
      /* The mode of the array ref.  See CAF_ARR_REF_*.  */
      /* caf_array_ref_t, replaced by unsigend char to allow specification in
         fortran FE.  */
     unsigned char mode[GFC_MAX_DIMENSIONS];
      /* The type of a static array.  Unset for array's with descriptors.  */
      int static_array_type;
      /* Subscript refs (s) or vector refs (v).  */
      union {
        struct {
          /* The start and end boundary of the ref and the stride.  */
          index_type start, end, stride;
        } s;
        struct {
          /* nvec entries of kind giving the elements to reference.  */
          void *vector;
          /* The number of entries in vector.  */
          size_t nvec;
          /* The integer kind used for the elements in vector.  */
          int kind;
        } v;
      } dim[GFC_MAX_DIMENSIONS];
    } a;
  } u;
} caf_reference_t;
@end verbatim

The references make up a single linked list of reference operations.  The
@code{NEXT} member links to the next reference or NULL to indicate the end of
the chain.  Component and array refs can be arbitrarily mixed as long as they
comply to the Fortran standard.

@emph{NOTES}
The member @code{STATIC_ARRAY_TYPE} is used only when the @code{TYPE} is
@code{CAF_REF_STATIC_ARRAY}.  The member gives the type of the data referenced.
Because no array descriptor is available for a descriptor-less array and
type conversion still needs to take place the type is transported here.

At the moment @code{CAF_ARR_REF_VECTOR} is not implemented in the front end for
descriptor-less arrays.  The library caf_single has untested support for it.

@node caf_team_t
@subsection @code{caf_team_t}

Opaque pointer to represent a team-handle.  This type is a stand-in for the
future implementation of teams.  It is about to change without further notice.

@node Function ABI Documentation
@section Function ABI Documentation

@menu
* _gfortran_caf_init:: Initialiation function
* _gfortran_caf_finish:: Finalization function
* _gfortran_caf_this_image:: Querying the image number
* _gfortran_caf_num_images:: Querying the maximal number of images
* _gfortran_caf_image_status :: Query the status of an image
* _gfortran_caf_failed_images :: Get an array of the indexes of the failed images
* _gfortran_caf_stopped_images :: Get an array of the indexes of the stopped images
* _gfortran_caf_register:: Registering coarrays
* _gfortran_caf_deregister:: Deregistering coarrays
* _gfortran_caf_is_present:: Query whether an allocatable or pointer component in a derived type coarray is allocated
* _gfortran_caf_send:: Sending data from a local image to a remote image
* _gfortran_caf_get:: Getting data from a remote image
* _gfortran_caf_sendget:: Sending data between remote images
* _gfortran_caf_send_by_ref:: Sending data from a local image to a remote image using enhanced references
* _gfortran_caf_get_by_ref:: Getting data from a remote image using enhanced references
* _gfortran_caf_sendget_by_ref:: Sending data between remote images using enhanced references
* _gfortran_caf_lock:: Locking a lock variable
* _gfortran_caf_unlock:: Unlocking a lock variable
* _gfortran_caf_event_post:: Post an event
* _gfortran_caf_event_wait:: Wait that an event occurred
* _gfortran_caf_event_query:: Query event count
* _gfortran_caf_sync_all:: All-image barrier
* _gfortran_caf_sync_images:: Barrier for selected images
* _gfortran_caf_sync_memory:: Wait for completion of segment-memory operations
* _gfortran_caf_error_stop:: Error termination with exit code
* _gfortran_caf_error_stop_str:: Error termination with string
* _gfortran_caf_fail_image :: Mark the image failed and end its execution
* _gfortran_caf_atomic_define:: Atomic variable assignment
* _gfortran_caf_atomic_ref:: Atomic variable reference
* _gfortran_caf_atomic_cas:: Atomic compare and swap
* _gfortran_caf_atomic_op:: Atomic operation
* _gfortran_caf_co_broadcast:: Sending data to all images
* _gfortran_caf_co_max:: Collective maximum reduction
* _gfortran_caf_co_min:: Collective minimum reduction
* _gfortran_caf_co_sum:: Collective summing reduction
* _gfortran_caf_co_reduce:: Generic collective reduction
@end menu


@node _gfortran_caf_init
@subsection @code{_gfortran_caf_init} --- Initialiation function
@cindex Coarray, _gfortran_caf_init

@table @asis
@item @emph{Description}:
This function is called at startup of the program before the Fortran main
program, if the latter has been compiled with @option{-fcoarray=lib}.
It takes as arguments the command-line arguments of the program.  It is
permitted to pass two @code{NULL} pointers as argument; if non-@code{NULL},
the library is permitted to modify the arguments.

@item @emph{Syntax}:
@code{void _gfortran_caf_init (int *argc, char ***argv)}

@item @emph{Arguments}:
@multitable @columnfractions .15 .70
@item @var{argc} @tab intent(inout) An integer pointer with the number of
arguments passed to the program or @code{NULL}.
@item @var{argv} @tab intent(inout) A pointer to an array of strings with the
command-line arguments or @code{NULL}.
@end multitable

@item @emph{NOTES}
The function is modelled after the initialization function of the Message
Passing Interface (MPI) specification.  Due to the way coarray registration
works, it might not be the first call to the library.  If the main program is
not written in Fortran and only a library uses coarrays, it can happen that
this function is never called.  Therefore, it is recommended that the library
does not rely on the passed arguments and whether the call has been done.
@end table


@node _gfortran_caf_finish
@subsection @code{_gfortran_caf_finish} --- Finalization function
@cindex Coarray, _gfortran_caf_finish

@table @asis
@item @emph{Description}:
This function is called at the end of the Fortran main program, if it has
been compiled with the @option{-fcoarray=lib} option.

@item @emph{Syntax}:
@code{void _gfortran_caf_finish (void)}

@item @emph{NOTES}
For non-Fortran programs, it is recommended to call the function at the end
of the main program.  To ensure that the shutdown is also performed for
programs where this function is not explicitly invoked, for instance
non-Fortran programs or calls to the system's exit() function, the library
can use a destructor function.  Note that programs can also be terminated
using the STOP and ERROR STOP statements; those use different library calls.
@end table


@node _gfortran_caf_this_image
@subsection @code{_gfortran_caf_this_image} --- Querying the image number
@cindex Coarray, _gfortran_caf_this_image

@table @asis
@item @emph{Description}:
This function returns the current image number, which is a positive number.

@item @emph{Syntax}:
@code{int _gfortran_caf_this_image (int distance)}

@item @emph{Arguments}:
@multitable @columnfractions .15 .70
@item @var{distance} @tab As specified for the @code{this_image} intrinsic
in TS18508.  Shall be a non-negative number.
@end multitable

@item @emph{NOTES}
If the Fortran intrinsic @code{this_image} is invoked without an argument, which
is the only permitted form in Fortran 2008, GCC passes @code{0} as
first argument.
@end table


@node _gfortran_caf_num_images
@subsection @code{_gfortran_caf_num_images} --- Querying the maximal number of images
@cindex Coarray, _gfortran_caf_num_images

@table @asis
@item @emph{Description}:
This function returns the number of images in the current team, if
@var{distance} is 0 or the number of images in the parent team at the specified
distance. If failed is -1, the function returns the number of all images at
the specified distance; if it is 0, the function returns the number of
nonfailed images, and if it is 1, it returns the number of failed images.

@item @emph{Syntax}:
@code{int _gfortran_caf_num_images(int distance, int failed)}

@item @emph{Arguments}:
@multitable @columnfractions .15 .70
@item @var{distance} @tab the distance from this image to the ancestor.
Shall be positive.
@item @var{failed} @tab shall be -1, 0, or 1
@end multitable

@item @emph{NOTES}
This function follows TS18508. If the num_image intrinsic has no arguments,
then the compiler passes @code{distance=0} and @code{failed=-1} to the function.
@end table


@node _gfortran_caf_image_status
@subsection @code{_gfortran_caf_image_status} --- Query the status of an image
@cindex Coarray, _gfortran_caf_image_status

@table @asis
@item @emph{Description}:
Get the status of the image given by the id @var{image} of the team given by
@var{team}.  Valid results are zero, for image is ok, @code{STAT_STOPPED_IMAGE}
from the ISO_FORTRAN_ENV module to indicate that the image has been stopped and
@code{STAT_FAILED_IMAGE} also from ISO_FORTRAN_ENV to indicate that the image
has executed a @code{FAIL IMAGE} statement.

@item @emph{Syntax}:
@code{int _gfortran_caf_image_status (int image, caf_team_t * team)}

@item @emph{Arguments}:
@multitable @columnfractions .15 .70
@item @var{image} @tab the positive scalar id of the image in the current TEAM.
@item @var{team} @tab optional; team on the which the inquiry is to be
performed.
@end multitable

@item @emph{NOTES}
This function follows TS18508.  Because team-functionality is not yet
implemented a null-pointer is passed for the @var{team} argument at the moment.
@end table


@node _gfortran_caf_failed_images
@subsection @code{_gfortran_caf_failed_images} --- Get an array of the indexes of the failed images
@cindex Coarray, _gfortran_caf_failed_images

@table @asis
@item @emph{Description}:
Get an array of image indexes in the current @var{team} that have failed.  The
array is sorted ascendingly.  When @var{team} is not provided the current team
is to be used.  When @var{kind} is provided then the resulting array is of that
integer kind else it is of default integer kind.  The returns an unallocated
size zero array when no images have failed.

@item @emph{Syntax}:
@code{int _gfortran_caf_failed_images (caf_team_t * team, int * kind)}

@item @emph{Arguments}:
@multitable @columnfractions .15 .70
@item @var{team} @tab optional; team on the which the inquiry is to be
performed.
@item @var{image} @tab optional; the kind of the resulting integer array.
@end multitable

@item @emph{NOTES}
This function follows TS18508.  Because team-functionality is not yet
implemented a null-pointer is passed for the @var{team} argument at the moment.
@end table


@node _gfortran_caf_stopped_images
@subsection @code{_gfortran_caf_stopped_images} --- Get an array of the indexes of the stopped images
@cindex Coarray, _gfortran_caf_stopped_images

@table @asis
@item @emph{Description}:
Get an array of image indexes in the current @var{team} that have stopped.  The
array is sorted ascendingly.  When @var{team} is not provided the current team
is to be used.  When @var{kind} is provided then the resulting array is of that
integer kind else it is of default integer kind.  The returns an unallocated
size zero array when no images have failed.

@item @emph{Syntax}:
@code{int _gfortran_caf_stopped_images (caf_team_t * team, int * kind)}

@item @emph{Arguments}:
@multitable @columnfractions .15 .70
@item @var{team} @tab optional; team on the which the inquiry is to be
performed.
@item @var{image} @tab optional; the kind of the resulting integer array.
@end multitable

@item @emph{NOTES}
This function follows TS18508.  Because team-functionality is not yet
implemented a null-pointer is passed for the @var{team} argument at the moment.
@end table


@node _gfortran_caf_register
@subsection @code{_gfortran_caf_register} --- Registering coarrays
@cindex Coarray, _gfortran_caf_register

@table @asis
@item @emph{Description}:
Registers memory for a coarray and creates a token to identify the coarray.  The
routine is called for both coarrays with @code{SAVE} attribute and using an
explicit @code{ALLOCATE} statement.  If an error occurs and @var{STAT} is a
@code{NULL} pointer, the function shall abort with printing an error message
and starting the error termination.  If no error occurs and @var{STAT} is
present, it shall be set to zero.  Otherwise, it shall be set to a positive
value and, if not-@code{NULL}, @var{ERRMSG} shall be set to a string describing
the failure.  The routine shall register the memory provided in the
@code{DATA}-component of the array descriptor @var{DESC}, when that component
is non-@code{NULL}, else it shall allocate sufficient memory and provide a
pointer to it in the @code{DATA}-component of @var{DESC}.  The array descriptor
has rank zero, when a scalar object is to be registered and the array
descriptor may be invalid after the call to @code{_gfortran_caf_register}.
When an array is to be allocated the descriptor persists.

For @code{CAF_REGTYPE_COARRAY_STATIC} and @code{CAF_REGTYPE_COARRAY_ALLOC},
the passed size is the byte size requested.  For @code{CAF_REGTYPE_LOCK_STATIC},
@code{CAF_REGTYPE_LOCK_ALLOC} and @code{CAF_REGTYPE_CRITICAL} it is the array
size or one for a scalar.

When @code{CAF_REGTYPE_COARRAY_ALLOC_REGISTER_ONLY} is used, then only a token
for an allocatable or pointer component is created.  The @code{SIZE} parameter
is not used then.  On the contrary when
@code{CAF_REGTYPE_COARRAY_ALLOC_ALLOCATE_ONLY} is specified, then the
@var{token} needs to be registered by a previous call with regtype
@code{CAF_REGTYPE_COARRAY_ALLOC_REGISTER_ONLY} and either the memory specified
in the @var{DESC}'s data-ptr is registered or allocate when the data-ptr is
@code{NULL}.

@item @emph{Syntax}:
@code{void caf_register (size_t size, caf_register_t type, caf_token_t *token,
gfc_descriptor_t *desc, int *stat, char *errmsg, size_t errmsg_len)}

@item @emph{Arguments}:
@multitable @columnfractions .15 .70
@item @var{size} @tab For normal coarrays, the byte size of the coarray to be
allocated; for lock types and event types, the number of elements.
@item @var{type} @tab one of the caf_register_t types.
@item @var{token} @tab intent(out) An opaque pointer identifying the coarray.
@item @var{desc} @tab intent(inout) The (pseudo) array descriptor.
@item @var{stat} @tab intent(out) For allocatable coarrays, stores the STAT=;
may be @code{NULL}
@item @var{errmsg} @tab intent(out) When an error occurs, this will be set to
an error message; may be @code{NULL}
@item @var{errmsg_len} @tab the buffer size of errmsg.
@end multitable

@item @emph{NOTES}
Nonallocatable coarrays have to be registered prior use from remote images.
In order to guarantee this, they have to be registered before the main
program. This can be achieved by creating constructor functions. That is what
GCC does such that also for nonallocatable coarrays the memory is allocated and
no static memory is used.  The token permits to identify the coarray; to the
processor, the token is a nonaliasing pointer. The library can, for instance,
store the base address of the coarray in the token, some handle or a more
complicated struct.  The library may also store the array descriptor
@var{DESC} when its rank is non-zero.

For lock types, the value shall only be used for checking the allocation
status. Note that for critical blocks, the locking is only required on one
image; in the locking statement, the processor shall always pass an
image index of one for critical-block lock variables
(@code{CAF_REGTYPE_CRITICAL}). For lock types and critical-block variables,
the initial value shall be unlocked (or, respectively, not in critical
section) such as the value false; for event types, the initial state should
be no event, e.g. zero.
@end table


@node _gfortran_caf_deregister
@subsection @code{_gfortran_caf_deregister} --- Deregistering coarrays
@cindex Coarray, _gfortran_caf_deregister

@table @asis
@item @emph{Description}:
Called to free or deregister the memory of a coarray; the processor calls this
function for automatic and explicit deallocation.  In case of an error, this
function shall fail with an error message, unless the @var{STAT} variable is
not null.  The library is only expected to free memory it allocated itself
during a call to @code{_gfortran_caf_register}.

@item @emph{Syntax}:
@code{void caf_deregister (caf_token_t *token, caf_deregister_t type,
int *stat, char *errmsg, size_t errmsg_len)}

@item @emph{Arguments}:
@multitable @columnfractions .15 .70
@item @var{token} @tab the token to free.
@item @var{type} @tab the type of action to take for the coarray.  A
@code{CAF_DEREGTYPE_COARRAY_DEALLOCATE_ONLY} is allowed only for allocatable or
pointer components of derived type coarrays.  The action only deallocates the
local memory without deleting the token.
@item @var{stat} @tab intent(out) Stores the STAT=; may be NULL
@item @var{errmsg} @tab intent(out) When an error occurs, this will be set
to an error message; may be NULL
@item @var{errmsg_len} @tab the buffer size of errmsg.
@end multitable

@item @emph{NOTES}
For nonalloatable coarrays this function is never called.  If a cleanup is
required, it has to be handled via the finish, stop and error stop functions,
and via destructors.
@end table


@node _gfortran_caf_is_present
@subsection @code{_gfortran_caf_is_present} --- Query whether an allocatable or pointer component in a derived type coarray is allocated
@cindex Coarray, _gfortran_caf_is_present

@table @asis
@item @emph{Description}:
Used to query the coarray library whether an allocatable component in a derived
type coarray is allocated on a remote image.

@item @emph{Syntax}:
@code{void _gfortran_caf_is_present (caf_token_t token, int image_index,
gfc_reference_t *ref)}

@item @emph{Arguments}:
@multitable @columnfractions .15 .70
@item @var{token} @tab An opaque pointer identifying the coarray.
@item @var{image_index} @tab The ID of the remote image; must be a positive
number.
@item @var{ref} @tab A chain of references to address the allocatable or
pointer component in the derived type coarray.  The object reference needs to be
a scalar or a full array reference, respectively.
@end multitable

@end table

@node _gfortran_caf_send
@subsection @code{_gfortran_caf_send} --- Sending data from a local image to a remote image
@cindex Coarray, _gfortran_caf_send

@table @asis
@item @emph{Description}:
Called to send a scalar, an array section or a whole array from a local
to a remote image identified by the image_index.

@item @emph{Syntax}:
@code{void _gfortran_caf_send (caf_token_t token, size_t offset,
int image_index, gfc_descriptor_t *dest, caf_vector_t *dst_vector,
gfc_descriptor_t *src, int dst_kind, int src_kind, bool may_require_tmp,
int *stat)}

@item @emph{Arguments}:
@multitable @columnfractions .15 .70
@item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
@item @var{offset} @tab intent(in)  By which amount of bytes the actual data is
shifted compared to the base address of the coarray.
@item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
positive number.
@item @var{dest} @tab intent(in)  Array descriptor for the remote image for the
bounds and the size.  The @code{base_addr} shall not be accessed.
@item @var{dst_vector} @tab intent(in)  If not NULL, it contains the vector
subscript of the destination array; the values are relative to the dimension
triplet of the dest argument.
@item @var{src} @tab intent(in)  Array descriptor of the local array to be
transferred to the remote image
@item @var{dst_kind} @tab intent(in)  Kind of the destination argument
@item @var{src_kind} @tab intent(in)  Kind of the source argument
@item @var{may_require_tmp} @tab intent(in)  The variable is @code{false} when
it is known at compile time that the @var{dest} and @var{src} either cannot
overlap or overlap (fully or partially) such that walking @var{src} and
@var{dest} in element wise element order (honoring the stride value) will not
lead to wrong results.  Otherwise, the value is @code{true}.
@item @var{stat} @tab intent(out) when non-NULL give the result of the
operation, i.e., zero on success and non-zero on error.  When NULL and an error
occurs, then an error message is printed and the program is terminated.
@end multitable

@item @emph{NOTES}
It is permitted to have @var{image_index} equal the current image; the memory
of the send-to and the send-from might (partially) overlap in that case.  The
implementation has to take care that it handles this case, e.g. using
@code{memmove} which handles (partially) overlapping memory. If
@var{may_require_tmp} is true, the library might additionally create a
temporary variable, unless additional checks show that this is not required
(e.g. because walking backward is possible or because both arrays are
contiguous and @code{memmove} takes care of overlap issues).

Note that the assignment of a scalar to an array is permitted. In addition,
the library has to handle numeric-type conversion and for strings, padding
and different character kinds.
@end table


@node _gfortran_caf_get
@subsection @code{_gfortran_caf_get} --- Getting data from a remote image
@cindex Coarray, _gfortran_caf_get

@table @asis
@item @emph{Description}:
Called to get an array section or a whole array from a remote,
image identified by the image_index.

@item @emph{Syntax}:
@code{void _gfortran_caf_get (caf_token_t token, size_t offset,
int image_index, gfc_descriptor_t *src, caf_vector_t *src_vector,
gfc_descriptor_t *dest, int src_kind, int dst_kind, bool may_require_tmp,
int *stat)}

@item @emph{Arguments}:
@multitable @columnfractions .15 .70
@item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
@item @var{offset} @tab intent(in)  By which amount of bytes the actual data is
shifted compared to the base address of the coarray.
@item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
positive number.
@item @var{dest} @tab intent(out) Array descriptor of the local array to store
the data retrieved from the remote image
@item @var{src} @tab intent(in) Array descriptor for the remote image for the
bounds and the size.  The @code{base_addr} shall not be accessed.
@item @var{src_vector} @tab intent(in)  If not NULL, it contains the vector
subscript of the source array; the values are relative to the dimension
triplet of the @var{src} argument.
@item @var{dst_kind} @tab intent(in)  Kind of the destination argument
@item @var{src_kind} @tab intent(in)  Kind of the source argument
@item @var{may_require_tmp} @tab intent(in)  The variable is @code{false} when
it is known at compile time that the @var{dest} and @var{src} either cannot
overlap or overlap (fully or partially) such that walking @var{src} and
@var{dest} in element wise element order (honoring the stride value) will not
lead to wrong results.  Otherwise, the value is @code{true}.
@item @var{stat} @tab intent(out) When non-NULL give the result of the
operation, i.e., zero on success and non-zero on error.  When NULL and an error
occurs, then an error message is printed and the program is terminated.
@end multitable

@item @emph{NOTES}
It is permitted to have @var{image_index} equal the current image; the memory of
the send-to and the send-from might (partially) overlap in that case.  The
implementation has to take care that it handles this case, e.g. using
@code{memmove} which handles (partially) overlapping memory. If
@var{may_require_tmp} is true, the library might additionally create a
temporary variable, unless additional checks show that this is not required
(e.g. because walking backward is possible or because both arrays are
contiguous and @code{memmove} takes care of overlap issues).

Note that the library has to handle numeric-type conversion and for strings,
padding and different character kinds.
@end table


@node _gfortran_caf_sendget
@subsection @code{_gfortran_caf_sendget} --- Sending data between remote images
@cindex Coarray, _gfortran_caf_sendget

@table @asis
@item @emph{Description}:
Called to send a scalar, an array section or a whole array from a remote image
identified by the @var{src_image_index} to a remote image identified by the
@var{dst_image_index}.

@item @emph{Syntax}:
@code{void _gfortran_caf_sendget (caf_token_t dst_token, size_t dst_offset,
int dst_image_index, gfc_descriptor_t *dest, caf_vector_t *dst_vector,
caf_token_t src_token, size_t src_offset, int src_image_index,
gfc_descriptor_t *src, caf_vector_t *src_vector, int dst_kind, int src_kind,
bool may_require_tmp, int *stat)}

@item @emph{Arguments}:
@multitable @columnfractions .15 .70
@item @var{dst_token} @tab intent(in)  An opaque pointer identifying the
destination coarray.
@item @var{dst_offset} @tab intent(in)  By which amount of bytes the actual data
is shifted compared to the base address of the destination coarray.
@item @var{dst_image_index} @tab intent(in)  The ID of the destination remote
image; must be a positive number.
@item @var{dest} @tab intent(in) Array descriptor for the destination
remote image for the bounds and the size.  The @code{base_addr} shall not be
accessed.
@item @var{dst_vector} @tab intent(int)  If not NULL, it contains the vector
subscript of the destination array; the values are relative to the dimension
triplet of the @var{dest} argument.
@item @var{src_token} @tab intent(in)  An opaque pointer identifying the source
coarray.
@item @var{src_offset} @tab intent(in)  By which amount of bytes the actual data
is shifted compared to the base address of the source coarray.
@item @var{src_image_index} @tab intent(in)  The ID of the source remote image;
must be a positive number.
@item @var{src} @tab intent(in) Array descriptor of the local array to be
transferred to the remote image.
@item @var{src_vector} @tab intent(in) Array descriptor of the local array to
be transferred to the remote image
@item @var{dst_kind} @tab intent(in)  Kind of the destination argument
@item @var{src_kind} @tab intent(in)  Kind of the source argument
@item @var{may_require_tmp} @tab intent(in)  The variable is @code{false} when
it is known at compile time that the @var{dest} and @var{src} either cannot
overlap or overlap (fully or partially) such that walking @var{src} and
@var{dest} in element wise element order (honoring the stride value) will not
lead to wrong results.  Otherwise, the value is @code{true}.
@item @var{stat} @tab intent(out) when non-NULL give the result of the
operation, i.e., zero on success and non-zero on error.  When NULL and an error
occurs, then an error message is printed and the program is terminated.
@end multitable

@item @emph{NOTES}
It is permitted to have the same image index for both @var{src_image_index} and
@var{dst_image_index}; the memory of the send-to and the send-from might
(partially) overlap in that case.  The implementation has to take care that it
handles this case, e.g. using @code{memmove} which handles (partially)
overlapping memory.  If @var{may_require_tmp} is true, the library
might additionally create a temporary variable, unless additional checks show
that this is not required (e.g. because walking backward is possible or because
both arrays are contiguous and @code{memmove} takes care of overlap issues).

Note that the assignment of a scalar to an array is permitted. In addition,
the library has to handle numeric-type conversion and for strings, padding and
different character kinds.
@end table

@node _gfortran_caf_send_by_ref
@subsection @code{_gfortran_caf_send_by_ref} --- Sending data from a local image to a remote image with enhanced referencing options
@cindex Coarray, _gfortran_caf_send_by_ref

@table @asis
@item @emph{Description}:
Called to send a scalar, an array section or a whole array from a local to a
remote image identified by the @var{image_index}.

@item @emph{Syntax}:
@code{void _gfortran_caf_send_by_ref (caf_token_t token, int image_index,
gfc_descriptor_t *src, caf_reference_t *refs, int dst_kind, int src_kind,
bool may_require_tmp, bool dst_reallocatable, int *stat, int dst_type)}

@item @emph{Arguments}:
@multitable @columnfractions .15 .70
@item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
@item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
positive number.
@item @var{src} @tab intent(in) Array descriptor of the local array to be
transferred to the remote image
@item @var{refs} @tab intent(in) The references on the remote array to store
the data given by src.  Guaranteed to have at least one entry.
@item @var{dst_kind} @tab intent(in)  Kind of the destination argument
@item @var{src_kind} @tab intent(in)  Kind of the source argument
@item @var{may_require_tmp} @tab intent(in)  The variable is @code{false} when
it is known at compile time that the @var{dest} and @var{src} either cannot
overlap or overlap (fully or partially) such that walking @var{src} and
@var{dest} in element wise element order (honoring the stride value) will not
lead to wrong results.  Otherwise, the value is @code{true}.
@item @var{dst_reallocatable} @tab intent(in)  Set when the destination is of
allocatable or pointer type and the refs will allow reallocation, i.e., the ref
is a full array or component ref.
@item @var{stat} @tab intent(out) When non-@code{NULL} give the result of the
operation, i.e., zero on success and non-zero on error.  When @code{NULL} and
an error occurs, then an error message is printed and the program is terminated.
@item @var{dst_type} @tab intent(in)  Give the type of the destination.  When
the destination is not an array, than the precise type, e.g. of a component in
a derived type, is not known, but provided here.
@end multitable

@item @emph{NOTES}
It is permitted to have @var{image_index} equal the current image; the memory of
the send-to and the send-from might (partially) overlap in that case.  The
implementation has to take care that it handles this case, e.g. using
@code{memmove} which handles (partially) overlapping memory.  If
@var{may_require_tmp} is true, the library might additionally create a
temporary variable, unless additional checks show that this is not required
(e.g. because walking backward is possible or because both arrays are
contiguous and @code{memmove} takes care of overlap issues).

Note that the assignment of a scalar to an array is permitted.  In addition,
the library has to handle numeric-type conversion and for strings, padding
and different character kinds.

Because of the more complicated references possible some operations may be
unsupported by certain libraries.  The library is expected to issue a precise
error message why the operation is not permitted.
@end table


@node _gfortran_caf_get_by_ref
@subsection @code{_gfortran_caf_get_by_ref} --- Getting data from a remote image using enhanced references
@cindex Coarray, _gfortran_caf_get_by_ref

@table @asis
@item @emph{Description}:
Called to get a scalar, an array section or a whole array from a remote image
identified by the @var{image_index}.

@item @emph{Syntax}:
@code{void _gfortran_caf_get_by_ref (caf_token_t token, int image_index,
caf_reference_t *refs, gfc_descriptor_t *dst, int dst_kind, int src_kind,
bool may_require_tmp, bool dst_reallocatable, int *stat, int src_type)}

@item @emph{Arguments}:
@multitable @columnfractions .15 .70
@item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
@item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
positive number.
@item @var{refs} @tab intent(in) The references to apply to the remote structure
to get the data.
@item @var{dst} @tab intent(in) Array descriptor of the local array to store
the data transferred from the remote image.  May be reallocated where needed
and when @var{DST_REALLOCATABLE} allows it.
@item @var{dst_kind} @tab intent(in)  Kind of the destination argument
@item @var{src_kind} @tab intent(in)  Kind of the source argument
@item @var{may_require_tmp} @tab intent(in)  The variable is @code{false} when
it is known at compile time that the @var{dest} and @var{src} either cannot
overlap or overlap (fully or partially) such that walking @var{src} and
@var{dest} in element wise element order (honoring the stride value) will not
lead to wrong results.  Otherwise, the value is @code{true}.
@item @var{dst_reallocatable} @tab intent(in)  Set when @var{DST} is of
allocatable or pointer type and its refs allow reallocation, i.e., the full
array or a component is referenced.
@item @var{stat} @tab intent(out) When non-@code{NULL} give the result of the
operation, i.e., zero on success and non-zero on error.  When @code{NULL} and an
error occurs, then an error message is printed and the program is terminated.
@item @var{src_type} @tab intent(in)  Give the type of the source.  When the
source is not an array, than the precise type, e.g. of a component in a
derived type, is not known, but provided here.
@end multitable

@item @emph{NOTES}
It is permitted to have @code{image_index} equal the current image; the memory
of the send-to and the send-from might (partially) overlap in that case.  The
implementation has to take care that it handles this case, e.g. using
@code{memmove} which handles (partially) overlapping memory.  If
@var{may_require_tmp} is true, the library might additionally create a
temporary variable, unless additional checks show that this is not required
(e.g. because walking backward is possible or because both arrays are
contiguous and @code{memmove} takes care of overlap issues).

Note that the library has to handle numeric-type conversion and for strings,
padding and different character kinds.

Because of the more complicated references possible some operations may be
unsupported by certain libraries.  The library is expected to issue a precise
error message why the operation is not permitted.
@end table


@node _gfortran_caf_sendget_by_ref
@subsection @code{_gfortran_caf_sendget_by_ref} --- Sending data between remote images using enhanced references on both sides
@cindex Coarray, _gfortran_caf_sendget_by_ref

@table @asis
@item @emph{Description}:
Called to send a scalar, an array section or a whole array from a remote image
identified by the @var{src_image_index} to a remote image identified by the
@var{dst_image_index}.

@item @emph{Syntax}:
@code{void _gfortran_caf_sendget_by_ref (caf_token_t dst_token,
int dst_image_index, caf_reference_t *dst_refs,
caf_token_t src_token, int src_image_index, caf_reference_t *src_refs,
int dst_kind, int src_kind, bool may_require_tmp, int *dst_stat,
int *src_stat, int dst_type, int src_type)}

@item @emph{Arguments}:
@multitable @columnfractions .15 .70
@item @var{dst_token} @tab intent(in)  An opaque pointer identifying the
destination coarray.
@item @var{dst_image_index} @tab intent(in)  The ID of the destination remote
image; must be a positive number.
@item @var{dst_refs} @tab intent(in) The references on the remote array to store
the data given by the source.  Guaranteed to have at least one entry.
@item @var{src_token} @tab intent(in)  An opaque pointer identifying the source
coarray.
@item @var{src_image_index} @tab intent(in)  The ID of the source remote image;
must be a positive number.
@item @var{src_refs} @tab intent(in) The references to apply to the remote
structure to get the data.
@item @var{dst_kind} @tab intent(in)  Kind of the destination argument
@item @var{src_kind} @tab intent(in)  Kind of the source argument
@item @var{may_require_tmp} @tab intent(in)  The variable is @code{false} when
it is known at compile time that the @var{dest} and @var{src} either cannot
overlap or overlap (fully or partially) such that walking @var{src} and
@var{dest} in element wise element order (honoring the stride value) will not
lead to wrong results.  Otherwise, the value is @code{true}.
@item @var{dst_stat} @tab intent(out) when non-@code{NULL} give the result of
the send-operation, i.e., zero on success and non-zero on error.  When
@code{NULL} and an error occurs, then an error message is printed and the
program is terminated.
@item @var{src_stat} @tab intent(out) When non-@code{NULL} give the result of
the get-operation, i.e., zero on success and non-zero on error.  When
@code{NULL} and an error occurs, then an error message is printed and the
program is terminated.
@item @var{dst_type} @tab intent(in)  Give the type of the destination.  When
the destination is not an array, than the precise type, e.g. of a component in
a derived type, is not known, but provided here.
@item @var{src_type} @tab intent(in)  Give the type of the source.  When the
source is not an array, than the precise type, e.g. of a component in a
derived type, is not known, but provided here.
@end multitable

@item @emph{NOTES}
It is permitted to have the same image index for both @var{src_image_index} and
@var{dst_image_index}; the memory of the send-to and the send-from might
(partially) overlap in that case.  The implementation has to take care that it
handles this case, e.g. using @code{memmove} which handles (partially)
overlapping memory.  If @var{may_require_tmp} is true, the library
might additionally create a temporary variable, unless additional checks show
that this is not required (e.g. because walking backward is possible or because
both arrays are contiguous and @code{memmove} takes care of overlap issues).

Note that the assignment of a scalar to an array is permitted.  In addition,
the library has to handle numeric-type conversion and for strings, padding and
different character kinds.

Because of the more complicated references possible some operations may be
unsupported by certain libraries.  The library is expected to issue a precise
error message why the operation is not permitted.
@end table


@node _gfortran_caf_lock
@subsection @code{_gfortran_caf_lock} --- Locking a lock variable
@cindex Coarray, _gfortran_caf_lock

@table @asis
@item @emph{Description}:
Acquire a lock on the given image on a scalar locking variable or for the
given array element for an array-valued variable.  If the @var{acquired_lock}
is @code{NULL}, the function returns after having obtained the lock.  If it is
non-@code{NULL}, then @var{acquired_lock} is assigned the value true (one) when
the lock could be obtained and false (zero) otherwise.  Locking a lock variable
which has already been locked by the same image is an error.

@item @emph{Syntax}:
@code{void _gfortran_caf_lock (caf_token_t token, size_t index, int image_index,
int *acquired_lock, int *stat, char *errmsg, size_t errmsg_len)}

@item @emph{Arguments}:
@multitable @columnfractions .15 .70
@item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
@item @var{index} @tab intent(in)  Array index; first array index is 0.  For
scalars, it is always 0.
@item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
positive number.
@item @var{acquired_lock} @tab intent(out) If not NULL, it returns whether lock
could be obtained.
@item @var{stat} @tab intent(out) Stores the STAT=; may be NULL.
@item @var{errmsg} @tab intent(out) When an error occurs, this will be set to
an error message; may be NULL.
@item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
@end multitable

@item @emph{NOTES}
This function is also called for critical blocks; for those, the array index
is always zero and the image index is one.  Libraries are permitted to use other
images for critical-block locking variables.
@end table

@node _gfortran_caf_unlock
@subsection @code{_gfortran_caf_lock} --- Unlocking a lock variable
@cindex Coarray, _gfortran_caf_unlock

@table @asis
@item @emph{Description}:
Release a lock on the given image on a scalar locking variable or for the
given array element for an array-valued variable. Unlocking a lock variable
which is unlocked or has been locked by a different image is an error.

@item @emph{Syntax}:
@code{void _gfortran_caf_unlock (caf_token_t token, size_t index, int image_index,
int *stat, char *errmsg, size_t errmsg_len)}

@item @emph{Arguments}:
@multitable @columnfractions .15 .70
@item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
@item @var{index} @tab intent(in)  Array index; first array index is 0.  For
scalars, it is always 0.
@item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
positive number.
@item @var{stat} @tab intent(out) For allocatable coarrays, stores the STAT=;
may be NULL.
@item @var{errmsg} @tab intent(out) When an error occurs, this will be set to
an error message; may be NULL.
@item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
@end multitable

@item @emph{NOTES}
This function is also called for critical block; for those, the array index
is always zero and the image index is one.  Libraries are permitted to use other
images for critical-block locking variables.
@end table

@node _gfortran_caf_event_post
@subsection @code{_gfortran_caf_event_post} --- Post an event
@cindex Coarray, _gfortran_caf_event_post

@table @asis
@item @emph{Description}:
Increment the event count of the specified event variable.

@item @emph{Syntax}:
@code{void _gfortran_caf_event_post (caf_token_t token, size_t index,
int image_index, int *stat, char *errmsg, size_t errmsg_len)}

@item @emph{Arguments}:
@multitable @columnfractions .15 .70
@item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
@item @var{index} @tab intent(in)  Array index; first array index is 0.  For
scalars, it is always 0.
@item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
positive number; zero indicates the current image, when accessed noncoindexed.
@item @var{stat} @tab intent(out)  Stores the STAT=; may be NULL.
@item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
an error message; may be NULL.
@item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
@end multitable

@item @emph{NOTES}
This acts like an atomic add of one to the remote image's event variable.
The statement is an image-control statement but does not imply sync memory.
Still, all preceding push communications of this image to the specified
remote image have to be completed before @code{event_wait} on the remote
image returns.
@end table



@node _gfortran_caf_event_wait
@subsection @code{_gfortran_caf_event_wait} --- Wait that an event occurred
@cindex Coarray, _gfortran_caf_event_wait

@table @asis
@item @emph{Description}:
Wait until the event count has reached at least the specified
@var{until_count}; if so, atomically decrement the event variable by this
amount and return.

@item @emph{Syntax}:
@code{void _gfortran_caf_event_wait (caf_token_t token, size_t index,
int until_count, int *stat, char *errmsg, size_t errmsg_len)}

@item @emph{Arguments}:
@multitable @columnfractions .15 .70
@item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
@item @var{index} @tab intent(in)  Array index; first array index is 0.  For
scalars, it is always 0.
@item @var{until_count} @tab intent(in)  The number of events which have to be
available before the function returns.
@item @var{stat} @tab intent(out)  Stores the STAT=; may be NULL.
@item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
an error message; may be NULL.
@item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
@end multitable

@item @emph{NOTES}
This function only operates on a local coarray. It acts like a loop checking
atomically the value of the event variable, breaking if the value is greater
or equal the requested number of counts. Before the function returns, the
event variable has to be decremented by the requested @var{until_count} value.
A possible implementation would be a busy loop for a certain number of spins
(possibly depending on the number of threads relative to the number of available
cores) followed by another waiting strategy such as a sleeping wait (possibly
with an increasing number of sleep time) or, if possible, a futex wait.

The statement is an image-control statement but does not imply sync memory.
Still, all preceding push communications of this image to the specified
remote image have to be completed before @code{event_wait} on the remote
image returns.
@end table



@node _gfortran_caf_event_query
@subsection @code{_gfortran_caf_event_query} --- Query event count
@cindex Coarray, _gfortran_caf_event_query

@table @asis
@item @emph{Description}:
Return the event count of the specified event variable.

@item @emph{Syntax}:
@code{void _gfortran_caf_event_query (caf_token_t token, size_t index,
int image_index, int *count, int *stat)}

@item @emph{Arguments}:
@multitable @columnfractions .15 .70
@item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
@item @var{index} @tab intent(in)  Array index; first array index is 0.  For
scalars, it is always 0.
@item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
positive number; zero indicates the current image when accessed noncoindexed.
@item @var{count} @tab intent(out)  The number of events currently posted to
the event variable.
@item @var{stat} @tab intent(out)  Stores the STAT=; may be NULL.
@end multitable

@item @emph{NOTES}
The typical use is to check the local event variable to only call
@code{event_wait} when the data is available. However, a coindexed variable
is permitted; there is no ordering or synchronization implied.  It acts like
an atomic fetch of the value of the event variable.
@end table



@node _gfortran_caf_sync_all
@subsection @code{_gfortran_caf_sync_all} --- All-image barrier
@cindex Coarray, _gfortran_caf_sync_all

@table @asis
@item @emph{Description}:
Synchronization of all images in the current team; the program only continues
on a given image after this function has been called on all images of the
current team.  Additionally, it ensures that all pending data transfers of
previous segment have completed.

@item @emph{Syntax}:
@code{void _gfortran_caf_sync_all (int *stat, char *errmsg, size_t errmsg_len)}

@item @emph{Arguments}:
@multitable @columnfractions .15 .70
@item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
@item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
an error message; may be NULL.
@item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
@end multitable
@end table



@node _gfortran_caf_sync_images
@subsection @code{_gfortran_caf_sync_images} --- Barrier for selected images
@cindex Coarray, _gfortran_caf_sync_images

@table @asis
@item @emph{Description}:
Synchronization between the specified images; the program only continues on a
given image after this function has been called on all images specified for
that image. Note that one image can wait for all other images in the current
team (e.g. via @code{sync images(*)}) while those only wait for that specific
image.  Additionally, @code{sync images} ensures that all pending data
transfers of previous segments have completed.

@item @emph{Syntax}:
@code{void _gfortran_caf_sync_images (int count, int images[], int *stat,
char *errmsg, size_t errmsg_len)}

@item @emph{Arguments}:
@multitable @columnfractions .15 .70
@item @var{count} @tab intent(in)  The number of images which are provided in
the next argument.  For a zero-sized array, the value is zero.  For
@code{sync images (*)}, the value is @math{-1}.
@item @var{images} @tab intent(in)  An array with the images provided by the
user.  If @var{count} is zero, a NULL pointer is passed.
@item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
@item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
an error message; may be NULL.
@item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
@end multitable
@end table



@node _gfortran_caf_sync_memory
@subsection @code{_gfortran_caf_sync_memory} --- Wait for completion of segment-memory operations
@cindex Coarray, _gfortran_caf_sync_memory

@table @asis
@item @emph{Description}:
Acts as optimization barrier between different segments. It also ensures that
all pending memory operations of this image have been completed.

@item @emph{Syntax}:
@code{void _gfortran_caf_sync_memory (int *stat, char *errmsg, size_t errmsg_len)}

@item @emph{Arguments}:
@multitable @columnfractions .15 .70
@item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
@item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
an error message; may be NULL.
@item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
@end multitable

@item @emph{NOTE} A simple implementation could be
@code{__asm__ __volatile__ ("":::"memory")} to prevent code movements.
@end table



@node _gfortran_caf_error_stop
@subsection @code{_gfortran_caf_error_stop} --- Error termination with exit code
@cindex Coarray, _gfortran_caf_error_stop

@table @asis
@item @emph{Description}:
Invoked for an @code{ERROR STOP} statement which has an integer argument.  The
function should terminate the program with the specified exit code.


@item @emph{Syntax}:
@code{void _gfortran_caf_error_stop (int error)}

@item @emph{Arguments}:
@multitable @columnfractions .15 .70
@item @var{error} @tab intent(in)  The exit status to be used.
@end multitable
@end table



@node _gfortran_caf_error_stop_str
@subsection @code{_gfortran_caf_error_stop_str} --- Error termination with string
@cindex Coarray, _gfortran_caf_error_stop_str

@table @asis
@item @emph{Description}:
Invoked for an @code{ERROR STOP} statement which has a string as argument.  The
function should terminate the program with a nonzero-exit code.

@item @emph{Syntax}:
@code{void _gfortran_caf_error_stop (const char *string, size_t len)}

@item @emph{Arguments}:
@multitable @columnfractions .15 .70
@item @var{string} @tab intent(in)  the error message (not zero terminated)
@item @var{len} @tab intent(in)  the length of the string
@end multitable
@end table



@node _gfortran_caf_fail_image
@subsection @code{_gfortran_caf_fail_image} --- Mark the image failed and end its execution
@cindex Coarray, _gfortran_caf_fail_image

@table @asis
@item @emph{Description}:
Invoked for an @code{FAIL IMAGE} statement.  The function should terminate the
current image.

@item @emph{Syntax}:
@code{void _gfortran_caf_fail_image ()}

@item @emph{NOTES}
This function follows TS18508.
@end table



@node _gfortran_caf_atomic_define
@subsection @code{_gfortran_caf_atomic_define} --- Atomic variable assignment
@cindex Coarray, _gfortran_caf_atomic_define

@table @asis
@item @emph{Description}:
Assign atomically a value to an integer or logical variable.

@item @emph{Syntax}:
@code{void _gfortran_caf_atomic_define (caf_token_t token, size_t offset,
int image_index, void *value, int *stat, int type, int kind)}

@item @emph{Arguments}:
@multitable @columnfractions .15 .70
@item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
@item @var{offset} @tab intent(in)  By which amount of bytes the actual data is
shifted compared to the base address of the coarray.
@item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
positive number; zero indicates the current image when used noncoindexed.
@item @var{value} @tab intent(in)  the value to be assigned, passed by reference
@item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
@item @var{type} @tab intent(in)  The data type, i.e. @code{BT_INTEGER} (1) or
@code{BT_LOGICAL} (2).
@item @var{kind} @tab intent(in)  The kind value (only 4; always @code{int})
@end multitable
@end table



@node _gfortran_caf_atomic_ref
@subsection @code{_gfortran_caf_atomic_ref} --- Atomic variable reference
@cindex Coarray, _gfortran_caf_atomic_ref

@table @asis
@item @emph{Description}:
Reference atomically a value of a kind-4 integer or logical variable.

@item @emph{Syntax}:
@code{void _gfortran_caf_atomic_ref (caf_token_t token, size_t offset,
int image_index, void *value, int *stat, int type, int kind)}

@item @emph{Arguments}:
@multitable @columnfractions .15 .70
@item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
@item @var{offset} @tab intent(in)  By which amount of bytes the actual data is
shifted compared to the base address of the coarray.
@item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
positive number; zero indicates the current image when used noncoindexed.
@item @var{value} @tab intent(out)  The variable assigned the atomically
referenced variable.
@item @var{stat} @tab intent(out) Stores the status STAT= and may be NULL.
@item @var{type} @tab the data type, i.e. @code{BT_INTEGER} (1) or
@code{BT_LOGICAL} (2).
@item @var{kind} @tab The kind value (only 4; always @code{int})
@end multitable
@end table



@node _gfortran_caf_atomic_cas
@subsection @code{_gfortran_caf_atomic_cas} --- Atomic compare and swap
@cindex Coarray, _gfortran_caf_atomic_cas

@table @asis
@item @emph{Description}:
Atomic compare and swap of a kind-4 integer or logical variable. Assigns
atomically the specified value to the atomic variable, if the latter has
the value specified by the passed condition value.

@item @emph{Syntax}:
@code{void _gfortran_caf_atomic_cas (caf_token_t token, size_t offset,
int image_index, void *old, void *compare, void *new_val, int *stat,
int type, int kind)}

@item @emph{Arguments}:
@multitable @columnfractions .15 .70
@item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
@item @var{offset} @tab intent(in)  By which amount of bytes the actual data is
shifted compared to the base address of the coarray.
@item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
positive number; zero indicates the current image when used noncoindexed.
@item @var{old} @tab intent(out)  The value which the atomic variable had
just before the cas operation.
@item @var{compare} @tab intent(in)  The value used for comparision.
@item @var{new_val} @tab intent(in)  The new value for the atomic variable,
assigned to the atomic variable, if @code{compare} equals the value of the
atomic variable.
@item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
@item @var{type} @tab intent(in)  the data type, i.e. @code{BT_INTEGER} (1) or
@code{BT_LOGICAL} (2).
@item @var{kind} @tab intent(in)  The kind value (only 4; always @code{int})
@end multitable
@end table



@node _gfortran_caf_atomic_op
@subsection @code{_gfortran_caf_atomic_op} --- Atomic operation
@cindex Coarray, _gfortran_caf_atomic_op

@table @asis
@item @emph{Description}:
Apply an operation atomically to an atomic integer or logical variable.
After the operation, @var{old} contains the value just before the operation,
which, respectively, adds (GFC_CAF_ATOMIC_ADD) atomically the @code{value} to
the atomic integer variable or does a bitwise AND, OR or exclusive OR
between the atomic variable and @var{value}; the result is then stored in the
atomic variable.

@item @emph{Syntax}:
@code{void _gfortran_caf_atomic_op (int op, caf_token_t token, size_t offset,
int image_index, void *value, void *old, int *stat, int type, int kind)}

@item @emph{Arguments}:
@multitable @columnfractions .15 .70
@item @var{op} @tab intent(in)  the operation to be performed; possible values
@code{GFC_CAF_ATOMIC_ADD} (1), @code{GFC_CAF_ATOMIC_AND} (2),
@code{GFC_CAF_ATOMIC_OR} (3), @code{GFC_CAF_ATOMIC_XOR} (4).
@item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
@item @var{offset} @tab intent(in)  By which amount of bytes the actual data is
shifted compared to the base address of the coarray.
@item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
positive number; zero indicates the current image when used noncoindexed.
@item @var{old} @tab intent(out)  The value which the atomic variable had
just before the atomic operation.
@item @var{val} @tab intent(in)  The new value for the atomic variable,
assigned to the atomic variable, if @code{compare} equals the value of the
atomic variable.
@item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
@item @var{type} @tab intent(in)  the data type, i.e. @code{BT_INTEGER} (1) or
@code{BT_LOGICAL} (2)
@item @var{kind} @tab intent(in)  the kind value (only 4; always @code{int})
@end multitable
@end table




@node _gfortran_caf_co_broadcast
@subsection @code{_gfortran_caf_co_broadcast} --- Sending data to all images
@cindex Coarray, _gfortran_caf_co_broadcast

@table @asis
@item @emph{Description}:
Distribute a value from a given image to all other images in the team. Has to
be called collectively.

@item @emph{Syntax}:
@code{void _gfortran_caf_co_broadcast (gfc_descriptor_t *a,
int source_image, int *stat, char *errmsg, size_t errmsg_len)}

@item @emph{Arguments}:
@multitable @columnfractions .15 .70
@item @var{a} @tab intent(inout)  An array descriptor with the data to be
broadcasted (on @var{source_image}) or to be received (other images).
@item @var{source_image} @tab intent(in)  The ID of the image from which the
data should be broadcasted.
@item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
@item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
an error message; may be NULL.
@item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg.
@end multitable
@end table



@node _gfortran_caf_co_max
@subsection @code{_gfortran_caf_co_max} --- Collective maximum reduction
@cindex Coarray, _gfortran_caf_co_max

@table @asis
@item @emph{Description}:
Calculates for each array element of the variable @var{a} the maximum
value for that element in the current team; if @var{result_image} has the
value 0, the result shall be stored on all images, otherwise, only on the
specified image. This function operates on numeric values and character
strings.

@item @emph{Syntax}:
@code{void _gfortran_caf_co_max (gfc_descriptor_t *a, int result_image,
int *stat, char *errmsg, int a_len, size_t errmsg_len)}

@item @emph{Arguments}:
@multitable @columnfractions .15 .70
@item @var{a} @tab intent(inout)  An array descriptor for the data to be
processed.  On the destination image(s) the result overwrites the old content.
@item @var{result_image} @tab intent(in)  The ID of the image to which the
reduced value should be copied to; if zero, it has to be copied to all images.
@item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
@item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
an error message; may be NULL.
@item @var{a_len} @tab intent(in)  the string length of argument @var{a}
@item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
@end multitable

@item @emph{NOTES}
If @var{result_image} is nonzero, the data in the array descriptor @var{a} on
all images except of the specified one become undefined; hence, the library may
make use of this.
@end table



@node _gfortran_caf_co_min
@subsection @code{_gfortran_caf_co_min} --- Collective minimum reduction
@cindex Coarray, _gfortran_caf_co_min

@table @asis
@item @emph{Description}:
Calculates for each array element of the variable @var{a} the minimum
value for that element in the current team; if @var{result_image} has the
value 0, the result shall be stored on all images, otherwise, only on the
specified image. This function operates on numeric values and character
strings.

@item @emph{Syntax}:
@code{void _gfortran_caf_co_min (gfc_descriptor_t *a, int result_image,
int *stat, char *errmsg, int a_len, size_t errmsg_len)}

@item @emph{Arguments}:
@multitable @columnfractions .15 .70
@item @var{a} @tab intent(inout)  An array descriptor for the data to be
processed.  On the destination image(s) the result overwrites the old content.
@item @var{result_image} @tab intent(in)  The ID of the image to which the
reduced value should be copied to; if zero, it has to be copied to all images.
@item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
@item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
an error message; may be NULL.
@item @var{a_len} @tab intent(in)  the string length of argument @var{a}
@item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
@end multitable

@item @emph{NOTES}
If @var{result_image} is nonzero, the data in the array descriptor @var{a} on
all images except of the specified one become undefined; hence, the library may
make use of this.
@end table



@node _gfortran_caf_co_sum
@subsection @code{_gfortran_caf_co_sum} --- Collective summing reduction
@cindex Coarray, _gfortran_caf_co_sum

@table @asis
@item @emph{Description}:
Calculates for each array element of the variable @var{a} the sum of all
values for that element in the current team; if @var{result_image} has the
value 0, the result shall be stored on all images, otherwise, only on the
specified image.  This function operates on numeric values only.

@item @emph{Syntax}:
@code{void _gfortran_caf_co_sum (gfc_descriptor_t *a, int result_image,
int *stat, char *errmsg, size_t errmsg_len)}

@item @emph{Arguments}:
@multitable @columnfractions .15 .70
@item @var{a} @tab intent(inout)  An array descriptor with the data to be
processed.  On the destination image(s) the result overwrites the old content.
@item @var{result_image} @tab intent(in)  The ID of the image to which the
reduced value should be copied to; if zero, it has to be copied to all images.
@item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
@item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
an error message; may be NULL.
@item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
@end multitable

@item @emph{NOTES}
If @var{result_image} is nonzero, the data in the array descriptor @var{a} on
all images except of the specified one become undefined; hence, the library may
make use of this.
@end table



@node _gfortran_caf_co_reduce
@subsection @code{_gfortran_caf_co_reduce} --- Generic collective reduction
@cindex Coarray, _gfortran_caf_co_reduce

@table @asis
@item @emph{Description}:
Calculates for each array element of the variable @var{a} the reduction
value for that element in the current team; if @var{result_image} has the
value 0, the result shall be stored on all images, otherwise, only on the
specified image.  The @var{opr} is a pure function doing a mathematically
commutative and associative operation.

The @var{opr_flags} denote the following; the values are bitwise ored.
@code{GFC_CAF_BYREF} (1) if the result should be returned
by reference; @code{GFC_CAF_HIDDENLEN} (2) whether the result and argument
string lengths shall be specified as hidden arguments;
@code{GFC_CAF_ARG_VALUE} (4) whether the arguments shall be passed by value,
@code{GFC_CAF_ARG_DESC} (8) whether the arguments shall be passed by descriptor.


@item @emph{Syntax}:
@code{void _gfortran_caf_co_reduce (gfc_descriptor_t *a,
void * (*opr) (void *, void *), int opr_flags, int result_image,
int *stat, char *errmsg, int a_len, size_t errmsg_len)}

@item @emph{Arguments}:
@multitable @columnfractions .15 .70
@item @var{a} @tab intent(inout)  An array descriptor with the data to be
processed.  On the destination image(s) the result overwrites the old content.
@item @var{opr} @tab intent(in)  Function pointer to the reduction function
@item @var{opr_flags} @tab intent(in)  Flags regarding the reduction function
@item @var{result_image} @tab intent(in)  The ID of the image to which the
reduced value should be copied to; if zero, it has to be copied to all images.
@item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
@item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
an error message; may be NULL.
@item @var{a_len} @tab intent(in)  the string length of argument @var{a}
@item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
@end multitable

@item @emph{NOTES}
If @var{result_image} is nonzero, the data in the array descriptor @var{a} on
all images except of the specified one become undefined; hence, the library may
make use of this.

For character arguments, the result is passed as first argument, followed
by the result string length, next come the two string arguments, followed
by the two hidden string length arguments.  With C binding, there are no hidden
arguments and by-reference passing and either only a single character is passed
or an array descriptor.
@end table


@c Intrinsic Procedures
@c ---------------------------------------------------------------------

@include intrinsic.texi


@tex
\blankpart
@end tex

@c ---------------------------------------------------------------------
@c Contributing
@c ---------------------------------------------------------------------

@node Contributing
@unnumbered Contributing
@cindex Contributing

Free software is only possible if people contribute to efforts
to create it.
We're always in need of more people helping out with ideas
and comments, writing documentation and contributing code.

If you want to contribute to GNU Fortran,
have a look at the long lists of projects you can take on.
Some of these projects are small,
some of them are large;
some are completely orthogonal to the rest of what is
happening on GNU Fortran,
but others are ``mainstream'' projects in need of enthusiastic hackers.
All of these projects are important!
We will eventually get around to the things here,
but they are also things doable by someone who is willing and able.

@menu
* Contributors::
* Projects::
@end menu


@node Contributors
@section Contributors to GNU Fortran
@cindex Contributors
@cindex Credits
@cindex Authors

Most of the parser was hand-crafted by @emph{Andy Vaught}, who is
also the initiator of the whole project.  Thanks Andy!
Most of the interface with GCC was written by @emph{Paul Brook}.

The following individuals have contributed code and/or
ideas and significant help to the GNU Fortran project
(in alphabetical order):

@itemize @minus
@item Janne Blomqvist
@item Steven Bosscher
@item Paul Brook
@item Tobias Burnus
@item Fran@,{c}ois-Xavier Coudert
@item Bud Davis
@item Jerry DeLisle
@item Erik Edelmann
@item Bernhard Fischer
@item Daniel Franke
@item Richard Guenther
@item Richard Henderson
@item Katherine Holcomb
@item Jakub Jelinek
@item Niels Kristian Bech Jensen
@item Steven Johnson
@item Steven G. Kargl
@item Thomas Koenig
@item Asher Langton
@item H. J. Lu
@item Toon Moene
@item Brooks Moses
@item Andrew Pinski
@item Tim Prince
@item Christopher D. Rickett
@item Richard Sandiford
@item Tobias Schl@"uter
@item Roger Sayle
@item Paul Thomas
@item Andy Vaught
@item Feng Wang
@item Janus Weil
@item Daniel Kraft
@end itemize

The following people have contributed bug reports,
smaller or larger patches,
and much needed feedback and encouragement for the
GNU Fortran project:

@itemize @minus
@item Bill Clodius
@item Dominique d'Humi@`eres
@item Kate Hedstrom
@item Erik Schnetter
@item Gerhard Steinmetz
@item Joost VandeVondele
@end itemize

Many other individuals have helped debug,
test and improve the GNU Fortran compiler over the past few years,
and we welcome you to do the same!
If you already have done so,
and you would like to see your name listed in the
list above, please contact us.


@node Projects
@section Projects

@table @emph

@item Help build the test suite
Solicit more code for donation to the test suite: the more extensive the
testsuite, the smaller the risk of breaking things in the future! We can
keep code private on request.

@item Bug hunting/squishing
Find bugs and write more test cases! Test cases are especially very
welcome, because it allows us to concentrate on fixing bugs instead of
isolating them.  Going through the bugzilla database at
@url{https://gcc.gnu.org/@/bugzilla/} to reduce testcases posted there and
add more information (for example, for which version does the testcase
work, for which versions does it fail?) is also very helpful.

@item Missing features
For a larger project, consider working on the missing features required for
Fortran language standards compliance (@pxref{Standards}), or contributing
to the implementation of extensions such as OpenMP (@pxref{OpenMP}) or
OpenACC (@pxref{OpenACC}) that are under active development.  Again,
contributing test cases for these features is useful too!

@end table


@c ---------------------------------------------------------------------
@c GNU General Public License
@c ---------------------------------------------------------------------

@include gpl_v3.texi



@c ---------------------------------------------------------------------
@c GNU Free Documentation License
@c ---------------------------------------------------------------------

@include fdl.texi



@c ---------------------------------------------------------------------
@c Funding Free Software
@c ---------------------------------------------------------------------

@include funding.texi

@c ---------------------------------------------------------------------
@c Indices
@c ---------------------------------------------------------------------

@node Option Index
@unnumbered Option Index
@command{gfortran}'s command line options are indexed here without any
initial @samp{-} or @samp{--}.  Where an option has both positive and
negative forms (such as -foption and -fno-option), relevant entries in
the manual are indexed under the most appropriate form; it may sometimes
be useful to look up both forms.
@printindex op

@node Keyword Index
@unnumbered Keyword Index
@printindex cp

@bye