File: bytecode2llvm.cpp

package info (click to toggle)
clamav 0.101.2+dfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: buster, sid
  • size: 29,464 kB
  • sloc: ansic: 158,856; sh: 8,156; cpp: 5,173; makefile: 2,077; yacc: 1,351; lex: 714; python: 120; perl: 17
file content (3377 lines) | stat: -rw-r--r-- 101,001 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
/*
 *  JIT compile ClamAV bytecode.
 *
 *  Copyright (C) 2013-2019 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
 *  Copyright (C) 2009-2013 Sourcefire, Inc.
 *
 *  Authors: Török Edvin
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License version 2 as
 *  published by the Free Software Foundation.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 *  MA 02110-1301, USA.
 */
#define DEBUG_TYPE "clamavjit"
#include <pthread.h>
#ifndef _WIN32
#include <sys/time.h>
#endif
#include <cstdlib>
#include <csetjmp>
#include <new>
#include <cerrno>
#include <string>

#include "ClamBCModule.h"
#include "ClamBCDiagnostics.h"
#include "llvm30_compat.h"

#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/PostOrderIterator.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/ADT/Triple.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/ScalarEvolution.h"
#if LLVM_VERSION < 35
#include "llvm/Analysis/Verifier.h"
#include "llvm/AutoUpgrade.h"
#include "llvm/Support/TargetFolder.h"
#else
#include "llvm/IR/Verifier.h"
#include "llvm/IR/AutoUpgrade.h"
#include "llvm/Analysis/TargetFolder.h"
#endif
#include "llvm/ExecutionEngine/ExecutionEngine.h"
#if LLVM_VERSION < 36
#include "llvm/ExecutionEngine/JIT.h"
#else
#include "llvm/ExecutionEngine/MCJIT.h"
#include "llvm/Support/DynamicLibrary.h"
#include "llvm/Object/ObjectFile.h"
#endif
#include "llvm/ExecutionEngine/JITEventListener.h"
#if LLVM_VERSION < 37
#include "llvm/PassManager.h"
#else
#include "llvm/IR/LegacyPassManager.h"
#endif
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/PrettyStackTrace.h"

#if LLVM_VERSION < 29
#include "llvm/System/DataTypes.h"
#include "llvm/System/Host.h"
#include "llvm/System/Memory.h"
#include "llvm/System/Mutex.h"
#include "llvm/System/Signals.h"
#include "llvm/System/Threading.h"
#include "llvm/System/ThreadLocal.h"
#else
#include "llvm/PassRegistry.h"
#include "llvm/Support/DataTypes.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/Memory.h"
#include "llvm/Support/Mutex.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/Threading.h"
#include "llvm/Support/ThreadLocal.h"
#endif

#if LLVM_VERSION < 33
#include "llvm/IntrinsicInst.h"
#else
#include "llvm/IR/IntrinsicInst.h"
#endif

#include "llvm/Support/Timer.h"

extern "C" {
void LLVMInitializeX86AsmPrinter();
void LLVMInitializePowerPCAsmPrinter();
}

#if LLVM_VERSION < 30
#include "llvm/Target/TargetSelect.h"
#else
#include "llvm/Support/TargetSelect.h"
#endif

#include "llvm/Target/TargetOptions.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"

#if LLVM_VERSION < 32
#include "llvm/Analysis/DebugInfo.h"
#elif LLVM_VERSION < 35
#include "llvm/DebugInfo.h"
#else
#include "llvm/IR/DebugInfo.h"
#endif

#if LLVM_VERSION < 32
#include "llvm/Support/IRBuilder.h"
#include "llvm/Target/TargetData.h"
#elif LLVM_VERSION < 33
#include "llvm/IRBuilder.h"
#include "llvm/DataLayout.h"
#else
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/DataLayout.h"
#endif

#if LLVM_VERSION < 33
#include "llvm/CallingConv.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Function.h"
#include "llvm/LLVMContext.h"
#include "llvm/Intrinsics.h"
#include "llvm/Module.h"
#else
#include "llvm/IR/CallingConv.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/Module.h"
#endif

#if LLVM_VERSION < 34
#include "llvm/Support/CFG.h"
#else
#include "llvm/Analysis/CFG.h"
#endif

#if LLVM_VERSION >= 35
#include "llvm/IR/Dominators.h"
#endif

//#define TIMING
#undef TIMING

#if LLVM_VERSION < 38
#include "llvm/Config/config.h"
#endif
#ifdef ENABLE_THREADS
#if !ENABLE_THREADS
#error "Thread support was explicitly disabled. Cannot continue"
#endif
#endif

#ifdef LLVM_ENABLE_THREADS
#if !LLVM_ENABLE_THREADS
#error "Thread support was explicitly disabled. Cannot continue"
#endif
#endif

#ifdef _GLIBCXX_PARALLEL
#error "libstdc++ parallel mode is not supported for ClamAV. Please remove -D_GLIBCXX_PARALLEL from CXXFLAGS!"
#endif

#ifdef HAVE_CONFIG_H
#undef PACKAGE_BUGREPORT
#undef PACKAGE_NAME
#undef PACKAGE_STRING
#undef PACKAGE_TARNAME
#undef PACKAGE_VERSION
#undef PACKAGE_URL
#include "clamav-config.h"
#endif

#include <openssl/ssl.h>
#include <openssl/err.h>

#include "dconf.h"
#include "clamav.h"
#include "clambc.h"
#include "bytecode.h"
#include "bytecode_priv.h"
#include "type_desc.h"

#define MODULE "libclamav JIT: "

extern "C" unsigned int cli_rndnum(unsigned int max);
using namespace llvm;
typedef DenseMap<const struct cli_bc_func*, void*> FunctionMapTy;
struct cli_bcengine {
    ExecutionEngine *EE;
    JITEventListener *Listener;
    LLVMContext Context;
    FunctionMapTy compiledFunctions;
    union {
	unsigned char b[16];
	void* align;/* just to align field to ptr */
    } guard;
};

extern "C" uint8_t cli_debug_flag;
#if LLVM_VERSION >= 29
namespace llvm {
    void initializeRuntimeLimitsPass(PassRegistry&);
};
#endif
namespace {

#if LLVM_VERSION >= 28
#define llvm_report_error(x) report_fatal_error(x)
#define llvm_install_error_handler(x) install_fatal_error_handler(x)
#define DwarfExceptionHandling JITExceptionHandling
#if LLVM_VERSION < 37
#define SetCurrentDebugLocation(x) SetCurrentDebugLocation(DebugLoc::getFromDILocation(x))
#endif
#define DEFINEPASS(passname) passname() : FunctionPass(ID)
#else
#define DEFINEPASS(passname) passname() : FunctionPass(&ID)
#endif

#if LLVM_VERSION >= 29
#define NORETURN LLVM_ATTRIBUTE_NORETURN
#endif

static sys::ThreadLocal<const jmp_buf> ExceptionReturn;

static void UpgradeCall(CallInst *&C, Function *Intr)
{
    Function *New;
    if (!UpgradeIntrinsicFunction(Intr, New) || New == Intr)
	return;
    UpgradeIntrinsicCall(C, New);
}

extern "C" {
#ifdef __GNUC__
void cli_errmsg(const char *str, ...) __attribute__((format(printf, 1, 2)));
#else
void cli_errmsg(const char *str, ...);
#endif

#ifdef __GNUC__
void cli_warnmsg(const char *str, ...) __attribute__((format(printf, 1, 2)));
#else
void cli_warnmsg(const char *str, ...);
#endif

#ifdef __GNUC__
void cli_dbgmsg_internal(const char *str, ...) __attribute__((format(printf, 1, 2)));
#else
void cli_dbgmsg_internal(const char *str, ...);
#endif
}

class ScopedExceptionHandler {
    public:
	jmp_buf &getEnv() { return env;}
	void Set() {
	    /* set the exception handler's return location to here for the
	     * current thread */
	    ExceptionReturn.set((const jmp_buf*)&env);
	}
	~ScopedExceptionHandler() {
	    /* leaving scope, remove exception handler for current thread */
	    ExceptionReturn.erase();
	}
    private:
	jmp_buf env;
};
#define HANDLER_TRY(handler) \
    if (setjmp(handler.getEnv()) == 0) {\
	handler.Set();

#define HANDLER_END(handler) \
    } else cli_warnmsg("[Bytecode JIT]: recovered from error\n");


void do_shutdown() {
    ScopedExceptionHandler handler;
    HANDLER_TRY(handler) {
	// TODO: be on the safe side, and clear errors here,
	// otherwise destructor calls report_fatal_error
	((class raw_fd_ostream&)errs()).clear_error();

	llvm_shutdown();

	((class raw_fd_ostream&)errs()).clear_error();
    }
    HANDLER_END(handler);
    remove_fatal_error_handler();
}

static void NORETURN jit_exception_handler(void)
{
    jmp_buf* buf = const_cast<jmp_buf*>(ExceptionReturn.get());
    if (buf) {
	// For errors raised during bytecode generation and execution.
	longjmp(*buf, 1);
    } else {
	// Oops, got no error recovery pointer set up,
	// this is probably an error raised during shutdown.
	cli_errmsg("[Bytecode JIT]: exception handler called, but no recovery point set up");
	// should never happen, we remove the error handler when we don't use
	// LLVM anymore, and when we use it, we do set an error recovery point.
	llvm_unreachable("Bytecode JIT]: no exception handler recovery installed, but exception hit!");
    }
}

static void NORETURN jit_ssp_handler(void)
{
    cli_errmsg("[Bytecode JIT]: *** stack smashing detected, bytecode aborted\n");
    jit_exception_handler();
}

#if LLVM_VERSION < 33
void llvm_error_handler(void *user_data, const std::string &reason)
#else
void llvm_error_handler(void *user_data, const std::string &reason, bool gen_crash_diag = true)
#endif
{
    // Output it to stderr, it might exceed the 1k/4k limit of cli_errmsg
    cli_errmsg("[Bytecode JIT]: [LLVM error] %s\n", reason.c_str());
    jit_exception_handler();
}

// Since libgcc is not available on all compilers (for example on win32),
// just define what these functions should do, the compiler will forward to
// the appropriate libcall if needed.
static int64_t rtlib_sdiv_i64(int64_t a, int64_t b)
{
    return a/b;
}

static uint64_t rtlib_udiv_i64(uint64_t a, uint64_t b)
{
    return a/b;
}

static int64_t rtlib_srem_i64(int64_t a, int64_t b)
{
    return a%b;
}

static uint64_t rtlib_urem_i64(uint64_t a, uint64_t b)
{
    return a%b;
}

static int64_t rtlib_mul_i64(uint64_t a, uint64_t b)
{
    return a*b;
}

static int64_t rtlib_shl_i64(int64_t a, int32_t b)
{
    return a << b;
}

static int64_t rtlib_srl_i64(int64_t a, int32_t b)
{
    return (uint64_t)a >> b;
}
/* Implementation independent sign-extended signed right shift */
#ifdef HAVE_SAR
#define CLI_SRS(n,s) ((n)>>(s))
#else
#define CLI_SRS(n,s) ((((n)>>(s)) ^ (1<<(sizeof(n)*8-1-s))) - (1<<(sizeof(n)*8-1-s)))
#endif
static int64_t rtlib_sra_i64(int64_t a, int32_t b)
{
    return CLI_SRS(a, b);//CLI_./..
}

static void rtlib_bzero(void *s, size_t n)
{
    memset(s, 0, n);
}

#ifdef _WIN32
#ifdef _WIN64
extern "C" void __chkstk(void);
#else
extern "C" void _chkstk(void);
#endif
#endif
// Resolve integer libcalls, but nothing else.
static void* noUnknownFunctions(const std::string& name) {
    void *addr =
	StringSwitch<void*>(name)
	.Case("__divdi3", (void*)(intptr_t)rtlib_sdiv_i64)
	.Case("__udivdi3", (void*)(intptr_t)rtlib_udiv_i64)
	.Case("__moddi3", (void*)(intptr_t)rtlib_srem_i64)
	.Case("__umoddi3", (void*)(intptr_t)rtlib_urem_i64)
	.Case("__muldi3", (void*)(intptr_t)rtlib_mul_i64)
	.Case("__ashrdi3", (void*)(intptr_t)rtlib_sra_i64)
	.Case("__ashldi3", (void*)(intptr_t)rtlib_shl_i64)
	.Case("__lshrdi3", (void*)(intptr_t)rtlib_srl_i64)
	.Case("__bzero", (void*)(intptr_t)rtlib_bzero)
	.Case("memmove", (void*)(intptr_t)memmove)
	.Case("memcpy", (void*)(intptr_t)memcpy)
	.Case("memset", (void*)(intptr_t)memset)
	.Case("abort", (void*)(intptr_t)jit_exception_handler)
#ifdef _WIN32
#ifdef _WIN64
	.Case("_chkstk", (void*)(intptr_t)__chkstk)
#else
	.Case("_chkstk", (void*)(intptr_t)_chkstk)
#endif
#endif
	.Default(0);
    if (addr)
	return addr;

#if LLVM_VERSION < 36
    std::string reason((Twine("Attempt to call external function ")+name).str());
    llvm_error_handler(0, reason);
#else
    // noUnknownFunctions relies on addGlobalMapping, which doesn't work with MCJIT.
    // Now the function pointers are found with SymbolSearching.
#endif
    return 0;
}

class NotifyListener : public JITEventListener {
public:
#if LLVM_VERSION < 36
    virtual void NotifyFunctionEmitted(const Function &F,
				       void *Code, size_t Size,
				       const EmittedFunctionDetails &Details)
    {
	if (!cli_debug_flag)
	    return;
	cli_dbgmsg_internal("[Bytecode JIT]: emitted function %s of %ld bytes at %p\n",
#if LLVM_VERSION < 31
			    F.getNameStr().c_str(), (long)Size, Code);
#else
			    F.getName().str().c_str(), (long)Size, Code);
#endif
    }
#else
    // MCJIT doesn't emit single functions, but instead whole objects.
    virtual void NotifyObjectEmitted(const object::ObjectFile &Obj,
                                     const RuntimeDyld::LoadedObjectInfo &L)
    {
        if (!cli_debug_flag)
            return;
        cli_dbgmsg_internal("[Bytecode JIT]; emitted %s %s of %zd bytes\n",
                            Obj.getFileFormatName().str().c_str(),
                            Obj.getFileName().str().c_str(), Obj.getData().size());
    }
#endif
};

class TimerWrapper {
private:
    Timer *t;
public:
    TimerWrapper(const std::string &name) {
	t = 0;
#ifdef TIMING
	t = new Timer(name);
#endif
    }
    ~TimerWrapper()
    {
	if (t)
	    delete t;
    }
    void startTimer()
    {
	if (t)
	    t->startTimer();
    }
    void stopTimer()
    {
	if (t)
	    t->stopTimer();
    }
};

class LLVMTypeMapper {
private:
#if LLVM_VERSION < 30
    std::vector<PATypeHolder> TypeMap;
#else
    std::vector<Type*> TypeMap;
#endif
    LLVMContext &Context;
    unsigned numTypes;
    constType *getStatic(uint16_t ty)
    {
	if (!ty)
	    return Type::getVoidTy(Context);
	if (ty <= 64)
	    return IntegerType::get(Context, ty);
	switch (ty) {
	    case 65:
		return PointerType::getUnqual(Type::getInt8Ty(Context));
	    case 66:
		return PointerType::getUnqual(Type::getInt16Ty(Context));
	    case 67:
		return PointerType::getUnqual(Type::getInt32Ty(Context));
	    case 68:
		return PointerType::getUnqual(Type::getInt64Ty(Context));
	}
	llvm_unreachable("getStatic");
    }
public:
    TimerWrapper pmTimer;
    TimerWrapper irgenTimer;

    LLVMTypeMapper(LLVMContext &Context, const struct cli_bc_type *types,
		   unsigned count, constType *Hidden=0) : Context(Context), numTypes(count),
    pmTimer("Function passes"),irgenTimer("IR generation")
    {
	TypeMap.reserve(count);
	// During recursive type construction pointers to Type* may be
	// invalidated, so we must use a TypeHolder to an Opaque type as a
	// start.
	for (unsigned i=0;i<count;i++) {
#if LLVM_VERSION < 30
	    TypeMap.push_back(OpaqueType::get(Context));
#else
	    TypeMap.push_back(0);
#endif
	}
	for (unsigned i=0;i<count;i++) {
	    const struct cli_bc_type *type = &types[i];

	    constType *Ty = buildType(type, types, Hidden, 0);
#if LLVM_VERSION < 30
	    // Make the opaque type a concrete type, doing recursive type
	    // unification if needed.
	    cast<OpaqueType>(TypeMap[i].get())->refineAbstractTypeTo(Ty);
#else
	    TypeMap[i] = Ty;
#endif
	}
    }

    constType *buildType(const struct cli_bc_type *type, const struct cli_bc_type *types, constType *Hidden,
			 int recursive)
    {
	std::vector<constType*> Elts;
	unsigned n = type->kind == DArrayType ? 1 : type->numElements;
	for (unsigned j=0;j<n;j++) {
	    Elts.push_back(get(type->containedTypes[j], types, Hidden));
	}
	constType *Ty;
	switch (type->kind) {
	    case DFunctionType:
		{
		    assert(Elts.size() > 0 && "Function with no return type?");
		    constType *RetTy = Elts[0];
		    if (Hidden)
			Elts[0] = Hidden;
		    else
			Elts.erase(Elts.begin());
		    Ty = FunctionType::get(RetTy, Elts, false);
		    break;
		}
	    case DPointerType:
		if (!PointerType::isValidElementType(Elts[0]))
		    Ty = PointerType::getUnqual(Type::getInt8Ty(Context));
		else
		    Ty = PointerType::getUnqual(Elts[0]);
		break;
	    case DStructType:
	    case DPackedStructType:
		Ty = StructType::get(Context, Elts, type->kind == DPackedStructType);
		break;
	    case DArrayType:
		Ty = ArrayType::get(Elts[0], type->numElements);
		break;
	    default:
		llvm_unreachable("type->kind");
	}
	return Ty;
    }

    constType *get(uint16_t ty, const struct cli_bc_type *types, constType *Hidden)
    {
	ty &= 0x7fff;
	if (ty < 69)
	    return getStatic(ty);
	ty -= 69;
	assert(ty < numTypes && "TypeID out of range");
#if LLVM_VERSION < 30
	return TypeMap[ty].get();
#else
	Type *Ty = TypeMap[ty];
	if (Ty)
	    return Ty;
	assert(types && Hidden || "accessing not-yet-built type");
	Ty = buildType(&types[ty], types, Hidden, 1);
	TypeMap[ty] = Ty;
	return Ty;
#endif
    }
};

struct CommonFunctions {
    Function *FHandler;
    Function *FMemset;
    Function *FMemmove;
    Function *FMemcpy;
    Function *FRealmemset;
    Function *FRealMemmove;
    Function *FRealmemcmp;
    Function *FRealmemcpy;
    Function *FBSwap16;
    Function *FBSwap32;
    Function *FBSwap64;
};

// loops with tripcounts higher than this need timeout check
static const unsigned LoopThreshold = 1000;

// after every N API calls we need timeout check
static const unsigned ApiThreshold = 100;

class RuntimeLimits : public FunctionPass {
    typedef SmallVector<std::pair<const BasicBlock*, const BasicBlock*>, 16>
	BBPairVectorTy;
    typedef SmallSet<BasicBlock*, 16> BBSetTy;
    typedef DenseMap<const BasicBlock*, unsigned> BBMapTy;
    bool loopNeedsTimeoutCheck(ScalarEvolution &SE, const Loop *L, BBMapTy &Map) {
	// This BB is a loop header, if trip count is small enough
	// no timeout checks are needed here.
	const SCEV *S = SE.getMaxBackedgeTakenCount(L);
	if (isa<SCEVCouldNotCompute>(S))
	    return true;
	DEBUG(errs() << "Found loop trip count" << *S << "\n");
	ConstantRange CR = SE.getUnsignedRange(S);
	uint64_t max = CR.getUnsignedMax().getLimitedValue();
	DEBUG(errs() << "Found max trip count " << max << "\n");
	if (max > LoopThreshold)
	    return true;
	unsigned apicalls = 0;
	for (Loop::block_iterator J=L->block_begin(),JE=L->block_end();
	     J != JE; ++J) {
	    apicalls += Map[*J];
	}
	apicalls *= max;
	if (apicalls > ApiThreshold) {
	    DEBUG(errs() << "apicall threshold exceeded: " << apicalls << "\n");
	    return true;
	}
	Map[L->getHeader()] = apicalls;
	return false;
    }

public:
    static char ID;
    DEFINEPASS(RuntimeLimits) {
#if LLVM_VERSION >= 29
	PassRegistry &Registry = *PassRegistry::getPassRegistry();
	initializeRuntimeLimitsPass(Registry);
#endif
    }

    virtual bool runOnFunction(Function &F) {
	BBSetTy BackedgeTargets;
	if (!F.isDeclaration()) {
	    // Get the common backedge targets.
	    // Note that we don't rely on LoopInfo here, since
	    // it is possible to construct a CFG that doesn't have natural loops,
	    // yet it does have backedges, and thus can lead to unbounded/high
	    // execution time.
	    BBPairVectorTy V;
	    FindFunctionBackedges(F, V);
	    for (BBPairVectorTy::iterator I=V.begin(),E=V.end();I != E; ++I) {
		BackedgeTargets.insert(const_cast<BasicBlock*>(I->second));
	    }
	}
	BBSetTy  needsTimeoutCheck;
	BBMapTy BBMap;
#if LLVM_VERSION < 35
	DominatorTree &DT = getAnalysis<DominatorTree>();
#else
	DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
#endif
	for (Function::iterator I=F.begin(),E=F.end(); I != E; ++I) {
	    BasicBlock *BB = &*I;
	    unsigned apicalls = 0;
	    for (BasicBlock::const_iterator J=BB->begin(),JE=BB->end();
		 J != JE; ++J) {
		if (const CallInst *CI = dyn_cast<CallInst>(J)) {
		    Function *F = CI->getCalledFunction();
		    if (!F || F->isDeclaration())
			apicalls++;
		}
	    }
	    if (apicalls > ApiThreshold) {
		DEBUG(errs() << "apicall threshold exceeded: " << apicalls << "\n");
		needsTimeoutCheck.insert(BB);
		apicalls = 0;
	    }
	    BBMap[BB] = apicalls;
	}
	if (!BackedgeTargets.empty()) {
#if LLVM_VERSION < 37
	    LoopInfo &LI = getAnalysis<LoopInfo>();
#else
        LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
#endif
#if LLVM_VERSION < 38
	    ScalarEvolution &SE = getAnalysis<ScalarEvolution>();
#else
        ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
#endif

	    // Now check whether any of these backedge targets are part of a loop
	    // with a small constant trip count
	    for (BBSetTy::iterator I=BackedgeTargets.begin(),E=BackedgeTargets.end();
		 I != E; ++I) {
		const Loop *L = LI.getLoopFor(*I);
		if (L && L->getHeader() == *I &&
		    !loopNeedsTimeoutCheck(SE, L, BBMap))
		    continue;
		needsTimeoutCheck.insert(*I);
		BBMap[*I] = 0;
	    }
	}
	// Estimate number of apicalls by walking dominator-tree bottom-up.
	// BBs that have timeout checks are considered to have 0 APIcalls
	// (since we already checked for timeout).
	for (po_iterator<DomTreeNode*> I = po_begin(DT.getRootNode()),
	     E = po_end(DT.getRootNode()); I != E; ++I) {
	    if (needsTimeoutCheck.count(I->getBlock()))
		continue;
	    unsigned apicalls = BBMap[I->getBlock()];
	    for (DomTreeNode::iterator J=I->begin(),JE=I->end();
		 J != JE; ++J) {
		apicalls += BBMap[(*J)->getBlock()];
	    }
	    if (apicalls > ApiThreshold) {
		needsTimeoutCheck.insert(I->getBlock());
		apicalls = 0;
	    }
	    BBMap[I->getBlock()] = apicalls;
	}
	if (needsTimeoutCheck.empty())
	    return false;
	DEBUG(errs() << "needs timeoutcheck:\n");
	std::vector<constType*>args;
	FunctionType* abrtTy = FunctionType::get(
	    Type::getVoidTy(F.getContext()),args,false);
	Constant *func_abort =
	    F.getParent()->getOrInsertFunction("abort", abrtTy);
	BasicBlock *AbrtBB = BasicBlock::Create(F.getContext(), "", &F);
        CallInst* AbrtC = CallInst::Create(func_abort, "", AbrtBB);
        AbrtC->setCallingConv(CallingConv::C);
        AbrtC->setTailCall(true);
#if LLVM_VERSION < 32
        AbrtC->setDoesNotReturn(true);
        AbrtC->setDoesNotThrow(true);
#else
        AbrtC->setDoesNotReturn();
        AbrtC->setDoesNotThrow();
#endif
        new UnreachableInst(F.getContext(), AbrtBB);
#if LLVM_VERSION < 39
	IRBuilder<false> Builder(F.getContext());
#else
    IRBuilder<> Builder(F.getContext());
#endif

#if LLVM_VERSION < 38
	Value *Flag = F.arg_begin();
#else
    Value *Flag = &*F.arg_begin();
#endif
#if LLVM_VERSION < 30
	Function *LSBarrier = Intrinsic::getDeclaration(F.getParent(),
							Intrinsic::memory_barrier);
	Value *MBArgs[] = {
	    ConstantInt::getFalse(F.getContext()),
	    ConstantInt::getFalse(F.getContext()),
	    ConstantInt::getTrue(F.getContext()),
	    ConstantInt::getFalse(F.getContext()),
	    ConstantInt::getFalse(F.getContext())
	};
#endif
	verifyFunction(F);
	BasicBlock *BB = &F.getEntryBlock();
#if LLVM_VERSION < 38
	Builder.SetInsertPoint(BB, BB->getTerminator());
#else
    Builder.SetInsertPoint(BB, BB->getTerminator()->getIterator());
#endif
	Flag = Builder.CreatePointerCast(Flag, PointerType::getUnqual(
		Type::getInt1Ty(F.getContext())));
	for (BBSetTy::iterator I=needsTimeoutCheck.begin(),
	     E=needsTimeoutCheck.end(); I != E; ++I) {
	    BasicBlock *BB = *I;
#if LLVM_VERSION < 38
	    Builder.SetInsertPoint(BB, BB->getTerminator());
#else
        Builder.SetInsertPoint(BB, BB->getTerminator()->getIterator());
#endif
#if LLVM_VERSION < 30
	    // store-load barrier: will be a no-op on x86 but not other arches
	    Builder.CreateCall(LSBarrier, ARRAYREF(Value*, MBArgs, MBArgs+5));
#elif LLVM_VERSION < 39
	    Builder.CreateFence(Release);
#else
        Builder.CreateFence(AtomicOrdering::Release);
#endif
	    // Load Flag that tells us we timed out (first byte in bc_ctx)
	    Value *Cond = Builder.CreateLoad(Flag, true);
#if LLVM_VERSION < 37
	    BasicBlock *newBB = SplitBlock(BB, BB->getTerminator(), this);
#else
        BasicBlock *newBB = SplitBlock(BB, BB->getTerminator());
#endif
	    TerminatorInst *TI = BB->getTerminator();
	    BranchInst::Create(AbrtBB, newBB, Cond, TI);
	    TI->eraseFromParent();
	    // Update dominator info
	    DomTreeNode *N = DT.getNode(AbrtBB);
	    if (!N) {
		DT.addNewBlock(AbrtBB, BB);
	    } else {
		BasicBlock *DomBB = DT.findNearestCommonDominator(BB,
								  N->getIDom()->getBlock());
		DT.changeImmediateDominator(AbrtBB, DomBB);
	    }
	    DEBUG(errs() << *I << "\n");
	}
	//verifyFunction(F);
	return true;
    }

    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
      AU.setPreservesAll();
#if LLVM_VERSION < 37
      AU.addRequired<LoopInfo>();
#else
      AU.addRequired<LoopInfoWrapperPass>();
#endif
#if LLVM_VERSION < 38
      AU.addRequired<ScalarEvolution>();
#else
      AU.addRequired<ScalarEvolutionWrapperPass>();
#endif
#if LLVM_VERSION < 35
      AU.addRequired<DominatorTree>();
#else
      AU.addRequired<DominatorTreeWrapperPass>();
#endif
    }
};
char RuntimeLimits::ID;

// select i1 false ... which instcombine would simplify but we don't run
// instcombine.
class BrSimplifier : public FunctionPass {
public:
    static char ID;
    DEFINEPASS(BrSimplifier) {}

    virtual bool runOnFunction(Function &F) {
	bool Changed = false;
	for (Function::iterator I=F.begin(),E=F.end(); I != E; ++I) {
	    if (BranchInst *BI = dyn_cast<BranchInst>(I->getTerminator())) {
		if (BI->isUnconditional())
		    continue;
		Value *V = BI->getCondition();
		if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
		    BasicBlock *Other;
		    if (CI->isOne()) {
			BranchInst::Create(BI->getSuccessor(0), &*I);
			Other = BI->getSuccessor(1);
		    } else {
			BranchInst::Create(BI->getSuccessor(1), &*I);
			Other = BI->getSuccessor(0);
		    }
		    Other->removePredecessor(&*I);
		    BI->eraseFromParent();
		    Changed = true;
		}
	    }
	    for (BasicBlock::iterator J=I->begin(),JE=I->end();
		 J != JE;) {
		SelectInst *SI = dyn_cast<SelectInst>(J);
		++J;
		if (!SI)
		    continue;
		ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
		if (!CI)
		    continue;
		if (CI->isOne())
		    SI->replaceAllUsesWith(SI->getTrueValue());
		else
		    SI->replaceAllUsesWith(SI->getFalseValue());
		SI->eraseFromParent();
		Changed = true;
	    }
	}

	return Changed;
    }
};
char BrSimplifier::ID;
/*
class SimpleGlobalDCE : public ModulePass {
    ExecutionEngine *EE;
public:
    static char ID;
    SimpleGlobalDCE(ExecutionEngine *EE) : ModulePass(&ID), EE(EE) {}

    virtual bool runOnModule(Module &M) {
	bool Changed = false;
	std::vector<GlobalValue*> toErase;
	for (Module::global_iterator I = M.global_begin(), E = M.global_end(); I != E; ++I) {
	    GlobalValue *GV = &*I;
	    if (GV->use_empty() && !EE->getPointerToGlobalIfAvailable(GV))
		toErase.push_back(GV);
	}
	for (std::vector<GlobalValue*>::iterator I=toErase.begin(), E=toErase.end();
	     I != E; ++I) {
	    (*I)->eraseFromParent();
	    Changed = true;
	}

	return Changed;
    }
};
char SimpleGlobalDCE::ID;
*/
class LLVMCodegen {
private:
    const struct cli_bc *bc;
    Module *M;
    LLVMContext &Context;
    ExecutionEngine *EE;
#if LLVM_VERSION < 37
    FunctionPassManager &PM, &PMUnsigned;
#else
    legacy::FunctionPassManager &PM, &PMUnsigned;
#endif
    LLVMTypeMapper *TypeMap;

    Function **apiFuncs;
    LLVMTypeMapper &apiMap;
    FunctionMapTy &compiledFunctions;
    Twine BytecodeID;

    TargetFolder Folder;
#if LLVM_VERSION < 39
    IRBuilder<false, TargetFolder> Builder;
#else
    IRBuilder<TargetFolder> Builder;
#endif

    std::vector<Value*> globals;
    DenseMap<unsigned, unsigned> GVoffsetMap;
    DenseMap<unsigned, constType*> GVtypeMap;
    Value **Values;
    unsigned numLocals;
    unsigned numArgs;
    std::vector<MDNode*> mdnodes;

    struct CommonFunctions *CF;

    Value *getOperand(const struct cli_bc_func *func, constType *Ty, operand_t operand)
    {
	unsigned map[] = {0, 1, 2, 3, 3, 4, 4, 4, 4};
	if (operand < func->numValues)
	    return Values[operand];
	unsigned w = Ty->getPrimitiveSizeInBits();
	if (w > 1)
	    w = (w+7)/8;
	else
	    w = 0;
	return convertOperand(func, map[w], operand);
    }

    Value *convertOperand(const struct cli_bc_func *func, constType *Ty, operand_t operand)
    {
	unsigned map[] = {0, 1, 2, 3, 3, 4, 4, 4, 4};
	if (operand < func->numArgs)
	    return Values[operand];
	if (operand < func->numValues) {
	    Value *V = Values[operand];
	    if (func->types[operand]&0x8000 && V->getType() == Ty) {
		return V;
	    }
	    V = Builder.CreateLoad(V);
	    if (V->getType() != Ty &&
		isa<PointerType>(V->getType()) &&
		isa<PointerType>(Ty))
		V = Builder.CreateBitCast(V, Ty);
	    if (V->getType() != Ty) {
		if (cli_debug_flag) {
		    std::string str;
		    raw_string_ostream ostr(str);
		    ostr << operand << " " ;
		    V->print(ostr);
		    Ty->print(ostr);
		    M->dump();
		    cli_dbgmsg_internal("[Bytecode JIT]: operand %d: %s\n", operand,ostr.str().c_str());
		}
		llvm_report_error("(libclamav) Type mismatch converting operand");
	    }
	    return V;
	}
	unsigned w = Ty->getPrimitiveSizeInBits();
	if (w > 1)
	    w = (w+7)/8;
	else
	    w = 0;
	return convertOperand(func, map[w], operand);
    }

    Value *convertOperand(const struct cli_bc_func *func,
			  const struct cli_bc_inst *inst,  operand_t operand)
    {
	return convertOperand(func, inst->interp_op%5, operand);
    }

    Value *convertOperand(const struct cli_bc_func *func,
			  unsigned w, operand_t operand) {
	if (operand < func->numArgs)
	    return Values[operand];
	if (operand < func->numValues) {
	    if (func->types[operand]&0x8000)
		return Values[operand];
	    return Builder.CreateLoad(Values[operand]);
	}

	if (operand & 0x80000000) {
	    operand &= 0x7fffffff;
	    assert(operand < globals.size() && "Global index out of range");
	    // Global
	    if (!operand)
		return ConstantPointerNull::get(PointerType::getUnqual(Type::getInt8Ty(Context)));
	    assert(globals[operand]);
	    if (GlobalVariable *GV = dyn_cast<GlobalVariable>(globals[operand])) {
		if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
		    return CE;
		}
		return GV;
	    }
	    return globals[operand];
	}
	// Constant
	operand -= func->numValues;
	// This was already validated by libclamav.
	assert(operand < func->numConstants && "Constant out of range");
	uint64_t *c = &func->constants[operand];
	uint64_t v;
	constType *Ty;
	switch (w) {
	    case 0:
	    case 1:
		Ty = w ? Type::getInt8Ty(Context) :
		    Type::getInt1Ty(Context);
		v = *(uint8_t*)c;
		break;
	    case 2:
		Ty = Type::getInt16Ty(Context);
		v = *(uint16_t*)c;
		break;
	    case 3:
		Ty = Type::getInt32Ty(Context);
		v = *(uint32_t*)c;
		break;
	    case 4:
		Ty = Type::getInt64Ty(Context);
		v = *(uint64_t*)c;
		break;
	    default:
		llvm_unreachable("width");
	}
	return ConstantInt::get(Ty, v);
    }

    void Store(uint16_t dest, Value *V)
    {
	assert(dest >= numArgs && dest < numLocals+numArgs && "Instruction destination out of range");
	Builder.CreateStore(V, Values[dest]);
    }

    // Insert code that calls \arg CF->FHandler if \arg FailCond is true.
    void InsertVerify(Value *FailCond, BasicBlock *&Fail, Function *FHandler, 
		      Function *F) {
	if (!Fail) {
	    Fail = BasicBlock::Create(Context, "fail", F);
	    CallInst::Create(FHandler,"",Fail);
	    new UnreachableInst(Context, Fail);
	}
	BasicBlock *OkBB = BasicBlock::Create(Context, "", F);
	Builder.CreateCondBr(FailCond, Fail, OkBB);
	Builder.SetInsertPoint(OkBB);
    }

    constType* mapType(uint16_t typeID)
    {
	return TypeMap->get(typeID&0x7fffffff, NULL, NULL);
    }

    Constant *buildConstant(constType *Ty, uint64_t *components, unsigned &c)
    {
        if (constPointerType *PTy = dyn_cast<PointerType>(Ty)) {
          Value *idxs[1] = {
	      ConstantInt::get(Type::getInt64Ty(Context), components[c++])
	  };
	  unsigned idx = components[c++];
	  if (!idx)
	      return ConstantPointerNull::get(PTy);
	  assert(idx < globals.size());
	  GlobalVariable *GV = cast<GlobalVariable>(globals[idx]);
	  Type *IP8Ty = PointerType::getUnqual(Type::getInt8Ty(Ty->getContext()));
	  Constant *C = ConstantExpr::getPointerCast(GV, IP8Ty);
	  //TODO: check constant bounds here
	  return ConstantExpr::getPointerCast(
#if LLVM_VERSION < 37
	      ConstantExpr::getInBoundsGetElementPtr(C, ARRAYREF(Value*, idxs, 1)),
#else
	      ConstantExpr::getInBoundsGetElementPtr(Ty, C, ARRAYREF(Value*, idxs, 1)),
#endif
	      PTy);
        }
	if (isa<IntegerType>(Ty)) {
	    return ConstantInt::get(Ty, components[c++]);
	}
	if (constArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
	   std::vector<Constant*> elements;
	   elements.reserve(ATy->getNumElements());
	   for (unsigned i=0;i<ATy->getNumElements();i++) {
	       elements.push_back(buildConstant(ATy->getElementType(), components, c));
	   }
	   return ConstantArray::get(ATy, elements);
	}
	if (constStructType *STy = dyn_cast<StructType>(Ty)) {
	   std::vector<Constant*> elements;
	   elements.reserve(STy->getNumElements());
	   for (unsigned i=0;i<STy->getNumElements();i++) {
	       elements.push_back(buildConstant(STy->getElementType(i), components, c));
	   }
	   return ConstantStruct::get(STy, elements);
	}
	Ty->dump();
	llvm_unreachable("invalid type");
	return 0;
    }

public:
    LLVMCodegen(const struct cli_bc *bc, Module *M, struct CommonFunctions *CF, FunctionMapTy &cFuncs,
#if LLVM_VERSION < 37
		ExecutionEngine *EE, FunctionPassManager &PM, FunctionPassManager &PMUnsigned,
#else
        ExecutionEngine *EE, legacy::FunctionPassManager &PM, legacy::FunctionPassManager &PMUnsigned,
#endif
		Function **apiFuncs, LLVMTypeMapper &apiMap)
	: bc(bc), M(M), Context(M->getContext()), EE(EE),
	PM(PM),PMUnsigned(PMUnsigned), TypeMap(), apiFuncs(apiFuncs),apiMap(apiMap),
	compiledFunctions(cFuncs), BytecodeID("bc"+Twine(bc->id)),
#if LLVM_VERSION < 32
	Folder(EE->getTargetData()), Builder(Context, Folder), Values(), CF(CF) {
#elif LLVM_VERSION < 37
	Folder(EE->getDataLayout()), Builder(Context, Folder), Values(), CF(CF) {
#elif LLVM_VERSION < 38
    Folder(*EE->getDataLayout()), Builder(Context, Folder), Values(), CF(CF) {
#else
    Folder(EE->getDataLayout()), Builder(Context, Folder), Values(), CF(CF) {
#endif

	for (unsigned i=0;i<cli_apicall_maxglobal - _FIRST_GLOBAL;i++) {
	    unsigned id = cli_globals[i].globalid;
	    GVoffsetMap[id] = cli_globals[i].offset;
	}
	numLocals = 0;
	numArgs = 0;
    }

#if LLVM_VERSION < 30
    template <typename InputIterator>
#endif
    Value* createGEP(Value *Base, constType *ETy, ARRAYREFPARAM(Value*,InputIterator Start,InputIterator End,ARef)) {
#if LLVM_VERSION < 37
	constType *Ty = GetElementPtrInst::getIndexedType(Base->getType(),ARRAYREFP(Start,End,ARef));
#else
    Type *Ty = NULL;
    // This used to be done internally in LLVM's getIndexedTypeInternal.
    PointerType *PTy = dyn_cast<PointerType>(Base->getType()->getScalarType());
    if (PTy) {
        Type *Agg = PTy->getElementType();
        Ty = GetElementPtrInst::getIndexedType(Agg,ARRAYREFP(Start,End,ARef));
    }
#endif
	if (!Ty || (ETy && (Ty != ETy && (!isa<IntegerType>(Ty) || !isa<IntegerType>(ETy))))) {
	    if (cli_debug_flag) {
		std::string str;
		raw_string_ostream ostr(str);

		ostr << "Wrong indices for GEP opcode: "
		    << " expected type: " << *ETy;
		if (Ty)
		    ostr << " actual type: " << *Ty;
		ostr << " base: " << *Base << ";";
		Base->getType()->print(ostr);
		ostr << "\n indices: ";
#if LLVM_VERSION < 30
		for (InputIterator I=Start; I != End; I++) {
#else
		for (ArrayRef<Value*>::iterator I=ARef.begin(); I != ARef.end(); I++) {
#endif
		    ostr << **I << ", ";
		}
		ostr << "\n";
		cli_dbgmsg_internal("[Bytecode JIT]: %s\n", ostr.str().c_str());
	    } else {
		cli_warnmsg("[Bytecode JIT]: Wrong indices for GEP opcode\n");
	    }
	    return 0;
	}
	return Builder.CreateGEP(Base,ARRAYREFP(Start,End,ARef));
    }

#if LLVM_VERSION < 30
    template <typename InputIterator>
#endif
    bool createGEP(unsigned dest, Value *Base, ARRAYREFPARAM(Value*,InputIterator Start,InputIterator End,ARef)) {
	assert(dest >= numArgs && dest < numLocals+numArgs && "Instruction destination out of range");
	constType *ETy = cast<PointerType>(cast<PointerType>(Values[dest]->getType())->getElementType())->getElementType();
	Value *V = createGEP(Base, ETy, ARRAYREFP(Start,End,ARef));
	if (!V) {
	    if (cli_debug_flag)
		cli_dbgmsg_internal("[Bytecode JIT] @%d\n", dest);
	    return false;
	}
	V = Builder.CreateBitCast(V, PointerType::getUnqual(ETy));
	Store(dest, V);
	return true;
    }

    MDNode *convertMDNode(unsigned i) {
	if (i < mdnodes.size()) {
	    if (mdnodes[i])
		return mdnodes[i];
	} else 
	    mdnodes.resize(i+1);
	assert(i < mdnodes.size());
	const struct cli_bc_dbgnode *node = &bc->dbgnodes[i];
#if LLVM_VERSION < 36
	Value **Vals = new Value*[node->numelements];
#else
	Metadata **Vals = new Metadata*[node->numelements];
#endif
	for (unsigned j=0;j<node->numelements;j++) {
	    const struct cli_bc_dbgnode_element* el = &node->elements[j];
#if LLVM_VERSION < 36
	    Value *V;
#else
	    Metadata *V;
#endif
	    if (!el->len) {
		if (el->nodeid == ~0u)
		    V = 0;
		else if (el->nodeid)
		    V = convertMDNode(el->nodeid);
		else
		    V = MDString::get(Context, "");
	    } else if (el->string) {
		V = MDString::get(Context, StringRef(el->string, el->len));
	    } else {
#if LLVM_VERSION < 36
		V = ConstantInt::get(IntegerType::get(Context, el->len),
				     el->constant);
#else
		V = ConstantAsMetadata::get(ConstantInt::get(IntegerType::get(Context, el->len),
				     el->constant));
#endif
	    }
	    Vals[j] = V;
	}
#if LLVM_VERSION < 36
	MDNode *N = MDNode::get(Context, ARRAYREF(Value*,Vals, node->numelements));
#else
	MDNode *N = MDNode::get(Context, ARRAYREF(Metadata*,Vals, node->numelements));
#endif
	delete[] Vals;
	mdnodes[i] = N;
	return N;
    }

    void AddStackProtect(Function *F)
    {
	BasicBlock &BB = F->getEntryBlock();
	if (isa<AllocaInst>(BB.begin())) {
	    // Have an alloca -> some instruction uses its address otherwise
	    // mem2reg would have converted it to an SSA register.
	    // Enable stack protector for this function.
#if LLVM_VERSION < 29
	    // LLVM 2.9 has broken SSP, it does a 'mov 0x28, $rax', which tries
	    // to read from the address 0x28 and crashes
	    F->addFnAttr(Attribute::StackProtectReq);
#endif
	}
	// always add stackprotect attribute (bb #2239), so we know this
	// function was verified. If there is no alloca it won't actually add
	// stack protector in emitted code so this won't slow down the app.
#if LLVM_VERSION < 29
	F->addFnAttr(Attribute::StackProtect);
#endif
    }

    Value *GEPOperand(Value *V) {
	if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
	    Value *VI = LI->getOperand(0);
	    StoreInst *SI = 0;
	    for (Value::use_iterator I=VI->use_begin(),
		 E=VI->use_end(); I != E; ++I) {
		Value *I_V = *I;
		if (StoreInst *S = dyn_cast<StoreInst>(I_V)) {
		    if (SI)
			return V;
		    SI = S;
		} else if (!isa<LoadInst>(I_V))
		    return V;
	    }
	    V = SI->getOperand(0);
	}
#if LLVM_VERSION < 32
	if (EE->getTargetData()->getPointerSize() == 8) {
#elif LLVM_VERSION < 38
	if (EE->getDataLayout()->getPointerSize() == 8) {
#else
    if (EE->getDataLayout().getPointerSize() == 8) {
#endif
	    // eliminate useless trunc, GEP can take i64 too
	    if (TruncInst *I = dyn_cast<TruncInst>(V)) {
		Value *Src = I->getOperand(0);
		if (Src->getType() == Type::getInt64Ty(Context) &&
		    I->getType() == Type::getInt32Ty(Context))
		    return Src;
	    }
	}
	return V;
    }

   Function* generate() {
        PrettyStackTraceString CrashInfo("Generate LLVM IR functions");
	apiMap.irgenTimer.startTimer();
	TypeMap = new LLVMTypeMapper(Context, bc->types + 4, bc->num_types - 5);
	for (unsigned i=0;i<bc->dbgnode_cnt;i++) {
	    mdnodes.push_back(convertMDNode(i));
	}

	for (unsigned i=0;i<cli_apicall_maxglobal - _FIRST_GLOBAL;i++) {
	    unsigned id = cli_globals[i].globalid;
	    constType *Ty = apiMap.get(cli_globals[i].type, NULL, NULL);
	    /*if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty))
		Ty = PointerType::getUnqual(ATy->getElementType());*/
	    GVtypeMap[id] = Ty;
	}

	// The hidden ctx param to all functions
	unsigned maxh = cli_globals[0].offset + sizeof(struct cli_bc_hooks);
	constType *HiddenCtx = PointerType::getUnqual(ArrayType::get(Type::getInt8Ty(Context), maxh));

	globals.reserve(bc->num_globals);
	BitVector FakeGVs;
	FakeGVs.resize(bc->num_globals);
	globals.push_back(0);
	for (unsigned i=1;i<bc->num_globals;i++) {
	    constType *Ty = mapType(bc->globaltys[i]);

	    // TODO: validate number of components against type_components
	    unsigned c = 0;
	    GlobalVariable *GV;
	    if (isa<PointerType>(Ty)) {
		unsigned g = bc->globals[i][1];
		if (GVoffsetMap.count(g)) {
		    FakeGVs.set(i);
		    globals.push_back(0);
		    continue;
		}
	    }
	    Constant *C = buildConstant(Ty, bc->globals[i], c);
	    GV = new GlobalVariable(*M, Ty, true,
				    GlobalValue::InternalLinkage,
				    C, "glob"+Twine(i));
	    globals.push_back(GV);
	}
	Function **Functions = new Function*[bc->num_func];
	for (unsigned j=0;j<bc->num_func;j++) {
	    // Create LLVM IR Function
	    const struct cli_bc_func *func = &bc->funcs[j];
	    std::vector<constType*> argTypes;
	    argTypes.push_back(HiddenCtx);
	    for (unsigned a=0;a<func->numArgs;a++) {
		argTypes.push_back(mapType(func->types[a]));
	    }
	    constType *RetTy = mapType(func->returnType);
	    FunctionType *FTy =  FunctionType::get(RetTy, argTypes,
							 false);
	    Functions[j] = Function::Create(FTy, Function::InternalLinkage,
					   BytecodeID+"f"+Twine(j), M);
	    Functions[j]->setDoesNotThrow();
	    Functions[j]->setCallingConv(CallingConv::Fast);
	    Functions[j]->setLinkage(GlobalValue::InternalLinkage);
#ifdef C_LINUX
	    /* bb #2270, this should really be fixed either by LLVM or GCC.*/
#if LLVM_VERSION < 32
	    Functions[j]->addFnAttr(Attribute::constructStackAlignmentFromInt(16));
#else
	// TODO: How does this translate?
//	    Functions[j]->addFnAttr(Attribute::StackAlignment);
#endif
#endif
	}
	constType *I32Ty = Type::getInt32Ty(Context);
	for (unsigned j=0;j<bc->num_func;j++) {
	    PrettyStackTraceString CrashInfo("Generate LLVM IR");
	    const struct cli_bc_func *func = &bc->funcs[j];
	    bool broken = false;

	    // Create all BasicBlocks
	    Function *F = Functions[j];
	    BasicBlock **BB = new BasicBlock*[func->numBB];
	    for (unsigned i=0;i<func->numBB;i++) {
		BB[i] = BasicBlock::Create(Context, "", F);
	    }

	    BasicBlock *Fail = 0;
	    Values = new Value*[func->numValues];
	    Builder.SetInsertPoint(BB[0]);
	    Function::arg_iterator I = F->arg_begin();
	    assert(F->arg_size() == (unsigned)(func->numArgs + 1) && "Mismatched args");
	    ++I;
	    for (unsigned i=0;i<func->numArgs; i++) {
		assert(I != F->arg_end());
		Values[i] = &*I;
		++I;
	    }
	    for (unsigned i=func->numArgs;i<func->numValues;i++) {
		if (!func->types[i]) {
		    //instructions without return value, like store
		    Values[i] = 0;
		    continue;
		}
		Values[i] = Builder.CreateAlloca(mapType(func->types[i]));
	    }
	    numLocals = func->numLocals;
	    numArgs = func->numArgs;

	    if (FakeGVs.any()) {
#if LLVM_VERSION < 38
		Argument *Ctx = F->arg_begin();
#else
        Argument *Ctx = &*F->arg_begin();
#endif
		for (unsigned i=0;i<bc->num_globals;i++) {
		    if (!FakeGVs[i])
			continue;
		    unsigned g = bc->globals[i][1];
		    unsigned offset = GVoffsetMap[g];

		    Constant *Idx = ConstantInt::get(Type::getInt32Ty(Context),
						     offset);
		    Value *Idxs[2] = {
			ConstantInt::get(Type::getInt32Ty(Context), 0),
			Idx
		    };
		    Value *GEP = Builder.CreateInBoundsGEP(Ctx, ARRAYREF(Value*, Idxs, Idxs+2));
		    constType *Ty = GVtypeMap[g];
		    Ty = PointerType::getUnqual(PointerType::getUnqual(Ty));
		    Value *Cast = Builder.CreateBitCast(GEP, Ty);
		    Value *SpecialGV = Builder.CreateLoad(Cast);
		    constType *IP8Ty = Type::getInt8Ty(Context);
		    IP8Ty = PointerType::getUnqual(IP8Ty);
		    SpecialGV = Builder.CreateBitCast(SpecialGV, IP8Ty);
		    SpecialGV->setName("g"+Twine(g-_FIRST_GLOBAL)+"_");
		    Value *C[] = {
			ConstantInt::get(Type::getInt32Ty(Context), bc->globals[i][0])
		    };
		    globals[i] = createGEP(SpecialGV, 0, ARRAYREF(Value*,C, C+1));
		    if (!globals[i]) {
			if (cli_debug_flag) {
			    std::string str;
			    raw_string_ostream ostr(str);
			    ostr << i << ":" << g << ":" << bc->globals[i][0] <<"\n";
			    Ty->print(ostr);
			    cli_dbgmsg_internal("[Bytecode JIT]: %s\n", ostr.str().c_str());
			}
			llvm_report_error("(libclamav) unable to create fake global");
		    }
		    globals[i] = Builder.CreateBitCast(globals[i], Ty);
		    if(GetElementPtrInst *GI = dyn_cast<GetElementPtrInst>(globals[i])) {
			GI->setIsInBounds(true);
			GI->setName("geped"+Twine(i)+"_");
		    }
		}
	    }

	    // Generate LLVM IR for each BB
	    for (unsigned i=0;i<func->numBB && !broken;i++) {
		bool unreachable = false;
		const struct cli_bc_bb *bb = &func->BB[i];
		Builder.SetInsertPoint(BB[i]);
		unsigned c = 0;
		for (unsigned j=0;j<bb->numInsts && !broken;j++) {
		    const struct cli_bc_inst *inst = &bb->insts[j];
		    Value *Op0=0, *Op1=0, *Op2=0;
		    // libclamav has already validated this.
		    assert(inst->opcode < OP_BC_INVALID && "Invalid opcode");
		    if (func->dbgnodes) {
			if (func->dbgnodes[c] != ~0u) {
			unsigned j = func->dbgnodes[c];
			assert(j < mdnodes.size());
#if LLVM_VERSION < 37
			Builder.SetCurrentDebugLocation(mdnodes[j]);
#else
            Builder.SetCurrentDebugLocation(DebugLoc(mdnodes[j]));
#endif
			} else
			    Builder.SetCurrentDebugLocation(0);
		    }
		    c++;
		    switch (inst->opcode) {
			case OP_BC_JMP:
			case OP_BC_BRANCH:
			case OP_BC_CALL_API:
			case OP_BC_CALL_DIRECT:
			case OP_BC_ZEXT:
			case OP_BC_SEXT:
			case OP_BC_TRUNC:
			case OP_BC_GEP1:
			case OP_BC_GEPZ:
			case OP_BC_GEPN:
			case OP_BC_STORE:
			case OP_BC_COPY:
			case OP_BC_RET:
			case OP_BC_PTRDIFF32:
			case OP_BC_PTRTOINT64:
			    // these instructions represents operands differently
			    break;
			default:
			    switch (operand_counts[inst->opcode]) {
				case 1:
				    Op0 = convertOperand(func, inst, inst->u.unaryop);
				    break;
				case 2:
				    Op0 = convertOperand(func, inst, inst->u.binop[0]);
				    Op1 = convertOperand(func, inst, inst->u.binop[1]);
				    if (Op0->getType() != Op1->getType()) {
					Op0->dump();
					Op1->dump();
					llvm_report_error("(libclamav) binop type mismatch");
				    }
				    break;
				case 3:
				    Op0 = convertOperand(func, inst, inst->u.three[0]);
				    Op1 = convertOperand(func, inst, inst->u.three[1]);
				    Op2 = convertOperand(func, inst, inst->u.three[2]);
				    break;
			    }
		    }

		    switch (inst->opcode) {
			case OP_BC_ADD:
			    Store(inst->dest, Builder.CreateAdd(Op0, Op1));
			    break;
			case OP_BC_SUB:
			    Store(inst->dest, Builder.CreateSub(Op0, Op1));
			    break;
			case OP_BC_MUL:
			    Store(inst->dest, Builder.CreateMul(Op0, Op1));
			    break;
			case OP_BC_UDIV:
			{
			    Value *Bad = Builder.CreateICmpEQ(Op1, ConstantInt::get(Op1->getType(), 0));
			    InsertVerify(Bad, Fail, CF->FHandler, F);
			    Store(inst->dest, Builder.CreateUDiv(Op0, Op1));
			    break;
			}
			case OP_BC_SDIV:
			{
			    //TODO: also verify Op0 == -1 && Op1 = INT_MIN
			    Value *Bad = Builder.CreateICmpEQ(Op1, ConstantInt::get(Op1->getType(), 0));
			    InsertVerify(Bad, Fail, CF->FHandler, F);
			    Store(inst->dest, Builder.CreateSDiv(Op0, Op1));
			    break;
			}
			case OP_BC_UREM:
			{
			    Value *Bad = Builder.CreateICmpEQ(Op1, ConstantInt::get(Op1->getType(), 0));
			    InsertVerify(Bad, Fail, CF->FHandler, F);
			    Store(inst->dest, Builder.CreateURem(Op0, Op1));
			    break;
			}
			case OP_BC_SREM:
			{
			    //TODO: also verify Op0 == -1 && Op1 = INT_MIN
			    Value *Bad = Builder.CreateICmpEQ(Op1, ConstantInt::get(Op1->getType(), 0));
			    InsertVerify(Bad, Fail, CF->FHandler, F);
			    Store(inst->dest, Builder.CreateSRem(Op0, Op1));
			    break;
			}
			case OP_BC_SHL:
			    Store(inst->dest, Builder.CreateShl(Op0, Op1));
			    break;
			case OP_BC_LSHR:
			    Store(inst->dest, Builder.CreateLShr(Op0, Op1));
			    break;
			case OP_BC_ASHR:
			    Store(inst->dest, Builder.CreateAShr(Op0, Op1));
			    break;
			case OP_BC_AND:
			    Store(inst->dest, Builder.CreateAnd(Op0, Op1));
			    break;
			case OP_BC_OR:
			    Store(inst->dest, Builder.CreateOr(Op0, Op1));
			    break;
			case OP_BC_XOR:
			    Store(inst->dest, Builder.CreateXor(Op0, Op1));
			    break;
			case OP_BC_TRUNC:
			{
			    Value *Src = convertOperand(func, inst, inst->u.cast.source);
			    constType *Ty = mapType(func->types[inst->dest]);
			    Store(inst->dest, Builder.CreateTrunc(Src,  Ty));
			    break;
			}
			case OP_BC_ZEXT:
			{
			    Value *Src = convertOperand(func, inst, inst->u.cast.source);
			    constType *Ty = mapType(func->types[inst->dest]);
			    Store(inst->dest, Builder.CreateZExt(Src,  Ty));
			    break;
			}
			case OP_BC_SEXT:
			{
			    Value *Src = convertOperand(func, inst, inst->u.cast.source);
			    constType *Ty = mapType(func->types[inst->dest]);
			    Store(inst->dest, Builder.CreateSExt(Src,  Ty));
			    break;
			}
			case OP_BC_BRANCH:
			{
			    Value *Cond = convertOperand(func, inst, inst->u.branch.condition);
			    BasicBlock *True = BB[inst->u.branch.br_true];
			    BasicBlock *False = BB[inst->u.branch.br_false];
			    if (Cond->getType() != Type::getInt1Ty(Context)) {
				cli_warnmsg("[Bytecode JIT]: type mismatch in condition");
				broken = true;
				break;
			    }
			    Builder.CreateCondBr(Cond, True, False);
			    break;
			}
			case OP_BC_JMP:
			{
			    BasicBlock *Jmp = BB[inst->u.jump];
			    Builder.CreateBr(Jmp);
			    break;
			}
			case OP_BC_RET:
			{
			    Op0 = convertOperand(func, F->getReturnType(), inst->u.unaryop);
			    Builder.CreateRet(Op0);
			    break;
			}
			case OP_BC_RET_VOID:
			    Builder.CreateRetVoid();
			    break;
			case OP_BC_ICMP_EQ:
			    Store(inst->dest, Builder.CreateICmpEQ(Op0, Op1));
			    break;
			case OP_BC_ICMP_NE:
			    Store(inst->dest, Builder.CreateICmpNE(Op0, Op1));
			    break;
			case OP_BC_ICMP_UGT:
			    Store(inst->dest, Builder.CreateICmpUGT(Op0, Op1));
			    break;
			case OP_BC_ICMP_UGE:
			    Store(inst->dest, Builder.CreateICmpUGE(Op0, Op1));
			    break;
			case OP_BC_ICMP_ULT:
			    Store(inst->dest, Builder.CreateICmpULT(Op0, Op1));
			    break;
			case OP_BC_ICMP_ULE:
			    Store(inst->dest, Builder.CreateICmpULE(Op0, Op1));
			    break;
			case OP_BC_ICMP_SGT:
			    Store(inst->dest, Builder.CreateICmpSGT(Op0, Op1));
			    break;
			case OP_BC_ICMP_SGE:
			    Store(inst->dest, Builder.CreateICmpSGE(Op0, Op1));
			    break;
			case OP_BC_ICMP_SLT:
			    Store(inst->dest, Builder.CreateICmpSLT(Op0, Op1));
			    break;
			case OP_BC_ICMP_SLE:
			    Store(inst->dest, Builder.CreateICmpSLE(Op0, Op1));
			    break;
			case OP_BC_SELECT:
			    Store(inst->dest, Builder.CreateSelect(Op0, Op1, Op2));
			    break;
			case OP_BC_COPY:
			{
			    Value *Dest = Values[inst->u.binop[1]];
			    constPointerType *PTy = cast<PointerType>(Dest->getType());
			    Op0 = convertOperand(func, PTy->getElementType(), inst->u.binop[0]);
			    PTy = PointerType::getUnqual(Op0->getType());
			    Dest = Builder.CreateBitCast(Dest, PTy);
			    Builder.CreateStore(Op0, Dest);
			    break;
			}
			case OP_BC_CALL_DIRECT:
			{
			    Function *DestF = Functions[inst->u.ops.funcid];
			    SmallVector<Value*, 2> args;
			    args.push_back(&*F->arg_begin()); // pass hidden arg
			    for (unsigned a=0;a<inst->u.ops.numOps;a++) {
				operand_t op = inst->u.ops.ops[a];
				args.push_back(convertOperand(func, DestF->getFunctionType()->getParamType(a+1), op));
			    }
			    CallInst *CI = Builder.CreateCall(DestF, ARRAYREF(Value*, args.begin(), args.end()));
			    CI->setCallingConv(CallingConv::Fast);
#if LLVM_VERSION < 32
			    CI->setDoesNotThrow(true);
#else
			    CI->setDoesNotThrow();
#endif
			    if (CI->getType()->getTypeID() != Type::VoidTyID)
				Store(inst->dest, CI);
			    break;
			}
			case OP_BC_CALL_API:
			{
			    assert(inst->u.ops.funcid < cli_apicall_maxapi && "APICall out of range");
			    std::vector<Value*> args;
			    Function *DestF = apiFuncs[inst->u.ops.funcid];
			    if (!strcmp(cli_apicalls[inst->u.ops.funcid].name, "engine_functionality_level")) {
				Store(inst->dest,
				      ConstantInt::get(Type::getInt32Ty(Context),
						       cl_retflevel()));
			    } else {
			    args.push_back(&*F->arg_begin()); // pass hidden arg
			    for (unsigned a=0;a<inst->u.ops.numOps;a++) {
				operand_t op = inst->u.ops.ops[a];
				args.push_back(convertOperand(func, DestF->getFunctionType()->getParamType(a+1), op));
			    }
			    CallInst *CI = Builder.CreateCall(DestF, ARRAYREFVECTOR(Value*, args));
#if LLVM_VERSION < 32
			    CI->setDoesNotThrow(true);
#else
			    CI->setDoesNotThrow();
#endif
			    Store(inst->dest, CI);
			    }
			    break;
			}
			case OP_BC_GEP1:
			{
			    constType *SrcTy = mapType(inst->u.three[0]);
			    Value *V = convertOperand(func, SrcTy, inst->u.three[1]);
			    Value *Op = convertOperand(func, I32Ty, inst->u.three[2]);
			    Op = GEPOperand(Op);
			    if (!createGEP(inst->dest, V, ARRAYREF(Value*, &Op, &Op+1))) {
				cli_warnmsg("[Bytecode JIT]: OP_BC_GEP1 createGEP failed\n");
				broken = true;
			    }
			    break;
			}
			case OP_BC_GEPZ:
			{
			    Value *Ops[2];
			    Ops[0] = ConstantInt::get(Type::getInt32Ty(Context), 0);
			    constType *SrcTy = mapType(inst->u.three[0]);
			    Value *V = convertOperand(func, SrcTy, inst->u.three[1]);
			    Ops[1] = convertOperand(func, I32Ty, inst->u.three[2]);
			    Ops[1] = GEPOperand(Ops[1]);
			    if (!createGEP(inst->dest, V, ARRAYREF(Value*, Ops, Ops+2))) {
				cli_warnmsg("[Bytecode JIT]: OP_BC_GEPZ createGEP failed\n");
				broken = true;
			    }
			    break;
			}
			case OP_BC_GEPN:
			{
			    std::vector<Value*> Idxs;
			    assert(inst->u.ops.numOps > 2);
			    constType *SrcTy = mapType(inst->u.ops.ops[0]);
			    Value *V = convertOperand(func, SrcTy, inst->u.ops.ops[1]);
			    for (unsigned a=2;a<inst->u.ops.numOps;a++) {
				Value *Op = convertOperand(func, I32Ty, inst->u.ops.ops[a]);
				Op = GEPOperand(Op);
				Idxs.push_back(Op);
			    }
			    if (!createGEP(inst->dest, V, ARRAYREFVECTOR(Value*, Idxs))) {
				cli_warnmsg("[Bytecode JIT]: OP_BC_GEPN createGEP failed\n");
				broken = true;
			    }
			    break;
			}
			case OP_BC_STORE:
			{
			    Value *Dest = convertOperand(func, inst, inst->u.binop[1]);
			    Value *V = convertOperand(func, inst, inst->u.binop[0]);
			    constType *VPTy = PointerType::getUnqual(V->getType());
			    if (VPTy != Dest->getType())
				Dest = Builder.CreateBitCast(Dest, VPTy);
			    Builder.CreateStore(V, Dest);
			    break;
			}
			case OP_BC_LOAD:
			{
			    Op0 = Builder.CreateBitCast(Op0,
							Values[inst->dest]->getType());
			    Op0 = Builder.CreateLoad(Op0);
			    Store(inst->dest, Op0);
			    break;
			}
			case OP_BC_MEMSET:
			{
			    Value *Dst = convertOperand(func, inst, inst->u.three[0]);
			    Dst = Builder.CreatePointerCast(Dst, PointerType::getUnqual(Type::getInt8Ty(Context)));
			    Value *Val = convertOperand(func, Type::getInt8Ty(Context), inst->u.three[1]);
			    Value *Len = convertOperand(func, Type::getInt32Ty(Context), inst->u.three[2]);
#if LLVM_VERSION < 29
			    CallInst *c = Builder.CreateCall4(CF->FMemset, Dst, Val, Len,
								ConstantInt::get(Type::getInt32Ty(Context), 1));
#elif LLVM_VERSION < 37
			    CallInst *c = Builder.CreateCall5(CF->FMemset, Dst, Val, Len,
								ConstantInt::get(Type::getInt32Ty(Context), 1),
								ConstantInt::get(Type::getInt1Ty(Context), 0)
								);
#else
                Value *args[] = { Dst, Val, Len,
                                  ConstantInt::get(Type::getInt32Ty(Context), 1),
                                  ConstantInt::get(Type::getInt1Ty(Context), 0)};
                CallInst *c = Builder.CreateCall(CF->FMemset, ARRAYREF(Value*, args, args + 5));
#endif
			    c->setTailCall(true);
			    c->setDoesNotThrow();
			    UpgradeCall(c, CF->FMemset);
			    break;
			}
			case OP_BC_MEMCPY:
			{
			    Value *Dst = convertOperand(func, inst, inst->u.three[0]);
			    Dst = Builder.CreatePointerCast(Dst, PointerType::getUnqual(Type::getInt8Ty(Context)));
			    Value *Src = convertOperand(func, inst, inst->u.three[1]);
			    Src = Builder.CreatePointerCast(Src, PointerType::getUnqual(Type::getInt8Ty(Context)));
			    Value *Len = convertOperand(func, Type::getInt32Ty(Context), inst->u.three[2]);
#if LLVM_VERSION < 29
			    CallInst *c = Builder.CreateCall4(CF->FMemcpy, Dst, Src, Len,
								ConstantInt::get(Type::getInt32Ty(Context), 1));
#elif LLVM_VERSION < 37
			    CallInst *c = Builder.CreateCall5(CF->FMemcpy, Dst, Src, Len,
								ConstantInt::get(Type::getInt32Ty(Context), 1),
								ConstantInt::get(Type::getInt1Ty(Context), 0)
								);
#else
                Value *args[] = { Dst, Src, Len,
                                  ConstantInt::get(Type::getInt32Ty(Context), 1),
                                  ConstantInt::get(Type::getInt1Ty(Context), 0)};
                CallInst *c = Builder.CreateCall(CF->FMemcpy, ARRAYREF(Value*, args, args + 5));
#endif
			    c->setTailCall(true);
			    c->setDoesNotThrow();
			    UpgradeCall(c, CF->FMemcpy);
			    break;
			}
			case OP_BC_MEMMOVE:
			{
			    Value *Dst = convertOperand(func, inst, inst->u.three[0]);
			    Dst = Builder.CreatePointerCast(Dst, PointerType::getUnqual(Type::getInt8Ty(Context)));
			    Value *Src = convertOperand(func, inst, inst->u.three[1]);
			    Src = Builder.CreatePointerCast(Src, PointerType::getUnqual(Type::getInt8Ty(Context)));
			    Value *Len = convertOperand(func, Type::getInt32Ty(Context), inst->u.three[2]);
#if LLVM_VERSION < 29
			    CallInst *c = Builder.CreateCall4(CF->FMemmove, Dst, Src, Len,
								ConstantInt::get(Type::getInt32Ty(Context), 1));
#elif LLVM_VERSION < 37
			    CallInst *c = Builder.CreateCall5(CF->FMemmove, Dst, Src, Len,
								ConstantInt::get(Type::getInt32Ty(Context), 1),
								ConstantInt::get(Type::getInt1Ty(Context), 0));
#else
                Value *args[] = {Dst, Src, Len,
                                 ConstantInt::get(Type::getInt32Ty(Context), 1),
                                 ConstantInt::get(Type::getInt1Ty(Context), 0)};
                CallInst *c = Builder.CreateCall(CF->FMemmove, args);
#endif
			    c->setTailCall(true);
			    c->setDoesNotThrow();
			    UpgradeCall(c, CF->FMemmove);
			    break;
			}
			case OP_BC_MEMCMP:
			{
			    Value *Dst = convertOperand(func, inst, inst->u.three[0]);
			    Dst = Builder.CreatePointerCast(Dst, PointerType::getUnqual(Type::getInt8Ty(Context)));
			    Value *Src = convertOperand(func, inst, inst->u.three[1]);
			    Src = Builder.CreatePointerCast(Src, PointerType::getUnqual(Type::getInt8Ty(Context)));
#if LLVM_VERSION < 32
			    Value *Len = convertOperand(func, EE->getTargetData()->getIntPtrType(Context), inst->u.three[2]);
#elif LLVM_VERSION < 38
			    Value *Len = convertOperand(func, EE->getDataLayout()->getIntPtrType(Context), inst->u.three[2]);
#else
                Value *Len = convertOperand(func, EE->getDataLayout().getIntPtrType(Context), inst->u.three[2]);
#endif
#if LLVM_VERSION < 37
			    CallInst *c = Builder.CreateCall3(CF->FRealmemcmp, Dst, Src, Len);
#else
                Value *args[] = {Dst, Src, Len};
                CallInst *c = Builder.CreateCall(CF->FRealmemcmp, ARRAYREF(Value*, args, args + 3));
#endif
			    c->setTailCall(true);
			    c->setDoesNotThrow();
			    Store(inst->dest, c);
			    break;
			}
			case OP_BC_ISBIGENDIAN:
			    Store(inst->dest, WORDS_BIGENDIAN ?
				  ConstantInt::getTrue(Context) :
				  ConstantInt::getFalse(Context));
			    break;
			case OP_BC_ABORT:
			    if (!unreachable) {
				CallInst *CI = Builder.CreateCall(CF->FHandler);
				CI->setDoesNotReturn();
				CI->setDoesNotThrow();
				Builder.CreateUnreachable();
				unreachable = true;
			    }
			    break;
			case OP_BC_BSWAP16:
			    {
				CallInst *C = Builder.CreateCall(CF->FBSwap16, convertOperand(func, inst, inst->u.unaryop));
				C->setTailCall(true);
#if LLVM_VERSION < 32
				C->setDoesNotThrow(true);
#else
				C->setDoesNotThrow();
#endif
				Store(inst->dest, C);
				break;
			    }
			case OP_BC_BSWAP32:
			    {
				CallInst *C = Builder.CreateCall(CF->FBSwap32, convertOperand(func, inst, inst->u.unaryop));
				C->setTailCall(true);
#if LLVM_VERSION < 32
				C->setDoesNotThrow(true);
#else
				C->setDoesNotThrow();
#endif
				Store(inst->dest, C);
				break;
			    }
			case OP_BC_BSWAP64:
			    {
				CallInst *C = Builder.CreateCall(CF->FBSwap64, convertOperand(func, inst, inst->u.unaryop));
				C->setTailCall(true);
#if LLVM_VERSION < 32
				C->setDoesNotThrow(true);
#else
				C->setDoesNotThrow();
#endif
				Store(inst->dest, C);
				break;
			    }
			case OP_BC_PTRDIFF32:
			    {
				Value *P1 = convertOperand(func, inst, inst->u.binop[0]);
				Value *P2 = convertOperand(func, inst, inst->u.binop[1]);
				P1 = Builder.CreatePtrToInt(P1, Type::getInt64Ty(Context));
				P2 = Builder.CreatePtrToInt(P2, Type::getInt64Ty(Context));
				Value *R = Builder.CreateSub(P1, P2);
				R = Builder.CreateTrunc(R, Type::getInt32Ty(Context));
				Store(inst->dest, R);
				break;
			    }
			case OP_BC_PTRTOINT64:
			    {
				Value *P1 = convertOperand(func, inst, inst->u.unaryop);
				P1 = Builder.CreatePtrToInt(P1, Type::getInt64Ty(Context));
				Store(inst->dest, P1);
				break;
			    }
			default:
			    cli_warnmsg("[Bytecode JIT]: JIT doesn't implement opcode %d yet!\n",
					inst->opcode);
			    broken = true;
			    break;
		    }
		}
	    }

	    // If successful so far, run verifyFunction
	    if (!broken) {
#if LLVM_VERSION < 35
		if (verifyFunction(*F, PrintMessageAction)) {
#else
		if (verifyFunction(*F, &errs())) {
#endif
		    // verification failed
		    broken = true;
		    cli_warnmsg("[Bytecode JIT]: Verification failed\n");
		    if (cli_debug_flag) {
			std::string str;
			raw_string_ostream ostr(str);
			F->print(ostr);
			cli_dbgmsg_internal("[Bytecode JIT]: %s\n", ostr.str().c_str());
		    }
		}
	    }

	    delete [] Values;

	    // Cleanup after failure and return 0
	    if (broken) {
		for (unsigned z=0; z < func->numBB ; z++) {
		    delete BB[z];
		}
		delete [] BB;
		apiMap.irgenTimer.stopTimer();
		delete TypeMap;
		for (unsigned z=0; z < bc->num_func; z++) {
		    delete Functions[z];
		}
		delete [] Functions;
		return 0;
	    }

	    delete [] BB;
	    apiMap.irgenTimer.stopTimer();
	    apiMap.pmTimer.startTimer();
	    if (bc->trusted) {
		PM.doInitialization();
		PM.run(*F);
		PM.doFinalization();
	    }
	    else {
		PMUnsigned.doInitialization();
		PMUnsigned.run(*F);
		PMUnsigned.doFinalization();
	    }

	    apiMap.pmTimer.stopTimer();
	    apiMap.irgenTimer.startTimer();
	}

	for (unsigned j=0;j<bc->num_func;j++) {
	    Function *F = Functions[j];
	    AddStackProtect(F);
	}
	delete TypeMap;
	std::vector<constType*> args;
	args.clear();
	args.push_back(HiddenCtx);
	FunctionType *Callable = FunctionType::get(Type::getInt32Ty(Context),
						   args, false);

	// If prototype matches, add to callable functions
	if (Functions[0]->getFunctionType() != Callable) {
	    cli_warnmsg("[Bytecode JIT]: Wrong prototype for function 0 in bytecode %d\n",  bc->id);
	    apiMap.irgenTimer.stopTimer();
	    for (unsigned z=0; z < bc->num_func; z++) {
		delete Functions[z];
	    }
	    delete [] Functions;
	    return 0;
	}
	// All functions have the Fast calling convention, however
	// entrypoint can only be C, emit wrapper
	Function *F = Function::Create(Functions[0]->getFunctionType(),
				       Function::ExternalLinkage,
#if LLVM_VERSION < 33
				       Functions[0]->getName()+"_wrap", M);
#else
				       Functions[0]->getName().str()+"_wrap", M);
#endif
	F->setDoesNotThrow();
	BasicBlock *BB = BasicBlock::Create(Context, "", F);
	std::vector<Value*> Args;
	for (Function::arg_iterator J=F->arg_begin(),
	     JE=F->arg_end(); J != JE; ++JE) {
	    Args.push_back(&*J);
	}
	CallInst *CI = CallInst::Create(Functions[0], ARRAYREFVECTOR(Value*, Args), "", BB);
	CI->setCallingConv(CallingConv::Fast);
	ReturnInst::Create(Context, CI, BB);

	delete [] Functions;
#if LLVM_VERSION < 35
	if (verifyFunction(*F, PrintMessageAction))
#else
	if (verifyFunction(*F, &errs()))
#endif
	    return 0;

/*			DEBUG(errs() << "Generating code\n");
			// Codegen current function as executable machine code.
			EE->getPointerToFunction(Functions[j]);
			void *code = EE->getPointerToFunction(F);
			DEBUG(errs() << "Code generation finished\n");*/

//		compiledFunctions[func] = code;
	apiMap.irgenTimer.stopTimer();
	return F;
    }
};

static sys::Mutex llvm_api_lock;

// This class automatically acquires the lock when instantiated,
// and releases the lock when leaving scope.
class LLVMApiScopedLock {
    public:
	// when multithreaded mode is false (no atomics available),
	// we need to wrap all LLVM API calls with a giant mutex lock, but
	// only then.
	LLVMApiScopedLock() {
	    // It is safer to just run all codegen under the mutex,
	    // it is not like we are going to codegen from multiple threads
	    // at a time anyway.
//	    if (!llvm_is_multithreaded())
#if LLVM_VERSION < 36
		llvm_api_lock.acquire();
#else
		llvm_api_lock.lock();
#endif
	}
	~LLVMApiScopedLock() {
//	    if (!llvm_is_multithreaded())
#if LLVM_VERSION < 36
		llvm_api_lock.release();
#else
		llvm_api_lock.unlock();
#endif
	}
};

static void addFunctionProtos(struct CommonFunctions *CF, ExecutionEngine *EE, Module *M)
{
    LLVMContext &Context = M->getContext();
    FunctionType *FTy = FunctionType::get(Type::getVoidTy(Context),
					  false);
    CF->FHandler = Function::Create(FTy, Function::ExternalLinkage,
					  "clamjit.fail", M);
    CF->FHandler->setDoesNotReturn();
    CF->FHandler->setDoesNotThrow();
#if LLVM_VERSION == 32
    CF->FHandler->addFnAttr(Attributes::NoInline);
#else
    CF->FHandler->addFnAttr(Attribute::NoInline);
#endif
#if LLVM_VERSION < 36
    // addGlobalMapping still exists in LLVM 3.6, but it doesn't work with MCJIT, which now replaces the JIT implementation.
    EE->addGlobalMapping(CF->FHandler, (void*)(intptr_t)jit_exception_handler);
#else
    sys::DynamicLibrary::AddSymbol(CF->FHandler->getName(), (void*)(intptr_t)jit_exception_handler);
#endif
    EE->InstallLazyFunctionCreator(noUnknownFunctions);
    EE->getPointerToFunction(CF->FHandler);

    std::vector<constType*> args;
    args.push_back(PointerType::getUnqual(Type::getInt8Ty(Context)));
    args.push_back(Type::getInt8Ty(Context));
    args.push_back(Type::getInt32Ty(Context));
    args.push_back(Type::getInt32Ty(Context));
#if LLVM_VERSION >= 29
    args.push_back(Type::getInt1Ty(Context));
#endif
    FunctionType* FuncTy_3 = FunctionType::get(Type::getVoidTy(Context),
					       args, false);
    CF->FMemset = Function::Create(FuncTy_3, GlobalValue::ExternalLinkage,
#if LLVM_VERSION < 29
                                   "llvm.memset.i32",
#else
                                   "llvm.memset.p0i8.i32",
#endif
                                   M);
    CF->FMemset->setDoesNotThrow();
#if LLVM_VERSION < 32
    CF->FMemset->setDoesNotCapture(1, true);
#else
    CF->FMemset->setDoesNotCapture(1);
#endif

    args.clear();
    args.push_back(PointerType::getUnqual(Type::getInt8Ty(Context)));
    args.push_back(PointerType::getUnqual(Type::getInt8Ty(Context)));
    args.push_back(Type::getInt32Ty(Context));
    args.push_back(Type::getInt32Ty(Context));
#if LLVM_VERSION >= 29
    args.push_back(Type::getInt1Ty(Context));
#endif
    FunctionType* FuncTy_4 = FunctionType::get(Type::getVoidTy(Context),
					       args, false);
    CF->FMemmove = Function::Create(FuncTy_4, GlobalValue::ExternalLinkage,
#if LLVM_VERSION < 29
                                    "llvm.memmove.i32",
#else
                                    "llvm.memmove.p0i8.i32",
#endif
                                    M);
    CF->FMemmove->setDoesNotThrow();
#if LLVM_VERSION < 32
    CF->FMemmove->setDoesNotCapture(1, true);
#else
    CF->FMemmove->setDoesNotCapture(1);
#endif

    CF->FMemcpy = Function::Create(FuncTy_4, GlobalValue::ExternalLinkage,
#if LLVM_VERSION < 29
                                   "llvm.memcpy.i32",
#else
                                   "llvm.memcpy.p0i8.p0i8.i32",
#endif
                                   M);
    CF->FMemcpy->setDoesNotThrow();
#if LLVM_VERSION < 32
    CF->FMemcpy->setDoesNotCapture(1, true);
#else
    CF->FMemcpy->setDoesNotCapture(1);
#endif

    args.clear();
    args.push_back(Type::getInt16Ty(Context));
    FunctionType *FuncTy_5 = FunctionType::get(Type::getInt16Ty(Context), args, false);
    CF->FBSwap16 = Function::Create(FuncTy_5, GlobalValue::ExternalLinkage,
					  "llvm.bswap.i16", M);
    CF->FBSwap16->setDoesNotThrow();

    args.clear();
    args.push_back(Type::getInt32Ty(Context));
    FunctionType *FuncTy_6 = FunctionType::get(Type::getInt32Ty(Context), args, false);
    CF->FBSwap32 = Function::Create(FuncTy_6, GlobalValue::ExternalLinkage,
					  "llvm.bswap.i32", M);
    CF->FBSwap32->setDoesNotThrow();

    args.clear();
    args.push_back(Type::getInt64Ty(Context));
    FunctionType *FuncTy_7 = FunctionType::get(Type::getInt64Ty(Context), args, false);
    CF->FBSwap64 = Function::Create(FuncTy_7, GlobalValue::ExternalLinkage,
					  "llvm.bswap.i64", M);
    CF->FBSwap64->setDoesNotThrow();

    FunctionType* DummyTy = FunctionType::get(Type::getVoidTy(Context), false);
    CF->FRealmemset = Function::Create(DummyTy, GlobalValue::ExternalLinkage,
					     "memset", M);
#if LLVM_VERSION < 36
    EE->addGlobalMapping(CF->FRealmemset, (void*)(intptr_t)memset);
#else
    sys::DynamicLibrary::AddSymbol(CF->FRealmemset->getName(), (void*)(intptr_t)memset);
#endif
    EE->getPointerToFunction(CF->FRealmemset);
    CF->FRealMemmove = Function::Create(DummyTy, GlobalValue::ExternalLinkage,
					      "memmove", M);
#if LLVM_VERSION < 36
    EE->addGlobalMapping(CF->FRealMemmove, (void*)(intptr_t)memmove);
#else
    sys::DynamicLibrary::AddSymbol(CF->FRealMemmove->getName(), (void*)(intptr_t)memmove);
#endif
    EE->getPointerToFunction(CF->FRealMemmove);
    CF->FRealmemcpy = Function::Create(DummyTy, GlobalValue::ExternalLinkage,
					     "memcpy", M);
#if LLVM_VERSION < 36
    EE->addGlobalMapping(CF->FRealmemcpy, (void*)(intptr_t)memcpy);
#else
    sys::DynamicLibrary::AddSymbol(CF->FRealmemcpy->getName(), (void*)(intptr_t)memcpy);
#endif
    EE->getPointerToFunction(CF->FRealmemcpy);

    args.clear();
    args.push_back(PointerType::getUnqual(Type::getInt8Ty(Context)));
    args.push_back(PointerType::getUnqual(Type::getInt8Ty(Context)));
#if LLVM_VERSION < 32
    args.push_back(EE->getTargetData()->getIntPtrType(Context));
#elif LLVM_VERSION < 38
    args.push_back(EE->getDataLayout()->getIntPtrType(Context));
#else
    args.push_back(EE->getDataLayout().getIntPtrType(Context));
#endif
    FuncTy_5 = FunctionType::get(Type::getInt32Ty(Context),
				 args, false);
    CF->FRealmemcmp = Function::Create(FuncTy_5, GlobalValue::ExternalLinkage, "memcmp", M);
#if LLVM_VERSION < 36
    EE->addGlobalMapping(CF->FRealmemcmp, (void*)(intptr_t)memcmp);
#else
    sys::DynamicLibrary::AddSymbol(CF->FRealmemcmp->getName(), (void*)(intptr_t)memcmp);
#endif
    EE->getPointerToFunction(CF->FRealmemcmp);
}

}
#if LLVM_VERSION >= 29
INITIALIZE_PASS_BEGIN(RuntimeLimits, "rl", "Runtime Limits", false, false)
#if LLVM_VERSION < 37
INITIALIZE_PASS_DEPENDENCY(LoopInfo)
#else
INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
#endif
#if LLVM_VERSION < 38
INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
#else
INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
#endif
#if LLVM_VERSION < 35
INITIALIZE_PASS_DEPENDENCY(DominatorTree)
#else
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
#endif
INITIALIZE_PASS_END(RuntimeLimits, "rl" ,"Runtime Limits", false, false)
#endif

static pthread_mutex_t watchdog_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t watchdog_cond = PTHREAD_COND_INITIALIZER;
static pthread_cond_t watchdog_cond2 = PTHREAD_COND_INITIALIZER;
static int watchdog_running = 0;

struct watchdog_item {
    volatile uint8_t* timeout;
    struct timespec abstimeout;
    struct watchdog_item *next;
    int in_use;
};

static struct watchdog_item* watchdog_head = NULL;
static struct watchdog_item* watchdog_tail = NULL;

extern "C" const char *cli_strerror(int errnum, char* buf, size_t len);
#define WATCHDOG_IDLE 10
static void *bytecode_watchdog(void *arg)
{
    struct timeval tv;
    struct timespec out;
    int ret;
    char err[128];
    pthread_mutex_lock(&watchdog_mutex);
    if (cli_debug_flag)
	cli_dbgmsg_internal("bytecode watchdog is running\n");
    do {
	struct watchdog_item *item;
	gettimeofday(&tv, NULL);
	out.tv_sec = tv.tv_sec + WATCHDOG_IDLE;
	out.tv_nsec = tv.tv_usec*1000;
	/* wait for some work, up to WATCHDOG_IDLE time */
	while (watchdog_head == NULL) {
	    ret = pthread_cond_timedwait(&watchdog_cond, &watchdog_mutex,
					 &out);
	    if (ret == ETIMEDOUT)
		break;
	    if (ret) {
		cli_warnmsg("bytecode_watchdog: cond_timedwait(1) failed: %s\n",
			    cli_strerror(ret, err, sizeof(err)));
		break;
	    }
	}
	if (watchdog_head == NULL)
	    break;
	/* wait till timeout is reached on this item */
	item = watchdog_head;
	while (item == watchdog_head) {
	    item->in_use = 1;
	    ret = pthread_cond_timedwait(&watchdog_cond, &watchdog_mutex,
					 &item->abstimeout);
	    if (ret == ETIMEDOUT)
		break;
	    if (ret) {
		cli_warnmsg("bytecode_watchdog: cond_timedwait(2) failed: %s\n",
			    cli_strerror(ret, err, sizeof(err)));
		break;
	    }
	}
	item->in_use = 0;
	pthread_cond_signal(&watchdog_cond2);
	if (item != watchdog_head)
	    continue;/* got removed meanwhile */
	/* timeout reached, signal it to bytecode */
	*item->timeout = 1;
	cli_warnmsg("[Bytecode JIT]: Bytecode run timed out, timeout flag set\n");
	watchdog_head = item->next;
	if (!watchdog_head)
	    watchdog_tail = NULL;
    } while (1);
    watchdog_running = 0;
    if (cli_debug_flag)
	cli_dbgmsg_internal("bytecode watchdog quiting\n");
    pthread_mutex_unlock(&watchdog_mutex);
    return NULL;
}

static void watchdog_disarm(struct watchdog_item *item)
{
    struct watchdog_item *q, *p = NULL;
    if (!item)
	return;
    pthread_mutex_lock(&watchdog_mutex);
    for (q=watchdog_head;q && q != item;p = q, q = q->next) {}
    if (q == item) {
	if (p)
	    p->next = q->next;
	if (q == watchdog_head)
	    watchdog_head = q->next;
	if (q == watchdog_tail)
	    watchdog_tail = p;
    }
    /* don't remove the item from the list until the watchdog is sleeping on
     * item, or it'll wake up on uninit data */
    while (item->in_use) {
	pthread_cond_signal(&watchdog_cond);
	pthread_cond_wait(&watchdog_cond2, &watchdog_mutex);
    }
    pthread_mutex_unlock(&watchdog_mutex);
}

static int watchdog_arm(struct watchdog_item *item, int ms, volatile uint8_t *timeout)
{
    int rc = 0;
    struct timeval tv0;

    *timeout = 0;
    item->timeout = timeout;
    item->next = NULL;
    item->in_use = 0;

    gettimeofday(&tv0, NULL);
    tv0.tv_usec += ms * 1000;
    item->abstimeout.tv_sec = tv0.tv_sec + tv0.tv_usec/1000000;
    item->abstimeout.tv_nsec = (tv0.tv_usec%1000000)*1000;

    pthread_mutex_lock(&watchdog_mutex);
    if (!watchdog_running) {
	pthread_t thread;
	pthread_attr_t attr;
	pthread_attr_init(&attr);
	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

	if ((rc = pthread_create(&thread, &attr, bytecode_watchdog, NULL))) {
	    char buf[256];
	    cli_errmsg("(watchdog) pthread_create failed: %s\n", cli_strerror(rc, buf, sizeof(buf)));
	}
	if (!rc)
	    watchdog_running = 1;
	pthread_attr_destroy(&attr);
    }
    if (!rc) {
	if (watchdog_tail)
	    watchdog_tail->next = item;
	watchdog_tail = item;
	if (!watchdog_head)
	    watchdog_head = item;
    }
    pthread_cond_signal(&watchdog_cond);
    pthread_mutex_unlock(&watchdog_mutex);
    return rc;
}

static int bytecode_execute(intptr_t code, struct cli_bc_ctx *ctx)
{
    ScopedExceptionHandler handler;
    // execute;
    HANDLER_TRY(handler) {
	// setup exception handler to longjmp back here
	uint32_t result = ((uint32_t (*)(struct cli_bc_ctx *))(intptr_t)code)(ctx);
	*(uint32_t*)ctx->values = result;
	return 0;
    }
    HANDLER_END(handler);
    cli_warnmsg("[Bytecode JIT]: JITed code intercepted runtime error!\n");
    return CL_EBYTECODE;
}

int cli_vm_execute_jit(const struct cli_all_bc *bcs, struct cli_bc_ctx *ctx,
		       const struct cli_bc_func *func)
{
    int ret;
    struct timeval tv0, tv1;
    struct watchdog_item witem;
    // no locks needed here, since LLVM automatically acquires a JIT lock
    // if needed.
    void *code = bcs->engine->compiledFunctions[func];
    if (!code) {
	cli_warnmsg("[Bytecode JIT]: Unable to find compiled function\n");
	if (func->numArgs)
	    cli_warnmsg("[Bytecode JIT] Function has %d arguments, it must have 0 to be called as entrypoint\n",
			func->numArgs);
	return CL_EBYTECODE;
    }
    if (cli_debug_flag)
	gettimeofday(&tv0, NULL);

    if (ctx->bytecode_timeout) {
	/* only spawn if timeout is set.
	 * we don't set timeout for selfcheck (see bb #2235) */
	if (watchdog_arm(&witem, ctx->bytecode_timeout, &ctx->timeout))
	    return CL_EBYTECODE;
    }

    ret = bytecode_execute((intptr_t)code, ctx);

    if (ctx->bytecode_timeout)
	watchdog_disarm(&witem);

    if (cli_debug_flag) {
	long diff;
	gettimeofday(&tv1, NULL);
	tv1.tv_sec -= tv0.tv_sec;
	tv1.tv_usec -= tv0.tv_usec;
	diff = tv1.tv_sec*1000000 + tv1.tv_usec;
	cli_dbgmsg_internal("bytecode finished in %ld us\n", diff);
    }
    return ctx->timeout ? CL_ETIMEOUT : ret;
}

static unsigned char name_salt[16] = { 16, 38, 97, 12, 8, 4, 72, 196, 217, 144, 33, 124, 18, 11, 17, 253 };
static void setGuard(unsigned char* guardbuf)
{
    char salt[48];
    memcpy(salt, name_salt, 16);
    for(unsigned i = 16; i < 48; i++)
	salt[i] = cli_rndnum(255);

    cl_hash_data((char*)"md5", salt, 48, guardbuf, NULL);
}
#if LLVM_VERSION < 32
static void addFPasses(FunctionPassManager &FPM, bool trusted, const TargetData *TD)
#elif LLVM_VERSION < 35
static void addFPasses(FunctionPassManager &FPM, bool trusted, const DataLayout *TD)
#elif LLVM_VERSION < 36
static void addFPasses(FunctionPassManager &FPM, bool trusted, const Module *M)
#elif LLVM_VERSION < 37
static void addFPasses(FunctionPassManager &FPM, bool trusted, Module *M)
#else
static void addFPasses(legacy::FunctionPassManager &FPM, bool trusted, Module *M)
#endif
{
    // Set up the optimizer pipeline.  Start with registering info about how
    // the target lays out data structures.
#if LLVM_VERSION < 32
    FPM.add(new TargetData(*TD));
#elif LLVM_VERSION < 35
    FPM.add(new DataLayout(*TD));
#elif LLVM_VERSION < 36
    FPM.add(new DataLayoutPass(M));
#elif LLVM_VERSION < 37
    DataLayoutPass *DLP = new DataLayoutPass();
    DLP->doInitialization(*M);
    FPM.add(DLP);
#else
    // No DataLayout pass needed anymore.
#endif
    // Promote allocas to registers.
    FPM.add(createPromoteMemoryToRegisterPass());
    FPM.add(new BrSimplifier());
    FPM.add(createDeadCodeEliminationPass());
}

int cli_bytecode_prepare_jit(struct cli_all_bc *bcs)
{
  if (!bcs->engine)
      return CL_EBYTECODE;
  ScopedExceptionHandler handler;
  LLVMApiScopedLock scopedLock;
  // setup exception handler to longjmp back here
  HANDLER_TRY(handler) {
  // LLVM itself never throws exceptions, but operator new may throw bad_alloc
  try {
    Module *M = new Module("ClamAV jit module", bcs->engine->Context);
    {
	// Create the JIT.
	std::string ErrorMsg;
#if LLVM_VERSION < 36
	EngineBuilder builder(M);
#else
	EngineBuilder builder(std::move(std::unique_ptr<Module>(M)));
#endif

#if LLVM_VERSION >= 31
	TargetOptions Options;
#if LLVM_VERSION < 37
    // This option was removed.
#ifdef CL_DEBUG
	//disable this for now, it leaks
	Options.JITEmitDebugInfo = false;
//	Options.JITEmitDebugInfo = true;
#else
	Options.JITEmitDebugInfo = false;
#endif
#endif
#if LLVM_VERSION < 34
	Options.DwarfExceptionHandling = false;
#else
	// TODO: How to do this now?
#endif
	builder.setTargetOptions(Options);
#endif

	builder.setErrorStr(&ErrorMsg);
	builder.setEngineKind(EngineKind::JIT);
	builder.setOptLevel(CodeGenOpt::Default);
	ExecutionEngine *EE = bcs->engine->EE = builder.create();
	if (!EE) {
	    if (!ErrorMsg.empty())
		cli_errmsg("[Bytecode JIT]: error creating execution engine: %s\n",
			   ErrorMsg.c_str());
	    else
		cli_errmsg("[Bytecode JIT]: JIT not registered?\n");
	    return CL_EBYTECODE;
	}
	bcs->engine->Listener  = new NotifyListener();
	EE->RegisterJITEventListener(bcs->engine->Listener);
//	EE->RegisterJITEventListener(createOProfileJITEventListener());
	// Due to LLVM PR4816 only X86 supports non-lazy compilation, disable
	// for now.
	EE->DisableLazyCompilation();
#if LLVM_VERSION < 36
	EE->DisableSymbolSearching();
#else
	// This must be enabled for AddSymbol to work.
	EE->DisableSymbolSearching(false);
#endif

	struct CommonFunctions CF;
	addFunctionProtos(&CF, EE, M);

#if LLVM_VERSION < 37
	FunctionPassManager OurFPM(M), OurFPMUnsigned(M);
#else
    legacy::FunctionPassManager OurFPM(M), OurFPMUnsigned(M);
#endif
#if LLVM_VERSION < 32
	M->setDataLayout(EE->getTargetData()->getStringRepresentation());
#elif LLVM_VERSION < 38
	M->setDataLayout(EE->getDataLayout()->getStringRepresentation());
#else
    M->setDataLayout(EE->getDataLayout().getStringRepresentation());
#endif
#if LLVM_VERSION < 31
	M->setTargetTriple(sys::getHostTriple());
#else
	M->setTargetTriple(sys::getDefaultTargetTriple());
#endif
#if LLVM_VERSION < 32
	addFPasses(OurFPM, true, EE->getTargetData());
	addFPasses(OurFPMUnsigned, false, EE->getTargetData());
#elif LLVM_VERSION < 35
	addFPasses(OurFPM, true, EE->getDataLayout());
	addFPasses(OurFPMUnsigned, false, EE->getDataLayout());
#else
	addFPasses(OurFPM, true, M);
	addFPasses(OurFPMUnsigned, false, M);
#endif


	//TODO: create a wrapper that calls pthread_getspecific
	unsigned maxh = cli_globals[0].offset + sizeof(struct cli_bc_hooks);
	constType *HiddenCtx = PointerType::getUnqual(ArrayType::get(Type::getInt8Ty(bcs->engine->Context), maxh));

	LLVMTypeMapper apiMap(bcs->engine->Context, cli_apicall_types, cli_apicall_maxtypes, HiddenCtx);
	Function **apiFuncs = new Function *[cli_apicall_maxapi];
	for (unsigned i=0;i<cli_apicall_maxapi;i++) {
	    const struct cli_apicall *api = &cli_apicalls[i];
	    constFunctionType *FTy = cast<FunctionType>(apiMap.get(69+api->type, NULL, NULL));
	    Function *F = Function::Create(FTy, Function::ExternalLinkage,
					   api->name, M);
	    void *dest;
	    switch (api->kind) {
		case 0:
		    dest = (void*)(intptr_t)cli_apicalls0[api->idx];
		    break;
		case 1:
		    dest = (void*)(intptr_t)cli_apicalls1[api->idx];
		    break;
		case 2:
		    dest = (void*)(intptr_t)cli_apicalls2[api->idx];
		    break;
		case 3:
		    dest = (void*)(intptr_t)cli_apicalls3[api->idx];
		    break;
		case 4:
		    dest = (void*)(intptr_t)cli_apicalls4[api->idx];
		    break;
		case 5:
		    dest = (void*)(intptr_t)cli_apicalls5[api->idx];
		    break;
		case 6:
		    dest = (void*)(intptr_t)cli_apicalls6[api->idx];
		    break;
		case 7:
		    dest = (void*)(intptr_t)cli_apicalls7[api->idx];
		    break;
		case 8:
		    dest = (void*)(intptr_t)cli_apicalls8[api->idx];
		    break;
		case 9:
		    dest = (void*)(intptr_t)cli_apicalls9[api->idx];
		    break;
		default:
		    llvm_unreachable("invalid api type");
	    }
	    if (!dest) {
		std::string reason((Twine("No mapping for builtin api ")+api->name).str());
		llvm_error_handler(0, reason);
	    }
#if LLVM_VERSION < 36
	    EE->addGlobalMapping(F, dest);
#else
    // addGlobalMapping doesn't work with MCJIT, so use symbol searching instead.
    sys::DynamicLibrary::AddSymbol(F->getName(), dest);
#endif
	    EE->getPointerToFunction(F);
	    apiFuncs[i] = F;
	}

	// stack protector
	FunctionType *FTy = FunctionType::get(Type::getVoidTy(M->getContext()),
						    false);
	GlobalVariable *Guard = new GlobalVariable(*M, PointerType::getUnqual(Type::getInt8Ty(M->getContext())),
						    true, GlobalValue::ExternalLinkage, 0, "__stack_chk_guard");
	unsigned plus = 0;
	if (2*sizeof(void*) <= 16 && cli_rndnum(2)==2) {
	    plus = sizeof(void*);
	}
#if LLVM_VERSION < 36
	EE->addGlobalMapping(Guard, (void*)(&bcs->engine->guard.b[plus]));
#else
    sys::DynamicLibrary::AddSymbol(Guard->getName(), (void*)(&bcs->engine->guard.b[plus]));
#endif
	setGuard(bcs->engine->guard.b);
	bcs->engine->guard.b[plus+sizeof(void*)-1] = 0x00;
//	printf("%p\n", *(void**)(&bcs->engine->guard.b[plus]));
	Function *SFail = Function::Create(FTy, Function::ExternalLinkage,
					      "__stack_chk_fail", M);
#if LLVM_VERSION < 36
	EE->addGlobalMapping(SFail, (void*)(intptr_t)jit_ssp_handler);
#else
    sys::DynamicLibrary::AddSymbol(SFail->getName(), (void*)(intptr_t)jit_ssp_handler);
#endif
        EE->getPointerToFunction(SFail);

	llvm::Function **Functions = new Function*[bcs->count];
	for (unsigned i=0;i<bcs->count;i++) {
	    const struct cli_bc *bc = &bcs->all_bcs[i];
	    if (bc->state == bc_skip || bc->state == bc_interp) {
		Functions[i] = 0;
		continue;
	    }
	    LLVMCodegen Codegen(bc, M, &CF, bcs->engine->compiledFunctions, EE,
				OurFPM, OurFPMUnsigned, apiFuncs, apiMap);
	    Function *F = Codegen.generate();
	    if (!F) {
		cli_errmsg("[Bytecode JIT]: JIT codegen failed\n");
		delete [] apiFuncs;
		for (unsigned z=0; z < i; z++) {
		    delete Functions[z];
		}
		delete [] Functions;
		return CL_EBYTECODE;
	    }
	    Functions[i] = F;
	}
	delete [] apiFuncs;

	bool has_untrusted = false;

	for (unsigned i=0;i<bcs->count;i++) {
	    if (!bcs->all_bcs[i].trusted) {
		has_untrusted = true;
		break;
	    }
	}
#if LLVM_VERSION < 37
	PassManager PM;
#else
	legacy::PassManager PM;
#endif
#if LLVM_VERSION < 32
	PM.add(new TargetData(*EE->getTargetData()));
#elif LLVM_VERSION < 35
	PM.add(new DataLayout(*EE->getDataLayout()));
#elif LLVM_VERSION < 36
	PM.add(new DataLayoutPass(M));
#elif LLVM_VERSION < 37
    DataLayoutPass *DLP = new DataLayoutPass();
    DLP->doInitialization(*M);
    PM.add(DLP);
#else
    // No DataLayout pass needed anymore.
#endif
	// TODO: only run this on the untrusted bytecodes, not all of them...
	if (has_untrusted)
	    PM.add(createClamBCRTChecks());
#if LLVM_VERSION >= 38
    // With LLVM 3.8 the test_bswap_jit test fails with the GVNPass enabled.
    // To prevent the segfaults mentioned below, replace it with the ConstantPropagationPass.
    PM.add(createConstantPropagationPass());
#elif LLVM_VERSION >= 36
	// With LLVM 3.6 (MCJIT) this Pass is required to work around
	// a crash in LLVM caused by the SCCP Pass:
	// Pass 'Sparse Conditional Constant Propagation' is not initialized.
	// Verify if there is a pass dependency cycle.
	// Required Passes:
	//
	// Program received signal SIGSEGV, Segmentation fault.
	PM.add(createGVNPass());
#endif
	PM.add(createSCCPPass());
	PM.add(createCFGSimplificationPass());
	PM.add(createGlobalOptimizerPass());
	PM.add(createConstantMergePass());

	RuntimeLimits *RL = new RuntimeLimits();
	PM.add(RL);
	TimerWrapper pmTimer2("Transform passes");
	pmTimer2.startTimer();
	PM.run(*M);
	pmTimer2.stopTimer();
	DEBUG(M->dump());

#if LLVM_VERSION >= 36
	EE->finalizeObject();
#endif

	{
	    PrettyStackTraceString CrashInfo2("Native machine codegen");
	    TimerWrapper codegenTimer("Native codegen");
	    codegenTimer.startTimer();
	    // compile all functions now, not lazily!
	    for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
		Function *Fn = &*I;
		if (!Fn->isDeclaration()) {
		    EE->getPointerToFunction(Fn);
		}
	    }
	    codegenTimer.stopTimer();
	}

	for (unsigned i=0;i<bcs->count;i++) {
	    const struct cli_bc_func *func = &bcs->all_bcs[i].funcs[0];
	    if (!Functions[i])
		continue;// not JITed
	    bcs->engine->compiledFunctions[func] = EE->getPointerToFunction(Functions[i]);
	    bcs->all_bcs[i].state = bc_jit;
	}
	delete [] Functions;
    }
    return CL_SUCCESS;
  } catch (std::bad_alloc &badalloc) {
      cli_errmsg("[Bytecode JIT]: bad_alloc: %s\n",
		 badalloc.what());
      return CL_EMEM;
  } catch (...) {
      cli_errmsg("[Bytecode JIT]: Unexpected unknown exception occurred\n");
      return CL_EBYTECODE;
  }
  return 0;
  } HANDLER_END(handler);
  cli_errmsg("[Bytecode JIT] *** FATAL error encountered during bytecode generation\n");
  return CL_EBYTECODE;
}

int bytecode_init(void)
{
    // If already initialized return
#if LLVM_VERSION < 35
    if (llvm_is_multithreaded()) {
	cli_warnmsg("bytecode_init: already initialized\n");
	return CL_EARG;
    }
#else
    if (!llvm_is_multithreaded()) {
        cli_warnmsg("bytecode_init: LLVM is compiled without multithreading support\n");
    }
#endif

    // LLVM safety assertion prevention fix
    // TODO: do we want to do a full shutdown?
    remove_fatal_error_handler();
    llvm_install_error_handler(llvm_error_handler);
#ifdef CL_DEBUG
    sys::PrintStackTraceOnErrorSignal();
#if LLVM_VERSION >= 34
    llvm::EnablePrettyStackTrace();
#endif
#else
#if LLVM_VERSION < 34
    llvm::DisablePrettyStackTrace = true;
#endif
#endif
    atexit(do_shutdown);

#if LLVM_VERSION < 31
#ifdef CL_DEBUG
    //disable this for now, it leaks
    llvm::JITEmitDebugInfo = false;
//    llvm::JITEmitDebugInfo = true;
#else
    llvm::JITEmitDebugInfo = false;
#endif
    llvm::DwarfExceptionHandling = false;
#endif
#if LLVM_VERSION < 33
    llvm_start_multithreaded();
#else
    // This is now deprecated/useless: Multi-threading can only be enabled/disabled with the compile time define LLVM_ENABLE_THREADS in LLVM.
#endif

    // If we have a native target, initialize it to ensure it is linked in and
    // usable by the JIT.
#ifndef AC_APPLE_UNIVERSAL_BUILD
    InitializeNativeTarget();
#if LLVM_VERSION >= 36
    InitializeNativeTargetAsmPrinter();
    InitializeNativeTargetAsmParser();
#endif
#else
    InitializeAllTargets();
#endif

    if (!llvm_is_multithreaded()) {
	//TODO:cli_dbgmsg
	DEBUG(errs() << "WARNING: ClamAV JIT built w/o atomic builtins\n"
	      << "On x86 for best performance ClamAV should be built for i686, not i386!\n");
    }
    return 0;
}

// Called once when loading a new set of BC files
int cli_bytecode_init_jit(struct cli_all_bc *bcs, unsigned dconfmask)
{
    LLVMApiScopedLock scopedLock;
    bcs->engine = new(std::nothrow) cli_bcengine;
    if (!bcs->engine)
	return CL_EMEM;
    bcs->engine->EE = 0;
    bcs->engine->Listener = 0;
    return 0;
}

int cli_bytecode_done_jit(struct cli_all_bc *bcs, int partial)
{
    LLVMApiScopedLock scopedLock;
    if (bcs->engine) {
	if (bcs->engine->EE) {
	    if (bcs->engine->Listener)
		bcs->engine->EE->UnregisterJITEventListener(bcs->engine->Listener);
	    delete bcs->engine->EE;
	    bcs->engine->EE = 0;
	}
	delete bcs->engine->Listener;
	bcs->engine->Listener = 0;
	if (!partial) {
	    delete bcs->engine;
	    bcs->engine = 0;
	}
    }
    return 0;
}

void cli_bytecode_debug(int argc, char **argv)
{
  cl::ParseCommandLineOptions(argc, argv);
}

typedef struct lines {
    MemoryBuffer *buffer;
    std::vector<const char*> linev;
} linesTy;

static struct lineprinter {
    StringMap<linesTy*> files;
} LinePrinter;

void cli_bytecode_debug_printsrc(const struct cli_bc_ctx *ctx)
{
    if (!ctx->file || !ctx->directory || !ctx->line) {
	errs() << (ctx->directory ? "d":"null") << ":" << (ctx->file ? "f" : "null")<< ":" << ctx->line << "\n";
	return;
    }
    // acquire a mutex here
    sys::Mutex mtx(false);
    sys::SmartScopedLock<false> lock(mtx);

    std::string path = std::string(ctx->directory) + "/" + std::string(ctx->file);
    StringMap<linesTy*>::iterator I = LinePrinter.files.find(path);
    linesTy *lines;
    if (I == LinePrinter.files.end()) {
	lines = new linesTy;
	std::string ErrorMessage;
#if LLVM_VERSION < 29
	lines->buffer = MemoryBuffer::getFile(path, &ErrorMessage);
#elif LLVM_VERSION < 35
	OwningPtr<MemoryBuffer> File;
	error_code ec = MemoryBuffer::getFile(path, File);
	if (ec) {
	    ErrorMessage = ec.message();
	    lines->buffer = 0;
	} else
	    lines->buffer = File.take();
#else
	ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr = MemoryBuffer::getFile(path);
	if (!FileOrErr) {
		// TODO: How to handle ErrorMessage?
		lines->buffer = 0;
	}
	else {
		lines->buffer = FileOrErr.get().release();
	}
#endif
	if (!lines->buffer) {
	    errs() << "Unable to open file '" << path << "'\n";
	    delete lines;
	    return ;
	}
	LinePrinter.files[path] = lines;
    } else {
	lines = I->getValue();
    }
    while (lines->linev.size() <= ctx->line+1) {
	const char *p;
	if (lines->linev.empty()) {
	    p = lines->buffer->getBufferStart();
	    lines->linev.push_back(p);
	} else {
	    p = lines->linev.back();
	    if (p == lines->buffer->getBufferEnd())
		break;
	    p = strchr(p, '\n');
	    if (!p) {
		p = lines->buffer->getBufferEnd();
		lines->linev.push_back(p);
	    } else
		lines->linev.push_back(p+1);
	}
    }
    if (ctx->line >= lines->linev.size()) {
	errs() << "Line number " << ctx->line << "out of file\n";
	return;
    }
    assert(ctx->line < lines->linev.size());

#if LLVM_VERSION < 28
    int line = (int)ctx->line ? (int)ctx->line : -1;
    int col = (int)ctx->col ? (int)ctx->col : -1;
    //TODO: print this ourselves, instead of using SMDiagnostic
    SMDiagnostic diag(ctx->file, line, col,
		 "", std::string(lines->linev[ctx->line-1], lines->linev[ctx->line]-1));
    diag.Print("[trace]", errs());
#endif
}

int have_clamjit=1;
void cli_bytecode_printversion()
{
  cl::PrintVersionMessage();
}

void cli_printcxxver()
{
    /* Try to print information about some commonly used compilers */
#ifdef __GNUC__
    printf("GNU C++: %s (%u.%u.%u)\n", __VERSION__, __GNUC__, __GNUC_MINOR__,
	   __GNUC_PATCHLEVEL__);
#endif
#ifdef __INTEL_COMPILER
    printf("Intel Compiler C++ %u\n", __INTEL_COMPILER);
#endif
#ifdef _MSC_VER
    printf("Microsoft Visual C++ %u\n", _MSC_VER);
#endif
}

namespace ClamBCModule {
void stop(const char *msg, llvm::Function* F, llvm::Instruction* I)
{
    if (F && F->hasName()) {
#if LLVM_VERSION < 31
	cli_warnmsg("[Bytecode JIT] in function %s: %s", F->getNameStr().c_str(), msg);
#else
	cli_warnmsg("[Bytecode JIT] in function %s: %s", F->getName().str().c_str(), msg);
#endif
    } else {
	cli_warnmsg("[Bytecode JIT] %s", msg);
    }
}
}

#if LLVM_VERSION >= 29
#if LLVM_VERSION < 36
static Value *findDbgGlobalDeclare(GlobalVariable *V) {
#else
static Metadata *findDbgGlobalDeclare(GlobalVariable *V) {
#endif
  const Module *M = V->getParent();
  NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv");
  if (!NMD)
    return 0;

  for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
#if LLVM_VERSION < 37
    DIDescriptor DIG(cast<MDNode>(NMD->getOperand(i)));
    if (!DIG.isGlobalVariable())
      continue;
    if (DIGlobalVariable(DIG).getGlobal() == V)
      return DIG;
#else
    MDNode *DIG = NMD->getOperand(i);
    if (!DIGlobalVariable::classof(DIG))
      continue;
    if ((cast<DIGlobalVariable>(DIG))->getVariable() == V)
      return DIG;
#endif
  }
  return 0;
}

/// Find the debug info descriptor corresponding to this function.
#if LLVM_VERSION < 36
static Value *findDbgSubprogramDeclare(Function *V) {
#else
static Metadata *findDbgSubprogramDeclare(Function *V) {
#endif
  const Module *M = V->getParent();
  NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.sp");
  if (!NMD)
    return 0;

  for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
#if LLVM_VERSION < 37
    DIDescriptor DIG(cast<MDNode>(NMD->getOperand(i)));
    if (!DIG.isSubprogram())
      continue;
    if (DISubprogram(DIG).getFunction() == V)
      return DIG;
#else
    MDNode *DIG = NMD->getOperand(i);
    if (!DISubprogram::classof(DIG))
      continue;
    if ((cast<DISubprogram>(DIG))->describes(V))
      return DIG;
#endif
  }
  return 0;
}

/// Finds the llvm.dbg.declare intrinsic corresponding to this value if any.
/// It looks through pointer casts too.
static const DbgDeclareInst *findDbgDeclare(const Value *V) {
  V = V->stripPointerCasts();

  if (!isa<Instruction>(V) && !isa<Argument>(V))
    return 0;

  const Function *F = NULL;
  if (const Instruction *I = dyn_cast<Instruction>(V))
    F = I->getParent()->getParent();
  else if (const Argument *A = dyn_cast<Argument>(V))
    F = A->getParent();

  for (Function::const_iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
    for (BasicBlock::const_iterator BI = (*FI).begin(), BE = (*FI).end();
         BI != BE; ++BI)
      if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
        if (DDI->getAddress() == V)
          return DDI;

  return 0;
}
static bool getLocationInfo(const Value *V, std::string &DisplayName,
                            std::string &Type, unsigned &LineNo,
                            std::string &File, std::string &Dir) {
#if LLVM_VERSION < 33
  DICompileUnit Unit;
#else
  StringRef G;
  StringRef H;
#endif
#if LLVM_VERSION < 35
  DIType TypeD;
#endif
  StringRef T;

  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(const_cast<Value*>(V))) {
#if LLVM_VERSION < 36
    Value *DIGV = findDbgGlobalDeclare(GV);
#else
    Metadata *DIGV = findDbgGlobalDeclare(GV);
#endif
    if (!DIGV) return false;
#if LLVM_VERSION < 37
    DIGlobalVariable Var(cast<MDNode>(DIGV));
#else
    DIGlobalVariable *Var = cast<DIGlobalVariable>(DIGV);
#endif

#if LLVM_VERSION < 37
    StringRef D = Var.getDisplayName();
#else
    StringRef D = Var->getDisplayName();
#endif
    if (!D.empty())
      DisplayName = D;
#if LLVM_VERSION < 37
    LineNo = Var.getLineNumber();
#else
    LineNo = Var->getLine();
#endif
#if LLVM_VERSION < 33
    Unit = Var.getCompileUnit();
#elif LLVM_VERSION < 37
    G = Var.getFilename();
    H = Var.getDirectory();
#else
    G = Var->getFilename();
    H = Var->getDirectory();
#endif
#if LLVM_VERSION < 35
    TypeD = Var.getType();
#elif LLVM_VERSION < 37
    T = Var.getType().getName();
#else
    T = (cast<DIType>(*Var->getType())).getName();
#endif
  } else if (Function *F = dyn_cast<Function>(const_cast<Value*>(V))){
#if LLVM_VERSION < 36
    Value *DIF = findDbgSubprogramDeclare(F);
#else
    Metadata *DIF = findDbgSubprogramDeclare(F);
#endif
    if (!DIF) return false;
#if LLVM_VERSION < 37
    DISubprogram Var(cast<MDNode>(DIF));
#else
    DISubprogram *Var = cast<DISubprogram>(DIF);
#endif

#if LLVM_VERSION < 37
    StringRef D = Var.getDisplayName();
#else
    StringRef D = Var->getDisplayName();
#endif
    if (!D.empty())
      DisplayName = D;
#if LLVM_VERSION < 37
    LineNo = Var.getLineNumber();
#else
    LineNo = Var->getLine();
#endif
#if LLVM_VERSION < 33
    Unit = Var.getCompileUnit();
#elif LLVM_VERSION < 37
    G = Var.getFilename();
    H = Var.getDirectory();
#else
    G = Var->getFilename();
    H = Var->getDirectory();
#endif
#if LLVM_VERSION < 35
    TypeD = Var.getType();
#elif LLVM_VERSION < 37
    T = Var.getType().getName();
#else
    T = Var->getType()->getName();
#endif
  } else {
    const DbgDeclareInst *DDI = findDbgDeclare(V);
    if (!DDI) return false;
#if LLVM_VERSION < 37
    DIVariable Var(cast<MDNode>(DDI->getVariable()));
#else
    DIVariable* Var = DDI->getVariable();
#endif

#if LLVM_VERSION < 37
    StringRef D = Var.getName();
#else
    StringRef D = Var->getName();
#endif
    if (!D.empty())
      DisplayName = D;
#if LLVM_VERSION < 37
    LineNo = Var.getLineNumber();
#else
    LineNo = Var->getLine();
#endif
#if LLVM_VERSION < 33
    Unit = Var.getCompileUnit();
#else
    // getFilename and getDirectory are not defined
    G = StringRef();
    H = StringRef();
#endif
#if LLVM_VERSION < 35
    TypeD = Var.getType();
#elif LLVM_VERSION < 37
    T = Var.getType().getName();
#else
    T = (cast<DIType>(*Var->getType())).getName();
#endif
  }

#if LLVM_VERSION < 35
  T = TypeD.getName();
#endif
  if (!T.empty())
    Type = T;
#if LLVM_VERSION < 33
  StringRef G = Unit.getFilename();
  StringRef H = Unit.getDirectory();
#endif
  if (!G.empty())
    File = G;
  if (!H.empty())
    Dir = H;
  return true;
}
#endif

void printValue(llvm::Value *V, bool a, bool b) {
    std::string DisplayName;
    std::string Type;
    unsigned Line;
    std::string File;
    std::string Dir;
    if (!getLocationInfo(V, DisplayName, Type, Line, File, Dir)) {
	errs() << *V << "\n";
	return;
    }
    errs() << "'" << DisplayName << "' (" << File << ":" << Line << ")";
}

void printLocation(llvm::Instruction *I, bool a, bool b) {
    if (MDNode *N = I->getMetadata("dbg")) {
#if LLVM_VERSION < 37
	DILocation Loc(N);
	errs() << Loc.getFilename() << ":" << Loc.getLineNumber();
	if (unsigned Col = Loc.getColumnNumber()) {
#else
    DebugLoc Loc(N);
    errs() << Loc.get()->getFilename() << ":" << Loc.getLine();
    if (unsigned Col = Loc.getCol()) {
#endif
  	    errs() << ":" << Col;
  	}
  	errs() << ": ";
  	return;
    }
    errs() << *I << ":\n";
}