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
|
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
/**
* @brief Wrapper class for ScriptMyILGen to do simple optimizations.
* The main one is to figure out which locals are active at the labels
* so the stack capture/restore code doesn't have to do everything.
* Second is it removes unnecessary back-to-back stloc/ldloc's.
*/
namespace OpenSim.Region.ScriptEngine.Yengine
{
/**
* @brief This is a list that keeps track of types pushed on the evaluation stack.
*/
public class StackDepth: List<Type>
{
public List<bool> isBoxeds = new List<bool>();
/**
* @brief Clear both stacks.
*/
public new void Clear()
{
base.Clear();
isBoxeds.Clear();
}
/**
* @brief Pop call parameters and validate the types.
*/
public void Pop(ParameterInfo[] pis)
{
int n = pis.Length;
int c = this.Count;
if(n > c)
throw new Exception("stack going negative");
for(int i = n; --i >= 0;)
{
--c;
ExpectedVsOnStack(pis[i].ParameterType, this[c], isBoxeds[c]);
}
Pop(n);
}
/**
* @brief Pop values and validate the types.
*/
public void Pop(Type[] ts)
{
int n = ts.Length;
int c = this.Count;
if(n > c)
throw new Exception("stack going negative");
for(int i = ts.Length; --i >= 0;)
{
--c;
ExpectedVsOnStack(ts[i], this[c], isBoxeds[c]);
}
Pop(n);
}
/**
* @brief Pop a single value and validate the type.
*/
public void Pop(Type t)
{
int c = this.Count;
if(c < 1)
throw new Exception("stack going negative");
ExpectedVsOnStack(t, this[c - 1], isBoxeds[c - 1]);
Pop(1);
}
/**
* @brief Pop a single value and validate that it is a numeric type.
*/
public Type PopNumVal()
{
int c = this.Count;
if(c < 1)
throw new Exception("stack going negative");
Type st = this[--c];
if(st == null)
{
throw new Exception("stack has null, expecting a numeric");
}
if(isBoxeds[c])
{
throw new Exception("stack is boxed " + st.Name + ", expecting a numeric");
}
if((st != typeof(bool)) && (st != typeof(char)) && (st != typeof(int)) &&
(st != typeof(long)) && (st != typeof(float)) && (st != typeof(double)))
{
throw new Exception("stack has " + st.Name + ", expecting a numeric");
}
return Pop(1);
}
/**
* @brief Pop a single value and validate that it is a reference type
*/
public Type PopRef()
{
int c = this.Count;
if(c < 1)
throw new Exception("stack going negative");
Type st = this[--c];
if((st != null) && !isBoxeds[c] && st.IsValueType)
{
throw new Exception("stack has " + st.Name + ", expecting a ref type");
}
return Pop(1);
}
/**
* @brief Pop a single value and validate that it is a value type
*/
public Type PopValue()
{
int c = this.Count;
if(c < 1)
throw new Exception("stack going negative");
Type st = this[--c];
if(st == null)
{
throw new Exception("stack has null, expecting a value type");
}
if(!st.IsValueType)
{
throw new Exception("stack has " + st.Name + ", expecting a value type");
}
if(isBoxeds[c])
{
throw new Exception("stack has boxed " + st.Name + ", expecting an unboxed value type");
}
return Pop(1);
}
// ex = what is expected to be on stack
// st = what is actually on stack (null for ldnull)
// stBoxed = stack value is boxed
public static void ExpectedVsOnStack(Type ex, Type st, bool stBoxed)
{
// ldnull pushed on stack can go into any pointer type
if(st == null)
{
if(ex.IsByRef || ex.IsPointer || ex.IsClass || ex.IsInterface)
return;
throw new Exception("stack has null, expect " + ex.Name);
}
// simple case of expecting an object
// ...so the stack can have object,string, etc
// but we cant allow int = boxed int here
if(ex.IsAssignableFrom(st) && !stBoxed)
return;
// case of expecting an enum on the stack
// but all the CIL code knows about are ints etc
// so convert the Enum type to integer or whatever
// and that should be assignable from what's on stack
if(ex.IsEnum && typeof(int).IsAssignableFrom(st))
return;
// bool, char, int are interchangeable on the stack
if((ex == typeof(bool) || ex == typeof(char) || ex == typeof(int)) &&
(st == typeof(bool) || st == typeof(char) || st == typeof(int)))
return;
// float and double are interchangeable on the stack
if((ex == typeof(float) || ex == typeof(double)) &&
(st == typeof(float) || st == typeof(double)))
return;
// object can accept any boxed type
if((ex == typeof(object)) && stBoxed)
return;
// otherwise, it is disallowed
throw new Exception("stack has " + StackTypeString(st, stBoxed) + ", expect " + ex.Name);
}
/**
* @brief Pop values without any validation.
*/
public Type Pop(int n)
{
if(this.Count != isBoxeds.Count)
throw new Exception("isBoxeds count bad");
Type lastPopped = null;
int c = this.Count;
if(n > c)
throw new Exception("stack going negative");
if(n > 0)
{
lastPopped = this[c - n];
this.RemoveRange(c - n, n);
isBoxeds.RemoveRange(c - n, n);
}
if(this.Count != isBoxeds.Count)
throw new Exception("isBoxeds count bad");
return lastPopped;
}
/**
* @brief Peek at the n'th stack value.
* n = 0 : top of stack
* 1 : next to top
* ...
*/
public Type Peek(int n)
{
int c = this.Count;
if(n > c - 1)
throw new Exception("stack going negative");
if(this.Count != isBoxeds.Count)
throw new Exception("isBoxeds count bad");
return this[c - n - 1];
}
public bool PeekBoxed(int n)
{
int c = isBoxeds.Count;
if(n > c - 1)
throw new Exception("stack going negative");
if(this.Count != isBoxeds.Count)
throw new Exception("isBoxeds count bad");
return isBoxeds[c - n - 1];
}
/**
* @brief Push a single value of the given type.
*/
public void Push(Type t)
{
Push(t, false);
}
public void Push(Type t, bool isBoxed)
{
if(this.Count != isBoxeds.Count)
throw new Exception("isBoxeds count bad");
this.Add(t);
isBoxeds.Add(isBoxed);
}
/**
* @brief See if the types at a given label exactly match those on the stack.
* We should have the stack types be the same no matter how we branched
* or fell through to a particular label.
*/
public void Matches(ScriptMyLabel label)
{
Type[] ts = label.stackDepth;
bool[] tsBoxeds = label.stackBoxeds;
int i;
if(this.Count != isBoxeds.Count)
throw new Exception("isBoxeds count bad");
if(ts == null)
{
label.stackDepth = this.ToArray();
label.stackBoxeds = isBoxeds.ToArray();
}
else if(ts.Length != this.Count)
{
throw new Exception("stack depth mismatch");
}
else
{
for(i = this.Count; --i >= 0;)
{
if(tsBoxeds[i] != this.isBoxeds[i])
goto mismatch;
if(ts[i] == this[i])
continue;
if((ts[i] == typeof(bool) || ts[i] == typeof(char) || ts[i] == typeof(int)) &&
(this[i] == typeof(bool) || this[i] == typeof(char) || this[i] == typeof(int)))
continue;
if((ts[i] == typeof(double) || ts[i] == typeof(float)) &&
(this[i] == typeof(double) || this[i] == typeof(float)))
continue;
goto mismatch;
}
}
return;
mismatch:
throw new Exception("stack type mismatch: " + StackTypeString(ts[i], tsBoxeds[i]) + " vs " + StackTypeString(this[i], this.isBoxeds[i]));
}
private static string StackTypeString(Type ts, bool isBoxed)
{
if(!isBoxed)
return ts.Name;
return "[" + ts.Name + "]";
}
}
/**
* @brief One of these per opcode and label in the function plus other misc markers.
* They form the CIL instruction stream of the function.
*/
public abstract class GraphNode
{
private static readonly bool DEBUG = false;
public const int OPINDENT = 4;
public const int OPDEBLEN = 12;
public ScriptCollector coll;
public GraphNodeBeginExceptionBlock tryBlock; // start of enclosing try block
// valid in the try section
// null in the catch/finally sections
// null outside of try block
// for the try node itself, links to outer try block
public GraphNodeBeginExceptionBlock excBlock; // start of enclosing try block
// valid in the try/catch/finally sections
// null outside of try/catch/finally block
// for the try node itself, links to outer try block
/*
* List of nodes in order as originally given.
*/
public GraphNode nextLin, prevLin;
public int linSeqNo;
/**
* @brief Save pointer to collector.
*/
public GraphNode(ScriptCollector coll)
{
this.coll = coll;
}
/**
* @brief Chain graph node to end of linear list.
*/
public virtual void ChainLin()
{
coll.lastLin.nextLin = this;
this.prevLin = coll.lastLin;
coll.lastLin = this;
this.tryBlock = coll.curTryBlock;
this.excBlock = coll.curExcBlock;
if(DEBUG)
{
StringBuilder sb = new StringBuilder("ChainLin*:");
sb.Append(coll.stackDepth.Count.ToString("D2"));
sb.Append(' ');
this.DebString(sb);
Console.WriteLine(sb.ToString());
}
}
/**
* @brief Append full info to debugging string for printing out the instruction.
*/
public void DebStringExt(StringBuilder sb)
{
int x = sb.Length;
sb.Append(this.linSeqNo.ToString().PadLeft(5));
sb.Append(": ");
this.DebString(sb);
if(this.ReadsLocal() != null)
ScriptCollector.PadToLength(sb, x + 60, " [read]");
if(this.WritesLocal() != null)
ScriptCollector.PadToLength(sb, x + 68, " [write]");
ScriptCollector.PadToLength(sb, x + 72, " ->");
bool first = true;
foreach(GraphNode nn in this.NextNodes)
{
if(first)
{
sb.Append(nn.linSeqNo.ToString().PadLeft(5));
first = false;
}
else
{
sb.Append(',');
sb.Append(nn.linSeqNo);
}
}
}
/**
* @brief See if it's possible for it to fall through to the next inline (nextLin) instruction.
*/
public virtual bool CanFallThrough()
{
return true;
}
/**
* @brief Append to debugging string for printing out the instruction.
*/
public abstract void DebString(StringBuilder sb);
public override string ToString()
{
StringBuilder sb = new StringBuilder();
this.DebString(sb);
return sb.ToString();
}
/**
* @brief See if this instruction reads a local variable.
*/
public virtual ScriptMyLocal ReadsLocal()
{
return null;
}
/**
* @brief See if this instruction writes a local variable.
*/
public virtual ScriptMyLocal WritesLocal()
{
return null;
}
/**
* @brief Write this instruction out to the wrapped object file.
*/
public abstract void WriteOutOne(ScriptMyILGen ilGen);
/**
* @brief Iterate through all the possible next nodes, including the next inline node, if any.
* The next inline code is excluded if the instruction never falls through, eg, return, unconditional branch.
* It includes a possible conditional branch to the beginning of the corresponding catch/finally of every
* instruction in a try section.
*/
private System.Collections.Generic.IEnumerable<GraphNode> nextNodes, nextNodesCatchFinally;
public System.Collections.Generic.IEnumerable<GraphNode> NextNodes
{
get
{
if(nextNodes == null)
{
nextNodes = GetNNEnumerable();
nextNodesCatchFinally = new NNEnumerableCatchFinally(this);
}
return nextNodesCatchFinally;
}
}
/**
* @brief This acts as a wrapper around all the other NNEnumerable's below.
* It assumes every instruction in a try { } can throw an exception so it
* says that every instruction in a try { } can conditionally branch to
* the beginning of the corresponding catch { } or finally { }.
*/
private class NNEnumerableCatchFinally: System.Collections.Generic.IEnumerable<GraphNode>
{
private GraphNode gn;
public NNEnumerableCatchFinally(GraphNode gn)
{
this.gn = gn;
}
System.Collections.Generic.IEnumerator<GraphNode> System.Collections.Generic.IEnumerable<GraphNode>.GetEnumerator()
{
return new NNEnumeratorCatchFinally(gn);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new NNEnumeratorCatchFinally(gn);
}
}
private class NNEnumeratorCatchFinally: NNEnumeratorBase
{
private GraphNode gn;
private int index = 0;
private System.Collections.Generic.IEnumerator<GraphNode> realEnumerator;
public NNEnumeratorCatchFinally(GraphNode gn)
{
this.gn = gn;
this.realEnumerator = gn.nextNodes.GetEnumerator();
}
public override bool MoveNext()
{
// First off, return any targets the instruction can come up with.
if(realEnumerator.MoveNext())
{
nn = realEnumerator.Current;
return true;
}
// Then if this instruction is in a try section, say this instruction
// can potentially branch to the beginning of the corresponding
// catch/finally.
if((index == 0) && (gn.tryBlock != null))
{
index++;
nn = gn.tryBlock.catchFinallyBlock;
return true;
}
// That's all we can do.
nn = null;
return false;
}
public override void Reset()
{
realEnumerator.Reset();
index = 0;
nn = null;
}
}
/**
* @brief This default iterator always returns the next inline node as the one-and-only next node.
* Other instructions need to override it if they can possibly do other than that.
*/
/**
* @brief GetNNEnumerable() gets the nextnode enumerable part of a GraphNode,
* which in turn gives the list of nodes that can possibly be next in
* a flow-control sense. It simply instantiates the NNEnumerator sub-
* class which does the actual enumeration.
*/
protected virtual System.Collections.Generic.IEnumerable<GraphNode> GetNNEnumerable()
{
return new NNEnumerable(this, typeof(NNEnumerator));
}
private class NNEnumerator: NNEnumeratorBase
{
private GraphNode gn;
private int index;
public NNEnumerator(GraphNode gn)
{
this.gn = gn;
}
public override bool MoveNext()
{
switch(index)
{
case 0:
{
index++;
nn = gn.nextLin;
return nn != null;
}
case 1:
{
nn = null;
return false;
}
}
throw new Exception();
}
public override void Reset()
{
index = 0;
nn = null;
}
}
}
/**
* @brief Things that derive from this are the beginning of a block.
* A block of code is that which begins with a label or is the beginning of all code
* and it contains no labels, ie, it can't be jumped into other than at its beginning.
*/
public abstract class GraphNodeBlock: GraphNode
{
public List<ScriptMyLocal> localsWrittenBeforeRead = new List<ScriptMyLocal>();
public List<ScriptMyLocal> localsReadBeforeWritten = new List<ScriptMyLocal>();
public int hasBeenResolved;
public GraphNodeBlock(ScriptCollector coll) : base(coll) { }
}
/**
* @brief This placeholder is at the beginning of the code so the first few instructions
* belong to some block.
*/
public class GraphNodeBegin: GraphNodeBlock
{
public GraphNodeBegin(ScriptCollector coll) : base(coll) { }
public override void DebString(StringBuilder sb)
{
sb.Append("begin");
}
public override void WriteOutOne(ScriptMyILGen ilGen)
{
}
}
/**
* @brief Beginning of try block.
*/
public class GraphNodeBeginExceptionBlock: GraphNodeBlock
{
public GraphNodeBeginExceptionBlock outerTryBlock; // next outer try opcode or null
public GraphNodeCatchFinallyBlock catchFinallyBlock; // start of associated catch or finally
public GraphNodeEndExceptionBlock endExcBlock; // end of associated catch or finally
public int excBlkSeqNo; // debugging
public GraphNodeBeginExceptionBlock(ScriptCollector coll) : base(coll)
{
}
public override void ChainLin()
{
base.ChainLin();
// we should always start try blocks with nothing on stack
// ...as CLI wipes stack for various conditions
if(coll.stackDepth.Count != 0)
{
throw new Exception("stack depth " + coll.stackDepth.Count);
}
}
public override void DebString(StringBuilder sb)
{
sb.Append(" beginexceptionblock_");
sb.Append(excBlkSeqNo);
}
public override void WriteOutOne(ScriptMyILGen ilGen)
{
ilGen.BeginExceptionBlock();
}
}
/**
* @brief Beginning of catch or finally block.
*/
public abstract class GraphNodeCatchFinallyBlock: GraphNodeBlock
{
public GraphNodeCatchFinallyBlock(ScriptCollector coll) : base(coll)
{
}
public override void ChainLin()
{
base.ChainLin();
// we should always start catch/finally blocks with nothing on stack
// ...as CLI wipes stack for various conditions
if(coll.stackDepth.Count != 0)
{
throw new Exception("stack depth " + coll.stackDepth.Count);
}
}
}
/**
* @brief Beginning of catch block.
*/
public class GraphNodeBeginCatchBlock: GraphNodeCatchFinallyBlock
{
public Type excType;
public GraphNodeBeginCatchBlock(ScriptCollector coll, Type excType) : base(coll)
{
this.excType = excType;
}
public override void ChainLin()
{
base.ChainLin();
// catch block always enters with one value on stack
if(coll.stackDepth.Count != 0)
{
throw new Exception("stack depth " + coll.stackDepth.Count);
}
coll.stackDepth.Push(excType);
}
public override void DebString(StringBuilder sb)
{
sb.Append(" begincatchblock_");
sb.Append(excBlock.excBlkSeqNo);
}
public override void WriteOutOne(ScriptMyILGen ilGen)
{
ilGen.BeginCatchBlock(excType);
}
/**
* @brief The beginning of every catch { } conditinally branches to the beginning
* of all outer catch { }s up to and including the next outer finally { }.
*/
protected override System.Collections.Generic.IEnumerable<GraphNode> GetNNEnumerable()
{
return new NNEnumerable(this, typeof(NNEnumerator));
}
private class NNEnumerator: NNEnumeratorBase
{
private GraphNodeBeginCatchBlock gn;
private int index;
public NNEnumerator(GraphNodeBeginCatchBlock gn)
{
this.gn = gn;
}
public override bool MoveNext()
{
while(true)
{
switch(index)
{
case 0:
{
// start with the fallthru
nn = gn.nextLin;
index++;
return true;
}
case 1:
{
// get the first outer catch { } or finally { }
// pretend we last returned beginning of this catch { }
// then loop back to get next outer catch { } or finally { }
nn = gn;
break;
}
case 2:
{
// nn points to a catch { } previously returned
// get the corresponding try { }
GraphNodeBeginExceptionBlock nntry = nn.excBlock;
// step out to next outer try { }
nntry = nntry.excBlock;
if(nntry == null)
break;
// return corresponding catch { } or finally { }
nn = nntry.catchFinallyBlock;
// if it's a finally { } we don't do anything after that
if(nn is GraphNodeBeginFinallyBlock)
index++;
return true;
}
case 3:
{
// we've returned the fallthru, catches and one finally
// so there's nothing more to say
nn = null;
return false;
}
default:
throw new Exception();
}
index++;
}
}
public override void Reset()
{
index = 0;
nn = null;
}
}
}
/**
* @brief Beginning of finally block.
*/
public class GraphNodeBeginFinallyBlock: GraphNodeCatchFinallyBlock
{
// leaveTargets has a list of all the targets of any contained
// leave instructions, ie, where an endfinally can possibly jump.
// But only those targets within the next outer finally { }, we
// don't contain any targets outside of that, those targets are
// stored in the actual finally that will jump to the target.
// The endfinally enumerator assumes that it is always possible
// for it to jump to the next outer finally (as would happen for
// an uncaught exception), so no need to do anything special.
public List<GraphNodeBlock> leaveTargets = new List<GraphNodeBlock>();
public GraphNodeBeginFinallyBlock(ScriptCollector coll) : base(coll)
{
}
public override void DebString(StringBuilder sb)
{
sb.Append(" beginfinallyblock_");
sb.Append(excBlock.excBlkSeqNo);
}
public override void WriteOutOne(ScriptMyILGen ilGen)
{
ilGen.BeginFinallyBlock();
}
}
/**
* @brief End of try/catch/finally block.
*/
public class GraphNodeEndExceptionBlock: GraphNode
{
public GraphNodeEndExceptionBlock(ScriptCollector coll) : base(coll)
{
}
public override void ChainLin()
{
base.ChainLin();
// we should always end exception blocks with nothing on stack
// ...as CLI wipes stack for various conditions
if(coll.stackDepth.Count != 0)
{
throw new Exception("stack depth " + coll.stackDepth.Count);
}
}
public override void DebString(StringBuilder sb)
{
sb.Append(" endexceptionblock_");
sb.Append(excBlock.excBlkSeqNo);
}
public override void WriteOutOne(ScriptMyILGen ilGen)
{
ilGen.EndExceptionBlock();
}
}
/**
* @brief Actual instruction emits...
*/
public abstract class GraphNodeEmit: GraphNode
{
public OpCode opcode;
public Token errorAt;
public GraphNodeEmit(ScriptCollector coll, Token errorAt, OpCode opcode) : base(coll)
{
this.opcode = opcode;
this.errorAt = errorAt;
}
public override void ChainLin()
{
base.ChainLin();
// compute resultant stack depth
int stack = coll.stackDepth.Count;
if((stack != 0) && ((opcode == OpCodes.Endfinally) || (opcode == OpCodes.Leave) || (opcode == OpCodes.Rethrow)))
{
throw new Exception(opcode + " stack depth " + stack);
}
if((stack != 1) && (opcode == OpCodes.Throw))
{
throw new Exception(opcode + " stack depth " + stack);
}
}
/**
* @brief See if it's possible for it to fall through to the next inline (nextLin) instruction.
*/
public override bool CanFallThrough()
{
switch(opcode.FlowControl)
{
case FlowControl.Branch:
return false; // unconditional branch
case FlowControl.Break:
return true; // break
case FlowControl.Call:
return true; // call
case FlowControl.Cond_Branch:
return true; // conditional branch
case FlowControl.Next:
return true; // falls through to next instruction
case FlowControl.Return:
return false; // return
case FlowControl.Throw:
return false; // throw
default:
{
string op = opcode.ToString();
if(op == "volatile.")
return true;
throw new Exception("unknown flow control " + opcode.FlowControl + " for " + op);
}
}
}
// if followed by OpCodes.Pop, it can be discarded
public bool isPoppable
{
get
{
return
((opcode.StackBehaviourPop == StackBehaviour.Pop0) && // ldarg,ldloc,ldsfld
(opcode.StackBehaviourPush == StackBehaviour.Push1)) ||
((opcode.StackBehaviourPop == StackBehaviour.Pop0) && // ldarga,ldloca,ldc,ldsflda,...
(opcode.StackBehaviourPush == StackBehaviour.Pushi)) ||
(opcode == OpCodes.Ldnull) ||
(opcode == OpCodes.Ldc_R4) ||
(opcode == OpCodes.Ldc_R8) ||
(opcode == OpCodes.Ldstr) ||
(opcode == OpCodes.Ldc_I8) ||
(opcode == OpCodes.Dup);
}
}
public override void DebString(StringBuilder sb)
{
sb.Append("".PadRight(OPINDENT));
sb.Append(opcode.ToString().PadRight(OPDEBLEN));
}
/**
* @brief If instruction is terminating, we say there is nothing following (eg, return).
* Otherwise, say the one-and-only next instruction is the next instruction inline.
*/
protected override System.Collections.Generic.IEnumerable<GraphNode> GetNNEnumerable()
{
return new NNEnumerable(this, typeof(NNEnumerator));
}
private class NNEnumerator: NNEnumeratorBase
{
private GraphNodeEmit gn;
private int index;
public NNEnumerator(GraphNodeEmit gn)
{
this.gn = gn;
}
public override bool MoveNext()
{
switch(index)
{
case 0:
{
if(gn.CanFallThrough())
{
index++;
nn = gn.nextLin;
return nn != null;
}
return false;
}
case 1:
{
nn = null;
return false;
}
}
throw new Exception();
}
public override void Reset()
{
index = 0;
nn = null;
}
}
}
public class GraphNodeEmitNull: GraphNodeEmit
{
public GraphNodeEmitNull(ScriptCollector coll, Token errorAt, OpCode opcode) : base(coll, errorAt, opcode)
{
}
public override void ChainLin()
{
base.ChainLin();
switch(opcode.ToString())
{
case "nop":
break;
case "break":
break;
case "volatile.":
break;
case "ldarg.0":
coll.stackDepth.Push(coll.wrapped.argTypes[0]);
break;
case "ldarg.1":
coll.stackDepth.Push(coll.wrapped.argTypes[1]);
break;
case "ldarg.2":
coll.stackDepth.Push(coll.wrapped.argTypes[2]);
break;
case "ldarg.3":
coll.stackDepth.Push(coll.wrapped.argTypes[3]);
break;
case "ldnull":
coll.stackDepth.Push(null);
break;
case "ldc.i4.m1":
case "ldc.i4.0":
case "ldc.i4.1":
case "ldc.i4.2":
case "ldc.i4.3":
case "ldc.i4.4":
case "ldc.i4.5":
case "ldc.i4.6":
case "ldc.i4.7":
case "ldc.i4.8":
{
coll.stackDepth.Push(typeof(int));
break;
}
case "dup":
{
Type t = coll.stackDepth.Peek(0);
bool b = coll.stackDepth.PeekBoxed(0);
coll.stackDepth.Push(t, b);
break;
}
case "pop":
{
coll.stackDepth.Pop(1);
break;
}
case "ret":
{
int sd = (coll.wrapped.retType != typeof(void)) ? 1 : 0;
if(coll.stackDepth.Count != sd)
throw new Exception("bad stack depth");
if(sd > 0)
{
coll.stackDepth.Pop(coll.wrapped.retType);
}
break;
}
case "add":
case "sub":
case "mul":
case "div":
case "div.un":
case "rem":
case "rem.un":
case "and":
case "or":
case "xor":
case "shl":
case "shr":
case "shr.un":
case "add.ovf":
case "add.ovf.un":
case "mul.ovf":
case "mul.ovf.un":
case "sub.ovf":
case "sub.ovf.un":
{
coll.stackDepth.PopNumVal();
Type t = coll.stackDepth.PopNumVal();
coll.stackDepth.Push(t);
break;
}
case "neg":
case "not":
{
Type t = coll.stackDepth.PopNumVal();
coll.stackDepth.Push(t);
break;
}
case "conv.i1":
case "conv.i2":
case "conv.i4":
case "conv.i8":
case "conv.r4":
case "conv.r8":
case "conv.u4":
case "conv.u8":
case "conv.r.un":
case "conv.ovf.i1.un":
case "conv.ovf.i2.un":
case "conv.ovf.i4.un":
case "conv.ovf.i8.un":
case "conv.ovf.u1.un":
case "conv.ovf.u2.un":
case "conv.ovf.u4.un":
case "conv.ovf.u8.un":
case "conv.ovf.i.un":
case "conv.ovf.u.un":
case "conv.ovf.i1":
case "conv.ovf.u1":
case "conv.ovf.i2":
case "conv.ovf.u2":
case "conv.ovf.i4":
case "conv.ovf.u4":
case "conv.ovf.i8":
case "conv.ovf.u8":
case "conv.u2":
case "conv.u1":
case "conv.i":
case "conv.ovf.i":
case "conv.ovf.u":
case "conv.u":
{
coll.stackDepth.PopNumVal();
coll.stackDepth.Push(ConvToType(opcode));
break;
}
case "throw":
{
if(coll.stackDepth.Count != 1)
throw new Exception("bad stack depth " + coll.stackDepth.Count);
coll.stackDepth.PopRef();
break;
}
case "ldlen":
{
coll.stackDepth.Pop(typeof(string));
coll.stackDepth.Push(typeof(int));
break;
}
case "ldelem.i1":
case "ldelem.u1":
case "ldelem.i2":
case "ldelem.u2":
case "ldelem.i4":
case "ldelem.u4":
case "ldelem.i8":
case "ldelem.i":
case "ldelem.r4":
case "ldelem.r8":
case "ldelem.ref":
{
Type t = coll.stackDepth.Peek(1).GetElementType();
coll.stackDepth.Pop(typeof(int));
coll.stackDepth.Pop(t.MakeArrayType());
coll.stackDepth.Push(t);
break;
}
case "stelem.i":
case "stelem.i1":
case "stelem.i2":
case "stelem.i4":
case "stelem.i8":
case "stelem.r4":
case "stelem.r8":
case "stelem.ref":
{
Type t = coll.stackDepth.Peek(2).GetElementType();
coll.stackDepth.Pop(t);
coll.stackDepth.Pop(typeof(int));
coll.stackDepth.Pop(t.MakeArrayType());
break;
}
case "endfinally":
case "rethrow":
{
if(coll.stackDepth.Count != 0)
throw new Exception("bad stack depth " + coll.stackDepth.Count);
break;
}
case "ceq":
{
Type t = coll.stackDepth.Pop(1);
if(t == null)
{
coll.stackDepth.PopRef();
}
else
{
coll.stackDepth.Pop(t);
}
coll.stackDepth.Push(typeof(int));
break;
}
case "cgt":
case "cgt.un":
case "clt":
case "clt.un":
{
coll.stackDepth.PopNumVal();
coll.stackDepth.PopNumVal();
coll.stackDepth.Push(typeof(int));
break;
}
case "ldind.i4":
{
coll.stackDepth.Pop(typeof(int).MakeByRefType());
coll.stackDepth.Push(typeof(int));
break;
}
case "stind.i4":
{
coll.stackDepth.Pop(typeof(int));
coll.stackDepth.Pop(typeof(int).MakeByRefType());
break;
}
default:
throw new Exception("unknown opcode " + opcode.ToString());
}
}
private static Type ConvToType(OpCode opcode)
{
string s = opcode.ToString();
s = s.Substring(5); // strip off "conv."
if(s.StartsWith("ovf."))
s = s.Substring(4);
if(s.EndsWith(".un"))
s = s.Substring(0, s.Length - 3);
switch(s)
{
case "i":
return typeof(IntPtr);
case "i1":
return typeof(sbyte);
case "i2":
return typeof(short);
case "i4":
return typeof(int);
case "i8":
return typeof(long);
case "r":
case "r4":
return typeof(float);
case "r8":
return typeof(double);
case "u1":
return typeof(byte);
case "u2":
return typeof(ushort);
case "u4":
return typeof(uint);
case "u8":
return typeof(ulong);
case "u":
return typeof(UIntPtr);
default:
throw new Exception("unknown opcode " + opcode.ToString());
}
}
public override void WriteOutOne(ScriptMyILGen ilGen)
{
ilGen.Emit(errorAt, opcode);
}
}
public class GraphNodeEmitNullEndfinally: GraphNodeEmitNull
{
public GraphNodeEmitNullEndfinally(ScriptCollector coll, Token errorAt) : base(coll, errorAt, OpCodes.Endfinally)
{
}
/**
* @brief Endfinally can branch to:
* 1) the corresponding EndExceptionBlock
* 2) any of the corresponding BeginFinallyBlock's leaveTargets
* 3) the next outer BeginFinallyBlock
*/
protected override System.Collections.Generic.IEnumerable<GraphNode> GetNNEnumerable()
{
return new NNEnumerable(this, typeof(NNEnumerator));
}
private class NNEnumerator: NNEnumeratorBase
{
private GraphNodeEmitNullEndfinally gn;
private IEnumerator<GraphNodeBlock> leaveTargetEnumerator;
private int index;
public NNEnumerator(GraphNodeEmitNullEndfinally gn)
{
this.gn = gn;
// endfinally instruction must be within some try/catch/finally mess
GraphNodeBeginExceptionBlock thistry = gn.excBlock;
// endfinally instruction must be within some finally { } mess
GraphNodeBeginFinallyBlock thisfin = (GraphNodeBeginFinallyBlock)thistry.catchFinallyBlock;
// get the list of the finally { } leave instruction targets
this.leaveTargetEnumerator = thisfin.leaveTargets.GetEnumerator();
}
public override bool MoveNext()
{
while(true)
{
switch(index)
{
// to start, return end of our finally { }
case 0:
{
GraphNodeBeginExceptionBlock thistry = gn.excBlock;
nn = thistry.endExcBlock;
if(nn == null)
throw new NullReferenceException("thistry.endExcBlock");
index++;
return true;
}
// return next one of our finally { }'s leave targets
// ie, where any leave instructions in the try { } want
// the finally { } to go to when it finishes
case 1:
{
if(this.leaveTargetEnumerator.MoveNext())
{
nn = this.leaveTargetEnumerator.Current;
if(nn == null)
throw new NullReferenceException("this.leaveTargetEnumerator.Current");
return true;
}
break;
}
// return beginning of next outer finally { }
case 2:
{
GraphNodeBeginExceptionBlock nntry = gn.excBlock;
while((nntry = nntry.excBlock) != null)
{
if(nntry.catchFinallyBlock is GraphNodeBeginFinallyBlock)
{
nn = nntry.catchFinallyBlock;
if(nn == null)
throw new NullReferenceException("nntry.catchFinallyBlock");
index++;
return true;
}
}
break;
}
// got nothing more
case 3:
{
return false;
}
default:
throw new Exception();
}
index++;
}
}
public override void Reset()
{
leaveTargetEnumerator.Reset();
index = 0;
nn = null;
}
}
}
public class GraphNodeEmitField: GraphNodeEmit
{
public FieldInfo field;
public GraphNodeEmitField(ScriptCollector coll, Token errorAt, OpCode opcode, FieldInfo field) : base(coll, errorAt, opcode)
{
this.field = field;
}
public override void ChainLin()
{
base.ChainLin();
switch(opcode.ToString())
{
case "ldfld":
PopPointer();
coll.stackDepth.Push(field.FieldType);
break;
case "ldflda":
PopPointer();
coll.stackDepth.Push(field.FieldType.MakeByRefType());
break;
case "stfld":
coll.stackDepth.Pop(field.FieldType);
PopPointer();
break;
case "ldsfld":
coll.stackDepth.Push(field.FieldType);
break;
case "ldsflda":
coll.stackDepth.Push(field.FieldType.MakeByRefType());
break;
case "stsfld":
coll.stackDepth.Pop(field.FieldType);
break;
default:
throw new Exception("unknown opcode " + opcode.ToString());
}
}
private void PopPointer()
{
Type t = field.DeclaringType; // get class/field type
if(t.IsValueType)
{
Type brt = t.MakeByRefType(); // if value type, eg Vector, it can be pushed by reference or by value
int c = coll.stackDepth.Count;
if((c > 0) && (coll.stackDepth[c - 1] == brt))
t = brt;
}
coll.stackDepth.Pop(t); // type of what should be on the stack pointing to object or struct
}
public override void DebString(StringBuilder sb)
{
base.DebString(sb);
sb.Append(field.Name);
}
public override void WriteOutOne(ScriptMyILGen ilGen)
{
ilGen.Emit(errorAt, opcode, field);
}
}
public class GraphNodeEmitLocal: GraphNodeEmit
{
public ScriptMyLocal myLocal;
public GraphNodeEmitLocal(ScriptCollector coll, Token errorAt, OpCode opcode, ScriptMyLocal myLocal) : base(coll, errorAt, opcode)
{
this.myLocal = myLocal;
}
public override void ChainLin()
{
base.ChainLin();
switch(opcode.ToString())
{
case "ldloc":
coll.stackDepth.Push(myLocal.type);
break;
case "ldloca":
coll.stackDepth.Push(myLocal.type.MakeByRefType());
break;
case "stloc":
coll.stackDepth.Pop(myLocal.type);
break;
default:
throw new Exception("unknown opcode " + opcode.ToString());
}
}
public override void DebString(StringBuilder sb)
{
base.DebString(sb);
sb.Append(myLocal.name);
}
public override ScriptMyLocal ReadsLocal()
{
if(opcode == OpCodes.Ldloc)
return myLocal;
if(opcode == OpCodes.Ldloca)
return myLocal;
if(opcode == OpCodes.Stloc)
return null;
throw new Exception("unknown opcode " + opcode);
}
public override ScriptMyLocal WritesLocal()
{
if(opcode == OpCodes.Ldloc)
return null;
if(opcode == OpCodes.Ldloca)
return myLocal;
if(opcode == OpCodes.Stloc)
return myLocal;
throw new Exception("unknown opcode " + opcode);
}
public override void WriteOutOne(ScriptMyILGen ilGen)
{
ilGen.Emit(errorAt, opcode, myLocal);
}
}
public class GraphNodeEmitType: GraphNodeEmit
{
public Type type;
public GraphNodeEmitType(ScriptCollector coll, Token errorAt, OpCode opcode, Type type) : base(coll, errorAt, opcode)
{
this.type = type;
}
public override void ChainLin()
{
base.ChainLin();
switch(opcode.ToString())
{
case "castclass":
case "isinst":
{
coll.stackDepth.PopRef();
coll.stackDepth.Push(type, type.IsValueType);
break;
}
case "box":
{
if(!type.IsValueType)
throw new Exception("can't box a non-value type");
coll.stackDepth.Pop(type);
coll.stackDepth.Push(type, true);
break;
}
case "unbox":
case "unbox.any":
{
if(!type.IsValueType)
throw new Exception("can't unbox to a non-value type");
coll.stackDepth.PopRef();
coll.stackDepth.Push(type);
break;
}
case "newarr":
{
coll.stackDepth.Pop(typeof(int));
coll.stackDepth.Push(type.MakeArrayType());
break;
}
case "sizeof":
{
coll.stackDepth.Pop(1);
coll.stackDepth.Push(typeof(int));
break;
}
case "ldelem":
{
coll.stackDepth.Pop(typeof(int));
coll.stackDepth.Pop(type.MakeArrayType());
coll.stackDepth.Push(type);
break;
}
case "ldelema":
{
coll.stackDepth.Pop(typeof(int));
coll.stackDepth.Pop(type.MakeArrayType());
coll.stackDepth.Push(type.MakeByRefType());
break;
}
case "stelem":
{
coll.stackDepth.Pop(type);
coll.stackDepth.Pop(typeof(int));
coll.stackDepth.Pop(type.MakeArrayType());
break;
}
default:
throw new Exception("unknown opcode " + opcode.ToString());
}
}
public override void DebString(StringBuilder sb)
{
base.DebString(sb);
sb.Append(type.Name);
}
public override void WriteOutOne(ScriptMyILGen ilGen)
{
ilGen.Emit(errorAt, opcode, type);
}
}
public class GraphNodeEmitLabel: GraphNodeEmit
{
public ScriptMyLabel myLabel;
public GraphNodeEmitLabel(ScriptCollector coll, Token errorAt, OpCode opcode, ScriptMyLabel myLabel) : base(coll, errorAt, opcode)
{
this.myLabel = myLabel;
}
public override void ChainLin()
{
base.ChainLin();
switch(opcode.ToString())
{
case "brfalse.s":
case "brtrue.s":
case "brfalse":
case "brtrue":
{
coll.stackDepth.Pop(1);
break;
}
case "beq.s":
case "bge.s":
case "bgt.s":
case "ble.s":
case "blt.s":
case "bne.un.s":
case "bge.un.s":
case "bgt.un.s":
case "ble.un.s":
case "blt.un.s":
case "beq":
case "bge":
case "bgt":
case "ble":
case "blt":
case "bne.un":
case "bge.un":
case "bgt.un":
case "ble.un":
case "blt.un":
{
coll.stackDepth.PopNumVal();
coll.stackDepth.PopNumVal();
break;
}
case "br":
case "br.s":
break;
case "leave":
{
if(coll.stackDepth.Count != 0)
throw new Exception("bad stack depth " + coll.stackDepth.Count);
break;
}
default:
throw new Exception("unknown opcode " + opcode.ToString());
}
// if a target doesn't have a depth yet, set its depth to the depth after instruction executes
// otherwise, make sure it matches all other branches to that target and what fell through to it
coll.stackDepth.Matches(myLabel);
}
public override void DebString(StringBuilder sb)
{
base.DebString(sb);
sb.Append(myLabel.name);
}
public override void WriteOutOne(ScriptMyILGen ilGen)
{
ilGen.Emit(errorAt, opcode, myLabel);
}
/**
* @brief Conditional branches return the next inline followed by the branch target
* Unconditional branches return only the branch target
* But if the target is outside our scope (eg __retlbl), omit it from the list
*/
protected override System.Collections.Generic.IEnumerable<GraphNode> GetNNEnumerable()
{
return new NNEnumerable(this, typeof(NNEnumerator));
}
private class NNEnumerator: NNEnumeratorBase
{
private GraphNodeEmitLabel gn;
private int index;
public NNEnumerator(GraphNodeEmitLabel gn)
{
this.gn = gn;
}
public override bool MoveNext()
{
switch(gn.opcode.FlowControl)
{
case FlowControl.Branch:
{
// unconditional branch just goes to target and nothing else
switch(index)
{
case 0:
{
nn = gn.myLabel.whereAmI;
index++;
return nn != null;
}
case 1:
{
return false;
}
}
throw new Exception();
}
case FlowControl.Cond_Branch:
{
// conditional branch goes inline and to target
switch(index)
{
case 0:
{
nn = gn.nextLin;
index++;
return true;
}
case 1:
{
nn = gn.myLabel.whereAmI;
index++;
return nn != null;
}
case 2:
{
return false;
}
}
throw new Exception();
}
default:
throw new Exception("unknown flow control " + gn.opcode.FlowControl.ToString() +
" of " + gn.opcode.ToString());
}
}
public override void Reset()
{
index = 0;
nn = null;
}
}
}
public class GraphNodeEmitLabelLeave: GraphNodeEmitLabel
{
public GraphNodeBlock unwindTo; // if unwinding, innermost finally block being unwound
// else, same as myTarget.whereAmI
// null if unwinding completely out of scope, eg, __retlbl
public GraphNodeEmitLabelLeave(ScriptCollector coll, Token errorAt, ScriptMyLabel myLabel) : base(coll, errorAt, OpCodes.Leave, myLabel)
{
}
/**
* @brief Leave instructions have exactly one unconditional next node.
* Either the given target if within the same try block
* or the beginning of the intervening finally block.
*/
protected override System.Collections.Generic.IEnumerable<GraphNode> GetNNEnumerable()
{
return new NNEnumerable(this, typeof(NNEnumerator));
}
private class NNEnumerator: NNEnumeratorBase
{
private GraphNodeEmitLabelLeave gn;
private int index;
public NNEnumerator(GraphNodeEmitLabelLeave gn)
{
this.gn = gn;
}
public override bool MoveNext()
{
if(index == 0)
{
nn = gn.unwindTo;
index++;
return nn != null;
}
nn = null;
return false;
}
public override void Reset()
{
index = 0;
nn = null;
}
}
}
public class GraphNodeEmitLabels: GraphNodeEmit
{
public ScriptMyLabel[] myLabels;
public GraphNodeEmitLabels(ScriptCollector coll, Token errorAt, OpCode opcode, ScriptMyLabel[] myLabels) : base(coll, errorAt, opcode)
{
this.myLabels = myLabels;
}
public override void ChainLin()
{
base.ChainLin();
switch(opcode.ToString())
{
case "switch":
{
coll.stackDepth.Pop(typeof(int));
break;
}
default:
throw new Exception("unknown opcode " + opcode.ToString());
}
// if a target doesn't have a depth yet, set its depth to the depth after instruction executes
// otherwise, make sure it matches all other branches to that target and what fell through to it
foreach(ScriptMyLabel myLabel in myLabels)
{
coll.stackDepth.Matches(myLabel);
}
}
public override void DebString(StringBuilder sb)
{
base.DebString(sb);
bool first = true;
foreach(ScriptMyLabel lbl in myLabels)
{
if(!first)
sb.Append(',');
sb.Append(lbl.name);
first = false;
}
}
public override void WriteOutOne(ScriptMyILGen ilGen)
{
ilGen.Emit(errorAt, opcode, myLabels);
}
/**
* @brief Return list of all labels followed by the next linear instruction
* But if the target is outside our scope (eg __retlbl), omit it from the list
*/
protected override System.Collections.Generic.IEnumerable<GraphNode> GetNNEnumerable()
{
return new NNEnumerable(this, typeof(NNEnumerator));
}
private class NNEnumerator: NNEnumeratorBase
{
private GraphNodeEmitLabels gn;
private int index;
public NNEnumerator(GraphNodeEmitLabels gn)
{
this.gn = gn;
}
public override bool MoveNext()
{
// Return next from list of switch case labels.
while(index < gn.myLabels.Length)
{
nn = gn.myLabels[index++].whereAmI;
if(nn != null)
return true;
}
// If all ran out, the switch instruction falls through.
if(index == gn.myLabels.Length)
{
index++;
nn = gn.nextLin;
return true;
}
// Even ran out of that, say there's nothing more.
nn = null;
return false;
}
public override void Reset()
{
index = 0;
nn = null;
}
}
}
public class GraphNodeEmitIntMeth: GraphNodeEmit
{
public ScriptObjWriter method;
public GraphNodeEmitIntMeth(ScriptCollector coll, Token errorAt, OpCode opcode, ScriptObjWriter method) : base(coll, errorAt, opcode)
{
this.method = method;
}
public override void ChainLin()
{
base.ChainLin();
switch(opcode.ToString())
{
case "call":
{
// calls have Varpop so pop the number of arguments
// they are all static so there is no separate 'this' parameter
coll.stackDepth.Pop(this.method.argTypes);
// calls are also Varpush so they push a return value iff non-void
if(this.method.retType != typeof(void))
coll.stackDepth.Push(this.method.retType);
break;
}
default:
throw new Exception("unknown opcode " + opcode.ToString());
}
}
public override void DebString(StringBuilder sb)
{
base.DebString(sb);
sb.Append(method.methName);
}
public override void WriteOutOne(ScriptMyILGen ilGen)
{
ilGen.Emit(errorAt, opcode, method);
}
}
public class GraphNodeEmitExtMeth: GraphNodeEmit
{
public MethodInfo method;
public GraphNodeEmitExtMeth(ScriptCollector coll, Token errorAt, OpCode opcode, MethodInfo method) : base(coll, errorAt, opcode)
{
this.method = method;
}
public override void ChainLin()
{
base.ChainLin();
switch(opcode.ToString())
{
case "call":
case "callvirt":
{
// calls have Varpop so pop the number of arguments
coll.stackDepth.Pop(this.method.GetParameters());
if((this.method.CallingConvention & CallingConventions.HasThis) != 0)
{
coll.stackDepth.Pop(method.DeclaringType);
}
// calls are also Varpush so they push a return value iff non-void
if(this.method.ReturnType != typeof(void))
coll.stackDepth.Push(this.method.ReturnType);
break;
}
default:
throw new Exception("unknown opcode " + opcode.ToString());
}
}
public override void DebString(StringBuilder sb)
{
base.DebString(sb);
sb.Append(method.Name);
}
public override void WriteOutOne(ScriptMyILGen ilGen)
{
ilGen.Emit(errorAt, opcode, method);
}
}
public class GraphNodeEmitCtor: GraphNodeEmit
{
public ConstructorInfo ctor;
public GraphNodeEmitCtor(ScriptCollector coll, Token errorAt, OpCode opcode, ConstructorInfo ctor) : base(coll, errorAt, opcode)
{
this.ctor = ctor;
}
public override void ChainLin()
{
base.ChainLin();
switch(opcode.ToString())
{
case "newobj":
{
coll.stackDepth.Pop(ctor.GetParameters());
coll.stackDepth.Push(ctor.DeclaringType);
break;
}
default:
throw new Exception("unknown opcode " + opcode.ToString());
}
}
public override void DebString(StringBuilder sb)
{
base.DebString(sb);
sb.Append(ctor.ReflectedType.Name);
}
public override void WriteOutOne(ScriptMyILGen ilGen)
{
ilGen.Emit(errorAt, opcode, ctor);
}
}
public class GraphNodeEmitDouble: GraphNodeEmit
{
public double value;
public GraphNodeEmitDouble(ScriptCollector coll, Token errorAt, OpCode opcode, double value) : base(coll, errorAt, opcode)
{
this.value = value;
}
public override void ChainLin()
{
base.ChainLin();
switch(opcode.ToString())
{
case "ldc.r8":
coll.stackDepth.Push(typeof(double));
break;
default:
throw new Exception("unknown opcode " + opcode.ToString());
}
}
public override void DebString(StringBuilder sb)
{
base.DebString(sb);
sb.Append(value);
}
public override void WriteOutOne(ScriptMyILGen ilGen)
{
ilGen.Emit(errorAt, opcode, value);
}
}
public class GraphNodeEmitFloat: GraphNodeEmit
{
public float value;
public GraphNodeEmitFloat(ScriptCollector coll, Token errorAt, OpCode opcode, float value) : base(coll, errorAt, opcode)
{
this.value = value;
}
public override void ChainLin()
{
base.ChainLin();
switch(opcode.ToString())
{
case "ldc.r4":
coll.stackDepth.Push(typeof(float));
break;
default:
throw new Exception("unknown opcode " + opcode.ToString());
}
}
public override void DebString(StringBuilder sb)
{
base.DebString(sb);
sb.Append(value);
}
public override void WriteOutOne(ScriptMyILGen ilGen)
{
ilGen.Emit(errorAt, opcode, value);
}
}
public class GraphNodeEmitInt: GraphNodeEmit
{
public int value;
public GraphNodeEmitInt(ScriptCollector coll, Token errorAt, OpCode opcode, int value) : base(coll, errorAt, opcode)
{
this.value = value;
}
public override void ChainLin()
{
base.ChainLin();
switch(opcode.ToString())
{
case "ldarg":
case "ldarg.s":
coll.stackDepth.Push(coll.wrapped.argTypes[value]);
break;
case "ldarga":
case "ldarga.s":
coll.stackDepth.Push(coll.wrapped.argTypes[value].MakeByRefType());
break;
case "starg":
case "starg.s":
coll.stackDepth.Pop(coll.wrapped.argTypes[value]);
break;
case "ldc.i4":
case "ldc.i4.s":
coll.stackDepth.Push(typeof(int));
break;
default:
throw new Exception("unknown opcode " + opcode.ToString());
}
}
public override void DebString(StringBuilder sb)
{
base.DebString(sb);
sb.Append(value);
}
public override void WriteOutOne(ScriptMyILGen ilGen)
{
ilGen.Emit(errorAt, opcode, value);
}
}
public class GraphNodeEmitString: GraphNodeEmit
{
public string value;
public GraphNodeEmitString(ScriptCollector coll, Token errorAt, OpCode opcode, string value) : base(coll, errorAt, opcode)
{
this.value = value;
}
public override void ChainLin()
{
base.ChainLin();
switch(opcode.ToString())
{
case "ldstr":
coll.stackDepth.Push(typeof(string));
break;
default:
throw new Exception("unknown opcode " + opcode.ToString());
}
}
public override void DebString(StringBuilder sb)
{
base.DebString(sb);
sb.Append("\"");
sb.Append(value);
sb.Append("\"");
}
public override void WriteOutOne(ScriptMyILGen ilGen)
{
ilGen.Emit(errorAt, opcode, value);
}
}
public class GraphNodeMarkLabel: GraphNodeBlock
{
public ScriptMyLabel myLabel;
public GraphNodeMarkLabel(ScriptCollector coll, ScriptMyLabel myLabel) : base(coll)
{
this.myLabel = myLabel;
}
public override void ChainLin()
{
base.ChainLin();
// if previous instruction can fall through to this label,
// if the label doesn't yet have a stack depth, mark it with current stack depth
// else, the label's stack depth from forward branches and current stack depth must match
// else,
// label must have had a forward branch to it so we can know stack depth
// set the current stack depth to the label's stack depth as of that forward branch
if(myLabel.whereAmI.prevLin.CanFallThrough())
{
coll.stackDepth.Matches(myLabel);
}
else
{
if(myLabel.stackDepth == null)
{
throw new Exception("stack depth unknown at " + myLabel.name);
}
coll.stackDepth.Clear();
int n = myLabel.stackDepth.Length;
for(int i = 0; i < n; i++)
{
coll.stackDepth.Push(myLabel.stackDepth[i], myLabel.stackBoxeds[i]);
}
}
}
public override void DebString(StringBuilder sb)
{
sb.Append(myLabel.name);
sb.Append(':');
if(myLabel.stackDepth != null)
{
sb.Append(" [");
sb.Append(myLabel.stackDepth.Length);
sb.Append(']');
}
}
public override void WriteOutOne(ScriptMyILGen ilGen)
{
ilGen.MarkLabel(myLabel);
}
}
/**
* @brief Generates enumerator that steps through list of nodes that can
* possibly be next in a flow-control sense.
*/
public class NNEnumerable: System.Collections.Generic.IEnumerable<GraphNode>
{
private object[] cps;
private ConstructorInfo ci;
public NNEnumerable(GraphNode gn, Type nnEnumeratorType)
{
this.cps = new object[] { gn };
this.ci = nnEnumeratorType.GetConstructor(new Type[] { gn.GetType() });
}
System.Collections.Generic.IEnumerator<GraphNode> System.Collections.Generic.IEnumerable<GraphNode>.GetEnumerator()
{
return (System.Collections.Generic.IEnumerator<GraphNode>)ci.Invoke(cps);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return (System.Collections.IEnumerator)ci.Invoke(cps);
}
}
/**
* @brief Steps through list of nodes that can possible be next in a flow-control sense.
*/
public abstract class NNEnumeratorBase: System.Collections.Generic.IEnumerator<GraphNode>
{
protected GraphNode nn;
public abstract bool MoveNext();
public abstract void Reset();
GraphNode System.Collections.Generic.IEnumerator<GraphNode>.Current
{
get
{
return this.nn;
}
}
object System.Collections.IEnumerator.Current
{
get
{
return this.nn;
}
}
void System.IDisposable.Dispose()
{
}
}
public class ScriptCollector: ScriptMyILGen
{
public static readonly bool DEBUG = false;
public ScriptObjWriter wrapped;
public GraphNode firstLin, lastLin;
private bool resolvedSomething;
private int resolveSequence;
private int excBlkSeqNos;
public StackDepth stackDepth = new StackDepth();
public GraphNodeBeginExceptionBlock curTryBlock = null; // pushed at beginning of try
// popped at BEGINNING of catch/finally
public GraphNodeBeginExceptionBlock curExcBlock = null; // pushed at beginning of try
// popped at END of catch/finally
private List<ScriptMyLocal> declaredLocals = new List<ScriptMyLocal>();
private List<ScriptMyLabel> definedLabels = new List<ScriptMyLabel>();
public string methName
{
get
{
return wrapped.methName;
}
}
/**
* @brief Wrap the optimizer around the ScriptObjWriter to collect the instruction stream.
* All stream-writing calls get saved to our graph nodes instead of being written to object file.
*/
public ScriptCollector(ScriptObjWriter wrapped)
{
this.wrapped = wrapped;
GraphNodeBegin gnb = new GraphNodeBegin(this);
this.firstLin = gnb;
this.lastLin = gnb;
}
public ScriptMyLocal DeclareLocal(Type type, string name)
{
ScriptMyLocal loc = new ScriptMyLocal();
loc.name = name;
loc.type = type;
loc.number = wrapped.localNumber++;
declaredLocals.Add(loc);
return loc;
}
public ScriptMyLabel DefineLabel(string name)
{
ScriptMyLabel lbl = new ScriptMyLabel();
lbl.name = name;
lbl.number = wrapped.labelNumber++;
definedLabels.Add(lbl);
return lbl;
}
public void BeginExceptionBlock()
{
GraphNodeBeginExceptionBlock tryBlock = new GraphNodeBeginExceptionBlock(this);
tryBlock.ChainLin();
tryBlock.excBlkSeqNo = ++this.excBlkSeqNos;
this.curExcBlock = tryBlock;
this.curTryBlock = tryBlock;
}
public void BeginCatchBlock(Type excType)
{
GraphNodeBeginCatchBlock catchBlock = new GraphNodeBeginCatchBlock(this, excType);
catchBlock.ChainLin();
if(curExcBlock.catchFinallyBlock != null)
throw new Exception("only one catch/finally allowed per try");
curExcBlock.catchFinallyBlock = catchBlock;
curTryBlock = curExcBlock.tryBlock;
}
public void BeginFinallyBlock()
{
GraphNodeBeginFinallyBlock finallyBlock = new GraphNodeBeginFinallyBlock(this);
finallyBlock.ChainLin();
if(curExcBlock.catchFinallyBlock != null)
throw new Exception("only one catch/finally allowed per try");
curExcBlock.catchFinallyBlock = finallyBlock;
curTryBlock = curExcBlock.tryBlock;
}
public void EndExceptionBlock()
{
GraphNodeEndExceptionBlock endExcBlock = new GraphNodeEndExceptionBlock(this);
endExcBlock.ChainLin();
curExcBlock.endExcBlock = endExcBlock;
curTryBlock = curExcBlock.tryBlock;
curExcBlock = curExcBlock.excBlock;
}
public void Emit(Token errorAt, OpCode opcode)
{
if(opcode == OpCodes.Endfinally)
{
new GraphNodeEmitNullEndfinally(this, errorAt).ChainLin();
}
else
{
new GraphNodeEmitNull(this, errorAt, opcode).ChainLin();
}
}
public void Emit(Token errorAt, OpCode opcode, FieldInfo field)
{
if(field == null)
throw new ArgumentNullException("field");
new GraphNodeEmitField(this, errorAt, opcode, field).ChainLin();
}
public void Emit(Token errorAt, OpCode opcode, ScriptMyLocal myLocal)
{
new GraphNodeEmitLocal(this, errorAt, opcode, myLocal).ChainLin();
}
public void Emit(Token errorAt, OpCode opcode, Type type)
{
new GraphNodeEmitType(this, errorAt, opcode, type).ChainLin();
}
public void Emit(Token errorAt, OpCode opcode, ScriptMyLabel myLabel)
{
if(opcode == OpCodes.Leave)
{
new GraphNodeEmitLabelLeave(this, errorAt, myLabel).ChainLin();
}
else
{
new GraphNodeEmitLabel(this, errorAt, opcode, myLabel).ChainLin();
}
}
public void Emit(Token errorAt, OpCode opcode, ScriptMyLabel[] myLabels)
{
new GraphNodeEmitLabels(this, errorAt, opcode, myLabels).ChainLin();
}
public void Emit(Token errorAt, OpCode opcode, ScriptObjWriter method)
{
if(method == null)
throw new ArgumentNullException("method");
new GraphNodeEmitIntMeth(this, errorAt, opcode, method).ChainLin();
}
public void Emit(Token errorAt, OpCode opcode, MethodInfo method)
{
if(method == null)
throw new ArgumentNullException("method");
new GraphNodeEmitExtMeth(this, errorAt, opcode, method).ChainLin();
}
public void Emit(Token errorAt, OpCode opcode, ConstructorInfo ctor)
{
if(ctor == null)
throw new ArgumentNullException("ctor");
new GraphNodeEmitCtor(this, errorAt, opcode, ctor).ChainLin();
}
public void Emit(Token errorAt, OpCode opcode, double value)
{
new GraphNodeEmitDouble(this, errorAt, opcode, value).ChainLin();
}
public void Emit(Token errorAt, OpCode opcode, float value)
{
new GraphNodeEmitFloat(this, errorAt, opcode, value).ChainLin();
}
public void Emit(Token errorAt, OpCode opcode, int value)
{
new GraphNodeEmitInt(this, errorAt, opcode, value).ChainLin();
}
public void Emit(Token errorAt, OpCode opcode, string value)
{
new GraphNodeEmitString(this, errorAt, opcode, value).ChainLin();
}
public void MarkLabel(ScriptMyLabel myLabel)
{
myLabel.whereAmI = new GraphNodeMarkLabel(this, myLabel);
myLabel.whereAmI.ChainLin();
}
/**
* @brief Write the whole graph out to the object file.
*/
public ScriptMyILGen WriteOutAll()
{
foreach(ScriptMyLocal loc in declaredLocals)
{
if(loc.isReferenced)
wrapped.DeclareLocal(loc);
}
foreach(ScriptMyLabel lbl in definedLabels)
{
wrapped.DefineLabel(lbl);
}
for(GraphNode gn = firstLin; gn != null; gn = gn.nextLin)
{
gn.WriteOutOne(wrapped);
}
return wrapped;
}
/**
* @brief Perform optimizations.
*/
public void Optimize()
{
if(curExcBlock != null)
throw new Exception("exception block still open");
// If an instruction says it doesn't fall through, remove all instructions to
// the end of the block.
for(GraphNode gn = firstLin; gn != null; gn = gn.nextLin)
{
if(!gn.CanFallThrough())
{
GraphNode nn;
while(((nn = gn.nextLin) != null) && !(nn is GraphNodeBlock) &&
!(nn is GraphNodeEndExceptionBlock))
{
if((gn.nextLin = nn.nextLin) != null)
{
nn.nextLin.prevLin = gn;
}
}
}
}
// Scan for OpCodes.Leave instructions.
// For each found, its target for flow analysis purposes is the beginning of the corresponding
// finally block. And the end of the finally block gets a conditional branch target of the
// leave instruction's target. A leave instruction can unwind zero or more finally blocks.
for(GraphNode gn = firstLin; gn != null; gn = gn.nextLin)
{
if(gn is GraphNodeEmitLabelLeave)
{
GraphNodeEmitLabelLeave leaveInstr = (GraphNodeEmitLabelLeave)gn; // the leave instruction
GraphNodeMarkLabel leaveTarget = leaveInstr.myLabel.whereAmI; // label being targeted by leave
GraphNodeBeginExceptionBlock leaveTargetsTryBlock = // try block directly enclosing leave target
(leaveTarget == null) ? null : leaveTarget.tryBlock; // ...it must not be unwound
// Step through try { }s from the leave instruction towards its target looking for try { }s with finally { }s.
// The leave instruction unconditionally branches to the beginning of the innermost one found.
// The end of the last one found conditionally branches to the leave instruction's target.
// If none found, the leave is a simple unconditional branch to its target.
GraphNodeBeginFinallyBlock innerFinallyBlock = null;
for(GraphNodeBeginExceptionBlock tryBlock = leaveInstr.tryBlock;
tryBlock != leaveTargetsTryBlock;
tryBlock = tryBlock.tryBlock)
{
if(tryBlock == null)
throw new Exception("leave target not at or outer to leave instruction");
GraphNodeCatchFinallyBlock cfb = tryBlock.catchFinallyBlock;
if(cfb is GraphNodeBeginFinallyBlock)
{
if(innerFinallyBlock == null)
{
leaveInstr.unwindTo = cfb;
}
innerFinallyBlock = (GraphNodeBeginFinallyBlock)cfb;
}
}
// The end of the outermost finally being unwound can conditionally jump to the target of the leave instruction.
// In the case of no finallies being unwound, the leave is just a simple unconditional branch.
if(innerFinallyBlock == null)
{
leaveInstr.unwindTo = leaveTarget;
}
else if(!innerFinallyBlock.leaveTargets.Contains(leaveTarget))
{
innerFinallyBlock.leaveTargets.Add(leaveTarget);
}
}
}
// See which variables a particular block reads before writing.
// This just considers the block itself and nothing that it branches to or fallsthru to.
GraphNodeBlock currentBlock = null;
for(GraphNode gn = firstLin; gn != null; gn = gn.nextLin)
{
if(gn is GraphNodeBlock)
currentBlock = (GraphNodeBlock)gn;
ScriptMyLocal rdlcl = gn.ReadsLocal();
if((rdlcl != null) &&
!currentBlock.localsWrittenBeforeRead.Contains(rdlcl) &&
!currentBlock.localsReadBeforeWritten.Contains(rdlcl))
{
currentBlock.localsReadBeforeWritten.Add(rdlcl);
}
ScriptMyLocal wrlcl = gn.WritesLocal();
if((wrlcl != null) &&
!currentBlock.localsWrittenBeforeRead.Contains(wrlcl) &&
!currentBlock.localsReadBeforeWritten.Contains(wrlcl))
{
currentBlock.localsWrittenBeforeRead.Add(wrlcl);
}
}
// For every block we branch to, add that blocks readables to our list of readables,
// because we need to have those values valid on entry to our block. But if we write the
// variable before we can possibly branch to that block, then we don't need to have it valid
// on entry to our block. So basically it looks like the branch instruction is reading
// everything required by any blocks it can branch to.
do
{
this.resolvedSomething = false;
this.resolveSequence++;
this.ResolveBlock((GraphNodeBlock)firstLin);
} while(this.resolvedSomething);
// Repeat the cutting loops as long as we keep finding stuff.
bool didSomething;
do
{
didSomething = false;
// Strip out ldc.i4.1/xor/ldc.i4.1/xor
for(GraphNode gn = firstLin; gn != null; gn = gn.nextLin)
{
if(!(gn is GraphNodeEmit))
continue;
GraphNodeEmit xor2 = (GraphNodeEmit)gn;
if(xor2.opcode != OpCodes.Xor)
continue;
if(!(xor2.prevLin is GraphNodeEmit))
continue;
GraphNodeEmit ld12 = (GraphNodeEmit)xor2.prevLin;
if(ld12.opcode != OpCodes.Ldc_I4_1)
continue;
if(!(ld12.prevLin is GraphNodeEmit))
continue;
GraphNodeEmit xor1 = (GraphNodeEmit)ld12.prevLin;
if(xor1.opcode != OpCodes.Xor)
continue;
if(!(xor2.prevLin is GraphNodeEmit))
continue;
GraphNodeEmit ld11 = (GraphNodeEmit)xor1.prevLin;
if(ld11.opcode != OpCodes.Ldc_I4_1)
continue;
ld11.prevLin.nextLin = xor2.nextLin;
xor2.nextLin.prevLin = ld11.prevLin;
didSomething = true;
}
// Replace c{cond}/ldc.i4.1/xor/br{false,true} -> c{cond}/br{true,false}
for(GraphNode gn = firstLin; gn != null; gn = gn.nextLin)
{
if(!(gn is GraphNodeEmit))
continue;
GraphNodeEmit brft = (GraphNodeEmit)gn;
if((brft.opcode != OpCodes.Brfalse) && (brft.opcode != OpCodes.Brtrue))
continue;
if(!(brft.prevLin is GraphNodeEmit))
continue;
GraphNodeEmit xor = (GraphNodeEmit)brft.prevLin;
if(xor.opcode != OpCodes.Xor)
continue;
if(!(xor.prevLin is GraphNodeEmit))
continue;
GraphNodeEmit ldc = (GraphNodeEmit)xor.prevLin;
if(ldc.opcode != OpCodes.Ldc_I4_1)
continue;
if(!(ldc.prevLin is GraphNodeEmit))
continue;
GraphNodeEmit cmp = (GraphNodeEmit)ldc.prevLin;
if(cmp.opcode.StackBehaviourPop != StackBehaviour.Pop1_pop1)
continue;
if(cmp.opcode.StackBehaviourPush != StackBehaviour.Pushi)
continue;
cmp.nextLin = brft;
brft.prevLin = cmp;
brft.opcode = (brft.opcode == OpCodes.Brfalse) ? OpCodes.Brtrue : OpCodes.Brfalse;
didSomething = true;
}
// Replace c{cond}/br{false,true} -> b{!,}{cond}
for(GraphNode gn = firstLin; gn != null; gn = gn.nextLin)
{
if(!(gn is GraphNodeEmit))
continue;
GraphNodeEmit brft = (GraphNodeEmit)gn;
if((brft.opcode != OpCodes.Brfalse) && (brft.opcode != OpCodes.Brtrue))
continue;
if(!(brft.prevLin is GraphNodeEmit))
continue;
GraphNodeEmit cmp = (GraphNodeEmit)brft.prevLin;
if(cmp.opcode.StackBehaviourPop != StackBehaviour.Pop1_pop1)
continue;
if(cmp.opcode.StackBehaviourPush != StackBehaviour.Pushi)
continue;
cmp.prevLin.nextLin = brft;
brft.prevLin = cmp.prevLin;
bool brtru = (brft.opcode == OpCodes.Brtrue);
if(cmp.opcode == OpCodes.Ceq)
brft.opcode = brtru ? OpCodes.Beq : OpCodes.Bne_Un;
else if(cmp.opcode == OpCodes.Cgt)
brft.opcode = brtru ? OpCodes.Bgt : OpCodes.Ble;
else if(cmp.opcode == OpCodes.Cgt_Un)
brft.opcode = brtru ? OpCodes.Bgt_Un : OpCodes.Ble_Un;
else if(cmp.opcode == OpCodes.Clt)
brft.opcode = brtru ? OpCodes.Blt : OpCodes.Bge;
else if(cmp.opcode == OpCodes.Clt_Un)
brft.opcode = brtru ? OpCodes.Blt_Un : OpCodes.Bge_Un;
else
throw new Exception();
didSomething = true;
}
// Replace ld{c.i4.0,null}/br{ne.un,eq} -> br{true,false}
for(GraphNode gn = firstLin; gn != null; gn = gn.nextLin)
{
if(!(gn is GraphNodeEmit))
continue;
GraphNodeEmit brcc = (GraphNodeEmit)gn;
if((brcc.opcode != OpCodes.Bne_Un) && (brcc.opcode != OpCodes.Beq))
continue;
if(!(brcc.prevLin is GraphNodeEmit))
continue;
GraphNodeEmit ldc0 = (GraphNodeEmit)brcc.prevLin;
if((ldc0.opcode != OpCodes.Ldc_I4_0) && (ldc0.opcode != OpCodes.Ldnull))
continue;
ldc0.prevLin.nextLin = brcc;
brcc.prevLin = ldc0.prevLin;
brcc.opcode = (brcc.opcode == OpCodes.Bne_Un) ? OpCodes.Brtrue : OpCodes.Brfalse;
didSomething = true;
}
// Replace:
// ldloc v1
// stloc v2
// ld<anything> except ld<anything> v2
// ldloc v2
// ...v2 unreferenced hereafter
// With:
// ld<anything> except ld<anything> v2
// ldloc v1
for(GraphNode gn = firstLin; gn != null; gn = gn.nextLin)
{
// check for 'ldloc v1' instruction
if(!(gn is GraphNodeEmitLocal))
continue;
GraphNodeEmitLocal ldlv1 = (GraphNodeEmitLocal)gn;
if(ldlv1.opcode != OpCodes.Ldloc)
continue;
// check for 'stloc v2' instruction
if(!(ldlv1.nextLin is GraphNodeEmitLocal))
continue;
GraphNodeEmitLocal stlv2 = (GraphNodeEmitLocal)ldlv1.nextLin;
if(stlv2.opcode != OpCodes.Stloc)
continue;
// check for 'ld<anything> except ld<anything> v2' instruction
if(!(stlv2.nextLin is GraphNodeEmit))
continue;
GraphNodeEmit ldany = (GraphNodeEmit)stlv2.nextLin;
if(!ldany.opcode.ToString().StartsWith("ld"))
continue;
if((ldany is GraphNodeEmitLocal) &&
((GraphNodeEmitLocal)ldany).myLocal == stlv2.myLocal)
continue;
// check for 'ldloc v2' instruction
if(!(ldany.nextLin is GraphNodeEmitLocal))
continue;
GraphNodeEmitLocal ldlv2 = (GraphNodeEmitLocal)ldany.nextLin;
if(ldlv2.opcode != OpCodes.Ldloc)
continue;
if(ldlv2.myLocal != stlv2.myLocal)
continue;
// check that v2 is not needed after this at all
if(IsLocalNeededAfterThis(ldlv2, ldlv2.myLocal))
continue;
// make 'ld<anything>...' the first instruction
ldany.prevLin = ldlv1.prevLin;
ldany.prevLin.nextLin = ldany;
// make 'ldloc v1' the second instruction
ldany.nextLin = ldlv1;
ldlv1.prevLin = ldany;
// and make 'ldloc v1' the last instruction
ldlv1.nextLin = ldlv2.nextLin;
ldlv1.nextLin.prevLin = ldlv1;
didSomething = true;
}
// Remove all the stloc/ldloc that are back-to-back without the local
// being needed afterwards. If it is needed afterwards, replace the
// stloc/ldloc with dup/stloc.
for(GraphNode gn = firstLin; gn != null; gn = gn.nextLin)
{
if((gn is GraphNodeEmitLocal) &&
(gn.prevLin is GraphNodeEmitLocal))
{
GraphNodeEmitLocal stloc = (GraphNodeEmitLocal)gn.prevLin;
GraphNodeEmitLocal ldloc = (GraphNodeEmitLocal)gn;
if((stloc.opcode == OpCodes.Stloc) &&
(ldloc.opcode == OpCodes.Ldloc) &&
(stloc.myLocal == ldloc.myLocal))
{
if(IsLocalNeededAfterThis(ldloc, ldloc.myLocal))
{
GraphNodeEmitNull dup = new GraphNodeEmitNull(this, stloc.errorAt, OpCodes.Dup);
dup.nextLin = stloc;
dup.prevLin = stloc.prevLin;
stloc.nextLin = ldloc.nextLin;
stloc.prevLin = dup;
dup.prevLin.nextLin = dup;
stloc.nextLin.prevLin = stloc;
gn = stloc;
}
else
{
stloc.prevLin.nextLin = ldloc.nextLin;
ldloc.nextLin.prevLin = stloc.prevLin;
gn = stloc.prevLin;
}
didSomething = true;
}
}
}
// Remove all write-only local variables, ie, those with no ldloc[a] references.
// Replace any stloc instructions with pops.
for(GraphNode gn = firstLin; gn != null; gn = gn.nextLin)
{
ScriptMyLocal rdlcl = gn.ReadsLocal();
if(rdlcl != null)
rdlcl.isReferenced = true;
}
for(GraphNode gn = firstLin; gn != null; gn = gn.nextLin)
{
ScriptMyLocal wrlcl = gn.WritesLocal();
if((wrlcl != null) && !wrlcl.isReferenced)
{
if(!(gn is GraphNodeEmitLocal) || (((GraphNodeEmitLocal)gn).opcode != OpCodes.Stloc))
{
throw new Exception("expecting stloc");
}
GraphNodeEmitNull pop = new GraphNodeEmitNull(this, ((GraphNodeEmit)gn).errorAt, OpCodes.Pop);
pop.nextLin = gn.nextLin;
pop.prevLin = gn.prevLin;
gn.nextLin.prevLin = pop;
gn.prevLin.nextLin = pop;
gn = pop;
didSomething = true;
}
}
// Remove any Ld<const>/Dup,Pop.
for(GraphNode gn = firstLin; gn != null; gn = gn.nextLin)
{
if((gn is GraphNodeEmit) &&
(gn.nextLin is GraphNodeEmit))
{
GraphNodeEmit gne = (GraphNodeEmit)gn;
GraphNodeEmit nne = (GraphNodeEmit)gn.nextLin;
if(gne.isPoppable && (nne.opcode == OpCodes.Pop))
{
gne.prevLin.nextLin = nne.nextLin;
nne.nextLin.prevLin = gne.prevLin;
gn = gne.prevLin;
didSomething = true;
}
}
}
} while(didSomething);
// Dump out the results.
if(DEBUG)
{
Console.WriteLine("");
Console.WriteLine(methName);
Console.WriteLine(" resolveSequence=" + this.resolveSequence);
Console.WriteLine(" Locals:");
foreach(ScriptMyLocal loc in declaredLocals)
{
Console.WriteLine(" " + loc.type.Name + " " + loc.name);
}
Console.WriteLine(" Labels:");
foreach(ScriptMyLabel lbl in definedLabels)
{
Console.WriteLine(" " + lbl.name);
}
Console.WriteLine(" Code:");
DumpCode();
}
}
private void DumpCode()
{
int linSeqNos = 0;
for(GraphNode gn = firstLin; gn != null; gn = gn.nextLin)
{
gn.linSeqNo = ++linSeqNos;
}
for(GraphNode gn = firstLin; gn != null; gn = gn.nextLin)
{
StringBuilder sb = new StringBuilder();
gn.DebStringExt(sb);
Console.WriteLine(sb.ToString());
if(gn is GraphNodeBlock)
{
GraphNodeBlock gnb = (GraphNodeBlock)gn;
foreach(ScriptMyLocal lcl in gnb.localsReadBeforeWritten)
{
Console.WriteLine(" reads " + lcl.name);
}
}
}
}
/**
* @brief Scan the given block for branches to other blocks.
* For any locals read by those blocks, mark them as being read by this block,
* provided this block has not written them by that point. This makes it look
* as though the branch instruction is reading all the locals needed by any
* target blocks.
*/
private void ResolveBlock(GraphNodeBlock currentBlock)
{
if(currentBlock.hasBeenResolved == this.resolveSequence)
return;
// So we don't recurse forever on a backward branch.
currentBlock.hasBeenResolved = this.resolveSequence;
// Assume we haven't written any locals yet.
List<ScriptMyLocal> localsWrittenSoFar = new List<ScriptMyLocal>();
// Scan through the instructions in this block.
for(GraphNode gn = currentBlock; gn != null;)
{
// See if the instruction writes a local we don't know about yet.
ScriptMyLocal wrlcl = gn.WritesLocal();
if((wrlcl != null) && !localsWrittenSoFar.Contains(wrlcl))
{
localsWrittenSoFar.Add(wrlcl);
}
// Scan through all the possible next instructions after this.
// Note that if we are in the first part of a try/catch/finally block,
// every instruction conditionally branches to the beginning of the
// second part (the catch/finally block).
GraphNode nextFallthruNode = null;
foreach(GraphNode nn in gn.NextNodes)
{
if(nn is GraphNodeBlock)
{
// Start of a block, go through all locals needed by that block on entry.
GraphNodeBlock nextBlock = (GraphNodeBlock)nn;
ResolveBlock(nextBlock);
foreach(ScriptMyLocal readByNextBlock in nextBlock.localsReadBeforeWritten)
{
// If this block hasn't written it by now and this block doesn't already
// require it on entry, say this block requires it on entry.
if(!localsWrittenSoFar.Contains(readByNextBlock) &&
!currentBlock.localsReadBeforeWritten.Contains(readByNextBlock))
{
currentBlock.localsReadBeforeWritten.Add(readByNextBlock);
this.resolvedSomething = true;
}
}
}
else
{
// Not start of a block, should be normal fallthru instruction.
if(nextFallthruNode != null)
throw new Exception("more than one fallthru from " + gn.ToString());
nextFallthruNode = nn;
}
}
// Process next instruction if it isn't the start of a block.
if(nextFallthruNode == gn)
throw new Exception("can't fallthru to self");
gn = nextFallthruNode;
}
}
/**
* @brief Figure out whether the value in a local var is needed after the given instruction.
* True if we reach the end of the program on all branches before reading it
* True if we write the local var on all branches before reading it
* False otherwise
*/
private bool IsLocalNeededAfterThis(GraphNode node, ScriptMyLocal local)
{
do
{
GraphNode nextFallthruNode = null;
foreach(GraphNode nn in node.NextNodes)
{
if(nn is GraphNodeBlock)
{
if(((GraphNodeBlock)nn).localsReadBeforeWritten.Contains(local))
{
return true;
}
}
else
{
nextFallthruNode = nn;
}
}
node = nextFallthruNode;
if(node == null)
return false;
if(node.ReadsLocal() == local)
return true;
} while(node.WritesLocal() != local);
return false;
}
public static void PadToLength(StringBuilder sb, int len, string str)
{
int pad = len - sb.Length;
if(pad < 0)
pad = 0;
sb.Append(str.PadLeft(pad));
}
}
}
|