1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
|
//===- Attributor.cpp - Module-wide attribute deduction -------------------===//
//
// 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 an inter procedural pass that deduces and/or propagating
// attributes. This is done in an abstract interpretation style fixpoint
// iteration. See the Attributor.h file comment and the class descriptions in
// that file for more information.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/IPO/Attributor.h"
#include "llvm/ADT/DepthFirstIterator.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/CaptureTracking.h"
#include "llvm/Analysis/EHPersonalities.h"
#include "llvm/Analysis/GlobalsModRef.h"
#include "llvm/Analysis/Loads.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/Argument.h"
#include "llvm/IR/Attributes.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Utils/Local.h"
#include <cassert>
using namespace llvm;
#define DEBUG_TYPE "attributor"
STATISTIC(NumFnWithExactDefinition,
"Number of function with exact definitions");
STATISTIC(NumFnWithoutExactDefinition,
"Number of function without exact definitions");
STATISTIC(NumAttributesTimedOut,
"Number of abstract attributes timed out before fixpoint");
STATISTIC(NumAttributesValidFixpoint,
"Number of abstract attributes in a valid fixpoint state");
STATISTIC(NumAttributesManifested,
"Number of abstract attributes manifested in IR");
// Some helper macros to deal with statistics tracking.
//
// Usage:
// For simple IR attribute tracking overload trackStatistics in the abstract
// attribute and choose the right STATS_DECLTRACK_********* macro,
// e.g.,:
// void trackStatistics() const override {
// STATS_DECLTRACK_ARG_ATTR(returned)
// }
// If there is a single "increment" side one can use the macro
// STATS_DECLTRACK with a custom message. If there are multiple increment
// sides, STATS_DECL and STATS_TRACK can also be used separatly.
//
#define BUILD_STAT_MSG_IR_ATTR(TYPE, NAME) \
("Number of " #TYPE " marked '" #NAME "'")
#define BUILD_STAT_NAME(NAME, TYPE) NumIR##TYPE##_##NAME
#define STATS_DECL(NAME, TYPE, MSG) STATISTIC(BUILD_STAT_NAME(NAME, TYPE), MSG);
#define STATS_TRACK(NAME, TYPE) ++(BUILD_STAT_NAME(NAME, TYPE));
#define STATS_DECLTRACK(NAME, TYPE, MSG) \
STATS_DECL(NAME, TYPE, MSG) \
STATS_TRACK(NAME, TYPE)
#define STATS_DECLTRACK_ARG_ATTR(NAME) \
STATS_DECLTRACK(NAME, Arguments, BUILD_STAT_MSG_IR_ATTR(arguments, NAME))
#define STATS_DECLTRACK_CSARG_ATTR(NAME) \
STATS_DECLTRACK(NAME, CSArguments, \
BUILD_STAT_MSG_IR_ATTR(call site arguments, NAME))
#define STATS_DECLTRACK_FN_ATTR(NAME) \
STATS_DECLTRACK(NAME, Function, BUILD_STAT_MSG_IR_ATTR(functions, NAME))
#define STATS_DECLTRACK_CS_ATTR(NAME) \
STATS_DECLTRACK(NAME, CS, BUILD_STAT_MSG_IR_ATTR(call site, NAME))
#define STATS_DECLTRACK_FNRET_ATTR(NAME) \
STATS_DECLTRACK(NAME, FunctionReturn, \
BUILD_STAT_MSG_IR_ATTR(function returns, NAME));
#define STATS_DECLTRACK_CSRET_ATTR(NAME) \
STATS_DECLTRACK(NAME, CSReturn, \
BUILD_STAT_MSG_IR_ATTR(call site returns, NAME))
#define STATS_DECLTRACK_FLOATING_ATTR(NAME) \
STATS_DECLTRACK(NAME, Floating, \
("Number of floating values known to be '" #NAME "'"))
// TODO: Determine a good default value.
//
// In the LLVM-TS and SPEC2006, 32 seems to not induce compile time overheads
// (when run with the first 5 abstract attributes). The results also indicate
// that we never reach 32 iterations but always find a fixpoint sooner.
//
// This will become more evolved once we perform two interleaved fixpoint
// iterations: bottom-up and top-down.
static cl::opt<unsigned>
MaxFixpointIterations("attributor-max-iterations", cl::Hidden,
cl::desc("Maximal number of fixpoint iterations."),
cl::init(32));
static cl::opt<bool> DisableAttributor(
"attributor-disable", cl::Hidden,
cl::desc("Disable the attributor inter-procedural deduction pass."),
cl::init(true));
static cl::opt<bool> VerifyAttributor(
"attributor-verify", cl::Hidden,
cl::desc("Verify the Attributor deduction and "
"manifestation of attributes -- may issue false-positive errors"),
cl::init(false));
/// Logic operators for the change status enum class.
///
///{
ChangeStatus llvm::operator|(ChangeStatus l, ChangeStatus r) {
return l == ChangeStatus::CHANGED ? l : r;
}
ChangeStatus llvm::operator&(ChangeStatus l, ChangeStatus r) {
return l == ChangeStatus::UNCHANGED ? l : r;
}
///}
/// Recursively visit all values that might become \p IRP at some point. This
/// will be done by looking through cast instructions, selects, phis, and calls
/// with the "returned" attribute. Once we cannot look through the value any
/// further, the callback \p VisitValueCB is invoked and passed the current
/// value, the \p State, and a flag to indicate if we stripped anything. To
/// limit how much effort is invested, we will never visit more values than
/// specified by \p MaxValues.
template <typename AAType, typename StateTy>
bool genericValueTraversal(
Attributor &A, IRPosition IRP, const AAType &QueryingAA, StateTy &State,
const function_ref<void(Value &, StateTy &, bool)> &VisitValueCB,
int MaxValues = 8) {
const AAIsDead *LivenessAA = nullptr;
if (IRP.getAnchorScope())
LivenessAA = A.getAAFor<AAIsDead>(
QueryingAA, IRPosition::function(*IRP.getAnchorScope()));
// TODO: Use Positions here to allow context sensitivity in VisitValueCB
SmallPtrSet<Value *, 16> Visited;
SmallVector<Value *, 16> Worklist;
Worklist.push_back(&IRP.getAssociatedValue());
int Iteration = 0;
do {
Value *V = Worklist.pop_back_val();
// Check if we should process the current value. To prevent endless
// recursion keep a record of the values we followed!
if (!Visited.insert(V).second)
continue;
// Make sure we limit the compile time for complex expressions.
if (Iteration++ >= MaxValues)
return false;
// Explicitly look through calls with a "returned" attribute if we do
// not have a pointer as stripPointerCasts only works on them.
Value *NewV = nullptr;
if (V->getType()->isPointerTy()) {
NewV = V->stripPointerCasts();
} else {
CallSite CS(V);
if (CS && CS.getCalledFunction()) {
for (Argument &Arg : CS.getCalledFunction()->args())
if (Arg.hasReturnedAttr()) {
NewV = CS.getArgOperand(Arg.getArgNo());
break;
}
}
}
if (NewV && NewV != V) {
Worklist.push_back(NewV);
continue;
}
// Look through select instructions, visit both potential values.
if (auto *SI = dyn_cast<SelectInst>(V)) {
Worklist.push_back(SI->getTrueValue());
Worklist.push_back(SI->getFalseValue());
continue;
}
// Look through phi nodes, visit all live operands.
if (auto *PHI = dyn_cast<PHINode>(V)) {
for (unsigned u = 0, e = PHI->getNumIncomingValues(); u < e; u++) {
const BasicBlock *IncomingBB = PHI->getIncomingBlock(u);
if (!LivenessAA ||
!LivenessAA->isAssumedDead(IncomingBB->getTerminator()))
Worklist.push_back(PHI->getIncomingValue(u));
}
continue;
}
// Once a leaf is reached we inform the user through the callback.
VisitValueCB(*V, State, Iteration > 1);
} while (!Worklist.empty());
// All values have been visited.
return true;
}
/// Return true if \p New is equal or worse than \p Old.
static bool isEqualOrWorse(const Attribute &New, const Attribute &Old) {
if (!Old.isIntAttribute())
return true;
return Old.getValueAsInt() >= New.getValueAsInt();
}
/// Return true if the information provided by \p Attr was added to the
/// attribute list \p Attrs. This is only the case if it was not already present
/// in \p Attrs at the position describe by \p PK and \p AttrIdx.
static bool addIfNotExistent(LLVMContext &Ctx, const Attribute &Attr,
AttributeList &Attrs, int AttrIdx) {
if (Attr.isEnumAttribute()) {
Attribute::AttrKind Kind = Attr.getKindAsEnum();
if (Attrs.hasAttribute(AttrIdx, Kind))
if (isEqualOrWorse(Attr, Attrs.getAttribute(AttrIdx, Kind)))
return false;
Attrs = Attrs.addAttribute(Ctx, AttrIdx, Attr);
return true;
}
if (Attr.isStringAttribute()) {
StringRef Kind = Attr.getKindAsString();
if (Attrs.hasAttribute(AttrIdx, Kind))
if (isEqualOrWorse(Attr, Attrs.getAttribute(AttrIdx, Kind)))
return false;
Attrs = Attrs.addAttribute(Ctx, AttrIdx, Attr);
return true;
}
if (Attr.isIntAttribute()) {
Attribute::AttrKind Kind = Attr.getKindAsEnum();
if (Attrs.hasAttribute(AttrIdx, Kind))
if (isEqualOrWorse(Attr, Attrs.getAttribute(AttrIdx, Kind)))
return false;
Attrs = Attrs.removeAttribute(Ctx, AttrIdx, Kind);
Attrs = Attrs.addAttribute(Ctx, AttrIdx, Attr);
return true;
}
llvm_unreachable("Expected enum or string attribute!");
}
ChangeStatus AbstractAttribute::update(Attributor &A) {
ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
if (getState().isAtFixpoint())
return HasChanged;
LLVM_DEBUG(dbgs() << "[Attributor] Update: " << *this << "\n");
HasChanged = updateImpl(A);
LLVM_DEBUG(dbgs() << "[Attributor] Update " << HasChanged << " " << *this
<< "\n");
return HasChanged;
}
ChangeStatus
IRAttributeManifest::manifestAttrs(Attributor &A, IRPosition &IRP,
const ArrayRef<Attribute> &DeducedAttrs) {
ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
Function *ScopeFn = IRP.getAssociatedFunction();
IRPosition::Kind PK = IRP.getPositionKind();
// In the following some generic code that will manifest attributes in
// DeducedAttrs if they improve the current IR. Due to the different
// annotation positions we use the underlying AttributeList interface.
AttributeList Attrs;
switch (PK) {
case IRPosition::IRP_INVALID:
case IRPosition::IRP_FLOAT:
llvm_unreachable("Cannot manifest at a floating or invalid position!");
case IRPosition::IRP_ARGUMENT:
case IRPosition::IRP_FUNCTION:
case IRPosition::IRP_RETURNED:
Attrs = ScopeFn->getAttributes();
break;
case IRPosition::IRP_CALL_SITE:
case IRPosition::IRP_CALL_SITE_RETURNED:
case IRPosition::IRP_CALL_SITE_ARGUMENT:
Attrs = ImmutableCallSite(&IRP.getAnchorValue()).getAttributes();
break;
}
LLVMContext &Ctx = IRP.getAnchorValue().getContext();
for (const Attribute &Attr : DeducedAttrs) {
if (!addIfNotExistent(Ctx, Attr, Attrs, IRP.getAttrIdx()))
continue;
HasChanged = ChangeStatus::CHANGED;
}
if (HasChanged == ChangeStatus::UNCHANGED)
return HasChanged;
switch (PK) {
case IRPosition::IRP_ARGUMENT:
case IRPosition::IRP_FUNCTION:
case IRPosition::IRP_RETURNED:
ScopeFn->setAttributes(Attrs);
break;
case IRPosition::IRP_CALL_SITE:
case IRPosition::IRP_CALL_SITE_RETURNED:
case IRPosition::IRP_CALL_SITE_ARGUMENT:
CallSite(&IRP.getAnchorValue()).setAttributes(Attrs);
break;
case IRPosition::IRP_INVALID:
case IRPosition::IRP_FLOAT:
break;
}
return HasChanged;
}
const IRPosition IRPosition::EmptyKey(255);
const IRPosition IRPosition::TombstoneKey(256);
SubsumingPositionIterator::SubsumingPositionIterator(const IRPosition &IRP) {
IRPositions.emplace_back(IRP);
ImmutableCallSite ICS(&IRP.getAnchorValue());
switch (IRP.getPositionKind()) {
case IRPosition::IRP_INVALID:
case IRPosition::IRP_FLOAT:
case IRPosition::IRP_FUNCTION:
return;
case IRPosition::IRP_ARGUMENT:
case IRPosition::IRP_RETURNED:
IRPositions.emplace_back(
IRPosition::function(*IRP.getAssociatedFunction()));
return;
case IRPosition::IRP_CALL_SITE:
assert(ICS && "Expected call site!");
// TODO: We need to look at the operand bundles similar to the redirection
// in CallBase.
if (!ICS.hasOperandBundles())
if (const Function *Callee = ICS.getCalledFunction())
IRPositions.emplace_back(IRPosition::function(*Callee));
return;
case IRPosition::IRP_CALL_SITE_RETURNED:
assert(ICS && "Expected call site!");
// TODO: We need to look at the operand bundles similar to the redirection
// in CallBase.
if (!ICS.hasOperandBundles()) {
if (const Function *Callee = ICS.getCalledFunction()) {
IRPositions.emplace_back(IRPosition::returned(*Callee));
IRPositions.emplace_back(IRPosition::function(*Callee));
}
}
IRPositions.emplace_back(
IRPosition::callsite_function(cast<CallBase>(*ICS.getInstruction())));
return;
case IRPosition::IRP_CALL_SITE_ARGUMENT: {
int ArgNo = IRP.getArgNo();
assert(ICS && ArgNo >= 0 && "Expected call site!");
// TODO: We need to look at the operand bundles similar to the redirection
// in CallBase.
if (!ICS.hasOperandBundles()) {
const Function *Callee = ICS.getCalledFunction();
if (Callee && Callee->arg_size() > unsigned(ArgNo))
IRPositions.emplace_back(IRPosition::argument(*Callee->getArg(ArgNo)));
if (Callee)
IRPositions.emplace_back(IRPosition::function(*Callee));
}
IRPositions.emplace_back(IRPosition::value(IRP.getAssociatedValue()));
return;
}
}
}
bool IRPosition::hasAttr(ArrayRef<Attribute::AttrKind> AKs) const {
for (const IRPosition &EquivIRP : SubsumingPositionIterator(*this))
for (Attribute::AttrKind AK : AKs)
if (EquivIRP.getAttr(AK).getKindAsEnum() == AK)
return true;
return false;
}
void IRPosition::getAttrs(ArrayRef<Attribute::AttrKind> AKs,
SmallVectorImpl<Attribute> &Attrs) const {
for (const IRPosition &EquivIRP : SubsumingPositionIterator(*this))
for (Attribute::AttrKind AK : AKs) {
const Attribute &Attr = EquivIRP.getAttr(AK);
if (Attr.getKindAsEnum() == AK)
Attrs.push_back(Attr);
}
}
void IRPosition::verify() {
switch (KindOrArgNo) {
default:
assert(KindOrArgNo >= 0 && "Expected argument or call site argument!");
assert((isa<CallBase>(AnchorVal) || isa<Argument>(AnchorVal)) &&
"Expected call base or argument for positive attribute index!");
if (auto *Arg = dyn_cast<Argument>(AnchorVal)) {
assert(Arg->getArgNo() == unsigned(getArgNo()) &&
"Argument number mismatch!");
assert(Arg == &getAssociatedValue() && "Associated value mismatch!");
} else {
auto &CB = cast<CallBase>(*AnchorVal);
(void)CB;
assert(CB.arg_size() > unsigned(getArgNo()) &&
"Call site argument number mismatch!");
assert(CB.getArgOperand(getArgNo()) == &getAssociatedValue() &&
"Associated value mismatch!");
}
break;
case IRP_INVALID:
assert(!AnchorVal && "Expected no value for an invalid position!");
break;
case IRP_FLOAT:
assert((!isa<CallBase>(&getAssociatedValue()) &&
!isa<Argument>(&getAssociatedValue())) &&
"Expected specialized kind for call base and argument values!");
break;
case IRP_RETURNED:
assert(isa<Function>(AnchorVal) &&
"Expected function for a 'returned' position!");
assert(AnchorVal == &getAssociatedValue() && "Associated value mismatch!");
break;
case IRP_CALL_SITE_RETURNED:
assert((isa<CallBase>(AnchorVal)) &&
"Expected call base for 'call site returned' position!");
assert(AnchorVal == &getAssociatedValue() && "Associated value mismatch!");
break;
case IRP_CALL_SITE:
assert((isa<CallBase>(AnchorVal)) &&
"Expected call base for 'call site function' position!");
assert(AnchorVal == &getAssociatedValue() && "Associated value mismatch!");
break;
case IRP_FUNCTION:
assert(isa<Function>(AnchorVal) &&
"Expected function for a 'function' position!");
assert(AnchorVal == &getAssociatedValue() && "Associated value mismatch!");
break;
}
}
/// Helper functions to clamp a state \p S of type \p StateType with the
/// information in \p R and indicate/return if \p S did change (as-in update is
/// required to be run again).
///
///{
template <typename StateType>
ChangeStatus clampStateAndIndicateChange(StateType &S, const StateType &R);
template <>
ChangeStatus clampStateAndIndicateChange<IntegerState>(IntegerState &S,
const IntegerState &R) {
auto Assumed = S.getAssumed();
S ^= R;
return Assumed == S.getAssumed() ? ChangeStatus::UNCHANGED
: ChangeStatus::CHANGED;
}
///}
/// Clamp the information known for all returned values of a function
/// (identified by \p QueryingAA) into \p S.
template <typename AAType, typename StateType = typename AAType::StateType>
static void clampReturnedValueStates(Attributor &A, const AAType &QueryingAA,
StateType &S) {
LLVM_DEBUG(dbgs() << "[Attributor] Clamp return value states for "
<< static_cast<const AbstractAttribute &>(QueryingAA)
<< " into " << S << "\n");
assert((QueryingAA.getIRPosition().getPositionKind() ==
IRPosition::IRP_RETURNED ||
QueryingAA.getIRPosition().getPositionKind() ==
IRPosition::IRP_CALL_SITE_RETURNED) &&
"Can only clamp returned value states for a function returned or call "
"site returned position!");
// Use an optional state as there might not be any return values and we want
// to join (IntegerState::operator&) the state of all there are.
Optional<StateType> T;
// Callback for each possibly returned value.
auto CheckReturnValue = [&](Value &RV) -> bool {
const IRPosition &RVPos = IRPosition::value(RV);
const AAType *AA = A.getAAFor<AAType>(QueryingAA, RVPos);
LLVM_DEBUG(dbgs() << "[Attributor] RV: " << RV
<< " AA: " << (AA ? AA->getAsStr() : "n/a") << " @ "
<< RVPos << "\n");
// TODO: We should create abstract attributes on-demand, patches are already
// prepared, pending approval.
if (!AA || AA->getIRPosition() != RVPos)
return false;
const StateType &AAS = static_cast<const StateType &>(AA->getState());
if (T.hasValue())
*T &= AAS;
else
T = AAS;
LLVM_DEBUG(dbgs() << "[Attributor] AA State: " << AAS << " RV State: " << T
<< "\n");
return T->isValidState();
};
if (!A.checkForAllReturnedValues(CheckReturnValue, QueryingAA))
S.indicatePessimisticFixpoint();
else if (T.hasValue())
S ^= *T;
}
/// Helper class for generic deduction: return value -> returned position.
template <typename AAType, typename StateType = typename AAType::StateType>
struct AAReturnedFromReturnedValues : public AAType {
AAReturnedFromReturnedValues(const IRPosition &IRP) : AAType(IRP) {}
/// See AbstractAttribute::updateImpl(...).
ChangeStatus updateImpl(Attributor &A) override {
StateType S;
clampReturnedValueStates<AAType, StateType>(A, *this, S);
return clampStateAndIndicateChange<StateType>(this->getState(), S);
}
};
/// Clamp the information known at all call sites for a given argument
/// (identified by \p QueryingAA) into \p S.
template <typename AAType, typename StateType = typename AAType::StateType>
static void clampCallSiteArgumentStates(Attributor &A, const AAType &QueryingAA,
StateType &S) {
LLVM_DEBUG(dbgs() << "[Attributor] Clamp call site argument states for "
<< static_cast<const AbstractAttribute &>(QueryingAA)
<< " into " << S << "\n");
assert(QueryingAA.getIRPosition().getPositionKind() ==
IRPosition::IRP_ARGUMENT &&
"Can only clamp call site argument states for an argument position!");
// Use an optional state as there might not be any return values and we want
// to join (IntegerState::operator&) the state of all there are.
Optional<StateType> T;
// The argument number which is also the call site argument number.
unsigned ArgNo = QueryingAA.getIRPosition().getArgNo();
auto CallSiteCheck = [&](CallSite CS) {
const IRPosition &CSArgPos = IRPosition::callsite_argument(CS, ArgNo);
const AAType *AA = A.getAAFor<AAType>(QueryingAA, CSArgPos);
LLVM_DEBUG(dbgs() << "[Attributor] CS: " << *CS.getInstruction()
<< " AA: " << (AA ? AA->getAsStr() : "n/a") << " @"
<< CSArgPos << "\n");
// TODO: We should create abstract attributes on-demand, patches are already
// prepared, pending approval.
if (!AA || AA->getIRPosition() != CSArgPos)
return false;
const StateType &AAS = static_cast<const StateType &>(AA->getState());
if (T.hasValue())
*T &= AAS;
else
T = AAS;
LLVM_DEBUG(dbgs() << "[Attributor] AA State: " << AAS << " CSA State: " << T
<< "\n");
return T->isValidState();
};
if (!A.checkForAllCallSites(CallSiteCheck, QueryingAA, true))
S.indicatePessimisticFixpoint();
else if (T.hasValue())
S ^= *T;
}
/// Helper class for generic deduction: call site argument -> argument position.
template <typename AAType, typename StateType = typename AAType::StateType>
struct AAArgumentFromCallSiteArguments : public AAType {
AAArgumentFromCallSiteArguments(const IRPosition &IRP) : AAType(IRP) {}
/// See AbstractAttribute::updateImpl(...).
ChangeStatus updateImpl(Attributor &A) override {
StateType S;
clampCallSiteArgumentStates<AAType, StateType>(A, *this, S);
return clampStateAndIndicateChange<StateType>(this->getState(), S);
}
};
/// Helper class for generic replication: function returned -> cs returned.
template <typename AAType>
struct AACallSiteReturnedFromReturned : public AAType {
AACallSiteReturnedFromReturned(const IRPosition &IRP) : AAType(IRP) {}
/// See AbstractAttribute::updateImpl(...).
ChangeStatus updateImpl(Attributor &A) override {
assert(this->getIRPosition().getPositionKind() ==
IRPosition::IRP_CALL_SITE_RETURNED &&
"Can only wrap function returned positions for call site returned "
"positions!");
auto &S = this->getState();
const Function *AssociatedFunction =
this->getIRPosition().getAssociatedFunction();
if (!AssociatedFunction)
return S.indicatePessimisticFixpoint();
IRPosition FnPos = IRPosition::returned(*AssociatedFunction);
// TODO: We should create abstract attributes on-demand, patches are already
// prepared, pending approval.
const AAType *AA = A.getAAFor<AAType>(*this, FnPos);
if (!AA)
return S.indicatePessimisticFixpoint();
return clampStateAndIndicateChange(
S, static_cast<const typename AAType::StateType &>(AA->getState()));
}
};
/// -----------------------NoUnwind Function Attribute--------------------------
struct AANoUnwindImpl : AANoUnwind {
AANoUnwindImpl(const IRPosition &IRP) : AANoUnwind(IRP) {}
/// See AbstractAttribute::initialize(...).
void initialize(Attributor &A) override {
if (hasAttr({Attribute::NoUnwind}))
indicateOptimisticFixpoint();
}
const std::string getAsStr() const override {
return getAssumed() ? "nounwind" : "may-unwind";
}
/// See AbstractAttribute::updateImpl(...).
ChangeStatus updateImpl(Attributor &A) override {
auto Opcodes = {
(unsigned)Instruction::Invoke, (unsigned)Instruction::CallBr,
(unsigned)Instruction::Call, (unsigned)Instruction::CleanupRet,
(unsigned)Instruction::CatchSwitch, (unsigned)Instruction::Resume};
auto CheckForNoUnwind = [&](Instruction &I) {
if (!I.mayThrow())
return true;
auto *NoUnwindAA = A.getAAFor<AANoUnwind>(*this, IRPosition::value(I));
return NoUnwindAA && NoUnwindAA->isAssumedNoUnwind();
};
if (!A.checkForAllInstructions(CheckForNoUnwind, *this, Opcodes))
return indicatePessimisticFixpoint();
return ChangeStatus::UNCHANGED;
}
};
struct AANoUnwindFunction final : public AANoUnwindImpl {
AANoUnwindFunction(const IRPosition &IRP) : AANoUnwindImpl(IRP) {}
/// See AbstractAttribute::trackStatistics()
void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(nounwind) }
};
/// NoUnwind attribute deduction for a call sites.
using AANoUnwindCallSite = AANoUnwindFunction;
/// --------------------- Function Return Values -------------------------------
/// "Attribute" that collects all potential returned values and the return
/// instructions that they arise from.
///
/// If there is a unique returned value R, the manifest method will:
/// - mark R with the "returned" attribute, if R is an argument.
class AAReturnedValuesImpl : public AAReturnedValues, public AbstractState {
/// Mapping of values potentially returned by the associated function to the
/// return instructions that might return them.
DenseMap<Value *, SmallPtrSet<ReturnInst *, 2>> ReturnedValues;
SmallPtrSet<CallBase *, 8> UnresolvedCalls;
/// State flags
///
///{
bool IsFixed;
bool IsValidState;
///}
public:
AAReturnedValuesImpl(const IRPosition &IRP) : AAReturnedValues(IRP) {}
/// See AbstractAttribute::initialize(...).
void initialize(Attributor &A) override {
// Reset the state.
IsFixed = false;
IsValidState = true;
ReturnedValues.clear();
Function *F = getAssociatedFunction();
if (!F || !F->hasExactDefinition()) {
indicatePessimisticFixpoint();
return;
}
// The map from instruction opcodes to those instructions in the function.
auto &OpcodeInstMap = A.getInfoCache().getOpcodeInstMapForFunction(*F);
// Look through all arguments, if one is marked as returned we are done.
for (Argument &Arg : F->args()) {
if (Arg.hasReturnedAttr()) {
auto &ReturnInstSet = ReturnedValues[&Arg];
for (Instruction *RI : OpcodeInstMap[Instruction::Ret])
ReturnInstSet.insert(cast<ReturnInst>(RI));
indicateOptimisticFixpoint();
return;
}
}
}
/// See AbstractAttribute::manifest(...).
ChangeStatus manifest(Attributor &A) override;
/// See AbstractAttribute::getState(...).
AbstractState &getState() override { return *this; }
/// See AbstractAttribute::getState(...).
const AbstractState &getState() const override { return *this; }
/// See AbstractAttribute::updateImpl(Attributor &A).
ChangeStatus updateImpl(Attributor &A) override;
llvm::iterator_range<iterator> returned_values() override {
return llvm::make_range(ReturnedValues.begin(), ReturnedValues.end());
}
llvm::iterator_range<const_iterator> returned_values() const override {
return llvm::make_range(ReturnedValues.begin(), ReturnedValues.end());
}
const SmallPtrSetImpl<CallBase *> &getUnresolvedCalls() const override {
return UnresolvedCalls;
}
/// Return the number of potential return values, -1 if unknown.
size_t getNumReturnValues() const override {
return isValidState() ? ReturnedValues.size() : -1;
}
/// Return an assumed unique return value if a single candidate is found. If
/// there cannot be one, return a nullptr. If it is not clear yet, return the
/// Optional::NoneType.
Optional<Value *> getAssumedUniqueReturnValue(Attributor &A) const;
/// See AbstractState::checkForAllReturnedValues(...).
bool checkForAllReturnedValuesAndReturnInsts(
const function_ref<bool(Value &, const SmallPtrSetImpl<ReturnInst *> &)>
&Pred) const override;
/// Pretty print the attribute similar to the IR representation.
const std::string getAsStr() const override;
/// See AbstractState::isAtFixpoint().
bool isAtFixpoint() const override { return IsFixed; }
/// See AbstractState::isValidState().
bool isValidState() const override { return IsValidState; }
/// See AbstractState::indicateOptimisticFixpoint(...).
ChangeStatus indicateOptimisticFixpoint() override {
IsFixed = true;
IsValidState &= true;
return ChangeStatus::UNCHANGED;
}
ChangeStatus indicatePessimisticFixpoint() override {
IsFixed = true;
IsValidState = false;
return ChangeStatus::CHANGED;
}
};
ChangeStatus AAReturnedValuesImpl::manifest(Attributor &A) {
ChangeStatus Changed = ChangeStatus::UNCHANGED;
// Bookkeeping.
assert(isValidState());
STATS_DECLTRACK(KnownReturnValues, FunctionReturn,
"Number of function with known return values");
// Check if we have an assumed unique return value that we could manifest.
Optional<Value *> UniqueRV = getAssumedUniqueReturnValue(A);
if (!UniqueRV.hasValue() || !UniqueRV.getValue())
return Changed;
// Bookkeeping.
STATS_DECLTRACK(UniqueReturnValue, FunctionReturn,
"Number of function with unique return");
// If the assumed unique return value is an argument, annotate it.
if (auto *UniqueRVArg = dyn_cast<Argument>(UniqueRV.getValue())) {
getIRPosition() = IRPosition::argument(*UniqueRVArg);
Changed = IRAttribute::manifest(A) | Changed;
}
return Changed;
}
const std::string AAReturnedValuesImpl::getAsStr() const {
return (isAtFixpoint() ? "returns(#" : "may-return(#") +
(isValidState() ? std::to_string(getNumReturnValues()) : "?") +
")[#UC: " + std::to_string(UnresolvedCalls.size()) + "]";
}
Optional<Value *>
AAReturnedValuesImpl::getAssumedUniqueReturnValue(Attributor &A) const {
// If checkForAllReturnedValues provides a unique value, ignoring potential
// undef values that can also be present, it is assumed to be the actual
// return value and forwarded to the caller of this method. If there are
// multiple, a nullptr is returned indicating there cannot be a unique
// returned value.
Optional<Value *> UniqueRV;
auto Pred = [&](Value &RV) -> bool {
// If we found a second returned value and neither the current nor the saved
// one is an undef, there is no unique returned value. Undefs are special
// since we can pretend they have any value.
if (UniqueRV.hasValue() && UniqueRV != &RV &&
!(isa<UndefValue>(RV) || isa<UndefValue>(UniqueRV.getValue()))) {
UniqueRV = nullptr;
return false;
}
// Do not overwrite a value with an undef.
if (!UniqueRV.hasValue() || !isa<UndefValue>(RV))
UniqueRV = &RV;
return true;
};
if (!A.checkForAllReturnedValues(Pred, *this))
UniqueRV = nullptr;
return UniqueRV;
}
bool AAReturnedValuesImpl::checkForAllReturnedValuesAndReturnInsts(
const function_ref<bool(Value &, const SmallPtrSetImpl<ReturnInst *> &)>
&Pred) const {
if (!isValidState())
return false;
// Check all returned values but ignore call sites as long as we have not
// encountered an overdefined one during an update.
for (auto &It : ReturnedValues) {
Value *RV = It.first;
const SmallPtrSetImpl<ReturnInst *> &RetInsts = It.second;
CallBase *CB = dyn_cast<CallBase>(RV);
if (CB && !UnresolvedCalls.count(CB))
continue;
if (!Pred(*RV, RetInsts))
return false;
}
return true;
}
ChangeStatus AAReturnedValuesImpl::updateImpl(Attributor &A) {
size_t NumUnresolvedCalls = UnresolvedCalls.size();
bool Changed = false;
// State used in the value traversals starting in returned values.
struct RVState {
// The map in which we collect return values -> return instrs.
decltype(ReturnedValues) &RetValsMap;
// The flag to indicate a change.
bool &Changed;
// The return instrs we come from.
SmallPtrSet<ReturnInst *, 2> RetInsts;
};
// Callback for a leaf value returned by the associated function.
auto VisitValueCB = [](Value &Val, RVState &RVS, bool) {
auto Size = RVS.RetValsMap[&Val].size();
RVS.RetValsMap[&Val].insert(RVS.RetInsts.begin(), RVS.RetInsts.end());
bool Inserted = RVS.RetValsMap[&Val].size() != Size;
RVS.Changed |= Inserted;
LLVM_DEBUG({
if (Inserted)
dbgs() << "[AAReturnedValues] 1 Add new returned value " << Val
<< " => " << RVS.RetInsts.size() << "\n";
});
};
// Helper method to invoke the generic value traversal.
auto VisitReturnedValue = [&](Value &RV, RVState &RVS) {
IRPosition RetValPos = IRPosition::value(RV);
return genericValueTraversal<AAReturnedValues, RVState>(A, RetValPos, *this,
RVS, VisitValueCB);
};
// Callback for all "return intructions" live in the associated function.
auto CheckReturnInst = [this, &VisitReturnedValue, &Changed](Instruction &I) {
ReturnInst &Ret = cast<ReturnInst>(I);
RVState RVS({ReturnedValues, Changed, {}});
RVS.RetInsts.insert(&Ret);
return VisitReturnedValue(*Ret.getReturnValue(), RVS);
};
// Start by discovering returned values from all live returned instructions in
// the associated function.
if (!A.checkForAllInstructions(CheckReturnInst, *this, {Instruction::Ret}))
return indicatePessimisticFixpoint();
// Once returned values "directly" present in the code are handled we try to
// resolve returned calls.
decltype(ReturnedValues) NewRVsMap;
for (auto &It : ReturnedValues) {
LLVM_DEBUG(dbgs() << "[AAReturnedValues] Returned value: " << *It.first
<< " by #" << It.second.size() << " RIs\n");
CallBase *CB = dyn_cast<CallBase>(It.first);
if (!CB || UnresolvedCalls.count(CB))
continue;
const auto *RetValAAPtr =
A.getAAFor<AAReturnedValues>(*this, IRPosition::callsite_function(*CB));
// Skip dead ends, thus if we do not know anything about the returned
// call we mark it as unresolved and it will stay that way.
if (!RetValAAPtr || !RetValAAPtr->getState().isValidState()) {
LLVM_DEBUG(dbgs() << "[AAReturnedValues] Unresolved call: " << *CB
<< "\n");
UnresolvedCalls.insert(CB);
continue;
}
const auto &RetValAA = *RetValAAPtr;
LLVM_DEBUG(dbgs() << "[AAReturnedValues] Found another AAReturnedValues: "
<< static_cast<const AbstractAttribute &>(RetValAA)
<< "\n");
// Do not try to learn partial information. If the callee has unresolved
// return values we will treat the call as unresolved/opaque.
auto &RetValAAUnresolvedCalls = RetValAA.getUnresolvedCalls();
if (!RetValAAUnresolvedCalls.empty()) {
UnresolvedCalls.insert(CB);
continue;
}
// Now check if we can track transitively returned values. If possible, thus
// if all return value can be represented in the current scope, do so.
bool Unresolved = false;
for (auto &RetValAAIt : RetValAA.returned_values()) {
Value *RetVal = RetValAAIt.first;
if (isa<Argument>(RetVal) || isa<CallBase>(RetVal) ||
isa<Constant>(RetVal))
continue;
// Anything that did not fit in the above categories cannot be resolved,
// mark the call as unresolved.
LLVM_DEBUG(dbgs() << "[AAReturnedValues] transitively returned value "
"cannot be translated: "
<< *RetVal << "\n");
UnresolvedCalls.insert(CB);
Unresolved = true;
break;
}
if (Unresolved)
continue;
for (auto &RetValAAIt : RetValAA.returned_values()) {
Value *RetVal = RetValAAIt.first;
if (Argument *Arg = dyn_cast<Argument>(RetVal)) {
// Arguments are mapped to call site operands and we begin the traversal
// again.
bool Unused;
RVState RVS({NewRVsMap, Unused, RetValAAIt.second});
VisitReturnedValue(*CB->getArgOperand(Arg->getArgNo()), RVS);
continue;
} else if (isa<CallBase>(RetVal)) {
// Call sites are resolved by the callee attribute over time, no need to
// do anything for us.
continue;
} else if (isa<Constant>(RetVal)) {
// Constants are valid everywhere, we can simply take them.
NewRVsMap[RetVal].insert(It.second.begin(), It.second.end());
continue;
}
}
}
// To avoid modifications to the ReturnedValues map while we iterate over it
// we kept record of potential new entries in a copy map, NewRVsMap.
for (auto &It : NewRVsMap) {
assert(!It.second.empty() && "Entry does not add anything.");
auto &ReturnInsts = ReturnedValues[It.first];
for (ReturnInst *RI : It.second)
if (ReturnInsts.insert(RI).second) {
LLVM_DEBUG(dbgs() << "[AAReturnedValues] Add new returned value "
<< *It.first << " => " << *RI << "\n");
Changed = true;
}
}
Changed |= (NumUnresolvedCalls != UnresolvedCalls.size());
return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
}
struct AAReturnedValuesFunction final : public AAReturnedValuesImpl {
AAReturnedValuesFunction(const IRPosition &IRP) : AAReturnedValuesImpl(IRP) {}
/// See AbstractAttribute::trackStatistics()
void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(returned) }
};
/// Returned values information for a call sites.
using AAReturnedValuesCallSite = AAReturnedValuesFunction;
/// ------------------------ NoSync Function Attribute -------------------------
struct AANoSyncImpl : AANoSync {
AANoSyncImpl(const IRPosition &IRP) : AANoSync(IRP) {}
/// See AbstractAttribute::initialize(...).
void initialize(Attributor &A) override {
if (hasAttr({Attribute::NoSync}))
indicateOptimisticFixpoint();
}
const std::string getAsStr() const override {
return getAssumed() ? "nosync" : "may-sync";
}
/// See AbstractAttribute::updateImpl(...).
ChangeStatus updateImpl(Attributor &A) override;
/// Helper function used to determine whether an instruction is non-relaxed
/// atomic. In other words, if an atomic instruction does not have unordered
/// or monotonic ordering
static bool isNonRelaxedAtomic(Instruction *I);
/// Helper function used to determine whether an instruction is volatile.
static bool isVolatile(Instruction *I);
/// Helper function uset to check if intrinsic is volatile (memcpy, memmove,
/// memset).
static bool isNoSyncIntrinsic(Instruction *I);
};
bool AANoSyncImpl::isNonRelaxedAtomic(Instruction *I) {
if (!I->isAtomic())
return false;
AtomicOrdering Ordering;
switch (I->getOpcode()) {
case Instruction::AtomicRMW:
Ordering = cast<AtomicRMWInst>(I)->getOrdering();
break;
case Instruction::Store:
Ordering = cast<StoreInst>(I)->getOrdering();
break;
case Instruction::Load:
Ordering = cast<LoadInst>(I)->getOrdering();
break;
case Instruction::Fence: {
auto *FI = cast<FenceInst>(I);
if (FI->getSyncScopeID() == SyncScope::SingleThread)
return false;
Ordering = FI->getOrdering();
break;
}
case Instruction::AtomicCmpXchg: {
AtomicOrdering Success = cast<AtomicCmpXchgInst>(I)->getSuccessOrdering();
AtomicOrdering Failure = cast<AtomicCmpXchgInst>(I)->getFailureOrdering();
// Only if both are relaxed, than it can be treated as relaxed.
// Otherwise it is non-relaxed.
if (Success != AtomicOrdering::Unordered &&
Success != AtomicOrdering::Monotonic)
return true;
if (Failure != AtomicOrdering::Unordered &&
Failure != AtomicOrdering::Monotonic)
return true;
return false;
}
default:
llvm_unreachable(
"New atomic operations need to be known in the attributor.");
}
// Relaxed.
if (Ordering == AtomicOrdering::Unordered ||
Ordering == AtomicOrdering::Monotonic)
return false;
return true;
}
/// Checks if an intrinsic is nosync. Currently only checks mem* intrinsics.
/// FIXME: We should ipmrove the handling of intrinsics.
bool AANoSyncImpl::isNoSyncIntrinsic(Instruction *I) {
if (auto *II = dyn_cast<IntrinsicInst>(I)) {
switch (II->getIntrinsicID()) {
/// Element wise atomic memory intrinsics are can only be unordered,
/// therefore nosync.
case Intrinsic::memset_element_unordered_atomic:
case Intrinsic::memmove_element_unordered_atomic:
case Intrinsic::memcpy_element_unordered_atomic:
return true;
case Intrinsic::memset:
case Intrinsic::memmove:
case Intrinsic::memcpy:
if (!cast<MemIntrinsic>(II)->isVolatile())
return true;
return false;
default:
return false;
}
}
return false;
}
bool AANoSyncImpl::isVolatile(Instruction *I) {
assert(!ImmutableCallSite(I) && !isa<CallBase>(I) &&
"Calls should not be checked here");
switch (I->getOpcode()) {
case Instruction::AtomicRMW:
return cast<AtomicRMWInst>(I)->isVolatile();
case Instruction::Store:
return cast<StoreInst>(I)->isVolatile();
case Instruction::Load:
return cast<LoadInst>(I)->isVolatile();
case Instruction::AtomicCmpXchg:
return cast<AtomicCmpXchgInst>(I)->isVolatile();
default:
return false;
}
}
ChangeStatus AANoSyncImpl::updateImpl(Attributor &A) {
auto CheckRWInstForNoSync = [&](Instruction &I) {
/// We are looking for volatile instructions or Non-Relaxed atomics.
/// FIXME: We should ipmrove the handling of intrinsics.
if (isa<IntrinsicInst>(&I) && isNoSyncIntrinsic(&I))
return true;
if (ImmutableCallSite ICS = ImmutableCallSite(&I)) {
if (ICS.hasFnAttr(Attribute::NoSync))
return true;
auto *NoSyncAA =
A.getAAFor<AANoSyncImpl>(*this, IRPosition::callsite_function(ICS));
if (NoSyncAA && NoSyncAA->isAssumedNoSync())
return true;
return false;
}
if (!isVolatile(&I) && !isNonRelaxedAtomic(&I))
return true;
return false;
};
auto CheckForNoSync = [&](Instruction &I) {
// At this point we handled all read/write effects and they are all
// nosync, so they can be skipped.
if (I.mayReadOrWriteMemory())
return true;
// non-convergent and readnone imply nosync.
return !ImmutableCallSite(&I).isConvergent();
};
if (!A.checkForAllReadWriteInstructions(CheckRWInstForNoSync, *this) ||
!A.checkForAllCallLikeInstructions(CheckForNoSync, *this))
return indicatePessimisticFixpoint();
return ChangeStatus::UNCHANGED;
}
struct AANoSyncFunction final : public AANoSyncImpl {
AANoSyncFunction(const IRPosition &IRP) : AANoSyncImpl(IRP) {}
/// See AbstractAttribute::trackStatistics()
void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(nosync) }
};
/// NoSync attribute deduction for a call sites.
using AANoSyncCallSite = AANoSyncFunction;
/// ------------------------ No-Free Attributes ----------------------------
struct AANoFreeImpl : public AANoFree {
AANoFreeImpl(const IRPosition &IRP) : AANoFree(IRP) {}
/// See AbstractAttribute::initialize(...).
void initialize(Attributor &A) override {
if (hasAttr({Attribute::NoFree}))
indicateOptimisticFixpoint();
}
/// See AbstractAttribute::updateImpl(...).
ChangeStatus updateImpl(Attributor &A) override {
auto CheckForNoFree = [&](Instruction &I) {
ImmutableCallSite ICS(&I);
if (ICS.hasFnAttr(Attribute::NoFree))
return true;
auto *NoFreeAA =
A.getAAFor<AANoFreeImpl>(*this, IRPosition::callsite_function(ICS));
return NoFreeAA && NoFreeAA->isAssumedNoFree();
};
if (!A.checkForAllCallLikeInstructions(CheckForNoFree, *this))
return indicatePessimisticFixpoint();
return ChangeStatus::UNCHANGED;
}
/// See AbstractAttribute::getAsStr().
const std::string getAsStr() const override {
return getAssumed() ? "nofree" : "may-free";
}
};
struct AANoFreeFunction final : public AANoFreeImpl {
AANoFreeFunction(const IRPosition &IRP) : AANoFreeImpl(IRP) {}
/// See AbstractAttribute::trackStatistics()
void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(nofree) }
};
/// NoFree attribute deduction for a call sites.
using AANoFreeCallSite = AANoFreeFunction;
/// ------------------------ NonNull Argument Attribute ------------------------
struct AANonNullImpl : AANonNull {
AANonNullImpl(const IRPosition &IRP) : AANonNull(IRP) {}
/// See AbstractAttribute::getAsStr().
const std::string getAsStr() const override {
return getAssumed() ? "nonnull" : "may-null";
}
/// See AbstractAttribute::initialize(...).
void initialize(Attributor &A) override {
if (hasAttr({Attribute::NonNull, Attribute::Dereferenceable}))
indicateOptimisticFixpoint();
}
/// Generate a predicate that checks if a given value is assumed nonnull.
/// The generated function returns true if a value satisfies any of
/// following conditions.
/// (i) A value is known nonZero(=nonnull).
/// (ii) A value is associated with AANonNull and its isAssumedNonNull() is
/// true.
std::function<bool(Value &, const SmallPtrSetImpl<ReturnInst *> &)>
generatePredicate(Attributor &);
};
std::function<bool(Value &, const SmallPtrSetImpl<ReturnInst *> &)>
AANonNullImpl::generatePredicate(Attributor &A) {
// FIXME: The `AAReturnedValues` should provide the predicate with the
// `ReturnInst` vector as well such that we can use the control flow sensitive
// version of `isKnownNonZero`. This should fix `test11` in
// `test/Transforms/FunctionAttrs/nonnull.ll`
std::function<bool(Value &, const SmallPtrSetImpl<ReturnInst *> &)> Pred =
[&](Value &RV, const SmallPtrSetImpl<ReturnInst *> &RetInsts) -> bool {
if (isKnownNonZero(&RV, A.getDataLayout()))
return true;
if (ImmutableCallSite ICS = ImmutableCallSite(&RV))
if (ICS.hasRetAttr(Attribute::NonNull))
return true;
auto *NonNullAA = A.getAAFor<AANonNull>(*this, IRPosition::value(RV));
return (NonNullAA && NonNullAA->isAssumedNonNull());
};
return Pred;
}
/// NonNull attribute for function return value.
struct AANonNullReturned final : AANonNullImpl {
AANonNullReturned(const IRPosition &IRP) : AANonNullImpl(IRP) {}
/// See AbstractAttribute::updateImpl(...).
ChangeStatus updateImpl(Attributor &A) override {
std::function<bool(Value &, const SmallPtrSetImpl<ReturnInst *> &)> Pred =
this->generatePredicate(A);
if (!A.checkForAllReturnedValuesAndReturnInsts(Pred, *this))
return indicatePessimisticFixpoint();
return ChangeStatus::UNCHANGED;
}
/// See AbstractAttribute::trackStatistics()
void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(nonnull) }
};
/// NonNull attribute for function argument.
struct AANonNullArgument final : AANonNullImpl {
AANonNullArgument(const IRPosition &IRP) : AANonNullImpl(IRP) {}
/// See AbstractAttribute::updateImpl(...).
ChangeStatus updateImpl(Attributor &A) override {
unsigned ArgNo = getArgNo();
// Callback function
std::function<bool(CallSite)> CallSiteCheck = [&](CallSite CS) {
assert(CS && "Sanity check: Call site was not initialized properly!");
IRPosition CSArgPos = IRPosition::callsite_argument(CS, ArgNo);
if (CSArgPos.hasAttr({Attribute::NonNull, Attribute::Dereferenceable}))
return true;
// Check that NonNullAA is AANonNullCallSiteArgument.
if (auto *NonNullAA = A.getAAFor<AANonNullImpl>(*this, CSArgPos)) {
ImmutableCallSite ICS(&NonNullAA->getAnchorValue());
if (ICS && CS.getInstruction() == ICS.getInstruction())
return NonNullAA->isAssumedNonNull();
return false;
}
Value *V = CS.getArgOperand(ArgNo);
if (isKnownNonZero(V, A.getDataLayout()))
return true;
return false;
};
if (!A.checkForAllCallSites(CallSiteCheck, *this, true))
return indicatePessimisticFixpoint();
return ChangeStatus::UNCHANGED;
}
/// See AbstractAttribute::trackStatistics()
void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(nonnull) }
};
/// NonNull attribute for a call site argument.
struct AANonNullCallSiteArgument final : AANonNullImpl {
AANonNullCallSiteArgument(const IRPosition &IRP) : AANonNullImpl(IRP) {}
/// See AbstractAttribute::initialize(...).
void initialize(Attributor &A) override {
AANonNullImpl::initialize(A);
if (!isKnownNonNull() &&
isKnownNonZero(&getAssociatedValue(), A.getDataLayout()))
indicateOptimisticFixpoint();
}
/// See AbstractAttribute::updateImpl(Attributor &A).
ChangeStatus updateImpl(Attributor &A) override {
// NOTE: Never look at the argument of the callee in this method.
// If we do this, "nonnull" is always deduced because of the
// assumption.
Value &V = getAssociatedValue();
auto *NonNullAA = A.getAAFor<AANonNull>(*this, IRPosition::value(V));
if (!NonNullAA || !NonNullAA->isAssumedNonNull())
return indicatePessimisticFixpoint();
return ChangeStatus::UNCHANGED;
}
/// See AbstractAttribute::trackStatistics()
void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(nonnull) }
};
/// NonNull attribute deduction for a call sites.
using AANonNullCallSiteReturned = AANonNullReturned;
/// ------------------------ No-Recurse Attributes ----------------------------
struct AANoRecurseImpl : public AANoRecurse {
AANoRecurseImpl(const IRPosition &IRP) : AANoRecurse(IRP) {}
/// See AbstractAttribute::initialize(...).
void initialize(Attributor &A) override {
if (hasAttr({getAttrKind()})) {
indicateOptimisticFixpoint();
return;
}
}
/// See AbstractAttribute::getAsStr()
const std::string getAsStr() const override {
return getAssumed() ? "norecurse" : "may-recurse";
}
};
struct AANoRecurseFunction final : AANoRecurseImpl {
AANoRecurseFunction(const IRPosition &IRP) : AANoRecurseImpl(IRP) {}
/// See AbstractAttribute::updateImpl(...).
ChangeStatus updateImpl(Attributor &A) override {
// TODO: Implement this.
return indicatePessimisticFixpoint();
}
void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(norecurse) }
};
using AANoRecurseCallSite = AANoRecurseFunction;
/// ------------------------ Will-Return Attributes ----------------------------
// Helper function that checks whether a function has any cycle.
// TODO: Replace with more efficent code
static bool containsCycle(Function &F) {
SmallPtrSet<BasicBlock *, 32> Visited;
// Traverse BB by dfs and check whether successor is already visited.
for (BasicBlock *BB : depth_first(&F)) {
Visited.insert(BB);
for (auto *SuccBB : successors(BB)) {
if (Visited.count(SuccBB))
return true;
}
}
return false;
}
// Helper function that checks the function have a loop which might become an
// endless loop
// FIXME: Any cycle is regarded as endless loop for now.
// We have to allow some patterns.
static bool containsPossiblyEndlessLoop(Function *F) {
return !F || !F->hasExactDefinition() || containsCycle(*F);
}
struct AAWillReturnImpl : public AAWillReturn {
AAWillReturnImpl(const IRPosition &IRP) : AAWillReturn(IRP) {}
/// See AbstractAttribute::initialize(...).
void initialize(Attributor &A) override {
if (hasAttr({Attribute::WillReturn})) {
indicateOptimisticFixpoint();
return;
}
Function *F = getAssociatedFunction();
if (containsPossiblyEndlessLoop(F))
indicatePessimisticFixpoint();
}
/// See AbstractAttribute::updateImpl(...).
ChangeStatus updateImpl(Attributor &A) override {
auto CheckForWillReturn = [&](Instruction &I) {
ImmutableCallSite ICS(&I);
if (ICS.hasFnAttr(Attribute::WillReturn))
return true;
IRPosition IPos = IRPosition::callsite_function(ICS);
auto *WillReturnAA = A.getAAFor<AAWillReturn>(*this, IPos);
if (!WillReturnAA || !WillReturnAA->isAssumedWillReturn())
return false;
// FIXME: Prohibit any recursion for now.
if (ICS.hasFnAttr(Attribute::NoRecurse))
return true;
auto *NoRecurseAA = A.getAAFor<AANoRecurse>(*this, IPos);
return NoRecurseAA && NoRecurseAA->isAssumedNoRecurse();
};
if (!A.checkForAllCallLikeInstructions(CheckForWillReturn, *this))
return indicatePessimisticFixpoint();
return ChangeStatus::UNCHANGED;
}
/// See AbstractAttribute::getAsStr()
const std::string getAsStr() const override {
return getAssumed() ? "willreturn" : "may-noreturn";
}
};
struct AAWillReturnFunction final : AAWillReturnImpl {
AAWillReturnFunction(const IRPosition &IRP) : AAWillReturnImpl(IRP) {}
/// See AbstractAttribute::trackStatistics()
void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(willreturn) }
};
/// WillReturn attribute deduction for a call sites.
using AAWillReturnCallSite = AAWillReturnFunction;
/// ------------------------ NoAlias Argument Attribute ------------------------
struct AANoAliasImpl : AANoAlias {
AANoAliasImpl(const IRPosition &IRP) : AANoAlias(IRP) {}
/// See AbstractAttribute::initialize(...).
void initialize(Attributor &A) override {
if (hasAttr({Attribute::NoAlias}))
indicateOptimisticFixpoint();
}
const std::string getAsStr() const override {
return getAssumed() ? "noalias" : "may-alias";
}
};
/// NoAlias attribute for a floating value.
struct AANoAliasFloating final : AANoAliasImpl {
AANoAliasFloating(const IRPosition &IRP) : AANoAliasImpl(IRP) {}
/// See AbstractAttribute::updateImpl(...).
ChangeStatus updateImpl(Attributor &A) override {
// TODO: Implement this.
return indicatePessimisticFixpoint();
}
/// See AbstractAttribute::trackStatistics()
void trackStatistics() const override {
STATS_DECLTRACK_FLOATING_ATTR(noalias)
}
};
/// NoAlias attribute for an argument.
struct AANoAliasArgument final : AANoAliasImpl {
AANoAliasArgument(const IRPosition &IRP) : AANoAliasImpl(IRP) {}
/// See AbstractAttribute::updateImpl(...).
ChangeStatus updateImpl(Attributor &A) override {
// TODO: Implement this.
return indicatePessimisticFixpoint();
}
/// See AbstractAttribute::trackStatistics()
void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(noalias) }
};
struct AANoAliasCallSiteArgument final : AANoAliasImpl {
AANoAliasCallSiteArgument(const IRPosition &IRP) : AANoAliasImpl(IRP) {}
/// See AbstractAttribute::updateImpl(...).
ChangeStatus updateImpl(Attributor &A) override {
// TODO: Implement this.
return indicatePessimisticFixpoint();
}
/// See AbstractAttribute::trackStatistics()
void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(noalias) }
};
/// NoAlias attribute for function return value.
struct AANoAliasReturned final : AANoAliasImpl {
AANoAliasReturned(const IRPosition &IRP) : AANoAliasImpl(IRP) {}
/// See AbstractAttribute::updateImpl(...).
virtual ChangeStatus updateImpl(Attributor &A) override {
auto CheckReturnValue = [&](Value &RV) -> bool {
if (Constant *C = dyn_cast<Constant>(&RV))
if (C->isNullValue() || isa<UndefValue>(C))
return true;
/// For now, we can only deduce noalias if we have call sites.
/// FIXME: add more support.
ImmutableCallSite ICS(&RV);
if (!ICS)
return false;
if (!ICS.returnDoesNotAlias()) {
auto *NoAliasAA =
A.getAAFor<AANoAlias>(*this, IRPosition::callsite_returned(ICS));
if (!NoAliasAA || !NoAliasAA->isAssumedNoAlias())
return false;
}
/// FIXME: We can improve capture check in two ways:
/// 1. Use the AANoCapture facilities.
/// 2. Use the location of return insts for escape queries.
if (PointerMayBeCaptured(&RV, /* ReturnCaptures */ false,
/* StoreCaptures */ true))
return false;
return true;
};
if (!A.checkForAllReturnedValues(CheckReturnValue, *this))
return indicatePessimisticFixpoint();
return ChangeStatus::UNCHANGED;
}
/// See AbstractAttribute::trackStatistics()
void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(noalias) }
};
/// NoAlias attribute deduction for a call site return value.
using AANoAliasCallSiteReturned = AANoAliasReturned;
/// -------------------AAIsDead Function Attribute-----------------------
struct AAIsDeadImpl : public AAIsDead {
AAIsDeadImpl(const IRPosition &IRP) : AAIsDead(IRP) {}
void initialize(Attributor &A) override {
const Function *F = getAssociatedFunction();
if (!F || !F->hasExactDefinition()) {
indicatePessimisticFixpoint();
return;
}
ToBeExploredPaths.insert(&(F->getEntryBlock().front()));
AssumedLiveBlocks.insert(&(F->getEntryBlock()));
for (size_t i = 0; i < ToBeExploredPaths.size(); ++i)
if (const Instruction *NextNoReturnI =
findNextNoReturn(A, ToBeExploredPaths[i]))
NoReturnCalls.insert(NextNoReturnI);
}
/// Find the next assumed noreturn instruction in the block of \p I starting
/// from, thus including, \p I.
///
/// The caller is responsible to monitor the ToBeExploredPaths set as new
/// instructions discovered in other basic block will be placed in there.
///
/// \returns The next assumed noreturn instructions in the block of \p I
/// starting from, thus including, \p I.
const Instruction *findNextNoReturn(Attributor &A, const Instruction *I);
/// See AbstractAttribute::getAsStr().
const std::string getAsStr() const override {
return "Live[#BB " + std::to_string(AssumedLiveBlocks.size()) + "/" +
std::to_string(getAssociatedFunction()->size()) + "][#NRI " +
std::to_string(NoReturnCalls.size()) + "]";
}
/// See AbstractAttribute::manifest(...).
ChangeStatus manifest(Attributor &A) override {
assert(getState().isValidState() &&
"Attempted to manifest an invalid state!");
ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
const Function &F = *getAssociatedFunction();
// Flag to determine if we can change an invoke to a call assuming the
// callee is nounwind. This is not possible if the personality of the
// function allows to catch asynchronous exceptions.
bool Invoke2CallAllowed = !mayCatchAsynchronousExceptions(F);
for (const Instruction *NRC : NoReturnCalls) {
Instruction *I = const_cast<Instruction *>(NRC);
BasicBlock *BB = I->getParent();
Instruction *SplitPos = I->getNextNode();
if (auto *II = dyn_cast<InvokeInst>(I)) {
// If we keep the invoke the split position is at the beginning of the
// normal desitination block (it invokes a noreturn function after all).
BasicBlock *NormalDestBB = II->getNormalDest();
SplitPos = &NormalDestBB->front();
/// Invoke is replaced with a call and unreachable is placed after it if
/// the callee is nounwind and noreturn. Otherwise, we keep the invoke
/// and only place an unreachable in the normal successor.
if (Invoke2CallAllowed) {
if (Function *Callee = II->getCalledFunction()) {
auto *AANoUnw =
A.getAAFor<AANoUnwind>(*this, IRPosition::function(*Callee));
if (Callee->hasFnAttribute(Attribute::NoUnwind) ||
(AANoUnw && AANoUnw->isAssumedNoUnwind())) {
LLVM_DEBUG(dbgs()
<< "[AAIsDead] Replace invoke with call inst\n");
// We do not need an invoke (II) but instead want a call followed
// by an unreachable. However, we do not remove II as other
// abstract attributes might have it cached as part of their
// results. Given that we modify the CFG anyway, we simply keep II
// around but in a new dead block. To avoid II being live through
// a different edge we have to ensure the block we place it in is
// only reached from the current block of II and then not reached
// at all when we insert the unreachable.
SplitBlockPredecessors(NormalDestBB, {BB}, ".i2c");
CallInst *CI = createCallMatchingInvoke(II);
CI->insertBefore(II);
CI->takeName(II);
II->replaceAllUsesWith(CI);
SplitPos = CI->getNextNode();
}
}
}
}
BB = SplitPos->getParent();
SplitBlock(BB, SplitPos);
changeToUnreachable(BB->getTerminator(), /* UseLLVMTrap */ false);
HasChanged = ChangeStatus::CHANGED;
}
return HasChanged;
}
/// See AbstractAttribute::updateImpl(...).
ChangeStatus updateImpl(Attributor &A) override;
/// See AAIsDead::isAssumedDead(BasicBlock *).
bool isAssumedDead(const BasicBlock *BB) const override {
assert(BB->getParent() == getAssociatedFunction() &&
"BB must be in the same anchor scope function.");
if (!getAssumed())
return false;
return !AssumedLiveBlocks.count(BB);
}
/// See AAIsDead::isKnownDead(BasicBlock *).
bool isKnownDead(const BasicBlock *BB) const override {
return getKnown() && isAssumedDead(BB);
}
/// See AAIsDead::isAssumed(Instruction *I).
bool isAssumedDead(const Instruction *I) const override {
assert(I->getParent()->getParent() == getAssociatedFunction() &&
"Instruction must be in the same anchor scope function.");
if (!getAssumed())
return false;
// If it is not in AssumedLiveBlocks then it for sure dead.
// Otherwise, it can still be after noreturn call in a live block.
if (!AssumedLiveBlocks.count(I->getParent()))
return true;
// If it is not after a noreturn call, than it is live.
return isAfterNoReturn(I);
}
/// See AAIsDead::isKnownDead(Instruction *I).
bool isKnownDead(const Instruction *I) const override {
return getKnown() && isAssumedDead(I);
}
/// Check if instruction is after noreturn call, in other words, assumed dead.
bool isAfterNoReturn(const Instruction *I) const;
/// Determine if \p F might catch asynchronous exceptions.
static bool mayCatchAsynchronousExceptions(const Function &F) {
return F.hasPersonalityFn() && !canSimplifyInvokeNoUnwind(&F);
}
/// Collection of to be explored paths.
SmallSetVector<const Instruction *, 8> ToBeExploredPaths;
/// Collection of all assumed live BasicBlocks.
DenseSet<const BasicBlock *> AssumedLiveBlocks;
/// Collection of calls with noreturn attribute, assumed or knwon.
SmallSetVector<const Instruction *, 4> NoReturnCalls;
};
struct AAIsDeadFunction final : public AAIsDeadImpl {
AAIsDeadFunction(const IRPosition &IRP) : AAIsDeadImpl(IRP) {}
/// See AbstractAttribute::trackStatistics()
void trackStatistics() const override {
STATS_DECL(DeadBlocks, Function,
"Number of basic blocks classified as dead");
BUILD_STAT_NAME(DeadBlocks, Function) +=
getAssociatedFunction()->size() - AssumedLiveBlocks.size();
STATS_DECL(PartiallyDeadBlocks, Function,
"Number of basic blocks classified as partially dead");
BUILD_STAT_NAME(PartiallyDeadBlocks, Function) += NoReturnCalls.size();
}
};
bool AAIsDeadImpl::isAfterNoReturn(const Instruction *I) const {
const Instruction *PrevI = I->getPrevNode();
while (PrevI) {
if (NoReturnCalls.count(PrevI))
return true;
PrevI = PrevI->getPrevNode();
}
return false;
}
const Instruction *AAIsDeadImpl::findNextNoReturn(Attributor &A,
const Instruction *I) {
const BasicBlock *BB = I->getParent();
const Function &F = *BB->getParent();
// Flag to determine if we can change an invoke to a call assuming the callee
// is nounwind. This is not possible if the personality of the function allows
// to catch asynchronous exceptions.
bool Invoke2CallAllowed = !mayCatchAsynchronousExceptions(F);
// TODO: We should have a function that determines if an "edge" is dead.
// Edges could be from an instruction to the next or from a terminator
// to the successor. For now, we need to special case the unwind block
// of InvokeInst below.
while (I) {
ImmutableCallSite ICS(I);
if (ICS) {
const IRPosition &IPos = IRPosition::callsite_function(ICS);
// Regarless of the no-return property of an invoke instruction we only
// learn that the regular successor is not reachable through this
// instruction but the unwind block might still be.
if (auto *Invoke = dyn_cast<InvokeInst>(I)) {
// Use nounwind to justify the unwind block is dead as well.
auto *AANoUnw = A.getAAFor<AANoUnwind>(*this, IPos);
if (!Invoke2CallAllowed ||
(!AANoUnw || !AANoUnw->isAssumedNoUnwind())) {
AssumedLiveBlocks.insert(Invoke->getUnwindDest());
ToBeExploredPaths.insert(&Invoke->getUnwindDest()->front());
}
}
auto *NoReturnAA = A.getAAFor<AANoReturn>(*this, IPos);
if (ICS.hasFnAttr(Attribute::NoReturn) ||
(NoReturnAA && NoReturnAA->isAssumedNoReturn()))
return I;
}
I = I->getNextNode();
}
// get new paths (reachable blocks).
for (const BasicBlock *SuccBB : successors(BB)) {
AssumedLiveBlocks.insert(SuccBB);
ToBeExploredPaths.insert(&SuccBB->front());
}
// No noreturn instruction found.
return nullptr;
}
ChangeStatus AAIsDeadImpl::updateImpl(Attributor &A) {
// Temporary collection to iterate over existing noreturn instructions. This
// will alow easier modification of NoReturnCalls collection
SmallVector<const Instruction *, 8> NoReturnChanged;
ChangeStatus Status = ChangeStatus::UNCHANGED;
for (const Instruction *I : NoReturnCalls)
NoReturnChanged.push_back(I);
for (const Instruction *I : NoReturnChanged) {
size_t Size = ToBeExploredPaths.size();
const Instruction *NextNoReturnI = findNextNoReturn(A, I);
if (NextNoReturnI != I) {
Status = ChangeStatus::CHANGED;
NoReturnCalls.remove(I);
if (NextNoReturnI)
NoReturnCalls.insert(NextNoReturnI);
}
// Explore new paths.
while (Size != ToBeExploredPaths.size()) {
Status = ChangeStatus::CHANGED;
if (const Instruction *NextNoReturnI =
findNextNoReturn(A, ToBeExploredPaths[Size++]))
NoReturnCalls.insert(NextNoReturnI);
}
}
LLVM_DEBUG(dbgs() << "[AAIsDead] AssumedLiveBlocks: "
<< AssumedLiveBlocks.size() << " Total number of blocks: "
<< getAssociatedFunction()->size() << "\n");
// If we know everything is live there is no need to query for liveness.
if (NoReturnCalls.empty() &&
getAssociatedFunction()->size() == AssumedLiveBlocks.size()) {
// Indicating a pessimistic fixpoint will cause the state to be "invalid"
// which will cause the Attributor to not return the AAIsDead on request,
// which will prevent us from querying isAssumedDead().
indicatePessimisticFixpoint();
assert(!isValidState() && "Expected an invalid state!");
}
return Status;
}
/// Liveness information for a call sites.
//
// TODO: Once we have call site specific value information we can provide call
// site specific liveness liveness information and then it makes sense to
// specialize attributes for call sites instead of redirecting requests to
// the callee.
using AAIsDeadCallSite = AAIsDeadFunction;
/// -------------------- Dereferenceable Argument Attribute --------------------
struct DerefState : AbstractState {
/// State representing for dereferenceable bytes.
IntegerState DerefBytesState;
/// State representing that whether the value is globaly dereferenceable.
BooleanState GlobalState;
/// See AbstractState::isValidState()
bool isValidState() const override { return DerefBytesState.isValidState(); }
/// See AbstractState::isAtFixpoint()
bool isAtFixpoint() const override {
return !isValidState() ||
(DerefBytesState.isAtFixpoint() && GlobalState.isAtFixpoint());
}
/// See AbstractState::indicateOptimisticFixpoint(...)
ChangeStatus indicateOptimisticFixpoint() override {
DerefBytesState.indicateOptimisticFixpoint();
GlobalState.indicateOptimisticFixpoint();
return ChangeStatus::UNCHANGED;
}
/// See AbstractState::indicatePessimisticFixpoint(...)
ChangeStatus indicatePessimisticFixpoint() override {
DerefBytesState.indicatePessimisticFixpoint();
GlobalState.indicatePessimisticFixpoint();
return ChangeStatus::CHANGED;
}
/// Update known dereferenceable bytes.
void takeKnownDerefBytesMaximum(uint64_t Bytes) {
DerefBytesState.takeKnownMaximum(Bytes);
}
/// Update assumed dereferenceable bytes.
void takeAssumedDerefBytesMinimum(uint64_t Bytes) {
DerefBytesState.takeAssumedMinimum(Bytes);
}
/// Equality for DerefState.
bool operator==(const DerefState &R) {
return this->DerefBytesState == R.DerefBytesState &&
this->GlobalState == R.GlobalState;
}
/// Inequality for IntegerState.
bool operator!=(const DerefState &R) { return !(*this == R); }
/// See IntegerState::operator^=
DerefState operator^=(const DerefState &R) {
DerefBytesState ^= R.DerefBytesState;
GlobalState ^= R.GlobalState;
return *this;
}
/// See IntegerState::operator&=
DerefState operator&=(const DerefState &R) {
DerefBytesState &= R.DerefBytesState;
GlobalState &= R.GlobalState;
return *this;
}
/// See IntegerState::operator|=
DerefState operator|=(const DerefState &R) {
DerefBytesState |= R.DerefBytesState;
GlobalState |= R.GlobalState;
return *this;
}
};
struct AADereferenceableImpl : AADereferenceable, DerefState {
AADereferenceableImpl(const IRPosition &IRP) : AADereferenceable(IRP) {}
using StateType = DerefState;
void initialize(Attributor &A) override {
SmallVector<Attribute, 4> Attrs;
getAttrs({Attribute::Dereferenceable, Attribute::DereferenceableOrNull},
Attrs);
for (const Attribute &Attr : Attrs)
takeKnownDerefBytesMaximum(Attr.getValueAsInt());
NonNullAA = A.getAAFor<AANonNull>(*this, getIRPosition());
}
/// See AbstractAttribute::getState()
/// {
StateType &getState() override { return *this; }
const StateType &getState() const override { return *this; }
/// }
/// See AADereferenceable::getAssumedDereferenceableBytes().
uint32_t getAssumedDereferenceableBytes() const override {
return DerefBytesState.getAssumed();
}
/// See AADereferenceable::getKnownDereferenceableBytes().
uint32_t getKnownDereferenceableBytes() const override {
return DerefBytesState.getKnown();
}
/// See AADereferenceable::isAssumedGlobal().
bool isAssumedGlobal() const override { return GlobalState.getAssumed(); }
/// See AADereferenceable::isKnownGlobal().
bool isKnownGlobal() const override { return GlobalState.getKnown(); }
bool isAssumedNonNull() const override {
return NonNullAA && NonNullAA->isAssumedNonNull();
}
void getDeducedAttributes(LLVMContext &Ctx,
SmallVectorImpl<Attribute> &Attrs) const override {
// TODO: Add *_globally support
if (isAssumedNonNull())
Attrs.emplace_back(Attribute::getWithDereferenceableBytes(
Ctx, getAssumedDereferenceableBytes()));
else
Attrs.emplace_back(Attribute::getWithDereferenceableOrNullBytes(
Ctx, getAssumedDereferenceableBytes()));
}
uint64_t computeAssumedDerefenceableBytes(Attributor &A, Value &V,
bool &IsGlobal);
/// See AbstractAttribute::getAsStr().
const std::string getAsStr() const override {
if (!getAssumedDereferenceableBytes())
return "unknown-dereferenceable";
return std::string("dereferenceable") +
(isAssumedNonNull() ? "" : "_or_null") +
(isAssumedGlobal() ? "_globally" : "") + "<" +
std::to_string(getKnownDereferenceableBytes()) + "-" +
std::to_string(getAssumedDereferenceableBytes()) + ">";
}
private:
const AANonNull *NonNullAA = nullptr;
};
struct AADereferenceableReturned final : AADereferenceableImpl {
AADereferenceableReturned(const IRPosition &IRP)
: AADereferenceableImpl(IRP) {}
/// See AbstractAttribute::updateImpl(...).
ChangeStatus updateImpl(Attributor &A) override;
/// See AbstractAttribute::trackStatistics()
void trackStatistics() const override {
STATS_DECLTRACK_FNRET_ATTR(dereferenceable)
}
};
// Helper function that returns dereferenceable bytes.
static uint64_t calcDifferenceIfBaseIsNonNull(int64_t DerefBytes,
int64_t Offset, bool IsNonNull) {
if (!IsNonNull)
return 0;
return std::max((int64_t)0, DerefBytes - Offset);
}
uint64_t
AADereferenceableImpl::computeAssumedDerefenceableBytes(Attributor &A, Value &V,
bool &IsGlobal) {
// TODO: Tracking the globally flag.
IsGlobal = false;
// First, we try to get information about V from Attributor.
if (auto *DerefAA =
A.getAAFor<AADereferenceable>(*this, IRPosition::value(V))) {
return DerefAA->getAssumedDereferenceableBytes();
}
// Otherwise, we try to compute assumed bytes from base pointer.
const DataLayout &DL = A.getDataLayout();
unsigned IdxWidth =
DL.getIndexSizeInBits(V.getType()->getPointerAddressSpace());
APInt Offset(IdxWidth, 0);
Value *Base = V.stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
if (auto *BaseDerefAA =
A.getAAFor<AADereferenceable>(*this, IRPosition::value(*Base))) {
return calcDifferenceIfBaseIsNonNull(
BaseDerefAA->getAssumedDereferenceableBytes(), Offset.getSExtValue(),
Offset != 0 || BaseDerefAA->isAssumedNonNull());
}
// Then, use IR information.
if (isDereferenceablePointer(Base, Base->getType(), DL))
return calcDifferenceIfBaseIsNonNull(
DL.getTypeStoreSize(Base->getType()->getPointerElementType()),
Offset.getSExtValue(),
!NullPointerIsDefined(getAnchorScope(),
V.getType()->getPointerAddressSpace()));
return 0;
}
ChangeStatus AADereferenceableReturned::updateImpl(Attributor &A) {
auto BeforeState = static_cast<DerefState>(*this);
bool IsGlobal = isAssumedGlobal();
auto CheckReturnValue = [&](Value &RV) -> bool {
takeAssumedDerefBytesMinimum(
computeAssumedDerefenceableBytes(A, RV, IsGlobal));
return isValidState();
};
if (A.checkForAllReturnedValues(CheckReturnValue, *this)) {
GlobalState.intersectAssumedBits(IsGlobal);
return BeforeState == static_cast<DerefState>(*this)
? ChangeStatus::UNCHANGED
: ChangeStatus::CHANGED;
}
return indicatePessimisticFixpoint();
}
struct AADereferenceableArgument final : AADereferenceableImpl {
AADereferenceableArgument(const IRPosition &IRP)
: AADereferenceableImpl(IRP) {}
/// See AbstractAttribute::updateImpl(...).
ChangeStatus updateImpl(Attributor &A) override;
/// See AbstractAttribute::trackStatistics()
void trackStatistics() const override {
STATS_DECLTRACK_ARG_ATTR(dereferenceable)
}
};
ChangeStatus AADereferenceableArgument::updateImpl(Attributor &A) {
Argument &Arg = cast<Argument>(getAnchorValue());
auto BeforeState = static_cast<DerefState>(*this);
unsigned ArgNo = Arg.getArgNo();
bool IsGlobal = isAssumedGlobal();
// Callback function
std::function<bool(CallSite)> CallSiteCheck = [&](CallSite CS) -> bool {
assert(CS && "Sanity check: Call site was not initialized properly!");
// Check that DereferenceableAA is AADereferenceableCallSiteArgument.
if (auto *DereferenceableAA = A.getAAFor<AADereferenceable>(
*this, IRPosition::callsite_argument(CS, ArgNo))) {
ImmutableCallSite ICS(
&DereferenceableAA->getIRPosition().getAnchorValue());
if (ICS && CS.getInstruction() == ICS.getInstruction()) {
takeAssumedDerefBytesMinimum(
DereferenceableAA->getAssumedDereferenceableBytes());
IsGlobal &= DereferenceableAA->isAssumedGlobal();
return isValidState();
}
}
takeAssumedDerefBytesMinimum(computeAssumedDerefenceableBytes(
A, *CS.getArgOperand(ArgNo), IsGlobal));
return isValidState();
};
if (!A.checkForAllCallSites(CallSiteCheck, *this, true))
return indicatePessimisticFixpoint();
GlobalState.intersectAssumedBits(IsGlobal);
return BeforeState == static_cast<DerefState>(*this) ? ChangeStatus::UNCHANGED
: ChangeStatus::CHANGED;
}
/// Dereferenceable attribute for a call site argument.
struct AADereferenceableCallSiteArgument final : AADereferenceableImpl {
AADereferenceableCallSiteArgument(const IRPosition &IRP)
: AADereferenceableImpl(IRP) {}
/// See AbstractAttribute::updateImpl(Attributor &A).
ChangeStatus updateImpl(Attributor &A) override;
/// See AbstractAttribute::trackStatistics()
void trackStatistics() const override {
STATS_DECLTRACK_CSARG_ATTR(dereferenceable)
}
};
ChangeStatus AADereferenceableCallSiteArgument::updateImpl(Attributor &A) {
// NOTE: Never look at the argument of the callee in this method.
// If we do this, "dereferenceable" is always deduced because of the
// assumption.
Value &V = getAssociatedValue();
auto BeforeState = static_cast<DerefState>(*this);
bool IsGlobal = isAssumedGlobal();
takeAssumedDerefBytesMinimum(
computeAssumedDerefenceableBytes(A, V, IsGlobal));
GlobalState.intersectAssumedBits(IsGlobal);
return BeforeState == static_cast<DerefState>(*this) ? ChangeStatus::UNCHANGED
: ChangeStatus::CHANGED;
}
/// Dereferenceable attribute deduction for a call site return value.
using AADereferenceableCallSiteReturned = AADereferenceableReturned;
// ------------------------ Align Argument Attribute ------------------------
struct AAAlignImpl : AAAlign {
AAAlignImpl(const IRPosition &IRP) : AAAlign(IRP) {}
// Max alignemnt value allowed in IR
static const unsigned MAX_ALIGN = 1U << 29;
/// See AbstractAttribute::initialize(...).
void initialize(Attributor &A) override {
takeAssumedMinimum(MAX_ALIGN);
SmallVector<Attribute, 4> Attrs;
getAttrs({Attribute::Alignment}, Attrs);
for (const Attribute &Attr : Attrs)
takeKnownMaximum(Attr.getValueAsInt());
}
/// See AbstractAttribute::getDeducedAttributes
virtual void
getDeducedAttributes(LLVMContext &Ctx,
SmallVectorImpl<Attribute> &Attrs) const override {
if (getAssumedAlign() > 1)
Attrs.emplace_back(Attribute::getWithAlignment(Ctx, getAssumedAlign()));
}
/// See AbstractAttribute::getAsStr().
const std::string getAsStr() const override {
return getAssumedAlign() ? ("align<" + std::to_string(getKnownAlign()) +
"-" + std::to_string(getAssumedAlign()) + ">")
: "unknown-align";
}
};
/// Align attribute for a floating value.
struct AAAlignFloating : AAAlignImpl {
AAAlignFloating(const IRPosition &IRP) : AAAlignImpl(IRP) {}
/// See AbstractAttribute::updateImpl(...).
ChangeStatus updateImpl(Attributor &A) override {
const DataLayout &DL = A.getDataLayout();
auto VisitValueCB = [&](Value &V, AAAlign::StateType &T, bool Stripped) {
if (!Stripped &&
getIRPosition().getPositionKind() == IRPosition::IRP_FLOAT) {
// Use only IR information if we did not strip anything.
T.takeKnownMaximum(V.getPointerAlignment(DL));
T.indicatePessimisticFixpoint();
} else if (const auto *AA =
A.getAAFor<AAAlign>(*this, IRPosition::value(V))) {
// Try to use abstract attribute information.
const AAAlign::StateType &DS =
static_cast<const AAAlign::StateType &>(AA->getState());
T.takeAssumedMinimum(DS.getAssumed());
} else {
// Last resort, look into the IR.
T.takeKnownMaximum(V.getPointerAlignment(DL));
T.indicatePessimisticFixpoint();
}
};
StateType T;
if (!genericValueTraversal<AAAlign, StateType>(A, getIRPosition(), *this, T,
VisitValueCB))
indicatePessimisticFixpoint();
return clampStateAndIndicateChange(getState(), T);
}
/// See AbstractAttribute::trackStatistics()
void trackStatistics() const override { STATS_DECLTRACK_FLOATING_ATTR(align) }
};
/// Align attribute for function return value.
struct AAAlignReturned final : AAReturnedFromReturnedValues<AAAlignImpl> {
AAAlignReturned(const IRPosition &IRP)
: AAReturnedFromReturnedValues<AAAlignImpl>(IRP) {}
/// See AbstractAttribute::trackStatistics()
void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(aligned) }
};
/// Align attribute for function argument.
struct AAAlignArgument final : AAArgumentFromCallSiteArguments<AAAlignImpl> {
AAAlignArgument(const IRPosition &IRP)
: AAArgumentFromCallSiteArguments<AAAlignImpl>(IRP) {}
/// See AbstractAttribute::trackStatistics()
void trackStatistics() const override{STATS_DECLTRACK_ARG_ATTR(aligned)};
};
struct AAAlignCallSiteArgument final : AAAlignFloating {
AAAlignCallSiteArgument(const IRPosition &IRP) : AAAlignFloating(IRP) {}
/// See AbstractAttribute::trackStatistics()
void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(aligned) }
};
/// Align attribute deduction for a call site return value.
using AAAlignCallSiteReturned = AAAlignReturned;
/// ------------------ Function No-Return Attribute ----------------------------
struct AANoReturnImpl : public AANoReturn {
AANoReturnImpl(const IRPosition &IRP) : AANoReturn(IRP) {}
/// See AbstractAttribute::getAsStr().
const std::string getAsStr() const override {
return getAssumed() ? "noreturn" : "may-return";
}
/// See AbstractAttribute::initialize(...).
void initialize(Attributor &A) override {
if (hasAttr({getAttrKind()}))
indicateOptimisticFixpoint();
}
/// See AbstractAttribute::updateImpl(Attributor &A).
virtual ChangeStatus updateImpl(Attributor &A) override {
auto CheckForNoReturn = [](Instruction &) { return false; };
if (!A.checkForAllInstructions(CheckForNoReturn, *this,
{(unsigned)Instruction::Ret}))
return indicatePessimisticFixpoint();
return ChangeStatus::UNCHANGED;
}
};
struct AANoReturnFunction final : AANoReturnImpl {
AANoReturnFunction(const IRPosition &IRP) : AANoReturnImpl(IRP) {}
/// See AbstractAttribute::trackStatistics()
void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(noreturn) }
};
/// NoReturn attribute deduction for a call sites.
using AANoReturnCallSite = AANoReturnFunction;
/// ----------------------------------------------------------------------------
/// Attributor
/// ----------------------------------------------------------------------------
bool Attributor::isAssumedDead(const AbstractAttribute &AA,
const AAIsDead *LivenessAA) {
const Instruction *CtxI = AA.getIRPosition().getCtxI();
if (!CtxI)
return false;
if (!LivenessAA)
LivenessAA =
getAAFor<AAIsDead>(AA, IRPosition::function(*CtxI->getFunction()));
if (!LivenessAA || !LivenessAA->isAssumedDead(CtxI))
return false;
// TODO: Do not track dependences automatically but add it here as only a
// "is-assumed-dead" result causes a dependence.
return true;
}
bool Attributor::checkForAllCallSites(const function_ref<bool(CallSite)> &Pred,
const AbstractAttribute &QueryingAA,
bool RequireAllCallSites) {
// We can try to determine information from
// the call sites. However, this is only possible all call sites are known,
// hence the function has internal linkage.
const IRPosition &IRP = QueryingAA.getIRPosition();
const Function *AssociatedFunction = IRP.getAssociatedFunction();
if (!AssociatedFunction)
return false;
if (RequireAllCallSites && !AssociatedFunction->hasInternalLinkage()) {
LLVM_DEBUG(
dbgs()
<< "[Attributor] Function " << AssociatedFunction->getName()
<< " has no internal linkage, hence not all call sites are known\n");
return false;
}
for (const Use &U : AssociatedFunction->uses()) {
Instruction *I = cast<Instruction>(U.getUser());
Function *Caller = I->getFunction();
auto *LivenessAA =
getAAFor<AAIsDead>(QueryingAA, IRPosition::function(*Caller));
// Skip dead calls.
if (LivenessAA && LivenessAA->isAssumedDead(I))
continue;
CallSite CS(U.getUser());
if (!CS || !CS.isCallee(&U) || !CS.getCaller()->hasExactDefinition()) {
if (!RequireAllCallSites)
continue;
LLVM_DEBUG(dbgs() << "[Attributor] User " << *U.getUser()
<< " is an invalid use of "
<< AssociatedFunction->getName() << "\n");
return false;
}
if (Pred(CS))
continue;
LLVM_DEBUG(dbgs() << "[Attributor] Call site callback failed for "
<< *CS.getInstruction() << "\n");
return false;
}
return true;
}
bool Attributor::checkForAllReturnedValuesAndReturnInsts(
const function_ref<bool(Value &, const SmallPtrSetImpl<ReturnInst *> &)>
&Pred,
const AbstractAttribute &QueryingAA) {
const IRPosition &IRP = QueryingAA.getIRPosition();
// Since we need to provide return instructions we have to have an exact
// definition.
const Function *AssociatedFunction = IRP.getAssociatedFunction();
if (!AssociatedFunction || !AssociatedFunction->hasExactDefinition())
return false;
// If this is a call site query we use the call site specific return values
// and liveness information.
const IRPosition &QueryIRP = IRPosition::function_scope(IRP);
const auto &AARetVal = getAAFor<AAReturnedValues>(QueryingAA, QueryIRP);
if (!AARetVal || !AARetVal->getState().isValidState())
return false;
return AARetVal->checkForAllReturnedValuesAndReturnInsts(Pred);
}
bool Attributor::checkForAllReturnedValues(
const function_ref<bool(Value &)> &Pred,
const AbstractAttribute &QueryingAA) {
const IRPosition &IRP = QueryingAA.getIRPosition();
const Function *AssociatedFunction = IRP.getAssociatedFunction();
if (!AssociatedFunction || !AssociatedFunction->hasExactDefinition())
return false;
const IRPosition &QueryIRP = IRPosition::function_scope(IRP);
const auto &AARetVal = getAAFor<AAReturnedValues>(QueryingAA, QueryIRP);
if (!AARetVal || !AARetVal->getState().isValidState())
return false;
return AARetVal->checkForAllReturnedValuesAndReturnInsts(
[&](Value &RV, const SmallPtrSetImpl<ReturnInst *> &) {
return Pred(RV);
});
}
bool Attributor::checkForAllInstructions(
const llvm::function_ref<bool(Instruction &)> &Pred,
const AbstractAttribute &QueryingAA, const ArrayRef<unsigned> &Opcodes) {
const IRPosition &IRP = QueryingAA.getIRPosition();
// Since we need to provide instructions we have to have an exact definition.
const Function *AssociatedFunction = IRP.getAssociatedFunction();
if (!AssociatedFunction || !AssociatedFunction->hasExactDefinition())
return false;
const IRPosition &QueryIRP = IRPosition::function_scope(IRP);
const auto &LivenessAA = getAAFor<AAIsDead>(QueryingAA, QueryIRP);
auto &OpcodeInstMap =
InfoCache.getOpcodeInstMapForFunction(*AssociatedFunction);
for (unsigned Opcode : Opcodes) {
for (Instruction *I : OpcodeInstMap[Opcode]) {
// Skip dead instructions.
if (LivenessAA && LivenessAA->isAssumedDead(I))
continue;
if (!Pred(*I))
return false;
}
}
return true;
}
bool Attributor::checkForAllReadWriteInstructions(
const llvm::function_ref<bool(Instruction &)> &Pred,
AbstractAttribute &QueryingAA) {
const Function *AssociatedFunction =
QueryingAA.getIRPosition().getAssociatedFunction();
if (!AssociatedFunction)
return false;
const auto &LivenessAA =
getAAFor<AAIsDead>(QueryingAA, QueryingAA.getIRPosition());
for (Instruction *I :
InfoCache.getReadOrWriteInstsForFunction(*AssociatedFunction)) {
// Skip dead instructions.
if (LivenessAA && LivenessAA->isAssumedDead(I))
continue;
if (!Pred(*I))
return false;
}
return true;
}
ChangeStatus Attributor::run() {
// Initialize all abstract attributes.
for (AbstractAttribute *AA : AllAbstractAttributes)
AA->initialize(*this);
LLVM_DEBUG(dbgs() << "[Attributor] Identified and initialized "
<< AllAbstractAttributes.size()
<< " abstract attributes.\n");
// Now that all abstract attributes are collected and initialized we start
// the abstract analysis.
unsigned IterationCounter = 1;
SmallVector<AbstractAttribute *, 64> ChangedAAs;
SetVector<AbstractAttribute *> Worklist;
Worklist.insert(AllAbstractAttributes.begin(), AllAbstractAttributes.end());
do {
LLVM_DEBUG(dbgs() << "\n\n[Attributor] #Iteration: " << IterationCounter
<< ", Worklist size: " << Worklist.size() << "\n");
// Add all abstract attributes that are potentially dependent on one that
// changed to the work list.
for (AbstractAttribute *ChangedAA : ChangedAAs) {
auto &QuerriedAAs = QueryMap[ChangedAA];
Worklist.insert(QuerriedAAs.begin(), QuerriedAAs.end());
}
// Reset the changed set.
ChangedAAs.clear();
// Update all abstract attribute in the work list and record the ones that
// changed.
for (AbstractAttribute *AA : Worklist)
if (!isAssumedDead(*AA, nullptr))
if (AA->update(*this) == ChangeStatus::CHANGED)
ChangedAAs.push_back(AA);
// Reset the work list and repopulate with the changed abstract attributes.
// Note that dependent ones are added above.
Worklist.clear();
Worklist.insert(ChangedAAs.begin(), ChangedAAs.end());
} while (!Worklist.empty() && ++IterationCounter < MaxFixpointIterations);
LLVM_DEBUG(dbgs() << "\n[Attributor] Fixpoint iteration done after: "
<< IterationCounter << "/" << MaxFixpointIterations
<< " iterations\n");
bool FinishedAtFixpoint = Worklist.empty();
// Reset abstract arguments not settled in a sound fixpoint by now. This
// happens when we stopped the fixpoint iteration early. Note that only the
// ones marked as "changed" *and* the ones transitively depending on them
// need to be reverted to a pessimistic state. Others might not be in a
// fixpoint state but we can use the optimistic results for them anyway.
SmallPtrSet<AbstractAttribute *, 32> Visited;
for (unsigned u = 0; u < ChangedAAs.size(); u++) {
AbstractAttribute *ChangedAA = ChangedAAs[u];
if (!Visited.insert(ChangedAA).second)
continue;
AbstractState &State = ChangedAA->getState();
if (!State.isAtFixpoint()) {
State.indicatePessimisticFixpoint();
NumAttributesTimedOut++;
}
auto &QuerriedAAs = QueryMap[ChangedAA];
ChangedAAs.append(QuerriedAAs.begin(), QuerriedAAs.end());
}
LLVM_DEBUG({
if (!Visited.empty())
dbgs() << "\n[Attributor] Finalized " << Visited.size()
<< " abstract attributes.\n";
});
unsigned NumManifested = 0;
unsigned NumAtFixpoint = 0;
ChangeStatus ManifestChange = ChangeStatus::UNCHANGED;
for (AbstractAttribute *AA : AllAbstractAttributes) {
AbstractState &State = AA->getState();
// If there is not already a fixpoint reached, we can now take the
// optimistic state. This is correct because we enforced a pessimistic one
// on abstract attributes that were transitively dependent on a changed one
// already above.
if (!State.isAtFixpoint())
State.indicateOptimisticFixpoint();
// If the state is invalid, we do not try to manifest it.
if (!State.isValidState())
continue;
// Skip dead code.
if (isAssumedDead(*AA, nullptr))
continue;
// Manifest the state and record if we changed the IR.
ChangeStatus LocalChange = AA->manifest(*this);
if (LocalChange == ChangeStatus::CHANGED && AreStatisticsEnabled())
AA->trackStatistics();
ManifestChange = ManifestChange | LocalChange;
NumAtFixpoint++;
NumManifested += (LocalChange == ChangeStatus::CHANGED);
}
(void)NumManifested;
(void)NumAtFixpoint;
LLVM_DEBUG(dbgs() << "\n[Attributor] Manifested " << NumManifested
<< " arguments while " << NumAtFixpoint
<< " were in a valid fixpoint state\n");
// If verification is requested, we finished this run at a fixpoint, and the
// IR was changed, we re-run the whole fixpoint analysis, starting at
// re-initialization of the arguments. This re-run should not result in an IR
// change. Though, the (virtual) state of attributes at the end of the re-run
// might be more optimistic than the known state or the IR state if the better
// state cannot be manifested.
if (VerifyAttributor && FinishedAtFixpoint &&
ManifestChange == ChangeStatus::CHANGED) {
VerifyAttributor = false;
ChangeStatus VerifyStatus = run();
if (VerifyStatus != ChangeStatus::UNCHANGED)
llvm_unreachable(
"Attributor verification failed, re-run did result in an IR change "
"even after a fixpoint was reached in the original run. (False "
"positives possible!)");
VerifyAttributor = true;
}
NumAttributesManifested += NumManifested;
NumAttributesValidFixpoint += NumAtFixpoint;
return ManifestChange;
}
/// Helper function that checks if an abstract attribute of type \p AAType
/// should be created for IR position \p IRP and if so creates and registers it
/// with the Attributor \p A.
///
/// This method will look at the provided whitelist. If one is given and the
/// kind \p AAType::ID is not contained, no abstract attribute is created.
///
/// \returns The created abstract argument, or nullptr if none was created.
template <typename AAType>
static AAType *checkAndRegisterAA(const IRPosition &IRP, Attributor &A,
DenseSet<const char *> *Whitelist) {
if (Whitelist && !Whitelist->count(&AAType::ID))
return nullptr;
return &A.registerAA<AAType>(*new AAType(IRP));
}
void Attributor::identifyDefaultAbstractAttributes(
Function &F, DenseSet<const char *> *Whitelist) {
IRPosition FPos = IRPosition::function(F);
// Check for dead BasicBlocks in every function.
// We need dead instruction detection because we do not want to deal with
// broken IR in which SSA rules do not apply.
checkAndRegisterAA<AAIsDeadFunction>(FPos, *this, /* Whitelist */ nullptr);
// Every function might be "will-return".
checkAndRegisterAA<AAWillReturnFunction>(FPos, *this, Whitelist);
// Every function can be nounwind.
checkAndRegisterAA<AANoUnwindFunction>(FPos, *this, Whitelist);
// Every function might be marked "nosync"
checkAndRegisterAA<AANoSyncFunction>(FPos, *this, Whitelist);
// Every function might be "no-free".
checkAndRegisterAA<AANoFreeFunction>(FPos, *this, Whitelist);
// Every function might be "no-return".
checkAndRegisterAA<AANoReturnFunction>(FPos, *this, Whitelist);
// Return attributes are only appropriate if the return type is non void.
Type *ReturnType = F.getReturnType();
if (!ReturnType->isVoidTy()) {
// Argument attribute "returned" --- Create only one per function even
// though it is an argument attribute.
checkAndRegisterAA<AAReturnedValuesFunction>(FPos, *this, Whitelist);
if (ReturnType->isPointerTy()) {
IRPosition RetPos = IRPosition::returned(F);
// Every function with pointer return type might be marked align.
checkAndRegisterAA<AAAlignReturned>(RetPos, *this, Whitelist);
// Every function with pointer return type might be marked nonnull.
checkAndRegisterAA<AANonNullReturned>(RetPos, *this, Whitelist);
// Every function with pointer return type might be marked noalias.
checkAndRegisterAA<AANoAliasReturned>(RetPos, *this, Whitelist);
// Every function with pointer return type might be marked
// dereferenceable.
checkAndRegisterAA<AADereferenceableReturned>(RetPos, *this, Whitelist);
}
}
for (Argument &Arg : F.args()) {
if (Arg.getType()->isPointerTy()) {
IRPosition ArgPos = IRPosition::argument(Arg);
// Every argument with pointer type might be marked nonnull.
checkAndRegisterAA<AANonNullArgument>(ArgPos, *this, Whitelist);
// Every argument with pointer type might be marked dereferenceable.
checkAndRegisterAA<AADereferenceableArgument>(ArgPos, *this, Whitelist);
// Every argument with pointer type might be marked align.
checkAndRegisterAA<AAAlignArgument>(ArgPos, *this, Whitelist);
}
}
// Walk all instructions to find more attribute opportunities and also
// interesting instructions that might be queried by abstract attributes
// during their initialization or update.
auto &ReadOrWriteInsts = InfoCache.FuncRWInstsMap[&F];
auto &InstOpcodeMap = InfoCache.FuncInstOpcodeMap[&F];
for (Instruction &I : instructions(&F)) {
bool IsInterestingOpcode = false;
// To allow easy access to all instructions in a function with a given
// opcode we store them in the InfoCache. As not all opcodes are interesting
// to concrete attributes we only cache the ones that are as identified in
// the following switch.
// Note: There are no concrete attributes now so this is initially empty.
switch (I.getOpcode()) {
default:
assert((!ImmutableCallSite(&I)) && (!isa<CallBase>(&I)) &&
"New call site/base instruction type needs to be known int the "
"attributor.");
break;
case Instruction::Call:
case Instruction::CallBr:
case Instruction::Invoke:
case Instruction::CleanupRet:
case Instruction::CatchSwitch:
case Instruction::Resume:
case Instruction::Ret:
IsInterestingOpcode = true;
}
if (IsInterestingOpcode)
InstOpcodeMap[I.getOpcode()].push_back(&I);
if (I.mayReadOrWriteMemory())
ReadOrWriteInsts.push_back(&I);
CallSite CS(&I);
if (CS && CS.getCalledFunction()) {
for (int i = 0, e = CS.getCalledFunction()->arg_size(); i < e; i++) {
if (!CS.getArgument(i)->getType()->isPointerTy())
continue;
IRPosition CSArgPos = IRPosition::callsite_argument(CS, i);
// Call site argument attribute "non-null".
checkAndRegisterAA<AANonNullCallSiteArgument>(CSArgPos, *this,
Whitelist);
// Call site argument attribute "dereferenceable".
checkAndRegisterAA<AADereferenceableCallSiteArgument>(CSArgPos, *this,
Whitelist);
// Call site argument attribute "align".
checkAndRegisterAA<AAAlignCallSiteArgument>(CSArgPos, *this, Whitelist);
}
}
}
}
/// Helpers to ease debugging through output streams and print calls.
///
///{
raw_ostream &llvm::operator<<(raw_ostream &OS, ChangeStatus S) {
return OS << (S == ChangeStatus::CHANGED ? "changed" : "unchanged");
}
raw_ostream &llvm::operator<<(raw_ostream &OS, IRPosition::Kind AP) {
switch (AP) {
case IRPosition::IRP_INVALID:
return OS << "inv";
case IRPosition::IRP_FLOAT:
return OS << "flt";
case IRPosition::IRP_RETURNED:
return OS << "fn_ret";
case IRPosition::IRP_CALL_SITE_RETURNED:
return OS << "cs_ret";
case IRPosition::IRP_FUNCTION:
return OS << "fn";
case IRPosition::IRP_CALL_SITE:
return OS << "cs";
case IRPosition::IRP_ARGUMENT:
return OS << "arg";
case IRPosition::IRP_CALL_SITE_ARGUMENT:
return OS << "cs_arg";
}
llvm_unreachable("Unknown attribute position!");
}
raw_ostream &llvm::operator<<(raw_ostream &OS, const IRPosition &Pos) {
const Value &AV = Pos.getAssociatedValue();
return OS << "{" << Pos.getPositionKind() << ":" << AV.getName() << " ["
<< Pos.getAnchorValue().getName() << "@" << Pos.getArgNo() << "]}";
}
raw_ostream &llvm::operator<<(raw_ostream &OS, const IntegerState &S) {
return OS << "(" << S.getKnown() << "-" << S.getAssumed() << ")"
<< static_cast<const AbstractState &>(S);
}
raw_ostream &llvm::operator<<(raw_ostream &OS, const AbstractState &S) {
return OS << (!S.isValidState() ? "top" : (S.isAtFixpoint() ? "fix" : ""));
}
raw_ostream &llvm::operator<<(raw_ostream &OS, const AbstractAttribute &AA) {
AA.print(OS);
return OS;
}
void AbstractAttribute::print(raw_ostream &OS) const {
OS << "[P: " << getIRPosition() << "][" << getAsStr() << "][S: " << getState()
<< "]";
}
///}
/// ----------------------------------------------------------------------------
/// Pass (Manager) Boilerplate
/// ----------------------------------------------------------------------------
static bool runAttributorOnModule(Module &M) {
if (DisableAttributor)
return false;
LLVM_DEBUG(dbgs() << "[Attributor] Run on module with " << M.size()
<< " functions.\n");
// Create an Attributor and initially empty information cache that is filled
// while we identify default attribute opportunities.
InformationCache InfoCache(M.getDataLayout());
Attributor A(InfoCache);
for (Function &F : M) {
// TODO: Not all attributes require an exact definition. Find a way to
// enable deduction for some but not all attributes in case the
// definition might be changed at runtime, see also
// http://lists.llvm.org/pipermail/llvm-dev/2018-February/121275.html.
// TODO: We could always determine abstract attributes and if sufficient
// information was found we could duplicate the functions that do not
// have an exact definition.
if (!F.hasExactDefinition()) {
NumFnWithoutExactDefinition++;
continue;
}
// For now we ignore naked and optnone functions.
if (F.hasFnAttribute(Attribute::Naked) ||
F.hasFnAttribute(Attribute::OptimizeNone))
continue;
NumFnWithExactDefinition++;
// Populate the Attributor with abstract attribute opportunities in the
// function and the information cache with IR information.
A.identifyDefaultAbstractAttributes(F);
}
return A.run() == ChangeStatus::CHANGED;
}
PreservedAnalyses AttributorPass::run(Module &M, ModuleAnalysisManager &AM) {
if (runAttributorOnModule(M)) {
// FIXME: Think about passes we will preserve and add them here.
return PreservedAnalyses::none();
}
return PreservedAnalyses::all();
}
namespace {
struct AttributorLegacyPass : public ModulePass {
static char ID;
AttributorLegacyPass() : ModulePass(ID) {
initializeAttributorLegacyPassPass(*PassRegistry::getPassRegistry());
}
bool runOnModule(Module &M) override {
if (skipModule(M))
return false;
return runAttributorOnModule(M);
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
// FIXME: Think about passes we will preserve and add them here.
AU.setPreservesCFG();
}
};
} // end anonymous namespace
Pass *llvm::createAttributorLegacyPass() { return new AttributorLegacyPass(); }
char AttributorLegacyPass::ID = 0;
const char AAReturnedValues::ID = 0;
const char AANoUnwind::ID = 0;
const char AANoSync::ID = 0;
const char AANoFree::ID = 0;
const char AANonNull::ID = 0;
const char AANoRecurse::ID = 0;
const char AAWillReturn::ID = 0;
const char AANoAlias::ID = 0;
const char AANoReturn::ID = 0;
const char AAIsDead::ID = 0;
const char AADereferenceable::ID = 0;
const char AAAlign::ID = 0;
INITIALIZE_PASS_BEGIN(AttributorLegacyPass, "attributor",
"Deduce and propagate attributes", false, false)
INITIALIZE_PASS_END(AttributorLegacyPass, "attributor",
"Deduce and propagate attributes", false, false)
|