1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
|
/* The analysis "engine".
Copyright (C) 2019-2024 Free Software Foundation, Inc.
Contributed by David Malcolm <dmalcolm@redhat.com>.
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3, or (at your option)
any later version.
GCC is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GCC; see the file COPYING3. If not see
<http://www.gnu.org/licenses/>. */
#include "config.h"
#define INCLUDE_MEMORY
#include "system.h"
#include "coretypes.h"
#include "make-unique.h"
#include "tree.h"
#include "fold-const.h"
#include "gcc-rich-location.h"
#include "diagnostic-core.h"
#include "diagnostic-event-id.h"
#include "diagnostic-path.h"
#include "function.h"
#include "pretty-print.h"
#include "sbitmap.h"
#include "bitmap.h"
#include "ordered-hash-map.h"
#include "analyzer/analyzer.h"
#include "analyzer/analyzer-logging.h"
#include "analyzer/call-string.h"
#include "analyzer/program-point.h"
#include "analyzer/store.h"
#include "analyzer/region-model.h"
#include "analyzer/constraint-manager.h"
#include "analyzer/sm.h"
#include "analyzer/pending-diagnostic.h"
#include "analyzer/diagnostic-manager.h"
#include "cfg.h"
#include "basic-block.h"
#include "gimple.h"
#include "gimple-iterator.h"
#include "gimple-pretty-print.h"
#include "cgraph.h"
#include "digraph.h"
#include "analyzer/supergraph.h"
#include "analyzer/program-state.h"
#include "analyzer/exploded-graph.h"
#include "analyzer/analysis-plan.h"
#include "analyzer/checker-path.h"
#include "analyzer/state-purge.h"
#include "analyzer/bar-chart.h"
#include "analyzer/call-info.h"
#include <zlib.h>
#include "plugin.h"
#include "target.h"
#include <memory>
#include "stringpool.h"
#include "attribs.h"
#include "tree-dfa.h"
#include "analyzer/known-function-manager.h"
#include "analyzer/call-summary.h"
/* For an overview, see gcc/doc/analyzer.texi. */
#if ENABLE_ANALYZER
namespace ana {
/* class impl_region_model_context : public region_model_context. */
impl_region_model_context::
impl_region_model_context (exploded_graph &eg,
exploded_node *enode_for_diag,
const program_state *old_state,
program_state *new_state,
uncertainty_t *uncertainty,
path_context *path_ctxt,
const gimple *stmt,
stmt_finder *stmt_finder,
bool *out_could_have_done_work)
: m_eg (&eg), m_logger (eg.get_logger ()),
m_enode_for_diag (enode_for_diag),
m_old_state (old_state),
m_new_state (new_state),
m_stmt (stmt),
m_stmt_finder (stmt_finder),
m_ext_state (eg.get_ext_state ()),
m_uncertainty (uncertainty),
m_path_ctxt (path_ctxt),
m_out_could_have_done_work (out_could_have_done_work)
{
}
impl_region_model_context::
impl_region_model_context (program_state *state,
const extrinsic_state &ext_state,
uncertainty_t *uncertainty,
logger *logger)
: m_eg (NULL), m_logger (logger), m_enode_for_diag (NULL),
m_old_state (NULL),
m_new_state (state),
m_stmt (NULL),
m_stmt_finder (NULL),
m_ext_state (ext_state),
m_uncertainty (uncertainty),
m_path_ctxt (NULL),
m_out_could_have_done_work (nullptr)
{
}
bool
impl_region_model_context::warn (std::unique_ptr<pending_diagnostic> d,
const stmt_finder *custom_finder)
{
LOG_FUNC (get_logger ());
auto curr_stmt_finder = custom_finder ? custom_finder : m_stmt_finder;
if (m_stmt == NULL && curr_stmt_finder == NULL)
{
if (get_logger ())
get_logger ()->log ("rejecting diagnostic: no stmt");
return false;
}
if (m_eg)
{
bool terminate_path = d->terminate_path_p ();
pending_location ploc (m_enode_for_diag,
m_enode_for_diag->get_supernode (),
m_stmt,
curr_stmt_finder);
if (m_eg->get_diagnostic_manager ().add_diagnostic (ploc,
std::move (d)))
{
if (m_path_ctxt
&& terminate_path
&& flag_analyzer_suppress_followups)
m_path_ctxt->terminate_path ();
return true;
}
}
return false;
}
void
impl_region_model_context::add_note (std::unique_ptr<pending_note> pn)
{
LOG_FUNC (get_logger ());
if (m_eg)
m_eg->get_diagnostic_manager ().add_note (std::move (pn));
}
void
impl_region_model_context::add_event (std::unique_ptr<checker_event> event)
{
LOG_FUNC (get_logger ());
if (m_eg)
m_eg->get_diagnostic_manager ().add_event (std::move (event));
}
void
impl_region_model_context::on_svalue_leak (const svalue *sval)
{
for (sm_state_map *smap : m_new_state->m_checker_states)
smap->on_svalue_leak (sval, this);
}
void
impl_region_model_context::
on_liveness_change (const svalue_set &live_svalues,
const region_model *model)
{
for (sm_state_map *smap : m_new_state->m_checker_states)
smap->on_liveness_change (live_svalues, model, m_ext_state, this);
}
void
impl_region_model_context::on_unknown_change (const svalue *sval,
bool is_mutable)
{
if (!sval->can_have_associated_state_p ())
return;
for (sm_state_map *smap : m_new_state->m_checker_states)
smap->on_unknown_change (sval, is_mutable, m_ext_state);
}
void
impl_region_model_context::on_escaped_function (tree fndecl)
{
m_eg->on_escaped_function (fndecl);
}
uncertainty_t *
impl_region_model_context::get_uncertainty ()
{
return m_uncertainty;
}
/* Purge state involving SVAL. The region_model has already been purged,
so we only need to purge other state in the program_state:
the sm-state. */
void
impl_region_model_context::purge_state_involving (const svalue *sval)
{
int i;
sm_state_map *smap;
FOR_EACH_VEC_ELT (m_new_state->m_checker_states, i, smap)
smap->purge_state_involving (sval, m_ext_state);
}
void
impl_region_model_context::bifurcate (std::unique_ptr<custom_edge_info> info)
{
if (m_path_ctxt)
m_path_ctxt->bifurcate (std::move (info));
}
void
impl_region_model_context::terminate_path ()
{
if (m_path_ctxt)
return m_path_ctxt->terminate_path ();
}
/* struct setjmp_record. */
int
setjmp_record::cmp (const setjmp_record &rec1, const setjmp_record &rec2)
{
if (int cmp_enode = rec1.m_enode->m_index - rec2.m_enode->m_index)
return cmp_enode;
gcc_assert (&rec1 == &rec2);
return 0;
}
/* class setjmp_svalue : public svalue. */
/* Implementation of svalue::accept vfunc for setjmp_svalue. */
void
setjmp_svalue::accept (visitor *v) const
{
v->visit_setjmp_svalue (this);
}
/* Implementation of svalue::dump_to_pp vfunc for setjmp_svalue. */
void
setjmp_svalue::dump_to_pp (pretty_printer *pp, bool simple) const
{
if (simple)
pp_printf (pp, "SETJMP(EN: %i)", get_enode_index ());
else
pp_printf (pp, "setjmp_svalue(EN%i)", get_enode_index ());
}
/* Get the index of the stored exploded_node. */
int
setjmp_svalue::get_enode_index () const
{
return m_setjmp_record.m_enode->m_index;
}
/* Concrete implementation of sm_context, wiring it up to the rest of this
file. */
class impl_sm_context : public sm_context
{
public:
impl_sm_context (exploded_graph &eg,
int sm_idx,
const state_machine &sm,
exploded_node *enode_for_diag,
const program_state *old_state,
program_state *new_state,
const sm_state_map *old_smap,
sm_state_map *new_smap,
path_context *path_ctxt,
const stmt_finder *stmt_finder = NULL,
bool unknown_side_effects = false)
: sm_context (sm_idx, sm),
m_logger (eg.get_logger ()),
m_eg (eg), m_enode_for_diag (enode_for_diag),
m_old_state (old_state), m_new_state (new_state),
m_old_smap (old_smap), m_new_smap (new_smap),
m_path_ctxt (path_ctxt),
m_stmt_finder (stmt_finder),
m_unknown_side_effects (unknown_side_effects)
{
}
logger *get_logger () const { return m_logger.get_logger (); }
tree get_fndecl_for_call (const gcall *call) final override
{
impl_region_model_context old_ctxt
(m_eg, m_enode_for_diag, NULL, NULL, NULL/*m_enode->get_state ()*/,
NULL, call);
region_model *model = m_new_state->m_region_model;
return model->get_fndecl_for_call (call, &old_ctxt);
}
state_machine::state_t get_state (const gimple *stmt ATTRIBUTE_UNUSED,
tree var) final override
{
logger * const logger = get_logger ();
LOG_FUNC (logger);
/* Use NULL ctxt on this get_rvalue call to avoid triggering
uninitialized value warnings. */
const svalue *var_old_sval
= m_old_state->m_region_model->get_rvalue (var, NULL);
state_machine::state_t current
= m_old_smap->get_state (var_old_sval, m_eg.get_ext_state ());
return current;
}
state_machine::state_t get_state (const gimple *stmt ATTRIBUTE_UNUSED,
const svalue *sval) final override
{
logger * const logger = get_logger ();
LOG_FUNC (logger);
state_machine::state_t current
= m_old_smap->get_state (sval, m_eg.get_ext_state ());
return current;
}
void set_next_state (const gimple *,
tree var,
state_machine::state_t to,
tree origin) final override
{
logger * const logger = get_logger ();
LOG_FUNC (logger);
const svalue *var_new_sval
= m_new_state->m_region_model->get_rvalue (var, NULL);
const svalue *origin_new_sval
= m_new_state->m_region_model->get_rvalue (origin, NULL);
/* We use the new sval here to avoid issues with uninitialized values. */
state_machine::state_t current
= m_old_smap->get_state (var_new_sval, m_eg.get_ext_state ());
if (logger)
logger->log ("%s: state transition of %qE: %s -> %s",
m_sm.get_name (),
var,
current->get_name (),
to->get_name ());
m_new_smap->set_state (m_new_state->m_region_model, var_new_sval,
to, origin_new_sval, m_eg.get_ext_state ());
}
void set_next_state (const gimple *stmt,
const svalue *sval,
state_machine::state_t to,
tree origin) final override
{
logger * const logger = get_logger ();
LOG_FUNC (logger);
impl_region_model_context old_ctxt
(m_eg, m_enode_for_diag, NULL, NULL, NULL/*m_enode->get_state ()*/,
NULL, stmt);
const svalue *origin_new_sval
= m_new_state->m_region_model->get_rvalue (origin, NULL);
state_machine::state_t current
= m_old_smap->get_state (sval, m_eg.get_ext_state ());
if (logger)
{
logger->start_log_line ();
logger->log_partial ("%s: state transition of ",
m_sm.get_name ());
sval->dump_to_pp (logger->get_printer (), true);
logger->log_partial (": %s -> %s",
current->get_name (),
to->get_name ());
logger->end_log_line ();
}
m_new_smap->set_state (m_new_state->m_region_model, sval,
to, origin_new_sval, m_eg.get_ext_state ());
}
void warn (const supernode *snode, const gimple *stmt,
tree var,
std::unique_ptr<pending_diagnostic> d) final override
{
LOG_FUNC (get_logger ());
gcc_assert (d);
const svalue *var_old_sval
= m_old_state->m_region_model->get_rvalue (var, NULL);
state_machine::state_t current
= (var
? m_old_smap->get_state (var_old_sval, m_eg.get_ext_state ())
: m_old_smap->get_global_state ());
bool terminate_path = d->terminate_path_p ();
pending_location ploc (m_enode_for_diag, snode, stmt, m_stmt_finder);
m_eg.get_diagnostic_manager ().add_diagnostic
(&m_sm, ploc,
var, var_old_sval, current, std::move (d));
if (m_path_ctxt
&& terminate_path
&& flag_analyzer_suppress_followups)
m_path_ctxt->terminate_path ();
}
void warn (const supernode *snode, const gimple *stmt,
const svalue *sval,
std::unique_ptr<pending_diagnostic> d) final override
{
LOG_FUNC (get_logger ());
gcc_assert (d);
state_machine::state_t current
= (sval
? m_old_smap->get_state (sval, m_eg.get_ext_state ())
: m_old_smap->get_global_state ());
bool terminate_path = d->terminate_path_p ();
pending_location ploc (m_enode_for_diag, snode, stmt, m_stmt_finder);
m_eg.get_diagnostic_manager ().add_diagnostic
(&m_sm, ploc,
NULL_TREE, sval, current, std::move (d));
if (m_path_ctxt
&& terminate_path
&& flag_analyzer_suppress_followups)
m_path_ctxt->terminate_path ();
}
/* Hook for picking more readable trees for SSA names of temporaries,
so that rather than e.g.
"double-free of '<unknown>'"
we can print:
"double-free of 'inbuf.data'". */
tree get_diagnostic_tree (tree expr) final override
{
/* Only for SSA_NAMEs of temporaries; otherwise, return EXPR, as it's
likely to be the least surprising tree to report. */
if (TREE_CODE (expr) != SSA_NAME)
return expr;
if (SSA_NAME_VAR (expr) != NULL)
return expr;
gcc_assert (m_new_state);
const svalue *sval = m_new_state->m_region_model->get_rvalue (expr, NULL);
/* Find trees for all regions storing the value. */
if (tree t = m_new_state->m_region_model->get_representative_tree (sval))
return t;
else
return expr;
}
tree get_diagnostic_tree (const svalue *sval) final override
{
return m_new_state->m_region_model->get_representative_tree (sval);
}
state_machine::state_t get_global_state () const final override
{
return m_old_state->m_checker_states[m_sm_idx]->get_global_state ();
}
void set_global_state (state_machine::state_t state) final override
{
m_new_state->m_checker_states[m_sm_idx]->set_global_state (state);
}
void clear_all_per_svalue_state () final override
{
m_new_state->m_checker_states[m_sm_idx]->clear_all_per_svalue_state ();
}
void on_custom_transition (custom_transition *transition) final override
{
transition->impl_transition (&m_eg,
const_cast<exploded_node *> (m_enode_for_diag),
m_sm_idx);
}
tree is_zero_assignment (const gimple *stmt) final override
{
const gassign *assign_stmt = dyn_cast <const gassign *> (stmt);
if (!assign_stmt)
return NULL_TREE;
impl_region_model_context old_ctxt
(m_eg, m_enode_for_diag, m_old_state, m_new_state, NULL, NULL, stmt);
if (const svalue *sval
= m_new_state->m_region_model->get_gassign_result (assign_stmt,
&old_ctxt))
if (tree cst = sval->maybe_get_constant ())
if (::zerop(cst))
return gimple_assign_lhs (assign_stmt);
return NULL_TREE;
}
path_context *get_path_context () const final override
{
return m_path_ctxt;
}
bool unknown_side_effects_p () const final override
{
return m_unknown_side_effects;
}
const program_state *get_old_program_state () const final override
{
return m_old_state;
}
const program_state *get_new_program_state () const final override
{
return m_new_state;
}
log_user m_logger;
exploded_graph &m_eg;
exploded_node *m_enode_for_diag;
const program_state *m_old_state;
program_state *m_new_state;
const sm_state_map *m_old_smap;
sm_state_map *m_new_smap;
path_context *m_path_ctxt;
const stmt_finder *m_stmt_finder;
/* Are we handling an external function with unknown side effects? */
bool m_unknown_side_effects;
};
bool
impl_region_model_context::
get_state_map_by_name (const char *name,
sm_state_map **out_smap,
const state_machine **out_sm,
unsigned *out_sm_idx,
std::unique_ptr<sm_context> *out_sm_context)
{
if (!m_new_state)
return false;
unsigned sm_idx;
if (!m_ext_state.get_sm_idx_by_name (name, &sm_idx))
return false;
const state_machine *sm = &m_ext_state.get_sm (sm_idx);
sm_state_map *new_smap = m_new_state->m_checker_states[sm_idx];
*out_smap = new_smap;
*out_sm = sm;
if (out_sm_idx)
*out_sm_idx = sm_idx;
if (out_sm_context)
{
const sm_state_map *old_smap = m_old_state->m_checker_states[sm_idx];
*out_sm_context
= make_unique<impl_sm_context> (*m_eg,
sm_idx,
*sm,
m_enode_for_diag,
m_old_state,
m_new_state,
old_smap,
new_smap,
m_path_ctxt,
m_stmt_finder,
false);
}
return true;
}
/* Subclass of stmt_finder for finding the best stmt to report the leak at,
given the emission path. */
class leak_stmt_finder : public stmt_finder
{
public:
leak_stmt_finder (const exploded_graph &eg, tree var)
: m_eg (eg), m_var (var) {}
std::unique_ptr<stmt_finder> clone () const final override
{
return make_unique<leak_stmt_finder> (m_eg, m_var);
}
const gimple *find_stmt (const exploded_path &epath)
final override
{
logger * const logger = m_eg.get_logger ();
LOG_FUNC (logger);
if (m_var && TREE_CODE (m_var) == SSA_NAME)
{
/* Locate the final write to this SSA name in the path. */
const gimple *def_stmt = SSA_NAME_DEF_STMT (m_var);
int idx_of_def_stmt;
bool found = epath.find_stmt_backwards (def_stmt, &idx_of_def_stmt);
if (!found)
goto not_found;
/* What was the next write to the underlying var
after the SSA name was set? (if any). */
for (unsigned idx = idx_of_def_stmt + 1;
idx < epath.m_edges.length ();
++idx)
{
const exploded_edge *eedge = epath.m_edges[idx];
if (logger)
logger->log ("eedge[%i]: EN %i -> EN %i",
idx,
eedge->m_src->m_index,
eedge->m_dest->m_index);
const exploded_node *dst_node = eedge->m_dest;
const program_point &dst_point = dst_node->get_point ();
const gimple *stmt = dst_point.get_stmt ();
if (!stmt)
continue;
if (const gassign *assign = dyn_cast <const gassign *> (stmt))
{
tree lhs = gimple_assign_lhs (assign);
if (TREE_CODE (lhs) == SSA_NAME
&& SSA_NAME_VAR (lhs) == SSA_NAME_VAR (m_var))
return assign;
}
}
}
not_found:
/* Look backwards for the first statement with a location. */
int i;
const exploded_edge *eedge;
FOR_EACH_VEC_ELT_REVERSE (epath.m_edges, i, eedge)
{
if (logger)
logger->log ("eedge[%i]: EN %i -> EN %i",
i,
eedge->m_src->m_index,
eedge->m_dest->m_index);
const exploded_node *dst_node = eedge->m_dest;
const program_point &dst_point = dst_node->get_point ();
const gimple *stmt = dst_point.get_stmt ();
if (stmt)
if (get_pure_location (stmt->location) != UNKNOWN_LOCATION)
return stmt;
}
gcc_unreachable ();
return NULL;
}
private:
const exploded_graph &m_eg;
tree m_var;
};
/* A measurement of how good EXPR is for presenting to the user, so
that e.g. we can say prefer printing
"leak of 'tmp.m_ptr'"
over:
"leak of '<unknown>'". */
static int
readability (const_tree expr)
{
/* Arbitrarily-chosen "high readability" value. */
const int HIGH_READABILITY = 65536;
gcc_assert (expr);
switch (TREE_CODE (expr))
{
case COMPONENT_REF:
case MEM_REF:
/* Impose a slight readability penalty relative to that of
operand 0. */
return readability (TREE_OPERAND (expr, 0)) - 16;
case SSA_NAME:
{
if (tree var = SSA_NAME_VAR (expr))
{
if (DECL_ARTIFICIAL (var))
{
/* If we have an SSA name for an artificial var,
only use it if it has a debug expr associated with
it that fixup_tree_for_diagnostic can use. */
if (VAR_P (var) && DECL_HAS_DEBUG_EXPR_P (var))
return readability (DECL_DEBUG_EXPR (var)) - 1;
}
else
{
/* Slightly favor the underlying var over the SSA name to
avoid having them compare equal. */
return readability (var) - 1;
}
}
/* Avoid printing '<unknown>' for SSA names for temporaries. */
return -1;
}
break;
case PARM_DECL:
case VAR_DECL:
if (DECL_NAME (expr))
return HIGH_READABILITY;
else
/* We don't want to print temporaries. For example, the C FE
prints them as e.g. "<Uxxxx>" where "xxxx" is the low 16 bits
of the tree pointer (see pp_c_tree_decl_identifier). */
return -1;
case RESULT_DECL:
/* Printing "<return-value>" isn't ideal, but is less awful than
trying to print a temporary. */
return HIGH_READABILITY / 2;
case NOP_EXPR:
{
/* Impose a moderate readability penalty for casts. */
const int CAST_PENALTY = 32;
return readability (TREE_OPERAND (expr, 0)) - CAST_PENALTY;
}
case INTEGER_CST:
return HIGH_READABILITY;
default:
return 0;
}
return 0;
}
/* A qsort comparator for trees to sort them into most user-readable to
least user-readable. */
int
readability_comparator (const void *p1, const void *p2)
{
path_var pv1 = *(path_var const *)p1;
path_var pv2 = *(path_var const *)p2;
const int tree_r1 = readability (pv1.m_tree);
const int tree_r2 = readability (pv2.m_tree);
/* Favor items that are deeper on the stack and hence more recent;
this also favors locals over globals. */
const int COST_PER_FRAME = 64;
const int depth_r1 = pv1.m_stack_depth * COST_PER_FRAME;
const int depth_r2 = pv2.m_stack_depth * COST_PER_FRAME;
/* Combine the scores from the tree and from the stack depth.
This e.g. lets us have a slightly penalized cast in the most
recent stack frame "beat" an uncast value in an older stack frame. */
const int sum_r1 = tree_r1 + depth_r1;
const int sum_r2 = tree_r2 + depth_r2;
if (int cmp = sum_r2 - sum_r1)
return cmp;
/* Otherwise, more readable trees win. */
if (int cmp = tree_r2 - tree_r1)
return cmp;
/* Otherwise, if they have the same readability, then impose an
arbitrary deterministic ordering on them. */
if (int cmp = TREE_CODE (pv1.m_tree) - TREE_CODE (pv2.m_tree))
return cmp;
switch (TREE_CODE (pv1.m_tree))
{
default:
break;
case SSA_NAME:
if (int cmp = (SSA_NAME_VERSION (pv1.m_tree)
- SSA_NAME_VERSION (pv2.m_tree)))
return cmp;
break;
case PARM_DECL:
case VAR_DECL:
case RESULT_DECL:
if (int cmp = DECL_UID (pv1.m_tree) - DECL_UID (pv2.m_tree))
return cmp;
break;
}
/* TODO: We ought to find ways of sorting such cases. */
return 0;
}
/* Return true is SNODE is the EXIT node of a function, or is one
of the final snodes within its function.
Specifically, handle the final supernodes before the EXIT node,
for the case of clobbers that happen immediately before exiting.
We need a run of snodes leading to the return_p snode, where all edges are
intraprocedural, and every snode has just one successor.
We use this when suppressing leak reports at the end of "main". */
static bool
returning_from_function_p (const supernode *snode)
{
if (!snode)
return false;
unsigned count = 0;
const supernode *iter = snode;
while (true)
{
if (iter->return_p ())
return true;
if (iter->m_succs.length () != 1)
return false;
const superedge *sedge = iter->m_succs[0];
if (sedge->get_kind () != SUPEREDGE_CFG_EDGE)
return false;
iter = sedge->m_dest;
/* Impose a limit to ensure we terminate for pathological cases.
We only care about the final 3 nodes, due to cases like:
BB:
(clobber causing leak)
BB:
<label>:
return _val;
EXIT BB.*/
if (++count > 3)
return false;
}
}
/* Find the best tree for SVAL and call SM's on_leak vfunc with it.
If on_leak returns a pending_diagnostic, queue it up to be reported,
so that we potentially complain about a leak of SVAL in the given STATE. */
void
impl_region_model_context::on_state_leak (const state_machine &sm,
const svalue *sval,
state_machine::state_t state)
{
logger * const logger = get_logger ();
LOG_SCOPE (logger);
if (logger)
{
logger->start_log_line ();
logger->log_partial ("considering leak of ");
sval->dump_to_pp (logger->get_printer (), true);
logger->end_log_line ();
}
if (!m_eg)
return;
/* m_old_state also needs to be non-NULL so that the sm_ctxt can look
up the old state of SVAL. */
gcc_assert (m_old_state);
/* SVAL has leaked within the new state: it is not used by any reachable
regions.
We need to convert it back to a tree, but since it's likely no regions
use it, we have to find the "best" tree for it in the old_state. */
svalue_set visited;
path_var leaked_pv
= m_old_state->m_region_model->get_representative_path_var (sval,
&visited);
/* Strip off top-level casts */
if (leaked_pv.m_tree && TREE_CODE (leaked_pv.m_tree) == NOP_EXPR)
leaked_pv.m_tree = TREE_OPERAND (leaked_pv.m_tree, 0);
/* This might be NULL; the pending_diagnostic subclasses need to cope
with this. */
tree leaked_tree = leaked_pv.m_tree;
if (logger)
{
if (leaked_tree)
logger->log ("best leaked_tree: %qE", leaked_tree);
else
logger->log ("best leaked_tree: NULL");
}
leak_stmt_finder stmt_finder (*m_eg, leaked_tree);
gcc_assert (m_enode_for_diag);
/* Don't complain about leaks when returning from "main". */
if (returning_from_function_p (m_enode_for_diag->get_supernode ()))
{
tree fndecl = m_enode_for_diag->get_function ()->decl;
if (id_equal (DECL_NAME (fndecl), "main"))
{
if (logger)
logger->log ("not reporting leak from main");
return;
}
}
tree leaked_tree_for_diag = fixup_tree_for_diagnostic (leaked_tree);
std::unique_ptr<pending_diagnostic> pd = sm.on_leak (leaked_tree_for_diag);
if (pd)
{
pending_location ploc (m_enode_for_diag,
m_enode_for_diag->get_supernode (),
m_stmt,
&stmt_finder);
m_eg->get_diagnostic_manager ().add_diagnostic
(&sm, ploc,
leaked_tree_for_diag, sval, state, std::move (pd));
}
}
/* Implementation of region_model_context::on_condition vfunc.
Notify all state machines about the condition, which could lead to
state transitions. */
void
impl_region_model_context::on_condition (const svalue *lhs,
enum tree_code op,
const svalue *rhs)
{
int sm_idx;
sm_state_map *smap;
FOR_EACH_VEC_ELT (m_new_state->m_checker_states, sm_idx, smap)
{
const state_machine &sm = m_ext_state.get_sm (sm_idx);
impl_sm_context sm_ctxt (*m_eg, sm_idx, sm, m_enode_for_diag,
m_old_state, m_new_state,
m_old_state->m_checker_states[sm_idx],
m_new_state->m_checker_states[sm_idx],
m_path_ctxt);
sm.on_condition (&sm_ctxt,
(m_enode_for_diag
? m_enode_for_diag->get_supernode ()
: NULL),
m_stmt,
lhs, op, rhs);
}
}
/* Implementation of region_model_context::on_bounded_ranges vfunc.
Notify all state machines about the ranges, which could lead to
state transitions. */
void
impl_region_model_context::on_bounded_ranges (const svalue &sval,
const bounded_ranges &ranges)
{
int sm_idx;
sm_state_map *smap;
FOR_EACH_VEC_ELT (m_new_state->m_checker_states, sm_idx, smap)
{
const state_machine &sm = m_ext_state.get_sm (sm_idx);
impl_sm_context sm_ctxt (*m_eg, sm_idx, sm, m_enode_for_diag,
m_old_state, m_new_state,
m_old_state->m_checker_states[sm_idx],
m_new_state->m_checker_states[sm_idx],
m_path_ctxt);
sm.on_bounded_ranges (&sm_ctxt,
(m_enode_for_diag
? m_enode_for_diag->get_supernode ()
: NULL),
m_stmt, sval, ranges);
}
}
/* Implementation of region_model_context::on_pop_frame vfunc.
Notify all state machines about the frame being popped, which
could lead to states being discarded. */
void
impl_region_model_context::on_pop_frame (const frame_region *frame_reg)
{
int sm_idx;
sm_state_map *smap;
FOR_EACH_VEC_ELT (m_new_state->m_checker_states, sm_idx, smap)
{
const state_machine &sm = m_ext_state.get_sm (sm_idx);
sm.on_pop_frame (smap, frame_reg);
}
}
/* Implementation of region_model_context::on_phi vfunc.
Notify all state machines about the phi, which could lead to
state transitions. */
void
impl_region_model_context::on_phi (const gphi *phi, tree rhs)
{
int sm_idx;
sm_state_map *smap;
FOR_EACH_VEC_ELT (m_new_state->m_checker_states, sm_idx, smap)
{
const state_machine &sm = m_ext_state.get_sm (sm_idx);
impl_sm_context sm_ctxt (*m_eg, sm_idx, sm, m_enode_for_diag,
m_old_state, m_new_state,
m_old_state->m_checker_states[sm_idx],
m_new_state->m_checker_states[sm_idx],
m_path_ctxt);
sm.on_phi (&sm_ctxt, m_enode_for_diag->get_supernode (), phi, rhs);
}
}
/* Implementation of region_model_context::on_unexpected_tree_code vfunc.
Mark the new state as being invalid for further exploration.
TODO(stage1): introduce a warning for when this occurs. */
void
impl_region_model_context::on_unexpected_tree_code (tree t,
const dump_location_t &loc)
{
logger * const logger = get_logger ();
if (logger)
logger->log ("unhandled tree code: %qs in %qs at %s:%i",
get_tree_code_name (TREE_CODE (t)),
loc.get_impl_location ().m_function,
loc.get_impl_location ().m_file,
loc.get_impl_location ().m_line);
if (m_new_state)
m_new_state->m_valid = false;
}
/* Implementation of region_model_context::maybe_did_work vfunc.
Mark that "externally visible work" has occurred, and thus we
shouldn't report an infinite loop here. */
void
impl_region_model_context::maybe_did_work ()
{
if (m_out_could_have_done_work)
*m_out_could_have_done_work = true;
}
/* struct point_and_state. */
/* Assert that this object is sane. */
void
point_and_state::validate (const extrinsic_state &ext_state) const
{
/* Skip this in a release build. */
#if !CHECKING_P
return;
#endif
m_point.validate ();
m_state.validate (ext_state);
/* Verify that the callstring's model of the stack corresponds to that
of the region_model. */
/* They should have the same depth. */
gcc_assert (m_point.get_stack_depth ()
== m_state.m_region_model->get_stack_depth ());
/* Check the functions in the callstring vs those in the frames
at each depth. */
for (const frame_region *iter_frame
= m_state.m_region_model->get_current_frame ();
iter_frame; iter_frame = iter_frame->get_calling_frame ())
{
int index = iter_frame->get_index ();
gcc_assert (m_point.get_function_at_depth (index)
== &iter_frame->get_function ());
}
}
/* Subroutine of print_enode_indices: print a run of indices from START_IDX
to END_IDX to PP, using and updating *FIRST_RUN. */
static void
print_run (pretty_printer *pp, int start_idx, int end_idx,
bool *first_run)
{
if (!(*first_run))
pp_string (pp, ", ");
*first_run = false;
if (start_idx == end_idx)
pp_printf (pp, "EN: %i", start_idx);
else
pp_printf (pp, "EN: %i-%i", start_idx, end_idx);
}
/* Print the indices within ENODES to PP, collecting them as
runs/singletons e.g. "EN: 4-7, EN: 20-23, EN: 42". */
static void
print_enode_indices (pretty_printer *pp,
const auto_vec<exploded_node *> &enodes)
{
int cur_start_idx = -1;
int cur_finish_idx = -1;
bool first_run = true;
unsigned i;
exploded_node *enode;
FOR_EACH_VEC_ELT (enodes, i, enode)
{
if (cur_start_idx == -1)
{
gcc_assert (cur_finish_idx == -1);
cur_start_idx = cur_finish_idx = enode->m_index;
}
else
{
if (enode->m_index == cur_finish_idx + 1)
/* Continuation of a run. */
cur_finish_idx = enode->m_index;
else
{
/* Finish existing run, start a new one. */
gcc_assert (cur_start_idx >= 0);
gcc_assert (cur_finish_idx >= 0);
print_run (pp, cur_start_idx, cur_finish_idx,
&first_run);
cur_start_idx = cur_finish_idx = enode->m_index;
}
}
}
/* Finish any existing run. */
if (cur_start_idx >= 0)
{
gcc_assert (cur_finish_idx >= 0);
print_run (pp, cur_start_idx, cur_finish_idx,
&first_run);
}
}
/* struct eg_traits::dump_args_t. */
/* The <FILENAME>.eg.dot output can quickly become unwieldy if we show
full details for all enodes (both in terms of CPU time to render it,
and in terms of being meaningful to a human viewing it).
If we show just the IDs then the resulting graph is usually viewable,
but then we have to keep switching back and forth between the .dot
view and other dumps.
This function implements a heuristic for showing detail at the enodes
that (we hope) matter, and just the ID at other enodes, fixing the CPU
usage of the .dot viewer, and drawing the attention of the viewer
to these enodes.
Return true if ENODE should be shown in detail in .dot output.
Return false if no detail should be shown for ENODE. */
bool
eg_traits::dump_args_t::show_enode_details_p (const exploded_node &enode) const
{
/* If the number of exploded nodes isn't too large, we may as well show
all enodes in full detail in the .dot output. */
if (m_eg.m_nodes.length ()
<= (unsigned) param_analyzer_max_enodes_for_full_dump)
return true;
/* Otherwise, assume that what's most interesting are state explosions,
and thus the places where this happened.
Expand enodes at program points where we hit the per-enode limit, so we
can investigate what exploded. */
const per_program_point_data *per_point_data
= m_eg.get_per_program_point_data (enode.get_point ());
return per_point_data->m_excess_enodes > 0;
}
/* class exploded_node : public dnode<eg_traits>. */
const char *
exploded_node::status_to_str (enum status s)
{
switch (s)
{
default: gcc_unreachable ();
case STATUS_WORKLIST: return "WORKLIST";
case STATUS_PROCESSED: return "PROCESSED";
case STATUS_MERGER: return "MERGER";
case STATUS_BULK_MERGED: return "BULK_MERGED";
}
}
/* exploded_node's ctor. */
exploded_node::exploded_node (const point_and_state &ps,
int index)
: m_ps (ps), m_status (STATUS_WORKLIST), m_index (index),
m_num_processed_stmts (0)
{
gcc_checking_assert (ps.get_state ().m_region_model->canonicalized_p ());
}
/* Get the stmt that was processed in this enode at index IDX.
IDX is an index within the stmts processed at this enode, rather
than within those of the supernode. */
const gimple *
exploded_node::get_processed_stmt (unsigned idx) const
{
gcc_assert (idx < m_num_processed_stmts);
const program_point &point = get_point ();
gcc_assert (point.get_kind () == PK_BEFORE_STMT);
const supernode *snode = get_supernode ();
const unsigned int point_stmt_idx = point.get_stmt_idx ();
const unsigned int idx_within_snode = point_stmt_idx + idx;
const gimple *stmt = snode->m_stmts[idx_within_snode];
return stmt;
}
/* For use by dump_dot, get a value for the .dot "fillcolor" attribute.
Colorize by sm-state, to make it easier to see how sm-state propagates
through the exploded_graph. */
const char *
exploded_node::get_dot_fillcolor () const
{
const program_state &state = get_state ();
/* We want to be able to easily distinguish the no-sm-state case,
and to be able to distinguish cases where there's a single state
from each other.
Sum the sm_states, and use the result to choose from a table,
modulo table-size, special-casing the "no sm-state" case. */
int total_sm_state = 0;
int i;
sm_state_map *smap;
FOR_EACH_VEC_ELT (state.m_checker_states, i, smap)
{
for (sm_state_map::iterator_t iter = smap->begin ();
iter != smap->end ();
++iter)
total_sm_state += (*iter).second.m_state->get_id ();
total_sm_state += smap->get_global_state ()->get_id ();
}
if (total_sm_state > 0)
{
/* An arbitrarily-picked collection of light colors. */
const char * const colors[]
= {"azure", "coral", "cornsilk", "lightblue", "yellow",
"honeydew", "lightpink", "lightsalmon", "palegreen1",
"wheat", "seashell"};
const int num_colors = ARRAY_SIZE (colors);
return colors[total_sm_state % num_colors];
}
else
/* No sm-state. */
return "lightgrey";
}
/* Implementation of dnode::dump_dot vfunc for exploded_node. */
void
exploded_node::dump_dot (graphviz_out *gv, const dump_args_t &args) const
{
pretty_printer *pp = gv->get_pp ();
dump_dot_id (pp);
pp_printf (pp, " [shape=none,margin=0,style=filled,fillcolor=%s,label=\"",
get_dot_fillcolor ());
pp_write_text_to_stream (pp);
pp_printf (pp, "EN: %i", m_index);
if (m_status == STATUS_MERGER)
pp_string (pp, " (merger)");
else if (m_status == STATUS_BULK_MERGED)
pp_string (pp, " (bulk merged)");
pp_newline (pp);
if (args.show_enode_details_p (*this))
{
format f (true);
m_ps.get_point ().print (pp, f);
pp_newline (pp);
const extrinsic_state &ext_state = args.m_eg.get_ext_state ();
const program_state &state = m_ps.get_state ();
state.dump_to_pp (ext_state, false, true, pp);
pp_newline (pp);
dump_processed_stmts (pp);
}
dump_saved_diagnostics (pp);
args.dump_extra_info (this, pp);
pp_write_text_as_dot_label_to_stream (pp, /*for_record=*/true);
pp_string (pp, "\"];\n\n");
/* It can be hard to locate the saved diagnostics as text within the
enode nodes, so add extra nodes to the graph for each saved_diagnostic,
highlighted in red.
Compare with dump_saved_diagnostics. */
{
unsigned i;
const saved_diagnostic *sd;
FOR_EACH_VEC_ELT (m_saved_diagnostics, i, sd)
{
sd->dump_as_dot_node (pp);
/* Add edge connecting this enode to the saved_diagnostic. */
dump_dot_id (pp);
pp_string (pp, " -> ");
sd->dump_dot_id (pp);
pp_string (pp, " [style=\"dotted\" arrowhead=\"none\"];");
pp_newline (pp);
}
}
pp_flush (pp);
}
/* Show any stmts that were processed within this enode,
and their index within the supernode. */
void
exploded_node::dump_processed_stmts (pretty_printer *pp) const
{
if (m_num_processed_stmts > 0)
{
const program_point &point = get_point ();
gcc_assert (point.get_kind () == PK_BEFORE_STMT);
const supernode *snode = get_supernode ();
const unsigned int point_stmt_idx = point.get_stmt_idx ();
pp_printf (pp, "stmts: %i", m_num_processed_stmts);
pp_newline (pp);
for (unsigned i = 0; i < m_num_processed_stmts; i++)
{
const unsigned int idx_within_snode = point_stmt_idx + i;
const gimple *stmt = snode->m_stmts[idx_within_snode];
pp_printf (pp, " %i: ", idx_within_snode);
pp_gimple_stmt_1 (pp, stmt, 0, (dump_flags_t)0);
pp_newline (pp);
}
}
}
/* Dump any saved_diagnostics at this enode to PP. */
void
exploded_node::dump_saved_diagnostics (pretty_printer *pp) const
{
unsigned i;
const saved_diagnostic *sd;
FOR_EACH_VEC_ELT (m_saved_diagnostics, i, sd)
{
pp_printf (pp, "DIAGNOSTIC: %s (sd: %i)",
sd->m_d->get_kind (), sd->get_index ());
pp_newline (pp);
}
}
/* Dump this to PP in a form suitable for use as an id in .dot output. */
void
exploded_node::dump_dot_id (pretty_printer *pp) const
{
pp_printf (pp, "exploded_node_%i", m_index);
}
/* Dump a multiline representation of this node to PP. */
void
exploded_node::dump_to_pp (pretty_printer *pp,
const extrinsic_state &ext_state) const
{
pp_printf (pp, "EN: %i", m_index);
pp_newline (pp);
format f (true);
m_ps.get_point ().print (pp, f);
pp_newline (pp);
m_ps.get_state ().dump_to_pp (ext_state, false, true, pp);
pp_newline (pp);
}
/* Dump a multiline representation of this node to FILE. */
void
exploded_node::dump (FILE *fp,
const extrinsic_state &ext_state) const
{
pretty_printer pp;
pp_format_decoder (&pp) = default_tree_printer;
pp_show_color (&pp) = pp_show_color (global_dc->printer);
pp.buffer->stream = fp;
dump_to_pp (&pp, ext_state);
pp_flush (&pp);
}
/* Dump a multiline representation of this node to stderr. */
DEBUG_FUNCTION void
exploded_node::dump (const extrinsic_state &ext_state) const
{
dump (stderr, ext_state);
}
/* Return a new json::object of the form
{"point" : object for program_point,
"state" : object for program_state,
"status" : str,
"idx" : int,
"processed_stmts" : int}. */
json::object *
exploded_node::to_json (const extrinsic_state &ext_state) const
{
json::object *enode_obj = new json::object ();
enode_obj->set ("point", get_point ().to_json ());
enode_obj->set ("state", get_state ().to_json (ext_state));
enode_obj->set ("status", new json::string (status_to_str (m_status)));
enode_obj->set ("idx", new json::integer_number (m_index));
enode_obj->set ("processed_stmts",
new json::integer_number (m_num_processed_stmts));
return enode_obj;
}
} // namespace ana
/* Return true if FNDECL has a gimple body. */
// TODO: is there a pre-canned way to do this?
bool
fndecl_has_gimple_body_p (tree fndecl)
{
if (fndecl == NULL_TREE)
return false;
cgraph_node *n = cgraph_node::get (fndecl);
if (!n)
return false;
return n->has_gimple_body_p ();
}
namespace ana {
/* Modify STATE in place, applying the effects of the stmt at this node's
point. */
exploded_node::on_stmt_flags
exploded_node::on_stmt (exploded_graph &eg,
const supernode *snode,
const gimple *stmt,
program_state *state,
uncertainty_t *uncertainty,
bool *out_could_have_done_work,
path_context *path_ctxt)
{
logger *logger = eg.get_logger ();
LOG_SCOPE (logger);
if (logger)
{
logger->start_log_line ();
pp_gimple_stmt_1 (logger->get_printer (), stmt, 0, (dump_flags_t)0);
logger->end_log_line ();
}
/* Update input_location in case of ICE: make it easier to track down which
source construct we're failing to handle. */
input_location = stmt->location;
gcc_assert (state->m_region_model);
/* Preserve the old state. It is used here for looking
up old checker states, for determining state transitions, and
also within impl_region_model_context and impl_sm_context for
going from tree to svalue_id. */
const program_state old_state (*state);
impl_region_model_context ctxt (eg, this,
&old_state, state, uncertainty,
path_ctxt, stmt, nullptr,
out_could_have_done_work);
/* Handle call summaries here. */
if (cgraph_edge *cgedge
= supergraph_call_edge (snode->get_function (), stmt))
if (eg.get_analysis_plan ().use_summary_p (cgedge))
{
function *called_fn = get_ultimate_function_for_cgraph_edge (cgedge);
per_function_data *called_fn_data
= eg.get_per_function_data (called_fn);
if (called_fn_data)
{
gcc_assert (called_fn);
return replay_call_summaries (eg,
snode,
as_a <const gcall *> (stmt),
state,
path_ctxt,
*called_fn,
*called_fn_data,
&ctxt);
}
}
bool unknown_side_effects = false;
bool terminate_path = false;
on_stmt_pre (eg, stmt, state, &terminate_path,
&unknown_side_effects, &ctxt);
if (terminate_path)
return on_stmt_flags::terminate_path ();
int sm_idx;
sm_state_map *smap;
FOR_EACH_VEC_ELT (old_state.m_checker_states, sm_idx, smap)
{
const state_machine &sm = eg.get_ext_state ().get_sm (sm_idx);
const sm_state_map *old_smap
= old_state.m_checker_states[sm_idx];
sm_state_map *new_smap = state->m_checker_states[sm_idx];
impl_sm_context sm_ctxt (eg, sm_idx, sm, this, &old_state, state,
old_smap, new_smap, path_ctxt, NULL,
unknown_side_effects);
/* Allow the state_machine to handle the stmt. */
if (sm.on_stmt (&sm_ctxt, snode, stmt))
unknown_side_effects = false;
}
if (path_ctxt->terminate_path_p ())
return on_stmt_flags::terminate_path ();
on_stmt_post (stmt, state, unknown_side_effects, &ctxt);
return on_stmt_flags ();
}
/* Handle the pre-sm-state part of STMT, modifying STATE in-place.
Write true to *OUT_TERMINATE_PATH if the path should be terminated.
Write true to *OUT_UNKNOWN_SIDE_EFFECTS if the stmt has unknown
side effects. */
void
exploded_node::on_stmt_pre (exploded_graph &eg,
const gimple *stmt,
program_state *state,
bool *out_terminate_path,
bool *out_unknown_side_effects,
region_model_context *ctxt)
{
/* Handle special-case calls that require the full program_state. */
if (const gcall *call = dyn_cast <const gcall *> (stmt))
{
if (is_special_named_call_p (call, "__analyzer_dump", 0))
{
/* Handle the builtin "__analyzer_dump" by dumping state
to stderr. */
state->dump (eg.get_ext_state (), true);
return;
}
else if (is_special_named_call_p (call, "__analyzer_dump_state", 2))
{
state->impl_call_analyzer_dump_state (call, eg.get_ext_state (),
ctxt);
return;
}
else if (is_setjmp_call_p (call))
{
state->m_region_model->on_setjmp (call, this, ctxt);
if (ctxt)
ctxt->maybe_did_work ();
return;
}
else if (is_longjmp_call_p (call))
{
on_longjmp (eg, call, state, ctxt);
*out_terminate_path = true;
if (ctxt)
ctxt->maybe_did_work ();
return;
}
}
/* Otherwise, defer to m_region_model. */
state->m_region_model->on_stmt_pre (stmt,
out_unknown_side_effects,
ctxt);
}
/* Handle the post-sm-state part of STMT, modifying STATE in-place. */
void
exploded_node::on_stmt_post (const gimple *stmt,
program_state *state,
bool unknown_side_effects,
region_model_context *ctxt)
{
if (const gcall *call = dyn_cast <const gcall *> (stmt))
state->m_region_model->on_call_post (call, unknown_side_effects, ctxt);
}
/* A concrete call_info subclass representing a replay of a call summary. */
class call_summary_edge_info : public call_info
{
public:
call_summary_edge_info (const call_details &cd,
const function &called_fn,
call_summary *summary,
const extrinsic_state &ext_state)
: call_info (cd, called_fn),
m_called_fn (called_fn),
m_summary (summary),
m_ext_state (ext_state)
{}
bool update_state (program_state *state,
const exploded_edge *,
region_model_context *ctxt) const final override
{
/* Update STATE based on summary_end_state. */
call_details cd (get_call_details (state->m_region_model, ctxt));
call_summary_replay r (cd, m_called_fn, m_summary, m_ext_state);
const program_state &summary_end_state = m_summary->get_state ();
return state->replay_call_summary (r, summary_end_state);
}
bool update_model (region_model *model,
const exploded_edge *,
region_model_context *ctxt) const final override
{
/* Update STATE based on summary_end_state. */
call_details cd (get_call_details (model, ctxt));
call_summary_replay r (cd, m_called_fn, m_summary, m_ext_state);
const program_state &summary_end_state = m_summary->get_state ();
model->replay_call_summary (r, *summary_end_state.m_region_model);
return true;
}
label_text get_desc (bool /*can_colorize*/) const final override
{
return m_summary->get_desc ();
}
private:
const function &m_called_fn;
call_summary *m_summary;
const extrinsic_state &m_ext_state;
};
/* Use PATH_CTXT to bifurcate, which when handled will add custom edges
for a replay of the various feasible summaries in CALLED_FN_DATA. */
exploded_node::on_stmt_flags
exploded_node::replay_call_summaries (exploded_graph &eg,
const supernode *snode,
const gcall *call_stmt,
program_state *state,
path_context *path_ctxt,
const function &called_fn,
per_function_data &called_fn_data,
region_model_context *ctxt)
{
logger *logger = eg.get_logger ();
LOG_SCOPE (logger);
/* Each summary will call bifurcate on the PATH_CTXT. */
for (auto summary : called_fn_data.m_summaries)
replay_call_summary (eg, snode, call_stmt, state,
path_ctxt, called_fn, summary, ctxt);
path_ctxt->terminate_path ();
return on_stmt_flags ();
}
/* Use PATH_CTXT to bifurcate, which when handled will add a
custom edge for a replay of SUMMARY, if the summary's
conditions are feasible based on the current state. */
void
exploded_node::replay_call_summary (exploded_graph &eg,
const supernode *snode,
const gcall *call_stmt,
program_state *old_state,
path_context *path_ctxt,
const function &called_fn,
call_summary *summary,
region_model_context *ctxt)
{
logger *logger = eg.get_logger ();
LOG_SCOPE (logger);
gcc_assert (snode);
gcc_assert (call_stmt);
gcc_assert (old_state);
gcc_assert (summary);
if (logger)
logger->log ("using %s as summary for call to %qE from %qE",
summary->get_desc ().get (),
called_fn.decl,
snode->get_function ()->decl);
const extrinsic_state &ext_state = eg.get_ext_state ();
const program_state &summary_end_state = summary->get_state ();
if (logger)
{
pretty_printer *pp = logger->get_printer ();
logger->start_log_line ();
pp_string (pp, "callsite state: ");
old_state->dump_to_pp (ext_state, true, false, pp);
logger->end_log_line ();
logger->start_log_line ();
pp_string (pp, "summary end state: ");
summary_end_state.dump_to_pp (ext_state, true, false, pp);
logger->end_log_line ();
}
program_state new_state (*old_state);
call_details cd (call_stmt, new_state.m_region_model, ctxt);
call_summary_replay r (cd, called_fn, summary, ext_state);
if (path_ctxt)
path_ctxt->bifurcate (make_unique<call_summary_edge_info> (cd,
called_fn,
summary,
ext_state));
}
/* Consider the effect of following superedge SUCC from this node.
Return true if it's feasible to follow the edge, or false
if it's infeasible.
Examples: if it's the "true" branch within
a CFG and we know the conditional is false, we know it's infeasible.
If it's one of multiple interprocedual "return" edges, then only
the edge back to the most recent callsite is feasible.
Update NEXT_STATE accordingly (e.g. to record that a condition was
true or false, or that the NULL-ness of a pointer has been checked,
pushing/popping stack frames, etc).
Update NEXT_POINT accordingly (updating the call string). */
bool
exploded_node::on_edge (exploded_graph &eg,
const superedge *succ,
program_point *next_point,
program_state *next_state,
uncertainty_t *uncertainty)
{
LOG_FUNC (eg.get_logger ());
if (!next_point->on_edge (eg, succ))
return false;
if (!next_state->on_edge (eg, this, succ, uncertainty))
return false;
return true;
}
/* Verify that the stack at LONGJMP_POINT is still valid, given a call
to "setjmp" at SETJMP_POINT - the stack frame that "setjmp" was
called in must still be valid.
Caveat: this merely checks the call_strings in the points; it doesn't
detect the case where a frame returns and is then called again. */
static bool
valid_longjmp_stack_p (const program_point &longjmp_point,
const program_point &setjmp_point)
{
const call_string &cs_at_longjmp = longjmp_point.get_call_string ();
const call_string &cs_at_setjmp = setjmp_point.get_call_string ();
if (cs_at_longjmp.length () < cs_at_setjmp.length ())
return false;
/* Check that the call strings match, up to the depth of the
setjmp point. */
for (unsigned depth = 0; depth < cs_at_setjmp.length (); depth++)
if (cs_at_longjmp[depth] != cs_at_setjmp[depth])
return false;
return true;
}
/* A pending_diagnostic subclass for complaining about bad longjmps,
where the enclosing function of the "setjmp" has returned (and thus
the stack frame no longer exists). */
class stale_jmp_buf : public pending_diagnostic_subclass<stale_jmp_buf>
{
public:
stale_jmp_buf (const gcall *setjmp_call, const gcall *longjmp_call,
const program_point &setjmp_point)
: m_setjmp_call (setjmp_call), m_longjmp_call (longjmp_call),
m_setjmp_point (setjmp_point), m_stack_pop_event (NULL)
{}
int get_controlling_option () const final override
{
return OPT_Wanalyzer_stale_setjmp_buffer;
}
bool emit (diagnostic_emission_context &ctxt) final override
{
return ctxt.warn ("%qs called after enclosing function of %qs has returned",
get_user_facing_name (m_longjmp_call),
get_user_facing_name (m_setjmp_call));
}
const char *get_kind () const final override
{ return "stale_jmp_buf"; }
bool operator== (const stale_jmp_buf &other) const
{
return (m_setjmp_call == other.m_setjmp_call
&& m_longjmp_call == other.m_longjmp_call);
}
bool
maybe_add_custom_events_for_superedge (const exploded_edge &eedge,
checker_path *emission_path)
final override
{
/* Detect exactly when the stack first becomes invalid,
and issue an event then. */
if (m_stack_pop_event)
return false;
const exploded_node *src_node = eedge.m_src;
const program_point &src_point = src_node->get_point ();
const exploded_node *dst_node = eedge.m_dest;
const program_point &dst_point = dst_node->get_point ();
if (valid_longjmp_stack_p (src_point, m_setjmp_point)
&& !valid_longjmp_stack_p (dst_point, m_setjmp_point))
{
/* Compare with diagnostic_manager::add_events_for_superedge. */
const int src_stack_depth = src_point.get_stack_depth ();
m_stack_pop_event = new precanned_custom_event
(event_loc_info (src_point.get_location (),
src_point.get_fndecl (),
src_stack_depth),
"stack frame is popped here, invalidating saved environment");
emission_path->add_event
(std::unique_ptr<custom_event> (m_stack_pop_event));
return false;
}
return false;
}
label_text describe_final_event (const evdesc::final_event &ev) final override
{
if (m_stack_pop_event)
return ev.formatted_print
("%qs called after enclosing function of %qs returned at %@",
get_user_facing_name (m_longjmp_call),
get_user_facing_name (m_setjmp_call),
m_stack_pop_event->get_id_ptr ());
else
return ev.formatted_print
("%qs called after enclosing function of %qs has returned",
get_user_facing_name (m_longjmp_call),
get_user_facing_name (m_setjmp_call));;
}
private:
const gcall *m_setjmp_call;
const gcall *m_longjmp_call;
program_point m_setjmp_point;
custom_event *m_stack_pop_event;
};
/* Handle LONGJMP_CALL, a call to longjmp or siglongjmp.
Attempt to locate where setjmp/sigsetjmp was called on the jmp_buf and build
an exploded_node and exploded_edge to it representing a rewind to that frame,
handling the various kinds of failure that can occur. */
void
exploded_node::on_longjmp (exploded_graph &eg,
const gcall *longjmp_call,
program_state *new_state,
region_model_context *ctxt)
{
tree buf_ptr = gimple_call_arg (longjmp_call, 0);
gcc_assert (POINTER_TYPE_P (TREE_TYPE (buf_ptr)));
region_model *new_region_model = new_state->m_region_model;
const svalue *buf_ptr_sval = new_region_model->get_rvalue (buf_ptr, ctxt);
const region *buf = new_region_model->deref_rvalue (buf_ptr_sval, buf_ptr,
ctxt);
const svalue *buf_content_sval
= new_region_model->get_store_value (buf, ctxt);
const setjmp_svalue *setjmp_sval
= buf_content_sval->dyn_cast_setjmp_svalue ();
if (!setjmp_sval)
return;
const setjmp_record tmp_setjmp_record = setjmp_sval->get_setjmp_record ();
/* Build a custom enode and eedge for rewinding from the longjmp/siglongjmp
call back to the setjmp/sigsetjmp. */
rewind_info_t rewind_info (tmp_setjmp_record, longjmp_call);
const gcall *setjmp_call = rewind_info.get_setjmp_call ();
const program_point &setjmp_point = rewind_info.get_setjmp_point ();
const program_point &longjmp_point = get_point ();
/* Verify that the setjmp's call_stack hasn't been popped. */
if (!valid_longjmp_stack_p (longjmp_point, setjmp_point))
{
ctxt->warn (make_unique<stale_jmp_buf> (setjmp_call,
longjmp_call,
setjmp_point));
return;
}
gcc_assert (longjmp_point.get_stack_depth ()
>= setjmp_point.get_stack_depth ());
/* Update the state for use by the destination node. */
/* Stash the current number of diagnostics so that we can update
any that this adds to show where the longjmp is rewinding to. */
diagnostic_manager *dm = &eg.get_diagnostic_manager ();
unsigned prev_num_diagnostics = dm->get_num_diagnostics ();
new_region_model->on_longjmp (longjmp_call, setjmp_call,
setjmp_point.get_stack_depth (), ctxt);
/* Detect leaks in the new state relative to the old state. */
program_state::detect_leaks (get_state (), *new_state, NULL,
eg.get_ext_state (), ctxt);
program_point next_point
= program_point::after_supernode (setjmp_point.get_supernode (),
setjmp_point.get_call_string ());
exploded_node *next
= eg.get_or_create_node (next_point, *new_state, this);
/* Create custom exploded_edge for a longjmp. */
if (next)
{
exploded_edge *eedge
= eg.add_edge (const_cast<exploded_node *> (this), next, NULL, true,
make_unique<rewind_info_t> (tmp_setjmp_record,
longjmp_call));
/* For any diagnostics that were queued here (such as leaks) we want
the checker_path to show the rewinding events after the "final event"
so that the user sees where the longjmp is rewinding to (otherwise the
path is meaningless).
For example, we want to emit something like:
| NN | {
| NN | longjmp (env, 1);
| | ~~~~~~~~~~~~~~~~
| | |
| | (10) 'ptr' leaks here; was allocated at (7)
| | (11) rewinding from 'longjmp' in 'inner'...
|
<-------------+
|
'outer': event 12
|
| NN | i = setjmp(env);
| | ^~~~~~
| | |
| | (12) ...to 'setjmp' in 'outer' (saved at (2))
where the "final" event above is event (10), but we want to append
events (11) and (12) afterwards.
Do this by setting m_trailing_eedge on any diagnostics that were
just saved. */
unsigned num_diagnostics = dm->get_num_diagnostics ();
for (unsigned i = prev_num_diagnostics; i < num_diagnostics; i++)
{
saved_diagnostic *sd = dm->get_saved_diagnostic (i);
sd->m_trailing_eedge = eedge;
}
}
}
/* Subroutine of exploded_graph::process_node for finding the successors
of the supernode for a function exit basic block.
Ensure that pop_frame is called, potentially queuing diagnostics about
leaks. */
void
exploded_node::detect_leaks (exploded_graph &eg)
{
LOG_FUNC_1 (eg.get_logger (), "EN: %i", m_index);
gcc_assert (get_point ().get_supernode ()->return_p ());
/* If we're not a "top-level" function, do nothing; pop_frame
will be called when handling the return superedge. */
if (get_point ().get_stack_depth () > 1)
return;
/* We have a "top-level" function. */
gcc_assert (get_point ().get_stack_depth () == 1);
const program_state &old_state = get_state ();
/* Work with a temporary copy of the state: pop the frame, and see
what leaks (via purge_unused_svalues). */
program_state new_state (old_state);
gcc_assert (new_state.m_region_model);
uncertainty_t uncertainty;
impl_region_model_context ctxt (eg, this,
&old_state, &new_state, &uncertainty, NULL,
get_stmt ());
const svalue *result = NULL;
new_state.m_region_model->pop_frame (NULL, &result, &ctxt);
program_state::detect_leaks (old_state, new_state, result,
eg.get_ext_state (), &ctxt);
}
/* Dump the successors and predecessors of this enode to OUTF. */
void
exploded_node::dump_succs_and_preds (FILE *outf) const
{
unsigned i;
exploded_edge *e;
{
auto_vec<exploded_node *> preds (m_preds.length ());
FOR_EACH_VEC_ELT (m_preds, i, e)
preds.quick_push (e->m_src);
pretty_printer pp;
print_enode_indices (&pp, preds);
fprintf (outf, "preds: %s\n",
pp_formatted_text (&pp));
}
{
auto_vec<exploded_node *> succs (m_succs.length ());
FOR_EACH_VEC_ELT (m_succs, i, e)
succs.quick_push (e->m_dest);
pretty_printer pp;
print_enode_indices (&pp, succs);
fprintf (outf, "succs: %s\n",
pp_formatted_text (&pp));
}
}
/* class dynamic_call_info_t : public custom_edge_info. */
/* Implementation of custom_edge_info::update_model vfunc
for dynamic_call_info_t.
Update state for a dynamically discovered call (or return), by pushing
or popping the a frame for the appropriate function. */
bool
dynamic_call_info_t::update_model (region_model *model,
const exploded_edge *eedge,
region_model_context *ctxt) const
{
gcc_assert (eedge);
if (m_is_returning_call)
model->update_for_return_gcall (m_dynamic_call, ctxt);
else
{
function *callee = eedge->m_dest->get_function ();
model->update_for_gcall (m_dynamic_call, ctxt, callee);
}
return true;
}
/* Implementation of custom_edge_info::add_events_to_path vfunc
for dynamic_call_info_t. */
void
dynamic_call_info_t::add_events_to_path (checker_path *emission_path,
const exploded_edge &eedge) const
{
const exploded_node *src_node = eedge.m_src;
const program_point &src_point = src_node->get_point ();
const int src_stack_depth = src_point.get_stack_depth ();
const exploded_node *dest_node = eedge.m_dest;
const program_point &dest_point = dest_node->get_point ();
const int dest_stack_depth = dest_point.get_stack_depth ();
if (m_is_returning_call)
emission_path->add_event
(make_unique<return_event> (eedge,
event_loc_info (m_dynamic_call
? m_dynamic_call->location
: UNKNOWN_LOCATION,
dest_point.get_fndecl (),
dest_stack_depth)));
else
emission_path->add_event
(make_unique<call_event> (eedge,
event_loc_info (m_dynamic_call
? m_dynamic_call->location
: UNKNOWN_LOCATION,
src_point.get_fndecl (),
src_stack_depth)));
}
/* class rewind_info_t : public custom_edge_info. */
/* Implementation of custom_edge_info::update_model vfunc
for rewind_info_t.
Update state for the special-case of a rewind of a longjmp
to a setjmp (which doesn't have a superedge, but does affect
state). */
bool
rewind_info_t::update_model (region_model *model,
const exploded_edge *eedge,
region_model_context *) const
{
gcc_assert (eedge);
const program_point &longjmp_point = eedge->m_src->get_point ();
const program_point &setjmp_point = eedge->m_dest->get_point ();
gcc_assert (longjmp_point.get_stack_depth ()
>= setjmp_point.get_stack_depth ());
model->on_longjmp (get_longjmp_call (),
get_setjmp_call (),
setjmp_point.get_stack_depth (), NULL);
return true;
}
/* Implementation of custom_edge_info::add_events_to_path vfunc
for rewind_info_t. */
void
rewind_info_t::add_events_to_path (checker_path *emission_path,
const exploded_edge &eedge) const
{
const exploded_node *src_node = eedge.m_src;
const program_point &src_point = src_node->get_point ();
const int src_stack_depth = src_point.get_stack_depth ();
const exploded_node *dst_node = eedge.m_dest;
const program_point &dst_point = dst_node->get_point ();
const int dst_stack_depth = dst_point.get_stack_depth ();
emission_path->add_event
(make_unique<rewind_from_longjmp_event>
(&eedge,
event_loc_info (get_longjmp_call ()->location,
src_point.get_fndecl (),
src_stack_depth),
this));
emission_path->add_event
(make_unique<rewind_to_setjmp_event>
(&eedge,
event_loc_info (get_setjmp_call ()->location,
dst_point.get_fndecl (),
dst_stack_depth),
this));
}
/* class exploded_edge : public dedge<eg_traits>. */
/* exploded_edge's ctor. */
exploded_edge::exploded_edge (exploded_node *src, exploded_node *dest,
const superedge *sedge, bool could_do_work,
std::unique_ptr<custom_edge_info> custom_info)
: dedge<eg_traits> (src, dest), m_sedge (sedge),
m_custom_info (std::move (custom_info)),
m_could_do_work_p (could_do_work)
{
}
/* Implementation of dedge::dump_dot vfunc for exploded_edge.
Use the label of the underlying superedge, if any. */
void
exploded_edge::dump_dot (graphviz_out *gv, const dump_args_t &) const
{
pretty_printer *pp = gv->get_pp ();
m_src->dump_dot_id (pp);
pp_string (pp, " -> ");
m_dest->dump_dot_id (pp);
dump_dot_label (pp);
}
/* Second half of exploded_edge::dump_dot. This is split out
for use by trimmed_graph::dump_dot and base_feasible_edge::dump_dot. */
void
exploded_edge::dump_dot_label (pretty_printer *pp) const
{
const char *style = "\"solid,bold\"";
const char *color = "black";
int weight = 10;
const char *constraint = "true";
if (m_sedge)
switch (m_sedge->m_kind)
{
default:
gcc_unreachable ();
case SUPEREDGE_CFG_EDGE:
break;
case SUPEREDGE_CALL:
color = "red";
//constraint = "false";
break;
case SUPEREDGE_RETURN:
color = "green";
//constraint = "false";
break;
case SUPEREDGE_INTRAPROCEDURAL_CALL:
style = "\"dotted\"";
break;
}
if (m_custom_info)
{
color = "red";
style = "\"dotted\"";
}
pp_printf (pp,
(" [style=%s, color=%s, weight=%d, constraint=%s,"
" headlabel=\""),
style, color, weight, constraint);
if (m_sedge)
m_sedge->dump_label_to_pp (pp, false);
else if (m_custom_info)
m_custom_info->print (pp);
pp_printf (pp, "%s",
could_do_work_p () ? "(could do work)" : "DOES NO WORK");
//pp_write_text_as_dot_label_to_stream (pp, /*for_record=*/false);
pp_printf (pp, "\"];\n");
}
/* Return a new json::object of the form
{"src_idx": int, the index of the source exploded edge,
"dst_idx": int, the index of the destination exploded edge,
"sedge": (optional) object for the superedge, if any,
"custom": (optional) str, a description, if this is a custom edge}. */
json::object *
exploded_edge::to_json () const
{
json::object *eedge_obj = new json::object ();
eedge_obj->set ("src_idx", new json::integer_number (m_src->m_index));
eedge_obj->set ("dst_idx", new json::integer_number (m_dest->m_index));
if (m_sedge)
eedge_obj->set ("sedge", m_sedge->to_json ());
if (m_custom_info)
{
pretty_printer pp;
pp_format_decoder (&pp) = default_tree_printer;
m_custom_info->print (&pp);
eedge_obj->set ("custom", new json::string (pp_formatted_text (&pp)));
}
return eedge_obj;
}
/* struct stats. */
/* stats' ctor. */
stats::stats (int num_supernodes)
: m_node_reuse_count (0),
m_node_reuse_after_merge_count (0),
m_num_supernodes (num_supernodes)
{
for (int i = 0; i < NUM_POINT_KINDS; i++)
m_num_nodes[i] = 0;
}
/* Log these stats in multiline form to LOGGER. */
void
stats::log (logger *logger) const
{
gcc_assert (logger);
for (int i = 0; i < NUM_POINT_KINDS; i++)
if (m_num_nodes[i] > 0)
logger->log ("m_num_nodes[%s]: %i",
point_kind_to_string (static_cast <enum point_kind> (i)),
m_num_nodes[i]);
logger->log ("m_node_reuse_count: %i", m_node_reuse_count);
logger->log ("m_node_reuse_after_merge_count: %i",
m_node_reuse_after_merge_count);
}
/* Dump these stats in multiline form to OUT. */
void
stats::dump (FILE *out) const
{
for (int i = 0; i < NUM_POINT_KINDS; i++)
if (m_num_nodes[i] > 0)
fprintf (out, "m_num_nodes[%s]: %i\n",
point_kind_to_string (static_cast <enum point_kind> (i)),
m_num_nodes[i]);
fprintf (out, "m_node_reuse_count: %i\n", m_node_reuse_count);
fprintf (out, "m_node_reuse_after_merge_count: %i\n",
m_node_reuse_after_merge_count);
if (m_num_supernodes > 0)
fprintf (out, "PK_AFTER_SUPERNODE nodes per supernode: %.2f\n",
(float)m_num_nodes[PK_AFTER_SUPERNODE] / (float)m_num_supernodes);
}
/* Return the total number of enodes recorded within this object. */
int
stats::get_total_enodes () const
{
int result = 0;
for (int i = 0; i < NUM_POINT_KINDS; i++)
result += m_num_nodes[i];
return result;
}
/* struct per_function_data. */
per_function_data::~per_function_data ()
{
for (auto iter : m_summaries)
delete iter;
}
void
per_function_data::add_call_summary (exploded_node *node)
{
m_summaries.safe_push (new call_summary (this, node));
}
/* strongly_connected_components's ctor. Tarjan's SCC algorithm. */
strongly_connected_components::
strongly_connected_components (const supergraph &sg, logger *logger)
: m_sg (sg), m_per_node (m_sg.num_nodes ())
{
LOG_SCOPE (logger);
auto_timevar tv (TV_ANALYZER_SCC);
for (int i = 0; i < m_sg.num_nodes (); i++)
m_per_node.quick_push (per_node_data ());
for (int i = 0; i < m_sg.num_nodes (); i++)
if (m_per_node[i].m_index == -1)
strong_connect (i);
if (0)
dump ();
}
/* Dump this object to stderr. */
DEBUG_FUNCTION void
strongly_connected_components::dump () const
{
for (int i = 0; i < m_sg.num_nodes (); i++)
{
const per_node_data &v = m_per_node[i];
fprintf (stderr, "SN %i: index: %i lowlink: %i on_stack: %i\n",
i, v.m_index, v.m_lowlink, v.m_on_stack);
}
}
/* Return a new json::array of per-snode SCC ids. */
json::array *
strongly_connected_components::to_json () const
{
json::array *scc_arr = new json::array ();
for (int i = 0; i < m_sg.num_nodes (); i++)
scc_arr->append (new json::integer_number (get_scc_id (i)));
return scc_arr;
}
/* Subroutine of strongly_connected_components's ctor, part of Tarjan's
SCC algorithm. */
void
strongly_connected_components::strong_connect (unsigned index)
{
supernode *v_snode = m_sg.get_node_by_index (index);
/* Set the depth index for v to the smallest unused index. */
per_node_data *v = &m_per_node[index];
v->m_index = index;
v->m_lowlink = index;
m_stack.safe_push (index);
v->m_on_stack = true;
index++;
/* Consider successors of v. */
unsigned i;
superedge *sedge;
FOR_EACH_VEC_ELT (v_snode->m_succs, i, sedge)
{
if (sedge->get_kind () != SUPEREDGE_CFG_EDGE
&& sedge->get_kind () != SUPEREDGE_INTRAPROCEDURAL_CALL)
continue;
supernode *w_snode = sedge->m_dest;
per_node_data *w = &m_per_node[w_snode->m_index];
if (w->m_index == -1)
{
/* Successor w has not yet been visited; recurse on it. */
strong_connect (w_snode->m_index);
v->m_lowlink = MIN (v->m_lowlink, w->m_lowlink);
}
else if (w->m_on_stack)
{
/* Successor w is in stack S and hence in the current SCC
If w is not on stack, then (v, w) is a cross-edge in the DFS
tree and must be ignored. */
v->m_lowlink = MIN (v->m_lowlink, w->m_index);
}
}
/* If v is a root node, pop the stack and generate an SCC. */
if (v->m_lowlink == v->m_index)
{
per_node_data *w;
do {
int idx = m_stack.pop ();
w = &m_per_node[idx];
w->m_on_stack = false;
} while (w != v);
}
}
/* worklist's ctor. */
worklist::worklist (const exploded_graph &eg, const analysis_plan &plan)
: m_scc (eg.get_supergraph (), eg.get_logger ()),
m_plan (plan),
m_queue (key_t (*this, NULL))
{
}
/* Return the number of nodes in the worklist. */
unsigned
worklist::length () const
{
return m_queue.nodes ();
}
/* Return the next node in the worklist, removing it. */
exploded_node *
worklist::take_next ()
{
return m_queue.extract_min ();
}
/* Return the next node in the worklist without removing it. */
exploded_node *
worklist::peek_next ()
{
return m_queue.min ();
}
/* Add ENODE to the worklist. */
void
worklist::add_node (exploded_node *enode)
{
gcc_assert (enode->get_status () == exploded_node::STATUS_WORKLIST);
m_queue.insert (key_t (*this, enode), enode);
}
/* Comparator for implementing worklist::key_t comparison operators.
Return negative if KA is before KB
Return positive if KA is after KB
Return 0 if they are equal.
The ordering of the worklist is critical for performance and for
avoiding node explosions. Ideally we want all enodes at a CFG join-point
with the same callstring to be sorted next to each other in the worklist
so that a run of consecutive enodes can be merged and processed "in bulk"
rather than individually or pairwise, minimizing the number of new enodes
created. */
int
worklist::key_t::cmp (const worklist::key_t &ka, const worklist::key_t &kb)
{
const program_point &point_a = ka.m_enode->get_point ();
const program_point &point_b = kb.m_enode->get_point ();
const call_string &call_string_a = point_a.get_call_string ();
const call_string &call_string_b = point_b.get_call_string ();
/* Order empty-callstring points with different functions based on the
analysis_plan, so that we generate summaries before they are used. */
if (flag_analyzer_call_summaries
&& call_string_a.empty_p ()
&& call_string_b.empty_p ()
&& point_a.get_function () != NULL
&& point_b.get_function () != NULL
&& point_a.get_function () != point_b.get_function ())
{
if (int cmp = ka.m_worklist.m_plan.cmp_function (point_a.get_function (),
point_b.get_function ()))
return cmp;
}
/* Sort by callstring, so that nodes with deeper call strings are processed
before those with shallower call strings.
If we have
splitting BB
/ \
/ \
fn call no fn call
\ /
\ /
join BB
then we want the path inside the function call to be fully explored up
to the return to the join BB before we explore on the "no fn call" path,
so that both enodes at the join BB reach the front of the worklist at
the same time and thus have a chance of being merged. */
int cs_cmp = call_string::cmp (call_string_a, call_string_b);
if (cs_cmp)
return cs_cmp;
/* Order by SCC. */
int scc_id_a = ka.get_scc_id (ka.m_enode);
int scc_id_b = kb.get_scc_id (kb.m_enode);
if (scc_id_a != scc_id_b)
return scc_id_a - scc_id_b;
/* If in same SCC, order by supernode index (an arbitrary but stable
ordering). */
const supernode *snode_a = ka.m_enode->get_supernode ();
const supernode *snode_b = kb.m_enode->get_supernode ();
if (snode_a == NULL)
{
if (snode_b != NULL)
/* One is NULL. */
return -1;
else
/* Both are NULL. */
return 0;
}
if (snode_b == NULL)
/* One is NULL. */
return 1;
/* Neither are NULL. */
gcc_assert (snode_a && snode_b);
if (snode_a->m_index != snode_b->m_index)
return snode_a->m_index - snode_b->m_index;
gcc_assert (snode_a == snode_b);
/* Order within supernode via program point. */
int within_snode_cmp
= function_point::cmp_within_supernode (point_a.get_function_point (),
point_b.get_function_point ());
if (within_snode_cmp)
return within_snode_cmp;
/* Otherwise, we ought to have the same program_point. */
gcc_assert (point_a == point_b);
const program_state &state_a = ka.m_enode->get_state ();
const program_state &state_b = kb.m_enode->get_state ();
/* Sort by sm-state, so that identical sm-states are grouped
together in the worklist. */
for (unsigned sm_idx = 0; sm_idx < state_a.m_checker_states.length ();
++sm_idx)
{
sm_state_map *smap_a = state_a.m_checker_states[sm_idx];
sm_state_map *smap_b = state_b.m_checker_states[sm_idx];
if (int smap_cmp = sm_state_map::cmp (*smap_a, *smap_b))
return smap_cmp;
}
/* Otherwise, we have two enodes at the same program point but with
different states. We don't have a good total ordering on states,
so order them by enode index, so that we have at least have a
stable sort. */
return ka.m_enode->m_index - kb.m_enode->m_index;
}
/* Return a new json::object of the form
{"scc" : [per-snode-IDs]}, */
json::object *
worklist::to_json () const
{
json::object *worklist_obj = new json::object ();
worklist_obj->set ("scc", m_scc.to_json ());
/* The following field isn't yet being JSONified:
queue_t m_queue; */
return worklist_obj;
}
/* exploded_graph's ctor. */
exploded_graph::exploded_graph (const supergraph &sg, logger *logger,
const extrinsic_state &ext_state,
const state_purge_map *purge_map,
const analysis_plan &plan,
int verbosity)
: m_sg (sg), m_logger (logger),
m_worklist (*this, plan),
m_ext_state (ext_state),
m_purge_map (purge_map),
m_plan (plan),
m_diagnostic_manager (logger, ext_state.get_engine (), verbosity),
m_global_stats (m_sg.num_nodes ()),
m_functionless_stats (m_sg.num_nodes ()),
m_PK_AFTER_SUPERNODE_per_snode (m_sg.num_nodes ())
{
m_origin = get_or_create_node
(program_point::origin (*ext_state.get_model_manager ()),
program_state (ext_state), NULL);
for (int i = 0; i < m_sg.num_nodes (); i++)
m_PK_AFTER_SUPERNODE_per_snode.quick_push (i);
}
/* exploded_graph's dtor. */
exploded_graph::~exploded_graph ()
{
for (auto iter : m_per_point_data)
delete iter.second;
for (auto iter : m_per_function_data)
delete iter.second;
for (auto iter : m_per_function_stats)
delete iter.second;
for (auto iter : m_per_call_string_data)
delete iter.second;
}
/* Subroutine for use when implementing __attribute__((tainted_args))
on functions and on function pointer fields in structs.
Called on STATE representing a call to FNDECL.
Mark all params of FNDECL in STATE as "tainted". Mark the value of all
regions pointed to by params of FNDECL as "tainted".
Return true if successful; return false if the "taint" state machine
was not found. */
static bool
mark_params_as_tainted (program_state *state, tree fndecl,
const extrinsic_state &ext_state)
{
unsigned taint_sm_idx;
if (!ext_state.get_sm_idx_by_name ("taint", &taint_sm_idx))
return false;
sm_state_map *smap = state->m_checker_states[taint_sm_idx];
const state_machine &sm = ext_state.get_sm (taint_sm_idx);
state_machine::state_t tainted = sm.get_state_by_name ("tainted");
region_model_manager *mgr = ext_state.get_model_manager ();
function *fun = DECL_STRUCT_FUNCTION (fndecl);
gcc_assert (fun);
for (tree iter_parm = DECL_ARGUMENTS (fndecl); iter_parm;
iter_parm = DECL_CHAIN (iter_parm))
{
tree param = iter_parm;
if (tree parm_default_ssa = ssa_default_def (fun, iter_parm))
param = parm_default_ssa;
const region *param_reg = state->m_region_model->get_lvalue (param, NULL);
const svalue *init_sval = mgr->get_or_create_initial_value (param_reg);
smap->set_state (state->m_region_model, init_sval,
tainted, NULL /*origin_new_sval*/, ext_state);
if (POINTER_TYPE_P (TREE_TYPE (param)))
{
const region *pointee_reg = mgr->get_symbolic_region (init_sval);
/* Mark "*param" as tainted. */
const svalue *init_pointee_sval
= mgr->get_or_create_initial_value (pointee_reg);
smap->set_state (state->m_region_model, init_pointee_sval,
tainted, NULL /*origin_new_sval*/, ext_state);
}
}
return true;
}
/* Custom event for use by tainted_args_function_info when a function
has been marked with __attribute__((tainted_args)). */
class tainted_args_function_custom_event : public custom_event
{
public:
tainted_args_function_custom_event (const event_loc_info &loc_info)
: custom_event (loc_info),
m_fndecl (loc_info.m_fndecl)
{
}
label_text get_desc (bool can_colorize) const final override
{
return make_label_text
(can_colorize,
"function %qE marked with %<__attribute__((tainted_args))%>",
m_fndecl);
}
private:
tree m_fndecl;
};
/* Custom exploded_edge info for top-level calls to a function
marked with __attribute__((tainted_args)). */
class tainted_args_function_info : public custom_edge_info
{
public:
tainted_args_function_info (tree fndecl)
: m_fndecl (fndecl)
{}
void print (pretty_printer *pp) const final override
{
pp_string (pp, "call to tainted_args function");
};
bool update_model (region_model *,
const exploded_edge *,
region_model_context *) const final override
{
/* No-op. */
return true;
}
void add_events_to_path (checker_path *emission_path,
const exploded_edge &) const final override
{
emission_path->add_event
(make_unique<tainted_args_function_custom_event>
(event_loc_info (DECL_SOURCE_LOCATION (m_fndecl), m_fndecl, 0)));
}
private:
tree m_fndecl;
};
/* Ensure that there is an exploded_node representing an external call to
FUN, adding it to the worklist if creating it.
Add an edge from the origin exploded_node to the function entrypoint
exploded_node.
Return the exploded_node for the entrypoint to the function. */
exploded_node *
exploded_graph::add_function_entry (const function &fun)
{
gcc_assert (gimple_has_body_p (fun.decl));
/* Be idempotent. */
function *key = const_cast<function *> (&fun);
if (m_functions_with_enodes.contains (key))
{
logger * const logger = get_logger ();
if (logger)
logger->log ("entrypoint for %qE already exists", fun.decl);
return NULL;
}
program_point point
= program_point::from_function_entry (*m_ext_state.get_model_manager (),
m_sg, fun);
program_state state (m_ext_state);
state.push_frame (m_ext_state, fun);
std::unique_ptr<custom_edge_info> edge_info = NULL;
if (lookup_attribute ("tainted_args", DECL_ATTRIBUTES (fun.decl)))
{
if (mark_params_as_tainted (&state, fun.decl, m_ext_state))
edge_info = make_unique<tainted_args_function_info> (fun.decl);
}
if (!state.m_valid)
return NULL;
exploded_node *enode = get_or_create_node (point, state, NULL);
if (!enode)
return NULL;
add_edge (m_origin, enode, NULL, false, std::move (edge_info));
m_functions_with_enodes.add (key);
return enode;
}
/* Get or create an exploded_node for (POINT, STATE).
If a new node is created, it is added to the worklist.
Use ENODE_FOR_DIAG, a pre-existing enode, for any diagnostics
that need to be emitted (e.g. when purging state *before* we have
a new enode). */
exploded_node *
exploded_graph::get_or_create_node (const program_point &point,
const program_state &state,
exploded_node *enode_for_diag)
{
logger * const logger = get_logger ();
LOG_FUNC (logger);
if (logger)
{
format f (false);
pretty_printer *pp = logger->get_printer ();
logger->start_log_line ();
pp_string (pp, "point: ");
point.print (pp, f);
logger->end_log_line ();
logger->start_log_line ();
pp_string (pp, "state: ");
state.dump_to_pp (m_ext_state, true, false, pp);
logger->end_log_line ();
}
/* Stop exploring paths for which we don't know how to effectively
model the state. */
if (!state.m_valid)
{
if (logger)
logger->log ("invalid state; not creating node");
return NULL;
}
auto_cfun sentinel (point.get_function ());
state.validate (get_ext_state ());
//state.dump (get_ext_state ());
/* Prune state to try to improve the chances of a cache hit,
avoiding generating redundant nodes. */
uncertainty_t uncertainty;
program_state pruned_state
= state.prune_for_point (*this, point, enode_for_diag, &uncertainty);
pruned_state.validate (get_ext_state ());
//pruned_state.dump (get_ext_state ());
if (logger)
{
pretty_printer *pp = logger->get_printer ();
logger->start_log_line ();
pp_string (pp, "pruned_state: ");
pruned_state.dump_to_pp (m_ext_state, true, false, pp);
logger->end_log_line ();
pruned_state.m_region_model->dump_to_pp (logger->get_printer (), true,
false);
}
stats *per_fn_stats = get_or_create_function_stats (point.get_function ());
stats *per_cs_stats
= &get_or_create_per_call_string_data (point.get_call_string ())->m_stats;
point_and_state ps (point, pruned_state);
ps.validate (m_ext_state);
if (exploded_node **slot = m_point_and_state_to_node.get (&ps))
{
/* An exploded_node for PS already exists. */
if (logger)
logger->log ("reused EN: %i", (*slot)->m_index);
m_global_stats.m_node_reuse_count++;
per_fn_stats->m_node_reuse_count++;
per_cs_stats->m_node_reuse_count++;
return *slot;
}
per_program_point_data *per_point_data
= get_or_create_per_program_point_data (point);
/* Consider merging state with another enode at this program_point. */
if (flag_analyzer_state_merge)
{
exploded_node *existing_enode;
unsigned i;
FOR_EACH_VEC_ELT (per_point_data->m_enodes, i, existing_enode)
{
if (logger)
logger->log ("considering merging with existing EN: %i for point",
existing_enode->m_index);
gcc_assert (existing_enode->get_point () == point);
const program_state &existing_state = existing_enode->get_state ();
/* This merges successfully within the loop. */
program_state merged_state (m_ext_state);
if (pruned_state.can_merge_with_p (existing_state, m_ext_state, point,
&merged_state))
{
merged_state.validate (m_ext_state);
if (logger)
logger->log ("merging new state with that of EN: %i",
existing_enode->m_index);
/* Try again for a cache hit.
Whether we get one or not, merged_state's value_ids have no
relationship to those of the input state, and thus to those
of CHANGE, so we must purge any svalue_ids from *CHANGE. */
ps.set_state (merged_state);
if (exploded_node **slot = m_point_and_state_to_node.get (&ps))
{
/* An exploded_node for PS already exists. */
if (logger)
logger->log ("reused EN: %i", (*slot)->m_index);
m_global_stats.m_node_reuse_after_merge_count++;
per_fn_stats->m_node_reuse_after_merge_count++;
per_cs_stats->m_node_reuse_after_merge_count++;
return *slot;
}
}
else
if (logger)
logger->log ("not merging new state with that of EN: %i",
existing_enode->m_index);
}
}
/* Impose a limit on the number of enodes per program point, and
simply stop if we exceed it. */
if ((int)per_point_data->m_enodes.length ()
>= param_analyzer_max_enodes_per_program_point)
{
pretty_printer pp;
point.print (&pp, format (false));
print_enode_indices (&pp, per_point_data->m_enodes);
if (logger)
logger->log ("not creating enode; too many at program point: %s",
pp_formatted_text (&pp));
warning_at (point.get_location (), OPT_Wanalyzer_too_complex,
"terminating analysis for this program point: %s",
pp_formatted_text (&pp));
per_point_data->m_excess_enodes++;
return NULL;
}
ps.validate (m_ext_state);
/* An exploded_node for "ps" doesn't already exist; create one. */
exploded_node *node = new exploded_node (ps, m_nodes.length ());
add_node (node);
m_point_and_state_to_node.put (node->get_ps_key (), node);
/* Update per-program_point data. */
per_point_data->m_enodes.safe_push (node);
const enum point_kind node_pk = node->get_point ().get_kind ();
m_global_stats.m_num_nodes[node_pk]++;
per_fn_stats->m_num_nodes[node_pk]++;
per_cs_stats->m_num_nodes[node_pk]++;
if (node_pk == PK_AFTER_SUPERNODE)
m_PK_AFTER_SUPERNODE_per_snode[point.get_supernode ()->m_index]++;
if (logger)
{
format f (false);
pretty_printer *pp = logger->get_printer ();
logger->log ("created EN: %i", node->m_index);
logger->start_log_line ();
pp_string (pp, "point: ");
point.print (pp, f);
logger->end_log_line ();
logger->start_log_line ();
pp_string (pp, "pruned_state: ");
pruned_state.dump_to_pp (m_ext_state, true, false, pp);
logger->end_log_line ();
}
/* Add the new node to the worlist. */
m_worklist.add_node (node);
return node;
}
/* Add an exploded_edge from SRC to DEST, recording its association
with SEDGE (which may be NULL), and, if non-NULL, taking ownership
of CUSTOM_INFO. COULD_DO_WORK is used for detecting infinite loops.
Return the newly-created eedge. */
exploded_edge *
exploded_graph::add_edge (exploded_node *src, exploded_node *dest,
const superedge *sedge, bool could_do_work,
std::unique_ptr<custom_edge_info> custom_info)
{
if (get_logger ())
get_logger ()->log ("creating edge EN: %i -> EN: %i",
src->m_index, dest->m_index);
exploded_edge *e
= new exploded_edge (src, dest, sedge, could_do_work,
std::move (custom_info));
digraph<eg_traits>::add_edge (e);
return e;
}
/* Ensure that this graph has per-program_point-data for POINT;
borrow a pointer to it. */
per_program_point_data *
exploded_graph::
get_or_create_per_program_point_data (const program_point &point)
{
if (per_program_point_data **slot = m_per_point_data.get (&point))
return *slot;
per_program_point_data *per_point_data = new per_program_point_data (point);
m_per_point_data.put (&per_point_data->m_key, per_point_data);
return per_point_data;
}
/* Get this graph's per-program-point-data for POINT if there is any,
otherwise NULL. */
per_program_point_data *
exploded_graph::get_per_program_point_data (const program_point &point) const
{
if (per_program_point_data **slot
= const_cast <point_map_t &> (m_per_point_data).get (&point))
return *slot;
return NULL;
}
/* Ensure that this graph has per-call_string-data for CS;
borrow a pointer to it. */
per_call_string_data *
exploded_graph::get_or_create_per_call_string_data (const call_string &cs)
{
if (per_call_string_data **slot = m_per_call_string_data.get (&cs))
return *slot;
per_call_string_data *data = new per_call_string_data (cs, m_sg.num_nodes ());
m_per_call_string_data.put (&data->m_key,
data);
return data;
}
/* Ensure that this graph has per-function-data for FUN;
borrow a pointer to it. */
per_function_data *
exploded_graph::get_or_create_per_function_data (function *fun)
{
if (per_function_data **slot = m_per_function_data.get (fun))
return *slot;
per_function_data *data = new per_function_data ();
m_per_function_data.put (fun, data);
return data;
}
/* Get this graph's per-function-data for FUN if there is any,
otherwise NULL. */
per_function_data *
exploded_graph::get_per_function_data (function *fun) const
{
if (per_function_data **slot
= const_cast <per_function_data_t &> (m_per_function_data).get (fun))
return *slot;
return NULL;
}
/* Return true if FUN should be traversed directly, rather than only as
called via other functions. */
static bool
toplevel_function_p (const function &fun, logger *logger)
{
/* Don't directly traverse into functions that have an "__analyzer_"
prefix. Doing so is useful for the analyzer test suite, allowing
us to have functions that are called in traversals, but not directly
explored, thus testing how the analyzer handles calls and returns.
With this, we can have DejaGnu directives that cover just the case
of where a function is called by another function, without generating
excess messages from the case of the first function being traversed
directly. */
#define ANALYZER_PREFIX "__analyzer_"
if (!strncmp (IDENTIFIER_POINTER (DECL_NAME (fun.decl)), ANALYZER_PREFIX,
strlen (ANALYZER_PREFIX)))
{
if (logger)
logger->log ("not traversing %qE (starts with %qs)",
fun.decl, ANALYZER_PREFIX);
return false;
}
if (logger)
logger->log ("traversing %qE (all checks passed)", fun.decl);
return true;
}
/* Custom event for use by tainted_call_info when a callback field has been
marked with __attribute__((tainted_args)), for labelling the field. */
class tainted_args_field_custom_event : public custom_event
{
public:
tainted_args_field_custom_event (tree field)
: custom_event (event_loc_info (DECL_SOURCE_LOCATION (field), NULL_TREE, 0)),
m_field (field)
{
}
label_text get_desc (bool can_colorize) const final override
{
return make_label_text (can_colorize,
"field %qE of %qT"
" is marked with %<__attribute__((tainted_args))%>",
m_field, DECL_CONTEXT (m_field));
}
private:
tree m_field;
};
/* Custom event for use by tainted_call_info when a callback field has been
marked with __attribute__((tainted_args)), for labelling the function used
in that callback. */
class tainted_args_callback_custom_event : public custom_event
{
public:
tainted_args_callback_custom_event (const event_loc_info &loc_info,
tree field)
: custom_event (loc_info),
m_field (field)
{
}
label_text get_desc (bool can_colorize) const final override
{
return make_label_text (can_colorize,
"function %qE used as initializer for field %qE"
" marked with %<__attribute__((tainted_args))%>",
get_fndecl (), m_field);
}
private:
tree m_field;
};
/* Custom edge info for use when adding a function used by a callback field
marked with '__attribute__((tainted_args))'. */
class tainted_args_call_info : public custom_edge_info
{
public:
tainted_args_call_info (tree field, tree fndecl, location_t loc)
: m_field (field), m_fndecl (fndecl), m_loc (loc)
{}
void print (pretty_printer *pp) const final override
{
pp_string (pp, "call to tainted field");
};
bool update_model (region_model *,
const exploded_edge *,
region_model_context *) const final override
{
/* No-op. */
return true;
}
void add_events_to_path (checker_path *emission_path,
const exploded_edge &) const final override
{
/* Show the field in the struct declaration, e.g.
"(1) field 'store' is marked with '__attribute__((tainted_args))'" */
emission_path->add_event
(make_unique<tainted_args_field_custom_event> (m_field));
/* Show the callback in the initializer
e.g.
"(2) function 'gadget_dev_desc_UDC_store' used as initializer
for field 'store' marked with '__attribute__((tainted_args))'". */
emission_path->add_event
(make_unique<tainted_args_callback_custom_event>
(event_loc_info (m_loc, m_fndecl, 0),
m_field));
}
private:
tree m_field;
tree m_fndecl;
location_t m_loc;
};
/* Given an initializer at LOC for FIELD marked with
'__attribute__((tainted_args))' initialized with FNDECL, add an
entrypoint to FNDECL to EG (and to its worklist) where the params to
FNDECL are marked as tainted. */
static void
add_tainted_args_callback (exploded_graph *eg, tree field, tree fndecl,
location_t loc)
{
logger *logger = eg->get_logger ();
LOG_SCOPE (logger);
if (!gimple_has_body_p (fndecl))
return;
const extrinsic_state &ext_state = eg->get_ext_state ();
function *fun = DECL_STRUCT_FUNCTION (fndecl);
gcc_assert (fun);
program_point point
= program_point::from_function_entry (*ext_state.get_model_manager (),
eg->get_supergraph (), *fun);
program_state state (ext_state);
state.push_frame (ext_state, *fun);
if (!mark_params_as_tainted (&state, fndecl, ext_state))
return;
if (!state.m_valid)
return;
exploded_node *enode = eg->get_or_create_node (point, state, NULL);
if (logger)
{
if (enode)
logger->log ("created EN %i for tainted_args %qE entrypoint",
enode->m_index, fndecl);
else
{
logger->log ("did not create enode for tainted_args %qE entrypoint",
fndecl);
return;
}
}
eg->add_edge (eg->get_origin (), enode, NULL, false,
make_unique<tainted_args_call_info> (field, fndecl, loc));
}
/* Callback for walk_tree for finding callbacks within initializers;
ensure that any callback initializer where the corresponding field is
marked with '__attribute__((tainted_args))' is treated as an entrypoint
to the analysis, special-casing that the inputs to the callback are
untrustworthy. */
static tree
add_any_callbacks (tree *tp, int *, void *data)
{
exploded_graph *eg = (exploded_graph *)data;
if (TREE_CODE (*tp) == CONSTRUCTOR)
{
/* Find fields with the "tainted_args" attribute.
walk_tree only walks the values, not the index values;
look at the index values. */
unsigned HOST_WIDE_INT idx;
constructor_elt *ce;
for (idx = 0; vec_safe_iterate (CONSTRUCTOR_ELTS (*tp), idx, &ce);
idx++)
if (ce->index && TREE_CODE (ce->index) == FIELD_DECL)
if (lookup_attribute ("tainted_args", DECL_ATTRIBUTES (ce->index)))
{
tree value = ce->value;
if (TREE_CODE (value) == ADDR_EXPR
&& TREE_CODE (TREE_OPERAND (value, 0)) == FUNCTION_DECL)
add_tainted_args_callback (eg, ce->index,
TREE_OPERAND (value, 0),
EXPR_LOCATION (value));
}
}
return NULL_TREE;
}
/* Add initial nodes to EG, with entrypoints for externally-callable
functions. */
void
exploded_graph::build_initial_worklist ()
{
logger * const logger = get_logger ();
LOG_SCOPE (logger);
cgraph_node *node;
FOR_EACH_FUNCTION_WITH_GIMPLE_BODY (node)
{
function *fun = node->get_fun ();
gcc_assert (fun);
if (!toplevel_function_p (*fun, logger))
continue;
exploded_node *enode = add_function_entry (*fun);
if (logger)
{
if (enode)
logger->log ("created EN %i for %qE entrypoint",
enode->m_index, fun->decl);
else
logger->log ("did not create enode for %qE entrypoint", fun->decl);
}
}
/* Find callbacks that are reachable from global initializers. */
varpool_node *vpnode;
FOR_EACH_VARIABLE (vpnode)
{
tree decl = vpnode->decl;
tree init = DECL_INITIAL (decl);
if (!init)
continue;
walk_tree (&init, add_any_callbacks, this, NULL);
}
}
/* The main loop of the analysis.
Take freshly-created exploded_nodes from the worklist, calling
process_node on them to explore the <point, state> graph.
Add edges to their successors, potentially creating new successors
(which are also added to the worklist). */
void
exploded_graph::process_worklist ()
{
logger * const logger = get_logger ();
LOG_SCOPE (logger);
auto_timevar tv (TV_ANALYZER_WORKLIST);
while (m_worklist.length () > 0)
{
exploded_node *node = m_worklist.take_next ();
gcc_assert (node->get_status () == exploded_node::STATUS_WORKLIST);
gcc_assert (node->m_succs.length () == 0
|| node == m_origin);
if (logger)
logger->log ("next to process: EN: %i", node->m_index);
/* If we have a run of nodes that are before-supernode, try merging and
processing them together, rather than pairwise or individually. */
if (flag_analyzer_state_merge && node != m_origin)
if (maybe_process_run_of_before_supernode_enodes (node))
goto handle_limit;
/* Avoid exponential explosions of nodes by attempting to merge
nodes that are at the same program point and which have
sufficiently similar state. */
if (flag_analyzer_state_merge && node != m_origin)
if (exploded_node *node_2 = m_worklist.peek_next ())
{
gcc_assert (node_2->get_status ()
== exploded_node::STATUS_WORKLIST);
gcc_assert (node->m_succs.length () == 0);
gcc_assert (node_2->m_succs.length () == 0);
gcc_assert (node != node_2);
if (logger)
logger->log ("peek worklist: EN: %i", node_2->m_index);
if (node->get_point () == node_2->get_point ())
{
const program_point &point = node->get_point ();
if (logger)
{
format f (false);
pretty_printer *pp = logger->get_printer ();
logger->start_log_line ();
logger->log_partial
("got potential merge EN: %i and EN: %i at ",
node->m_index, node_2->m_index);
point.print (pp, f);
logger->end_log_line ();
}
const program_state &state = node->get_state ();
const program_state &state_2 = node_2->get_state ();
/* They shouldn't be equal, or we wouldn't have two
separate nodes. */
gcc_assert (state != state_2);
program_state merged_state (m_ext_state);
if (state.can_merge_with_p (state_2, m_ext_state,
point, &merged_state))
{
if (logger)
logger->log ("merging EN: %i and EN: %i",
node->m_index, node_2->m_index);
if (merged_state == state)
{
/* Then merge node_2 into node by adding an edge. */
add_edge (node_2, node, NULL, false);
/* Remove node_2 from the worklist. */
m_worklist.take_next ();
node_2->set_status (exploded_node::STATUS_MERGER);
/* Continue processing "node" below. */
}
else if (merged_state == state_2)
{
/* Then merge node into node_2, and leave node_2
in the worklist, to be processed on the next
iteration. */
add_edge (node, node_2, NULL, false);
node->set_status (exploded_node::STATUS_MERGER);
continue;
}
else
{
/* We have a merged state that differs from
both state and state_2. */
/* Remove node_2 from the worklist. */
m_worklist.take_next ();
/* Create (or get) an exploded node for the merged
states, adding to the worklist. */
exploded_node *merged_enode
= get_or_create_node (node->get_point (),
merged_state, node);
if (merged_enode == NULL)
continue;
if (logger)
logger->log ("merged EN: %i and EN: %i into EN: %i",
node->m_index, node_2->m_index,
merged_enode->m_index);
/* "node" and "node_2" have both now been removed
from the worklist; we should not process them.
"merged_enode" may be a new node; if so it will be
processed in a subsequent iteration.
Alternatively, "merged_enode" could be an existing
node; one way the latter can
happen is if we end up merging a succession of
similar nodes into one. */
/* If merged_node is one of the two we were merging,
add it back to the worklist to ensure it gets
processed.
Add edges from the merged nodes to it (but not a
self-edge). */
if (merged_enode == node)
m_worklist.add_node (merged_enode);
else
{
add_edge (node, merged_enode, NULL, false);
node->set_status (exploded_node::STATUS_MERGER);
}
if (merged_enode == node_2)
m_worklist.add_node (merged_enode);
else
{
add_edge (node_2, merged_enode, NULL, false);
node_2->set_status (exploded_node::STATUS_MERGER);
}
continue;
}
}
/* TODO: should we attempt more than two nodes,
or just do pairs of nodes? (and hope that we get
a cascade of mergers). */
}
}
process_node (node);
handle_limit:
/* Impose a hard limit on the number of exploded nodes, to ensure
that the analysis terminates in the face of pathological state
explosion (or bugs).
Specifically, the limit is on the number of PK_AFTER_SUPERNODE
exploded nodes, looking at supernode exit events.
We use exit rather than entry since there can be multiple
entry ENs, one per phi; the number of PK_AFTER_SUPERNODE ought
to be equivalent to the number of supernodes multiplied by the
number of states. */
const int limit = m_sg.num_nodes () * param_analyzer_bb_explosion_factor;
if (m_global_stats.m_num_nodes[PK_AFTER_SUPERNODE] > limit)
{
if (logger)
logger->log ("bailing out; too many nodes");
warning_at (node->get_point ().get_location (),
OPT_Wanalyzer_too_complex,
"analysis bailed out early"
" (%i 'after-snode' enodes; %i enodes)",
m_global_stats.m_num_nodes[PK_AFTER_SUPERNODE],
m_nodes.length ());
return;
}
}
}
/* Attempt to process a consecutive run of sufficiently-similar nodes in
the worklist at a CFG join-point (having already popped ENODE from the
head of the worklist).
If ENODE's point is of the form (before-supernode, SNODE) and the next
nodes in the worklist are a consecutive run of enodes of the same form,
for the same supernode as ENODE (but potentially from different in-edges),
process them all together, setting their status to STATUS_BULK_MERGED,
and return true.
Otherwise, return false, in which case ENODE must be processed in the
normal way.
When processing them all together, generate successor states based
on phi nodes for the appropriate CFG edges, and then attempt to merge
these states into a minimal set of merged successor states, partitioning
the inputs by merged successor state.
Create new exploded nodes for all of the merged states, and add edges
connecting the input enodes to the corresponding merger exploded nodes.
We hope we have a much smaller number of merged successor states
compared to the number of input enodes - ideally just one,
if all successor states can be merged.
Processing and merging many together as one operation rather than as
pairs avoids scaling issues where per-pair mergers could bloat the
graph with merger nodes (especially so after switch statements). */
bool
exploded_graph::
maybe_process_run_of_before_supernode_enodes (exploded_node *enode)
{
/* A struct for tracking per-input state. */
struct item
{
item (exploded_node *input_enode)
: m_input_enode (input_enode),
m_processed_state (input_enode->get_state ()),
m_merger_idx (-1)
{}
exploded_node *m_input_enode;
program_state m_processed_state;
int m_merger_idx;
};
gcc_assert (enode->get_status () == exploded_node::STATUS_WORKLIST);
gcc_assert (enode->m_succs.length () == 0);
const program_point &point = enode->get_point ();
if (point.get_kind () != PK_BEFORE_SUPERNODE)
return false;
const supernode *snode = point.get_supernode ();
logger * const logger = get_logger ();
LOG_SCOPE (logger);
/* Find a run of enodes in the worklist that are before the same supernode,
but potentially from different in-edges. */
auto_vec <exploded_node *> enodes;
enodes.safe_push (enode);
while (exploded_node *enode_2 = m_worklist.peek_next ())
{
gcc_assert (enode_2->get_status ()
== exploded_node::STATUS_WORKLIST);
gcc_assert (enode_2->m_succs.length () == 0);
const program_point &point_2 = enode_2->get_point ();
if (point_2.get_kind () == PK_BEFORE_SUPERNODE
&& point_2.get_supernode () == snode
&& &point_2.get_call_string () == &point.get_call_string ())
{
enodes.safe_push (enode_2);
m_worklist.take_next ();
}
else
break;
}
/* If the only node is ENODE, then give up. */
if (enodes.length () == 1)
return false;
if (logger)
logger->log ("got run of %i enodes for SN: %i",
enodes.length (), snode->m_index);
/* All of these enodes have a shared successor point (even if they
were for different in-edges). */
program_point next_point (point.get_next ());
/* Calculate the successor state for each enode in enodes. */
auto_delete_vec<item> items (enodes.length ());
unsigned i;
exploded_node *iter_enode;
FOR_EACH_VEC_ELT (enodes, i, iter_enode)
{
item *it = new item (iter_enode);
items.quick_push (it);
const program_state &state = iter_enode->get_state ();
program_state *next_state = &it->m_processed_state;
next_state->validate (m_ext_state);
const program_point &iter_point = iter_enode->get_point ();
if (const superedge *iter_sedge = iter_point.get_from_edge ())
{
uncertainty_t uncertainty;
impl_region_model_context ctxt (*this, iter_enode,
&state, next_state,
&uncertainty, NULL, NULL);
const cfg_superedge *last_cfg_superedge
= iter_sedge->dyn_cast_cfg_superedge ();
if (last_cfg_superedge)
next_state->m_region_model->update_for_phis
(snode, last_cfg_superedge, &ctxt);
}
next_state->validate (m_ext_state);
}
/* Attempt to partition the items into a set of merged states.
We hope we have a much smaller number of merged states
compared to the number of input enodes - ideally just one,
if all can be merged. */
auto_delete_vec <program_state> merged_states;
auto_vec<item *> first_item_for_each_merged_state;
item *it;
FOR_EACH_VEC_ELT (items, i, it)
{
const program_state &it_state = it->m_processed_state;
program_state *merged_state;
unsigned iter_merger_idx;
FOR_EACH_VEC_ELT (merged_states, iter_merger_idx, merged_state)
{
merged_state->validate (m_ext_state);
program_state merge (m_ext_state);
if (it_state.can_merge_with_p (*merged_state, m_ext_state,
next_point, &merge))
{
*merged_state = merge;
merged_state->validate (m_ext_state);
it->m_merger_idx = iter_merger_idx;
if (logger)
logger->log ("reusing merger state %i for item %i (EN: %i)",
it->m_merger_idx, i, it->m_input_enode->m_index);
goto got_merger;
}
}
/* If it couldn't be merged with any existing merged_states,
create a new one. */
if (it->m_merger_idx == -1)
{
it->m_merger_idx = merged_states.length ();
merged_states.safe_push (new program_state (it_state));
first_item_for_each_merged_state.safe_push (it);
if (logger)
logger->log ("using new merger state %i for item %i (EN: %i)",
it->m_merger_idx, i, it->m_input_enode->m_index);
}
got_merger:
gcc_assert (it->m_merger_idx >= 0);
gcc_assert ((unsigned)it->m_merger_idx < merged_states.length ());
}
/* Create merger nodes. */
auto_vec<exploded_node *> next_enodes (merged_states.length ());
program_state *merged_state;
FOR_EACH_VEC_ELT (merged_states, i, merged_state)
{
exploded_node *src_enode
= first_item_for_each_merged_state[i]->m_input_enode;
exploded_node *next
= get_or_create_node (next_point, *merged_state, src_enode);
/* "next" could be NULL; we handle that when adding the edges below. */
next_enodes.quick_push (next);
if (logger)
{
if (next)
logger->log ("using EN: %i for merger state %i", next->m_index, i);
else
logger->log ("using NULL enode for merger state %i", i);
}
}
/* Create edges from each input enode to the appropriate successor enode.
Update the status of the now-processed input enodes. */
FOR_EACH_VEC_ELT (items, i, it)
{
exploded_node *next = next_enodes[it->m_merger_idx];
if (next)
add_edge (it->m_input_enode, next, NULL,
false); /* no "work" is done during merger. */
it->m_input_enode->set_status (exploded_node::STATUS_BULK_MERGED);
}
if (logger)
logger->log ("merged %i in-enodes into %i out-enode(s) at SN: %i",
items.length (), merged_states.length (), snode->m_index);
return true;
}
/* Return true if STMT must appear at the start of its exploded node, and
thus we can't consolidate its effects within a run of other statements,
where PREV_STMT was the previous statement. */
static bool
stmt_requires_new_enode_p (const gimple *stmt,
const gimple *prev_stmt)
{
if (const gcall *call = dyn_cast <const gcall *> (stmt))
{
/* Stop consolidating at calls to
"__analyzer_dump_exploded_nodes", so they always appear at the
start of an exploded_node. */
if (is_special_named_call_p (call, "__analyzer_dump_exploded_nodes",
1))
return true;
/* sm-signal.cc injects an additional custom eedge at "signal" calls
from the registration enode to the handler enode, separate from the
regular next state, which defeats the "detect state change" logic
in process_node. Work around this via special-casing, to ensure
we split the enode immediately before any "signal" call. */
if (is_special_named_call_p (call, "signal", 2, true))
return true;
}
/* If we had a PREV_STMT with an unknown location, and this stmt
has a known location, then if a state change happens here, it
could be consolidated into PREV_STMT, giving us an event with
no location. Ensure that STMT gets its own exploded_node to
avoid this. */
if (get_pure_location (prev_stmt->location) == UNKNOWN_LOCATION
&& get_pure_location (stmt->location) != UNKNOWN_LOCATION)
return true;
return false;
}
/* Return true if OLD_STATE and NEW_STATE are sufficiently different that
we should split enodes and create an exploded_edge separating them
(which makes it easier to identify state changes of intereset when
constructing checker_paths). */
static bool
state_change_requires_new_enode_p (const program_state &old_state,
const program_state &new_state)
{
/* Changes in dynamic extents signify creations of heap/alloca regions
and resizings of heap regions; likely to be of interest in
diagnostic paths. */
if (old_state.m_region_model->get_dynamic_extents ()
!= new_state.m_region_model->get_dynamic_extents ())
return true;
/* Changes in sm-state are of interest. */
int sm_idx;
sm_state_map *smap;
FOR_EACH_VEC_ELT (old_state.m_checker_states, sm_idx, smap)
{
const sm_state_map *old_smap = old_state.m_checker_states[sm_idx];
const sm_state_map *new_smap = new_state.m_checker_states[sm_idx];
if (*old_smap != *new_smap)
return true;
}
return false;
}
/* Create enodes and eedges for the function calls that doesn't have an
underlying call superedge.
Such case occurs when GCC's middle end didn't know which function to
call but the analyzer does (with the help of current state).
Some example such calls are dynamically dispatched calls to virtual
functions or calls that happen via function pointer. */
bool
exploded_graph::maybe_create_dynamic_call (const gcall *call,
tree fn_decl,
exploded_node *node,
program_state next_state,
program_point &next_point,
uncertainty_t *uncertainty,
logger *logger)
{
LOG_FUNC (logger);
const program_point *this_point = &node->get_point ();
function *fun = DECL_STRUCT_FUNCTION (fn_decl);
if (fun)
{
const supergraph &sg = this->get_supergraph ();
supernode *sn_entry = sg.get_node_for_function_entry (*fun);
supernode *sn_exit = sg.get_node_for_function_exit (*fun);
program_point new_point
= program_point::before_supernode (sn_entry,
NULL,
this_point->get_call_string ());
new_point.push_to_call_stack (sn_exit,
next_point.get_supernode());
/* Impose a maximum recursion depth and don't analyze paths
that exceed it further.
This is something of a blunt workaround, but it only
applies to recursion (and mutual recursion), not to
general call stacks. */
if (new_point.get_call_string ().calc_recursion_depth ()
> param_analyzer_max_recursion_depth)
{
if (logger)
logger->log ("rejecting call edge: recursion limit exceeded");
return false;
}
next_state.push_call (*this, node, call, uncertainty);
if (next_state.m_valid)
{
if (logger)
logger->log ("Discovered call to %s [SN: %i -> SN: %i]",
function_name(fun),
this_point->get_supernode ()->m_index,
sn_entry->m_index);
exploded_node *enode = get_or_create_node (new_point,
next_state,
node);
if (enode)
add_edge (node,enode, NULL,
false, /* No work is done by the call itself. */
make_unique<dynamic_call_info_t> (call));
return true;
}
}
return false;
}
/* Subclass of path_context for use within exploded_graph::process_node,
so that we can split states e.g. at "realloc" calls. */
class impl_path_context : public path_context
{
public:
impl_path_context (const program_state *cur_state,
logger *logger)
: m_cur_state (cur_state),
m_logger (logger),
m_terminate_path (false)
{
}
bool bifurcation_p () const
{
return m_custom_eedge_infos.length () > 0;
}
const program_state &get_state_at_bifurcation () const
{
gcc_assert (m_state_at_bifurcation);
return *m_state_at_bifurcation;
}
void
bifurcate (std::unique_ptr<custom_edge_info> info) final override
{
if (m_logger)
m_logger->log ("bifurcating path");
if (m_state_at_bifurcation)
/* Verify that the state at bifurcation is consistent when we
split into multiple out-edges. */
gcc_assert (*m_state_at_bifurcation == *m_cur_state);
else
/* Take a copy of the cur_state at the moment when bifurcation
happens. */
m_state_at_bifurcation
= std::unique_ptr<program_state> (new program_state (*m_cur_state));
/* Take ownership of INFO. */
m_custom_eedge_infos.safe_push (info.release ());
}
void terminate_path () final override
{
if (m_logger)
m_logger->log ("terminating path");
m_terminate_path = true;
}
bool terminate_path_p () const final override
{
return m_terminate_path;
}
const vec<custom_edge_info *> & get_custom_eedge_infos ()
{
return m_custom_eedge_infos;
}
private:
const program_state *m_cur_state;
logger *m_logger;
/* Lazily-created copy of the state before the split. */
std::unique_ptr<program_state> m_state_at_bifurcation;
auto_vec <custom_edge_info *> m_custom_eedge_infos;
bool m_terminate_path;
};
/* A subclass of pending_diagnostic for complaining about jumps through NULL
function pointers. */
class jump_through_null : public pending_diagnostic_subclass<jump_through_null>
{
public:
jump_through_null (const gcall *call)
: m_call (call)
{}
const char *get_kind () const final override
{
return "jump_through_null";
}
bool operator== (const jump_through_null &other) const
{
return m_call == other.m_call;
}
int get_controlling_option () const final override
{
return OPT_Wanalyzer_jump_through_null;
}
bool emit (diagnostic_emission_context &ctxt) final override
{
return ctxt.warn ("jump through null pointer");
}
label_text describe_final_event (const evdesc::final_event &ev) final override
{
return ev.formatted_print ("jump through null pointer here");
}
private:
const gcall *m_call;
};
/* The core of exploded_graph::process_worklist (the main analysis loop),
handling one node in the worklist.
Get successor <point, state> pairs for NODE, calling get_or_create on
them, and adding an exploded_edge to each successors.
Freshly-created nodes will be added to the worklist. */
void
exploded_graph::process_node (exploded_node *node)
{
logger * const logger = get_logger ();
LOG_FUNC_1 (logger, "EN: %i", node->m_index);
node->set_status (exploded_node::STATUS_PROCESSED);
const program_point &point = node->get_point ();
/* Update cfun and input_location in case of an ICE: make it easier to
track down which source construct we're failing to handle. */
auto_cfun sentinel (node->get_function ());
const gimple *stmt = point.get_stmt ();
if (stmt)
input_location = stmt->location;
const program_state &state = node->get_state ();
if (logger)
{
pretty_printer *pp = logger->get_printer ();
logger->start_log_line ();
pp_string (pp, "point: ");
point.print (pp, format (false));
pp_string (pp, ", state: ");
state.dump_to_pp (m_ext_state, true, false, pp);
logger->end_log_line ();
}
switch (point.get_kind ())
{
default:
gcc_unreachable ();
case PK_ORIGIN:
/* This node exists to simplify finding the shortest path
to an exploded_node. */
break;
case PK_BEFORE_SUPERNODE:
{
program_state next_state (state);
uncertainty_t uncertainty;
if (point.get_from_edge ())
{
impl_region_model_context ctxt (*this, node,
&state, &next_state,
&uncertainty, NULL, NULL);
const cfg_superedge *last_cfg_superedge
= point.get_from_edge ()->dyn_cast_cfg_superedge ();
if (last_cfg_superedge)
next_state.m_region_model->update_for_phis
(node->get_supernode (),
last_cfg_superedge,
&ctxt);
program_state::detect_leaks (state, next_state, NULL,
get_ext_state (), &ctxt);
}
program_point next_point (point.get_next ());
exploded_node *next = get_or_create_node (next_point, next_state, node);
if (next)
add_edge (node, next, NULL,
false); /* Assume no work is done at phi nodes. */
}
break;
case PK_BEFORE_STMT:
{
/* Determine the effect of a run of one or more statements
within one supernode, generating an edge to the program_point
after the last statement that's processed.
Stop iterating statements and thus consolidating into one enode
when:
- reaching the end of the statements in the supernode
- if an sm-state-change occurs (so that it gets its own
exploded_node)
- if "-fanalyzer-fine-grained" is active
- encountering certain statements must appear at the start of
their enode (for which stmt_requires_new_enode_p returns true)
Update next_state in-place, to get the result of the one
or more stmts that are processed.
Split the node in-place if an sm-state-change occurs, so that
the sm-state-change occurs on an edge where the src enode has
exactly one stmt, the one that caused the change. */
program_state next_state (state);
impl_path_context path_ctxt (&next_state, logger);
bool could_have_done_work = false;
uncertainty_t uncertainty;
const supernode *snode = point.get_supernode ();
unsigned stmt_idx;
const gimple *prev_stmt = NULL;
for (stmt_idx = point.get_stmt_idx ();
stmt_idx < snode->m_stmts.length ();
stmt_idx++)
{
const gimple *stmt = snode->m_stmts[stmt_idx];
if (stmt_idx > point.get_stmt_idx ())
if (stmt_requires_new_enode_p (stmt, prev_stmt))
{
stmt_idx--;
break;
}
prev_stmt = stmt;
program_state old_state (next_state);
/* Process the stmt. */
exploded_node::on_stmt_flags flags
= node->on_stmt (*this, snode, stmt, &next_state, &uncertainty,
&could_have_done_work, &path_ctxt);
node->m_num_processed_stmts++;
/* If flags.m_terminate_path, stop analyzing; any nodes/edges
will have been added by on_stmt (e.g. for handling longjmp). */
if (flags.m_terminate_path)
return;
if (next_state.m_region_model)
{
impl_region_model_context ctxt (*this, node,
&old_state, &next_state,
&uncertainty, NULL, stmt);
program_state::detect_leaks (old_state, next_state, NULL,
get_ext_state (), &ctxt);
}
unsigned next_idx = stmt_idx + 1;
program_point next_point
= (next_idx < point.get_supernode ()->m_stmts.length ()
? program_point::before_stmt (point.get_supernode (), next_idx,
point.get_call_string ())
: program_point::after_supernode (point.get_supernode (),
point.get_call_string ()));
next_state = next_state.prune_for_point (*this, next_point, node,
&uncertainty);
if (flag_analyzer_fine_grained
|| state_change_requires_new_enode_p (old_state, next_state)
|| path_ctxt.bifurcation_p ()
|| path_ctxt.terminate_path_p ())
{
program_point split_point
= program_point::before_stmt (point.get_supernode (),
stmt_idx,
point.get_call_string ());
if (split_point != node->get_point ())
{
/* If we're not at the start of NODE, split the enode at
this stmt, so we have:
node -> split_enode
so that when split_enode is processed the next edge
we add will be:
split_enode -> next
and any state change will effectively occur on that
latter edge, and split_enode will contain just stmt. */
if (logger)
logger->log ("getting split_enode");
exploded_node *split_enode
= get_or_create_node (split_point, old_state, node);
if (!split_enode)
return;
/* "stmt" will be reprocessed when split_enode is
processed. */
node->m_num_processed_stmts--;
if (logger)
logger->log ("creating edge to split_enode");
add_edge (node, split_enode, NULL, could_have_done_work);
return;
}
else
/* If we're at the start of NODE, stop iterating,
so that an edge will be created from NODE to
(next_point, next_state) below. */
break;
}
}
unsigned next_idx = stmt_idx + 1;
program_point next_point
= (next_idx < point.get_supernode ()->m_stmts.length ()
? program_point::before_stmt (point.get_supernode (), next_idx,
point.get_call_string ())
: program_point::after_supernode (point.get_supernode (),
point.get_call_string ()));
if (path_ctxt.terminate_path_p ())
{
if (logger)
logger->log ("not adding node: terminating path");
}
else
{
exploded_node *next
= get_or_create_node (next_point, next_state, node);
if (next)
add_edge (node, next, NULL, could_have_done_work);
}
/* If we have custom edge infos, "bifurcate" the state
accordingly, potentially creating a new state/enode/eedge
instances. For example, to handle a "realloc" call, we
might split into 3 states, for the "failure",
"resizing in place", and "moving to a new buffer" cases. */
for (auto edge_info_iter : path_ctxt.get_custom_eedge_infos ())
{
/* Take ownership of the edge infos from the path_ctxt. */
std::unique_ptr<custom_edge_info> edge_info (edge_info_iter);
if (logger)
{
logger->start_log_line ();
logger->log_partial ("bifurcating for edge: ");
edge_info->print (logger->get_printer ());
logger->end_log_line ();
}
program_state bifurcated_new_state
(path_ctxt.get_state_at_bifurcation ());
/* Apply edge_info to state. */
impl_region_model_context
bifurcation_ctxt (*this,
node, // enode_for_diag
&path_ctxt.get_state_at_bifurcation (),
&bifurcated_new_state,
NULL, // uncertainty_t *uncertainty
NULL, // path_context *path_ctxt
stmt);
if (edge_info->update_state (&bifurcated_new_state,
NULL, /* no exploded_edge yet. */
&bifurcation_ctxt))
{
exploded_node *next2
= get_or_create_node (next_point, bifurcated_new_state, node);
if (next2)
add_edge (node, next2, NULL,
true /* assume that work could be done */,
std::move (edge_info));
}
else
{
if (logger)
logger->log ("infeasible state, not adding node");
}
}
}
break;
case PK_AFTER_SUPERNODE:
{
bool found_a_superedge = false;
bool is_an_exit_block = false;
/* If this is an EXIT BB, detect leaks, and potentially
create a function summary. */
if (point.get_supernode ()->return_p ())
{
is_an_exit_block = true;
node->detect_leaks (*this);
if (flag_analyzer_call_summaries
&& point.get_call_string ().empty_p ())
{
/* TODO: create function summary
There can be more than one; each corresponds to a different
final enode in the function. */
if (logger)
{
pretty_printer *pp = logger->get_printer ();
logger->start_log_line ();
logger->log_partial
("would create function summary for %qE; state: ",
point.get_fndecl ());
state.dump_to_pp (m_ext_state, true, false, pp);
logger->end_log_line ();
}
per_function_data *per_fn_data
= get_or_create_per_function_data (point.get_function ());
per_fn_data->add_call_summary (node);
}
}
/* Traverse into successors of the supernode. */
int i;
superedge *succ;
FOR_EACH_VEC_ELT (point.get_supernode ()->m_succs, i, succ)
{
found_a_superedge = true;
if (logger)
{
label_text succ_desc (succ->get_description (false));
logger->log ("considering SN: %i -> SN: %i (%s)",
succ->m_src->m_index, succ->m_dest->m_index,
succ_desc.get ());
}
program_point next_point
= program_point::before_supernode (succ->m_dest, succ,
point.get_call_string ());
program_state next_state (state);
uncertainty_t uncertainty;
/* Make use the current state and try to discover and analyse
indirect function calls (a call that doesn't have an underlying
cgraph edge representing call).
Some examples of such calls are virtual function calls
and calls that happen via a function pointer. */
if (succ->m_kind == SUPEREDGE_INTRAPROCEDURAL_CALL
&& !(succ->get_any_callgraph_edge ()))
{
const gcall *call
= point.get_supernode ()->get_final_call ();
impl_region_model_context ctxt (*this,
node,
&state,
&next_state,
&uncertainty,
NULL,
point.get_stmt());
region_model *model = state.m_region_model;
bool call_discovered = false;
if (tree fn_decl = model->get_fndecl_for_call (call, &ctxt))
call_discovered = maybe_create_dynamic_call (call,
fn_decl,
node,
next_state,
next_point,
&uncertainty,
logger);
if (!call_discovered)
{
/* Check for jump through NULL. */
if (tree fn_ptr = gimple_call_fn (call))
{
const svalue *fn_ptr_sval
= model->get_rvalue (fn_ptr, &ctxt);
if (fn_ptr_sval->all_zeroes_p ())
ctxt.warn (make_unique<jump_through_null> (call));
}
/* An unknown function or a special function was called
at this point, in such case, don't terminate the
analysis of the current function.
The analyzer handles calls to such functions while
analysing the stmt itself, so the function call
must have been handled by the anlyzer till now. */
exploded_node *next
= get_or_create_node (next_point,
next_state,
node);
if (next)
add_edge (node, next, succ,
true /* assume that work is done */);
}
}
if (!node->on_edge (*this, succ, &next_point, &next_state,
&uncertainty))
{
if (logger)
logger->log ("skipping impossible edge to SN: %i",
succ->m_dest->m_index);
continue;
}
exploded_node *next = get_or_create_node (next_point, next_state,
node);
if (next)
{
add_edge (node, next, succ, false);
/* We might have a function entrypoint. */
detect_infinite_recursion (next);
}
}
/* Return from the calls which doesn't have a return superedge.
Such case occurs when GCC's middle end didn't knew which function to
call but analyzer did. */
if ((is_an_exit_block && !found_a_superedge)
&& (!point.get_call_string ().empty_p ()))
{
const call_string &cs = point.get_call_string ();
program_point next_point
= program_point::before_supernode (cs.get_caller_node (),
NULL,
cs);
program_state next_state (state);
uncertainty_t uncertainty;
const gcall *call
= next_point.get_supernode ()->get_returning_call ();
if (call)
next_state.returning_call (*this, node, call, &uncertainty);
if (next_state.m_valid)
{
next_point.pop_from_call_stack ();
exploded_node *enode = get_or_create_node (next_point,
next_state,
node);
if (enode)
add_edge (node, enode, NULL, false,
make_unique<dynamic_call_info_t> (call, true));
}
}
}
break;
}
}
/* Ensure that this graph has a stats instance for FN, return it.
FN can be NULL, in which case a stats instances is returned covering
"functionless" parts of the graph (the origin node). */
stats *
exploded_graph::get_or_create_function_stats (function *fn)
{
if (!fn)
return &m_functionless_stats;
if (stats **slot = m_per_function_stats.get (fn))
return *slot;
else
{
int num_supernodes = fn ? n_basic_blocks_for_fn (fn) : 0;
/* not quite the num supernodes, but nearly. */
stats *new_stats = new stats (num_supernodes);
m_per_function_stats.put (fn, new_stats);
return new_stats;
}
}
/* Print bar charts to PP showing:
- the number of enodes per function, and
- for each function:
- the number of enodes per supernode/BB
- the number of excess enodes per supernode/BB beyond the
per-program-point limit, if there were any. */
void
exploded_graph::print_bar_charts (pretty_printer *pp) const
{
cgraph_node *cgnode;
pp_string (pp, "enodes per function:");
pp_newline (pp);
bar_chart enodes_per_function;
FOR_EACH_FUNCTION_WITH_GIMPLE_BODY (cgnode)
{
function *fn = cgnode->get_fun ();
const stats * const *s_ptr
= const_cast <function_stat_map_t &> (m_per_function_stats).get (fn);
enodes_per_function.add_item (function_name (fn),
s_ptr ? (*s_ptr)->get_total_enodes () : 0);
}
enodes_per_function.print (pp);
/* Accumulate number of enodes per supernode. */
auto_vec<unsigned> enodes_per_supernode (m_sg.num_nodes ());
for (int i = 0; i < m_sg.num_nodes (); i++)
enodes_per_supernode.quick_push (0);
int i;
exploded_node *enode;
FOR_EACH_VEC_ELT (m_nodes, i, enode)
{
const supernode *iter_snode = enode->get_supernode ();
if (!iter_snode)
continue;
enodes_per_supernode[iter_snode->m_index]++;
}
/* Accumulate excess enodes per supernode. */
auto_vec<unsigned> excess_enodes_per_supernode (m_sg.num_nodes ());
for (int i = 0; i < m_sg.num_nodes (); i++)
excess_enodes_per_supernode.quick_push (0);
for (point_map_t::iterator iter = m_per_point_data.begin ();
iter != m_per_point_data.end (); ++iter)
{
const program_point *point = (*iter).first;
const supernode *iter_snode = point->get_supernode ();
if (!iter_snode)
continue;
const per_program_point_data *point_data = (*iter).second;
excess_enodes_per_supernode[iter_snode->m_index]
+= point_data->m_excess_enodes;
}
/* Show per-function bar_charts of enodes per supernode/BB. */
pp_string (pp, "per-function enodes per supernode/BB:");
pp_newline (pp);
FOR_EACH_FUNCTION_WITH_GIMPLE_BODY (cgnode)
{
function *fn = cgnode->get_fun ();
pp_printf (pp, "function: %qs", function_name (fn));
pp_newline (pp);
bar_chart enodes_per_snode;
bar_chart excess_enodes_per_snode;
bool have_excess_enodes = false;
for (int i = 0; i < m_sg.num_nodes (); i++)
{
const supernode *iter_snode = m_sg.get_node_by_index (i);
if (iter_snode->get_function () != fn)
continue;
pretty_printer tmp_pp;
pp_printf (&tmp_pp, "sn %i (bb %i)",
iter_snode->m_index, iter_snode->m_bb->index);
enodes_per_snode.add_item (pp_formatted_text (&tmp_pp),
enodes_per_supernode[iter_snode->m_index]);
const int num_excess
= excess_enodes_per_supernode[iter_snode->m_index];
excess_enodes_per_snode.add_item (pp_formatted_text (&tmp_pp),
num_excess);
if (num_excess)
have_excess_enodes = true;
}
enodes_per_snode.print (pp);
if (have_excess_enodes)
{
pp_printf (pp, "EXCESS ENODES:");
pp_newline (pp);
excess_enodes_per_snode.print (pp);
}
}
}
/* Write all stats information to this graph's logger, if any. */
void
exploded_graph::log_stats () const
{
logger * const logger = get_logger ();
if (!logger)
return;
LOG_SCOPE (logger);
m_ext_state.get_engine ()->log_stats (logger);
logger->log ("m_sg.num_nodes (): %i", m_sg.num_nodes ());
logger->log ("m_nodes.length (): %i", m_nodes.length ());
logger->log ("m_edges.length (): %i", m_edges.length ());
logger->log ("remaining enodes in worklist: %i", m_worklist.length ());
logger->log ("global stats:");
m_global_stats.log (logger);
for (function_stat_map_t::iterator iter = m_per_function_stats.begin ();
iter != m_per_function_stats.end ();
++iter)
{
function *fn = (*iter).first;
log_scope s (logger, function_name (fn));
(*iter).second->log (logger);
}
print_bar_charts (logger->get_printer ());
}
/* Dump all stats information to OUT. */
void
exploded_graph::dump_stats (FILE *out) const
{
fprintf (out, "m_sg.num_nodes (): %i\n", m_sg.num_nodes ());
fprintf (out, "m_nodes.length (): %i\n", m_nodes.length ());
fprintf (out, "m_edges.length (): %i\n", m_edges.length ());
fprintf (out, "remaining enodes in worklist: %i", m_worklist.length ());
fprintf (out, "global stats:\n");
m_global_stats.dump (out);
for (function_stat_map_t::iterator iter = m_per_function_stats.begin ();
iter != m_per_function_stats.end ();
++iter)
{
function *fn = (*iter).first;
fprintf (out, "function: %s\n", function_name (fn));
(*iter).second->dump (out);
}
fprintf (out, "PK_AFTER_SUPERNODE per supernode:\n");
for (unsigned i = 0; i < m_PK_AFTER_SUPERNODE_per_snode.length (); i++)
fprintf (out, " SN %i: %3i\n", i, m_PK_AFTER_SUPERNODE_per_snode[i]);
}
void
exploded_graph::dump_states_for_supernode (FILE *out,
const supernode *snode) const
{
fprintf (out, "PK_AFTER_SUPERNODE nodes for SN: %i\n", snode->m_index);
int i;
exploded_node *enode;
int state_idx = 0;
FOR_EACH_VEC_ELT (m_nodes, i, enode)
{
const supernode *iter_snode = enode->get_supernode ();
if (enode->get_point ().get_kind () == PK_AFTER_SUPERNODE
&& iter_snode == snode)
{
pretty_printer pp;
pp_format_decoder (&pp) = default_tree_printer;
enode->get_state ().dump_to_pp (m_ext_state, true, false, &pp);
fprintf (out, "state %i: EN: %i\n %s\n",
state_idx++, enode->m_index,
pp_formatted_text (&pp));
}
}
fprintf (out, "#exploded_node for PK_AFTER_SUPERNODE for SN: %i = %i\n",
snode->m_index, state_idx);
}
/* Return a new json::object of the form
{"nodes" : [objs for enodes],
"edges" : [objs for eedges],
"ext_state": object for extrinsic_state,
"diagnostic_manager": object for diagnostic_manager}. */
json::object *
exploded_graph::to_json () const
{
json::object *egraph_obj = new json::object ();
/* Nodes. */
{
json::array *nodes_arr = new json::array ();
unsigned i;
exploded_node *n;
FOR_EACH_VEC_ELT (m_nodes, i, n)
nodes_arr->append (n->to_json (m_ext_state));
egraph_obj->set ("nodes", nodes_arr);
}
/* Edges. */
{
json::array *edges_arr = new json::array ();
unsigned i;
exploded_edge *n;
FOR_EACH_VEC_ELT (m_edges, i, n)
edges_arr->append (n->to_json ());
egraph_obj->set ("edges", edges_arr);
}
/* m_sg is JSONified at the top-level. */
egraph_obj->set ("ext_state", m_ext_state.to_json ());
egraph_obj->set ("worklist", m_worklist.to_json ());
egraph_obj->set ("diagnostic_manager", m_diagnostic_manager.to_json ());
/* The following fields aren't yet being JSONified:
const state_purge_map *const m_purge_map;
const analysis_plan &m_plan;
stats m_global_stats;
function_stat_map_t m_per_function_stats;
stats m_functionless_stats;
call_string_data_map_t m_per_call_string_data;
auto_vec<int> m_PK_AFTER_SUPERNODE_per_snode; */
return egraph_obj;
}
/* class exploded_path. */
/* Copy ctor. */
exploded_path::exploded_path (const exploded_path &other)
: m_edges (other.m_edges.length ())
{
int i;
const exploded_edge *eedge;
FOR_EACH_VEC_ELT (other.m_edges, i, eedge)
m_edges.quick_push (eedge);
}
/* Look for the last use of SEARCH_STMT within this path.
If found write the edge's index to *OUT_IDX and return true, otherwise
return false. */
bool
exploded_path::find_stmt_backwards (const gimple *search_stmt,
int *out_idx) const
{
int i;
const exploded_edge *eedge;
FOR_EACH_VEC_ELT_REVERSE (m_edges, i, eedge)
{
const exploded_node *dst_node = eedge->m_dest;
const program_point &dst_point = dst_node->get_point ();
const gimple *stmt = dst_point.get_stmt ();
if (stmt == search_stmt)
{
*out_idx = i;
return true;
}
}
return false;
}
/* Get the final exploded_node in this path, which must be non-empty. */
exploded_node *
exploded_path::get_final_enode () const
{
gcc_assert (m_edges.length () > 0);
return m_edges[m_edges.length () - 1]->m_dest;
}
/* Check state along this path, returning true if it is feasible.
If OUT is non-NULL, and the path is infeasible, write a new
feasibility_problem to *OUT. */
bool
exploded_path::feasible_p (logger *logger,
std::unique_ptr<feasibility_problem> *out,
engine *eng, const exploded_graph *eg) const
{
LOG_SCOPE (logger);
feasibility_state state (eng->get_model_manager (),
eg->get_supergraph ());
/* Traverse the path, updating this state. */
for (unsigned edge_idx = 0; edge_idx < m_edges.length (); edge_idx++)
{
const exploded_edge *eedge = m_edges[edge_idx];
if (logger)
logger->log ("considering edge %i: EN:%i -> EN:%i",
edge_idx,
eedge->m_src->m_index,
eedge->m_dest->m_index);
std::unique_ptr <rejected_constraint> rc;
if (!state.maybe_update_for_edge (logger, eedge, nullptr, &rc))
{
gcc_assert (rc);
if (out)
{
const exploded_node &src_enode = *eedge->m_src;
const program_point &src_point = src_enode.get_point ();
const gimple *last_stmt
= src_point.get_supernode ()->get_last_stmt ();
*out = ::make_unique<feasibility_problem> (edge_idx, *eedge,
last_stmt,
std::move (rc));
}
return false;
}
if (logger)
{
logger->log ("state after edge %i: EN:%i -> EN:%i",
edge_idx,
eedge->m_src->m_index,
eedge->m_dest->m_index);
logger->start_log_line ();
state.get_model ().dump_to_pp (logger->get_printer (), true, false);
logger->end_log_line ();
}
}
return true;
}
/* Dump this path in multiline form to PP.
If EXT_STATE is non-NULL, then show the nodes. */
void
exploded_path::dump_to_pp (pretty_printer *pp,
const extrinsic_state *ext_state) const
{
for (unsigned i = 0; i < m_edges.length (); i++)
{
const exploded_edge *eedge = m_edges[i];
pp_printf (pp, "m_edges[%i]: EN %i -> EN %i",
i,
eedge->m_src->m_index,
eedge->m_dest->m_index);
pp_newline (pp);
if (ext_state)
eedge->m_dest->dump_to_pp (pp, *ext_state);
}
}
/* Dump this path in multiline form to FP. */
void
exploded_path::dump (FILE *fp, const extrinsic_state *ext_state) const
{
pretty_printer pp;
pp_format_decoder (&pp) = default_tree_printer;
pp_show_color (&pp) = pp_show_color (global_dc->printer);
pp.buffer->stream = fp;
dump_to_pp (&pp, ext_state);
pp_flush (&pp);
}
/* Dump this path in multiline form to stderr. */
DEBUG_FUNCTION void
exploded_path::dump (const extrinsic_state *ext_state) const
{
dump (stderr, ext_state);
}
/* Dump this path verbosely to FILENAME. */
void
exploded_path::dump_to_file (const char *filename,
const extrinsic_state &ext_state) const
{
FILE *fp = fopen (filename, "w");
if (!fp)
return;
pretty_printer pp;
pp_format_decoder (&pp) = default_tree_printer;
pp.buffer->stream = fp;
dump_to_pp (&pp, &ext_state);
pp_flush (&pp);
fclose (fp);
}
/* class feasibility_problem. */
void
feasibility_problem::dump_to_pp (pretty_printer *pp) const
{
pp_printf (pp, "edge from EN: %i to EN: %i",
m_eedge.m_src->m_index, m_eedge.m_dest->m_index);
if (m_rc)
{
pp_string (pp, "; rejected constraint: ");
m_rc->dump_to_pp (pp);
pp_string (pp, "; rmodel: ");
m_rc->get_model ().dump_to_pp (pp, true, false);
}
}
/* class feasibility_state. */
/* Ctor for feasibility_state, at the beginning of a path. */
feasibility_state::feasibility_state (region_model_manager *manager,
const supergraph &sg)
: m_model (manager),
m_snodes_visited (sg.m_nodes.length ())
{
bitmap_clear (m_snodes_visited);
}
/* Copy ctor for feasibility_state, for extending a path. */
feasibility_state::feasibility_state (const feasibility_state &other)
: m_model (other.m_model),
m_snodes_visited (const_sbitmap (other.m_snodes_visited)->n_bits)
{
bitmap_copy (m_snodes_visited, other.m_snodes_visited);
}
feasibility_state::feasibility_state (const region_model &model,
const supergraph &sg)
: m_model (model),
m_snodes_visited (sg.m_nodes.length ())
{
bitmap_clear (m_snodes_visited);
}
feasibility_state &
feasibility_state::operator= (const feasibility_state &other)
{
m_model = other.m_model;
bitmap_copy (m_snodes_visited, other.m_snodes_visited);
return *this;
}
/* The heart of feasibility-checking.
Attempt to update this state in-place based on traversing EEDGE
in a path.
Update the model for the stmts in the src enode.
Attempt to add constraints for EEDGE.
If feasible, return true.
Otherwise, return false and write to *OUT_RC. */
bool
feasibility_state::
maybe_update_for_edge (logger *logger,
const exploded_edge *eedge,
region_model_context *ctxt,
std::unique_ptr<rejected_constraint> *out_rc)
{
const exploded_node &src_enode = *eedge->m_src;
const program_point &src_point = src_enode.get_point ();
if (logger)
{
logger->start_log_line ();
src_point.print (logger->get_printer (), format (false));
logger->end_log_line ();
}
/* Update state for the stmts that were processed in each enode. */
for (unsigned stmt_idx = 0; stmt_idx < src_enode.m_num_processed_stmts;
stmt_idx++)
{
const gimple *stmt = src_enode.get_processed_stmt (stmt_idx);
/* Update cfun and input_location in case of ICE: make it easier to
track down which source construct we're failing to handle. */
auto_cfun sentinel (src_point.get_function ());
input_location = stmt->location;
update_for_stmt (stmt);
}
const superedge *sedge = eedge->m_sedge;
if (sedge)
{
if (logger)
{
label_text desc (sedge->get_description (false));
logger->log (" sedge: SN:%i -> SN:%i %s",
sedge->m_src->m_index,
sedge->m_dest->m_index,
desc.get ());
}
const gimple *last_stmt = src_point.get_supernode ()->get_last_stmt ();
if (!m_model.maybe_update_for_edge (*sedge, last_stmt, ctxt, out_rc))
{
if (logger)
{
logger->start_log_line ();
logger->log_partial ("rejecting due to region model: ");
m_model.dump_to_pp (logger->get_printer (), true, false);
logger->end_log_line ();
}
return false;
}
}
else
{
/* Special-case the initial eedge from the origin node to the
initial function by pushing a frame for it. */
if (src_point.get_kind () == PK_ORIGIN)
{
gcc_assert (eedge->m_src->m_index == 0);
gcc_assert (eedge->m_dest->get_point ().get_kind ()
== PK_BEFORE_SUPERNODE);
function *fun = eedge->m_dest->get_function ();
gcc_assert (fun);
m_model.push_frame (*fun, NULL, ctxt);
if (logger)
logger->log (" pushing frame for %qD", fun->decl);
}
else if (eedge->m_custom_info)
{
eedge->m_custom_info->update_model (&m_model, eedge, ctxt);
}
}
/* Handle phi nodes on an edge leaving a PK_BEFORE_SUPERNODE (to
a PK_BEFORE_STMT, or a PK_AFTER_SUPERNODE if no stmts).
This will typically not be associated with a superedge. */
if (src_point.get_from_edge ())
{
const cfg_superedge *last_cfg_superedge
= src_point.get_from_edge ()->dyn_cast_cfg_superedge ();
const exploded_node &dst_enode = *eedge->m_dest;
const unsigned dst_snode_idx = dst_enode.get_supernode ()->m_index;
if (last_cfg_superedge)
{
if (logger)
logger->log (" update for phis");
m_model.update_for_phis (src_enode.get_supernode (),
last_cfg_superedge,
ctxt);
/* If we've entering an snode that we've already visited on this
epath, then we need do fix things up for loops; see the
comment for store::loop_replay_fixup.
Perhaps we should probably also verify the callstring,
and track program_points, but hopefully doing it by supernode
is good enough. */
if (bitmap_bit_p (m_snodes_visited, dst_snode_idx))
m_model.loop_replay_fixup (dst_enode.get_state ().m_region_model);
}
bitmap_set_bit (m_snodes_visited, dst_snode_idx);
}
return true;
}
/* Update this object for the effects of STMT. */
void
feasibility_state::update_for_stmt (const gimple *stmt)
{
if (const gassign *assign = dyn_cast <const gassign *> (stmt))
m_model.on_assignment (assign, NULL);
else if (const gasm *asm_stmt = dyn_cast <const gasm *> (stmt))
m_model.on_asm_stmt (asm_stmt, NULL);
else if (const gcall *call = dyn_cast <const gcall *> (stmt))
{
bool unknown_side_effects = m_model.on_call_pre (call, NULL);
m_model.on_call_post (call, unknown_side_effects, NULL);
}
else if (const greturn *return_ = dyn_cast <const greturn *> (stmt))
m_model.on_return (return_, NULL);
}
/* Dump this object to PP. */
void
feasibility_state::dump_to_pp (pretty_printer *pp,
bool simple, bool multiline) const
{
m_model.dump_to_pp (pp, simple, multiline);
}
/* A family of cluster subclasses for use when generating .dot output for
exploded graphs (-fdump-analyzer-exploded-graph), for grouping the
enodes into hierarchical boxes.
All functionless enodes appear in the top-level graph.
Every (function, call_string) pair gets its own cluster. Within that
cluster, each supernode gets its own cluster.
Hence all enodes relating to a particular function with a particular
callstring will be in a cluster together; all enodes for the same
function but with a different callstring will be in a different
cluster. */
/* Base class of cluster for clustering exploded_node instances in .dot
output, based on various subclass-specific criteria. */
class exploded_cluster : public cluster<eg_traits>
{
};
/* Cluster containing all exploded_node instances for one supernode. */
class supernode_cluster : public exploded_cluster
{
public:
supernode_cluster (const supernode *supernode) : m_supernode (supernode) {}
// TODO: dtor?
void dump_dot (graphviz_out *gv, const dump_args_t &args) const final override
{
gv->println ("subgraph \"cluster_supernode_%i\" {", m_supernode->m_index);
gv->indent ();
gv->println ("style=\"dashed\";");
gv->println ("label=\"SN: %i (bb: %i; scc: %i)\";",
m_supernode->m_index, m_supernode->m_bb->index,
args.m_eg.get_scc_id (*m_supernode));
int i;
exploded_node *enode;
FOR_EACH_VEC_ELT (m_enodes, i, enode)
enode->dump_dot (gv, args);
/* Terminate subgraph. */
gv->outdent ();
gv->println ("}");
}
void add_node (exploded_node *en) final override
{
m_enodes.safe_push (en);
}
/* Comparator for use by auto_vec<supernode_cluster *>::qsort. */
static int cmp_ptr_ptr (const void *p1, const void *p2)
{
const supernode_cluster *c1
= *(const supernode_cluster * const *)p1;
const supernode_cluster *c2
= *(const supernode_cluster * const *)p2;
return c1->m_supernode->m_index - c2->m_supernode->m_index;
}
private:
const supernode *m_supernode;
auto_vec <exploded_node *> m_enodes;
};
/* Cluster containing all supernode_cluster instances for one
(function, call_string) pair. */
class function_call_string_cluster : public exploded_cluster
{
public:
function_call_string_cluster (function *fun, const call_string &cs)
: m_fun (fun), m_cs (cs) {}
~function_call_string_cluster ()
{
for (map_t::iterator iter = m_map.begin ();
iter != m_map.end ();
++iter)
delete (*iter).second;
}
void dump_dot (graphviz_out *gv, const dump_args_t &args) const final override
{
const char *funcname = function_name (m_fun);
gv->println ("subgraph \"cluster_function_%s\" {",
IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (m_fun->decl)));
gv->indent ();
gv->write_indent ();
gv->print ("label=\"call string: ");
m_cs.print (gv->get_pp ());
gv->print (" function: %s \";", funcname);
gv->print ("\n");
/* Dump m_map, sorting it to avoid churn when comparing dumps. */
auto_vec<supernode_cluster *> child_clusters (m_map.elements ());
for (map_t::iterator iter = m_map.begin ();
iter != m_map.end ();
++iter)
child_clusters.quick_push ((*iter).second);
child_clusters.qsort (supernode_cluster::cmp_ptr_ptr);
unsigned i;
supernode_cluster *child_cluster;
FOR_EACH_VEC_ELT (child_clusters, i, child_cluster)
child_cluster->dump_dot (gv, args);
/* Terminate subgraph. */
gv->outdent ();
gv->println ("}");
}
void add_node (exploded_node *en) final override
{
const supernode *supernode = en->get_supernode ();
gcc_assert (supernode);
supernode_cluster **slot = m_map.get (supernode);
if (slot)
(*slot)->add_node (en);
else
{
supernode_cluster *child = new supernode_cluster (supernode);
m_map.put (supernode, child);
child->add_node (en);
}
}
/* Comparator for use by auto_vec<function_call_string_cluster *>. */
static int cmp_ptr_ptr (const void *p1, const void *p2)
{
const function_call_string_cluster *c1
= *(const function_call_string_cluster * const *)p1;
const function_call_string_cluster *c2
= *(const function_call_string_cluster * const *)p2;
if (int cmp_names
= strcmp (IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (c1->m_fun->decl)),
IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (c2->m_fun->decl))))
return cmp_names;
return call_string::cmp (c1->m_cs, c2->m_cs);
}
private:
function *m_fun;
const call_string &m_cs;
typedef ordered_hash_map<const supernode *, supernode_cluster *> map_t;
map_t m_map;
};
/* Keys for root_cluster. */
struct function_call_string
{
function_call_string (function *fun, const call_string *cs)
: m_fun (fun), m_cs (cs)
{
gcc_assert (fun);
gcc_assert (cs);
}
function *m_fun;
const call_string *m_cs;
};
} // namespace ana
template <> struct default_hash_traits<function_call_string>
: public pod_hash_traits<function_call_string>
{
static const bool empty_zero_p = false;
};
template <>
inline hashval_t
pod_hash_traits<function_call_string>::hash (value_type v)
{
return (pointer_hash <function>::hash (v.m_fun)
^ pointer_hash <const call_string>::hash (v.m_cs));
}
template <>
inline bool
pod_hash_traits<function_call_string>::equal (const value_type &existing,
const value_type &candidate)
{
return existing.m_fun == candidate.m_fun && &existing.m_cs == &candidate.m_cs;
}
template <>
inline void
pod_hash_traits<function_call_string>::mark_deleted (value_type &v)
{
v.m_fun = reinterpret_cast<function *> (1);
}
template <>
inline void
pod_hash_traits<function_call_string>::mark_empty (value_type &v)
{
v.m_fun = NULL;
}
template <>
inline bool
pod_hash_traits<function_call_string>::is_deleted (value_type v)
{
return v.m_fun == reinterpret_cast<function *> (1);
}
template <>
inline bool
pod_hash_traits<function_call_string>::is_empty (value_type v)
{
return v.m_fun == NULL;
}
namespace ana {
/* Top-level cluster for generating .dot output for exploded graphs,
handling the functionless nodes, and grouping the remaining nodes by
callstring. */
class root_cluster : public exploded_cluster
{
public:
~root_cluster ()
{
for (map_t::iterator iter = m_map.begin ();
iter != m_map.end ();
++iter)
delete (*iter).second;
}
void dump_dot (graphviz_out *gv, const dump_args_t &args) const final override
{
int i;
exploded_node *enode;
FOR_EACH_VEC_ELT (m_functionless_enodes, i, enode)
enode->dump_dot (gv, args);
/* Dump m_map, sorting it to avoid churn when comparing dumps. */
auto_vec<function_call_string_cluster *> child_clusters (m_map.elements ());
for (map_t::iterator iter = m_map.begin ();
iter != m_map.end ();
++iter)
child_clusters.quick_push ((*iter).second);
child_clusters.qsort (function_call_string_cluster::cmp_ptr_ptr);
function_call_string_cluster *child_cluster;
FOR_EACH_VEC_ELT (child_clusters, i, child_cluster)
child_cluster->dump_dot (gv, args);
}
void add_node (exploded_node *en) final override
{
function *fun = en->get_function ();
if (!fun)
{
m_functionless_enodes.safe_push (en);
return;
}
const call_string &cs = en->get_point ().get_call_string ();
function_call_string key (fun, &cs);
function_call_string_cluster **slot = m_map.get (key);
if (slot)
(*slot)->add_node (en);
else
{
function_call_string_cluster *child
= new function_call_string_cluster (fun, cs);
m_map.put (key, child);
child->add_node (en);
}
}
private:
typedef hash_map<function_call_string, function_call_string_cluster *> map_t;
map_t m_map;
/* This should just be the origin exploded_node. */
auto_vec <exploded_node *> m_functionless_enodes;
};
/* Subclass of range_label for use within
exploded_graph::dump_exploded_nodes for implementing
-fdump-analyzer-exploded-nodes: a label for a specific
exploded_node. */
class enode_label : public range_label
{
public:
enode_label (const extrinsic_state &ext_state,
exploded_node *enode)
: m_ext_state (ext_state), m_enode (enode) {}
label_text get_text (unsigned) const final override
{
pretty_printer pp;
pp_format_decoder (&pp) = default_tree_printer;
m_enode->get_state ().dump_to_pp (m_ext_state, true, false, &pp);
return make_label_text (false, "EN: %i: %s",
m_enode->m_index, pp_formatted_text (&pp));
}
private:
const extrinsic_state &m_ext_state;
exploded_node *m_enode;
};
/* Postprocessing support for dumping the exploded nodes.
Handle -fdump-analyzer-exploded-nodes,
-fdump-analyzer-exploded-nodes-2, and the
"__analyzer_dump_exploded_nodes" builtin. */
void
exploded_graph::dump_exploded_nodes () const
{
// TODO
/* Locate calls to __analyzer_dump_exploded_nodes. */
// Print how many egs there are for them?
/* Better: log them as we go, and record the exploded nodes
in question. */
/* Show every enode. */
/* Gather them by stmt, so that we can more clearly see the
"hotspots" requiring numerous exploded nodes. */
/* Alternatively, simply throw them all into one big rich_location
and see if the label-printing will sort it out...
This requires them all to be in the same source file. */
if (flag_dump_analyzer_exploded_nodes)
{
auto_timevar tv (TV_ANALYZER_DUMP);
gcc_rich_location richloc (UNKNOWN_LOCATION);
unsigned i;
exploded_node *enode;
FOR_EACH_VEC_ELT (m_nodes, i, enode)
{
if (const gimple *stmt = enode->get_stmt ())
{
if (get_pure_location (richloc.get_loc ()) == UNKNOWN_LOCATION)
richloc.set_range (0, stmt->location, SHOW_RANGE_WITH_CARET);
else
richloc.add_range (stmt->location,
SHOW_RANGE_WITHOUT_CARET,
new enode_label (m_ext_state, enode));
}
}
warning_at (&richloc, 0, "%i exploded nodes", m_nodes.length ());
/* Repeat the warning without all the labels, so that message is visible
(the other one may well have scrolled past the terminal limit). */
warning_at (richloc.get_loc (), 0,
"%i exploded nodes", m_nodes.length ());
if (m_worklist.length () > 0)
warning_at (richloc.get_loc (), 0,
"worklist still contains %i nodes", m_worklist.length ());
}
/* Dump the egraph in textual form to a dump file. */
if (flag_dump_analyzer_exploded_nodes_2)
{
auto_timevar tv (TV_ANALYZER_DUMP);
char *filename
= concat (dump_base_name, ".eg.txt", NULL);
FILE *outf = fopen (filename, "w");
if (!outf)
error_at (UNKNOWN_LOCATION, "unable to open %qs for writing", filename);
free (filename);
fprintf (outf, "exploded graph for %s\n", dump_base_name);
fprintf (outf, " nodes: %i\n", m_nodes.length ());
fprintf (outf, " edges: %i\n", m_edges.length ());
unsigned i;
exploded_node *enode;
FOR_EACH_VEC_ELT (m_nodes, i, enode)
{
fprintf (outf, "\nEN %i:\n", enode->m_index);
enode->dump_succs_and_preds (outf);
pretty_printer pp;
enode->get_point ().print (&pp, format (true));
fprintf (outf, "%s\n", pp_formatted_text (&pp));
enode->get_state ().dump_to_file (m_ext_state, false, true, outf);
}
fclose (outf);
}
/* Dump the egraph in textual form to multiple dump files, one per enode. */
if (flag_dump_analyzer_exploded_nodes_3)
{
auto_timevar tv (TV_ANALYZER_DUMP);
unsigned i;
exploded_node *enode;
FOR_EACH_VEC_ELT (m_nodes, i, enode)
{
char *filename
= xasprintf ("%s.en-%i.txt", dump_base_name, i);
FILE *outf = fopen (filename, "w");
if (!outf)
error_at (UNKNOWN_LOCATION, "unable to open %qs for writing", filename);
free (filename);
fprintf (outf, "EN %i:\n", enode->m_index);
enode->dump_succs_and_preds (outf);
pretty_printer pp;
enode->get_point ().print (&pp, format (true));
fprintf (outf, "%s\n", pp_formatted_text (&pp));
enode->get_state ().dump_to_file (m_ext_state, false, true, outf);
fclose (outf);
}
}
/* Emit a warning at any call to "__analyzer_dump_exploded_nodes",
giving the number of processed exploded nodes for "before-stmt",
and the IDs of processed, merger, and worklist enodes.
We highlight the count of *processed* enodes since this is of most
interest in DejaGnu tests for ensuring that state merger has
happened.
We don't show the count of merger and worklist enodes, as this is
more of an implementation detail of the merging/worklist that we
don't want to bake into our expected DejaGnu messages. */
unsigned i;
exploded_node *enode;
hash_set<const gimple *> seen;
FOR_EACH_VEC_ELT (m_nodes, i, enode)
{
if (enode->get_point ().get_kind () != PK_BEFORE_STMT)
continue;
if (const gimple *stmt = enode->get_stmt ())
if (const gcall *call = dyn_cast <const gcall *> (stmt))
if (is_special_named_call_p (call, "__analyzer_dump_exploded_nodes",
1))
{
if (seen.contains (stmt))
continue;
auto_vec<exploded_node *> processed_enodes;
auto_vec<exploded_node *> merger_enodes;
auto_vec<exploded_node *> worklist_enodes;
/* This is O(N^2). */
unsigned j;
exploded_node *other_enode;
FOR_EACH_VEC_ELT (m_nodes, j, other_enode)
{
if (other_enode->get_point ().get_kind () != PK_BEFORE_STMT)
continue;
if (other_enode->get_stmt () == stmt)
switch (other_enode->get_status ())
{
default:
gcc_unreachable ();
case exploded_node::STATUS_WORKLIST:
worklist_enodes.safe_push (other_enode);
break;
case exploded_node::STATUS_PROCESSED:
processed_enodes.safe_push (other_enode);
break;
case exploded_node::STATUS_MERGER:
merger_enodes.safe_push (other_enode);
break;
}
}
pretty_printer pp;
pp_character (&pp, '[');
print_enode_indices (&pp, processed_enodes);
if (merger_enodes.length () > 0)
{
pp_string (&pp, "] merger(s): [");
print_enode_indices (&pp, merger_enodes);
}
if (worklist_enodes.length () > 0)
{
pp_string (&pp, "] worklist: [");
print_enode_indices (&pp, worklist_enodes);
}
pp_character (&pp, ']');
warning_n (stmt->location, 0, processed_enodes.length (),
"%i processed enode: %s",
"%i processed enodes: %s",
processed_enodes.length (), pp_formatted_text (&pp));
seen.add (stmt);
/* If the argument is non-zero, then print all of the states
of the various enodes. */
tree t_arg = fold (gimple_call_arg (call, 0));
if (TREE_CODE (t_arg) != INTEGER_CST)
{
error_at (call->location,
"integer constant required for arg 1");
return;
}
int i_arg = TREE_INT_CST_LOW (t_arg);
if (i_arg)
{
exploded_node *other_enode;
FOR_EACH_VEC_ELT (processed_enodes, j, other_enode)
{
fprintf (stderr, "%i of %i: EN %i:\n",
j + 1, processed_enodes.length (),
other_enode->m_index);
other_enode->dump_succs_and_preds (stderr);
/* Dump state. */
other_enode->get_state ().dump (m_ext_state, false);
}
}
}
}
}
DEBUG_FUNCTION exploded_node *
exploded_graph::get_node_by_index (int idx) const
{
exploded_node *enode = m_nodes[idx];
gcc_assert (enode->m_index == idx);
return enode;
}
/* Ensure that there is an exploded_node for a top-level call to FNDECL. */
void
exploded_graph::on_escaped_function (tree fndecl)
{
logger * const logger = get_logger ();
LOG_FUNC_1 (logger, "%qE", fndecl);
cgraph_node *cgnode = cgraph_node::get (fndecl);
if (!cgnode)
return;
function *fun = cgnode->get_fun ();
if (!fun)
return;
if (!gimple_has_body_p (fndecl))
return;
exploded_node *enode = add_function_entry (*fun);
if (logger)
{
if (enode)
logger->log ("created EN %i for %qE entrypoint",
enode->m_index, fun->decl);
else
logger->log ("did not create enode for %qE entrypoint", fun->decl);
}
}
/* A collection of classes for visualizing the callgraph in .dot form
(as represented in the supergraph). */
/* Forward decls. */
class viz_callgraph_node;
class viz_callgraph_edge;
class viz_callgraph;
class viz_callgraph_cluster;
/* Traits for using "digraph.h" to visualize the callgraph. */
struct viz_callgraph_traits
{
typedef viz_callgraph_node node_t;
typedef viz_callgraph_edge edge_t;
typedef viz_callgraph graph_t;
struct dump_args_t
{
dump_args_t (const exploded_graph *eg) : m_eg (eg) {}
const exploded_graph *m_eg;
};
typedef viz_callgraph_cluster cluster_t;
};
/* Subclass of dnode representing a function within the callgraph. */
class viz_callgraph_node : public dnode<viz_callgraph_traits>
{
friend class viz_callgraph;
public:
viz_callgraph_node (function *fun, int index)
: m_fun (fun), m_index (index), m_num_supernodes (0), m_num_superedges (0)
{
gcc_assert (fun);
}
void dump_dot (graphviz_out *gv, const dump_args_t &args) const final override
{
pretty_printer *pp = gv->get_pp ();
dump_dot_id (pp);
pp_printf (pp, " [shape=none,margin=0,style=filled,fillcolor=%s,label=\"",
"lightgrey");
pp_write_text_to_stream (pp);
pp_printf (pp, "VCG: %i: %s", m_index, function_name (m_fun));
pp_newline (pp);
pp_printf (pp, "supernodes: %i\n", m_num_supernodes);
pp_newline (pp);
pp_printf (pp, "superedges: %i\n", m_num_superedges);
pp_newline (pp);
if (args.m_eg)
{
unsigned i;
exploded_node *enode;
unsigned num_enodes = 0;
FOR_EACH_VEC_ELT (args.m_eg->m_nodes, i, enode)
{
if (enode->get_point ().get_function () == m_fun)
num_enodes++;
}
pp_printf (pp, "enodes: %i\n", num_enodes);
pp_newline (pp);
// TODO: also show the per-callstring breakdown
const exploded_graph::call_string_data_map_t *per_cs_data
= args.m_eg->get_per_call_string_data ();
for (exploded_graph::call_string_data_map_t::iterator iter
= per_cs_data->begin ();
iter != per_cs_data->end ();
++iter)
{
const call_string *cs = (*iter).first;
//per_call_string_data *data = (*iter).second;
num_enodes = 0;
FOR_EACH_VEC_ELT (args.m_eg->m_nodes, i, enode)
{
if (enode->get_point ().get_function () == m_fun
&& &enode->get_point ().get_call_string () == cs)
num_enodes++;
}
if (num_enodes > 0)
{
cs->print (pp);
pp_printf (pp, ": %i\n", num_enodes);
}
}
/* Show any summaries. */
per_function_data *data = args.m_eg->get_per_function_data (m_fun);
if (data)
{
pp_newline (pp);
pp_printf (pp, "summaries: %i\n", data->m_summaries.length ());
for (auto summary : data->m_summaries)
{
pp_printf (pp, "\nsummary: %s:\n", summary->get_desc ().get ());
const extrinsic_state &ext_state = args.m_eg->get_ext_state ();
const program_state &state = summary->get_state ();
state.dump_to_pp (ext_state, false, true, pp);
pp_newline (pp);
}
}
}
pp_write_text_as_dot_label_to_stream (pp, /*for_record=*/true);
pp_string (pp, "\"];\n\n");
pp_flush (pp);
}
void dump_dot_id (pretty_printer *pp) const
{
pp_printf (pp, "vcg_%i", m_index);
}
private:
function *m_fun;
int m_index;
int m_num_supernodes;
int m_num_superedges;
};
/* Subclass of dedge representing a callgraph edge. */
class viz_callgraph_edge : public dedge<viz_callgraph_traits>
{
public:
viz_callgraph_edge (viz_callgraph_node *src, viz_callgraph_node *dest)
: dedge<viz_callgraph_traits> (src, dest)
{}
void dump_dot (graphviz_out *gv, const dump_args_t &) const
final override
{
pretty_printer *pp = gv->get_pp ();
const char *style = "\"solid,bold\"";
const char *color = "black";
int weight = 10;
const char *constraint = "true";
m_src->dump_dot_id (pp);
pp_string (pp, " -> ");
m_dest->dump_dot_id (pp);
pp_printf (pp,
(" [style=%s, color=%s, weight=%d, constraint=%s,"
" headlabel=\""),
style, color, weight, constraint);
pp_printf (pp, "\"];\n");
}
};
/* Subclass of digraph representing the callgraph. */
class viz_callgraph : public digraph<viz_callgraph_traits>
{
public:
viz_callgraph (const supergraph &sg);
viz_callgraph_node *get_vcg_node_for_function (function *fun)
{
return *m_map.get (fun);
}
viz_callgraph_node *get_vcg_node_for_snode (supernode *snode)
{
return get_vcg_node_for_function (snode->m_fun);
}
private:
hash_map<function *, viz_callgraph_node *> m_map;
};
/* Placeholder subclass of cluster. */
class viz_callgraph_cluster : public cluster<viz_callgraph_traits>
{
};
/* viz_callgraph's ctor. */
viz_callgraph::viz_callgraph (const supergraph &sg)
{
cgraph_node *node;
FOR_EACH_FUNCTION_WITH_GIMPLE_BODY (node)
{
function *fun = node->get_fun ();
viz_callgraph_node *vcg_node
= new viz_callgraph_node (fun, m_nodes.length ());
m_map.put (fun, vcg_node);
add_node (vcg_node);
}
unsigned i;
superedge *sedge;
FOR_EACH_VEC_ELT (sg.m_edges, i, sedge)
{
viz_callgraph_node *vcg_src = get_vcg_node_for_snode (sedge->m_src);
if (vcg_src->m_fun)
get_vcg_node_for_function (vcg_src->m_fun)->m_num_superedges++;
if (sedge->dyn_cast_call_superedge ())
{
viz_callgraph_node *vcg_dest = get_vcg_node_for_snode (sedge->m_dest);
viz_callgraph_edge *vcg_edge
= new viz_callgraph_edge (vcg_src, vcg_dest);
add_edge (vcg_edge);
}
}
supernode *snode;
FOR_EACH_VEC_ELT (sg.m_nodes, i, snode)
{
if (snode->m_fun)
get_vcg_node_for_function (snode->m_fun)->m_num_supernodes++;
}
}
/* Dump the callgraph to FILENAME. */
static void
dump_callgraph (const supergraph &sg, const char *filename,
const exploded_graph *eg)
{
FILE *outf = fopen (filename, "w");
if (!outf)
return;
// TODO
viz_callgraph vcg (sg);
vcg.dump_dot (filename, NULL, viz_callgraph_traits::dump_args_t (eg));
fclose (outf);
}
/* Dump the callgraph to "<srcfile>.callgraph.dot". */
static void
dump_callgraph (const supergraph &sg, const exploded_graph *eg)
{
auto_timevar tv (TV_ANALYZER_DUMP);
char *filename = concat (dump_base_name, ".callgraph.dot", NULL);
dump_callgraph (sg, filename, eg);
free (filename);
}
/* Subclass of dot_annotator for implementing
DUMP_BASE_NAME.supergraph-eg.dot, a post-analysis dump of the supergraph.
Annotate the supergraph nodes by printing the exploded nodes in concise
form within them, next to their pertinent statements where appropriate,
colorizing the exploded nodes based on sm-state.
Also show saved diagnostics within the exploded nodes, giving information
on whether they were feasible, and, if infeasible, where the problem
was. */
class exploded_graph_annotator : public dot_annotator
{
public:
exploded_graph_annotator (const exploded_graph &eg)
: m_eg (eg)
{
/* Avoid O(N^2) by prepopulating m_enodes_per_snodes. */
unsigned i;
supernode *snode;
FOR_EACH_VEC_ELT (eg.get_supergraph ().m_nodes, i, snode)
m_enodes_per_snodes.safe_push (new auto_vec <exploded_node *> ());
exploded_node *enode;
FOR_EACH_VEC_ELT (m_eg.m_nodes, i, enode)
if (enode->get_supernode ())
m_enodes_per_snodes[enode->get_supernode ()->m_index]->safe_push (enode);
}
/* Show exploded nodes for BEFORE_SUPERNODE points before N. */
bool add_node_annotations (graphviz_out *gv, const supernode &n,
bool within_table)
const final override
{
if (!within_table)
return false;
gv->begin_tr ();
pretty_printer *pp = gv->get_pp ();
gv->begin_td ();
pp_string (pp, "BEFORE");
pp_printf (pp, " (scc: %i)", m_eg.get_scc_id (n));
gv->end_td ();
unsigned i;
exploded_node *enode;
bool had_enode = false;
FOR_EACH_VEC_ELT (*m_enodes_per_snodes[n.m_index], i, enode)
{
gcc_assert (enode->get_supernode () == &n);
const program_point &point = enode->get_point ();
if (point.get_kind () != PK_BEFORE_SUPERNODE)
continue;
print_enode (gv, enode);
had_enode = true;
}
if (!had_enode)
pp_string (pp, "<TD BGCOLOR=\"red\">UNREACHED</TD>");
pp_flush (pp);
gv->end_tr ();
return true;
}
/* Show exploded nodes for STMT. */
void add_stmt_annotations (graphviz_out *gv, const gimple *stmt,
bool within_row)
const final override
{
if (!within_row)
return;
pretty_printer *pp = gv->get_pp ();
const supernode *snode
= m_eg.get_supergraph ().get_supernode_for_stmt (stmt);
unsigned i;
exploded_node *enode;
bool had_td = false;
FOR_EACH_VEC_ELT (*m_enodes_per_snodes[snode->m_index], i, enode)
{
const program_point &point = enode->get_point ();
if (point.get_kind () != PK_BEFORE_STMT)
continue;
if (point.get_stmt () != stmt)
continue;
print_enode (gv, enode);
had_td = true;
}
pp_flush (pp);
if (!had_td)
{
gv->begin_td ();
gv->end_td ();
}
}
/* Show exploded nodes for AFTER_SUPERNODE points after N. */
bool add_after_node_annotations (graphviz_out *gv, const supernode &n)
const final override
{
gv->begin_tr ();
pretty_printer *pp = gv->get_pp ();
gv->begin_td ();
pp_string (pp, "AFTER");
gv->end_td ();
unsigned i;
exploded_node *enode;
FOR_EACH_VEC_ELT (*m_enodes_per_snodes[n.m_index], i, enode)
{
gcc_assert (enode->get_supernode () == &n);
const program_point &point = enode->get_point ();
if (point.get_kind () != PK_AFTER_SUPERNODE)
continue;
print_enode (gv, enode);
}
pp_flush (pp);
gv->end_tr ();
return true;
}
private:
/* Concisely print a TD element for ENODE, showing the index, status,
and any saved_diagnostics at the enode. Colorize it to show sm-state.
Ideally we'd dump ENODE's state here, hidden behind some kind of
interactive disclosure method like a tooltip, so that the states
can be explored without overwhelming the graph.
However, I wasn't able to get graphviz/xdot to show tooltips on
individual elements within a HTML-like label. */
void print_enode (graphviz_out *gv, const exploded_node *enode) const
{
pretty_printer *pp = gv->get_pp ();
pp_printf (pp, "<TD BGCOLOR=\"%s\">",
enode->get_dot_fillcolor ());
pp_printf (pp, "<TABLE BORDER=\"0\">");
gv->begin_trtd ();
pp_printf (pp, "EN: %i", enode->m_index);
switch (enode->get_status ())
{
default:
gcc_unreachable ();
case exploded_node::STATUS_WORKLIST:
pp_string (pp, "(W)");
break;
case exploded_node::STATUS_PROCESSED:
break;
case exploded_node::STATUS_MERGER:
pp_string (pp, "(M)");
break;
case exploded_node::STATUS_BULK_MERGED:
pp_string (pp, "(BM)");
break;
}
gv->end_tdtr ();
/* Dump any saved_diagnostics at this enode. */
for (unsigned i = 0; i < enode->get_num_diagnostics (); i++)
{
const saved_diagnostic *sd = enode->get_saved_diagnostic (i);
print_saved_diagnostic (gv, sd);
}
pp_printf (pp, "</TABLE>");
pp_printf (pp, "</TD>");
}
/* Print a TABLE element for SD, showing the kind, the length of the
exploded_path, whether the path was feasible, and if infeasible,
what the problem was. */
void print_saved_diagnostic (graphviz_out *gv,
const saved_diagnostic *sd) const
{
pretty_printer *pp = gv->get_pp ();
gv->begin_trtd ();
pp_printf (pp, "<TABLE BORDER=\"0\">");
gv->begin_tr ();
pp_string (pp, "<TD BGCOLOR=\"green\">");
pp_printf (pp, "DIAGNOSTIC: %s", sd->m_d->get_kind ());
gv->end_tdtr ();
gv->begin_trtd ();
if (sd->get_best_epath ())
pp_printf (pp, "epath length: %i", sd->get_epath_length ());
else
pp_printf (pp, "no best epath");
gv->end_tdtr ();
if (const feasibility_problem *p = sd->get_feasibility_problem ())
{
gv->begin_trtd ();
pp_printf (pp, "INFEASIBLE at eedge %i: EN:%i -> EN:%i",
p->m_eedge_idx,
p->m_eedge.m_src->m_index,
p->m_eedge.m_dest->m_index);
pp_write_text_as_html_like_dot_to_stream (pp);
gv->end_tdtr ();
gv->begin_trtd ();
p->m_eedge.m_sedge->dump (pp);
pp_write_text_as_html_like_dot_to_stream (pp);
gv->end_tdtr ();
gv->begin_trtd ();
pp_gimple_stmt_1 (pp, p->m_last_stmt, 0, (dump_flags_t)0);
pp_write_text_as_html_like_dot_to_stream (pp);
gv->end_tdtr ();
/* Ideally we'd print p->m_model here; see the notes above about
tooltips. */
}
pp_printf (pp, "</TABLE>");
gv->end_tdtr ();
}
const exploded_graph &m_eg;
auto_delete_vec<auto_vec <exploded_node *> > m_enodes_per_snodes;
};
/* Implement -fdump-analyzer-json. */
static void
dump_analyzer_json (const supergraph &sg,
const exploded_graph &eg)
{
auto_timevar tv (TV_ANALYZER_DUMP);
char *filename = concat (dump_base_name, ".analyzer.json.gz", NULL);
gzFile output = gzopen (filename, "w");
if (!output)
{
error_at (UNKNOWN_LOCATION, "unable to open %qs for writing", filename);
free (filename);
return;
}
json::object *toplev_obj = new json::object ();
toplev_obj->set ("sgraph", sg.to_json ());
toplev_obj->set ("egraph", eg.to_json ());
pretty_printer pp;
toplev_obj->print (&pp, flag_diagnostics_json_formatting);
pp_formatted_text (&pp);
delete toplev_obj;
if (gzputs (output, pp_formatted_text (&pp)) == EOF
|| gzclose (output))
error_at (UNKNOWN_LOCATION, "error writing %qs", filename);
free (filename);
}
/* Concrete subclass of plugin_analyzer_init_iface, allowing plugins
to register new state machines. */
class plugin_analyzer_init_impl : public plugin_analyzer_init_iface
{
public:
plugin_analyzer_init_impl (auto_delete_vec <state_machine> *checkers,
known_function_manager *known_fn_mgr,
logger *logger)
: m_checkers (checkers),
m_known_fn_mgr (known_fn_mgr),
m_logger (logger)
{}
void register_state_machine (std::unique_ptr<state_machine> sm) final override
{
LOG_SCOPE (m_logger);
m_checkers->safe_push (sm.release ());
}
void register_known_function (const char *name,
std::unique_ptr<known_function> kf) final override
{
LOG_SCOPE (m_logger);
m_known_fn_mgr->add (name, std::move (kf));
}
logger *get_logger () const final override
{
return m_logger;
}
private:
auto_delete_vec <state_machine> *m_checkers;
known_function_manager *m_known_fn_mgr;
logger *m_logger;
};
/* Run the analysis "engine". */
void
impl_run_checkers (logger *logger)
{
LOG_SCOPE (logger);
if (logger)
{
logger->log ("BITS_BIG_ENDIAN: %i", BITS_BIG_ENDIAN ? 1 : 0);
logger->log ("BYTES_BIG_ENDIAN: %i", BYTES_BIG_ENDIAN ? 1 : 0);
logger->log ("WORDS_BIG_ENDIAN: %i", WORDS_BIG_ENDIAN ? 1 : 0);
log_stashed_constants (logger);
}
/* If using LTO, ensure that the cgraph nodes have function bodies. */
cgraph_node *node;
FOR_EACH_FUNCTION_WITH_GIMPLE_BODY (node)
node->get_untransformed_body ();
/* Create the supergraph. */
supergraph sg (logger);
engine eng (&sg, logger);
state_purge_map *purge_map = NULL;
if (flag_analyzer_state_purge)
purge_map = new state_purge_map (sg, eng.get_model_manager (), logger);
if (flag_dump_analyzer_supergraph)
{
/* Dump supergraph pre-analysis. */
auto_timevar tv (TV_ANALYZER_DUMP);
char *filename = concat (dump_base_name, ".supergraph.dot", NULL);
supergraph::dump_args_t args ((enum supergraph_dot_flags)0, NULL);
sg.dump_dot (filename, args);
free (filename);
}
if (flag_dump_analyzer_state_purge)
{
auto_timevar tv (TV_ANALYZER_DUMP);
state_purge_annotator a (purge_map);
char *filename = concat (dump_base_name, ".state-purge.dot", NULL);
supergraph::dump_args_t args ((enum supergraph_dot_flags)0, &a);
sg.dump_dot (filename, args);
free (filename);
}
auto_delete_vec <state_machine> checkers;
make_checkers (checkers, logger);
register_known_functions (*eng.get_known_function_manager (),
*eng.get_model_manager ());
plugin_analyzer_init_impl data (&checkers,
eng.get_known_function_manager (),
logger);
invoke_plugin_callbacks (PLUGIN_ANALYZER_INIT, &data);
if (logger)
{
int i;
state_machine *sm;
FOR_EACH_VEC_ELT (checkers, i, sm)
logger->log ("checkers[%i]: %s", i, sm->get_name ());
}
/* Extrinsic state shared by nodes in the graph. */
const extrinsic_state ext_state (checkers, &eng, logger);
const analysis_plan plan (sg, logger);
/* The exploded graph. */
exploded_graph eg (sg, logger, ext_state, purge_map, plan,
analyzer_verbosity);
/* Add entrypoints to the graph for externally-callable functions. */
eg.build_initial_worklist ();
/* Now process the worklist, exploring the <point, state> graph. */
eg.process_worklist ();
if (warn_analyzer_infinite_loop)
eg.detect_infinite_loops ();
if (flag_dump_analyzer_exploded_graph)
{
auto_timevar tv (TV_ANALYZER_DUMP);
char *filename
= concat (dump_base_name, ".eg.dot", NULL);
exploded_graph::dump_args_t args (eg);
root_cluster c;
eg.dump_dot (filename, &c, args);
free (filename);
}
/* Now emit any saved diagnostics. */
eg.get_diagnostic_manager ().emit_saved_diagnostics (eg);
eg.dump_exploded_nodes ();
eg.log_stats ();
if (flag_dump_analyzer_callgraph)
dump_callgraph (sg, &eg);
if (flag_dump_analyzer_supergraph)
{
/* Dump post-analysis form of supergraph. */
auto_timevar tv (TV_ANALYZER_DUMP);
char *filename = concat (dump_base_name, ".supergraph-eg.dot", NULL);
exploded_graph_annotator a (eg);
supergraph::dump_args_t args ((enum supergraph_dot_flags)0, &a);
sg.dump_dot (filename, args);
free (filename);
}
if (flag_dump_analyzer_json)
dump_analyzer_json (sg, eg);
if (flag_dump_analyzer_untracked)
eng.get_model_manager ()->dump_untracked_regions ();
delete purge_map;
/* Free up any dominance info that we may have created. */
FOR_EACH_FUNCTION_WITH_GIMPLE_BODY (node)
{
function *fun = node->get_fun ();
free_dominance_info (fun, CDI_DOMINATORS);
}
}
/* Handle -fdump-analyzer and -fdump-analyzer-stderr. */
static FILE *dump_fout = NULL;
/* Track if we're responsible for closing dump_fout. */
static bool owns_dump_fout = false;
/* If dumping is enabled, attempt to create dump_fout if it hasn't already
been opened. Return it. */
FILE *
get_or_create_any_logfile ()
{
if (!dump_fout)
{
if (flag_dump_analyzer_stderr)
dump_fout = stderr;
else if (flag_dump_analyzer)
{
char *dump_filename = concat (dump_base_name, ".analyzer.txt", NULL);
dump_fout = fopen (dump_filename, "w");
free (dump_filename);
if (dump_fout)
owns_dump_fout = true;
}
}
return dump_fout;
}
/* External entrypoint to the analysis "engine".
Set up any dumps, then call impl_run_checkers. */
void
run_checkers ()
{
/* Save input_location. */
location_t saved_input_location = input_location;
{
log_user the_logger (NULL);
get_or_create_any_logfile ();
if (dump_fout)
the_logger.set_logger (new logger (dump_fout, 0, 0,
*global_dc->printer));
LOG_SCOPE (the_logger.get_logger ());
impl_run_checkers (the_logger.get_logger ());
/* end of lifetime of the_logger (so that dump file is closed after the
various dtors run). */
}
if (owns_dump_fout)
{
fclose (dump_fout);
owns_dump_fout = false;
dump_fout = NULL;
}
/* Restore input_location. Subsequent passes may assume that input_location
is some arbitrary value *not* in the block tree, which might be violated
if we didn't restore it. */
input_location = saved_input_location;
}
} // namespace ana
#endif /* #if ENABLE_ANALYZER */
|