summaryrefslogtreecommitdiff
path: root/src/jit/inlinepolicy.cpp
blob: 61e70c3ed412bcf7f775a44a7d0f9317ca7df527 (plain)
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#include "jitpch.h"
#ifdef _MSC_VER
#pragma hdrstop
#endif

#include "inlinepolicy.h"
#include "sm.h"

//------------------------------------------------------------------------
// getPolicy: Factory method for getting an InlinePolicy
//
// Arguments:
//    compiler      - the compiler instance that will evaluate inlines
//    isPrejitRoot  - true if this policy is evaluating a prejit root
//
// Return Value:
//    InlinePolicy to use in evaluating an inline.
//
// Notes:
//    Determines which of the various policies should apply,
//    and creates (or reuses) a policy instance to use.

InlinePolicy* InlinePolicy::GetPolicy(Compiler* compiler, bool isPrejitRoot)
{

#if defined(DEBUG) || defined(INLINE_DATA)

#if defined(DEBUG)
    const bool useRandomPolicyForStress = compiler->compRandomInlineStress();
#else
    const bool useRandomPolicyForStress = false;
#endif // defined(DEBUG)

    const bool useRandomPolicy = (JitConfig.JitInlinePolicyRandom() != 0);

    // Optionally install the RandomPolicy.
    if (useRandomPolicyForStress || useRandomPolicy)
    {
        return new (compiler, CMK_Inlining) RandomPolicy(compiler, isPrejitRoot);
    }

    // Optionally install the ReplayPolicy.
    bool useReplayPolicy = JitConfig.JitInlinePolicyReplay() != 0;

    if (useReplayPolicy)
    {
        return new (compiler, CMK_Inlining) ReplayPolicy(compiler, isPrejitRoot);
    }

    // Optionally install the SizePolicy.
    bool useSizePolicy = JitConfig.JitInlinePolicySize() != 0;

    if (useSizePolicy)
    {
        return new (compiler, CMK_Inlining) SizePolicy(compiler, isPrejitRoot);
    }

    // Optionally install the FullPolicy.
    bool useFullPolicy = JitConfig.JitInlinePolicyFull() != 0;

    if (useFullPolicy)
    {
        return new (compiler, CMK_Inlining) FullPolicy(compiler, isPrejitRoot);
    }

    // Optionally install the DiscretionaryPolicy.
    bool useDiscretionaryPolicy = JitConfig.JitInlinePolicyDiscretionary() != 0;

    if (useDiscretionaryPolicy)
    {
        return new (compiler, CMK_Inlining) DiscretionaryPolicy(compiler, isPrejitRoot);
    }

#endif // defined(DEBUG) || defined(INLINE_DATA)

    // Optionally install the ModelPolicy.
    bool useModelPolicy = JitConfig.JitInlinePolicyModel() != 0;

    if (useModelPolicy)
    {
        return new (compiler, CMK_Inlining) ModelPolicy(compiler, isPrejitRoot);
    }

    // Optionally fallback to the original legacy policy
    bool useLegacyPolicy = JitConfig.JitInlinePolicyLegacy() != 0;

    if (useLegacyPolicy)
    {
        return new (compiler, CMK_Inlining) LegacyPolicy(compiler, isPrejitRoot);
    }

    // Use the enhanced legacy policy by default
    return new (compiler, CMK_Inlining) EnhancedLegacyPolicy(compiler, isPrejitRoot);
}

//------------------------------------------------------------------------
// NoteFatal: handle an observation with fatal impact
//
// Arguments:
//    obs      - the current obsevation

void LegalPolicy::NoteFatal(InlineObservation obs)
{
    // As a safeguard, all fatal impact must be
    // reported via NoteFatal.
    assert(InlGetImpact(obs) == InlineImpact::FATAL);
    NoteInternal(obs);
    assert(InlDecisionIsFailure(m_Decision));
}

//------------------------------------------------------------------------
// NoteInternal: helper for handling an observation
//
// Arguments:
//    obs      - the current obsevation

void LegalPolicy::NoteInternal(InlineObservation obs)
{
    // Note any INFORMATION that reaches here will now cause failure.
    // Non-fatal INFORMATION observations must be handled higher up.
    InlineTarget target = InlGetTarget(obs);

    if (target == InlineTarget::CALLEE)
    {
        this->SetNever(obs);
    }
    else
    {
        this->SetFailure(obs);
    }
}

//------------------------------------------------------------------------
// SetFailure: helper for setting a failing decision
//
// Arguments:
//    obs      - the current obsevation

void LegalPolicy::SetFailure(InlineObservation obs)
{
    // Expect a valid observation
    assert(InlIsValidObservation(obs));

    switch (m_Decision)
    {
        case InlineDecision::FAILURE:
            // Repeated failure only ok if evaluating a prejit root
            // (since we can't fail fast because we're not inlining)
            // or if inlining and the observation is CALLSITE_TOO_MANY_LOCALS
            // (since we can't fail fast from lvaGrabTemp).
            assert(m_IsPrejitRoot || (obs == InlineObservation::CALLSITE_TOO_MANY_LOCALS));
            break;
        case InlineDecision::UNDECIDED:
        case InlineDecision::CANDIDATE:
            m_Decision    = InlineDecision::FAILURE;
            m_Observation = obs;
            break;
        default:
            // SUCCESS, NEVER, or ??
            assert(!"Unexpected m_Decision");
            unreached();
    }
}

//------------------------------------------------------------------------
// SetNever: helper for setting a never decision
//
// Arguments:
//    obs      - the current obsevation

void LegalPolicy::SetNever(InlineObservation obs)
{
    // Expect a valid observation
    assert(InlIsValidObservation(obs));

    switch (m_Decision)
    {
        case InlineDecision::NEVER:
            // Repeated never only ok if evaluating a prejit root
            assert(m_IsPrejitRoot);
            break;
        case InlineDecision::UNDECIDED:
        case InlineDecision::CANDIDATE:
            m_Decision    = InlineDecision::NEVER;
            m_Observation = obs;
            break;
        default:
            // SUCCESS, FAILURE or ??
            assert(!"Unexpected m_Decision");
            unreached();
    }
}

//------------------------------------------------------------------------
// SetCandidate: helper updating candidacy
//
// Arguments:
//    obs      - the current obsevation
//
// Note:
//    Candidate observations are handled here. If the inline has already
//    failed, they're ignored. If there's already a candidate reason,
//    this new reason trumps it.

void LegalPolicy::SetCandidate(InlineObservation obs)
{
    // Ignore if this inline is going to fail.
    if (InlDecisionIsFailure(m_Decision))
    {
        return;
    }

    // We should not have declared success yet.
    assert(!InlDecisionIsSuccess(m_Decision));

    // Update, overriding any previous candidacy.
    m_Decision    = InlineDecision::CANDIDATE;
    m_Observation = obs;
}

//------------------------------------------------------------------------
// NoteSuccess: handle finishing all the inlining checks successfully

void LegacyPolicy::NoteSuccess()
{
    assert(InlDecisionIsCandidate(m_Decision));
    m_Decision = InlineDecision::SUCCESS;
}

//------------------------------------------------------------------------
// NoteBool: handle a boolean observation with non-fatal impact
//
// Arguments:
//    obs      - the current obsevation
//    value    - the value of the observation
void LegacyPolicy::NoteBool(InlineObservation obs, bool value)
{
    // Check the impact
    InlineImpact impact = InlGetImpact(obs);

    // As a safeguard, all fatal impact must be
    // reported via NoteFatal.
    assert(impact != InlineImpact::FATAL);

    // Handle most information here
    bool isInformation = (impact == InlineImpact::INFORMATION);
    bool propagate     = !isInformation;

    if (isInformation)
    {
        switch (obs)
        {
            case InlineObservation::CALLEE_IS_FORCE_INLINE:
                // We may make the force-inline observation more than
                // once.  All observations should agree.
                assert(!m_IsForceInlineKnown || (m_IsForceInline == value));
                m_IsForceInline      = value;
                m_IsForceInlineKnown = true;
                break;

            case InlineObservation::CALLEE_IS_INSTANCE_CTOR:
                m_IsInstanceCtor = value;
                break;

            case InlineObservation::CALLEE_CLASS_PROMOTABLE:
                m_IsFromPromotableValueClass = value;
                break;

            case InlineObservation::CALLEE_HAS_SIMD:
                m_HasSimd = value;
                break;

            case InlineObservation::CALLEE_LOOKS_LIKE_WRAPPER:
                // LegacyPolicy ignores this for prejit roots.
                if (!m_IsPrejitRoot)
                {
                    m_LooksLikeWrapperMethod = value;
                }
                break;

            case InlineObservation::CALLEE_ARG_FEEDS_CONSTANT_TEST:
                // LegacyPolicy ignores this for prejit roots.
                if (!m_IsPrejitRoot)
                {
                    m_ArgFeedsConstantTest++;
                }
                break;

            case InlineObservation::CALLEE_ARG_FEEDS_RANGE_CHECK:
                // LegacyPolicy ignores this for prejit roots.
                if (!m_IsPrejitRoot)
                {
                    m_ArgFeedsRangeCheck++;
                }
                break;

            case InlineObservation::CALLEE_HAS_SWITCH:
            case InlineObservation::CALLEE_UNSUPPORTED_OPCODE:
                // LegacyPolicy ignores these for prejit roots.
                if (!m_IsPrejitRoot)
                {
                    // Pass these on, they should cause inlining to fail.
                    propagate = true;
                }
                break;

            case InlineObservation::CALLSITE_CONSTANT_ARG_FEEDS_TEST:
                // We shouldn't see this for a prejit root since
                // we don't know anything about callers.
                assert(!m_IsPrejitRoot);
                m_ConstantArgFeedsConstantTest++;
                break;

            case InlineObservation::CALLEE_BEGIN_OPCODE_SCAN:
            {
                // Set up the state machine, if this inline is
                // discretionary and is still a candidate.
                if (InlDecisionIsCandidate(m_Decision) &&
                    (m_Observation == InlineObservation::CALLEE_IS_DISCRETIONARY_INLINE))
                {
                    // Better not have a state machine already.
                    assert(m_StateMachine == nullptr);
                    m_StateMachine = new (m_RootCompiler, CMK_Inlining) CodeSeqSM;
                    m_StateMachine->Start(m_RootCompiler);
                }
                break;
            }

            case InlineObservation::CALLEE_END_OPCODE_SCAN:
            {
                if (m_StateMachine != nullptr)
                {
                    m_StateMachine->End();
                }

                // If this function is mostly loads and stores, we
                // should try harder to inline it.  You can't just use
                // the percentage test because if the method has 8
                // instructions and 6 are loads, it's only 75% loads.
                // This allows for CALL, RET, and one more non-ld/st
                // instruction.
                if (((m_InstructionCount - m_LoadStoreCount) < 4) ||
                    (((double)m_LoadStoreCount / (double)m_InstructionCount) > .90))
                {
                    m_MethodIsMostlyLoadStore = true;
                }

                // Budget check.
                //
                // Conceptually this should happen when we
                // observe the candidate's IL size.
                //
                // However, we do this here to avoid potential
                // inconsistency between the state of the budget
                // during candidate scan and the state when the IL is
                // being scanned.
                //
                // Consider the case where we're just below the budget
                // during candidate scan, and we have three possible
                // inlines, any two of which put us over budget. We
                // allow them all to become candidates. We then move
                // on to inlining and the first two get inlined and
                // put us over budget. Now the third can't be inlined
                // anymore, but we have a policy that when we replay
                // the candidate IL size during the inlining pass it
                // "reestablishes" candidacy rather than alters
                // candidacy ... so instead we bail out here.

                if (!m_IsPrejitRoot)
                {
                    InlineStrategy* strategy   = m_RootCompiler->m_inlineStrategy;
                    bool            overBudget = strategy->BudgetCheck(m_CodeSize);
                    if (overBudget)
                    {
                        SetFailure(InlineObservation::CALLSITE_OVER_BUDGET);
                    }
                }

                break;
            }

            case InlineObservation::CALLEE_HAS_PINNED_LOCALS:
                // The legacy policy is to never inline methods with
                // pinned locals.
                SetNever(obs);
                break;

            default:
                // Ignore the remainder for now
                break;
        }
    }

    if (propagate)
    {
        NoteInternal(obs);
    }
}

//------------------------------------------------------------------------
// NoteInt: handle an observed integer value
//
// Arguments:
//    obs      - the current obsevation
//    value    - the value being observed

void LegacyPolicy::NoteInt(InlineObservation obs, int value)
{
    switch (obs)
    {
        case InlineObservation::CALLEE_MAXSTACK:
        {
            assert(m_IsForceInlineKnown);

            unsigned calleeMaxStack = static_cast<unsigned>(value);

            if (!m_IsForceInline && (calleeMaxStack > SMALL_STACK_SIZE))
            {
                SetNever(InlineObservation::CALLEE_MAXSTACK_TOO_BIG);
            }

            break;
        }

        case InlineObservation::CALLEE_NUMBER_OF_BASIC_BLOCKS:
        {
            assert(m_IsForceInlineKnown);
            assert(value != 0);

            unsigned basicBlockCount = static_cast<unsigned>(value);

            if (!m_IsForceInline && (basicBlockCount > MAX_BASIC_BLOCKS))
            {
                SetNever(InlineObservation::CALLEE_TOO_MANY_BASIC_BLOCKS);
            }

            break;
        }

        case InlineObservation::CALLEE_IL_CODE_SIZE:
        {
            assert(m_IsForceInlineKnown);
            assert(value != 0);
            m_CodeSize = static_cast<unsigned>(value);

            // Now that we know size and forceinline state,
            // update candidacy.
            if (m_IsForceInline)
            {
                // Candidate based on force inline
                SetCandidate(InlineObservation::CALLEE_IS_FORCE_INLINE);
            }
            else if (m_CodeSize <= InlineStrategy::ALWAYS_INLINE_SIZE)
            {
                // Candidate based on small size
                SetCandidate(InlineObservation::CALLEE_BELOW_ALWAYS_INLINE_SIZE);
            }
            else if (m_CodeSize <= m_RootCompiler->m_inlineStrategy->GetMaxInlineILSize())
            {
                // Candidate, pending profitability evaluation
                SetCandidate(InlineObservation::CALLEE_IS_DISCRETIONARY_INLINE);
            }
            else
            {
                // Callee too big, not a candidate
                SetNever(InlineObservation::CALLEE_TOO_MUCH_IL);
            }

            break;
        }

        case InlineObservation::CALLSITE_DEPTH:
        {
            unsigned depth = static_cast<unsigned>(value);

            if (depth > m_RootCompiler->m_inlineStrategy->GetMaxInlineDepth())
            {
                SetFailure(InlineObservation::CALLSITE_IS_TOO_DEEP);
            }

            break;
        }

        case InlineObservation::CALLEE_OPCODE_NORMED:
        case InlineObservation::CALLEE_OPCODE:
        {
            m_InstructionCount++;
            OPCODE opcode = static_cast<OPCODE>(value);

            if (m_StateMachine != nullptr)
            {
                SM_OPCODE smOpcode = CodeSeqSM::MapToSMOpcode(opcode);
                noway_assert(smOpcode < SM_COUNT);
                noway_assert(smOpcode != SM_PREFIX_N);
                if (obs == InlineObservation::CALLEE_OPCODE_NORMED)
                {
                    if (smOpcode == SM_LDARGA_S)
                    {
                        smOpcode = SM_LDARGA_S_NORMED;
                    }
                    else if (smOpcode == SM_LDLOCA_S)
                    {
                        smOpcode = SM_LDLOCA_S_NORMED;
                    }
                }

                m_StateMachine->Run(smOpcode DEBUGARG(0));
            }

            // Look for opcodes that imply loads and stores.
            // Logic here is as it is to match legacy behavior.
            if ((opcode >= CEE_LDARG_0 && opcode <= CEE_STLOC_S) || (opcode >= CEE_LDARG && opcode <= CEE_STLOC) ||
                (opcode >= CEE_LDNULL && opcode <= CEE_LDC_R8) || (opcode >= CEE_LDIND_I1 && opcode <= CEE_STIND_R8) ||
                (opcode >= CEE_LDFLD && opcode <= CEE_STOBJ) || (opcode >= CEE_LDELEMA && opcode <= CEE_STELEM) ||
                (opcode == CEE_POP))
            {
                m_LoadStoreCount++;
            }

            break;
        }

        case InlineObservation::CALLSITE_FREQUENCY:
            assert(m_CallsiteFrequency == InlineCallsiteFrequency::UNUSED);
            m_CallsiteFrequency = static_cast<InlineCallsiteFrequency>(value);
            assert(m_CallsiteFrequency != InlineCallsiteFrequency::UNUSED);
            break;

        default:
            // Ignore all other information
            break;
    }
}

//------------------------------------------------------------------------
// DetermineMultiplier: determine benefit multiplier for this inline
//
// Notes: uses the accumulated set of observations to compute a
// profitability boost for the inline candidate.

double LegacyPolicy::DetermineMultiplier()
{
    double multiplier = 0;

    // Bump up the multiplier for instance constructors

    if (m_IsInstanceCtor)
    {
        multiplier += 1.5;
        JITDUMP("\nmultiplier in instance constructors increased to %g.", multiplier);
    }

    // Bump up the multiplier for methods in promotable struct

    if (m_IsFromPromotableValueClass)
    {
        multiplier += 3;
        JITDUMP("\nmultiplier in methods of promotable struct increased to %g.", multiplier);
    }

#ifdef FEATURE_SIMD

    if (m_HasSimd)
    {
        multiplier += JitConfig.JitInlineSIMDMultiplier();
        JITDUMP("\nInline candidate has SIMD type args, locals or return value.  Multiplier increased to %g.",
                multiplier);
    }

#endif // FEATURE_SIMD

    if (m_LooksLikeWrapperMethod)
    {
        multiplier += 1.0;
        JITDUMP("\nInline candidate looks like a wrapper method.  Multiplier increased to %g.", multiplier);
    }

    if (m_ArgFeedsConstantTest > 0)
    {
        multiplier += 1.0;
        JITDUMP("\nInline candidate has an arg that feeds a constant test.  Multiplier increased to %g.", multiplier);
    }

    if (m_MethodIsMostlyLoadStore)
    {
        multiplier += 3.0;
        JITDUMP("\nInline candidate is mostly loads and stores.  Multiplier increased to %g.", multiplier);
    }

    if (m_ArgFeedsRangeCheck > 0)
    {
        multiplier += 0.5;
        JITDUMP("\nInline candidate has arg that feeds range check.  Multiplier increased to %g.", multiplier);
    }

    if (m_ConstantArgFeedsConstantTest > 0)
    {
        multiplier += 3.0;
        JITDUMP("\nInline candidate has const arg that feeds a conditional.  Multiplier increased to %g.", multiplier);
    }

    switch (m_CallsiteFrequency)
    {
        case InlineCallsiteFrequency::RARE:
            // Note this one is not additive, it uses '=' instead of '+='
            multiplier = 1.3;
            JITDUMP("\nInline candidate callsite is rare.  Multiplier limited to %g.", multiplier);
            break;
        case InlineCallsiteFrequency::BORING:
            multiplier += 1.3;
            JITDUMP("\nInline candidate callsite is boring.  Multiplier increased to %g.", multiplier);
            break;
        case InlineCallsiteFrequency::WARM:
            multiplier += 2.0;
            JITDUMP("\nInline candidate callsite is warm.  Multiplier increased to %g.", multiplier);
            break;
        case InlineCallsiteFrequency::LOOP:
            multiplier += 3.0;
            JITDUMP("\nInline candidate callsite is in a loop.  Multiplier increased to %g.", multiplier);
            break;
        case InlineCallsiteFrequency::HOT:
            multiplier += 3.0;
            JITDUMP("\nInline candidate callsite is hot.  Multiplier increased to %g.", multiplier);
            break;
        default:
            assert(!"Unexpected callsite frequency");
            break;
    }

#ifdef DEBUG

    int additionalMultiplier = JitConfig.JitInlineAdditionalMultiplier();

    if (additionalMultiplier != 0)
    {
        multiplier += additionalMultiplier;
        JITDUMP("\nmultiplier increased via JitInlineAdditonalMultiplier=%d to %g.", additionalMultiplier, multiplier);
    }

    if (m_RootCompiler->compInlineStress())
    {
        multiplier += 10;
        JITDUMP("\nmultiplier increased via inline stress to %g.", multiplier);
    }

#endif // DEBUG

    return multiplier;
}

//------------------------------------------------------------------------
// DetermineNativeSizeEstimate: return estimated native code size for
// this inline candidate.
//
// Notes:
//    This is an estimate for the size of the inlined callee.
//    It does not include size impact on the caller side.
//
//    Uses the results of a state machine model for discretionary
//    candidates.  Should not be needed for forced or always
//    candidates.

int LegacyPolicy::DetermineNativeSizeEstimate()
{
    // Should be a discretionary candidate.
    assert(m_StateMachine != nullptr);

    return m_StateMachine->NativeSize;
}

//------------------------------------------------------------------------
// DetermineCallsiteNativeSizeEstimate: estimate native size for the
// callsite.
//
// Arguments:
//    methInfo -- method info for the callee
//
// Notes:
//    Estimates the native size (in bytes, scaled up by 10x) for the
//    call site. While the quality of the estimate here is questionable
//    (especially for x64) it is being left as is for legacy compatibility.

int LegacyPolicy::DetermineCallsiteNativeSizeEstimate(CORINFO_METHOD_INFO* methInfo)
{
    int callsiteSize = 55; // Direct call take 5 native bytes; indirect call takes 6 native bytes.

    bool hasThis = methInfo->args.hasThis();

    if (hasThis)
    {
        callsiteSize += 30; // "mov" or "lea"
    }

    CORINFO_ARG_LIST_HANDLE argLst = methInfo->args.args;
    COMP_HANDLE             comp   = m_RootCompiler->info.compCompHnd;

    for (unsigned i = (hasThis ? 1 : 0); i < methInfo->args.totalILArgs(); i++, argLst = comp->getArgNext(argLst))
    {
        var_types sigType = (var_types)m_RootCompiler->eeGetArgType(argLst, &methInfo->args);

        if (sigType == TYP_STRUCT)
        {
            typeInfo verType = m_RootCompiler->verParseArgSigToTypeInfo(&methInfo->args, argLst);

            /*

            IN0028: 00009B      lea     EAX, bword ptr [EBP-14H]
            IN0029: 00009E      push    dword ptr [EAX+4]
            IN002a: 0000A1      push    gword ptr [EAX]
            IN002b: 0000A3      call    [MyStruct.staticGetX2(struct):int]

            */

            callsiteSize += 10; // "lea     EAX, bword ptr [EBP-14H]"

            // NB sizeof (void*) fails to convey intent when cross-jitting.

            unsigned opsz  = (unsigned)(roundUp(comp->getClassSize(verType.GetClassHandle()), sizeof(void*)));
            unsigned slots = opsz / sizeof(void*);

            callsiteSize += slots * 20; // "push    gword ptr [EAX+offs]  "
        }
        else
        {
            callsiteSize += 30; // push by average takes 3 bytes.
        }
    }

    return callsiteSize;
}

//------------------------------------------------------------------------
// DetermineProfitability: determine if this inline is profitable
//
// Arguments:
//    methodInfo -- method info for the callee
//
// Notes:
//    A profitable inline is one that is projected to have a beneficial
//    size/speed tradeoff.
//
//    It is expected that this method is only invoked for discretionary
//    candidates, since it does not make sense to do this assessment for
//    failed, always, or forced inlines.

void LegacyPolicy::DetermineProfitability(CORINFO_METHOD_INFO* methodInfo)
{

#if defined(DEBUG)

    // Punt if we're inlining and we've reached the acceptance limit.
    int      limit   = JitConfig.JitInlineLimit();
    unsigned current = m_RootCompiler->m_inlineStrategy->GetInlineCount();

    if (!m_IsPrejitRoot && (limit >= 0) && (current >= static_cast<unsigned>(limit)))
    {
        SetFailure(InlineObservation::CALLSITE_OVER_INLINE_LIMIT);
        return;
    }

#endif // defined(DEBUG)

    assert(InlDecisionIsCandidate(m_Decision));
    assert(m_Observation == InlineObservation::CALLEE_IS_DISCRETIONARY_INLINE);

    m_CalleeNativeSizeEstimate   = DetermineNativeSizeEstimate();
    m_CallsiteNativeSizeEstimate = DetermineCallsiteNativeSizeEstimate(methodInfo);
    m_Multiplier                 = DetermineMultiplier();
    const int threshold          = (int)(m_CallsiteNativeSizeEstimate * m_Multiplier);

    // Note the LegacyPolicy estimates are scaled up by SIZE_SCALE
    JITDUMP("\ncalleeNativeSizeEstimate=%d\n", m_CalleeNativeSizeEstimate)
    JITDUMP("callsiteNativeSizeEstimate=%d\n", m_CallsiteNativeSizeEstimate);
    JITDUMP("benefit multiplier=%g\n", m_Multiplier);
    JITDUMP("threshold=%d\n", threshold);

    // Reject if callee size is over the threshold
    if (m_CalleeNativeSizeEstimate > threshold)
    {
        // Inline appears to be unprofitable
        JITLOG_THIS(m_RootCompiler,
                    (LL_INFO100000, "Native estimate for function size exceeds threshold"
                                    " for inlining %g > %g (multiplier = %g)\n",
                     (double)m_CalleeNativeSizeEstimate / SIZE_SCALE, (double)threshold / SIZE_SCALE, m_Multiplier));

        // Fail the inline
        if (m_IsPrejitRoot)
        {
            SetNever(InlineObservation::CALLEE_NOT_PROFITABLE_INLINE);
        }
        else
        {
            SetFailure(InlineObservation::CALLSITE_NOT_PROFITABLE_INLINE);
        }
    }
    else
    {
        // Inline appears to be profitable
        JITLOG_THIS(m_RootCompiler,
                    (LL_INFO100000, "Native estimate for function size is within threshold"
                                    " for inlining %g <= %g (multiplier = %g)\n",
                     (double)m_CalleeNativeSizeEstimate / SIZE_SCALE, (double)threshold / SIZE_SCALE, m_Multiplier));

        // Update candidacy
        if (m_IsPrejitRoot)
        {
            SetCandidate(InlineObservation::CALLEE_IS_PROFITABLE_INLINE);
        }
        else
        {
            SetCandidate(InlineObservation::CALLSITE_IS_PROFITABLE_INLINE);
        }
    }
}

//------------------------------------------------------------------------
// CodeSizeEstimate: estimated code size impact of the inline
//
// Return Value:
//    Estimated code size impact, in bytes * 10
//
// Notes:
//    Only meaningful for discretionary inlines (whether successful or
//    not).  For always or force inlines the legacy policy doesn't
//    estimate size impact.

int LegacyPolicy::CodeSizeEstimate()
{
    if (m_StateMachine != nullptr)
    {
        // This is not something the LegacyPolicy explicitly computed,
        // since it uses a blended evaluation model (mixing size and time
        // together for overall profitability). But it's effecitvely an
        // estimate of the size impact.
        return (m_CalleeNativeSizeEstimate - m_CallsiteNativeSizeEstimate);
    }
    else
    {
        return 0;
    }
}

//------------------------------------------------------------------------
// NoteBool: handle a boolean observation with non-fatal impact
//
// Arguments:
//    obs      - the current observation
//    value    - the value of the observation

void EnhancedLegacyPolicy::NoteBool(InlineObservation obs, bool value)
{

#ifdef DEBUG
    // Check the impact
    InlineImpact impact = InlGetImpact(obs);

    // As a safeguard, all fatal impact must be
    // reported via NoteFatal.
    assert(impact != InlineImpact::FATAL);
#endif // DEBUG

    switch (obs)
    {
        case InlineObservation::CALLEE_DOES_NOT_RETURN:
            m_IsNoReturn      = value;
            m_IsNoReturnKnown = true;
            break;

        case InlineObservation::CALLSITE_RARE_GC_STRUCT:
            // If this is a discretionary or always inline candidate
            // with a gc struct, we may change our mind about inlining
            // if the call site is rare, to avoid costs associated with
            // zeroing the GC struct up in the root prolog.
            if (m_Observation == InlineObservation::CALLEE_BELOW_ALWAYS_INLINE_SIZE)
            {
                assert(m_CallsiteFrequency == InlineCallsiteFrequency::UNUSED);
                SetFailure(obs);
                return;
            }
            else if (m_Observation == InlineObservation::CALLEE_IS_DISCRETIONARY_INLINE)
            {
                assert(m_CallsiteFrequency == InlineCallsiteFrequency::RARE);
                SetFailure(obs);
                return;
            }
            break;

        case InlineObservation::CALLEE_HAS_PINNED_LOCALS:
            if (m_CallsiteIsInTryRegion)
            {
                // Inlining a method with pinned locals in a try
                // region requires wrapping the inline body in a
                // try/finally to ensure unpinning. Bail instead.
                SetFailure(InlineObservation::CALLSITE_PIN_IN_TRY_REGION);
                return;
            }
            break;

        default:
            // Pass all other information to the legacy policy
            LegacyPolicy::NoteBool(obs, value);
            break;
    }
}

//------------------------------------------------------------------------
// NoteInt: handle an observed integer value
//
// Arguments:
//    obs      - the current obsevation
//    value    - the value being observed

void EnhancedLegacyPolicy::NoteInt(InlineObservation obs, int value)
{
    switch (obs)
    {
        case InlineObservation::CALLEE_NUMBER_OF_BASIC_BLOCKS:
        {
            assert(value != 0);
            assert(m_IsNoReturnKnown);

            //
            // Let's be conservative for now and reject inlining of "no return" methods only
            // if the callee contains a single basic block. This covers most of the use cases
            // (typical throw helpers simply do "throw new X();" and so they have a single block)
            // without affecting more exotic cases (loops that do actual work for example) where
            // failure to inline could negatively impact code quality.
            //

            unsigned basicBlockCount = static_cast<unsigned>(value);

            if (m_IsNoReturn && (basicBlockCount == 1))
            {
                SetNever(InlineObservation::CALLEE_DOES_NOT_RETURN);
            }
            else
            {
                LegacyPolicy::NoteInt(obs, value);
            }

            break;
        }

        default:
            // Pass all other information to the legacy policy
            LegacyPolicy::NoteInt(obs, value);
            break;
    }
}

//------------------------------------------------------------------------
// PropagateNeverToRuntime: determine if a never result should cause the
// method to be marked as un-inlinable.

bool EnhancedLegacyPolicy::PropagateNeverToRuntime() const
{
    //
    // Do not propagate the "no return" observation. If we do this then future inlining
    // attempts will fail immediately without marking the call node as "no return".
    // This can have an adverse impact on caller's code quality as it may have to preserve
    // registers across the call.
    // TODO-Throughput: We should persist the "no return" information in the runtime
    // so we don't need to re-analyze the inlinee all the time.
    //

    bool propagate = (m_Observation != InlineObservation::CALLEE_DOES_NOT_RETURN);

    propagate &= LegacyPolicy::PropagateNeverToRuntime();

    return propagate;
}

#if defined(DEBUG) || defined(INLINE_DATA)

//------------------------------------------------------------------------
// RandomPolicy: construct a new RandomPolicy
//
// Arguments:
//    compiler -- compiler instance doing the inlining (root compiler)
//    isPrejitRoot -- true if this compiler is prejitting the root method

RandomPolicy::RandomPolicy(Compiler* compiler, bool isPrejitRoot) : DiscretionaryPolicy(compiler, isPrejitRoot)
{
    m_Random = compiler->m_inlineStrategy->GetRandom();
}

//------------------------------------------------------------------------
// NoteInt: handle an observed integer value
//
// Arguments:
//    obs      - the current obsevation
//    value    - the value being observed

void RandomPolicy::NoteInt(InlineObservation obs, int value)
{
    switch (obs)
    {
        case InlineObservation::CALLEE_IL_CODE_SIZE:
        {
            assert(m_IsForceInlineKnown);
            assert(value != 0);
            m_CodeSize = static_cast<unsigned>(value);

            if (m_IsForceInline)
            {
                // Candidate based on force inline
                SetCandidate(InlineObservation::CALLEE_IS_FORCE_INLINE);
            }
            else
            {
                // Candidate, pending profitability evaluation
                SetCandidate(InlineObservation::CALLEE_IS_DISCRETIONARY_INLINE);
            }

            break;
        }

        default:
            // Defer to superclass for all other information
            DiscretionaryPolicy::NoteInt(obs, value);
            break;
    }
}

//------------------------------------------------------------------------
// DetermineProfitability: determine if this inline is profitable
//
// Arguments:
//    methodInfo -- method info for the callee
//
// Notes:
//    The random policy makes random decisions about profitablity.
//    Generally we aspire to inline differently, not necessarily to
//    inline more.

void RandomPolicy::DetermineProfitability(CORINFO_METHOD_INFO* methodInfo)
{
    assert(InlDecisionIsCandidate(m_Decision));
    assert(m_Observation == InlineObservation::CALLEE_IS_DISCRETIONARY_INLINE);

    // Budget check.
    if (!m_IsPrejitRoot)
    {
        InlineStrategy* strategy   = m_RootCompiler->m_inlineStrategy;
        bool            overBudget = strategy->BudgetCheck(m_CodeSize);
        if (overBudget)
        {
            SetFailure(InlineObservation::CALLSITE_OVER_BUDGET);
            return;
        }
    }

    // If we're also dumping inline data, make additional observations
    // based on the method info, and estimate code size and perf
    // impact, so that the reports have the necessary data.
    if (JitConfig.JitInlineDumpData() != 0)
    {
        MethodInfoObservations(methodInfo);
        EstimateCodeSize();
        EstimatePerformanceImpact();
    }

    // Use a probability curve that roughly matches the observed
    // behavior of the LegacyPolicy. That way we're inlining
    // differently but not creating enormous methods.
    //
    // We vary a bit at the extremes. The RandomPolicy won't always
    // inline the small methods (<= 16 IL bytes) and won't always
    // reject the large methods (> 100 IL bytes).

    unsigned threshold = 0;

    if (m_CodeSize <= 16)
    {
        threshold = 75;
    }
    else if (m_CodeSize <= 30)
    {
        threshold = 50;
    }
    else if (m_CodeSize <= 40)
    {
        threshold = 40;
    }
    else if (m_CodeSize <= 50)
    {
        threshold = 30;
    }
    else if (m_CodeSize <= 75)
    {
        threshold = 20;
    }
    else if (m_CodeSize <= 100)
    {
        threshold = 10;
    }
    else if (m_CodeSize <= 200)
    {
        threshold = 5;
    }
    else
    {
        threshold = 1;
    }

    unsigned randomValue = m_Random->Next(1, 100);

    // Reject if callee size is over the threshold
    if (randomValue > threshold)
    {
        // Inline appears to be unprofitable
        JITLOG_THIS(m_RootCompiler, (LL_INFO100000, "Random rejection (r=%d > t=%d)\n", randomValue, threshold));

        // Fail the inline
        if (m_IsPrejitRoot)
        {
            SetNever(InlineObservation::CALLEE_RANDOM_REJECT);
        }
        else
        {
            SetFailure(InlineObservation::CALLSITE_RANDOM_REJECT);
        }
    }
    else
    {
        // Inline appears to be profitable
        JITLOG_THIS(m_RootCompiler, (LL_INFO100000, "Random acceptance (r=%d <= t=%d)\n", randomValue, threshold));

        // Update candidacy
        if (m_IsPrejitRoot)
        {
            SetCandidate(InlineObservation::CALLEE_RANDOM_ACCEPT);
        }
        else
        {
            SetCandidate(InlineObservation::CALLSITE_RANDOM_ACCEPT);
        }
    }
}

#endif // defined(DEBUG) || defined(INLINE_DATA)

#ifdef _MSC_VER
// Disable warning about new array member initialization behavior
#pragma warning(disable : 4351)
#endif

//------------------------------------------------------------------------
// DiscretionaryPolicy: construct a new DiscretionaryPolicy
//
// Arguments:
//    compiler -- compiler instance doing the inlining (root compiler)
//    isPrejitRoot -- true if this compiler is prejitting the root method

// clang-format off
DiscretionaryPolicy::DiscretionaryPolicy(Compiler* compiler, bool isPrejitRoot)
    : EnhancedLegacyPolicy(compiler, isPrejitRoot)
    , m_Depth(0)
    , m_BlockCount(0)
    , m_Maxstack(0)
    , m_ArgCount(0)
    , m_ArgType()
    , m_ArgSize()
    , m_LocalCount(0)
    , m_ReturnType(CORINFO_TYPE_UNDEF)
    , m_ReturnSize(0)
    , m_ArgAccessCount(0)
    , m_LocalAccessCount(0)
    , m_IntConstantCount(0)
    , m_FloatConstantCount(0)
    , m_IntLoadCount(0)
    , m_FloatLoadCount(0)
    , m_IntStoreCount(0)
    , m_FloatStoreCount(0)
    , m_SimpleMathCount(0)
    , m_ComplexMathCount(0)
    , m_OverflowMathCount(0)
    , m_IntArrayLoadCount(0)
    , m_FloatArrayLoadCount(0)
    , m_RefArrayLoadCount(0)
    , m_StructArrayLoadCount(0)
    , m_IntArrayStoreCount(0)
    , m_FloatArrayStoreCount(0)
    , m_RefArrayStoreCount(0)
    , m_StructArrayStoreCount(0)
    , m_StructOperationCount(0)
    , m_ObjectModelCount(0)
    , m_FieldLoadCount(0)
    , m_FieldStoreCount(0)
    , m_StaticFieldLoadCount(0)
    , m_StaticFieldStoreCount(0)
    , m_LoadAddressCount(0)
    , m_ThrowCount(0)
    , m_ReturnCount(0)
    , m_CallCount(0)
    , m_CallSiteWeight(0)
    , m_ModelCodeSizeEstimate(0)
    , m_PerCallInstructionEstimate(0)
    , m_IsClassCtor(false)
    , m_IsSameThis(false)
    , m_CallerHasNewArray(false)
    , m_CallerHasNewObj(false)
    , m_CalleeHasGCStruct(false)
{
    // Empty
}
// clang-format on

//------------------------------------------------------------------------
// NoteBool: handle an observed boolean value
//
// Arguments:
//    obs      - the current obsevation
//    value    - the value being observed

void DiscretionaryPolicy::NoteBool(InlineObservation obs, bool value)
{
    switch (obs)
    {
        case InlineObservation::CALLEE_LOOKS_LIKE_WRAPPER:
            m_LooksLikeWrapperMethod = value;
            break;

        case InlineObservation::CALLEE_ARG_FEEDS_CONSTANT_TEST:
            assert(value);
            m_ArgFeedsConstantTest++;
            break;

        case InlineObservation::CALLEE_ARG_FEEDS_RANGE_CHECK:
            assert(value);
            m_ArgFeedsRangeCheck++;
            break;

        case InlineObservation::CALLSITE_CONSTANT_ARG_FEEDS_TEST:
            assert(value);
            m_ConstantArgFeedsConstantTest++;
            break;

        case InlineObservation::CALLEE_IS_CLASS_CTOR:
            m_IsClassCtor = value;
            break;

        case InlineObservation::CALLSITE_IS_SAME_THIS:
            m_IsSameThis = value;
            break;

        case InlineObservation::CALLER_HAS_NEWARRAY:
            m_CallerHasNewArray = value;
            break;

        case InlineObservation::CALLER_HAS_NEWOBJ:
            m_CallerHasNewObj = value;
            break;

        case InlineObservation::CALLEE_HAS_GC_STRUCT:
            m_CalleeHasGCStruct = value;
            break;

        case InlineObservation::CALLSITE_RARE_GC_STRUCT:
            // This is redundant since this policy tracks call site
            // hotness for all candidates. So ignore.
            break;

        default:
            EnhancedLegacyPolicy::NoteBool(obs, value);
            break;
    }
}

//------------------------------------------------------------------------
// NoteInt: handle an observed integer value
//
// Arguments:
//    obs      - the current obsevation
//    value    - the value being observed

void DiscretionaryPolicy::NoteInt(InlineObservation obs, int value)
{
    switch (obs)
    {
        case InlineObservation::CALLEE_IL_CODE_SIZE:
            // Override how code size is handled
            {
                assert(m_IsForceInlineKnown);
                assert(value != 0);
                m_CodeSize = static_cast<unsigned>(value);

                if (m_IsForceInline)
                {
                    // Candidate based on force inline
                    SetCandidate(InlineObservation::CALLEE_IS_FORCE_INLINE);
                }
                else
                {
                    // Candidate, pending profitability evaluation
                    SetCandidate(InlineObservation::CALLEE_IS_DISCRETIONARY_INLINE);
                }

                break;
            }

        case InlineObservation::CALLEE_OPCODE:
        {
            // This tries to do a rough binning of opcodes based
            // on similarity of impact on codegen.
            OPCODE opcode = static_cast<OPCODE>(value);
            ComputeOpcodeBin(opcode);
            EnhancedLegacyPolicy::NoteInt(obs, value);
            break;
        }

        case InlineObservation::CALLEE_MAXSTACK:
            m_Maxstack = value;
            break;

        case InlineObservation::CALLEE_NUMBER_OF_BASIC_BLOCKS:
            m_BlockCount = value;
            break;

        case InlineObservation::CALLSITE_DEPTH:
            m_Depth = value;
            break;

        case InlineObservation::CALLSITE_WEIGHT:
            m_CallSiteWeight = static_cast<unsigned>(value);
            break;

        default:
            // Delegate remainder to the super class.
            EnhancedLegacyPolicy::NoteInt(obs, value);
            break;
    }
}

//------------------------------------------------------------------------
// ComputeOpcodeBin: simple histogramming of opcodes based on presumably
// similar codegen impact.
//
// Arguments:
//    opcode - an MSIL opcode from the callee

void DiscretionaryPolicy::ComputeOpcodeBin(OPCODE opcode)
{
    switch (opcode)
    {
        case CEE_LDARG_0:
        case CEE_LDARG_1:
        case CEE_LDARG_2:
        case CEE_LDARG_3:
        case CEE_LDARG_S:
        case CEE_LDARG:
        case CEE_STARG_S:
        case CEE_STARG:
            m_ArgAccessCount++;
            break;

        case CEE_LDLOC_0:
        case CEE_LDLOC_1:
        case CEE_LDLOC_2:
        case CEE_LDLOC_3:
        case CEE_LDLOC_S:
        case CEE_STLOC_0:
        case CEE_STLOC_1:
        case CEE_STLOC_2:
        case CEE_STLOC_3:
        case CEE_STLOC_S:
        case CEE_LDLOC:
        case CEE_STLOC:
            m_LocalAccessCount++;
            break;

        case CEE_LDNULL:
        case CEE_LDC_I4_M1:
        case CEE_LDC_I4_0:
        case CEE_LDC_I4_1:
        case CEE_LDC_I4_2:
        case CEE_LDC_I4_3:
        case CEE_LDC_I4_4:
        case CEE_LDC_I4_5:
        case CEE_LDC_I4_6:
        case CEE_LDC_I4_7:
        case CEE_LDC_I4_8:
        case CEE_LDC_I4_S:
            m_IntConstantCount++;
            break;

        case CEE_LDC_R4:
        case CEE_LDC_R8:
            m_FloatConstantCount++;
            break;

        case CEE_LDIND_I1:
        case CEE_LDIND_U1:
        case CEE_LDIND_I2:
        case CEE_LDIND_U2:
        case CEE_LDIND_I4:
        case CEE_LDIND_U4:
        case CEE_LDIND_I8:
        case CEE_LDIND_I:
            m_IntLoadCount++;
            break;

        case CEE_LDIND_R4:
        case CEE_LDIND_R8:
            m_FloatLoadCount++;
            break;

        case CEE_STIND_I1:
        case CEE_STIND_I2:
        case CEE_STIND_I4:
        case CEE_STIND_I8:
        case CEE_STIND_I:
            m_IntStoreCount++;
            break;

        case CEE_STIND_R4:
        case CEE_STIND_R8:
            m_FloatStoreCount++;
            break;

        case CEE_SUB:
        case CEE_AND:
        case CEE_OR:
        case CEE_XOR:
        case CEE_SHL:
        case CEE_SHR:
        case CEE_SHR_UN:
        case CEE_NEG:
        case CEE_NOT:
        case CEE_CONV_I1:
        case CEE_CONV_I2:
        case CEE_CONV_I4:
        case CEE_CONV_I8:
        case CEE_CONV_U4:
        case CEE_CONV_U8:
        case CEE_CONV_U2:
        case CEE_CONV_U1:
        case CEE_CONV_I:
        case CEE_CONV_U:
            m_SimpleMathCount++;
            break;

        case CEE_MUL:
        case CEE_DIV:
        case CEE_DIV_UN:
        case CEE_REM:
        case CEE_REM_UN:
        case CEE_CONV_R4:
        case CEE_CONV_R8:
        case CEE_CONV_R_UN:
            m_ComplexMathCount++;
            break;

        case CEE_CONV_OVF_I1_UN:
        case CEE_CONV_OVF_I2_UN:
        case CEE_CONV_OVF_I4_UN:
        case CEE_CONV_OVF_I8_UN:
        case CEE_CONV_OVF_U1_UN:
        case CEE_CONV_OVF_U2_UN:
        case CEE_CONV_OVF_U4_UN:
        case CEE_CONV_OVF_U8_UN:
        case CEE_CONV_OVF_I_UN:
        case CEE_CONV_OVF_U_UN:
        case CEE_CONV_OVF_I1:
        case CEE_CONV_OVF_U1:
        case CEE_CONV_OVF_I2:
        case CEE_CONV_OVF_U2:
        case CEE_CONV_OVF_I4:
        case CEE_CONV_OVF_U4:
        case CEE_CONV_OVF_I8:
        case CEE_CONV_OVF_U8:
        case CEE_ADD_OVF:
        case CEE_ADD_OVF_UN:
        case CEE_MUL_OVF:
        case CEE_MUL_OVF_UN:
        case CEE_SUB_OVF:
        case CEE_SUB_OVF_UN:
        case CEE_CKFINITE:
            m_OverflowMathCount++;
            break;

        case CEE_LDELEM_I1:
        case CEE_LDELEM_U1:
        case CEE_LDELEM_I2:
        case CEE_LDELEM_U2:
        case CEE_LDELEM_I4:
        case CEE_LDELEM_U4:
        case CEE_LDELEM_I8:
        case CEE_LDELEM_I:
            m_IntArrayLoadCount++;
            break;

        case CEE_LDELEM_R4:
        case CEE_LDELEM_R8:
            m_FloatArrayLoadCount++;
            break;

        case CEE_LDELEM_REF:
            m_RefArrayLoadCount++;
            break;

        case CEE_LDELEM:
            m_StructArrayLoadCount++;
            break;

        case CEE_STELEM_I:
        case CEE_STELEM_I1:
        case CEE_STELEM_I2:
        case CEE_STELEM_I4:
        case CEE_STELEM_I8:
            m_IntArrayStoreCount++;
            break;

        case CEE_STELEM_R4:
        case CEE_STELEM_R8:
            m_FloatArrayStoreCount++;
            break;

        case CEE_STELEM_REF:
            m_RefArrayStoreCount++;
            break;

        case CEE_STELEM:
            m_StructArrayStoreCount++;
            break;

        case CEE_CPOBJ:
        case CEE_LDOBJ:
        case CEE_CPBLK:
        case CEE_INITBLK:
        case CEE_STOBJ:
            m_StructOperationCount++;
            break;

        case CEE_CASTCLASS:
        case CEE_ISINST:
        case CEE_UNBOX:
        case CEE_BOX:
        case CEE_UNBOX_ANY:
        case CEE_LDFTN:
        case CEE_LDVIRTFTN:
        case CEE_SIZEOF:
            m_ObjectModelCount++;
            break;

        case CEE_LDFLD:
        case CEE_LDLEN:
        case CEE_REFANYTYPE:
        case CEE_REFANYVAL:
            m_FieldLoadCount++;
            break;

        case CEE_STFLD:
            m_FieldStoreCount++;
            break;

        case CEE_LDSFLD:
            m_StaticFieldLoadCount++;
            break;

        case CEE_STSFLD:
            m_StaticFieldStoreCount++;
            break;

        case CEE_LDELEMA:
        case CEE_LDSFLDA:
        case CEE_LDFLDA:
        case CEE_LDSTR:
        case CEE_LDARGA:
        case CEE_LDLOCA:
            m_LoadAddressCount++;
            break;

        case CEE_CALL:
        case CEE_CALLI:
        case CEE_CALLVIRT:
        case CEE_NEWOBJ:
        case CEE_NEWARR:
        case CEE_JMP:
            m_CallCount++;
            break;

        case CEE_THROW:
        case CEE_RETHROW:
            m_ThrowCount++;
            break;

        case CEE_RET:
            m_ReturnCount++;

        default:
            break;
    }
}

//------------------------------------------------------------------------
// PropagateNeverToRuntime: determine if a never result should cause the
// method to be marked as un-inlinable.

bool DiscretionaryPolicy::PropagateNeverToRuntime() const
{
    // Propagate most failures, but don't propagate when the inline
    // was viable but unprofitable.
    bool propagate = (m_Observation != InlineObservation::CALLEE_NOT_PROFITABLE_INLINE);

    return propagate;
}

//------------------------------------------------------------------------
// DetermineProfitability: determine if this inline is profitable
//
// Arguments:
//    methodInfo -- method info for the callee

void DiscretionaryPolicy::DetermineProfitability(CORINFO_METHOD_INFO* methodInfo)
{

#if defined(DEBUG)

    // Punt if we're inlining and we've reached the acceptance limit.
    int      limit   = JitConfig.JitInlineLimit();
    unsigned current = m_RootCompiler->m_inlineStrategy->GetInlineCount();

    if (!m_IsPrejitRoot && (limit >= 0) && (current >= static_cast<unsigned>(limit)))
    {
        SetFailure(InlineObservation::CALLSITE_OVER_INLINE_LIMIT);
        return;
    }

#endif // defined(DEBUG)

    // Make additional observations based on the method info
    MethodInfoObservations(methodInfo);

    // Estimate the code size impact. This is just for model
    // evaluation purposes -- we'll still use the legacy policy's
    // model for actual inlining.
    EstimateCodeSize();

    // Estimate peformance impact. This is just for model
    // evaluation purposes -- we'll still use the legacy policy's
    // model for actual inlining.
    EstimatePerformanceImpact();

    // Delegate to super class for the rest
    EnhancedLegacyPolicy::DetermineProfitability(methodInfo);
}

//------------------------------------------------------------------------
// MethodInfoObservations: make observations based on information from
// the method info for the callee.
//
// Arguments:
//    methodInfo -- method info for the callee

void DiscretionaryPolicy::MethodInfoObservations(CORINFO_METHOD_INFO* methodInfo)
{
    CORINFO_SIG_INFO& locals = methodInfo->locals;
    m_LocalCount             = locals.numArgs;

    CORINFO_SIG_INFO& args     = methodInfo->args;
    const unsigned    argCount = args.numArgs;
    m_ArgCount                 = argCount;

    const unsigned pointerSize = sizeof(void*);
    unsigned       i           = 0;

    // Implicit arguments

    const bool hasThis = args.hasThis();

    if (hasThis)
    {
        m_ArgType[i] = CORINFO_TYPE_CLASS;
        m_ArgSize[i] = pointerSize;
        i++;
        m_ArgCount++;
    }

    const bool hasTypeArg = args.hasTypeArg();

    if (hasTypeArg)
    {
        m_ArgType[i] = CORINFO_TYPE_NATIVEINT;
        m_ArgSize[i] = pointerSize;
        i++;
        m_ArgCount++;
    }

    // Explicit arguments

    unsigned                j             = 0;
    CORINFO_ARG_LIST_HANDLE argListHandle = args.args;
    COMP_HANDLE             comp          = m_RootCompiler->info.compCompHnd;

    while ((i < MAX_ARGS) && (j < argCount))
    {
        CORINFO_CLASS_HANDLE classHandle;
        CorInfoType          type = strip(comp->getArgType(&args, argListHandle, &classHandle));

        m_ArgType[i] = type;

        if (type == CORINFO_TYPE_VALUECLASS)
        {
            assert(classHandle != nullptr);
            m_ArgSize[i] = roundUp(comp->getClassSize(classHandle), pointerSize);
        }
        else
        {
            m_ArgSize[i] = pointerSize;
        }

        argListHandle = comp->getArgNext(argListHandle);
        i++;
        j++;
    }

    while (i < MAX_ARGS)
    {
        m_ArgType[i] = CORINFO_TYPE_UNDEF;
        m_ArgSize[i] = 0;
        i++;
    }

    // Return Type

    m_ReturnType = args.retType;

    if (m_ReturnType == CORINFO_TYPE_VALUECLASS)
    {
        assert(args.retTypeClass != nullptr);
        m_ReturnSize = roundUp(comp->getClassSize(args.retTypeClass), pointerSize);
    }
    else if (m_ReturnType == CORINFO_TYPE_VOID)
    {
        m_ReturnSize = 0;
    }
    else
    {
        m_ReturnSize = pointerSize;
    }
}

//------------------------------------------------------------------------
// EstimateCodeSize: produce (various) code size estimates based on
// observations.
//
// The "Baseline" code size model used by the legacy policy is
// effectively
//
//   0.100 * m_CalleeNativeSizeEstimate +
//  -0.100 * m_CallsiteNativeSizeEstimate
//
// On the inlines in CoreCLR's mscorlib, release windows x64, this
// yields scores of R=0.42, MSE=228, and MAE=7.25.
//
// This estimate can be improved slighly by refitting, resulting in
//
//  -1.451 +
//   0.095 * m_CalleeNativeSizeEstimate +
//  -0.104 * m_CallsiteNativeSizeEstimate
//
// With R=0.44, MSE=220, and MAE=6.93.

void DiscretionaryPolicy::EstimateCodeSize()
{
    // Ensure we have this available.
    m_CalleeNativeSizeEstimate = DetermineNativeSizeEstimate();

    // Size estimate based on GLMNET model.
    // R=0.55, MSE=177, MAE=6.59
    //
    // Suspect it doesn't handle factors properly...
    // clang-format off
    double sizeEstimate =
        -13.532 +
          0.359 * (int) m_CallsiteFrequency +
         -0.015 * m_ArgCount +
         -1.553 * m_ArgSize[5] +
          2.326 * m_LocalCount +
          0.287 * m_ReturnSize +
          0.561 * m_IntConstantCount +
          1.932 * m_FloatConstantCount +
         -0.822 * m_SimpleMathCount +
         -7.591 * m_IntArrayLoadCount +
          4.784 * m_RefArrayLoadCount +
         12.778 * m_StructArrayLoadCount +
          1.452 * m_FieldLoadCount +
          8.811 * m_StaticFieldLoadCount +
          2.752 * m_StaticFieldStoreCount +
         -6.566 * m_ThrowCount +
          6.021 * m_CallCount +
         -0.238 * m_IsInstanceCtor +
         -5.357 * m_IsFromPromotableValueClass +
         -7.901 * (m_ConstantArgFeedsConstantTest > 0 ? 1 : 0)  +
          0.065 * m_CalleeNativeSizeEstimate;
    // clang-format on

    // Scaled up and reported as an integer value.
    m_ModelCodeSizeEstimate = (int)(SIZE_SCALE * sizeEstimate);
}

//------------------------------------------------------------------------
// EstimatePeformanceImpact: produce performance estimates based on
// observations.
//
// Notes:
//    Attempts to predict the per-call savings in instructions executed.
//
//    A negative value indicates the doing the inline will save instructions
//    and likely time.

void DiscretionaryPolicy::EstimatePerformanceImpact()
{
    // Performance estimate based on GLMNET model.
    // R=0.24, RMSE=16.1, MAE=8.9.
    // clang-format off
    double perCallSavingsEstimate =
        -7.35
        + (m_CallsiteFrequency == InlineCallsiteFrequency::BORING ?  0.76 : 0)
        + (m_CallsiteFrequency == InlineCallsiteFrequency::LOOP   ? -2.02 : 0)
        + (m_ArgType[0] == CORINFO_TYPE_CLASS ?  3.51 : 0)
        + (m_ArgType[3] == CORINFO_TYPE_BOOL  ? 20.7  : 0)
        + (m_ArgType[4] == CORINFO_TYPE_CLASS ?  0.38 : 0)
        + (m_ReturnType == CORINFO_TYPE_CLASS ?  2.32 : 0);
    // clang-format on

    // Scaled up and reported as an integer value.
    m_PerCallInstructionEstimate = (int)(SIZE_SCALE * perCallSavingsEstimate);
}

//------------------------------------------------------------------------
// CodeSizeEstimate: estimated code size impact of the inline
//
// Return Value:
//    Estimated code size impact, in bytes * 10

int DiscretionaryPolicy::CodeSizeEstimate()
{
    return m_ModelCodeSizeEstimate;
}

#if defined(DEBUG) || defined(INLINE_DATA)

//------------------------------------------------------------------------
// DumpSchema: dump names for all the supporting data for the
// inline decision in CSV format.
//
// Arguments:
//    file -- file to write to

void DiscretionaryPolicy::DumpSchema(FILE* file) const
{
    fprintf(file, "ILSize");
    fprintf(file, ",CallsiteFrequency");
    fprintf(file, ",InstructionCount");
    fprintf(file, ",LoadStoreCount");
    fprintf(file, ",Depth");
    fprintf(file, ",BlockCount");
    fprintf(file, ",Maxstack");
    fprintf(file, ",ArgCount");

    for (unsigned i = 0; i < MAX_ARGS; i++)
    {
        fprintf(file, ",Arg%uType", i);
    }

    for (unsigned i = 0; i < MAX_ARGS; i++)
    {
        fprintf(file, ",Arg%uSize", i);
    }

    fprintf(file, ",LocalCount");
    fprintf(file, ",ReturnType");
    fprintf(file, ",ReturnSize");
    fprintf(file, ",ArgAccessCount");
    fprintf(file, ",LocalAccessCount");
    fprintf(file, ",IntConstantCount");
    fprintf(file, ",FloatConstantCount");
    fprintf(file, ",IntLoadCount");
    fprintf(file, ",FloatLoadCount");
    fprintf(file, ",IntStoreCount");
    fprintf(file, ",FloatStoreCount");
    fprintf(file, ",SimpleMathCount");
    fprintf(file, ",ComplexMathCount");
    fprintf(file, ",OverflowMathCount");
    fprintf(file, ",IntArrayLoadCount");
    fprintf(file, ",FloatArrayLoadCount");
    fprintf(file, ",RefArrayLoadCount");
    fprintf(file, ",StructArrayLoadCount");
    fprintf(file, ",IntArrayStoreCount");
    fprintf(file, ",FloatArrayStoreCount");
    fprintf(file, ",RefArrayStoreCount");
    fprintf(file, ",StructArrayStoreCount");
    fprintf(file, ",StructOperationCount");
    fprintf(file, ",ObjectModelCount");
    fprintf(file, ",FieldLoadCount");
    fprintf(file, ",FieldStoreCount");
    fprintf(file, ",StaticFieldLoadCount");
    fprintf(file, ",StaticFieldStoreCount");
    fprintf(file, ",LoadAddressCount");
    fprintf(file, ",ThrowCount");
    fprintf(file, ",ReturnCount");
    fprintf(file, ",CallCount");
    fprintf(file, ",CallSiteWeight");
    fprintf(file, ",IsForceInline");
    fprintf(file, ",IsInstanceCtor");
    fprintf(file, ",IsFromPromotableValueClass");
    fprintf(file, ",HasSimd");
    fprintf(file, ",LooksLikeWrapperMethod");
    fprintf(file, ",ArgFeedsConstantTest");
    fprintf(file, ",IsMostlyLoadStore");
    fprintf(file, ",ArgFeedsRangeCheck");
    fprintf(file, ",ConstantArgFeedsConstantTest");
    fprintf(file, ",CalleeNativeSizeEstimate");
    fprintf(file, ",CallsiteNativeSizeEstimate");
    fprintf(file, ",ModelCodeSizeEstimate");
    fprintf(file, ",ModelPerCallInstructionEstimate");
    fprintf(file, ",IsClassCtor");
    fprintf(file, ",IsSameThis");
    fprintf(file, ",CallerHasNewArray");
    fprintf(file, ",CallerHasNewObj");
    fprintf(file, ",CalleeDoesNotReturn");
    fprintf(file, ",CalleeHasGCStruct");
}

//------------------------------------------------------------------------
// DumpData: dump all the supporting data for the inline decision
// in CSV format.
//
// Arguments:
//    file -- file to write to

void DiscretionaryPolicy::DumpData(FILE* file) const
{
    fprintf(file, "%u", m_CodeSize);
    fprintf(file, ",%u", m_CallsiteFrequency);
    fprintf(file, ",%u", m_InstructionCount);
    fprintf(file, ",%u", m_LoadStoreCount);
    fprintf(file, ",%u", m_Depth);
    fprintf(file, ",%u", m_BlockCount);
    fprintf(file, ",%u", m_Maxstack);
    fprintf(file, ",%u", m_ArgCount);

    for (unsigned i = 0; i < MAX_ARGS; i++)
    {
        fprintf(file, ",%u", m_ArgType[i]);
    }

    for (unsigned i = 0; i < MAX_ARGS; i++)
    {
        fprintf(file, ",%u", (unsigned)m_ArgSize[i]);
    }

    fprintf(file, ",%u", m_LocalCount);
    fprintf(file, ",%u", m_ReturnType);
    fprintf(file, ",%u", (unsigned)m_ReturnSize);
    fprintf(file, ",%u", m_ArgAccessCount);
    fprintf(file, ",%u", m_LocalAccessCount);
    fprintf(file, ",%u", m_IntConstantCount);
    fprintf(file, ",%u", m_FloatConstantCount);
    fprintf(file, ",%u", m_IntLoadCount);
    fprintf(file, ",%u", m_FloatLoadCount);
    fprintf(file, ",%u", m_IntStoreCount);
    fprintf(file, ",%u", m_FloatStoreCount);
    fprintf(file, ",%u", m_SimpleMathCount);
    fprintf(file, ",%u", m_ComplexMathCount);
    fprintf(file, ",%u", m_OverflowMathCount);
    fprintf(file, ",%u", m_IntArrayLoadCount);
    fprintf(file, ",%u", m_FloatArrayLoadCount);
    fprintf(file, ",%u", m_RefArrayLoadCount);
    fprintf(file, ",%u", m_StructArrayLoadCount);
    fprintf(file, ",%u", m_IntArrayStoreCount);
    fprintf(file, ",%u", m_FloatArrayStoreCount);
    fprintf(file, ",%u", m_RefArrayStoreCount);
    fprintf(file, ",%u", m_StructArrayStoreCount);
    fprintf(file, ",%u", m_StructOperationCount);
    fprintf(file, ",%u", m_ObjectModelCount);
    fprintf(file, ",%u", m_FieldLoadCount);
    fprintf(file, ",%u", m_FieldStoreCount);
    fprintf(file, ",%u", m_StaticFieldLoadCount);
    fprintf(file, ",%u", m_StaticFieldStoreCount);
    fprintf(file, ",%u", m_LoadAddressCount);
    fprintf(file, ",%u", m_ReturnCount);
    fprintf(file, ",%u", m_ThrowCount);
    fprintf(file, ",%u", m_CallCount);
    fprintf(file, ",%u", m_CallSiteWeight);
    fprintf(file, ",%u", m_IsForceInline ? 1 : 0);
    fprintf(file, ",%u", m_IsInstanceCtor ? 1 : 0);
    fprintf(file, ",%u", m_IsFromPromotableValueClass ? 1 : 0);
    fprintf(file, ",%u", m_HasSimd ? 1 : 0);
    fprintf(file, ",%u", m_LooksLikeWrapperMethod ? 1 : 0);
    fprintf(file, ",%u", m_ArgFeedsConstantTest);
    fprintf(file, ",%u", m_MethodIsMostlyLoadStore ? 1 : 0);
    fprintf(file, ",%u", m_ArgFeedsRangeCheck);
    fprintf(file, ",%u", m_ConstantArgFeedsConstantTest);
    fprintf(file, ",%d", m_CalleeNativeSizeEstimate);
    fprintf(file, ",%d", m_CallsiteNativeSizeEstimate);
    fprintf(file, ",%d", m_ModelCodeSizeEstimate);
    fprintf(file, ",%d", m_PerCallInstructionEstimate);
    fprintf(file, ",%u", m_IsClassCtor ? 1 : 0);
    fprintf(file, ",%u", m_IsSameThis ? 1 : 0);
    fprintf(file, ",%u", m_CallerHasNewArray ? 1 : 0);
    fprintf(file, ",%u", m_CallerHasNewObj ? 1 : 0);
    fprintf(file, ",%u", m_IsNoReturn ? 1 : 0);
    fprintf(file, ",%u", m_CalleeHasGCStruct ? 1 : 0);
}

#endif // defined(DEBUG) || defined(INLINE_DATA)

//------------------------------------------------------------------------/
// ModelPolicy: construct a new ModelPolicy
//
// Arguments:
//    compiler -- compiler instance doing the inlining (root compiler)
//    isPrejitRoot -- true if this compiler is prejitting the root method

ModelPolicy::ModelPolicy(Compiler* compiler, bool isPrejitRoot) : DiscretionaryPolicy(compiler, isPrejitRoot)
{
    // Empty
}

//------------------------------------------------------------------------
// NoteInt: handle an observed integer value
//
// Arguments:
//    obs      - the current obsevation
//    value    - the value being observed
//
// Notes:
//    The ILSize threshold used here should be large enough that
//    it does not generally influence inlining decisions -- it only
//    helps to make them faster.
//
//    The value is determined as follows. We figure out the maximum
//    possible code size estimate that will lead to an inline. This is
//    found by determining the maximum possible inline benefit and
//    working backwards.
//
//    In the current ModelPolicy, the maximum benefit is -28.1, which
//    comes from a CallSiteWeight of 3 and a per call benefit of
//    -9.37.  This implies that any candidate with code size larger
//    than (28.1/0.2) will not pass the threshold. So maximum code
//    size estimate (in bytes) for any inlinee is 140.55, and hence
//    maximum estimate is 1405.
//
//    Since we are trying to short circuit early in the evaluation
//    process we don't have the code size estimate in hand. We need to
//    estimate the possible code size estimate based on something we
//    know cheaply and early -- the ILSize. So we use quantile
//    regression to project how ILSize predicts the model code size
//    estimate. Note that ILSize does not currently directly enter
//    into the model.
//
//    The median value for the model code size estimate based on
//    ILSize is given by -107 + 12.6 * ILSize for the V9 data.  This
//    means an ILSize of 120 is likely to lead to a size estimate of
//    at least 1405 at least 50% of the time. So we choose this as the
//    early rejection threshold.

void ModelPolicy::NoteInt(InlineObservation obs, int value)
{
    // Let underlying policy do its thing.
    DiscretionaryPolicy::NoteInt(obs, value);

    // Fail fast for inlinees that are too large to ever inline.
    // The value of 120 is model-dependent; see notes above.
    if (!m_IsForceInline && (obs == InlineObservation::CALLEE_IL_CODE_SIZE) && (value >= 120))
    {
        // Callee too big, not a candidate
        SetNever(InlineObservation::CALLEE_TOO_MUCH_IL);
        return;
    }

    // Safeguard against overly deep inlines
    if (obs == InlineObservation::CALLSITE_DEPTH)
    {
        unsigned depthLimit = m_RootCompiler->m_inlineStrategy->GetMaxInlineDepth();

        if (m_Depth > depthLimit)
        {
            SetFailure(InlineObservation::CALLSITE_IS_TOO_DEEP);
            return;
        }
    }
}

//------------------------------------------------------------------------
// DetermineProfitability: determine if this inline is profitable
//
// Arguments:
//    methodInfo -- method info for the callee
//
// Notes:
//    There are currently two parameters that are ad-hoc: the
//    per-call-site weight and the size/speed threshold. Ideally this
//    policy would have just one tunable parameter, the threshold,
//    which describes how willing we are to trade size for speed.

void ModelPolicy::DetermineProfitability(CORINFO_METHOD_INFO* methodInfo)
{
    // Do some homework
    MethodInfoObservations(methodInfo);
    EstimateCodeSize();
    EstimatePerformanceImpact();

    // Preliminary inline model.
    //
    // If code size is estimated to increase, look at
    // the profitability model for guidance.
    //
    // If code size will decrease, just inline.

    if (m_ModelCodeSizeEstimate <= 0)
    {
        // Inline will likely decrease code size
        JITLOG_THIS(m_RootCompiler, (LL_INFO100000, "Inline profitable, will decrease code size by %g bytes\n",
                                     (double)-m_ModelCodeSizeEstimate / SIZE_SCALE));

        if (m_IsPrejitRoot)
        {
            SetCandidate(InlineObservation::CALLEE_IS_SIZE_DECREASING_INLINE);
        }
        else
        {
            SetCandidate(InlineObservation::CALLSITE_IS_SIZE_DECREASING_INLINE);
        }
    }
    else
    {
        // We estimate that this inline will increase code size.  Only
        // inline if the performance win is sufficiently large to
        // justify bigger code.

        // First compute the number of instruction executions saved
        // via inlining per call to the callee per byte of code size
        // impact.
        //
        // The per call instruction estimate is negative if the inline
        // will reduce instruction count. Flip the sign here to make
        // positive be better and negative worse.
        double perCallBenefit = -((double)m_PerCallInstructionEstimate / (double)m_ModelCodeSizeEstimate);

        // Now estimate the local call frequency.
        //
        // Todo: use IBC data, or a better local profile estimate, or
        // try and incorporate this into the model. For instance if we
        // tried to predict the benefit per call to the root method
        // then the model would have to incorporate the local call
        // frequency, somehow.
        double callSiteWeight = 1.0;

        switch (m_CallsiteFrequency)
        {
            case InlineCallsiteFrequency::RARE:
                callSiteWeight = 0.1;
                break;
            case InlineCallsiteFrequency::BORING:
                callSiteWeight = 1.0;
                break;
            case InlineCallsiteFrequency::WARM:
                callSiteWeight = 1.5;
                break;
            case InlineCallsiteFrequency::LOOP:
            case InlineCallsiteFrequency::HOT:
                callSiteWeight = 3.0;
                break;
            default:
                assert(false);
                break;
        }

        // Determine the estimated number of instructions saved per
        // call to the root method per byte of code size impact. This
        // is our benefit figure of merit.
        double benefit = callSiteWeight * perCallBenefit;

        // Compare this to the threshold, and inline if greater.
        //
        // The threshold is interpretable as a size/speed tradeoff:
        // the value of 0.2 below indicates we'll allow inlines that
        // grow code by as many as 5 bytes to save 1 instruction
        // execution (per call to the root method).
        double threshold    = 0.20;
        bool   shouldInline = (benefit > threshold);

        JITLOG_THIS(m_RootCompiler,
                    (LL_INFO100000, "Inline %s profitable: benefit=%g (weight=%g, percall=%g, size=%g)\n",
                     shouldInline ? "is" : "is not", benefit, callSiteWeight,
                     (double)m_PerCallInstructionEstimate / SIZE_SCALE, (double)m_ModelCodeSizeEstimate / SIZE_SCALE));

        if (!shouldInline)
        {
            // Fail the inline
            if (m_IsPrejitRoot)
            {
                SetNever(InlineObservation::CALLEE_NOT_PROFITABLE_INLINE);
            }
            else
            {
                SetFailure(InlineObservation::CALLSITE_NOT_PROFITABLE_INLINE);
            }
        }
        else
        {
            // Update candidacy
            if (m_IsPrejitRoot)
            {
                SetCandidate(InlineObservation::CALLEE_IS_PROFITABLE_INLINE);
            }
            else
            {
                SetCandidate(InlineObservation::CALLSITE_IS_PROFITABLE_INLINE);
            }
        }
    }
}

#if defined(DEBUG) || defined(INLINE_DATA)

//------------------------------------------------------------------------/
// FullPolicy: construct a new FullPolicy
//
// Arguments:
//    compiler -- compiler instance doing the inlining (root compiler)
//    isPrejitRoot -- true if this compiler is prejitting the root method

FullPolicy::FullPolicy(Compiler* compiler, bool isPrejitRoot) : DiscretionaryPolicy(compiler, isPrejitRoot)
{
    // Empty
}

//------------------------------------------------------------------------
// DetermineProfitability: determine if this inline is profitable
//
// Arguments:
//    methodInfo -- method info for the callee

void FullPolicy::DetermineProfitability(CORINFO_METHOD_INFO* methodInfo)
{
    // Check depth

    unsigned depthLimit = m_RootCompiler->m_inlineStrategy->GetMaxInlineDepth();

    if (m_Depth > depthLimit)
    {
        SetFailure(InlineObservation::CALLSITE_IS_TOO_DEEP);
        return;
    }

    // Check size

    unsigned sizeLimit = m_RootCompiler->m_inlineStrategy->GetMaxInlineILSize();

    if (m_CodeSize > sizeLimit)
    {
        SetFailure(InlineObservation::CALLEE_TOO_MUCH_IL);
        return;
    }

    // Otherwise, we're good to go

    if (m_IsPrejitRoot)
    {
        SetCandidate(InlineObservation::CALLEE_IS_PROFITABLE_INLINE);
    }
    else
    {
        SetCandidate(InlineObservation::CALLSITE_IS_PROFITABLE_INLINE);
    }

    return;
}

//------------------------------------------------------------------------/
// SizePolicy: construct a new SizePolicy
//
// Arguments:
//    compiler -- compiler instance doing the inlining (root compiler)
//    isPrejitRoot -- true if this compiler is prejitting the root method

SizePolicy::SizePolicy(Compiler* compiler, bool isPrejitRoot) : DiscretionaryPolicy(compiler, isPrejitRoot)
{
    // Empty
}

//------------------------------------------------------------------------
// DetermineProfitability: determine if this inline is profitable
//
// Arguments:
//    methodInfo -- method info for the callee

void SizePolicy::DetermineProfitability(CORINFO_METHOD_INFO* methodInfo)
{
    // Do some homework
    MethodInfoObservations(methodInfo);
    EstimateCodeSize();

    // Does this inline increase the estimated size beyond
    // the original size estimate?
    const InlineStrategy* strategy    = m_RootCompiler->m_inlineStrategy;
    const int             initialSize = strategy->GetInitialSizeEstimate();
    const int             currentSize = strategy->GetCurrentSizeEstimate();
    const int             newSize     = currentSize + m_ModelCodeSizeEstimate;

    if (newSize <= initialSize)
    {
        // Estimated size impact is acceptable, so inline here.
        JITLOG_THIS(m_RootCompiler,
                    (LL_INFO100000, "Inline profitable, root size estimate %d is less than initial size %d\n",
                     newSize / SIZE_SCALE, initialSize / SIZE_SCALE));

        if (m_IsPrejitRoot)
        {
            SetCandidate(InlineObservation::CALLEE_IS_SIZE_DECREASING_INLINE);
        }
        else
        {
            SetCandidate(InlineObservation::CALLSITE_IS_SIZE_DECREASING_INLINE);
        }
    }
    else
    {
        // Estimated size increase is too large, so no inline here.
        //
        // Note that we ought to reconsider this inline if we make
        // room in the budget by inlining a bunch of size decreasing
        // inlines after this one. But for now, we won't do this.
        if (m_IsPrejitRoot)
        {
            SetNever(InlineObservation::CALLEE_NOT_PROFITABLE_INLINE);
        }
        else
        {
            SetFailure(InlineObservation::CALLSITE_NOT_PROFITABLE_INLINE);
        }
    }

    return;
}

// Statics to track emission of the replay banner
// and provide file access to the inline xml

bool          ReplayPolicy::s_WroteReplayBanner = false;
FILE*         ReplayPolicy::s_ReplayFile        = nullptr;
CritSecObject ReplayPolicy::s_XmlReaderLock;

//------------------------------------------------------------------------/
// ReplayPolicy: construct a new ReplayPolicy
//
// Arguments:
//    compiler -- compiler instance doing the inlining (root compiler)
//    isPrejitRoot -- true if this compiler is prejitting the root method

ReplayPolicy::ReplayPolicy(Compiler* compiler, bool isPrejitRoot)
    : DiscretionaryPolicy(compiler, isPrejitRoot)
    , m_InlineContext(nullptr)
    , m_Offset(BAD_IL_OFFSET)
    , m_WasForceInline(false)
{
    // Is there a log file open already? If so, we can use it.
    if (s_ReplayFile == nullptr)
    {
        // Did we already try and open and fail?
        if (!s_WroteReplayBanner)
        {
            // Nope, open it up.
            const wchar_t* replayFileName = JitConfig.JitInlineReplayFile();
            s_ReplayFile                  = _wfopen(replayFileName, W("r"));

            // Display banner to stderr, unless we're dumping inline Xml,
            // in which case the policy name is captured in the Xml.
            if (JitConfig.JitInlineDumpXml() == 0)
            {
                fprintf(stderr, "*** %s inlines from %ws\n", s_ReplayFile == nullptr ? "Unable to replay" : "Replaying",
                        replayFileName);
            }

            s_WroteReplayBanner = true;
        }
    }
}

//------------------------------------------------------------------------
// ReplayPolicy: Finalize reading of inline Xml
//
// Notes:
//    Called during jitShutdown()

void ReplayPolicy::FinalizeXml()
{
    if (s_ReplayFile != nullptr)
    {
        fclose(s_ReplayFile);
        s_ReplayFile = nullptr;
    }
}

//------------------------------------------------------------------------
// FindMethod: find the root method in the inline Xml
//
// ReturnValue:
//    true if found. File position left pointing just after the
//    <Token> entry for the method.

bool ReplayPolicy::FindMethod()
{
    if (s_ReplayFile == nullptr)
    {
        return false;
    }

    // See if we've already found this method.
    InlineStrategy* inlineStrategy = m_RootCompiler->m_inlineStrategy;
    long            filePosition   = inlineStrategy->GetMethodXmlFilePosition();

    if (filePosition == -1)
    {
        // Past lookup failed
        return false;
    }
    else if (filePosition > 0)
    {
        // Past lookup succeeded, jump there
        fseek(s_ReplayFile, filePosition, SEEK_SET);
        return true;
    }

    // Else, scan the file. Might be nice to build an index
    // or something, someday.
    const mdMethodDef methodToken =
        m_RootCompiler->info.compCompHnd->getMethodDefFromMethod(m_RootCompiler->info.compMethodHnd);
    const unsigned methodHash = m_RootCompiler->info.compMethodHash();

    bool foundMethod = false;
    char buffer[256];
    fseek(s_ReplayFile, 0, SEEK_SET);

    while (!foundMethod)
    {
        // Get next line
        if (fgets(buffer, sizeof(buffer), s_ReplayFile) == nullptr)
        {
            break;
        }

        // Look for next method entry
        if (strstr(buffer, "<Method>") == nullptr)
        {
            continue;
        }

        // Get next line
        if (fgets(buffer, sizeof(buffer), s_ReplayFile) == nullptr)
        {
            break;
        }

        // See if token matches
        unsigned token = 0;
        int      count = sscanf_s(buffer, " <Token>%u</Token> ", &token);
        if ((count != 1) || (token != methodToken))
        {
            continue;
        }

        // Get next line
        if (fgets(buffer, sizeof(buffer), s_ReplayFile) == nullptr)
        {
            break;
        }

        // See if hash matches
        unsigned hash = 0;
        count         = sscanf_s(buffer, " <Hash>%u</Hash> ", &hash);
        if ((count != 1) || (hash != methodHash))
        {
            continue;
        }

        // Found a match...
        foundMethod = true;
        break;
    }

    // Update file position cache for this method
    long foundPosition = -1;

    if (foundMethod)
    {
        foundPosition = ftell(s_ReplayFile);
    }

    inlineStrategy->SetMethodXmlFilePosition(foundPosition);

    return foundMethod;
}

//------------------------------------------------------------------------
// FindContext: find an inline context in the inline Xml
//
// Notes:
//    Assumes file position within the relevant method has just been
//    set by a successful call to FindMethod().
//
// Arguments:
//    context -- context of interest
//
// ReturnValue:
//    true if found. File position left pointing just after the
//    <Token> entry for the context.

bool ReplayPolicy::FindContext(InlineContext* context)
{
    // Make sure we've found the parent context.
    if (context->IsRoot())
    {
        // We've already found the method context so we're good.
        return true;
    }

    bool foundParent = FindContext(context->GetParent());

    if (!foundParent)
    {
        return false;
    }

    // File pointer should be pointing at the parent context level.
    // See if we see an inline entry for this context.
    //
    // Token and Hash we're looking for.
    mdMethodDef contextToken  = m_RootCompiler->info.compCompHnd->getMethodDefFromMethod(context->GetCallee());
    unsigned    contextHash   = m_RootCompiler->info.compCompHnd->getMethodHash(context->GetCallee());
    unsigned    contextOffset = (unsigned)context->GetOffset();

    return FindInline(contextToken, contextHash, contextOffset);
}

//------------------------------------------------------------------------
// FindInline: find entry for the current inline in inline Xml.
//
// Arguments:
//    token -- token describing the inline
//    hash  -- hash describing the inline
//    offset -- IL offset of the call site in the parent method
//
// ReturnValue:
//    true if the inline entry was found
//
// Notes:
//    Assumes file position has just been set by a successful call to
//    FindMethod or FindContext.
//
//    Token and Hash will not be sufficiently unique to identify a
//    particular inline, if there are multiple calls to the same
//    method.

bool ReplayPolicy::FindInline(unsigned token, unsigned hash, unsigned offset)
{
    char buffer[256];
    bool foundInline = false;
    int  depth       = 0;

    while (!foundInline)
    {
        // Get next line
        if (fgets(buffer, sizeof(buffer), s_ReplayFile) == nullptr)
        {
            break;
        }

        // If we hit </Method> we've gone too far,
        // and the XML is messed up.
        if (strstr(buffer, "</Method>") != nullptr)
        {
            break;
        }

        // Look for <Inlines />....
        if (strstr(buffer, "<Inlines />") != nullptr)
        {
            if (depth == 0)
            {
                // Exited depth 1, failed to find the context
                break;
            }
            else
            {
                // Exited nested, keep looking
                continue;
            }
        }

        // Look for <Inlines>....
        if (strstr(buffer, "<Inlines>") != nullptr)
        {
            depth++;
            continue;
        }

        // If we hit </Inlines> we've exited a nested entry
        // or the current entry.
        if (strstr(buffer, "</Inlines>") != nullptr)
        {
            depth--;

            if (depth == 0)
            {
                // Exited depth 1, failed to find the context
                break;
            }
            else
            {
                // Exited nested, keep looking
                continue;
            }
        }

        // Look for start of inline section at the right depth
        if ((depth != 1) || (strstr(buffer, "<Inline>") == nullptr))
        {
            continue;
        }

        // Get next line
        if (fgets(buffer, sizeof(buffer), s_ReplayFile) == nullptr)
        {
            break;
        }

        // Match token
        unsigned inlineToken = 0;
        int      count       = sscanf_s(buffer, " <Token>%u</Token> ", &inlineToken);

        if ((count != 1) || (inlineToken != token))
        {
            continue;
        }

        // Get next line
        if (fgets(buffer, sizeof(buffer), s_ReplayFile) == nullptr)
        {
            break;
        }

        // Match hash
        unsigned inlineHash = 0;
        count               = sscanf_s(buffer, " <Hash>%u</Hash> ", &inlineHash);

        if ((count != 1) || (inlineHash != hash))
        {
            continue;
        }

        // Get next line
        if (fgets(buffer, sizeof(buffer), s_ReplayFile) == nullptr)
        {
            break;
        }

        // Match offset
        unsigned inlineOffset = 0;
        count                 = sscanf_s(buffer, " <Offset>%u</Offset> ", &inlineOffset);
        if ((count != 1) || (inlineOffset != offset))
        {
            continue;
        }

        // Token,Hash,Offset may still not be unique enough, but it's
        // all we have right now.

        // We're good!
        foundInline = true;

        // Check for a data collection marker. This does not affect
        // matching...

        // Get next line
        if (fgets(buffer, sizeof(buffer), s_ReplayFile) != nullptr)
        {
            unsigned collectData = 0;
            count                = sscanf_s(buffer, " <CollectData>%u</CollectData> ", &collectData);

            if (count == 1)
            {
                m_IsDataCollectionTarget = (collectData == 1);
            }
        }

        break;
    }

    return foundInline;
}

//------------------------------------------------------------------------
// FindInline: find entry for a particular callee in inline Xml.
//
// Arguments:
//    callee -- handle for the callee method
//
// ReturnValue:
//    true if the inline should be performed.
//
// Notes:
//    Assumes file position has just been set by a successful call to
//    FindContext(...);
//
//    callee handle will not be sufficiently unique to identify a
//    particular inline, if there are multiple calls to the same
//    method.

bool ReplayPolicy::FindInline(CORINFO_METHOD_HANDLE callee)
{
    // Token and Hash we're looking for
    mdMethodDef calleeToken = m_RootCompiler->info.compCompHnd->getMethodDefFromMethod(callee);
    unsigned    calleeHash  = m_RootCompiler->info.compCompHnd->getMethodHash(callee);

    // Abstract this or just pass through raw bits
    // See matching code in xml writer
    int offset = -1;
    if (m_Offset != BAD_IL_OFFSET)
    {
        offset = (int)jitGetILoffs(m_Offset);
    }

    unsigned calleeOffset = (unsigned)offset;

    bool foundInline = FindInline(calleeToken, calleeHash, calleeOffset);

    return foundInline;
}

//------------------------------------------------------------------------
// NoteBool: handle an observed boolean value
//
// Arguments:
//    obs      - the current obsevation
//    value    - the value being observed
//
// Notes:
//    Overrides parent so Replay can control force inlines.

void ReplayPolicy::NoteBool(InlineObservation obs, bool value)
{
    // When inlining, let log override force inline.
    // Make a note of the actual value for later reporting during observations.
    if (!m_IsPrejitRoot && (obs == InlineObservation::CALLEE_IS_FORCE_INLINE))
    {
        m_WasForceInline = value;
        value            = false;
    }

    DiscretionaryPolicy::NoteBool(obs, value);
}

//------------------------------------------------------------------------
// DetermineProfitability: determine if this inline is profitable
//
// Arguments:
//    methodInfo -- method info for the callee

void ReplayPolicy::DetermineProfitability(CORINFO_METHOD_INFO* methodInfo)
{
    // TODO: handle prejit root case....need to record this in the
    // root method XML.
    if (m_IsPrejitRoot)
    {
        // Fall back to discretionary policy for now.
        return DiscretionaryPolicy::DetermineProfitability(methodInfo);
    }

    // If we're also dumping inline data, make additional observations
    // based on the method info, and estimate code size and perf
    // impact, so that the reports have the necessary data.
    if (JitConfig.JitInlineDumpData() != 0)
    {
        MethodInfoObservations(methodInfo);
        EstimateCodeSize();
        EstimatePerformanceImpact();
        m_IsForceInline = m_WasForceInline;
    }

    // Try and find this candiate in the Xml.
    // If we fail to find it, then don't inline.
    bool accept = false;

    // Grab the reader lock, since we'll be manipulating
    // the file pointer as we look for the relevant inline xml.
    {
        CritSecHolder readerLock(s_XmlReaderLock);

        // First, locate the entries for the root method.
        bool foundMethod = FindMethod();

        if (foundMethod && (m_InlineContext != nullptr))
        {
            // Next, navigate the context tree to find the entries
            // for the context that contains this candidate.
            bool foundContext = FindContext(m_InlineContext);

            if (foundContext)
            {
                // Finally, find this candidate within its context
                CORINFO_METHOD_HANDLE calleeHandle = methodInfo->ftn;
                accept                             = FindInline(calleeHandle);
            }
        }
    }

    if (accept)
    {
        JITLOG_THIS(m_RootCompiler, (LL_INFO100000, "Inline accepted via log replay"));

        if (m_IsPrejitRoot)
        {
            SetCandidate(InlineObservation::CALLEE_LOG_REPLAY_ACCEPT);
        }
        else
        {
            SetCandidate(InlineObservation::CALLSITE_LOG_REPLAY_ACCEPT);
        }
    }
    else
    {
        JITLOG_THIS(m_RootCompiler, (LL_INFO100000, "Inline rejected via log replay"));

        if (m_IsPrejitRoot)
        {
            SetNever(InlineObservation::CALLEE_LOG_REPLAY_REJECT);
        }
        else
        {
            SetFailure(InlineObservation::CALLSITE_LOG_REPLAY_REJECT);
        }
    }

    return;
}

#endif // defined(DEBUG) || defined(INLINE_DATA)