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
|
//===- CIRDialect.cpp - MLIR CIR ops implementation -----------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// This file implements the CIR dialect and its operations.
//
//===----------------------------------------------------------------------===//
#include "clang/CIR/Dialect/IR/CIRDialect.h"
#include "clang/CIR/Dialect/IR/CIROpsEnums.h"
#include "clang/CIR/Dialect/IR/CIRTypes.h"
#include "mlir/Interfaces/ControlFlowInterfaces.h"
#include "mlir/Interfaces/FunctionImplementation.h"
#include "mlir/Support/LLVM.h"
#include "clang/CIR/Dialect/IR/CIROpsDialect.cpp.inc"
#include "clang/CIR/Dialect/IR/CIROpsEnums.cpp.inc"
#include "clang/CIR/MissingFeatures.h"
#include "llvm/Support/LogicalResult.h"
#include <numeric>
using namespace mlir;
using namespace cir;
//===----------------------------------------------------------------------===//
// CIR Dialect
//===----------------------------------------------------------------------===//
namespace {
struct CIROpAsmDialectInterface : public OpAsmDialectInterface {
using OpAsmDialectInterface::OpAsmDialectInterface;
AliasResult getAlias(Type type, raw_ostream &os) const final {
if (auto recordType = dyn_cast<cir::RecordType>(type)) {
StringAttr nameAttr = recordType.getName();
if (!nameAttr)
os << "rec_anon_" << recordType.getKindAsStr();
else
os << "rec_" << nameAttr.getValue();
return AliasResult::OverridableAlias;
}
if (auto intType = dyn_cast<cir::IntType>(type)) {
// We only provide alias for standard integer types (i.e. integer types
// whose width is a power of 2 and at least 8).
unsigned width = intType.getWidth();
if (width < 8 || !llvm::isPowerOf2_32(width))
return AliasResult::NoAlias;
os << intType.getAlias();
return AliasResult::OverridableAlias;
}
if (auto voidType = dyn_cast<cir::VoidType>(type)) {
os << voidType.getAlias();
return AliasResult::OverridableAlias;
}
return AliasResult::NoAlias;
}
AliasResult getAlias(Attribute attr, raw_ostream &os) const final {
if (auto boolAttr = mlir::dyn_cast<cir::BoolAttr>(attr)) {
os << (boolAttr.getValue() ? "true" : "false");
return AliasResult::FinalAlias;
}
if (auto bitfield = mlir::dyn_cast<cir::BitfieldInfoAttr>(attr)) {
os << "bfi_" << bitfield.getName().str();
return AliasResult::FinalAlias;
}
return AliasResult::NoAlias;
}
};
} // namespace
void cir::CIRDialect::initialize() {
registerTypes();
registerAttributes();
addOperations<
#define GET_OP_LIST
#include "clang/CIR/Dialect/IR/CIROps.cpp.inc"
>();
addInterfaces<CIROpAsmDialectInterface>();
}
Operation *cir::CIRDialect::materializeConstant(mlir::OpBuilder &builder,
mlir::Attribute value,
mlir::Type type,
mlir::Location loc) {
return builder.create<cir::ConstantOp>(loc, type,
mlir::cast<mlir::TypedAttr>(value));
}
//===----------------------------------------------------------------------===//
// Helpers
//===----------------------------------------------------------------------===//
// Parses one of the keywords provided in the list `keywords` and returns the
// position of the parsed keyword in the list. If none of the keywords from the
// list is parsed, returns -1.
static int parseOptionalKeywordAlternative(AsmParser &parser,
ArrayRef<llvm::StringRef> keywords) {
for (auto en : llvm::enumerate(keywords)) {
if (succeeded(parser.parseOptionalKeyword(en.value())))
return en.index();
}
return -1;
}
namespace {
template <typename Ty> struct EnumTraits {};
#define REGISTER_ENUM_TYPE(Ty) \
template <> struct EnumTraits<cir::Ty> { \
static llvm::StringRef stringify(cir::Ty value) { \
return stringify##Ty(value); \
} \
static unsigned getMaxEnumVal() { return cir::getMaxEnumValFor##Ty(); } \
}
REGISTER_ENUM_TYPE(GlobalLinkageKind);
REGISTER_ENUM_TYPE(VisibilityKind);
REGISTER_ENUM_TYPE(SideEffect);
} // namespace
/// Parse an enum from the keyword, or default to the provided default value.
/// The return type is the enum type by default, unless overriden with the
/// second template argument.
template <typename EnumTy, typename RetTy = EnumTy>
static RetTy parseOptionalCIRKeyword(AsmParser &parser, EnumTy defaultValue) {
llvm::SmallVector<llvm::StringRef, 10> names;
for (unsigned i = 0, e = EnumTraits<EnumTy>::getMaxEnumVal(); i <= e; ++i)
names.push_back(EnumTraits<EnumTy>::stringify(static_cast<EnumTy>(i)));
int index = parseOptionalKeywordAlternative(parser, names);
if (index == -1)
return static_cast<RetTy>(defaultValue);
return static_cast<RetTy>(index);
}
/// Parse an enum from the keyword, return failure if the keyword is not found.
template <typename EnumTy, typename RetTy = EnumTy>
static ParseResult parseCIRKeyword(AsmParser &parser, RetTy &result) {
llvm::SmallVector<llvm::StringRef, 10> names;
for (unsigned i = 0, e = EnumTraits<EnumTy>::getMaxEnumVal(); i <= e; ++i)
names.push_back(EnumTraits<EnumTy>::stringify(static_cast<EnumTy>(i)));
int index = parseOptionalKeywordAlternative(parser, names);
if (index == -1)
return failure();
result = static_cast<RetTy>(index);
return success();
}
// Check if a region's termination omission is valid and, if so, creates and
// inserts the omitted terminator into the region.
static LogicalResult ensureRegionTerm(OpAsmParser &parser, Region ®ion,
SMLoc errLoc) {
Location eLoc = parser.getEncodedSourceLoc(parser.getCurrentLocation());
OpBuilder builder(parser.getBuilder().getContext());
// Insert empty block in case the region is empty to ensure the terminator
// will be inserted
if (region.empty())
builder.createBlock(®ion);
Block &block = region.back();
// Region is properly terminated: nothing to do.
if (!block.empty() && block.back().hasTrait<OpTrait::IsTerminator>())
return success();
// Check for invalid terminator omissions.
if (!region.hasOneBlock())
return parser.emitError(errLoc,
"multi-block region must not omit terminator");
// Terminator was omitted correctly: recreate it.
builder.setInsertionPointToEnd(&block);
builder.create<cir::YieldOp>(eLoc);
return success();
}
// True if the region's terminator should be omitted.
static bool omitRegionTerm(mlir::Region &r) {
const auto singleNonEmptyBlock = r.hasOneBlock() && !r.back().empty();
const auto yieldsNothing = [&r]() {
auto y = dyn_cast<cir::YieldOp>(r.back().getTerminator());
return y && y.getArgs().empty();
};
return singleNonEmptyBlock && yieldsNothing();
}
void printVisibilityAttr(OpAsmPrinter &printer,
cir::VisibilityAttr &visibility) {
switch (visibility.getValue()) {
case cir::VisibilityKind::Hidden:
printer << "hidden";
break;
case cir::VisibilityKind::Protected:
printer << "protected";
break;
case cir::VisibilityKind::Default:
break;
}
}
void parseVisibilityAttr(OpAsmParser &parser, cir::VisibilityAttr &visibility) {
cir::VisibilityKind visibilityKind =
parseOptionalCIRKeyword(parser, cir::VisibilityKind::Default);
visibility = cir::VisibilityAttr::get(parser.getContext(), visibilityKind);
}
//===----------------------------------------------------------------------===//
// CIR Custom Parsers/Printers
//===----------------------------------------------------------------------===//
static mlir::ParseResult parseOmittedTerminatorRegion(mlir::OpAsmParser &parser,
mlir::Region ®ion) {
auto regionLoc = parser.getCurrentLocation();
if (parser.parseRegion(region))
return failure();
if (ensureRegionTerm(parser, region, regionLoc).failed())
return failure();
return success();
}
static void printOmittedTerminatorRegion(mlir::OpAsmPrinter &printer,
cir::ScopeOp &op,
mlir::Region ®ion) {
printer.printRegion(region,
/*printEntryBlockArgs=*/false,
/*printBlockTerminators=*/!omitRegionTerm(region));
}
//===----------------------------------------------------------------------===//
// AllocaOp
//===----------------------------------------------------------------------===//
void cir::AllocaOp::build(mlir::OpBuilder &odsBuilder,
mlir::OperationState &odsState, mlir::Type addr,
mlir::Type allocaType, llvm::StringRef name,
mlir::IntegerAttr alignment) {
odsState.addAttribute(getAllocaTypeAttrName(odsState.name),
mlir::TypeAttr::get(allocaType));
odsState.addAttribute(getNameAttrName(odsState.name),
odsBuilder.getStringAttr(name));
if (alignment) {
odsState.addAttribute(getAlignmentAttrName(odsState.name), alignment);
}
odsState.addTypes(addr);
}
//===----------------------------------------------------------------------===//
// BreakOp
//===----------------------------------------------------------------------===//
LogicalResult cir::BreakOp::verify() {
assert(!cir::MissingFeatures::switchOp());
if (!getOperation()->getParentOfType<LoopOpInterface>() &&
!getOperation()->getParentOfType<SwitchOp>())
return emitOpError("must be within a loop");
return success();
}
//===----------------------------------------------------------------------===//
// ConditionOp
//===----------------------------------------------------------------------===//
//===----------------------------------
// BranchOpTerminatorInterface Methods
//===----------------------------------
void cir::ConditionOp::getSuccessorRegions(
ArrayRef<Attribute> operands, SmallVectorImpl<RegionSuccessor> ®ions) {
// TODO(cir): The condition value may be folded to a constant, narrowing
// down its list of possible successors.
// Parent is a loop: condition may branch to the body or to the parent op.
if (auto loopOp = dyn_cast<LoopOpInterface>(getOperation()->getParentOp())) {
regions.emplace_back(&loopOp.getBody(), loopOp.getBody().getArguments());
regions.emplace_back(loopOp->getResults());
}
assert(!cir::MissingFeatures::awaitOp());
}
MutableOperandRange
cir::ConditionOp::getMutableSuccessorOperands(RegionBranchPoint point) {
// No values are yielded to the successor region.
return MutableOperandRange(getOperation(), 0, 0);
}
LogicalResult cir::ConditionOp::verify() {
assert(!cir::MissingFeatures::awaitOp());
if (!isa<LoopOpInterface>(getOperation()->getParentOp()))
return emitOpError("condition must be within a conditional region");
return success();
}
//===----------------------------------------------------------------------===//
// ConstantOp
//===----------------------------------------------------------------------===//
static LogicalResult checkConstantTypes(mlir::Operation *op, mlir::Type opType,
mlir::Attribute attrType) {
if (isa<cir::ConstPtrAttr>(attrType)) {
if (!mlir::isa<cir::PointerType>(opType))
return op->emitOpError(
"pointer constant initializing a non-pointer type");
return success();
}
if (isa<cir::ZeroAttr>(attrType)) {
if (isa<cir::RecordType, cir::ArrayType, cir::VectorType, cir::ComplexType>(
opType))
return success();
return op->emitOpError(
"zero expects struct, array, vector, or complex type");
}
if (mlir::isa<cir::BoolAttr>(attrType)) {
if (!mlir::isa<cir::BoolType>(opType))
return op->emitOpError("result type (")
<< opType << ") must be '!cir.bool' for '" << attrType << "'";
return success();
}
if (mlir::isa<cir::IntAttr, cir::FPAttr>(attrType)) {
auto at = cast<TypedAttr>(attrType);
if (at.getType() != opType) {
return op->emitOpError("result type (")
<< opType << ") does not match value type (" << at.getType()
<< ")";
}
return success();
}
if (mlir::isa<cir::ConstArrayAttr, cir::ConstVectorAttr,
cir::ConstComplexAttr, cir::PoisonAttr>(attrType))
return success();
assert(isa<TypedAttr>(attrType) && "What else could we be looking at here?");
return op->emitOpError("global with type ")
<< cast<TypedAttr>(attrType).getType() << " not yet supported";
}
LogicalResult cir::ConstantOp::verify() {
// ODS already generates checks to make sure the result type is valid. We just
// need to additionally check that the value's attribute type is consistent
// with the result type.
return checkConstantTypes(getOperation(), getType(), getValue());
}
OpFoldResult cir::ConstantOp::fold(FoldAdaptor /*adaptor*/) {
return getValue();
}
//===----------------------------------------------------------------------===//
// ContinueOp
//===----------------------------------------------------------------------===//
LogicalResult cir::ContinueOp::verify() {
if (!getOperation()->getParentOfType<LoopOpInterface>())
return emitOpError("must be within a loop");
return success();
}
//===----------------------------------------------------------------------===//
// CastOp
//===----------------------------------------------------------------------===//
LogicalResult cir::CastOp::verify() {
mlir::Type resType = getType();
mlir::Type srcType = getSrc().getType();
if (mlir::isa<cir::VectorType>(srcType) &&
mlir::isa<cir::VectorType>(resType)) {
// Use the element type of the vector to verify the cast kind. (Except for
// bitcast, see below.)
srcType = mlir::dyn_cast<cir::VectorType>(srcType).getElementType();
resType = mlir::dyn_cast<cir::VectorType>(resType).getElementType();
}
switch (getKind()) {
case cir::CastKind::int_to_bool: {
if (!mlir::isa<cir::BoolType>(resType))
return emitOpError() << "requires !cir.bool type for result";
if (!mlir::isa<cir::IntType>(srcType))
return emitOpError() << "requires !cir.int type for source";
return success();
}
case cir::CastKind::ptr_to_bool: {
if (!mlir::isa<cir::BoolType>(resType))
return emitOpError() << "requires !cir.bool type for result";
if (!mlir::isa<cir::PointerType>(srcType))
return emitOpError() << "requires !cir.ptr type for source";
return success();
}
case cir::CastKind::integral: {
if (!mlir::isa<cir::IntType>(resType))
return emitOpError() << "requires !cir.int type for result";
if (!mlir::isa<cir::IntType>(srcType))
return emitOpError() << "requires !cir.int type for source";
return success();
}
case cir::CastKind::array_to_ptrdecay: {
const auto arrayPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
const auto flatPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
if (!arrayPtrTy || !flatPtrTy)
return emitOpError() << "requires !cir.ptr type for source and result";
// TODO(CIR): Make sure the AddrSpace of both types are equals
return success();
}
case cir::CastKind::bitcast: {
// Handle the pointer types first.
auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
if (srcPtrTy && resPtrTy) {
return success();
}
return success();
}
case cir::CastKind::floating: {
if (!mlir::isa<cir::FPTypeInterface>(srcType) ||
!mlir::isa<cir::FPTypeInterface>(resType))
return emitOpError() << "requires !cir.float type for source and result";
return success();
}
case cir::CastKind::float_to_int: {
if (!mlir::isa<cir::FPTypeInterface>(srcType))
return emitOpError() << "requires !cir.float type for source";
if (!mlir::dyn_cast<cir::IntType>(resType))
return emitOpError() << "requires !cir.int type for result";
return success();
}
case cir::CastKind::int_to_ptr: {
if (!mlir::dyn_cast<cir::IntType>(srcType))
return emitOpError() << "requires !cir.int type for source";
if (!mlir::dyn_cast<cir::PointerType>(resType))
return emitOpError() << "requires !cir.ptr type for result";
return success();
}
case cir::CastKind::ptr_to_int: {
if (!mlir::dyn_cast<cir::PointerType>(srcType))
return emitOpError() << "requires !cir.ptr type for source";
if (!mlir::dyn_cast<cir::IntType>(resType))
return emitOpError() << "requires !cir.int type for result";
return success();
}
case cir::CastKind::float_to_bool: {
if (!mlir::isa<cir::FPTypeInterface>(srcType))
return emitOpError() << "requires !cir.float type for source";
if (!mlir::isa<cir::BoolType>(resType))
return emitOpError() << "requires !cir.bool type for result";
return success();
}
case cir::CastKind::bool_to_int: {
if (!mlir::isa<cir::BoolType>(srcType))
return emitOpError() << "requires !cir.bool type for source";
if (!mlir::isa<cir::IntType>(resType))
return emitOpError() << "requires !cir.int type for result";
return success();
}
case cir::CastKind::int_to_float: {
if (!mlir::isa<cir::IntType>(srcType))
return emitOpError() << "requires !cir.int type for source";
if (!mlir::isa<cir::FPTypeInterface>(resType))
return emitOpError() << "requires !cir.float type for result";
return success();
}
case cir::CastKind::bool_to_float: {
if (!mlir::isa<cir::BoolType>(srcType))
return emitOpError() << "requires !cir.bool type for source";
if (!mlir::isa<cir::FPTypeInterface>(resType))
return emitOpError() << "requires !cir.float type for result";
return success();
}
case cir::CastKind::address_space: {
auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
if (!srcPtrTy || !resPtrTy)
return emitOpError() << "requires !cir.ptr type for source and result";
if (srcPtrTy.getPointee() != resPtrTy.getPointee())
return emitOpError() << "requires two types differ in addrspace only";
return success();
}
case cir::CastKind::float_to_complex: {
if (!mlir::isa<cir::FPTypeInterface>(srcType))
return emitOpError() << "requires !cir.float type for source";
auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
if (!resComplexTy)
return emitOpError() << "requires !cir.complex type for result";
if (srcType != resComplexTy.getElementType())
return emitOpError() << "requires source type match result element type";
return success();
}
case cir::CastKind::int_to_complex: {
if (!mlir::isa<cir::IntType>(srcType))
return emitOpError() << "requires !cir.int type for source";
auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
if (!resComplexTy)
return emitOpError() << "requires !cir.complex type for result";
if (srcType != resComplexTy.getElementType())
return emitOpError() << "requires source type match result element type";
return success();
}
case cir::CastKind::float_complex_to_real: {
auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
if (!srcComplexTy)
return emitOpError() << "requires !cir.complex type for source";
if (!mlir::isa<cir::FPTypeInterface>(resType))
return emitOpError() << "requires !cir.float type for result";
if (srcComplexTy.getElementType() != resType)
return emitOpError() << "requires source element type match result type";
return success();
}
case cir::CastKind::int_complex_to_real: {
auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
if (!srcComplexTy)
return emitOpError() << "requires !cir.complex type for source";
if (!mlir::isa<cir::IntType>(resType))
return emitOpError() << "requires !cir.int type for result";
if (srcComplexTy.getElementType() != resType)
return emitOpError() << "requires source element type match result type";
return success();
}
case cir::CastKind::float_complex_to_bool: {
auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
return emitOpError()
<< "requires floating point !cir.complex type for source";
if (!mlir::isa<cir::BoolType>(resType))
return emitOpError() << "requires !cir.bool type for result";
return success();
}
case cir::CastKind::int_complex_to_bool: {
auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
return emitOpError()
<< "requires floating point !cir.complex type for source";
if (!mlir::isa<cir::BoolType>(resType))
return emitOpError() << "requires !cir.bool type for result";
return success();
}
case cir::CastKind::float_complex: {
auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
return emitOpError()
<< "requires floating point !cir.complex type for source";
auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
if (!resComplexTy || !resComplexTy.isFloatingPointComplex())
return emitOpError()
<< "requires floating point !cir.complex type for result";
return success();
}
case cir::CastKind::float_complex_to_int_complex: {
auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
return emitOpError()
<< "requires floating point !cir.complex type for source";
auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
if (!resComplexTy || !resComplexTy.isIntegerComplex())
return emitOpError() << "requires integer !cir.complex type for result";
return success();
}
case cir::CastKind::int_complex: {
auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
return emitOpError() << "requires integer !cir.complex type for source";
auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
if (!resComplexTy || !resComplexTy.isIntegerComplex())
return emitOpError() << "requires integer !cir.complex type for result";
return success();
}
case cir::CastKind::int_complex_to_float_complex: {
auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
return emitOpError() << "requires integer !cir.complex type for source";
auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
if (!resComplexTy || !resComplexTy.isFloatingPointComplex())
return emitOpError()
<< "requires floating point !cir.complex type for result";
return success();
}
default:
llvm_unreachable("Unknown CastOp kind?");
}
}
static bool isIntOrBoolCast(cir::CastOp op) {
auto kind = op.getKind();
return kind == cir::CastKind::bool_to_int ||
kind == cir::CastKind::int_to_bool || kind == cir::CastKind::integral;
}
static Value tryFoldCastChain(cir::CastOp op) {
cir::CastOp head = op, tail = op;
while (op) {
if (!isIntOrBoolCast(op))
break;
head = op;
op = dyn_cast_or_null<cir::CastOp>(head.getSrc().getDefiningOp());
}
if (head == tail)
return {};
// if bool_to_int -> ... -> int_to_bool: take the bool
// as we had it was before all casts
if (head.getKind() == cir::CastKind::bool_to_int &&
tail.getKind() == cir::CastKind::int_to_bool)
return head.getSrc();
// if int_to_bool -> ... -> int_to_bool: take the result
// of the first one, as no other casts (and ext casts as well)
// don't change the first result
if (head.getKind() == cir::CastKind::int_to_bool &&
tail.getKind() == cir::CastKind::int_to_bool)
return head.getResult();
return {};
}
OpFoldResult cir::CastOp::fold(FoldAdaptor adaptor) {
if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getSrc())) {
// Propagate poison value
return cir::PoisonAttr::get(getContext(), getType());
}
if (getSrc().getType() == getType()) {
switch (getKind()) {
case cir::CastKind::integral: {
// TODO: for sign differences, it's possible in certain conditions to
// create a new attribute that's capable of representing the source.
llvm::SmallVector<mlir::OpFoldResult, 1> foldResults;
auto foldOrder = getSrc().getDefiningOp()->fold(foldResults);
if (foldOrder.succeeded() && mlir::isa<mlir::Attribute>(foldResults[0]))
return mlir::cast<mlir::Attribute>(foldResults[0]);
return {};
}
case cir::CastKind::bitcast:
case cir::CastKind::address_space:
case cir::CastKind::float_complex:
case cir::CastKind::int_complex: {
return getSrc();
}
default:
return {};
}
}
return tryFoldCastChain(*this);
}
//===----------------------------------------------------------------------===//
// CallOp
//===----------------------------------------------------------------------===//
mlir::OperandRange cir::CallOp::getArgOperands() {
if (isIndirect())
return getArgs().drop_front(1);
return getArgs();
}
mlir::MutableOperandRange cir::CallOp::getArgOperandsMutable() {
mlir::MutableOperandRange args = getArgsMutable();
if (isIndirect())
return args.slice(1, args.size() - 1);
return args;
}
mlir::Value cir::CallOp::getIndirectCall() {
assert(isIndirect());
return getOperand(0);
}
/// Return the operand at index 'i'.
Value cir::CallOp::getArgOperand(unsigned i) {
if (isIndirect())
++i;
return getOperand(i);
}
/// Return the number of operands.
unsigned cir::CallOp::getNumArgOperands() {
if (isIndirect())
return this->getOperation()->getNumOperands() - 1;
return this->getOperation()->getNumOperands();
}
static mlir::ParseResult parseCallCommon(mlir::OpAsmParser &parser,
mlir::OperationState &result) {
llvm::SmallVector<mlir::OpAsmParser::UnresolvedOperand, 4> ops;
llvm::SMLoc opsLoc;
mlir::FlatSymbolRefAttr calleeAttr;
llvm::ArrayRef<mlir::Type> allResultTypes;
// If we cannot parse a string callee, it means this is an indirect call.
if (!parser
.parseOptionalAttribute(calleeAttr, CIRDialect::getCalleeAttrName(),
result.attributes)
.has_value()) {
OpAsmParser::UnresolvedOperand indirectVal;
// Do not resolve right now, since we need to figure out the type
if (parser.parseOperand(indirectVal).failed())
return failure();
ops.push_back(indirectVal);
}
if (parser.parseLParen())
return mlir::failure();
opsLoc = parser.getCurrentLocation();
if (parser.parseOperandList(ops))
return mlir::failure();
if (parser.parseRParen())
return mlir::failure();
if (parser.parseOptionalKeyword("nothrow").succeeded())
result.addAttribute(CIRDialect::getNoThrowAttrName(),
mlir::UnitAttr::get(parser.getContext()));
if (parser.parseOptionalKeyword("side_effect").succeeded()) {
if (parser.parseLParen().failed())
return failure();
cir::SideEffect sideEffect;
if (parseCIRKeyword<cir::SideEffect>(parser, sideEffect).failed())
return failure();
if (parser.parseRParen().failed())
return failure();
auto attr = cir::SideEffectAttr::get(parser.getContext(), sideEffect);
result.addAttribute(CIRDialect::getSideEffectAttrName(), attr);
}
if (parser.parseOptionalAttrDict(result.attributes))
return ::mlir::failure();
if (parser.parseColon())
return ::mlir::failure();
mlir::FunctionType opsFnTy;
if (parser.parseType(opsFnTy))
return mlir::failure();
allResultTypes = opsFnTy.getResults();
result.addTypes(allResultTypes);
if (parser.resolveOperands(ops, opsFnTy.getInputs(), opsLoc, result.operands))
return mlir::failure();
return mlir::success();
}
static void printCallCommon(mlir::Operation *op,
mlir::FlatSymbolRefAttr calleeSym,
mlir::Value indirectCallee,
mlir::OpAsmPrinter &printer, bool isNothrow,
cir::SideEffect sideEffect) {
printer << ' ';
auto callLikeOp = mlir::cast<cir::CIRCallOpInterface>(op);
auto ops = callLikeOp.getArgOperands();
if (calleeSym) {
// Direct calls
printer.printAttributeWithoutType(calleeSym);
} else {
// Indirect calls
assert(indirectCallee);
printer << indirectCallee;
}
printer << "(" << ops << ")";
if (isNothrow)
printer << " nothrow";
if (sideEffect != cir::SideEffect::All) {
printer << " side_effect(";
printer << stringifySideEffect(sideEffect);
printer << ")";
}
printer.printOptionalAttrDict(op->getAttrs(),
{CIRDialect::getCalleeAttrName(),
CIRDialect::getNoThrowAttrName(),
CIRDialect::getSideEffectAttrName()});
printer << " : ";
printer.printFunctionalType(op->getOperands().getTypes(),
op->getResultTypes());
}
mlir::ParseResult cir::CallOp::parse(mlir::OpAsmParser &parser,
mlir::OperationState &result) {
return parseCallCommon(parser, result);
}
void cir::CallOp::print(mlir::OpAsmPrinter &p) {
mlir::Value indirectCallee = isIndirect() ? getIndirectCall() : nullptr;
cir::SideEffect sideEffect = getSideEffect();
printCallCommon(*this, getCalleeAttr(), indirectCallee, p, getNothrow(),
sideEffect);
}
static LogicalResult
verifyCallCommInSymbolUses(mlir::Operation *op,
SymbolTableCollection &symbolTable) {
auto fnAttr =
op->getAttrOfType<FlatSymbolRefAttr>(CIRDialect::getCalleeAttrName());
if (!fnAttr) {
// This is an indirect call, thus we don't have to check the symbol uses.
return mlir::success();
}
auto fn = symbolTable.lookupNearestSymbolFrom<cir::FuncOp>(op, fnAttr);
if (!fn)
return op->emitOpError() << "'" << fnAttr.getValue()
<< "' does not reference a valid function";
auto callIf = dyn_cast<cir::CIRCallOpInterface>(op);
assert(callIf && "expected CIR call interface to be always available");
// Verify that the operand and result types match the callee. Note that
// argument-checking is disabled for functions without a prototype.
auto fnType = fn.getFunctionType();
if (!fn.getNoProto()) {
unsigned numCallOperands = callIf.getNumArgOperands();
unsigned numFnOpOperands = fnType.getNumInputs();
if (!fnType.isVarArg() && numCallOperands != numFnOpOperands)
return op->emitOpError("incorrect number of operands for callee");
if (fnType.isVarArg() && numCallOperands < numFnOpOperands)
return op->emitOpError("too few operands for callee");
for (unsigned i = 0, e = numFnOpOperands; i != e; ++i)
if (callIf.getArgOperand(i).getType() != fnType.getInput(i))
return op->emitOpError("operand type mismatch: expected operand type ")
<< fnType.getInput(i) << ", but provided "
<< op->getOperand(i).getType() << " for operand number " << i;
}
assert(!cir::MissingFeatures::opCallCallConv());
// Void function must not return any results.
if (fnType.hasVoidReturn() && op->getNumResults() != 0)
return op->emitOpError("callee returns void but call has results");
// Non-void function calls must return exactly one result.
if (!fnType.hasVoidReturn() && op->getNumResults() != 1)
return op->emitOpError("incorrect number of results for callee");
// Parent function and return value types must match.
if (!fnType.hasVoidReturn() &&
op->getResultTypes().front() != fnType.getReturnType()) {
return op->emitOpError("result type mismatch: expected ")
<< fnType.getReturnType() << ", but provided "
<< op->getResult(0).getType();
}
return mlir::success();
}
LogicalResult
cir::CallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
return verifyCallCommInSymbolUses(*this, symbolTable);
}
//===----------------------------------------------------------------------===//
// ReturnOp
//===----------------------------------------------------------------------===//
static mlir::LogicalResult checkReturnAndFunction(cir::ReturnOp op,
cir::FuncOp function) {
// ReturnOps currently only have a single optional operand.
if (op.getNumOperands() > 1)
return op.emitOpError() << "expects at most 1 return operand";
// Ensure returned type matches the function signature.
auto expectedTy = function.getFunctionType().getReturnType();
auto actualTy =
(op.getNumOperands() == 0 ? cir::VoidType::get(op.getContext())
: op.getOperand(0).getType());
if (actualTy != expectedTy)
return op.emitOpError() << "returns " << actualTy
<< " but enclosing function returns " << expectedTy;
return mlir::success();
}
mlir::LogicalResult cir::ReturnOp::verify() {
// Returns can be present in multiple different scopes, get the
// wrapping function and start from there.
auto *fnOp = getOperation()->getParentOp();
while (!isa<cir::FuncOp>(fnOp))
fnOp = fnOp->getParentOp();
// Make sure return types match function return type.
if (checkReturnAndFunction(*this, cast<cir::FuncOp>(fnOp)).failed())
return failure();
return success();
}
//===----------------------------------------------------------------------===//
// IfOp
//===----------------------------------------------------------------------===//
ParseResult cir::IfOp::parse(OpAsmParser &parser, OperationState &result) {
// create the regions for 'then'.
result.regions.reserve(2);
Region *thenRegion = result.addRegion();
Region *elseRegion = result.addRegion();
mlir::Builder &builder = parser.getBuilder();
OpAsmParser::UnresolvedOperand cond;
Type boolType = cir::BoolType::get(builder.getContext());
if (parser.parseOperand(cond) ||
parser.resolveOperand(cond, boolType, result.operands))
return failure();
// Parse 'then' region.
mlir::SMLoc parseThenLoc = parser.getCurrentLocation();
if (parser.parseRegion(*thenRegion, /*arguments=*/{}, /*argTypes=*/{}))
return failure();
if (ensureRegionTerm(parser, *thenRegion, parseThenLoc).failed())
return failure();
// If we find an 'else' keyword, parse the 'else' region.
if (!parser.parseOptionalKeyword("else")) {
mlir::SMLoc parseElseLoc = parser.getCurrentLocation();
if (parser.parseRegion(*elseRegion, /*arguments=*/{}, /*argTypes=*/{}))
return failure();
if (ensureRegionTerm(parser, *elseRegion, parseElseLoc).failed())
return failure();
}
// Parse the optional attribute list.
if (parser.parseOptionalAttrDict(result.attributes))
return failure();
return success();
}
void cir::IfOp::print(OpAsmPrinter &p) {
p << " " << getCondition() << " ";
mlir::Region &thenRegion = this->getThenRegion();
p.printRegion(thenRegion,
/*printEntryBlockArgs=*/false,
/*printBlockTerminators=*/!omitRegionTerm(thenRegion));
// Print the 'else' regions if it exists and has a block.
mlir::Region &elseRegion = this->getElseRegion();
if (!elseRegion.empty()) {
p << " else ";
p.printRegion(elseRegion,
/*printEntryBlockArgs=*/false,
/*printBlockTerminators=*/!omitRegionTerm(elseRegion));
}
p.printOptionalAttrDict(getOperation()->getAttrs());
}
/// Default callback for IfOp builders.
void cir::buildTerminatedBody(OpBuilder &builder, Location loc) {
// add cir.yield to end of the block
builder.create<cir::YieldOp>(loc);
}
/// Given the region at `index`, or the parent operation if `index` is None,
/// return the successor regions. These are the regions that may be selected
/// during the flow of control. `operands` is a set of optional attributes that
/// correspond to a constant value for each operand, or null if that operand is
/// not a constant.
void cir::IfOp::getSuccessorRegions(mlir::RegionBranchPoint point,
SmallVectorImpl<RegionSuccessor> ®ions) {
// The `then` and the `else` region branch back to the parent operation.
if (!point.isParent()) {
regions.push_back(RegionSuccessor());
return;
}
// Don't consider the else region if it is empty.
Region *elseRegion = &this->getElseRegion();
if (elseRegion->empty())
elseRegion = nullptr;
// If the condition isn't constant, both regions may be executed.
regions.push_back(RegionSuccessor(&getThenRegion()));
// If the else region does not exist, it is not a viable successor.
if (elseRegion)
regions.push_back(RegionSuccessor(elseRegion));
return;
}
void cir::IfOp::build(OpBuilder &builder, OperationState &result, Value cond,
bool withElseRegion, BuilderCallbackRef thenBuilder,
BuilderCallbackRef elseBuilder) {
assert(thenBuilder && "the builder callback for 'then' must be present");
result.addOperands(cond);
OpBuilder::InsertionGuard guard(builder);
Region *thenRegion = result.addRegion();
builder.createBlock(thenRegion);
thenBuilder(builder, result.location);
Region *elseRegion = result.addRegion();
if (!withElseRegion)
return;
builder.createBlock(elseRegion);
elseBuilder(builder, result.location);
}
//===----------------------------------------------------------------------===//
// ScopeOp
//===----------------------------------------------------------------------===//
/// Given the region at `index`, or the parent operation if `index` is None,
/// return the successor regions. These are the regions that may be selected
/// during the flow of control. `operands` is a set of optional attributes
/// that correspond to a constant value for each operand, or null if that
/// operand is not a constant.
void cir::ScopeOp::getSuccessorRegions(
mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
// The only region always branch back to the parent operation.
if (!point.isParent()) {
regions.push_back(RegionSuccessor(getODSResults(0)));
return;
}
// If the condition isn't constant, both regions may be executed.
regions.push_back(RegionSuccessor(&getScopeRegion()));
}
void cir::ScopeOp::build(
OpBuilder &builder, OperationState &result,
function_ref<void(OpBuilder &, Type &, Location)> scopeBuilder) {
assert(scopeBuilder && "the builder callback for 'then' must be present");
OpBuilder::InsertionGuard guard(builder);
Region *scopeRegion = result.addRegion();
builder.createBlock(scopeRegion);
assert(!cir::MissingFeatures::opScopeCleanupRegion());
mlir::Type yieldTy;
scopeBuilder(builder, yieldTy, result.location);
if (yieldTy)
result.addTypes(TypeRange{yieldTy});
}
void cir::ScopeOp::build(
OpBuilder &builder, OperationState &result,
function_ref<void(OpBuilder &, Location)> scopeBuilder) {
assert(scopeBuilder && "the builder callback for 'then' must be present");
OpBuilder::InsertionGuard guard(builder);
Region *scopeRegion = result.addRegion();
builder.createBlock(scopeRegion);
assert(!cir::MissingFeatures::opScopeCleanupRegion());
scopeBuilder(builder, result.location);
}
LogicalResult cir::ScopeOp::verify() {
if (getRegion().empty()) {
return emitOpError() << "cir.scope must not be empty since it should "
"include at least an implicit cir.yield ";
}
mlir::Block &lastBlock = getRegion().back();
if (lastBlock.empty() || !lastBlock.mightHaveTerminator() ||
!lastBlock.getTerminator()->hasTrait<OpTrait::IsTerminator>())
return emitOpError() << "last block of cir.scope must be terminated";
return success();
}
//===----------------------------------------------------------------------===//
// BrOp
//===----------------------------------------------------------------------===//
mlir::SuccessorOperands cir::BrOp::getSuccessorOperands(unsigned index) {
assert(index == 0 && "invalid successor index");
return mlir::SuccessorOperands(getDestOperandsMutable());
}
Block *cir::BrOp::getSuccessorForOperands(ArrayRef<Attribute>) {
return getDest();
}
//===----------------------------------------------------------------------===//
// BrCondOp
//===----------------------------------------------------------------------===//
mlir::SuccessorOperands cir::BrCondOp::getSuccessorOperands(unsigned index) {
assert(index < getNumSuccessors() && "invalid successor index");
return SuccessorOperands(index == 0 ? getDestOperandsTrueMutable()
: getDestOperandsFalseMutable());
}
Block *cir::BrCondOp::getSuccessorForOperands(ArrayRef<Attribute> operands) {
if (IntegerAttr condAttr = dyn_cast_if_present<IntegerAttr>(operands.front()))
return condAttr.getValue().isOne() ? getDestTrue() : getDestFalse();
return nullptr;
}
//===----------------------------------------------------------------------===//
// CaseOp
//===----------------------------------------------------------------------===//
void cir::CaseOp::getSuccessorRegions(
mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
if (!point.isParent()) {
regions.push_back(RegionSuccessor());
return;
}
regions.push_back(RegionSuccessor(&getCaseRegion()));
}
void cir::CaseOp::build(OpBuilder &builder, OperationState &result,
ArrayAttr value, CaseOpKind kind,
OpBuilder::InsertPoint &insertPoint) {
OpBuilder::InsertionGuard guardSwitch(builder);
result.addAttribute("value", value);
result.getOrAddProperties<Properties>().kind =
cir::CaseOpKindAttr::get(builder.getContext(), kind);
Region *caseRegion = result.addRegion();
builder.createBlock(caseRegion);
insertPoint = builder.saveInsertionPoint();
}
//===----------------------------------------------------------------------===//
// SwitchOp
//===----------------------------------------------------------------------===//
static ParseResult parseSwitchOp(OpAsmParser &parser, mlir::Region ®ions,
mlir::OpAsmParser::UnresolvedOperand &cond,
mlir::Type &condType) {
cir::IntType intCondType;
if (parser.parseLParen())
return mlir::failure();
if (parser.parseOperand(cond))
return mlir::failure();
if (parser.parseColon())
return mlir::failure();
if (parser.parseCustomTypeWithFallback(intCondType))
return mlir::failure();
condType = intCondType;
if (parser.parseRParen())
return mlir::failure();
if (parser.parseRegion(regions, /*arguments=*/{}, /*argTypes=*/{}))
return failure();
return mlir::success();
}
static void printSwitchOp(OpAsmPrinter &p, cir::SwitchOp op,
mlir::Region &bodyRegion, mlir::Value condition,
mlir::Type condType) {
p << "(";
p << condition;
p << " : ";
p.printStrippedAttrOrType(condType);
p << ")";
p << ' ';
p.printRegion(bodyRegion, /*printEntryBlockArgs=*/false,
/*printBlockTerminators=*/true);
}
void cir::SwitchOp::getSuccessorRegions(
mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ion) {
if (!point.isParent()) {
region.push_back(RegionSuccessor());
return;
}
region.push_back(RegionSuccessor(&getBody()));
}
void cir::SwitchOp::build(OpBuilder &builder, OperationState &result,
Value cond, BuilderOpStateCallbackRef switchBuilder) {
assert(switchBuilder && "the builder callback for regions must be present");
OpBuilder::InsertionGuard guardSwitch(builder);
Region *switchRegion = result.addRegion();
builder.createBlock(switchRegion);
result.addOperands({cond});
switchBuilder(builder, result.location, result);
}
void cir::SwitchOp::collectCases(llvm::SmallVectorImpl<CaseOp> &cases) {
walk<mlir::WalkOrder::PreOrder>([&](mlir::Operation *op) {
// Don't walk in nested switch op.
if (isa<cir::SwitchOp>(op) && op != *this)
return WalkResult::skip();
if (auto caseOp = dyn_cast<cir::CaseOp>(op))
cases.push_back(caseOp);
return WalkResult::advance();
});
}
bool cir::SwitchOp::isSimpleForm(llvm::SmallVectorImpl<CaseOp> &cases) {
collectCases(cases);
if (getBody().empty())
return false;
if (!isa<YieldOp>(getBody().front().back()))
return false;
if (!llvm::all_of(getBody().front(),
[](Operation &op) { return isa<CaseOp, YieldOp>(op); }))
return false;
return llvm::all_of(cases, [this](CaseOp op) {
return op->getParentOfType<SwitchOp>() == *this;
});
}
//===----------------------------------------------------------------------===//
// SwitchFlatOp
//===----------------------------------------------------------------------===//
void cir::SwitchFlatOp::build(OpBuilder &builder, OperationState &result,
Value value, Block *defaultDestination,
ValueRange defaultOperands,
ArrayRef<APInt> caseValues,
BlockRange caseDestinations,
ArrayRef<ValueRange> caseOperands) {
std::vector<mlir::Attribute> caseValuesAttrs;
for (const APInt &val : caseValues)
caseValuesAttrs.push_back(cir::IntAttr::get(value.getType(), val));
mlir::ArrayAttr attrs = ArrayAttr::get(builder.getContext(), caseValuesAttrs);
build(builder, result, value, defaultOperands, caseOperands, attrs,
defaultDestination, caseDestinations);
}
/// <cases> ::= `[` (case (`,` case )* )? `]`
/// <case> ::= integer `:` bb-id (`(` ssa-use-and-type-list `)`)?
static ParseResult parseSwitchFlatOpCases(
OpAsmParser &parser, Type flagType, mlir::ArrayAttr &caseValues,
SmallVectorImpl<Block *> &caseDestinations,
SmallVectorImpl<llvm::SmallVector<OpAsmParser::UnresolvedOperand>>
&caseOperands,
SmallVectorImpl<llvm::SmallVector<Type>> &caseOperandTypes) {
if (failed(parser.parseLSquare()))
return failure();
if (succeeded(parser.parseOptionalRSquare()))
return success();
llvm::SmallVector<mlir::Attribute> values;
auto parseCase = [&]() {
int64_t value = 0;
if (failed(parser.parseInteger(value)))
return failure();
values.push_back(cir::IntAttr::get(flagType, value));
Block *destination;
llvm::SmallVector<OpAsmParser::UnresolvedOperand> operands;
llvm::SmallVector<Type> operandTypes;
if (parser.parseColon() || parser.parseSuccessor(destination))
return failure();
if (!parser.parseOptionalLParen()) {
if (parser.parseOperandList(operands, OpAsmParser::Delimiter::None,
/*allowResultNumber=*/false) ||
parser.parseColonTypeList(operandTypes) || parser.parseRParen())
return failure();
}
caseDestinations.push_back(destination);
caseOperands.emplace_back(operands);
caseOperandTypes.emplace_back(operandTypes);
return success();
};
if (failed(parser.parseCommaSeparatedList(parseCase)))
return failure();
caseValues = ArrayAttr::get(flagType.getContext(), values);
return parser.parseRSquare();
}
static void printSwitchFlatOpCases(OpAsmPrinter &p, cir::SwitchFlatOp op,
Type flagType, mlir::ArrayAttr caseValues,
SuccessorRange caseDestinations,
OperandRangeRange caseOperands,
const TypeRangeRange &caseOperandTypes) {
p << '[';
p.printNewline();
if (!caseValues) {
p << ']';
return;
}
size_t index = 0;
llvm::interleave(
llvm::zip(caseValues, caseDestinations),
[&](auto i) {
p << " ";
mlir::Attribute a = std::get<0>(i);
p << mlir::cast<cir::IntAttr>(a).getValue();
p << ": ";
p.printSuccessorAndUseList(std::get<1>(i), caseOperands[index++]);
},
[&] {
p << ',';
p.printNewline();
});
p.printNewline();
p << ']';
}
//===----------------------------------------------------------------------===//
// GlobalOp
//===----------------------------------------------------------------------===//
static ParseResult parseConstantValue(OpAsmParser &parser,
mlir::Attribute &valueAttr) {
NamedAttrList attr;
return parser.parseAttribute(valueAttr, "value", attr);
}
static void printConstant(OpAsmPrinter &p, Attribute value) {
p.printAttribute(value);
}
mlir::LogicalResult cir::GlobalOp::verify() {
// Verify that the initial value, if present, is either a unit attribute or
// an attribute CIR supports.
if (getInitialValue().has_value()) {
if (checkConstantTypes(getOperation(), getSymType(), *getInitialValue())
.failed())
return failure();
}
// TODO(CIR): Many other checks for properties that haven't been upstreamed
// yet.
return success();
}
void cir::GlobalOp::build(OpBuilder &odsBuilder, OperationState &odsState,
llvm::StringRef sym_name, mlir::Type sym_type,
cir::GlobalLinkageKind linkage) {
odsState.addAttribute(getSymNameAttrName(odsState.name),
odsBuilder.getStringAttr(sym_name));
odsState.addAttribute(getSymTypeAttrName(odsState.name),
mlir::TypeAttr::get(sym_type));
cir::GlobalLinkageKindAttr linkageAttr =
cir::GlobalLinkageKindAttr::get(odsBuilder.getContext(), linkage);
odsState.addAttribute(getLinkageAttrName(odsState.name), linkageAttr);
odsState.addAttribute(getGlobalVisibilityAttrName(odsState.name),
cir::VisibilityAttr::get(odsBuilder.getContext()));
}
static void printGlobalOpTypeAndInitialValue(OpAsmPrinter &p, cir::GlobalOp op,
TypeAttr type,
Attribute initAttr) {
if (!op.isDeclaration()) {
p << "= ";
// This also prints the type...
if (initAttr)
printConstant(p, initAttr);
} else {
p << ": " << type;
}
}
static ParseResult
parseGlobalOpTypeAndInitialValue(OpAsmParser &parser, TypeAttr &typeAttr,
Attribute &initialValueAttr) {
mlir::Type opTy;
if (parser.parseOptionalEqual().failed()) {
// Absence of equal means a declaration, so we need to parse the type.
// cir.global @a : !cir.int<s, 32>
if (parser.parseColonType(opTy))
return failure();
} else {
// Parse constant with initializer, examples:
// cir.global @y = #cir.fp<1.250000e+00> : !cir.double
// cir.global @rgb = #cir.const_array<[...] : !cir.array<i8 x 3>>
if (parseConstantValue(parser, initialValueAttr).failed())
return failure();
assert(mlir::isa<mlir::TypedAttr>(initialValueAttr) &&
"Non-typed attrs shouldn't appear here.");
auto typedAttr = mlir::cast<mlir::TypedAttr>(initialValueAttr);
opTy = typedAttr.getType();
}
typeAttr = TypeAttr::get(opTy);
return success();
}
//===----------------------------------------------------------------------===//
// GetGlobalOp
//===----------------------------------------------------------------------===//
LogicalResult
cir::GetGlobalOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
// Verify that the result type underlying pointer type matches the type of
// the referenced cir.global or cir.func op.
mlir::Operation *op =
symbolTable.lookupNearestSymbolFrom(*this, getNameAttr());
if (op == nullptr || !(isa<GlobalOp>(op) || isa<FuncOp>(op)))
return emitOpError("'")
<< getName()
<< "' does not reference a valid cir.global or cir.func";
mlir::Type symTy;
if (auto g = dyn_cast<GlobalOp>(op)) {
symTy = g.getSymType();
assert(!cir::MissingFeatures::addressSpace());
assert(!cir::MissingFeatures::opGlobalThreadLocal());
} else if (auto f = dyn_cast<FuncOp>(op)) {
symTy = f.getFunctionType();
} else {
llvm_unreachable("Unexpected operation for GetGlobalOp");
}
auto resultType = dyn_cast<PointerType>(getAddr().getType());
if (!resultType || symTy != resultType.getPointee())
return emitOpError("result type pointee type '")
<< resultType.getPointee() << "' does not match type " << symTy
<< " of the global @" << getName();
return success();
}
//===----------------------------------------------------------------------===//
// FuncOp
//===----------------------------------------------------------------------===//
/// Returns the name used for the linkage attribute. This *must* correspond to
/// the name of the attribute in ODS.
static llvm::StringRef getLinkageAttrNameString() { return "linkage"; }
void cir::FuncOp::build(OpBuilder &builder, OperationState &result,
StringRef name, FuncType type,
GlobalLinkageKind linkage) {
result.addRegion();
result.addAttribute(SymbolTable::getSymbolAttrName(),
builder.getStringAttr(name));
result.addAttribute(getFunctionTypeAttrName(result.name),
TypeAttr::get(type));
result.addAttribute(
getLinkageAttrNameString(),
GlobalLinkageKindAttr::get(builder.getContext(), linkage));
result.addAttribute(getGlobalVisibilityAttrName(result.name),
cir::VisibilityAttr::get(builder.getContext()));
}
ParseResult cir::FuncOp::parse(OpAsmParser &parser, OperationState &state) {
llvm::SMLoc loc = parser.getCurrentLocation();
mlir::Builder &builder = parser.getBuilder();
mlir::StringAttr noProtoNameAttr = getNoProtoAttrName(state.name);
mlir::StringAttr visNameAttr = getSymVisibilityAttrName(state.name);
mlir::StringAttr visibilityNameAttr = getGlobalVisibilityAttrName(state.name);
mlir::StringAttr dsoLocalNameAttr = getDsoLocalAttrName(state.name);
if (parser.parseOptionalKeyword(noProtoNameAttr).succeeded())
state.addAttribute(noProtoNameAttr, parser.getBuilder().getUnitAttr());
// Default to external linkage if no keyword is provided.
state.addAttribute(getLinkageAttrNameString(),
GlobalLinkageKindAttr::get(
parser.getContext(),
parseOptionalCIRKeyword<GlobalLinkageKind>(
parser, GlobalLinkageKind::ExternalLinkage)));
::llvm::StringRef visAttrStr;
if (parser.parseOptionalKeyword(&visAttrStr, {"private", "public", "nested"})
.succeeded()) {
state.addAttribute(visNameAttr,
parser.getBuilder().getStringAttr(visAttrStr));
}
cir::VisibilityAttr cirVisibilityAttr;
parseVisibilityAttr(parser, cirVisibilityAttr);
state.addAttribute(visibilityNameAttr, cirVisibilityAttr);
if (parser.parseOptionalKeyword(dsoLocalNameAttr).succeeded())
state.addAttribute(dsoLocalNameAttr, parser.getBuilder().getUnitAttr());
StringAttr nameAttr;
if (parser.parseSymbolName(nameAttr, SymbolTable::getSymbolAttrName(),
state.attributes))
return failure();
llvm::SmallVector<OpAsmParser::Argument, 8> arguments;
llvm::SmallVector<mlir::Type> resultTypes;
llvm::SmallVector<DictionaryAttr> resultAttrs;
bool isVariadic = false;
if (function_interface_impl::parseFunctionSignatureWithArguments(
parser, /*allowVariadic=*/true, arguments, isVariadic, resultTypes,
resultAttrs))
return failure();
llvm::SmallVector<mlir::Type> argTypes;
for (OpAsmParser::Argument &arg : arguments)
argTypes.push_back(arg.type);
if (resultTypes.size() > 1) {
return parser.emitError(
loc, "functions with multiple return types are not supported");
}
mlir::Type returnType =
(resultTypes.empty() ? cir::VoidType::get(builder.getContext())
: resultTypes.front());
cir::FuncType fnType = cir::FuncType::get(argTypes, returnType, isVariadic);
if (!fnType)
return failure();
state.addAttribute(getFunctionTypeAttrName(state.name),
TypeAttr::get(fnType));
bool hasAlias = false;
mlir::StringAttr aliaseeNameAttr = getAliaseeAttrName(state.name);
if (parser.parseOptionalKeyword("alias").succeeded()) {
if (parser.parseLParen().failed())
return failure();
mlir::StringAttr aliaseeAttr;
if (parser.parseOptionalSymbolName(aliaseeAttr).failed())
return failure();
state.addAttribute(aliaseeNameAttr, FlatSymbolRefAttr::get(aliaseeAttr));
if (parser.parseRParen().failed())
return failure();
hasAlias = true;
}
// Parse the optional function body.
auto *body = state.addRegion();
OptionalParseResult parseResult = parser.parseOptionalRegion(
*body, arguments, /*enableNameShadowing=*/false);
if (parseResult.has_value()) {
if (hasAlias)
return parser.emitError(loc, "function alias shall not have a body");
if (failed(*parseResult))
return failure();
// Function body was parsed, make sure its not empty.
if (body->empty())
return parser.emitError(loc, "expected non-empty function body");
}
return success();
}
// This function corresponds to `llvm::GlobalValue::isDeclaration` and should
// have a similar implementation. We don't currently ifuncs or materializable
// functions, but those should be handled here as they are implemented.
bool cir::FuncOp::isDeclaration() {
assert(!cir::MissingFeatures::supportIFuncAttr());
std::optional<StringRef> aliasee = getAliasee();
if (!aliasee)
return getFunctionBody().empty();
// Aliases are always definitions.
return false;
}
mlir::Region *cir::FuncOp::getCallableRegion() {
// TODO(CIR): This function will have special handling for aliases and a
// check for an external function, once those features have been upstreamed.
return &getBody();
}
void cir::FuncOp::print(OpAsmPrinter &p) {
if (getNoProto())
p << " no_proto";
if (getComdat())
p << " comdat";
if (getLinkage() != GlobalLinkageKind::ExternalLinkage)
p << ' ' << stringifyGlobalLinkageKind(getLinkage());
mlir::SymbolTable::Visibility vis = getVisibility();
if (vis != mlir::SymbolTable::Visibility::Public)
p << ' ' << vis;
cir::VisibilityAttr cirVisibilityAttr = getGlobalVisibilityAttr();
if (!cirVisibilityAttr.isDefault()) {
p << ' ';
printVisibilityAttr(p, cirVisibilityAttr);
}
if (getDsoLocal())
p << " dso_local";
p << ' ';
p.printSymbolName(getSymName());
cir::FuncType fnType = getFunctionType();
function_interface_impl::printFunctionSignature(
p, *this, fnType.getInputs(), fnType.isVarArg(), fnType.getReturnTypes());
if (std::optional<StringRef> aliaseeName = getAliasee()) {
p << " alias(";
p.printSymbolName(*aliaseeName);
p << ")";
}
// Print the body if this is not an external function.
Region &body = getOperation()->getRegion(0);
if (!body.empty()) {
p << ' ';
p.printRegion(body, /*printEntryBlockArgs=*/false,
/*printBlockTerminators=*/true);
}
}
// TODO(CIR): The properties of functions that require verification haven't
// been implemented yet.
mlir::LogicalResult cir::FuncOp::verify() { return success(); }
//===----------------------------------------------------------------------===//
// BinOp
//===----------------------------------------------------------------------===//
LogicalResult cir::BinOp::verify() {
bool noWrap = getNoUnsignedWrap() || getNoSignedWrap();
bool saturated = getSaturated();
if (!isa<cir::IntType>(getType()) && noWrap)
return emitError()
<< "only operations on integer values may have nsw/nuw flags";
bool noWrapOps = getKind() == cir::BinOpKind::Add ||
getKind() == cir::BinOpKind::Sub ||
getKind() == cir::BinOpKind::Mul;
bool saturatedOps =
getKind() == cir::BinOpKind::Add || getKind() == cir::BinOpKind::Sub;
if (noWrap && !noWrapOps)
return emitError() << "The nsw/nuw flags are applicable to opcodes: 'add', "
"'sub' and 'mul'";
if (saturated && !saturatedOps)
return emitError() << "The saturated flag is applicable to opcodes: 'add' "
"and 'sub'";
if (noWrap && saturated)
return emitError() << "The nsw/nuw flags and the saturated flag are "
"mutually exclusive";
assert(!cir::MissingFeatures::complexType());
// TODO(cir): verify for complex binops
return mlir::success();
}
//===----------------------------------------------------------------------===//
// TernaryOp
//===----------------------------------------------------------------------===//
/// Given the region at `point`, or the parent operation if `point` is None,
/// return the successor regions. These are the regions that may be selected
/// during the flow of control. `operands` is a set of optional attributes that
/// correspond to a constant value for each operand, or null if that operand is
/// not a constant.
void cir::TernaryOp::getSuccessorRegions(
mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
// The `true` and the `false` region branch back to the parent operation.
if (!point.isParent()) {
regions.push_back(RegionSuccessor(this->getODSResults(0)));
return;
}
// When branching from the parent operation, both the true and false
// regions are considered possible successors
regions.push_back(RegionSuccessor(&getTrueRegion()));
regions.push_back(RegionSuccessor(&getFalseRegion()));
}
void cir::TernaryOp::build(
OpBuilder &builder, OperationState &result, Value cond,
function_ref<void(OpBuilder &, Location)> trueBuilder,
function_ref<void(OpBuilder &, Location)> falseBuilder) {
result.addOperands(cond);
OpBuilder::InsertionGuard guard(builder);
Region *trueRegion = result.addRegion();
Block *block = builder.createBlock(trueRegion);
trueBuilder(builder, result.location);
Region *falseRegion = result.addRegion();
builder.createBlock(falseRegion);
falseBuilder(builder, result.location);
auto yield = dyn_cast<YieldOp>(block->getTerminator());
assert((yield && yield.getNumOperands() <= 1) &&
"expected zero or one result type");
if (yield.getNumOperands() == 1)
result.addTypes(TypeRange{yield.getOperandTypes().front()});
}
//===----------------------------------------------------------------------===//
// SelectOp
//===----------------------------------------------------------------------===//
OpFoldResult cir::SelectOp::fold(FoldAdaptor adaptor) {
mlir::Attribute condition = adaptor.getCondition();
if (condition) {
bool conditionValue = mlir::cast<cir::BoolAttr>(condition).getValue();
return conditionValue ? getTrueValue() : getFalseValue();
}
// cir.select if %0 then x else x -> x
mlir::Attribute trueValue = adaptor.getTrueValue();
mlir::Attribute falseValue = adaptor.getFalseValue();
if (trueValue == falseValue)
return trueValue;
if (getTrueValue() == getFalseValue())
return getTrueValue();
return {};
}
//===----------------------------------------------------------------------===//
// ShiftOp
//===----------------------------------------------------------------------===//
LogicalResult cir::ShiftOp::verify() {
mlir::Operation *op = getOperation();
auto op0VecTy = mlir::dyn_cast<cir::VectorType>(op->getOperand(0).getType());
auto op1VecTy = mlir::dyn_cast<cir::VectorType>(op->getOperand(1).getType());
if (!op0VecTy ^ !op1VecTy)
return emitOpError() << "input types cannot be one vector and one scalar";
if (op0VecTy) {
if (op0VecTy.getSize() != op1VecTy.getSize())
return emitOpError() << "input vector types must have the same size";
auto opResultTy = mlir::dyn_cast<cir::VectorType>(getType());
if (!opResultTy)
return emitOpError() << "the type of the result must be a vector "
<< "if it is vector shift";
auto op0VecEleTy = mlir::cast<cir::IntType>(op0VecTy.getElementType());
auto op1VecEleTy = mlir::cast<cir::IntType>(op1VecTy.getElementType());
if (op0VecEleTy.getWidth() != op1VecEleTy.getWidth())
return emitOpError()
<< "vector operands do not have the same elements sizes";
auto resVecEleTy = mlir::cast<cir::IntType>(opResultTy.getElementType());
if (op0VecEleTy.getWidth() != resVecEleTy.getWidth())
return emitOpError() << "vector operands and result type do not have the "
"same elements sizes";
}
return mlir::success();
}
//===----------------------------------------------------------------------===//
// UnaryOp
//===----------------------------------------------------------------------===//
LogicalResult cir::UnaryOp::verify() {
switch (getKind()) {
case cir::UnaryOpKind::Inc:
case cir::UnaryOpKind::Dec:
case cir::UnaryOpKind::Plus:
case cir::UnaryOpKind::Minus:
case cir::UnaryOpKind::Not:
// Nothing to verify.
return success();
}
llvm_unreachable("Unknown UnaryOp kind?");
}
static bool isBoolNot(cir::UnaryOp op) {
return isa<cir::BoolType>(op.getInput().getType()) &&
op.getKind() == cir::UnaryOpKind::Not;
}
// This folder simplifies the sequential boolean not operations.
// For instance, the next two unary operations will be eliminated:
//
// ```mlir
// %1 = cir.unary(not, %0) : !cir.bool, !cir.bool
// %2 = cir.unary(not, %1) : !cir.bool, !cir.bool
// ```
//
// and the argument of the first one (%0) will be used instead.
OpFoldResult cir::UnaryOp::fold(FoldAdaptor adaptor) {
if (auto poison =
mlir::dyn_cast_if_present<cir::PoisonAttr>(adaptor.getInput())) {
// Propagate poison values
return poison;
}
if (isBoolNot(*this))
if (auto previous = dyn_cast_or_null<UnaryOp>(getInput().getDefiningOp()))
if (isBoolNot(previous))
return previous.getInput();
return {};
}
//===----------------------------------------------------------------------===//
// GetMemberOp Definitions
//===----------------------------------------------------------------------===//
LogicalResult cir::GetMemberOp::verify() {
const auto recordTy = dyn_cast<RecordType>(getAddrTy().getPointee());
if (!recordTy)
return emitError() << "expected pointer to a record type";
if (recordTy.getMembers().size() <= getIndex())
return emitError() << "member index out of bounds";
if (recordTy.getMembers()[getIndex()] != getType().getPointee())
return emitError() << "member type mismatch";
return mlir::success();
}
//===----------------------------------------------------------------------===//
// VecCreateOp
//===----------------------------------------------------------------------===//
OpFoldResult cir::VecCreateOp::fold(FoldAdaptor adaptor) {
if (llvm::any_of(getElements(), [](mlir::Value value) {
return !mlir::isa<cir::ConstantOp>(value.getDefiningOp());
}))
return {};
return cir::ConstVectorAttr::get(
getType(), mlir::ArrayAttr::get(getContext(), adaptor.getElements()));
}
LogicalResult cir::VecCreateOp::verify() {
// Verify that the number of arguments matches the number of elements in the
// vector, and that the type of all the arguments matches the type of the
// elements in the vector.
const cir::VectorType vecTy = getType();
if (getElements().size() != vecTy.getSize()) {
return emitOpError() << "operand count of " << getElements().size()
<< " doesn't match vector type " << vecTy
<< " element count of " << vecTy.getSize();
}
const mlir::Type elementType = vecTy.getElementType();
for (const mlir::Value element : getElements()) {
if (element.getType() != elementType) {
return emitOpError() << "operand type " << element.getType()
<< " doesn't match vector element type "
<< elementType;
}
}
return success();
}
//===----------------------------------------------------------------------===//
// VecExtractOp
//===----------------------------------------------------------------------===//
OpFoldResult cir::VecExtractOp::fold(FoldAdaptor adaptor) {
const auto vectorAttr =
llvm::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec());
if (!vectorAttr)
return {};
const auto indexAttr =
llvm::dyn_cast_if_present<cir::IntAttr>(adaptor.getIndex());
if (!indexAttr)
return {};
const mlir::ArrayAttr elements = vectorAttr.getElts();
const uint64_t index = indexAttr.getUInt();
if (index >= elements.size())
return {};
return elements[index];
}
//===----------------------------------------------------------------------===//
// VecCmpOp
//===----------------------------------------------------------------------===//
OpFoldResult cir::VecCmpOp::fold(FoldAdaptor adaptor) {
auto lhsVecAttr =
mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getLhs());
auto rhsVecAttr =
mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getRhs());
if (!lhsVecAttr || !rhsVecAttr)
return {};
mlir::Type inputElemTy =
mlir::cast<cir::VectorType>(lhsVecAttr.getType()).getElementType();
if (!isAnyIntegerOrFloatingPointType(inputElemTy))
return {};
cir::CmpOpKind opKind = adaptor.getKind();
mlir::ArrayAttr lhsVecElhs = lhsVecAttr.getElts();
mlir::ArrayAttr rhsVecElhs = rhsVecAttr.getElts();
uint64_t vecSize = lhsVecElhs.size();
SmallVector<mlir::Attribute, 16> elements(vecSize);
bool isIntAttr = vecSize && mlir::isa<cir::IntAttr>(lhsVecElhs[0]);
for (uint64_t i = 0; i < vecSize; i++) {
mlir::Attribute lhsAttr = lhsVecElhs[i];
mlir::Attribute rhsAttr = rhsVecElhs[i];
int cmpResult = 0;
switch (opKind) {
case cir::CmpOpKind::lt: {
if (isIntAttr) {
cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() <
mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
} else {
cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() <
mlir::cast<cir::FPAttr>(rhsAttr).getValue();
}
break;
}
case cir::CmpOpKind::le: {
if (isIntAttr) {
cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() <=
mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
} else {
cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() <=
mlir::cast<cir::FPAttr>(rhsAttr).getValue();
}
break;
}
case cir::CmpOpKind::gt: {
if (isIntAttr) {
cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() >
mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
} else {
cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() >
mlir::cast<cir::FPAttr>(rhsAttr).getValue();
}
break;
}
case cir::CmpOpKind::ge: {
if (isIntAttr) {
cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() >=
mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
} else {
cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() >=
mlir::cast<cir::FPAttr>(rhsAttr).getValue();
}
break;
}
case cir::CmpOpKind::eq: {
if (isIntAttr) {
cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() ==
mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
} else {
cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() ==
mlir::cast<cir::FPAttr>(rhsAttr).getValue();
}
break;
}
case cir::CmpOpKind::ne: {
if (isIntAttr) {
cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() !=
mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
} else {
cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() !=
mlir::cast<cir::FPAttr>(rhsAttr).getValue();
}
break;
}
}
elements[i] = cir::IntAttr::get(getType().getElementType(), cmpResult);
}
return cir::ConstVectorAttr::get(
getType(), mlir::ArrayAttr::get(getContext(), elements));
}
//===----------------------------------------------------------------------===//
// VecShuffleOp
//===----------------------------------------------------------------------===//
OpFoldResult cir::VecShuffleOp::fold(FoldAdaptor adaptor) {
auto vec1Attr =
mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec1());
auto vec2Attr =
mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec2());
if (!vec1Attr || !vec2Attr)
return {};
mlir::Type vec1ElemTy =
mlir::cast<cir::VectorType>(vec1Attr.getType()).getElementType();
mlir::ArrayAttr vec1Elts = vec1Attr.getElts();
mlir::ArrayAttr vec2Elts = vec2Attr.getElts();
mlir::ArrayAttr indicesElts = adaptor.getIndices();
SmallVector<mlir::Attribute, 16> elements;
elements.reserve(indicesElts.size());
uint64_t vec1Size = vec1Elts.size();
for (const auto &idxAttr : indicesElts.getAsRange<cir::IntAttr>()) {
if (idxAttr.getSInt() == -1) {
elements.push_back(cir::UndefAttr::get(vec1ElemTy));
continue;
}
uint64_t idxValue = idxAttr.getUInt();
elements.push_back(idxValue < vec1Size ? vec1Elts[idxValue]
: vec2Elts[idxValue - vec1Size]);
}
return cir::ConstVectorAttr::get(
getType(), mlir::ArrayAttr::get(getContext(), elements));
}
LogicalResult cir::VecShuffleOp::verify() {
// The number of elements in the indices array must match the number of
// elements in the result type.
if (getIndices().size() != getResult().getType().getSize()) {
return emitOpError() << ": the number of elements in " << getIndices()
<< " and " << getResult().getType() << " don't match";
}
// The element types of the two input vectors and of the result type must
// match.
if (getVec1().getType().getElementType() !=
getResult().getType().getElementType()) {
return emitOpError() << ": element types of " << getVec1().getType()
<< " and " << getResult().getType() << " don't match";
}
const uint64_t maxValidIndex =
getVec1().getType().getSize() + getVec2().getType().getSize() - 1;
if (llvm::any_of(
getIndices().getAsRange<cir::IntAttr>(), [&](cir::IntAttr idxAttr) {
return idxAttr.getSInt() != -1 && idxAttr.getUInt() > maxValidIndex;
})) {
return emitOpError() << ": index for __builtin_shufflevector must be "
"less than the total number of vector elements";
}
return success();
}
//===----------------------------------------------------------------------===//
// VecShuffleDynamicOp
//===----------------------------------------------------------------------===//
OpFoldResult cir::VecShuffleDynamicOp::fold(FoldAdaptor adaptor) {
mlir::Attribute vec = adaptor.getVec();
mlir::Attribute indices = adaptor.getIndices();
if (mlir::isa_and_nonnull<cir::ConstVectorAttr>(vec) &&
mlir::isa_and_nonnull<cir::ConstVectorAttr>(indices)) {
auto vecAttr = mlir::cast<cir::ConstVectorAttr>(vec);
auto indicesAttr = mlir::cast<cir::ConstVectorAttr>(indices);
mlir::ArrayAttr vecElts = vecAttr.getElts();
mlir::ArrayAttr indicesElts = indicesAttr.getElts();
const uint64_t numElements = vecElts.size();
SmallVector<mlir::Attribute, 16> elements;
elements.reserve(numElements);
const uint64_t maskBits = llvm::NextPowerOf2(numElements - 1) - 1;
for (const auto &idxAttr : indicesElts.getAsRange<cir::IntAttr>()) {
uint64_t idxValue = idxAttr.getUInt();
uint64_t newIdx = idxValue & maskBits;
elements.push_back(vecElts[newIdx]);
}
return cir::ConstVectorAttr::get(
getType(), mlir::ArrayAttr::get(getContext(), elements));
}
return {};
}
LogicalResult cir::VecShuffleDynamicOp::verify() {
// The number of elements in the two input vectors must match.
if (getVec().getType().getSize() !=
mlir::cast<cir::VectorType>(getIndices().getType()).getSize()) {
return emitOpError() << ": the number of elements in " << getVec().getType()
<< " and " << getIndices().getType() << " don't match";
}
return success();
}
//===----------------------------------------------------------------------===//
// VecTernaryOp
//===----------------------------------------------------------------------===//
LogicalResult cir::VecTernaryOp::verify() {
// Verify that the condition operand has the same number of elements as the
// other operands. (The automatic verification already checked that all
// operands are vector types and that the second and third operands are the
// same type.)
if (getCond().getType().getSize() != getLhs().getType().getSize()) {
return emitOpError() << ": the number of elements in "
<< getCond().getType() << " and " << getLhs().getType()
<< " don't match";
}
return success();
}
OpFoldResult cir::VecTernaryOp::fold(FoldAdaptor adaptor) {
mlir::Attribute cond = adaptor.getCond();
mlir::Attribute lhs = adaptor.getLhs();
mlir::Attribute rhs = adaptor.getRhs();
if (!mlir::isa_and_nonnull<cir::ConstVectorAttr>(cond) ||
!mlir::isa_and_nonnull<cir::ConstVectorAttr>(lhs) ||
!mlir::isa_and_nonnull<cir::ConstVectorAttr>(rhs))
return {};
auto condVec = mlir::cast<cir::ConstVectorAttr>(cond);
auto lhsVec = mlir::cast<cir::ConstVectorAttr>(lhs);
auto rhsVec = mlir::cast<cir::ConstVectorAttr>(rhs);
mlir::ArrayAttr condElts = condVec.getElts();
SmallVector<mlir::Attribute, 16> elements;
elements.reserve(condElts.size());
for (const auto &[idx, condAttr] :
llvm::enumerate(condElts.getAsRange<cir::IntAttr>())) {
if (condAttr.getSInt()) {
elements.push_back(lhsVec.getElts()[idx]);
} else {
elements.push_back(rhsVec.getElts()[idx]);
}
}
cir::VectorType vecTy = getLhs().getType();
return cir::ConstVectorAttr::get(
vecTy, mlir::ArrayAttr::get(getContext(), elements));
}
//===----------------------------------------------------------------------===//
// ComplexCreateOp
//===----------------------------------------------------------------------===//
LogicalResult cir::ComplexCreateOp::verify() {
if (getType().getElementType() != getReal().getType()) {
emitOpError()
<< "operand type of cir.complex.create does not match its result type";
return failure();
}
return success();
}
OpFoldResult cir::ComplexCreateOp::fold(FoldAdaptor adaptor) {
mlir::Attribute real = adaptor.getReal();
mlir::Attribute imag = adaptor.getImag();
if (!real || !imag)
return {};
// When both of real and imag are constants, we can fold the operation into an
// `#cir.const_complex` operation.
auto realAttr = mlir::cast<mlir::TypedAttr>(real);
auto imagAttr = mlir::cast<mlir::TypedAttr>(imag);
return cir::ConstComplexAttr::get(realAttr, imagAttr);
}
//===----------------------------------------------------------------------===//
// ComplexRealOp
//===----------------------------------------------------------------------===//
LogicalResult cir::ComplexRealOp::verify() {
if (getType() != getOperand().getType().getElementType()) {
emitOpError() << ": result type does not match operand type";
return failure();
}
return success();
}
OpFoldResult cir::ComplexRealOp::fold(FoldAdaptor adaptor) {
if (auto complexCreateOp =
dyn_cast_or_null<cir::ComplexCreateOp>(getOperand().getDefiningOp()))
return complexCreateOp.getOperand(0);
auto complex =
mlir::cast_if_present<cir::ConstComplexAttr>(adaptor.getOperand());
return complex ? complex.getReal() : nullptr;
}
//===----------------------------------------------------------------------===//
// ComplexImagOp
//===----------------------------------------------------------------------===//
LogicalResult cir::ComplexImagOp::verify() {
if (getType() != getOperand().getType().getElementType()) {
emitOpError() << ": result type does not match operand type";
return failure();
}
return success();
}
OpFoldResult cir::ComplexImagOp::fold(FoldAdaptor adaptor) {
if (auto complexCreateOp =
dyn_cast_or_null<cir::ComplexCreateOp>(getOperand().getDefiningOp()))
return complexCreateOp.getOperand(1);
auto complex =
mlir::cast_if_present<cir::ConstComplexAttr>(adaptor.getOperand());
return complex ? complex.getImag() : nullptr;
}
//===----------------------------------------------------------------------===//
// ComplexRealPtrOp
//===----------------------------------------------------------------------===//
LogicalResult cir::ComplexRealPtrOp::verify() {
mlir::Type resultPointeeTy = getType().getPointee();
cir::PointerType operandPtrTy = getOperand().getType();
auto operandPointeeTy =
mlir::cast<cir::ComplexType>(operandPtrTy.getPointee());
if (resultPointeeTy != operandPointeeTy.getElementType()) {
return emitOpError() << ": result type does not match operand type";
}
return success();
}
//===----------------------------------------------------------------------===//
// ComplexImagPtrOp
//===----------------------------------------------------------------------===//
LogicalResult cir::ComplexImagPtrOp::verify() {
mlir::Type resultPointeeTy = getType().getPointee();
cir::PointerType operandPtrTy = getOperand().getType();
auto operandPointeeTy =
mlir::cast<cir::ComplexType>(operandPtrTy.getPointee());
if (resultPointeeTy != operandPointeeTy.getElementType()) {
return emitOpError()
<< "cir.complex.imag_ptr result type does not match operand type";
}
return success();
}
//===----------------------------------------------------------------------===//
// Bit manipulation operations
//===----------------------------------------------------------------------===//
static OpFoldResult
foldUnaryBitOp(mlir::Attribute inputAttr,
llvm::function_ref<llvm::APInt(const llvm::APInt &)> func,
bool poisonZero = false) {
if (mlir::isa_and_present<cir::PoisonAttr>(inputAttr)) {
// Propagate poison value
return inputAttr;
}
auto input = mlir::dyn_cast_if_present<IntAttr>(inputAttr);
if (!input)
return nullptr;
llvm::APInt inputValue = input.getValue();
if (poisonZero && inputValue.isZero())
return cir::PoisonAttr::get(input.getType());
llvm::APInt resultValue = func(inputValue);
return IntAttr::get(input.getType(), resultValue);
}
OpFoldResult BitClrsbOp::fold(FoldAdaptor adaptor) {
return foldUnaryBitOp(adaptor.getInput(), [](const llvm::APInt &inputValue) {
unsigned resultValue =
inputValue.getBitWidth() - inputValue.getSignificantBits();
return llvm::APInt(inputValue.getBitWidth(), resultValue);
});
}
OpFoldResult BitClzOp::fold(FoldAdaptor adaptor) {
return foldUnaryBitOp(
adaptor.getInput(),
[](const llvm::APInt &inputValue) {
unsigned resultValue = inputValue.countLeadingZeros();
return llvm::APInt(inputValue.getBitWidth(), resultValue);
},
getPoisonZero());
}
OpFoldResult BitCtzOp::fold(FoldAdaptor adaptor) {
return foldUnaryBitOp(
adaptor.getInput(),
[](const llvm::APInt &inputValue) {
return llvm::APInt(inputValue.getBitWidth(),
inputValue.countTrailingZeros());
},
getPoisonZero());
}
OpFoldResult BitFfsOp::fold(FoldAdaptor adaptor) {
return foldUnaryBitOp(adaptor.getInput(), [](const llvm::APInt &inputValue) {
unsigned trailingZeros = inputValue.countTrailingZeros();
unsigned result =
trailingZeros == inputValue.getBitWidth() ? 0 : trailingZeros + 1;
return llvm::APInt(inputValue.getBitWidth(), result);
});
}
OpFoldResult BitParityOp::fold(FoldAdaptor adaptor) {
return foldUnaryBitOp(adaptor.getInput(), [](const llvm::APInt &inputValue) {
return llvm::APInt(inputValue.getBitWidth(), inputValue.popcount() % 2);
});
}
OpFoldResult BitPopcountOp::fold(FoldAdaptor adaptor) {
return foldUnaryBitOp(adaptor.getInput(), [](const llvm::APInt &inputValue) {
return llvm::APInt(inputValue.getBitWidth(), inputValue.popcount());
});
}
OpFoldResult BitReverseOp::fold(FoldAdaptor adaptor) {
return foldUnaryBitOp(adaptor.getInput(), [](const llvm::APInt &inputValue) {
return inputValue.reverseBits();
});
}
OpFoldResult ByteSwapOp::fold(FoldAdaptor adaptor) {
return foldUnaryBitOp(adaptor.getInput(), [](const llvm::APInt &inputValue) {
return inputValue.byteSwap();
});
}
OpFoldResult RotateOp::fold(FoldAdaptor adaptor) {
if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()) ||
mlir::isa_and_present<cir::PoisonAttr>(adaptor.getAmount())) {
// Propagate poison values
return cir::PoisonAttr::get(getType());
}
auto input = mlir::dyn_cast_if_present<IntAttr>(adaptor.getInput());
auto amount = mlir::dyn_cast_if_present<IntAttr>(adaptor.getAmount());
if (!input && !amount)
return nullptr;
// We could fold cir.rotate even if one of its two operands is not a constant:
// - `cir.rotate left/right %0, 0` could be folded into just %0 even if %0
// is not a constant.
// - `cir.rotate left/right 0/0b111...111, %0` could be folded into 0 or
// 0b111...111 even if %0 is not a constant.
llvm::APInt inputValue;
if (input) {
inputValue = input.getValue();
if (inputValue.isZero() || inputValue.isAllOnes()) {
// An input value of all 0s or all 1s will not change after rotation
return input;
}
}
uint64_t amountValue;
if (amount) {
amountValue = amount.getValue().urem(getInput().getType().getWidth());
if (amountValue == 0) {
// A shift amount of 0 will not change the input value
return getInput();
}
}
if (!input || !amount)
return nullptr;
assert(inputValue.getBitWidth() == getInput().getType().getWidth() &&
"input value must have the same bit width as the input type");
llvm::APInt resultValue;
if (isRotateLeft())
resultValue = inputValue.rotl(amountValue);
else
resultValue = inputValue.rotr(amountValue);
return IntAttr::get(input.getContext(), input.getType(), resultValue);
}
//===----------------------------------------------------------------------===//
// TableGen'd op method definitions
//===----------------------------------------------------------------------===//
#define GET_OP_CLASSES
#include "clang/CIR/Dialect/IR/CIROps.cpp.inc"
|