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
|
//===-- lib/Evaluate/tools.cpp --------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "flang/Evaluate/tools.h"
#include "flang/Common/idioms.h"
#include "flang/Common/type-kinds.h"
#include "flang/Evaluate/characteristics.h"
#include "flang/Evaluate/traverse.h"
#include "flang/Parser/message.h"
#include "flang/Semantics/tools.h"
#include "llvm/ADT/StringSwitch.h"
#include <algorithm>
#include <variant>
using namespace Fortran::parser::literals;
namespace Fortran::evaluate {
// Can x*(a,b) be represented as (x*a,x*b)? This code duplication
// of the subexpression "x" cannot (yet?) be reliably undone by
// common subexpression elimination in lowering, so it's disabled
// here for now to avoid the risk of potential duplication of
// expensive subexpressions (e.g., large array expressions, references
// to expensive functions) in generate code.
static constexpr bool allowOperandDuplication{false};
std::optional<Expr<SomeType>> AsGenericExpr(DataRef &&ref) {
if (auto dyType{DynamicType::From(ref.GetLastSymbol())}) {
return TypedWrapper<Designator, DataRef>(*dyType, std::move(ref));
} else {
return std::nullopt;
}
}
std::optional<Expr<SomeType>> AsGenericExpr(const Symbol &symbol) {
return AsGenericExpr(DataRef{symbol});
}
Expr<SomeType> Parenthesize(Expr<SomeType> &&expr) {
return common::visit(
[&](auto &&x) {
using T = std::decay_t<decltype(x)>;
if constexpr (common::HasMember<T, TypelessExpression>) {
return expr; // no parentheses around typeless
} else if constexpr (std::is_same_v<T, Expr<SomeDerived>>) {
return AsGenericExpr(Parentheses<SomeDerived>{std::move(x)});
} else {
return common::visit(
[](auto &&y) {
using T = ResultType<decltype(y)>;
return AsGenericExpr(Parentheses<T>{std::move(y)});
},
std::move(x.u));
}
},
std::move(expr.u));
}
std::optional<DataRef> ExtractDataRef(
const ActualArgument &arg, bool intoSubstring, bool intoComplexPart) {
return ExtractDataRef(arg.UnwrapExpr(), intoSubstring, intoComplexPart);
}
std::optional<DataRef> ExtractSubstringBase(const Substring &substring) {
return common::visit(
common::visitors{
[&](const DataRef &x) -> std::optional<DataRef> { return x; },
[&](const StaticDataObject::Pointer &) -> std::optional<DataRef> {
return std::nullopt;
},
},
substring.parent());
}
// IsVariable()
auto IsVariableHelper::operator()(const Symbol &symbol) const -> Result {
// ASSOCIATE(x => expr) -- x counts as a variable, but undefinable
const Symbol &ultimate{symbol.GetUltimate()};
return !IsNamedConstant(ultimate) &&
(ultimate.has<semantics::ObjectEntityDetails>() ||
(ultimate.has<semantics::EntityDetails>() &&
ultimate.attrs().test(semantics::Attr::TARGET)) ||
ultimate.has<semantics::AssocEntityDetails>());
}
auto IsVariableHelper::operator()(const Component &x) const -> Result {
const Symbol &comp{x.GetLastSymbol()};
return (*this)(comp) && (IsPointer(comp) || (*this)(x.base()));
}
auto IsVariableHelper::operator()(const ArrayRef &x) const -> Result {
return (*this)(x.base());
}
auto IsVariableHelper::operator()(const Substring &x) const -> Result {
return (*this)(x.GetBaseObject());
}
auto IsVariableHelper::operator()(const ProcedureDesignator &x) const
-> Result {
if (const Symbol * symbol{x.GetSymbol()}) {
const Symbol *result{FindFunctionResult(*symbol)};
return result && IsPointer(*result) && !IsProcedurePointer(*result);
}
return false;
}
// Conversions of COMPLEX component expressions to REAL.
ConvertRealOperandsResult ConvertRealOperands(
parser::ContextualMessages &messages, Expr<SomeType> &&x,
Expr<SomeType> &&y, int defaultRealKind) {
return common::visit(
common::visitors{
[&](Expr<SomeInteger> &&ix,
Expr<SomeInteger> &&iy) -> ConvertRealOperandsResult {
// Can happen in a CMPLX() constructor. Per F'2018,
// both integer operands are converted to default REAL.
return {AsSameKindExprs<TypeCategory::Real>(
ConvertToKind<TypeCategory::Real>(
defaultRealKind, std::move(ix)),
ConvertToKind<TypeCategory::Real>(
defaultRealKind, std::move(iy)))};
},
[&](Expr<SomeInteger> &&ix,
Expr<SomeUnsigned> &&iy) -> ConvertRealOperandsResult {
return {AsSameKindExprs<TypeCategory::Real>(
ConvertToKind<TypeCategory::Real>(
defaultRealKind, std::move(ix)),
ConvertToKind<TypeCategory::Real>(
defaultRealKind, std::move(iy)))};
},
[&](Expr<SomeUnsigned> &&ix,
Expr<SomeInteger> &&iy) -> ConvertRealOperandsResult {
return {AsSameKindExprs<TypeCategory::Real>(
ConvertToKind<TypeCategory::Real>(
defaultRealKind, std::move(ix)),
ConvertToKind<TypeCategory::Real>(
defaultRealKind, std::move(iy)))};
},
[&](Expr<SomeUnsigned> &&ix,
Expr<SomeUnsigned> &&iy) -> ConvertRealOperandsResult {
return {AsSameKindExprs<TypeCategory::Real>(
ConvertToKind<TypeCategory::Real>(
defaultRealKind, std::move(ix)),
ConvertToKind<TypeCategory::Real>(
defaultRealKind, std::move(iy)))};
},
[&](Expr<SomeInteger> &&ix,
Expr<SomeReal> &&ry) -> ConvertRealOperandsResult {
return {AsSameKindExprs<TypeCategory::Real>(
ConvertTo(ry, std::move(ix)), std::move(ry))};
},
[&](Expr<SomeUnsigned> &&ix,
Expr<SomeReal> &&ry) -> ConvertRealOperandsResult {
return {AsSameKindExprs<TypeCategory::Real>(
ConvertTo(ry, std::move(ix)), std::move(ry))};
},
[&](Expr<SomeReal> &&rx,
Expr<SomeInteger> &&iy) -> ConvertRealOperandsResult {
return {AsSameKindExprs<TypeCategory::Real>(
std::move(rx), ConvertTo(rx, std::move(iy)))};
},
[&](Expr<SomeReal> &&rx,
Expr<SomeUnsigned> &&iy) -> ConvertRealOperandsResult {
return {AsSameKindExprs<TypeCategory::Real>(
std::move(rx), ConvertTo(rx, std::move(iy)))};
},
[&](Expr<SomeReal> &&rx,
Expr<SomeReal> &&ry) -> ConvertRealOperandsResult {
return {AsSameKindExprs<TypeCategory::Real>(
std::move(rx), std::move(ry))};
},
[&](Expr<SomeInteger> &&ix,
BOZLiteralConstant &&by) -> ConvertRealOperandsResult {
return {AsSameKindExprs<TypeCategory::Real>(
ConvertToKind<TypeCategory::Real>(
defaultRealKind, std::move(ix)),
ConvertToKind<TypeCategory::Real>(
defaultRealKind, std::move(by)))};
},
[&](Expr<SomeUnsigned> &&ix,
BOZLiteralConstant &&by) -> ConvertRealOperandsResult {
return {AsSameKindExprs<TypeCategory::Real>(
ConvertToKind<TypeCategory::Real>(
defaultRealKind, std::move(ix)),
ConvertToKind<TypeCategory::Real>(
defaultRealKind, std::move(by)))};
},
[&](BOZLiteralConstant &&bx,
Expr<SomeInteger> &&iy) -> ConvertRealOperandsResult {
return {AsSameKindExprs<TypeCategory::Real>(
ConvertToKind<TypeCategory::Real>(
defaultRealKind, std::move(bx)),
ConvertToKind<TypeCategory::Real>(
defaultRealKind, std::move(iy)))};
},
[&](BOZLiteralConstant &&bx,
Expr<SomeUnsigned> &&iy) -> ConvertRealOperandsResult {
return {AsSameKindExprs<TypeCategory::Real>(
ConvertToKind<TypeCategory::Real>(
defaultRealKind, std::move(bx)),
ConvertToKind<TypeCategory::Real>(
defaultRealKind, std::move(iy)))};
},
[&](Expr<SomeReal> &&rx,
BOZLiteralConstant &&by) -> ConvertRealOperandsResult {
return {AsSameKindExprs<TypeCategory::Real>(
std::move(rx), ConvertTo(rx, std::move(by)))};
},
[&](BOZLiteralConstant &&bx,
Expr<SomeReal> &&ry) -> ConvertRealOperandsResult {
return {AsSameKindExprs<TypeCategory::Real>(
ConvertTo(ry, std::move(bx)), std::move(ry))};
},
[&](BOZLiteralConstant &&,
BOZLiteralConstant &&) -> ConvertRealOperandsResult {
messages.Say("operands cannot both be BOZ"_err_en_US);
return std::nullopt;
},
[&](auto &&, auto &&) -> ConvertRealOperandsResult { // C718
messages.Say(
"operands must be INTEGER, UNSIGNED, REAL, or BOZ"_err_en_US);
return std::nullopt;
},
},
std::move(x.u), std::move(y.u));
}
// Helpers for NumericOperation and its subroutines below.
static std::optional<Expr<SomeType>> NoExpr() { return std::nullopt; }
template <TypeCategory CAT>
std::optional<Expr<SomeType>> Package(Expr<SomeKind<CAT>> &&catExpr) {
return {AsGenericExpr(std::move(catExpr))};
}
template <TypeCategory CAT>
std::optional<Expr<SomeType>> Package(
std::optional<Expr<SomeKind<CAT>>> &&catExpr) {
if (catExpr) {
return {AsGenericExpr(std::move(*catExpr))};
} else {
return std::nullopt;
}
}
// Mixed REAL+INTEGER operations. REAL**INTEGER is a special case that
// does not require conversion of the exponent expression.
template <template <typename> class OPR>
std::optional<Expr<SomeType>> MixedRealLeft(
Expr<SomeReal> &&rx, Expr<SomeInteger> &&iy) {
return Package(common::visit(
[&](auto &&rxk) -> Expr<SomeReal> {
using resultType = ResultType<decltype(rxk)>;
if constexpr (std::is_same_v<OPR<resultType>, Power<resultType>>) {
return AsCategoryExpr(
RealToIntPower<resultType>{std::move(rxk), std::move(iy)});
}
// G++ 8.1.0 emits bogus warnings about missing return statements if
// this statement is wrapped in an "else", as it should be.
return AsCategoryExpr(OPR<resultType>{
std::move(rxk), ConvertToType<resultType>(std::move(iy))});
},
std::move(rx.u)));
}
template <int KIND>
Expr<SomeComplex> MakeComplex(Expr<Type<TypeCategory::Real, KIND>> &&re,
Expr<Type<TypeCategory::Real, KIND>> &&im) {
return AsCategoryExpr(ComplexConstructor<KIND>{std::move(re), std::move(im)});
}
std::optional<Expr<SomeComplex>> ConstructComplex(
parser::ContextualMessages &messages, Expr<SomeType> &&real,
Expr<SomeType> &&imaginary, int defaultRealKind) {
if (auto converted{ConvertRealOperands(
messages, std::move(real), std::move(imaginary), defaultRealKind)}) {
return {common::visit(
[](auto &&pair) {
return MakeComplex(std::move(pair[0]), std::move(pair[1]));
},
std::move(*converted))};
}
return std::nullopt;
}
std::optional<Expr<SomeComplex>> ConstructComplex(
parser::ContextualMessages &messages, std::optional<Expr<SomeType>> &&real,
std::optional<Expr<SomeType>> &&imaginary, int defaultRealKind) {
if (auto parts{common::AllPresent(std::move(real), std::move(imaginary))}) {
return ConstructComplex(messages, std::get<0>(std::move(*parts)),
std::get<1>(std::move(*parts)), defaultRealKind);
}
return std::nullopt;
}
// Extracts the real or imaginary part of the result of a COMPLEX
// expression, when that expression is simple enough to be duplicated.
template <bool GET_IMAGINARY> struct ComplexPartExtractor {
template <typename A> static std::optional<Expr<SomeReal>> Get(const A &) {
return std::nullopt;
}
template <int KIND>
static std::optional<Expr<SomeReal>> Get(
const Parentheses<Type<TypeCategory::Complex, KIND>> &kz) {
if (auto x{Get(kz.left())}) {
return AsGenericExpr(AsSpecificExpr(
Parentheses<Type<TypeCategory::Real, KIND>>{std::move(*x)}));
} else {
return std::nullopt;
}
}
template <int KIND>
static std::optional<Expr<SomeReal>> Get(
const Negate<Type<TypeCategory::Complex, KIND>> &kz) {
if (auto x{Get(kz.left())}) {
return AsGenericExpr(AsSpecificExpr(
Negate<Type<TypeCategory::Real, KIND>>{std::move(*x)}));
} else {
return std::nullopt;
}
}
template <int KIND>
static std::optional<Expr<SomeReal>> Get(
const Convert<Type<TypeCategory::Complex, KIND>, TypeCategory::Complex>
&kz) {
if (auto x{Get(kz.left())}) {
return AsGenericExpr(AsSpecificExpr(
Convert<Type<TypeCategory::Real, KIND>, TypeCategory::Real>{
AsGenericExpr(std::move(*x))}));
} else {
return std::nullopt;
}
}
template <int KIND>
static std::optional<Expr<SomeReal>> Get(const ComplexConstructor<KIND> &kz) {
return GET_IMAGINARY ? Get(kz.right()) : Get(kz.left());
}
template <int KIND>
static std::optional<Expr<SomeReal>> Get(
const Constant<Type<TypeCategory::Complex, KIND>> &kz) {
if (auto cz{kz.GetScalarValue()}) {
return AsGenericExpr(
AsSpecificExpr(GET_IMAGINARY ? cz->AIMAG() : cz->REAL()));
} else {
return std::nullopt;
}
}
template <int KIND>
static std::optional<Expr<SomeReal>> Get(
const Designator<Type<TypeCategory::Complex, KIND>> &kz) {
if (const auto *symbolRef{std::get_if<SymbolRef>(&kz.u)}) {
return AsGenericExpr(AsSpecificExpr(
Designator<Type<TypeCategory::Complex, KIND>>{ComplexPart{
DataRef{*symbolRef},
GET_IMAGINARY ? ComplexPart::Part::IM : ComplexPart::Part::RE}}));
} else {
return std::nullopt;
}
}
template <int KIND>
static std::optional<Expr<SomeReal>> Get(
const Expr<Type<TypeCategory::Complex, KIND>> &kz) {
return Get(kz.u);
}
static std::optional<Expr<SomeReal>> Get(const Expr<SomeComplex> &z) {
return Get(z.u);
}
};
// Convert REAL to COMPLEX of the same kind. Preserving the real operand kind
// and then applying complex operand promotion rules allows the result to have
// the highest precision of REAL and COMPLEX operands as required by Fortran
// 2018 10.9.1.3.
Expr<SomeComplex> PromoteRealToComplex(Expr<SomeReal> &&someX) {
return common::visit(
[](auto &&x) {
using RT = ResultType<decltype(x)>;
return AsCategoryExpr(ComplexConstructor<RT::kind>{
std::move(x), AsExpr(Constant<RT>{Scalar<RT>{}})});
},
std::move(someX.u));
}
// Handle mixed COMPLEX+REAL (or INTEGER) operations in a better way
// than just converting the second operand to COMPLEX and performing the
// corresponding COMPLEX+COMPLEX operation.
template <template <typename> class OPR, TypeCategory RCAT>
std::optional<Expr<SomeType>> MixedComplexLeft(
parser::ContextualMessages &messages, const Expr<SomeComplex> &zx,
const Expr<SomeKind<RCAT>> &iry, [[maybe_unused]] int defaultRealKind) {
if constexpr (RCAT == TypeCategory::Integer &&
std::is_same_v<OPR<LargestReal>, Power<LargestReal>>) {
// COMPLEX**INTEGER is a special case that doesn't convert the exponent.
return Package(common::visit(
[&](const auto &zxk) {
using Ty = ResultType<decltype(zxk)>;
return AsCategoryExpr(AsExpr(
RealToIntPower<Ty>{common::Clone(zxk), common::Clone(iry)}));
},
zx.u));
}
std::optional<Expr<SomeReal>> zr{ComplexPartExtractor<false>{}.Get(zx)};
std::optional<Expr<SomeReal>> zi{ComplexPartExtractor<true>{}.Get(zx)};
if (!zr || !zi) {
} else if constexpr (std::is_same_v<OPR<LargestReal>, Add<LargestReal>> ||
std::is_same_v<OPR<LargestReal>, Subtract<LargestReal>>) {
// (a,b) + x -> (a+x, b)
// (a,b) - x -> (a-x, b)
if (std::optional<Expr<SomeType>> rr{
NumericOperation<OPR>(messages, AsGenericExpr(std::move(*zr)),
AsGenericExpr(common::Clone(iry)), defaultRealKind)}) {
return Package(ConstructComplex(messages, std::move(*rr),
AsGenericExpr(std::move(*zi)), defaultRealKind));
}
} else if constexpr (allowOperandDuplication &&
(std::is_same_v<OPR<LargestReal>, Multiply<LargestReal>> ||
std::is_same_v<OPR<LargestReal>, Divide<LargestReal>>)) {
// (a,b) * x -> (a*x, b*x)
// (a,b) / x -> (a/x, b/x)
auto copy{iry};
auto rr{NumericOperation<OPR>(messages, AsGenericExpr(std::move(*zr)),
AsGenericExpr(common::Clone(iry)), defaultRealKind)};
auto ri{NumericOperation<OPR>(messages, AsGenericExpr(std::move(*zi)),
AsGenericExpr(std::move(copy)), defaultRealKind)};
if (auto parts{common::AllPresent(std::move(rr), std::move(ri))}) {
return Package(ConstructComplex(messages, std::get<0>(std::move(*parts)),
std::get<1>(std::move(*parts)), defaultRealKind));
}
}
return std::nullopt;
}
// Mixed COMPLEX operations with the COMPLEX operand on the right.
// x + (a,b) -> (x+a, b)
// x - (a,b) -> (x-a, -b)
// x * (a,b) -> (x*a, x*b)
// x / (a,b) -> (x,0) / (a,b) (and **)
template <template <typename> class OPR, TypeCategory LCAT>
std::optional<Expr<SomeType>> MixedComplexRight(
parser::ContextualMessages &messages, const Expr<SomeKind<LCAT>> &irx,
const Expr<SomeComplex> &zy, [[maybe_unused]] int defaultRealKind) {
if constexpr (std::is_same_v<OPR<LargestReal>, Add<LargestReal>>) {
// x + (a,b) -> (a,b) + x -> (a+x, b)
return MixedComplexLeft<OPR, LCAT>(messages, zy, irx, defaultRealKind);
} else if constexpr (allowOperandDuplication &&
std::is_same_v<OPR<LargestReal>, Multiply<LargestReal>>) {
// x * (a,b) -> (a,b) * x -> (a*x, b*x)
return MixedComplexLeft<OPR, LCAT>(messages, zy, irx, defaultRealKind);
} else if constexpr (std::is_same_v<OPR<LargestReal>,
Subtract<LargestReal>>) {
// x - (a,b) -> (x-a, -b)
std::optional<Expr<SomeReal>> zr{ComplexPartExtractor<false>{}.Get(zy)};
std::optional<Expr<SomeReal>> zi{ComplexPartExtractor<true>{}.Get(zy)};
if (zr && zi) {
if (std::optional<Expr<SomeType>> rr{NumericOperation<Subtract>(messages,
AsGenericExpr(common::Clone(irx)), AsGenericExpr(std::move(*zr)),
defaultRealKind)}) {
return Package(ConstructComplex(messages, std::move(*rr),
AsGenericExpr(-std::move(*zi)), defaultRealKind));
}
}
}
return std::nullopt;
}
// Promotes REAL(rk) and COMPLEX(zk) operands COMPLEX(max(rk,zk))
// then combine them with an operator.
template <template <typename> class OPR, TypeCategory XCAT, TypeCategory YCAT>
Expr<SomeComplex> PromoteMixedComplexReal(
Expr<SomeKind<XCAT>> &&x, Expr<SomeKind<YCAT>> &&y) {
static_assert(XCAT == TypeCategory::Complex || YCAT == TypeCategory::Complex);
static_assert(XCAT == TypeCategory::Real || YCAT == TypeCategory::Real);
return common::visit(
[&](const auto &kx, const auto &ky) {
constexpr int maxKind{std::max(
ResultType<decltype(kx)>::kind, ResultType<decltype(ky)>::kind)};
using ZTy = Type<TypeCategory::Complex, maxKind>;
return Expr<SomeComplex>{
Expr<ZTy>{OPR<ZTy>{ConvertToType<ZTy>(std::move(x)),
ConvertToType<ZTy>(std::move(y))}}};
},
x.u, y.u);
}
// N.B. When a "typeless" BOZ literal constant appears as one (not both!) of
// the operands to a dyadic operation where one is permitted, it assumes the
// type and kind of the other operand.
template <template <typename> class OPR, bool CAN_BE_UNSIGNED>
std::optional<Expr<SomeType>> NumericOperation(
parser::ContextualMessages &messages, Expr<SomeType> &&x,
Expr<SomeType> &&y, int defaultRealKind) {
return common::visit(
common::visitors{
[](Expr<SomeInteger> &&ix, Expr<SomeInteger> &&iy) {
return Package(PromoteAndCombine<OPR, TypeCategory::Integer>(
std::move(ix), std::move(iy)));
},
[](Expr<SomeReal> &&rx, Expr<SomeReal> &&ry) {
return Package(PromoteAndCombine<OPR, TypeCategory::Real>(
std::move(rx), std::move(ry)));
},
[&](Expr<SomeUnsigned> &&ix, Expr<SomeUnsigned> &&iy) {
if constexpr (CAN_BE_UNSIGNED) {
return Package(PromoteAndCombine<OPR, TypeCategory::Unsigned>(
std::move(ix), std::move(iy)));
} else {
messages.Say("Operands must not be UNSIGNED"_err_en_US);
return NoExpr();
}
},
// Mixed REAL/INTEGER operations
[](Expr<SomeReal> &&rx, Expr<SomeInteger> &&iy) {
return MixedRealLeft<OPR>(std::move(rx), std::move(iy));
},
[](Expr<SomeInteger> &&ix, Expr<SomeReal> &&ry) {
return Package(common::visit(
[&](auto &&ryk) -> Expr<SomeReal> {
using resultType = ResultType<decltype(ryk)>;
return AsCategoryExpr(
OPR<resultType>{ConvertToType<resultType>(std::move(ix)),
std::move(ryk)});
},
std::move(ry.u)));
},
// Homogeneous and mixed COMPLEX operations
[](Expr<SomeComplex> &&zx, Expr<SomeComplex> &&zy) {
return Package(PromoteAndCombine<OPR, TypeCategory::Complex>(
std::move(zx), std::move(zy)));
},
[&](Expr<SomeComplex> &&zx, Expr<SomeInteger> &&iy) {
if (auto result{
MixedComplexLeft<OPR>(messages, zx, iy, defaultRealKind)}) {
return result;
} else {
return Package(PromoteAndCombine<OPR, TypeCategory::Complex>(
std::move(zx), ConvertTo(zx, std::move(iy))));
}
},
[&](Expr<SomeComplex> &&zx, Expr<SomeReal> &&ry) {
if (auto result{
MixedComplexLeft<OPR>(messages, zx, ry, defaultRealKind)}) {
return result;
} else {
return Package(
PromoteMixedComplexReal<OPR>(std::move(zx), std::move(ry)));
}
},
[&](Expr<SomeInteger> &&ix, Expr<SomeComplex> &&zy) {
if (auto result{MixedComplexRight<OPR>(
messages, ix, zy, defaultRealKind)}) {
return result;
} else {
return Package(PromoteAndCombine<OPR, TypeCategory::Complex>(
ConvertTo(zy, std::move(ix)), std::move(zy)));
}
},
[&](Expr<SomeReal> &&rx, Expr<SomeComplex> &&zy) {
if (auto result{MixedComplexRight<OPR>(
messages, rx, zy, defaultRealKind)}) {
return result;
} else {
return Package(
PromoteMixedComplexReal<OPR>(std::move(rx), std::move(zy)));
}
},
// Operations with one typeless operand
[&](BOZLiteralConstant &&bx, Expr<SomeInteger> &&iy) {
return NumericOperation<OPR, CAN_BE_UNSIGNED>(messages,
AsGenericExpr(ConvertTo(iy, std::move(bx))), std::move(y),
defaultRealKind);
},
[&](BOZLiteralConstant &&bx, Expr<SomeUnsigned> &&iy) {
return NumericOperation<OPR, CAN_BE_UNSIGNED>(messages,
AsGenericExpr(ConvertTo(iy, std::move(bx))), std::move(y),
defaultRealKind);
},
[&](BOZLiteralConstant &&bx, Expr<SomeReal> &&ry) {
return NumericOperation<OPR, CAN_BE_UNSIGNED>(messages,
AsGenericExpr(ConvertTo(ry, std::move(bx))), std::move(y),
defaultRealKind);
},
[&](Expr<SomeInteger> &&ix, BOZLiteralConstant &&by) {
return NumericOperation<OPR, CAN_BE_UNSIGNED>(messages,
std::move(x), AsGenericExpr(ConvertTo(ix, std::move(by))),
defaultRealKind);
},
[&](Expr<SomeUnsigned> &&ix, BOZLiteralConstant &&by) {
return NumericOperation<OPR, CAN_BE_UNSIGNED>(messages,
std::move(x), AsGenericExpr(ConvertTo(ix, std::move(by))),
defaultRealKind);
},
[&](Expr<SomeReal> &&rx, BOZLiteralConstant &&by) {
return NumericOperation<OPR, CAN_BE_UNSIGNED>(messages,
std::move(x), AsGenericExpr(ConvertTo(rx, std::move(by))),
defaultRealKind);
},
// Error cases
[&](Expr<SomeUnsigned> &&, auto &&) {
messages.Say("Both operands must be UNSIGNED"_err_en_US);
return NoExpr();
},
[&](auto &&, Expr<SomeUnsigned> &&) {
messages.Say("Both operands must be UNSIGNED"_err_en_US);
return NoExpr();
},
[&](auto &&, auto &&) {
messages.Say("non-numeric operands to numeric operation"_err_en_US);
return NoExpr();
},
},
std::move(x.u), std::move(y.u));
}
template std::optional<Expr<SomeType>> NumericOperation<Power, false>(
parser::ContextualMessages &, Expr<SomeType> &&, Expr<SomeType> &&,
int defaultRealKind);
template std::optional<Expr<SomeType>> NumericOperation<Multiply>(
parser::ContextualMessages &, Expr<SomeType> &&, Expr<SomeType> &&,
int defaultRealKind);
template std::optional<Expr<SomeType>> NumericOperation<Divide>(
parser::ContextualMessages &, Expr<SomeType> &&, Expr<SomeType> &&,
int defaultRealKind);
template std::optional<Expr<SomeType>> NumericOperation<Add>(
parser::ContextualMessages &, Expr<SomeType> &&, Expr<SomeType> &&,
int defaultRealKind);
template std::optional<Expr<SomeType>> NumericOperation<Subtract>(
parser::ContextualMessages &, Expr<SomeType> &&, Expr<SomeType> &&,
int defaultRealKind);
std::optional<Expr<SomeType>> Negation(
parser::ContextualMessages &messages, Expr<SomeType> &&x) {
return common::visit(
common::visitors{
[&](BOZLiteralConstant &&) {
messages.Say("BOZ literal cannot be negated"_err_en_US);
return NoExpr();
},
[&](NullPointer &&) {
messages.Say("NULL() cannot be negated"_err_en_US);
return NoExpr();
},
[&](ProcedureDesignator &&) {
messages.Say("Subroutine cannot be negated"_err_en_US);
return NoExpr();
},
[&](ProcedureRef &&) {
messages.Say("Pointer to subroutine cannot be negated"_err_en_US);
return NoExpr();
},
[&](Expr<SomeInteger> &&x) { return Package(-std::move(x)); },
[&](Expr<SomeReal> &&x) { return Package(-std::move(x)); },
[&](Expr<SomeComplex> &&x) { return Package(-std::move(x)); },
[&](Expr<SomeCharacter> &&) {
messages.Say("CHARACTER cannot be negated"_err_en_US);
return NoExpr();
},
[&](Expr<SomeLogical> &&) {
messages.Say("LOGICAL cannot be negated"_err_en_US);
return NoExpr();
},
[&](Expr<SomeUnsigned> &&x) { return Package(-std::move(x)); },
[&](Expr<SomeDerived> &&) {
messages.Say("Operand cannot be negated"_err_en_US);
return NoExpr();
},
},
std::move(x.u));
}
Expr<SomeLogical> LogicalNegation(Expr<SomeLogical> &&x) {
return common::visit(
[](auto &&xk) { return AsCategoryExpr(LogicalNegation(std::move(xk))); },
std::move(x.u));
}
template <TypeCategory CAT>
Expr<LogicalResult> PromoteAndRelate(
RelationalOperator opr, Expr<SomeKind<CAT>> &&x, Expr<SomeKind<CAT>> &&y) {
return common::visit(
[=](auto &&xy) {
return PackageRelation(opr, std::move(xy[0]), std::move(xy[1]));
},
AsSameKindExprs(std::move(x), std::move(y)));
}
std::optional<Expr<LogicalResult>> Relate(parser::ContextualMessages &messages,
RelationalOperator opr, Expr<SomeType> &&x, Expr<SomeType> &&y) {
return common::visit(
common::visitors{
[=](Expr<SomeInteger> &&ix,
Expr<SomeInteger> &&iy) -> std::optional<Expr<LogicalResult>> {
return PromoteAndRelate(opr, std::move(ix), std::move(iy));
},
[=](Expr<SomeUnsigned> &&ix,
Expr<SomeUnsigned> &&iy) -> std::optional<Expr<LogicalResult>> {
return PromoteAndRelate(opr, std::move(ix), std::move(iy));
},
[=](Expr<SomeReal> &&rx,
Expr<SomeReal> &&ry) -> std::optional<Expr<LogicalResult>> {
return PromoteAndRelate(opr, std::move(rx), std::move(ry));
},
[&](Expr<SomeReal> &&rx, Expr<SomeInteger> &&iy) {
return Relate(messages, opr, std::move(x),
AsGenericExpr(ConvertTo(rx, std::move(iy))));
},
[&](Expr<SomeInteger> &&ix, Expr<SomeReal> &&ry) {
return Relate(messages, opr,
AsGenericExpr(ConvertTo(ry, std::move(ix))), std::move(y));
},
[&](Expr<SomeComplex> &&zx,
Expr<SomeComplex> &&zy) -> std::optional<Expr<LogicalResult>> {
if (opr == RelationalOperator::EQ ||
opr == RelationalOperator::NE) {
return PromoteAndRelate(opr, std::move(zx), std::move(zy));
} else {
messages.Say(
"COMPLEX data may be compared only for equality"_err_en_US);
return std::nullopt;
}
},
[&](Expr<SomeComplex> &&zx, Expr<SomeInteger> &&iy) {
return Relate(messages, opr, std::move(x),
AsGenericExpr(ConvertTo(zx, std::move(iy))));
},
[&](Expr<SomeComplex> &&zx, Expr<SomeReal> &&ry) {
return Relate(messages, opr, std::move(x),
AsGenericExpr(ConvertTo(zx, std::move(ry))));
},
[&](Expr<SomeInteger> &&ix, Expr<SomeComplex> &&zy) {
return Relate(messages, opr,
AsGenericExpr(ConvertTo(zy, std::move(ix))), std::move(y));
},
[&](Expr<SomeReal> &&rx, Expr<SomeComplex> &&zy) {
return Relate(messages, opr,
AsGenericExpr(ConvertTo(zy, std::move(rx))), std::move(y));
},
[&](Expr<SomeCharacter> &&cx, Expr<SomeCharacter> &&cy) {
return common::visit(
[&](auto &&cxk,
auto &&cyk) -> std::optional<Expr<LogicalResult>> {
using Ty = ResultType<decltype(cxk)>;
if constexpr (std::is_same_v<Ty, ResultType<decltype(cyk)>>) {
return PackageRelation(opr, std::move(cxk), std::move(cyk));
} else {
messages.Say(
"CHARACTER operands do not have same KIND"_err_en_US);
return std::nullopt;
}
},
std::move(cx.u), std::move(cy.u));
},
// Default case
[&](auto &&, auto &&) {
DIE("invalid types for relational operator");
return std::optional<Expr<LogicalResult>>{};
},
},
std::move(x.u), std::move(y.u));
}
Expr<SomeLogical> BinaryLogicalOperation(
LogicalOperator opr, Expr<SomeLogical> &&x, Expr<SomeLogical> &&y) {
CHECK(opr != LogicalOperator::Not);
return common::visit(
[=](auto &&xy) {
using Ty = ResultType<decltype(xy[0])>;
return Expr<SomeLogical>{BinaryLogicalOperation<Ty::kind>(
opr, std::move(xy[0]), std::move(xy[1]))};
},
AsSameKindExprs(std::move(x), std::move(y)));
}
template <TypeCategory TO>
std::optional<Expr<SomeType>> ConvertToNumeric(int kind, Expr<SomeType> &&x) {
static_assert(common::IsNumericTypeCategory(TO));
return common::visit(
[=](auto &&cx) -> std::optional<Expr<SomeType>> {
using cxType = std::decay_t<decltype(cx)>;
if constexpr (!common::HasMember<cxType, TypelessExpression>) {
if constexpr (IsNumericTypeCategory(ResultType<cxType>::category)) {
return Expr<SomeType>{ConvertToKind<TO>(kind, std::move(cx))};
}
}
return std::nullopt;
},
std::move(x.u));
}
std::optional<Expr<SomeType>> ConvertToType(
const DynamicType &type, Expr<SomeType> &&x) {
if (type.IsTypelessIntrinsicArgument()) {
return std::nullopt;
}
switch (type.category()) {
case TypeCategory::Integer:
if (auto *boz{std::get_if<BOZLiteralConstant>(&x.u)}) {
// Extension to C7109: allow BOZ literals to appear in integer contexts
// when the type is unambiguous.
return Expr<SomeType>{
ConvertToKind<TypeCategory::Integer>(type.kind(), std::move(*boz))};
}
return ConvertToNumeric<TypeCategory::Integer>(type.kind(), std::move(x));
case TypeCategory::Unsigned:
if (auto *boz{std::get_if<BOZLiteralConstant>(&x.u)}) {
return Expr<SomeType>{
ConvertToKind<TypeCategory::Unsigned>(type.kind(), std::move(*boz))};
}
if (auto *cx{UnwrapExpr<Expr<SomeUnsigned>>(x)}) {
return Expr<SomeType>{
ConvertToKind<TypeCategory::Unsigned>(type.kind(), std::move(*cx))};
}
break;
case TypeCategory::Real:
if (auto *boz{std::get_if<BOZLiteralConstant>(&x.u)}) {
return Expr<SomeType>{
ConvertToKind<TypeCategory::Real>(type.kind(), std::move(*boz))};
}
return ConvertToNumeric<TypeCategory::Real>(type.kind(), std::move(x));
case TypeCategory::Complex:
return ConvertToNumeric<TypeCategory::Complex>(type.kind(), std::move(x));
case TypeCategory::Character:
if (auto *cx{UnwrapExpr<Expr<SomeCharacter>>(x)}) {
auto converted{
ConvertToKind<TypeCategory::Character>(type.kind(), std::move(*cx))};
if (auto length{type.GetCharLength()}) {
converted = common::visit(
[&](auto &&x) {
using CharacterType = ResultType<decltype(x)>;
return Expr<SomeCharacter>{
Expr<CharacterType>{SetLength<CharacterType::kind>{
std::move(x), std::move(*length)}}};
},
std::move(converted.u));
}
return Expr<SomeType>{std::move(converted)};
}
break;
case TypeCategory::Logical:
if (auto *cx{UnwrapExpr<Expr<SomeLogical>>(x)}) {
return Expr<SomeType>{
ConvertToKind<TypeCategory::Logical>(type.kind(), std::move(*cx))};
}
break;
case TypeCategory::Derived:
if (auto fromType{x.GetType()}) {
if (type.IsTkCompatibleWith(*fromType)) {
// "x" could be assigned or passed to "type", or appear in a
// structure constructor as a value for a component with "type"
return std::move(x);
}
}
break;
}
return std::nullopt;
}
std::optional<Expr<SomeType>> ConvertToType(
const DynamicType &to, std::optional<Expr<SomeType>> &&x) {
if (x) {
return ConvertToType(to, std::move(*x));
} else {
return std::nullopt;
}
}
std::optional<Expr<SomeType>> ConvertToType(
const Symbol &symbol, Expr<SomeType> &&x) {
if (auto symType{DynamicType::From(symbol)}) {
return ConvertToType(*symType, std::move(x));
}
return std::nullopt;
}
std::optional<Expr<SomeType>> ConvertToType(
const Symbol &to, std::optional<Expr<SomeType>> &&x) {
if (x) {
return ConvertToType(to, std::move(*x));
} else {
return std::nullopt;
}
}
bool IsAssumedRank(const Symbol &original) {
if (const auto *assoc{original.detailsIf<semantics::AssocEntityDetails>()}) {
if (assoc->rank()) {
return false; // in RANK(n) or RANK(*)
} else if (assoc->IsAssumedRank()) {
return true; // RANK DEFAULT
}
}
const Symbol &symbol{semantics::ResolveAssociations(original)};
const auto *object{symbol.detailsIf<semantics::ObjectEntityDetails>()};
return object && object->IsAssumedRank();
}
bool IsAssumedRank(const ActualArgument &arg) {
if (const auto *expr{arg.UnwrapExpr()}) {
return IsAssumedRank(*expr);
} else {
const Symbol *assumedTypeDummy{arg.GetAssumedTypeDummy()};
CHECK(assumedTypeDummy);
return IsAssumedRank(*assumedTypeDummy);
}
}
int GetCorank(const ActualArgument &arg) {
const auto *expr{arg.UnwrapExpr()};
return GetCorank(*expr);
}
bool IsProcedureDesignator(const Expr<SomeType> &expr) {
return std::holds_alternative<ProcedureDesignator>(expr.u);
}
bool IsFunctionDesignator(const Expr<SomeType> &expr) {
const auto *designator{std::get_if<ProcedureDesignator>(&expr.u)};
return designator && designator->GetType().has_value();
}
bool IsPointer(const Expr<SomeType> &expr) {
return IsObjectPointer(expr) || IsProcedurePointer(expr);
}
bool IsProcedurePointer(const Expr<SomeType> &expr) {
if (IsNullProcedurePointer(&expr)) {
return true;
} else if (const auto *funcRef{UnwrapProcedureRef(expr)}) {
if (const Symbol * proc{funcRef->proc().GetSymbol()}) {
const Symbol *result{FindFunctionResult(*proc)};
return result && IsProcedurePointer(*result);
} else {
return false;
}
} else if (const auto *proc{std::get_if<ProcedureDesignator>(&expr.u)}) {
return IsProcedurePointer(proc->GetSymbol());
} else {
return false;
}
}
bool IsProcedure(const Expr<SomeType> &expr) {
return IsProcedureDesignator(expr) || IsProcedurePointer(expr);
}
bool IsProcedurePointerTarget(const Expr<SomeType> &expr) {
return common::visit(common::visitors{
[](const NullPointer &) { return true; },
[](const ProcedureDesignator &) { return true; },
[](const ProcedureRef &) { return true; },
[&](const auto &) {
const Symbol *last{GetLastSymbol(expr)};
return last && IsProcedurePointer(*last);
},
},
expr.u);
}
bool IsObjectPointer(const Expr<SomeType> &expr) {
if (IsNullObjectPointer(&expr)) {
return true;
} else if (IsProcedurePointerTarget(expr)) {
return false;
} else if (const auto *funcRef{UnwrapProcedureRef(expr)}) {
return IsVariable(*funcRef);
} else if (const Symbol * symbol{UnwrapWholeSymbolOrComponentDataRef(expr)}) {
return IsPointer(symbol->GetUltimate());
} else {
return false;
}
}
// IsNullPointer() & variations
template <bool IS_PROC_PTR> struct IsNullPointerHelper {
template <typename A> bool operator()(const A &) const { return false; }
bool operator()(const ProcedureRef &call) const {
if constexpr (IS_PROC_PTR) {
const auto *intrinsic{call.proc().GetSpecificIntrinsic()};
return intrinsic &&
intrinsic->characteristics.value().attrs.test(
characteristics::Procedure::Attr::NullPointer);
} else {
return false;
}
}
template <typename T> bool operator()(const FunctionRef<T> &call) const {
if constexpr (IS_PROC_PTR) {
return false;
} else {
const auto *intrinsic{call.proc().GetSpecificIntrinsic()};
return intrinsic &&
intrinsic->characteristics.value().attrs.test(
characteristics::Procedure::Attr::NullPointer);
}
}
template <typename T> bool operator()(const Designator<T> &x) const {
if (const auto *component{std::get_if<Component>(&x.u)}) {
if (const auto *baseSym{std::get_if<SymbolRef>(&component->base().u)}) {
const Symbol &base{**baseSym};
if (const auto *object{
base.detailsIf<semantics::ObjectEntityDetails>()}) {
// TODO: nested component and array references
if (IsNamedConstant(base) && object->init()) {
if (auto structCons{
GetScalarConstantValue<SomeDerived>(*object->init())}) {
auto iter{structCons->values().find(component->GetLastSymbol())};
if (iter != structCons->values().end()) {
return (*this)(iter->second.value());
}
}
}
}
}
}
return false;
}
bool operator()(const NullPointer &) const { return true; }
template <typename T> bool operator()(const Parentheses<T> &x) const {
return (*this)(x.left());
}
template <typename T> bool operator()(const Expr<T> &x) const {
return common::visit(*this, x.u);
}
};
bool IsNullObjectPointer(const Expr<SomeType> *expr) {
return expr && IsNullPointerHelper<false>{}(*expr);
}
bool IsNullProcedurePointer(const Expr<SomeType> *expr) {
return expr && IsNullPointerHelper<true>{}(*expr);
}
bool IsNullPointer(const Expr<SomeType> *expr) {
return IsNullObjectPointer(expr) || IsNullProcedurePointer(expr);
}
bool IsBareNullPointer(const Expr<SomeType> *expr) {
return expr && std::holds_alternative<NullPointer>(expr->u);
}
struct IsNullAllocatableHelper {
template <typename A> bool operator()(const A &) const { return false; }
template <typename T> bool operator()(const FunctionRef<T> &call) const {
const auto *intrinsic{call.proc().GetSpecificIntrinsic()};
return intrinsic &&
intrinsic->characteristics.value().attrs.test(
characteristics::Procedure::Attr::NullAllocatable);
}
template <typename T> bool operator()(const Parentheses<T> &x) const {
return (*this)(x.left());
}
template <typename T> bool operator()(const Expr<T> &x) const {
return common::visit(*this, x.u);
}
};
bool IsNullAllocatable(const Expr<SomeType> *x) {
return x && IsNullAllocatableHelper{}(*x);
}
bool IsNullPointerOrAllocatable(const Expr<SomeType> *x) {
return IsNullPointer(x) || IsNullAllocatable(x);
}
// GetSymbolVector()
auto GetSymbolVectorHelper::operator()(const Symbol &x) const -> Result {
if (const auto *details{x.detailsIf<semantics::AssocEntityDetails>()}) {
if (IsVariable(details->expr()) && !UnwrapProcedureRef(*details->expr())) {
// associate(x => variable that is not a pointer returned by a function)
return (*this)(details->expr());
}
}
return {x.GetUltimate()};
}
auto GetSymbolVectorHelper::operator()(const Component &x) const -> Result {
Result result{(*this)(x.base())};
result.emplace_back(x.GetLastSymbol());
return result;
}
auto GetSymbolVectorHelper::operator()(const ArrayRef &x) const -> Result {
return GetSymbolVector(x.base());
}
auto GetSymbolVectorHelper::operator()(const CoarrayRef &x) const -> Result {
return GetSymbolVector(x.base());
}
const Symbol *GetLastTarget(const SymbolVector &symbols) {
auto end{std::crend(symbols)};
// N.B. Neither clang nor g++ recognizes "symbols.crbegin()" here.
auto iter{std::find_if(std::crbegin(symbols), end, [](const Symbol &x) {
return x.attrs().HasAny(
{semantics::Attr::POINTER, semantics::Attr::TARGET});
})};
return iter == end ? nullptr : &**iter;
}
struct CollectSymbolsHelper
: public SetTraverse<CollectSymbolsHelper, semantics::UnorderedSymbolSet> {
using Base = SetTraverse<CollectSymbolsHelper, semantics::UnorderedSymbolSet>;
CollectSymbolsHelper() : Base{*this} {}
using Base::operator();
semantics::UnorderedSymbolSet operator()(const Symbol &symbol) const {
return {symbol};
}
};
template <typename A> semantics::UnorderedSymbolSet CollectSymbols(const A &x) {
return CollectSymbolsHelper{}(x);
}
template semantics::UnorderedSymbolSet CollectSymbols(const Expr<SomeType> &);
template semantics::UnorderedSymbolSet CollectSymbols(
const Expr<SomeInteger> &);
template semantics::UnorderedSymbolSet CollectSymbols(
const Expr<SubscriptInteger> &);
struct CollectCudaSymbolsHelper : public SetTraverse<CollectCudaSymbolsHelper,
semantics::UnorderedSymbolSet> {
using Base =
SetTraverse<CollectCudaSymbolsHelper, semantics::UnorderedSymbolSet>;
CollectCudaSymbolsHelper() : Base{*this} {}
using Base::operator();
semantics::UnorderedSymbolSet operator()(const Symbol &symbol) const {
return {symbol};
}
// Overload some of the operator() to filter out the symbols that are not
// of interest for CUDA data transfer logic.
semantics::UnorderedSymbolSet operator()(const DescriptorInquiry &) const {
return {};
}
semantics::UnorderedSymbolSet operator()(const Subscript &) const {
return {};
}
semantics::UnorderedSymbolSet operator()(const ProcedureRef &) const {
return {};
}
};
template <typename A>
semantics::UnorderedSymbolSet CollectCudaSymbols(const A &x) {
return CollectCudaSymbolsHelper{}(x);
}
template semantics::UnorderedSymbolSet CollectCudaSymbols(
const Expr<SomeType> &);
template semantics::UnorderedSymbolSet CollectCudaSymbols(
const Expr<SomeInteger> &);
template semantics::UnorderedSymbolSet CollectCudaSymbols(
const Expr<SubscriptInteger> &);
bool HasCUDAImplicitTransfer(const Expr<SomeType> &expr) {
semantics::UnorderedSymbolSet hostSymbols;
semantics::UnorderedSymbolSet deviceSymbols;
semantics::UnorderedSymbolSet cudaSymbols{CollectCudaSymbols(expr)};
SymbolVector symbols{GetSymbolVector(expr)};
std::reverse(symbols.begin(), symbols.end());
bool skipNext{false};
for (const Symbol &sym : symbols) {
if (cudaSymbols.find(sym) != cudaSymbols.end()) {
bool isComponent{sym.owner().IsDerivedType()};
bool skipComponent{false};
if (!skipNext) {
if (IsCUDADeviceSymbol(sym)) {
deviceSymbols.insert(sym);
} else if (isComponent) {
skipComponent = true; // Component is not device. Look on the base.
} else {
hostSymbols.insert(sym);
}
}
skipNext = isComponent && !skipComponent;
} else {
skipNext = false;
}
}
bool hasConstant{HasConstant(expr)};
return (hasConstant || (hostSymbols.size() > 0)) && deviceSymbols.size() > 0;
}
// HasVectorSubscript()
struct HasVectorSubscriptHelper
: public AnyTraverse<HasVectorSubscriptHelper, bool,
/*TraverseAssocEntityDetails=*/false> {
using Base = AnyTraverse<HasVectorSubscriptHelper, bool, false>;
HasVectorSubscriptHelper() : Base{*this} {}
using Base::operator();
bool operator()(const Subscript &ss) const {
return !std::holds_alternative<Triplet>(ss.u) && ss.Rank() > 0;
}
bool operator()(const ProcedureRef &) const {
return false; // don't descend into function call arguments
}
};
bool HasVectorSubscript(const Expr<SomeType> &expr) {
return HasVectorSubscriptHelper{}(expr);
}
// HasConstant()
struct HasConstantHelper : public AnyTraverse<HasConstantHelper, bool,
/*TraverseAssocEntityDetails=*/false> {
using Base = AnyTraverse<HasConstantHelper, bool, false>;
HasConstantHelper() : Base{*this} {}
using Base::operator();
template <typename T> bool operator()(const Constant<T> &) const {
return true;
}
// Only look for constant not in subscript.
bool operator()(const Subscript &) const { return false; }
};
bool HasConstant(const Expr<SomeType> &expr) {
return HasConstantHelper{}(expr);
}
parser::Message *AttachDeclaration(
parser::Message &message, const Symbol &symbol) {
const Symbol *unhosted{&symbol};
while (
const auto *assoc{unhosted->detailsIf<semantics::HostAssocDetails>()}) {
unhosted = &assoc->symbol();
}
if (const auto *use{symbol.detailsIf<semantics::UseDetails>()}) {
message.Attach(use->location(),
"'%s' is USE-associated with '%s' in module '%s'"_en_US, symbol.name(),
unhosted->name(), GetUsedModule(*use).name());
} else {
message.Attach(
unhosted->name(), "Declaration of '%s'"_en_US, unhosted->name());
}
if (const auto *binding{
unhosted->detailsIf<semantics::ProcBindingDetails>()}) {
if (!symbol.attrs().test(semantics::Attr::DEFERRED) &&
binding->symbol().name() != symbol.name()) {
message.Attach(binding->symbol().name(),
"Procedure '%s' of type '%s' is bound to '%s'"_en_US, symbol.name(),
symbol.owner().GetName().value(), binding->symbol().name());
}
}
return &message;
}
parser::Message *AttachDeclaration(
parser::Message *message, const Symbol &symbol) {
return message ? AttachDeclaration(*message, symbol) : nullptr;
}
class FindImpureCallHelper
: public AnyTraverse<FindImpureCallHelper, std::optional<std::string>,
/*TraverseAssocEntityDetails=*/false> {
using Result = std::optional<std::string>;
using Base = AnyTraverse<FindImpureCallHelper, Result, false>;
public:
explicit FindImpureCallHelper(FoldingContext &c) : Base{*this}, context_{c} {}
using Base::operator();
Result operator()(const ProcedureRef &call) const {
if (auto chars{characteristics::Procedure::Characterize(
call.proc(), context_, /*emitError=*/false)}) {
if (chars->attrs.test(characteristics::Procedure::Attr::Pure)) {
return (*this)(call.arguments());
}
}
return call.proc().GetName();
}
private:
FoldingContext &context_;
};
std::optional<std::string> FindImpureCall(
FoldingContext &context, const Expr<SomeType> &expr) {
return FindImpureCallHelper{context}(expr);
}
std::optional<std::string> FindImpureCall(
FoldingContext &context, const ProcedureRef &proc) {
return FindImpureCallHelper{context}(proc);
}
// Common handling for procedure pointer compatibility of left- and right-hand
// sides. Returns nullopt if they're compatible. Otherwise, it returns a
// message that needs to be augmented by the names of the left and right sides
// and the content of the "whyNotCompatible" string.
std::optional<parser::MessageFixedText> CheckProcCompatibility(bool isCall,
const std::optional<characteristics::Procedure> &lhsProcedure,
const characteristics::Procedure *rhsProcedure,
const SpecificIntrinsic *specificIntrinsic, std::string &whyNotCompatible,
std::optional<std::string> &warning, bool ignoreImplicitVsExplicit) {
std::optional<parser::MessageFixedText> msg;
if (!lhsProcedure) {
msg = "In assignment to object %s, the target '%s' is a procedure"
" designator"_err_en_US;
} else if (!rhsProcedure) {
msg = "In assignment to procedure %s, the characteristics of the target"
" procedure '%s' could not be determined"_err_en_US;
} else if (!isCall && lhsProcedure->functionResult &&
rhsProcedure->functionResult &&
!lhsProcedure->functionResult->IsCompatibleWith(
*rhsProcedure->functionResult, &whyNotCompatible)) {
msg =
"Function %s associated with incompatible function designator '%s': %s"_err_en_US;
} else if (lhsProcedure->IsCompatibleWith(*rhsProcedure,
ignoreImplicitVsExplicit, &whyNotCompatible, specificIntrinsic,
&warning)) {
// OK
} else if (isCall) {
msg = "Procedure %s associated with result of reference to function '%s'"
" that is an incompatible procedure pointer: %s"_err_en_US;
} else if (lhsProcedure->IsPure() && !rhsProcedure->IsPure()) {
msg = "PURE procedure %s may not be associated with non-PURE"
" procedure designator '%s'"_err_en_US;
} else if (lhsProcedure->IsFunction() && rhsProcedure->IsSubroutine()) {
msg = "Function %s may not be associated with subroutine"
" designator '%s'"_err_en_US;
} else if (lhsProcedure->IsSubroutine() && rhsProcedure->IsFunction()) {
msg = "Subroutine %s may not be associated with function"
" designator '%s'"_err_en_US;
} else if (lhsProcedure->HasExplicitInterface() &&
!rhsProcedure->HasExplicitInterface()) {
// Section 10.2.2.4, paragraph 3 prohibits associating a procedure pointer
// that has an explicit interface with a procedure whose characteristics
// don't match. That's the case if the target procedure has an implicit
// interface. But this case is allowed by several other compilers as long
// as the explicit interface can be called via an implicit interface.
if (!lhsProcedure->CanBeCalledViaImplicitInterface()) {
msg = "Procedure %s with explicit interface that cannot be called via "
"an implicit interface cannot be associated with procedure "
"designator with an implicit interface"_err_en_US;
}
} else if (!lhsProcedure->HasExplicitInterface() &&
rhsProcedure->HasExplicitInterface()) {
// OK if the target can be called via an implicit interface
if (!rhsProcedure->CanBeCalledViaImplicitInterface() &&
!specificIntrinsic) {
msg = "Procedure %s with implicit interface may not be associated "
"with procedure designator '%s' with explicit interface that "
"cannot be called via an implicit interface"_err_en_US;
}
} else {
msg = "Procedure %s associated with incompatible procedure"
" designator '%s': %s"_err_en_US;
}
return msg;
}
const Symbol *UnwrapWholeSymbolDataRef(const DataRef &dataRef) {
const SymbolRef *p{std::get_if<SymbolRef>(&dataRef.u)};
return p ? &p->get() : nullptr;
}
const Symbol *UnwrapWholeSymbolDataRef(const std::optional<DataRef> &dataRef) {
return dataRef ? UnwrapWholeSymbolDataRef(*dataRef) : nullptr;
}
const Symbol *UnwrapWholeSymbolOrComponentDataRef(const DataRef &dataRef) {
if (const Component * c{std::get_if<Component>(&dataRef.u)}) {
return c->base().Rank() == 0 ? &c->GetLastSymbol() : nullptr;
} else {
return UnwrapWholeSymbolDataRef(dataRef);
}
}
const Symbol *UnwrapWholeSymbolOrComponentDataRef(
const std::optional<DataRef> &dataRef) {
return dataRef ? UnwrapWholeSymbolOrComponentDataRef(*dataRef) : nullptr;
}
const Symbol *UnwrapWholeSymbolOrComponentOrCoarrayRef(const DataRef &dataRef) {
if (const CoarrayRef * c{std::get_if<CoarrayRef>(&dataRef.u)}) {
return UnwrapWholeSymbolOrComponentOrCoarrayRef(c->base());
} else {
return UnwrapWholeSymbolOrComponentDataRef(dataRef);
}
}
const Symbol *UnwrapWholeSymbolOrComponentOrCoarrayRef(
const std::optional<DataRef> &dataRef) {
return dataRef ? UnwrapWholeSymbolOrComponentOrCoarrayRef(*dataRef) : nullptr;
}
// GetLastPointerSymbol()
static const Symbol *GetLastPointerSymbol(const Symbol &symbol) {
return IsPointer(GetAssociationRoot(symbol)) ? &symbol : nullptr;
}
static const Symbol *GetLastPointerSymbol(const SymbolRef &symbol) {
return GetLastPointerSymbol(*symbol);
}
static const Symbol *GetLastPointerSymbol(const Component &x) {
const Symbol &c{x.GetLastSymbol()};
return IsPointer(c) ? &c : GetLastPointerSymbol(x.base());
}
static const Symbol *GetLastPointerSymbol(const NamedEntity &x) {
const auto *c{x.UnwrapComponent()};
return c ? GetLastPointerSymbol(*c) : GetLastPointerSymbol(x.GetLastSymbol());
}
static const Symbol *GetLastPointerSymbol(const ArrayRef &x) {
return GetLastPointerSymbol(x.base());
}
static const Symbol *GetLastPointerSymbol(const CoarrayRef &x) {
return nullptr;
}
const Symbol *GetLastPointerSymbol(const DataRef &x) {
return common::visit(
[](const auto &y) { return GetLastPointerSymbol(y); }, x.u);
}
template <TypeCategory TO, TypeCategory FROM>
static std::optional<Expr<SomeType>> DataConstantConversionHelper(
FoldingContext &context, const DynamicType &toType,
const Expr<SomeType> &expr) {
if (!common::IsValidKindOfIntrinsicType(FROM, toType.kind())) {
return std::nullopt;
}
DynamicType sizedType{FROM, toType.kind()};
if (auto sized{
Fold(context, ConvertToType(sizedType, Expr<SomeType>{expr}))}) {
if (const auto *someExpr{UnwrapExpr<Expr<SomeKind<FROM>>>(*sized)}) {
return common::visit(
[](const auto &w) -> std::optional<Expr<SomeType>> {
using FromType = ResultType<decltype(w)>;
static constexpr int kind{FromType::kind};
if constexpr (IsValidKindOfIntrinsicType(TO, kind)) {
if (const auto *fromConst{UnwrapExpr<Constant<FromType>>(w)}) {
using FromWordType = typename FromType::Scalar;
using LogicalType = value::Logical<FromWordType::bits>;
using ElementType =
std::conditional_t<TO == TypeCategory::Logical, LogicalType,
typename LogicalType::Word>;
std::vector<ElementType> values;
auto at{fromConst->lbounds()};
auto shape{fromConst->shape()};
for (auto n{GetSize(shape)}; n-- > 0;
fromConst->IncrementSubscripts(at)) {
auto elt{fromConst->At(at)};
if constexpr (TO == TypeCategory::Logical) {
values.emplace_back(std::move(elt));
} else {
values.emplace_back(elt.word());
}
}
return {AsGenericExpr(AsExpr(Constant<Type<TO, kind>>{
std::move(values), std::move(shape)}))};
}
}
return std::nullopt;
},
someExpr->u);
}
}
return std::nullopt;
}
std::optional<Expr<SomeType>> DataConstantConversionExtension(
FoldingContext &context, const DynamicType &toType,
const Expr<SomeType> &expr0) {
Expr<SomeType> expr{Fold(context, Expr<SomeType>{expr0})};
if (!IsActuallyConstant(expr)) {
return std::nullopt;
}
if (auto fromType{expr.GetType()}) {
if (toType.category() == TypeCategory::Logical &&
fromType->category() == TypeCategory::Integer) {
return DataConstantConversionHelper<TypeCategory::Logical,
TypeCategory::Integer>(context, toType, expr);
}
if (toType.category() == TypeCategory::Integer &&
fromType->category() == TypeCategory::Logical) {
return DataConstantConversionHelper<TypeCategory::Integer,
TypeCategory::Logical>(context, toType, expr);
}
}
return std::nullopt;
}
bool IsAllocatableOrPointerObject(const Expr<SomeType> &expr) {
const semantics::Symbol *sym{UnwrapWholeSymbolOrComponentDataRef(expr)};
return (sym &&
semantics::IsAllocatableOrObjectPointer(&sym->GetUltimate())) ||
evaluate::IsObjectPointer(expr) || evaluate::IsNullAllocatable(&expr);
}
bool IsAllocatableDesignator(const Expr<SomeType> &expr) {
// Allocatable sub-objects are not themselves allocatable (9.5.3.1 NOTE 2).
if (const semantics::Symbol *
sym{UnwrapWholeSymbolOrComponentOrCoarrayRef(expr)}) {
return semantics::IsAllocatable(sym->GetUltimate());
}
return false;
}
bool MayBePassedAsAbsentOptional(const Expr<SomeType> &expr) {
const semantics::Symbol *sym{UnwrapWholeSymbolOrComponentDataRef(expr)};
// 15.5.2.12 1. is pretty clear that an unallocated allocatable/pointer actual
// may be passed to a non-allocatable/non-pointer optional dummy. Note that
// other compilers (like nag, nvfortran, ifort, gfortran and xlf) seems to
// ignore this point in intrinsic contexts (e.g CMPLX argument).
return (sym && semantics::IsOptional(*sym)) ||
IsAllocatableOrPointerObject(expr);
}
std::optional<Expr<SomeType>> HollerithToBOZ(FoldingContext &context,
const Expr<SomeType> &expr, const DynamicType &type) {
if (std::optional<std::string> chValue{GetScalarConstantValue<Ascii>(expr)}) {
// Pad on the right with spaces when short, truncate the right if long.
auto bytes{static_cast<std::size_t>(
ToInt64(type.MeasureSizeInBytes(context, false)).value())};
BOZLiteralConstant bits{0};
for (std::size_t j{0}; j < bytes; ++j) {
auto idx{isHostLittleEndian ? j : bytes - j - 1};
char ch{idx >= chValue->size() ? ' ' : chValue->at(idx)};
BOZLiteralConstant chBOZ{static_cast<unsigned char>(ch)};
bits = bits.IOR(chBOZ.SHIFTL(8 * j));
}
return ConvertToType(type, Expr<SomeType>{bits});
} else {
return std::nullopt;
}
}
// Extracts a whole symbol being used as a bound of a dummy argument,
// possibly wrapped with parentheses or MAX(0, ...).
// Works with any integer expression.
template <typename T> const Symbol *GetBoundSymbol(const Expr<T> &);
template <int KIND>
const Symbol *GetBoundSymbol(
const Expr<Type<TypeCategory::Integer, KIND>> &expr) {
using T = Type<TypeCategory::Integer, KIND>;
return common::visit(
common::visitors{
[](const Extremum<T> &max) -> const Symbol * {
if (max.ordering == Ordering::Greater) {
if (auto zero{ToInt64(max.left())}; zero && *zero == 0) {
return GetBoundSymbol(max.right());
}
}
return nullptr;
},
[](const Parentheses<T> &x) { return GetBoundSymbol(x.left()); },
[](const Designator<T> &x) -> const Symbol * {
if (const auto *ref{std::get_if<SymbolRef>(&x.u)}) {
return &**ref;
}
return nullptr;
},
[](const Convert<T, TypeCategory::Integer> &x) {
return common::visit(
[](const auto &y) -> const Symbol * {
using yType = std::decay_t<decltype(y)>;
using yResult = typename yType::Result;
if constexpr (yResult::kind <= KIND) {
return GetBoundSymbol(y);
} else {
return nullptr;
}
},
x.left().u);
},
[](const auto &) -> const Symbol * { return nullptr; },
},
expr.u);
}
template <>
const Symbol *GetBoundSymbol<SomeInteger>(const Expr<SomeInteger> &expr) {
return common::visit(
[](const auto &kindExpr) { return GetBoundSymbol(kindExpr); }, expr.u);
}
template <typename T>
std::optional<bool> AreEquivalentInInterface(
const Expr<T> &x, const Expr<T> &y) {
auto xVal{ToInt64(x)};
auto yVal{ToInt64(y)};
if (xVal && yVal) {
return *xVal == *yVal;
} else if (xVal || yVal) {
return false;
}
const Symbol *xSym{GetBoundSymbol(x)};
const Symbol *ySym{GetBoundSymbol(y)};
if (xSym && ySym) {
if (&xSym->GetUltimate() == &ySym->GetUltimate()) {
return true; // USE/host associated same symbol
}
auto xNum{semantics::GetDummyArgumentNumber(xSym)};
auto yNum{semantics::GetDummyArgumentNumber(ySym)};
if (xNum && yNum) {
if (*xNum == *yNum) {
auto xType{DynamicType::From(*xSym)};
auto yType{DynamicType::From(*ySym)};
return xType && yType && xType->IsEquivalentTo(*yType);
}
}
return false;
} else if (xSym || ySym) {
return false;
}
// Neither expression is an integer constant or a whole symbol.
if (x == y) {
return true;
} else {
return std::nullopt; // not sure
}
}
template std::optional<bool> AreEquivalentInInterface<SubscriptInteger>(
const Expr<SubscriptInteger> &, const Expr<SubscriptInteger> &);
template std::optional<bool> AreEquivalentInInterface<SomeInteger>(
const Expr<SomeInteger> &, const Expr<SomeInteger> &);
bool CheckForCoindexedObject(parser::ContextualMessages &messages,
const std::optional<ActualArgument> &arg, const std::string &procName,
const std::string &argName) {
if (arg && ExtractCoarrayRef(arg->UnwrapExpr())) {
messages.Say(arg->sourceLocation(),
"'%s' argument to '%s' may not be a coindexed object"_err_en_US,
argName, procName);
return false;
} else {
return true;
}
}
bool CheckForSymbolMatch(const Expr<SomeType> *lhs, const Expr<SomeType> *rhs) {
if (lhs && rhs) {
if (SymbolVector lhsSymbols{GetSymbolVector(*lhs)}; !lhsSymbols.empty()) {
const Symbol &first{*lhsSymbols.front()};
for (const Symbol &symbol : GetSymbolVector(*rhs)) {
if (first == symbol) {
return true;
}
}
}
}
return false;
}
namespace operation {
template <typename T> Expr<SomeType> AsSomeExpr(const T &x) {
return AsGenericExpr(common::Clone(x));
}
template <bool IgnoreResizingConverts>
struct ArgumentExtractor
: public Traverse<ArgumentExtractor<IgnoreResizingConverts>,
std::pair<operation::Operator, std::vector<Expr<SomeType>>>, false> {
using Arguments = std::vector<Expr<SomeType>>;
using Result = std::pair<operation::Operator, Arguments>;
using Base =
Traverse<ArgumentExtractor<IgnoreResizingConverts>, Result, false>;
static constexpr auto IgnoreResizes{IgnoreResizingConverts};
static constexpr auto Logical{common::TypeCategory::Logical};
ArgumentExtractor() : Base(*this) {}
Result Default() const { return {}; }
using Base::operator();
template <int Kind>
Result operator()(const Constant<Type<Logical, Kind>> &x) const {
if (const auto &val{x.GetScalarValue()}) {
return val->IsTrue()
? std::make_pair(operation::Operator::True, Arguments{})
: std::make_pair(operation::Operator::False, Arguments{});
}
return Default();
}
template <typename R> Result operator()(const FunctionRef<R> &x) const {
Result result{operation::OperationCode(x.proc()), {}};
for (size_t i{0}, e{x.arguments().size()}; i != e; ++i) {
if (auto *e{x.UnwrapArgExpr(i)}) {
result.second.push_back(*e);
}
}
return result;
}
template <typename D, typename R, typename... Os>
Result operator()(const Operation<D, R, Os...> &x) const {
if constexpr (std::is_same_v<D, Parentheses<R>>) {
// Ignore top-level parentheses.
return (*this)(x.template operand<0>());
}
if constexpr (IgnoreResizes && std::is_same_v<D, Convert<R, R::category>>) {
// Ignore conversions within the same category.
// Atomic operations on int(kind=1) may be implicitly widened
// to int(kind=4) for example.
return (*this)(x.template operand<0>());
} else {
return std::make_pair(operation::OperationCode(x),
OperationArgs(x, std::index_sequence_for<Os...>{}));
}
}
template <typename T> Result operator()(const Designator<T> &x) const {
return {operation::Operator::Identity, {AsSomeExpr(x)}};
}
template <typename T> Result operator()(const Constant<T> &x) const {
return {operation::Operator::Identity, {AsSomeExpr(x)}};
}
template <typename... Rs>
Result Combine(Result &&result, Rs &&...results) const {
// There shouldn't be any combining needed, since we're stopping the
// traversal at the top-level operation, but implement one that picks
// the first non-empty result.
if constexpr (sizeof...(Rs) == 0) {
return std::move(result);
} else {
if (!result.second.empty()) {
return std::move(result);
} else {
return Combine(std::move(results)...);
}
}
}
private:
template <typename D, typename R, typename... Os, size_t... Is>
Arguments OperationArgs(
const Operation<D, R, Os...> &x, std::index_sequence<Is...>) const {
return Arguments{Expr<SomeType>(x.template operand<Is>())...};
}
};
} // namespace operation
std::string operation::ToString(operation::Operator op) {
switch (op) {
case Operator::Unknown:
return "??";
case Operator::Add:
return "+";
case Operator::And:
return "AND";
case Operator::Associated:
return "ASSOCIATED";
case Operator::Call:
return "function-call";
case Operator::Constant:
return "constant";
case Operator::Convert:
return "type-conversion";
case Operator::Div:
return "/";
case Operator::Eq:
return "==";
case Operator::Eqv:
return "EQV";
case Operator::False:
return ".FALSE.";
case Operator::Ge:
return ">=";
case Operator::Gt:
return ">";
case Operator::Identity:
return "identity";
case Operator::Intrinsic:
return "intrinsic";
case Operator::Le:
return "<=";
case Operator::Lt:
return "<";
case Operator::Max:
return "MAX";
case Operator::Min:
return "MIN";
case Operator::Mul:
return "*";
case Operator::Ne:
return "/=";
case Operator::Neqv:
return "NEQV/EOR";
case Operator::Not:
return "NOT";
case Operator::Or:
return "OR";
case Operator::Pow:
return "**";
case Operator::Resize:
return "resize";
case Operator::Sub:
return "-";
case Operator::True:
return ".TRUE.";
}
llvm_unreachable("Unhandler operator");
}
operation::Operator operation::OperationCode(const ProcedureDesignator &proc) {
Operator code{llvm::StringSwitch<Operator>(proc.GetName())
.Case("associated", Operator::Associated)
.Case("min", Operator::Min)
.Case("max", Operator::Max)
.Case("iand", Operator::And)
.Case("ior", Operator::Or)
.Case("ieor", Operator::Neqv)
.Default(Operator::Call)};
if (code == Operator::Call && proc.GetSpecificIntrinsic()) {
return Operator::Intrinsic;
}
return code;
}
std::pair<operation::Operator, std::vector<Expr<SomeType>>>
GetTopLevelOperation(const Expr<SomeType> &expr) {
return operation::ArgumentExtractor<true>{}(expr);
}
namespace operation {
struct ConvertCollector
: public Traverse<ConvertCollector,
std::pair<std::optional<Expr<SomeType>>, std::vector<DynamicType>>,
false> {
using Result =
std::pair<std::optional<Expr<SomeType>>, std::vector<DynamicType>>;
using Base = Traverse<ConvertCollector, Result, false>;
ConvertCollector() : Base(*this) {}
Result Default() const { return {}; }
using Base::operator();
template <typename T> Result operator()(const Designator<T> &x) const {
return {AsSomeExpr(x), {}};
}
template <typename T> Result operator()(const FunctionRef<T> &x) const {
return {AsSomeExpr(x), {}};
}
template <typename T> Result operator()(const Constant<T> &x) const {
return {AsSomeExpr(x), {}};
}
template <typename D, typename R, typename... Os>
Result operator()(const Operation<D, R, Os...> &x) const {
if constexpr (std::is_same_v<D, Parentheses<R>>) {
// Ignore parentheses.
return (*this)(x.template operand<0>());
} else if constexpr (is_convert_v<D>) {
// Convert should always have a typed result, so it should be safe to
// dereference x.GetType().
return Combine(
{std::nullopt, {*x.GetType()}}, (*this)(x.template operand<0>()));
} else if constexpr (is_complex_constructor_v<D>) {
// This is a conversion iff the imaginary operand is 0.
if (IsZero(x.template operand<1>())) {
return Combine(
{std::nullopt, {*x.GetType()}}, (*this)(x.template operand<0>()));
} else {
return {AsSomeExpr(x.derived()), {}};
}
} else {
return {AsSomeExpr(x.derived()), {}};
}
}
template <typename... Rs>
Result Combine(Result &&result, Rs &&...results) const {
Result v(std::move(result));
auto setValue{[](std::optional<Expr<SomeType>> &x,
std::optional<Expr<SomeType>> &&y) {
assert((!x.has_value() || !y.has_value()) && "Multiple designators");
if (!x.has_value()) {
x = std::move(y);
}
}};
auto moveAppend{[](auto &accum, auto &&other) {
for (auto &&s : other) {
accum.push_back(std::move(s));
}
}};
(setValue(v.first, std::move(results).first), ...);
(moveAppend(v.second, std::move(results).second), ...);
return v;
}
private:
template <typename A> static bool IsZero(const A &x) { return false; }
template <typename T> static bool IsZero(const Expr<T> &x) {
return common::visit([](auto &&s) { return IsZero(s); }, x.u);
}
template <typename T> static bool IsZero(const Constant<T> &x) {
if (auto &&maybeScalar{x.GetScalarValue()}) {
return maybeScalar->IsZero();
} else {
return false;
}
}
template <typename T> struct is_convert {
static constexpr bool value{false};
};
template <typename T, common::TypeCategory C>
struct is_convert<Convert<T, C>> {
static constexpr bool value{true};
};
template <int K> struct is_convert<ComplexComponent<K>> {
// Conversion from complex to real.
static constexpr bool value{true};
};
template <typename T>
static constexpr bool is_convert_v{is_convert<T>::value};
template <typename T> struct is_complex_constructor {
static constexpr bool value{false};
};
template <int K> struct is_complex_constructor<ComplexConstructor<K>> {
static constexpr bool value{true};
};
template <typename T>
static constexpr bool is_complex_constructor_v{
is_complex_constructor<T>::value};
};
} // namespace operation
std::optional<Expr<SomeType>> GetConvertInput(const Expr<SomeType> &x) {
// This returns Expr<SomeType>{x} when x is a designator/functionref/constant.
return operation::ConvertCollector{}(x).first;
}
bool IsSameOrConvertOf(const Expr<SomeType> &expr, const Expr<SomeType> &x) {
// Check if expr is same as x, or a sequence of Convert operations on x.
if (expr == x) {
return true;
} else if (auto maybe{GetConvertInput(expr)}) {
return *maybe == x;
} else {
return false;
}
}
} // namespace Fortran::evaluate
namespace Fortran::semantics {
const Symbol &ResolveAssociations(
const Symbol &original, bool stopAtTypeGuard) {
const Symbol &symbol{original.GetUltimate()};
if (const auto *details{symbol.detailsIf<AssocEntityDetails>()}) {
if (!details->rank() /* not RANK(n) or RANK(*) */ &&
!(stopAtTypeGuard && details->isTypeGuard())) {
if (const Symbol * nested{UnwrapWholeSymbolDataRef(details->expr())}) {
return ResolveAssociations(*nested);
}
}
}
return symbol;
}
// When a construct association maps to a variable, and that variable
// is not an array with a vector-valued subscript, return the base
// Symbol of that variable, else nullptr. Descends into other construct
// associations when one associations maps to another.
static const Symbol *GetAssociatedVariable(const AssocEntityDetails &details) {
if (const auto &expr{details.expr()}) {
if (IsVariable(*expr) && !HasVectorSubscript(*expr)) {
if (const Symbol * varSymbol{GetFirstSymbol(*expr)}) {
return &GetAssociationRoot(*varSymbol);
}
}
}
return nullptr;
}
const Symbol &GetAssociationRoot(const Symbol &original, bool stopAtTypeGuard) {
const Symbol &symbol{ResolveAssociations(original, stopAtTypeGuard)};
if (const auto *details{symbol.detailsIf<AssocEntityDetails>()}) {
if (const Symbol * root{GetAssociatedVariable(*details)}) {
return *root;
}
}
return symbol;
}
const Symbol *GetMainEntry(const Symbol *symbol) {
if (symbol) {
if (const auto *subpDetails{symbol->detailsIf<SubprogramDetails>()}) {
if (const Scope * scope{subpDetails->entryScope()}) {
if (const Symbol * main{scope->symbol()}) {
return main;
}
}
}
}
return symbol;
}
bool IsVariableName(const Symbol &original) {
const Symbol &ultimate{original.GetUltimate()};
return !IsNamedConstant(ultimate) &&
(ultimate.has<ObjectEntityDetails>() ||
ultimate.has<AssocEntityDetails>());
}
static bool IsPureProcedureImpl(
const Symbol &original, semantics::UnorderedSymbolSet &set) {
// An ENTRY is pure if its containing subprogram is
const Symbol &symbol{DEREF(GetMainEntry(&original.GetUltimate()))};
if (set.find(symbol) != set.end()) {
return true;
}
set.emplace(symbol);
if (const auto *procDetails{symbol.detailsIf<ProcEntityDetails>()}) {
if (procDetails->procInterface()) {
// procedure with a pure interface
return IsPureProcedureImpl(*procDetails->procInterface(), set);
}
} else if (const auto *details{symbol.detailsIf<ProcBindingDetails>()}) {
return IsPureProcedureImpl(details->symbol(), set);
} else if (!IsProcedure(symbol)) {
return false;
}
if (IsStmtFunction(symbol)) {
// Section 15.7(1) states that a statement function is PURE if it does not
// reference an IMPURE procedure or a VOLATILE variable
if (const auto &expr{symbol.get<SubprogramDetails>().stmtFunction()}) {
for (const SymbolRef &ref : evaluate::CollectSymbols(*expr)) {
if (&*ref == &symbol) {
return false; // error recovery, recursion is caught elsewhere
}
if (IsFunction(*ref) && !IsPureProcedureImpl(*ref, set)) {
return false;
}
if (ref->GetUltimate().attrs().test(Attr::VOLATILE)) {
return false;
}
}
}
return true; // statement function was not found to be impure
}
return symbol.attrs().test(Attr::PURE) ||
(symbol.attrs().test(Attr::ELEMENTAL) &&
!symbol.attrs().test(Attr::IMPURE));
}
bool IsPureProcedure(const Symbol &original) {
semantics::UnorderedSymbolSet set;
return IsPureProcedureImpl(original, set);
}
bool IsPureProcedure(const Scope &scope) {
const Symbol *symbol{scope.GetSymbol()};
return symbol && IsPureProcedure(*symbol);
}
bool IsExplicitlyImpureProcedure(const Symbol &original) {
// An ENTRY is IMPURE if its containing subprogram is so
return DEREF(GetMainEntry(&original.GetUltimate()))
.attrs()
.test(Attr::IMPURE);
}
bool IsElementalProcedure(const Symbol &original) {
// An ENTRY is elemental if its containing subprogram is
const Symbol &symbol{DEREF(GetMainEntry(&original.GetUltimate()))};
if (IsProcedure(symbol)) {
auto &foldingContext{symbol.owner().context().foldingContext()};
auto restorer{foldingContext.messages().DiscardMessages()};
auto proc{evaluate::characteristics::Procedure::Characterize(
symbol, foldingContext)};
return proc &&
proc->attrs.test(evaluate::characteristics::Procedure::Attr::Elemental);
} else {
return false;
}
}
bool IsFunction(const Symbol &symbol) {
const Symbol &ultimate{symbol.GetUltimate()};
return ultimate.test(Symbol::Flag::Function) ||
(!ultimate.test(Symbol::Flag::Subroutine) &&
common::visit(
common::visitors{
[](const SubprogramDetails &x) { return x.isFunction(); },
[](const ProcEntityDetails &x) {
const Symbol *ifc{x.procInterface()};
return x.type() || (ifc && IsFunction(*ifc));
},
[](const ProcBindingDetails &x) {
return IsFunction(x.symbol());
},
[](const auto &) { return false; },
},
ultimate.details()));
}
bool IsFunction(const Scope &scope) {
const Symbol *symbol{scope.GetSymbol()};
return symbol && IsFunction(*symbol);
}
bool IsProcedure(const Symbol &symbol) {
return common::visit(common::visitors{
[&symbol](const SubprogramDetails &) {
const Scope *scope{symbol.scope()};
// Main programs & BLOCK DATA are not procedures.
return !scope ||
scope->kind() == Scope::Kind::Subprogram;
},
[](const SubprogramNameDetails &) { return true; },
[](const ProcEntityDetails &) { return true; },
[](const GenericDetails &) { return true; },
[](const ProcBindingDetails &) { return true; },
[](const auto &) { return false; },
},
symbol.GetUltimate().details());
}
bool IsProcedure(const Scope &scope) {
const Symbol *symbol{scope.GetSymbol()};
return symbol && IsProcedure(*symbol);
}
bool IsProcedurePointer(const Symbol &original) {
const Symbol &symbol{GetAssociationRoot(original)};
return IsPointer(symbol) && IsProcedure(symbol);
}
bool IsProcedurePointer(const Symbol *symbol) {
return symbol && IsProcedurePointer(*symbol);
}
bool IsObjectPointer(const Symbol *original) {
if (original) {
const Symbol &symbol{GetAssociationRoot(*original)};
return IsPointer(symbol) && !IsProcedure(symbol);
} else {
return false;
}
}
bool IsAllocatableOrObjectPointer(const Symbol *original) {
if (original) {
const Symbol &ultimate{original->GetUltimate()};
if (const auto *assoc{ultimate.detailsIf<AssocEntityDetails>()}) {
// Only SELECT RANK construct entities can be ALLOCATABLE/POINTER.
return (assoc->rank() || assoc->IsAssumedSize() ||
assoc->IsAssumedRank()) &&
IsAllocatableOrObjectPointer(UnwrapWholeSymbolDataRef(assoc->expr()));
} else {
return IsAllocatable(ultimate) ||
(IsPointer(ultimate) && !IsProcedure(ultimate));
}
} else {
return false;
}
}
const Symbol *FindCommonBlockContaining(const Symbol &original) {
const Symbol &root{GetAssociationRoot(original)};
const auto *details{root.detailsIf<ObjectEntityDetails>()};
return details ? details->commonBlock() : nullptr;
}
// 3.11 automatic data object
bool IsAutomatic(const Symbol &original) {
const Symbol &symbol{original.GetUltimate()};
if (const auto *object{symbol.detailsIf<ObjectEntityDetails>()}) {
if (!object->isDummy() && !IsAllocatable(symbol) && !IsPointer(symbol)) {
if (const DeclTypeSpec * type{symbol.GetType()}) {
// If a type parameter value is not a constant expression, the
// object is automatic.
if (type->category() == DeclTypeSpec::Character) {
if (const auto &length{
type->characterTypeSpec().length().GetExplicit()}) {
if (!evaluate::IsConstantExpr(*length)) {
return true;
}
}
} else if (const DerivedTypeSpec * derived{type->AsDerived()}) {
for (const auto &pair : derived->parameters()) {
if (const auto &value{pair.second.GetExplicit()}) {
if (!evaluate::IsConstantExpr(*value)) {
return true;
}
}
}
}
}
// If an array bound is not a constant expression, the object is
// automatic.
for (const ShapeSpec &dim : object->shape()) {
if (const auto &lb{dim.lbound().GetExplicit()}) {
if (!evaluate::IsConstantExpr(*lb)) {
return true;
}
}
if (const auto &ub{dim.ubound().GetExplicit()}) {
if (!evaluate::IsConstantExpr(*ub)) {
return true;
}
}
}
}
}
return false;
}
bool IsSaved(const Symbol &original) {
const Symbol &symbol{GetAssociationRoot(original)};
const Scope &scope{symbol.owner()};
const common::LanguageFeatureControl &features{
scope.context().languageFeatures()};
auto scopeKind{scope.kind()};
if (symbol.has<AssocEntityDetails>()) {
return false; // ASSOCIATE(non-variable)
} else if (scopeKind == Scope::Kind::DerivedType) {
return false; // this is a component
} else if (symbol.attrs().test(Attr::SAVE)) {
// explicit or implied SAVE attribute
// N.B.: semantics sets implied SAVE for main program
// local variables whose derived types have coarray
// potential subobject components.
return true;
} else if (IsDummy(symbol) || IsFunctionResult(symbol) ||
IsAutomatic(symbol) || IsNamedConstant(symbol)) {
return false;
} else if (scopeKind == Scope::Kind::Module ||
(scopeKind == Scope::Kind::MainProgram &&
(symbol.attrs().test(Attr::TARGET) || evaluate::IsCoarray(symbol)))) {
// 8.5.16p4
// In main programs, implied SAVE matters only for pointer
// initialization targets and coarrays.
return true;
} else if (scopeKind == Scope::Kind::MainProgram &&
(features.IsEnabled(common::LanguageFeature::SaveMainProgram) ||
(features.IsEnabled(
common::LanguageFeature::SaveBigMainProgramVariables) &&
symbol.size() > 32))) {
// With SaveBigMainProgramVariables, keeping all unsaved main program
// variables of 32 bytes or less on the stack allows keeping numerical and
// logical scalars, small scalar characters or derived, small arrays, and
// scalar descriptors on the stack. This leaves more room for lower level
// optimizers to do register promotion or get easy aliasing information.
return true;
} else if (features.IsEnabled(common::LanguageFeature::DefaultSave) &&
(scopeKind == Scope::Kind::MainProgram ||
(scope.kind() == Scope::Kind::Subprogram &&
!(scope.symbol() &&
scope.symbol()->attrs().test(Attr::RECURSIVE))))) {
// -fno-automatic/-save/-Msave option applies to all objects in executable
// main programs and subprograms unless they are explicitly RECURSIVE.
return true;
} else if (symbol.test(Symbol::Flag::InDataStmt)) {
return true;
} else if (const auto *object{symbol.detailsIf<ObjectEntityDetails>()};
object && object->init()) {
return true;
} else if (IsProcedurePointer(symbol) && symbol.has<ProcEntityDetails>() &&
symbol.get<ProcEntityDetails>().init()) {
return true;
} else if (scope.hasSAVE()) {
return true; // bare SAVE statement
} else if (const Symbol *block{FindCommonBlockContaining(symbol)};
block && block->attrs().test(Attr::SAVE)) {
return true; // in COMMON with SAVE
} else {
return false;
}
}
bool IsDummy(const Symbol &symbol) {
return common::visit(
common::visitors{[](const EntityDetails &x) { return x.isDummy(); },
[](const ObjectEntityDetails &x) { return x.isDummy(); },
[](const ProcEntityDetails &x) { return x.isDummy(); },
[](const SubprogramDetails &x) { return x.isDummy(); },
[](const auto &) { return false; }},
ResolveAssociations(symbol).details());
}
bool IsAssumedShape(const Symbol &symbol) {
const Symbol &ultimate{ResolveAssociations(symbol)};
const auto *object{ultimate.detailsIf<ObjectEntityDetails>()};
return object && object->IsAssumedShape() &&
!semantics::IsAllocatableOrObjectPointer(&ultimate);
}
bool IsDeferredShape(const Symbol &symbol) {
const Symbol &ultimate{ResolveAssociations(symbol)};
const auto *object{ultimate.detailsIf<ObjectEntityDetails>()};
return object && object->CanBeDeferredShape() &&
semantics::IsAllocatableOrObjectPointer(&ultimate);
}
bool IsFunctionResult(const Symbol &original) {
const Symbol &symbol{GetAssociationRoot(original)};
return common::visit(
common::visitors{
[](const EntityDetails &x) { return x.isFuncResult(); },
[](const ObjectEntityDetails &x) { return x.isFuncResult(); },
[](const ProcEntityDetails &x) { return x.isFuncResult(); },
[](const auto &) { return false; },
},
symbol.details());
}
bool IsKindTypeParameter(const Symbol &symbol) {
const auto *param{symbol.GetUltimate().detailsIf<TypeParamDetails>()};
return param && param->attr() == common::TypeParamAttr::Kind;
}
bool IsLenTypeParameter(const Symbol &symbol) {
const auto *param{symbol.GetUltimate().detailsIf<TypeParamDetails>()};
return param && param->attr() == common::TypeParamAttr::Len;
}
bool IsExtensibleType(const DerivedTypeSpec *derived) {
return !IsSequenceOrBindCType(derived) && !IsIsoCType(derived);
}
bool IsSequenceOrBindCType(const DerivedTypeSpec *derived) {
return derived &&
(derived->typeSymbol().attrs().test(Attr::BIND_C) ||
derived->typeSymbol().get<DerivedTypeDetails>().sequence());
}
static bool IsSameModule(const Scope *x, const Scope *y) {
if (x == y) {
return true;
} else if (x && y) {
// Allow for a builtin module to be read from distinct paths
const Symbol *xSym{x->symbol()};
const Symbol *ySym{y->symbol()};
if (xSym && ySym && xSym->name() == ySym->name()) {
const auto *xMod{xSym->detailsIf<ModuleDetails>()};
const auto *yMod{ySym->detailsIf<ModuleDetails>()};
if (xMod && yMod) {
auto xHash{xMod->moduleFileHash()};
auto yHash{yMod->moduleFileHash()};
return xHash && yHash && *xHash == *yHash;
}
}
}
return false;
}
bool IsBuiltinDerivedType(const DerivedTypeSpec *derived, const char *name) {
if (derived) {
const auto &symbol{derived->typeSymbol()};
const Scope &scope{symbol.owner()};
return symbol.name() == "__builtin_"s + name &&
IsSameModule(&scope, scope.context().GetBuiltinsScope());
} else {
return false;
}
}
bool IsBuiltinCPtr(const Symbol &symbol) {
if (const DeclTypeSpec *declType = symbol.GetType()) {
if (const DerivedTypeSpec *derived = declType->AsDerived()) {
return IsIsoCType(derived);
}
}
return false;
}
bool IsFromBuiltinModule(const Symbol &symbol) {
const Scope &scope{symbol.GetUltimate().owner()};
return IsSameModule(&scope, scope.context().GetBuiltinsScope());
}
bool IsIsoCType(const DerivedTypeSpec *derived) {
return IsBuiltinDerivedType(derived, "c_ptr") ||
IsBuiltinDerivedType(derived, "c_funptr");
}
bool IsEventType(const DerivedTypeSpec *derived) {
return IsBuiltinDerivedType(derived, "event_type");
}
bool IsLockType(const DerivedTypeSpec *derived) {
return IsBuiltinDerivedType(derived, "lock_type");
}
bool IsNotifyType(const DerivedTypeSpec *derived) {
return IsBuiltinDerivedType(derived, "notify_type");
}
bool IsIeeeFlagType(const DerivedTypeSpec *derived) {
return IsBuiltinDerivedType(derived, "ieee_flag_type");
}
bool IsIeeeRoundType(const DerivedTypeSpec *derived) {
return IsBuiltinDerivedType(derived, "ieee_round_type");
}
bool IsTeamType(const DerivedTypeSpec *derived) {
return IsBuiltinDerivedType(derived, "team_type");
}
bool IsBadCoarrayType(const DerivedTypeSpec *derived) {
return IsTeamType(derived) || IsIsoCType(derived);
}
bool IsEventTypeOrLockType(const DerivedTypeSpec *derivedTypeSpec) {
return IsEventType(derivedTypeSpec) || IsLockType(derivedTypeSpec);
}
int CountLenParameters(const DerivedTypeSpec &type) {
return llvm::count_if(
type.parameters(), [](const auto &pair) { return pair.second.isLen(); });
}
int CountNonConstantLenParameters(const DerivedTypeSpec &type) {
return llvm::count_if(type.parameters(), [](const auto &pair) {
if (!pair.second.isLen()) {
return false;
} else if (const auto &expr{pair.second.GetExplicit()}) {
return !IsConstantExpr(*expr);
} else {
return true;
}
});
}
const Symbol &GetUsedModule(const UseDetails &details) {
return DEREF(details.symbol().owner().symbol());
}
static const Symbol *FindFunctionResult(
const Symbol &original, UnorderedSymbolSet &seen) {
const Symbol &root{GetAssociationRoot(original)};
;
if (!seen.insert(root).second) {
return nullptr; // don't loop
}
return common::visit(
common::visitors{[](const SubprogramDetails &subp) {
return subp.isFunction() ? &subp.result() : nullptr;
},
[&](const ProcEntityDetails &proc) {
const Symbol *iface{proc.procInterface()};
return iface ? FindFunctionResult(*iface, seen) : nullptr;
},
[&](const ProcBindingDetails &binding) {
return FindFunctionResult(binding.symbol(), seen);
},
[](const auto &) -> const Symbol * { return nullptr; }},
root.details());
}
const Symbol *FindFunctionResult(const Symbol &symbol) {
UnorderedSymbolSet seen;
return FindFunctionResult(symbol, seen);
}
// These are here in Evaluate/tools.cpp so that Evaluate can use
// them; they cannot be defined in symbol.h due to the dependence
// on Scope.
bool SymbolSourcePositionCompare::operator()(
const SymbolRef &x, const SymbolRef &y) const {
return x->GetSemanticsContext().allCookedSources().Precedes(
x->name(), y->name());
}
bool SymbolSourcePositionCompare::operator()(
const MutableSymbolRef &x, const MutableSymbolRef &y) const {
return x->GetSemanticsContext().allCookedSources().Precedes(
x->name(), y->name());
}
SemanticsContext &Symbol::GetSemanticsContext() const {
return DEREF(owner_).context();
}
bool AreTkCompatibleTypes(const DeclTypeSpec *x, const DeclTypeSpec *y) {
if (x && y) {
if (auto xDt{evaluate::DynamicType::From(*x)}) {
if (auto yDt{evaluate::DynamicType::From(*y)}) {
return xDt->IsTkCompatibleWith(*yDt);
}
}
}
return false;
}
common::IgnoreTKRSet GetIgnoreTKR(const Symbol &symbol) {
common::IgnoreTKRSet result;
if (const auto *object{symbol.detailsIf<ObjectEntityDetails>()}) {
result = object->ignoreTKR();
if (const Symbol * ownerSymbol{symbol.owner().symbol()}) {
if (const auto *ownerSubp{ownerSymbol->detailsIf<SubprogramDetails>()}) {
if (ownerSubp->defaultIgnoreTKR()) {
result |= common::ignoreTKRAll;
}
}
}
}
return result;
}
std::optional<int> GetDummyArgumentNumber(const Symbol *symbol) {
if (symbol) {
if (IsDummy(*symbol)) {
if (const Symbol * subpSym{symbol->owner().symbol()}) {
if (const auto *subp{subpSym->detailsIf<SubprogramDetails>()}) {
int j{0};
for (const Symbol *dummy : subp->dummyArgs()) {
if (dummy == symbol) {
return j;
}
++j;
}
}
}
}
}
return std::nullopt;
}
// Given a symbol that is a SubprogramNameDetails in a submodule, try to
// find its interface definition in its module or ancestor submodule.
const Symbol *FindAncestorModuleProcedure(const Symbol *symInSubmodule) {
if (symInSubmodule && symInSubmodule->owner().IsSubmodule()) {
if (const auto *nameDetails{
symInSubmodule->detailsIf<semantics::SubprogramNameDetails>()};
nameDetails &&
nameDetails->kind() == semantics::SubprogramKind::Module) {
const Symbol *next{symInSubmodule->owner().symbol()};
while (const Symbol * submodSym{next}) {
next = nullptr;
if (const auto *modDetails{
submodSym->detailsIf<semantics::ModuleDetails>()};
modDetails && modDetails->isSubmodule() && modDetails->scope()) {
if (const semantics::Scope & parent{modDetails->scope()->parent()};
parent.IsSubmodule() || parent.IsModule()) {
if (auto iter{parent.find(symInSubmodule->name())};
iter != parent.end()) {
const Symbol &proc{iter->second->GetUltimate()};
if (IsProcedure(proc)) {
return &proc;
}
} else if (parent.IsSubmodule()) {
next = parent.symbol();
}
}
}
}
}
}
return nullptr;
}
} // namespace Fortran::semantics
|