1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505
//! A `Builder` enables you to build instructions.
use llvm_sys::core::{
LLVMAddCase, LLVMAddClause, LLVMAddDestination, LLVMBuildAShr, LLVMBuildAdd, LLVMBuildAddrSpaceCast,
LLVMBuildAggregateRet, LLVMBuildAlloca, LLVMBuildAnd, LLVMBuildArrayAlloca, LLVMBuildArrayMalloc,
LLVMBuildAtomicCmpXchg, LLVMBuildAtomicRMW, LLVMBuildBitCast, LLVMBuildBr, LLVMBuildCast, LLVMBuildCondBr,
LLVMBuildExactSDiv, LLVMBuildExtractElement, LLVMBuildExtractValue, LLVMBuildFAdd, LLVMBuildFCmp, LLVMBuildFDiv,
LLVMBuildFMul, LLVMBuildFNeg, LLVMBuildFPCast, LLVMBuildFPExt, LLVMBuildFPToSI, LLVMBuildFPToUI, LLVMBuildFPTrunc,
LLVMBuildFRem, LLVMBuildFSub, LLVMBuildFence, LLVMBuildFree, LLVMBuildGlobalString, LLVMBuildGlobalStringPtr,
LLVMBuildICmp, LLVMBuildIndirectBr, LLVMBuildInsertElement, LLVMBuildInsertValue, LLVMBuildIntCast,
LLVMBuildIntToPtr, LLVMBuildIsNotNull, LLVMBuildIsNull, LLVMBuildLShr, LLVMBuildLandingPad, LLVMBuildMalloc,
LLVMBuildMul, LLVMBuildNSWAdd, LLVMBuildNSWMul, LLVMBuildNSWNeg, LLVMBuildNSWSub, LLVMBuildNUWAdd, LLVMBuildNUWMul,
LLVMBuildNUWNeg, LLVMBuildNUWSub, LLVMBuildNeg, LLVMBuildNot, LLVMBuildOr, LLVMBuildPhi, LLVMBuildPointerCast,
LLVMBuildPtrToInt, LLVMBuildResume, LLVMBuildRet, LLVMBuildRetVoid, LLVMBuildSDiv, LLVMBuildSExt,
LLVMBuildSExtOrBitCast, LLVMBuildSIToFP, LLVMBuildSRem, LLVMBuildSelect, LLVMBuildShl, LLVMBuildShuffleVector,
LLVMBuildStore, LLVMBuildSub, LLVMBuildSwitch, LLVMBuildTrunc, LLVMBuildTruncOrBitCast, LLVMBuildUDiv,
LLVMBuildUIToFP, LLVMBuildURem, LLVMBuildUnreachable, LLVMBuildVAArg, LLVMBuildXor, LLVMBuildZExt,
LLVMBuildZExtOrBitCast, LLVMClearInsertionPosition, LLVMDisposeBuilder, LLVMGetInsertBlock, LLVMInsertIntoBuilder,
LLVMInsertIntoBuilderWithName, LLVMPositionBuilder, LLVMPositionBuilderAtEnd, LLVMPositionBuilderBefore,
LLVMSetCleanup,
};
#[llvm_versions(4.0..=14.0)]
use llvm_sys::core::{
LLVMBuildCall, LLVMBuildGEP, LLVMBuildInBoundsGEP, LLVMBuildInvoke, LLVMBuildLoad, LLVMBuildPtrDiff,
LLVMBuildStructGEP,
};
#[llvm_versions(15.0..=latest)]
use llvm_sys::core::{
LLVMBuildCall2, LLVMBuildGEP2, LLVMBuildInBoundsGEP2, LLVMBuildInvoke2, LLVMBuildLoad2, LLVMBuildPtrDiff2,
LLVMBuildStructGEP2,
};
#[llvm_versions(8.0..=latest)]
use llvm_sys::core::{LLVMBuildIntCast2, LLVMBuildMemCpy, LLVMBuildMemMove, LLVMBuildMemSet};
use llvm_sys::prelude::{LLVMBuilderRef, LLVMValueRef};
use thiserror::Error;
use crate::basic_block::BasicBlock;
#[llvm_versions(7.0..=8.0)]
use crate::context::AsContextRef;
#[llvm_versions(7.0..=latest)]
use crate::debug_info::DILocation;
use crate::support::to_c_str;
use crate::types::{AsTypeRef, BasicType, FloatMathType, FunctionType, IntMathType, PointerMathType, PointerType};
#[llvm_versions(4.0..=14.0)]
use crate::values::CallableValue;
use crate::values::{
AggregateValue, AggregateValueEnum, AsValueRef, BasicMetadataValueEnum, BasicValue, BasicValueEnum, CallSiteValue,
FloatMathValue, FunctionValue, GlobalValue, InstructionOpcode, InstructionValue, IntMathValue, IntValue, PhiValue,
PointerMathValue, PointerValue, StructValue, VectorValue,
};
use crate::{AtomicOrdering, AtomicRMWBinOp, FloatPredicate, IntPredicate};
use std::cell::Cell;
use std::marker::PhantomData;
#[derive(Debug, PartialEq, Clone, Copy)]
enum PositionState {
NotSet,
Set,
}
/// Errors that can be generated by the Builder. All `build_*` methods return a `Result<_, BuilderError>`, which must be handled.
#[derive(Error, Debug, PartialEq, Eq)]
pub enum BuilderError {
#[error("Builder position is not set")]
UnsetPosition,
#[error("Alignment error")]
AlignmentError(&'static str),
#[error("Aggregate extract index out of range")]
ExtractOutOfRange,
#[error("Bitwidth of a value is incorrect")]
BitwidthError(&'static str),
#[error("Pointee type does not match the value's type")]
PointeeTypeMismatch(&'static str),
#[error("Values do not have the same type")]
ValueTypeMismatch(&'static str),
#[error("Ordering error or mismatch")]
OrderingError(&'static str),
#[error("GEP pointee is not a struct")]
GEPPointee,
#[error("GEP index out of range")]
GEPIndex,
}
#[derive(Debug)]
/// All `build_*` methods return a `Result<_, BuilderError>` type containing either the returned value or some error.
/// Those methods all may return `BuilderError::UnsetPosition` if a `position_*` method has not yet been called, in addition
/// to any other possibility.
pub struct Builder<'ctx> {
builder: LLVMBuilderRef,
positioned: Cell<PositionState>,
_marker: PhantomData<&'ctx ()>,
}
#[allow(unused)] // only used in documentation
use crate::context::Context;
impl<'ctx> Builder<'ctx> {
pub unsafe fn new(builder: LLVMBuilderRef) -> Self {
debug_assert!(!builder.is_null());
Builder {
positioned: Cell::from(PositionState::NotSet),
builder,
_marker: PhantomData,
}
}
/// Acquires the underlying raw pointer belonging to this `Builder` type.
pub fn as_mut_ptr(&self) -> LLVMBuilderRef {
self.builder
}
// REVIEW: Would probably make this API a bit simpler by taking Into<Option<&BasicValue>>
// So that you could just do build_return(&value) or build_return(None). Is that frowned upon?
/// Builds a function return instruction. It should be provided with `None` if the return type
/// is void otherwise `Some(&value)` should be provided.
///
/// # Example
///
/// ```no_run
/// use inkwell::context::Context;
///
/// // A simple function which returns its argument:
/// let context = Context::create();
/// let module = context.create_module("ret");
/// let builder = context.create_builder();
/// let i32_type = context.i32_type();
/// let arg_types = [i32_type.into()];
/// let fn_type = i32_type.fn_type(&arg_types, false);
/// let fn_value = module.add_function("ret", fn_type, None);
/// let entry = context.append_basic_block(fn_value, "entry");
/// let i32_arg = fn_value.get_first_param().unwrap();
///
/// builder.position_at_end(entry);
/// builder.build_return(Some(&i32_arg)).unwrap();
/// ```
pub fn build_return(&self, value: Option<&dyn BasicValue<'ctx>>) -> Result<InstructionValue<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let value = unsafe {
value.map_or_else(
|| LLVMBuildRetVoid(self.builder),
|value| LLVMBuildRet(self.builder, value.as_value_ref()),
)
};
unsafe { Ok(InstructionValue::new(value)) }
}
/// Builds a function return instruction for a return type which is an aggregate type (ie structs and arrays).
/// It is not necessary to use this over `build_return` but may be more convenient to use.
///
/// # Example
///
/// ```no_run
/// use inkwell::context::Context;
///
/// // This builds a simple function which returns a struct (tuple) of two ints.
/// let context = Context::create();
/// let module = context.create_module("ret");
/// let builder = context.create_builder();
/// let i32_type = context.i32_type();
/// let i32_three = i32_type.const_int(3, false);
/// let i32_seven = i32_type.const_int(7, false);
/// let struct_type = context.struct_type(&[i32_type.into(), i32_type.into()], false);
/// let fn_type = struct_type.fn_type(&[], false);
/// let fn_value = module.add_function("ret", fn_type, None);
/// let entry = context.append_basic_block(fn_value, "entry");
///
/// builder.position_at_end(entry);
/// builder.build_aggregate_return(&[i32_three.into(), i32_seven.into()]).unwrap();
/// ```
pub fn build_aggregate_return(
&self,
values: &[BasicValueEnum<'ctx>],
) -> Result<InstructionValue<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let mut args: Vec<LLVMValueRef> = values.iter().map(|val| val.as_value_ref()).collect();
let value = unsafe { LLVMBuildAggregateRet(self.builder, args.as_mut_ptr(), args.len() as u32) };
unsafe { Ok(InstructionValue::new(value)) }
}
/// Builds a function call instruction.
/// [`FunctionValue`]s can be implicitly converted into a [`CallableValue`].
/// See [`CallableValue`] for details on calling a [`PointerValue`] that points to a function.
///
/// [`FunctionValue`]: crate::values::FunctionValue
///
/// # Example
///
/// ```no_run
/// use inkwell::context::Context;
///
/// // A simple function which calls itself:
/// let context = Context::create();
/// let module = context.create_module("ret");
/// let builder = context.create_builder();
/// let i32_type = context.i32_type();
/// let fn_type = i32_type.fn_type(&[i32_type.into()], false);
/// let fn_value = module.add_function("ret", fn_type, None);
/// let entry = context.append_basic_block(fn_value, "entry");
/// let i32_arg = fn_value.get_first_param().unwrap();
/// let md_string = context.metadata_string("a metadata");
///
/// builder.position_at_end(entry);
///
/// let ret_val = builder.build_call(fn_value, &[i32_arg.into(), md_string.into()], "call").unwrap()
/// .try_as_basic_value()
/// .left()
/// .unwrap();
///
/// builder.build_return(Some(&ret_val)).unwrap();
/// ```
#[llvm_versions(4.0..=14.0)]
pub fn build_call<F>(
&self,
function: F,
args: &[BasicMetadataValueEnum<'ctx>],
name: &str,
) -> Result<CallSiteValue<'ctx>, BuilderError>
where
F: Into<CallableValue<'ctx>>,
{
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let callable_value = function.into();
let fn_val_ref = callable_value.as_value_ref();
// LLVM gets upset when void return calls are named because they don't return anything
let name = if callable_value.returns_void() { "" } else { name };
let c_string = to_c_str(name);
let mut args: Vec<LLVMValueRef> = args.iter().map(|val| val.as_value_ref()).collect();
let value = unsafe {
LLVMBuildCall(
self.builder,
fn_val_ref,
args.as_mut_ptr(),
args.len() as u32,
c_string.as_ptr(),
)
};
unsafe { Ok(CallSiteValue::new(value)) }
}
/// Builds a function call instruction. Alias for [Builder::build_direct_call].
#[llvm_versions(15.0..=latest)]
pub fn build_call(
&self,
function: FunctionValue<'ctx>,
args: &[BasicMetadataValueEnum<'ctx>],
name: &str,
) -> Result<CallSiteValue<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
self.build_direct_call(function, args, name)
}
/// Builds a function call instruction. The function being called is known at compile time. If
/// you want to call a function pointer, see [Builder::build_indirect_call].
///
/// # Example
///
/// ```no_run
/// use inkwell::context::Context;
///
/// // A simple function which calls itself:
/// let context = Context::create();
/// let module = context.create_module("ret");
/// let builder = context.create_builder();
/// let i32_type = context.i32_type();
/// let fn_type = i32_type.fn_type(&[i32_type.into()], false);
/// let fn_value = module.add_function("ret", fn_type, None);
/// let entry = context.append_basic_block(fn_value, "entry");
/// let i32_arg = fn_value.get_first_param().unwrap();
/// let md_string = context.metadata_string("a metadata");
///
/// builder.position_at_end(entry);
///
/// let ret_val = builder.build_call(fn_value, &[i32_arg.into(), md_string.into()], "call").unwrap()
/// .try_as_basic_value()
/// .left()
/// .unwrap();
///
/// builder.build_return(Some(&ret_val)).unwrap();
/// ```
#[llvm_versions(15.0..=latest)]
pub fn build_direct_call(
&self,
function: FunctionValue<'ctx>,
args: &[BasicMetadataValueEnum<'ctx>],
name: &str,
) -> Result<CallSiteValue<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
self.build_call_help(function.get_type(), function.as_value_ref(), args, name)
}
/// Call a function pointer. Because a pointer does not carry a type, the type of the function
/// must be specified explicitly.
///
/// See [Context::create_inline_asm] for a practical example. Basic usage looks like this:
///
/// ```no_run
/// use inkwell::context::Context;
///
/// // A simple function which calls itself:
/// let context = Context::create();
/// let module = context.create_module("ret");
/// let builder = context.create_builder();
/// let i32_type = context.i32_type();
/// let fn_type = i32_type.fn_type(&[i32_type.into()], false);
/// let fn_value = module.add_function("ret", fn_type, None);
/// let entry = context.append_basic_block(fn_value, "entry");
/// let i32_arg = fn_value.get_first_param().unwrap();
/// let md_string = context.metadata_string("a metadata");
///
/// builder.position_at_end(entry);
///
/// let function_pointer = fn_value.as_global_value().as_pointer_value();
/// let ret_val = builder.build_indirect_call(fn_value.get_type(), function_pointer, &[i32_arg.into(), md_string.into()], "call").unwrap()
/// .try_as_basic_value()
/// .left()
/// .unwrap();
///
/// builder.build_return(Some(&ret_val)).unwrap();
/// ```
///
#[llvm_versions(15.0..=latest)]
pub fn build_indirect_call(
&self,
function_type: FunctionType<'ctx>,
function_pointer: PointerValue<'ctx>,
args: &[BasicMetadataValueEnum<'ctx>],
name: &str,
) -> Result<CallSiteValue<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
self.build_call_help(function_type, function_pointer.as_value_ref(), args, name)
}
#[llvm_versions(15.0..=latest)]
fn build_call_help(
&self,
function_type: FunctionType<'ctx>,
fn_val_ref: LLVMValueRef,
args: &[BasicMetadataValueEnum<'ctx>],
name: &str,
) -> Result<CallSiteValue<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
// LLVM gets upset when void return calls are named because they don't return anything
let name = match function_type.get_return_type() {
None => "",
Some(_) => name,
};
let fn_ty_ref = function_type.as_type_ref();
let c_string = to_c_str(name);
let mut args: Vec<LLVMValueRef> = args.iter().map(|val| val.as_value_ref()).collect();
let value = unsafe {
LLVMBuildCall2(
self.builder,
fn_ty_ref,
fn_val_ref,
args.as_mut_ptr(),
args.len() as u32,
c_string.as_ptr(),
)
};
unsafe { Ok(CallSiteValue::new(value)) }
}
/// An invoke is similar to a normal function call, but used to
/// call functions that may throw an exception, and then respond to the exception.
///
/// When the called function returns normally, the `then` block is evaluated next. If instead
/// the function threw an exception, the `catch` block is entered. The first non-phi
/// instruction of the catch block must be a `landingpad` instruction. See also
/// [`Builder::build_landing_pad`].
///
/// The [`add_prune_eh_pass`] turns an invoke into a call when the called function is
/// guaranteed to never throw an exception.
///
/// [`add_prune_eh_pass`]: crate::passes::PassManager::add_prune_eh_pass
///
/// This example catches C++ exceptions of type `int`, and returns `0` if an exceptions is thrown.
/// For usage of a cleanup landing pad and the `resume` instruction, see [`Builder::build_resume`]
/// ```no_run
/// use inkwell::context::Context;
/// use inkwell::AddressSpace;
/// use inkwell::module::Linkage;
///
/// let context = Context::create();
/// let module = context.create_module("sum");
/// let builder = context.create_builder();
///
/// let f32_type = context.f32_type();
/// let fn_type = f32_type.fn_type(&[], false);
///
/// // we will pretend this function can throw an exception
/// let function = module.add_function("bomb", fn_type, None);
/// let basic_block = context.append_basic_block(function, "entry");
///
/// builder.position_at_end(basic_block);
///
/// let pi = f32_type.const_float(::std::f64::consts::PI);
///
/// builder.build_return(Some(&pi)).unwrap();
///
/// let function2 = module.add_function("wrapper", fn_type, None);
/// let basic_block2 = context.append_basic_block(function2, "entry");
///
/// builder.position_at_end(basic_block2);
///
/// let then_block = context.append_basic_block(function2, "then_block");
/// let catch_block = context.append_basic_block(function2, "catch_block");
///
/// let call_site = builder.build_invoke(function, &[], then_block, catch_block, "get_pi").unwrap();
///
/// {
/// builder.position_at_end(then_block);
///
/// // in the then_block, the `call_site` value is defined and can be used
/// let result = call_site.try_as_basic_value().left().unwrap();
///
/// builder.build_return(Some(&result)).unwrap();
/// }
///
/// {
/// builder.position_at_end(catch_block);
///
/// // the personality function used by C++
/// let personality_function = {
/// let name = "__gxx_personality_v0";
/// let linkage = Some(Linkage::External);
///
/// module.add_function(name, context.i64_type().fn_type(&[], false), linkage)
/// };
///
/// // type of an exception in C++
/// #[cfg(not(any(feature = "llvm15-0", feature = "llvm16-0", feature = "llvm17-0", feature = "llvm18-0")))]
/// let i8_ptr_type = context.i32_type().ptr_type(AddressSpace::default());
/// #[cfg(any(feature = "llvm15-0", feature = "llvm16-0", feature = "llvm17-0", feature = "llvm18-0"))]
/// let i32_ptr_ty = context.ptr_type(AddressSpace::default());
/// let i32_type = context.i32_type();
/// let exception_type = context.struct_type(&[i8_ptr_type.into(), i32_type.into()], false);
///
/// let null = i8_ptr_type.const_zero();
/// let res = builder.build_landing_pad(exception_type, personality_function, &[null.into()], false, "res").unwrap();
///
/// // we handle the exception by returning a default value
/// builder.build_return(Some(&f32_type.const_zero())).unwrap();
/// }
/// ```
#[llvm_versions(4.0..=14.0)]
pub fn build_invoke<F>(
&self,
function: F,
args: &[BasicValueEnum<'ctx>],
then_block: BasicBlock<'ctx>,
catch_block: BasicBlock<'ctx>,
name: &str,
) -> Result<CallSiteValue<'ctx>, BuilderError>
where
F: Into<CallableValue<'ctx>>,
{
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let callable_value: CallableValue<'ctx> = function.into();
let fn_val_ref = callable_value.as_value_ref();
// LLVM gets upset when void return calls are named because they don't return anything
let name = if callable_value.returns_void() { "" } else { name };
let c_string = to_c_str(name);
let mut args: Vec<LLVMValueRef> = args.iter().map(|val| val.as_value_ref()).collect();
let value = unsafe {
LLVMBuildInvoke(
self.builder,
fn_val_ref,
args.as_mut_ptr(),
args.len() as u32,
then_block.basic_block,
catch_block.basic_block,
c_string.as_ptr(),
)
};
Ok(unsafe { CallSiteValue::new(value) })
}
/// An invoke is similar to a normal function call, but used to
/// call functions that may throw an exception, and then respond to the exception.
///
/// When the called function returns normally, the `then` block is evaluated next. If instead
/// the function threw an exception, the `catch` block is entered. The first non-phi
/// instruction of the catch block must be a `landingpad` instruction. See also
/// [`Builder::build_landing_pad`].
///
/// The [`add_prune_eh_pass`] turns an invoke into a call when the called function is
/// guaranteed to never throw an exception.
///
/// [`add_prune_eh_pass`]: crate::passes::PassManager::add_prune_eh_pass
///
/// This example catches C++ exceptions of type `int`, and returns `0` if an exceptions is thrown.
/// For usage of a cleanup landing pad and the `resume` instruction, see [`Builder::build_resume`]
/// ```no_run
/// use inkwell::context::Context;
/// use inkwell::AddressSpace;
/// use inkwell::module::Linkage;
///
/// let context = Context::create();
/// let module = context.create_module("sum");
/// let builder = context.create_builder();
///
/// let f32_type = context.f32_type();
/// let fn_type = f32_type.fn_type(&[], false);
///
/// // we will pretend this function can throw an exception
/// let function = module.add_function("bomb", fn_type, None);
/// let basic_block = context.append_basic_block(function, "entry");
///
/// builder.position_at_end(basic_block);
///
/// let pi = f32_type.const_float(::std::f64::consts::PI);
///
/// builder.build_return(Some(&pi)).unwrap();
///
/// let function2 = module.add_function("wrapper", fn_type, None);
/// let basic_block2 = context.append_basic_block(function2, "entry");
///
/// builder.position_at_end(basic_block2);
///
/// let then_block = context.append_basic_block(function2, "then_block");
/// let catch_block = context.append_basic_block(function2, "catch_block");
///
/// let call_site = builder.build_invoke(function, &[], then_block, catch_block, "get_pi").unwrap();
///
/// {
/// builder.position_at_end(then_block);
///
/// // in the then_block, the `call_site` value is defined and can be used
/// let result = call_site.try_as_basic_value().left().unwrap();
///
/// builder.build_return(Some(&result)).unwrap();
/// }
///
/// {
/// builder.position_at_end(catch_block);
///
/// // the personality function used by C++
/// let personality_function = {
/// let name = "__gxx_personality_v0";
/// let linkage = Some(Linkage::External);
///
/// module.add_function(name, context.i64_type().fn_type(&[], false), linkage)
/// };
///
/// // type of an exception in C++
/// let ptr_type = context.ptr_type(AddressSpace::default());
/// let i32_type = context.i32_type();
/// let exception_type = context.struct_type(&[ptr_type.into(), i32_type.into()], false);
///
/// let null = ptr_type.const_zero();
/// let res = builder.build_landing_pad(exception_type, personality_function, &[null.into()], false, "res").unwrap();
///
/// // we handle the exception by returning a default value
/// builder.build_return(Some(&f32_type.const_zero())).unwrap();
/// }
/// ```
#[llvm_versions(15.0..=latest)]
pub fn build_invoke(
&self,
function: FunctionValue<'ctx>,
args: &[BasicValueEnum<'ctx>],
then_block: BasicBlock<'ctx>,
catch_block: BasicBlock<'ctx>,
name: &str,
) -> Result<CallSiteValue<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
self.build_direct_invoke(function, args, then_block, catch_block, name)
}
#[llvm_versions(15.0..=latest)]
pub fn build_direct_invoke(
&self,
function: FunctionValue<'ctx>,
args: &[BasicValueEnum<'ctx>],
then_block: BasicBlock<'ctx>,
catch_block: BasicBlock<'ctx>,
name: &str,
) -> Result<CallSiteValue<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
self.build_invoke_help(
function.get_type(),
function.as_value_ref(),
args,
then_block,
catch_block,
name,
)
}
#[llvm_versions(15.0..=latest)]
pub fn build_indirect_invoke(
&self,
function_type: FunctionType<'ctx>,
function_pointer: PointerValue<'ctx>,
args: &[BasicValueEnum<'ctx>],
then_block: BasicBlock<'ctx>,
catch_block: BasicBlock<'ctx>,
name: &str,
) -> Result<CallSiteValue<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
self.build_invoke_help(
function_type,
function_pointer.as_value_ref(),
args,
then_block,
catch_block,
name,
)
}
#[llvm_versions(15.0..=latest)]
fn build_invoke_help(
&self,
fn_ty: FunctionType<'ctx>,
fn_val_ref: LLVMValueRef,
args: &[BasicValueEnum<'ctx>],
then_block: BasicBlock<'ctx>,
catch_block: BasicBlock<'ctx>,
name: &str,
) -> Result<CallSiteValue<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let fn_ty_ref = fn_ty.as_type_ref();
// LLVM gets upset when void return calls are named because they don't return anything
let name = if fn_ty.get_return_type().is_none() { "" } else { name };
let c_string = to_c_str(name);
let mut args: Vec<LLVMValueRef> = args.iter().map(|val| val.as_value_ref()).collect();
let value = unsafe {
LLVMBuildInvoke2(
self.builder,
fn_ty_ref,
fn_val_ref,
args.as_mut_ptr(),
args.len() as u32,
then_block.basic_block,
catch_block.basic_block,
c_string.as_ptr(),
)
};
unsafe { Ok(CallSiteValue::new(value)) }
}
/// Landing pads are places where control flow jumps to if a [`Builder::build_invoke`] triggered an exception.
/// The landing pad will match the exception against its *clauses*. Depending on the clause
/// that is matched, the exception can then be handled, or resumed after some optional cleanup,
/// causing the exception to bubble up.
///
/// Exceptions in LLVM are designed based on the needs of a C++ compiler, but can be used more generally.
/// Here are some specific examples of landing pads. For a full example of handling an exception, see [`Builder::build_invoke`].
///
/// * **cleanup**: a cleanup landing pad is always visited when unwinding the stack.
/// A cleanup is extra code that needs to be run when unwinding a scope. C++ destructors are a typical example.
/// In a language with reference counting, the cleanup block can decrement the refcount of values in scope.
/// The [`Builder::build_resume`] function has a full example using a cleanup lading pad.
///
/// ```no_run
/// use inkwell::context::Context;
/// use inkwell::AddressSpace;
/// use inkwell::module::Linkage;
///
/// let context = Context::create();
/// let module = context.create_module("sum");
/// let builder = context.create_builder();
///
/// // type of an exception in C++
/// #[cfg(not(any(feature = "llvm15-0", feature = "llvm16-0", feature = "llvm17-0", feature = "llvm18-0")))]
/// let i8_ptr_type = context.i8_type().ptr_type(AddressSpace::default());
/// #[cfg(any(feature = "llvm15-0", feature = "llvm16-0", feature = "llvm17-0", feature = "llvm18-0"))]
/// let i8_ptr_type = context.ptr_type(AddressSpace::default());
/// let i32_type = context.i32_type();
/// let exception_type = context.struct_type(&[i8_ptr_type.into(), i32_type.into()], false);
///
/// // the personality function used by C++
/// let personality_function = {
/// let name = "__gxx_personality_v0";
/// let linkage = Some(Linkage::External);
///
/// module.add_function(name, context.i64_type().fn_type(&[], false), linkage)
/// };
///
/// // make the cleanup landing pad
/// let res = builder.build_landing_pad( exception_type, personality_function, &[], true, "res").unwrap();
/// ```
///
/// * **catch all**: An implementation of the C++ `catch(...)`, which catches all exceptions.
/// A catch clause with a NULL pointer value will match anything.
///
/// ```no_run
/// use inkwell::context::Context;
/// use inkwell::AddressSpace;
/// use inkwell::module::Linkage;
///
/// let context = Context::create();
/// let module = context.create_module("sum");
/// let builder = context.create_builder();
///
/// // type of an exception in C++
/// #[cfg(not(any(feature = "llvm15-0", feature = "llvm16-0", feature = "llvm17-0", feature = "llvm18-0")))]
/// let i8_ptr_type = context.i8_type().ptr_type(AddressSpace::default());
/// #[cfg(any(feature = "llvm15-0", feature = "llvm16-0", feature = "llvm17-0", feature = "llvm18-0"))]
/// let i8_ptr_type = context.ptr_type(AddressSpace::default());
/// let i32_type = context.i32_type();
/// let exception_type = context.struct_type(&[i8_ptr_type.into(), i32_type.into()], false);
///
/// // the personality function used by C++
/// let personality_function = {
/// let name = "__gxx_personality_v0";
/// let linkage = Some(Linkage::External);
///
/// module.add_function(name, context.i64_type().fn_type(&[], false), linkage)
/// };
///
/// // make a null pointer of type i8
/// let null = i8_ptr_type.const_zero();
///
/// // make the catch all landing pad
/// let res = builder.build_landing_pad(exception_type, personality_function, &[null.into()], false, "res").unwrap();
/// ```
///
/// * **catch a type of exception**: Catch a specific type of exception. The example uses C++'s type info.
///
/// ```no_run
/// use inkwell::context::Context;
/// use inkwell::module::Linkage;
/// use inkwell::AddressSpace;
/// use inkwell::values::BasicValue;
///
/// let context = Context::create();
/// let module = context.create_module("sum");
/// let builder = context.create_builder();
///
/// // type of an exception in C++
/// #[cfg(not(any(feature = "llvm15-0", feature = "llvm16-0", feature = "llvm17-0", feature = "llvm18-0")))]
/// let i8_ptr_type = context.i8_type().ptr_type(AddressSpace::default());
/// #[cfg(any(feature = "llvm15-0", feature = "llvm16-0", feature = "llvm17-0", feature = "llvm18-0"))]
/// let i8_ptr_type = context.ptr_type(AddressSpace::default());
/// let i32_type = context.i32_type();
/// let exception_type = context.struct_type(&[i8_ptr_type.into(), i32_type.into()], false);
///
/// // the personality function used by C++
/// let personality_function = {
/// let name = "__gxx_personality_v0";
/// let linkage = Some(Linkage::External);
///
/// module.add_function(name, context.i64_type().fn_type(&[], false), linkage)
/// };
///
/// // link in the C++ type info for the `int` type
/// let type_info_int = module.add_global(i8_ptr_type, Some(AddressSpace::default()), "_ZTIi");
/// type_info_int.set_linkage(Linkage::External);
///
/// // make the catch landing pad
/// let clause = type_info_int.as_basic_value_enum();
/// let res = builder.build_landing_pad(exception_type, personality_function, &[clause], false, "res").unwrap();
/// ```
///
/// * **filter**: A filter clause encodes that only some types of exceptions are valid at this
/// point. A filter clause is made by constructing a clause from a constant array.
///
/// ```no_run
/// use inkwell::context::Context;
/// use inkwell::module::Linkage;
/// use inkwell::values::AnyValue;
/// use inkwell::AddressSpace;
///
/// let context = Context::create();
/// let module = context.create_module("sum");
/// let builder = context.create_builder();
///
/// // type of an exception in C++
/// #[cfg(not(any(feature = "llvm15-0", feature = "llvm16-0", feature = "llvm17-0", feature = "llvm18-0")))]
/// let i8_ptr_type = context.i8_type().ptr_type(AddressSpace::default());
/// #[cfg(any(feature = "llvm15-0", feature = "llvm16-0", feature = "llvm17-0", feature = "llvm18-0"))]
/// let i8_ptr_type = context.ptr_type(AddressSpace::default());
/// let i32_type = context.i32_type();
/// let exception_type = context.struct_type(&[i8_ptr_type.into(), i32_type.into()], false);
///
/// // the personality function used by C++
/// let personality_function = {
/// let name = "__gxx_personality_v0";
/// let linkage = Some(Linkage::External);
///
/// module.add_function(name, context.i64_type().fn_type(&[], false), linkage)
/// };
///
/// // link in the C++ type info for the `int` type
/// let type_info_int = module.add_global(i8_ptr_type, Some(AddressSpace::default()), "_ZTIi");
/// type_info_int.set_linkage(Linkage::External);
///
/// // make the filter landing pad
/// let filter_pattern = i8_ptr_type.const_array(&[type_info_int.as_any_value_enum().into_pointer_value()]);
/// let res = builder.build_landing_pad(exception_type, personality_function, &[filter_pattern.into()], false, "res").unwrap();
/// ```
pub fn build_landing_pad<T>(
&self,
exception_type: T,
personality_function: FunctionValue<'ctx>,
clauses: &[BasicValueEnum<'ctx>],
is_cleanup: bool,
name: &str,
) -> Result<BasicValueEnum<'ctx>, BuilderError>
where
T: BasicType<'ctx>,
{
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let num_clauses = clauses.len() as u32;
let value = unsafe {
LLVMBuildLandingPad(
self.builder,
exception_type.as_type_ref(),
personality_function.as_value_ref(),
num_clauses,
c_string.as_ptr(),
)
};
for clause in clauses {
unsafe {
LLVMAddClause(value, clause.as_value_ref());
}
}
unsafe {
LLVMSetCleanup(value, is_cleanup as _);
};
unsafe { Ok(BasicValueEnum::new(value)) }
}
/// Resume propagation of an existing (in-flight) exception whose unwinding was interrupted with a landingpad instruction.
///
/// This example uses a cleanup landing pad. A cleanup is extra code that needs to be run when
/// unwinding a scope. C++ destructors are a typical example. In a language with reference counting,
/// the cleanup block can decrement the refcount of values in scope.
///
/// ```no_run
/// use inkwell::context::Context;
/// use inkwell::AddressSpace;
/// use inkwell::module::Linkage;
///
/// let context = Context::create();
/// let module = context.create_module("sum");
/// let builder = context.create_builder();
///
/// let f32_type = context.f32_type();
/// let fn_type = f32_type.fn_type(&[], false);
///
/// // we will pretend this function can throw an exception
/// let function = module.add_function("bomb", fn_type, None);
/// let basic_block = context.append_basic_block(function, "entry");
///
/// builder.position_at_end(basic_block);
///
/// let pi = f32_type.const_float(::std::f64::consts::PI);
///
/// builder.build_return(Some(&pi)).unwrap();
///
/// let function2 = module.add_function("wrapper", fn_type, None);
/// let basic_block2 = context.append_basic_block(function2, "entry");
///
/// builder.position_at_end(basic_block2);
///
/// let then_block = context.append_basic_block(function2, "then_block");
/// let catch_block = context.append_basic_block(function2, "catch_block");
///
/// let call_site = builder.build_invoke(function, &[], then_block, catch_block, "get_pi").unwrap();
///
/// {
/// builder.position_at_end(then_block);
///
/// // in the then_block, the `call_site` value is defined and can be used
/// let result = call_site.try_as_basic_value().left().unwrap();
///
/// builder.build_return(Some(&result)).unwrap();
/// }
///
/// {
/// builder.position_at_end(catch_block);
///
/// // the personality function used by C++
/// let personality_function = {
/// let name = "__gxx_personality_v0";
/// let linkage = Some(Linkage::External);
///
/// module.add_function(name, context.i64_type().fn_type(&[], false), linkage)
/// };
///
/// // type of an exception in C++
/// #[cfg(not(any(feature = "llvm15-0", feature = "llvm16-0", feature = "llvm17-0", feature = "llvm18-0")))]
/// let i8_ptr_type = context.i8_type().ptr_type(AddressSpace::default());
/// #[cfg(any(feature = "llvm15-0", feature = "llvm16-0", feature = "llvm17-0", feature = "llvm18-0"))]
/// let i8_ptr_type = context.ptr_type(AddressSpace::default());
/// let i32_type = context.i32_type();
/// let exception_type = context.struct_type(&[i8_ptr_type.into(), i32_type.into()], false);
///
/// // make the landing pad; must give a concrete type to the slice
/// let res = builder.build_landing_pad( exception_type, personality_function, &[], true, "res").unwrap();
///
/// // do cleanup ...
///
/// builder.build_resume(res).unwrap();
/// }
/// ```
pub fn build_resume<V: BasicValue<'ctx>>(&self, value: V) -> Result<InstructionValue<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let val = unsafe { LLVMBuildResume(self.builder, value.as_value_ref()) };
unsafe { Ok(InstructionValue::new(val)) }
}
// REVIEW: Doesn't GEP work on array too?
/// GEP is very likely to segfault if indexes are used incorrectly, and is therefore an unsafe function. Maybe we can change this in the future.
#[llvm_versions(4.0..=14.0)]
pub unsafe fn build_gep(
&self,
ptr: PointerValue<'ctx>,
ordered_indexes: &[IntValue<'ctx>],
name: &str,
) -> Result<PointerValue<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let mut index_values: Vec<LLVMValueRef> = ordered_indexes.iter().map(|val| val.as_value_ref()).collect();
let value = LLVMBuildGEP(
self.builder,
ptr.as_value_ref(),
index_values.as_mut_ptr(),
index_values.len() as u32,
c_string.as_ptr(),
);
Ok(PointerValue::new(value))
}
// REVIEW: Doesn't GEP work on array too?
/// GEP is very likely to segfault if indexes are used incorrectly, and is therefore an unsafe function. Maybe we can change this in the future.
#[llvm_versions(15.0..=latest)]
pub unsafe fn build_gep<T: BasicType<'ctx>>(
&self,
pointee_ty: T,
ptr: PointerValue<'ctx>,
ordered_indexes: &[IntValue<'ctx>],
name: &str,
) -> Result<PointerValue<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let mut index_values: Vec<LLVMValueRef> = ordered_indexes.iter().map(|val| val.as_value_ref()).collect();
let value = LLVMBuildGEP2(
self.builder,
pointee_ty.as_type_ref(),
ptr.as_value_ref(),
index_values.as_mut_ptr(),
index_values.len() as u32,
c_string.as_ptr(),
);
Ok(PointerValue::new(value))
}
// REVIEW: Doesn't GEP work on array too?
// REVIEW: This could be merge in with build_gep via a in_bounds: bool param
/// GEP is very likely to segfault if indexes are used incorrectly, and is therefore an unsafe function. Maybe we can change this in the future.
#[llvm_versions(4.0..=14.0)]
pub unsafe fn build_in_bounds_gep(
&self,
ptr: PointerValue<'ctx>,
ordered_indexes: &[IntValue<'ctx>],
name: &str,
) -> Result<PointerValue<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let mut index_values: Vec<LLVMValueRef> = ordered_indexes.iter().map(|val| val.as_value_ref()).collect();
let value = LLVMBuildInBoundsGEP(
self.builder,
ptr.as_value_ref(),
index_values.as_mut_ptr(),
index_values.len() as u32,
c_string.as_ptr(),
);
Ok(PointerValue::new(value))
}
// REVIEW: Doesn't GEP work on array too?
// REVIEW: This could be merge in with build_gep via a in_bounds: bool param
/// GEP is very likely to segfault if indexes are used incorrectly, and is therefore an unsafe function. Maybe we can change this in the future.
#[llvm_versions(15.0..=latest)]
pub unsafe fn build_in_bounds_gep<T: BasicType<'ctx>>(
&self,
pointee_ty: T,
ptr: PointerValue<'ctx>,
ordered_indexes: &[IntValue<'ctx>],
name: &str,
) -> Result<PointerValue<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let mut index_values: Vec<LLVMValueRef> = ordered_indexes.iter().map(|val| val.as_value_ref()).collect();
let value = LLVMBuildInBoundsGEP2(
self.builder,
pointee_ty.as_type_ref(),
ptr.as_value_ref(),
index_values.as_mut_ptr(),
index_values.len() as u32,
c_string.as_ptr(),
);
Ok(PointerValue::new(value))
}
/// Builds a GEP instruction on a struct pointer. Returns `Err(BuilderError::GEPError)` if input `PointerValue` doesn't
/// point to a struct or if index is out of bounds.
///
/// # Example
///
/// ```no_run
/// use inkwell::AddressSpace;
/// use inkwell::context::Context;
///
/// let context = Context::create();
/// let builder = context.create_builder();
/// let module = context.create_module("struct_gep");
/// let void_type = context.void_type();
/// let i32_ty = context.i32_type();
/// #[cfg(not(any(feature = "llvm15-0", feature = "llvm16-0", feature = "llvm17-0", feature = "llvm18-0")))]
/// let i32_ptr_ty = i32_ty.ptr_type(AddressSpace::default());
/// #[cfg(any(feature = "llvm15-0", feature = "llvm16-0", feature = "llvm17-0", feature = "llvm18-0"))]
/// let i32_ptr_ty = context.ptr_type(AddressSpace::default());
/// let field_types = &[i32_ty.into(), i32_ty.into()];
/// let struct_ty = context.struct_type(field_types, false);
/// let struct_ptr_ty = struct_ty.ptr_type(AddressSpace::default());
/// let fn_type = void_type.fn_type(&[i32_ptr_ty.into(), struct_ptr_ty.into()], false);
/// let fn_value = module.add_function("", fn_type, None);
/// let entry = context.append_basic_block(fn_value, "entry");
///
/// builder.position_at_end(entry);
///
/// let i32_ptr = fn_value.get_first_param().unwrap().into_pointer_value();
/// let struct_ptr = fn_value.get_last_param().unwrap().into_pointer_value();
///
/// assert!(builder.build_struct_gep(i32_ptr, 0, "struct_gep").is_err());
/// assert!(builder.build_struct_gep(i32_ptr, 10, "struct_gep").is_err());
/// assert!(builder.build_struct_gep(struct_ptr, 0, "struct_gep").is_ok());
/// assert!(builder.build_struct_gep(struct_ptr, 1, "struct_gep").is_ok());
/// assert!(builder.build_struct_gep(struct_ptr, 2, "struct_gep").is_err());
/// ```
#[llvm_versions(4.0..=14.0)]
pub fn build_struct_gep(
&self,
ptr: PointerValue<'ctx>,
index: u32,
name: &str,
) -> Result<PointerValue<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let ptr_ty = ptr.get_type();
let pointee_ty = ptr_ty.get_element_type();
if !pointee_ty.is_struct_type() {
return Err(BuilderError::GEPPointee);
}
let struct_ty = pointee_ty.into_struct_type();
if index >= struct_ty.count_fields() {
return Err(BuilderError::GEPIndex);
}
let c_string = to_c_str(name);
let value = unsafe { LLVMBuildStructGEP(self.builder, ptr.as_value_ref(), index, c_string.as_ptr()) };
unsafe { Ok(PointerValue::new(value)) }
}
/// Builds a GEP instruction on a struct pointer. Returns `Err` `BuilderError::GEPPointee` or `BuilderError::GEPIndex` if input `PointerValue` doesn't
/// point to a struct or if index is out of bounds.
///
/// # Example
///
/// ```no_run
/// use inkwell::AddressSpace;
/// use inkwell::context::Context;
///
/// let context = Context::create();
/// let builder = context.create_builder();
/// let module = context.create_module("struct_gep");
/// let void_type = context.void_type();
/// let i32_ty = context.i32_type();
/// #[cfg(not(any(feature = "llvm15-0", feature = "llvm16-0", feature = "llvm17-0", feature = "llvm18-0")))]
/// let i32_ptr_ty = i32_ty.ptr_type(AddressSpace::default());
/// #[cfg(any(feature = "llvm15-0", feature = "llvm16-0", feature = "llvm17-0", feature = "llvm18-0"))]
/// let i32_ptr_ty = context.ptr_type(AddressSpace::default());
/// let field_types = &[i32_ty.into(), i32_ty.into()];
/// let struct_ty = context.struct_type(field_types, false);
/// let struct_ptr_ty = struct_ty.ptr_type(AddressSpace::default());
/// let fn_type = void_type.fn_type(&[i32_ptr_ty.into(), struct_ptr_ty.into()], false);
/// let fn_value = module.add_function("", fn_type, None);
/// let entry = context.append_basic_block(fn_value, "entry");
///
/// builder.position_at_end(entry);
///
/// let i32_ptr = fn_value.get_first_param().unwrap().into_pointer_value();
/// let struct_ptr = fn_value.get_last_param().unwrap().into_pointer_value();
///
/// assert!(builder.build_struct_gep(i32_ty, i32_ptr, 0, "struct_gep").is_err());
/// assert!(builder.build_struct_gep(i32_ty, i32_ptr, 10, "struct_gep").is_err());
/// assert!(builder.build_struct_gep(struct_ty, struct_ptr, 0, "struct_gep").is_ok());
/// assert!(builder.build_struct_gep(struct_ty, struct_ptr, 1, "struct_gep").is_ok());
/// assert!(builder.build_struct_gep(struct_ty, struct_ptr, 2, "struct_gep").is_err());
/// ```
#[llvm_versions(15.0..=latest)]
pub fn build_struct_gep<T: BasicType<'ctx>>(
&self,
pointee_ty: T,
ptr: PointerValue<'ctx>,
index: u32,
name: &str,
) -> Result<PointerValue<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let pointee_ty = pointee_ty.as_any_type_enum();
if !pointee_ty.is_struct_type() {
return Err(BuilderError::GEPPointee);
}
let struct_ty = pointee_ty.into_struct_type();
if index >= struct_ty.count_fields() {
return Err(BuilderError::GEPIndex);
}
let c_string = to_c_str(name);
let value = unsafe {
LLVMBuildStructGEP2(
self.builder,
pointee_ty.as_type_ref(),
ptr.as_value_ref(),
index,
c_string.as_ptr(),
)
};
unsafe { Ok(PointerValue::new(value)) }
}
/// Builds an instruction which calculates the difference of two pointers.
///
/// # Example
///
/// ```no_run
/// use inkwell::context::Context;
/// use inkwell::AddressSpace;
///
/// // Builds a function which diffs two pointers
/// let context = Context::create();
/// let module = context.create_module("ret");
/// let builder = context.create_builder();
/// let void_type = context.void_type();
/// let i32_type = context.i32_type();
/// #[cfg(not(any(feature = "llvm15-0", feature = "llvm16-0", feature = "llvm17-0", feature = "llvm18-0")))]
/// let i32_ptr_type = i32_type.ptr_type(AddressSpace::default());
/// #[cfg(any(feature = "llvm15-0", feature = "llvm16-0", feature = "llvm17-0", feature = "llvm18-0"))]
/// let i32_ptr_type = context.ptr_type(AddressSpace::default());
/// let fn_type = void_type.fn_type(&[i32_ptr_type.into(), i32_ptr_type.into()], false);
/// let fn_value = module.add_function("ret", fn_type, None);
/// let entry = context.append_basic_block(fn_value, "entry");
/// let i32_ptr_param1 = fn_value.get_first_param().unwrap().into_pointer_value();
/// let i32_ptr_param2 = fn_value.get_nth_param(1).unwrap().into_pointer_value();
///
/// builder.position_at_end(entry);
/// builder.build_ptr_diff(i32_ptr_param1, i32_ptr_param2, "diff").unwrap();
/// builder.build_return(None).unwrap();
/// ```
#[llvm_versions(4.0..=14.0)]
pub fn build_ptr_diff(
&self,
lhs_ptr: PointerValue<'ctx>,
rhs_ptr: PointerValue<'ctx>,
name: &str,
) -> Result<IntValue<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe {
LLVMBuildPtrDiff(
self.builder,
lhs_ptr.as_value_ref(),
rhs_ptr.as_value_ref(),
c_string.as_ptr(),
)
};
unsafe { Ok(IntValue::new(value)) }
}
/// Builds an instruction which calculates the difference of two pointers.
///
/// # Example
///
/// ```no_run
/// use inkwell::context::Context;
/// use inkwell::AddressSpace;
///
/// // Builds a function which diffs two pointers
/// let context = Context::create();
/// let module = context.create_module("ret");
/// let builder = context.create_builder();
/// let void_type = context.void_type();
/// let i32_type = context.i32_type();
/// #[cfg(not(any(feature = "llvm15-0", feature = "llvm16-0", feature = "llvm17-0", feature = "llvm18-0")))]
/// let i32_ptr_type = i32_type.ptr_type(AddressSpace::default());
/// #[cfg(any(feature = "llvm15-0", feature = "llvm16-0", feature = "llvm17-0", feature = "llvm18-0"))]
/// let i32_ptr_type = context.ptr_type(AddressSpace::default());
/// let fn_type = void_type.fn_type(&[i32_ptr_type.into(), i32_ptr_type.into()], false);
/// let fn_value = module.add_function("ret", fn_type, None);
/// let entry = context.append_basic_block(fn_value, "entry");
/// let i32_ptr_param1 = fn_value.get_first_param().unwrap().into_pointer_value();
/// let i32_ptr_param2 = fn_value.get_nth_param(1).unwrap().into_pointer_value();
///
/// builder.position_at_end(entry);
/// builder.build_ptr_diff(i32_ptr_type, i32_ptr_param1, i32_ptr_param2, "diff").unwrap();
/// builder.build_return(None).unwrap();
/// ```
#[llvm_versions(15.0..=latest)]
pub fn build_ptr_diff<T: BasicType<'ctx>>(
&self,
pointee_ty: T,
lhs_ptr: PointerValue<'ctx>,
rhs_ptr: PointerValue<'ctx>,
name: &str,
) -> Result<IntValue<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe {
LLVMBuildPtrDiff2(
self.builder,
pointee_ty.as_type_ref(),
lhs_ptr.as_value_ref(),
rhs_ptr.as_value_ref(),
c_string.as_ptr(),
)
};
unsafe { Ok(IntValue::new(value)) }
}
// SubTypes: Maybe this should return PhiValue<T>? That way we could force incoming values to be of T::Value?
// That is, assuming LLVM complains about different phi types.. which I imagine it would. But this would get
// tricky with VoidType since it has no instance value?
// TODOC: Phi Instruction(s) must be first instruction(s) in a BasicBlock.
// REVIEW: Not sure if we can enforce the above somehow via types.
pub fn build_phi<T: BasicType<'ctx>>(&self, type_: T, name: &str) -> Result<PhiValue<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe { LLVMBuildPhi(self.builder, type_.as_type_ref(), c_string.as_ptr()) };
unsafe { Ok(PhiValue::new(value)) }
}
/// Builds a store instruction. It allows you to store a value of type `T` in a pointer to a type `T`.
///
/// # Example
///
/// ```no_run
/// use inkwell::context::Context;
/// use inkwell::AddressSpace;
///
/// // Builds a function which takes an i32 pointer and stores a 7 in it.
/// let context = Context::create();
/// let module = context.create_module("ret");
/// let builder = context.create_builder();
/// let void_type = context.void_type();
/// let i32_type = context.i32_type();
/// #[cfg(not(any(feature = "llvm15-0", feature = "llvm16-0", feature = "llvm17-0", feature = "llvm18-0")))]
/// let i32_ptr_type = i32_type.ptr_type(AddressSpace::default());
/// #[cfg(any(feature = "llvm15-0", feature = "llvm16-0", feature = "llvm17-0", feature = "llvm18-0"))]
/// let i32_ptr_type = context.ptr_type(AddressSpace::default());
/// let i32_seven = i32_type.const_int(7, false);
/// let fn_type = void_type.fn_type(&[i32_ptr_type.into()], false);
/// let fn_value = module.add_function("ret", fn_type, None);
/// let entry = context.append_basic_block(fn_value, "entry");
/// let i32_ptr_param = fn_value.get_first_param().unwrap().into_pointer_value();
///
/// builder.position_at_end(entry);
/// builder.build_store(i32_ptr_param, i32_seven).unwrap();
/// builder.build_return(None).unwrap();
/// ```
pub fn build_store<V: BasicValue<'ctx>>(
&self,
ptr: PointerValue<'ctx>,
value: V,
) -> Result<InstructionValue<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let value = unsafe { LLVMBuildStore(self.builder, value.as_value_ref(), ptr.as_value_ref()) };
unsafe { Ok(InstructionValue::new(value)) }
}
/// Builds a load instruction. It allows you to retrieve a value of type `T` from a pointer to a type `T`.
///
/// # Example
///
/// ```no_run
/// use inkwell::context::Context;
/// use inkwell::AddressSpace;
///
/// // Builds a function which takes an i32 pointer and returns the pointed at i32.
/// let context = Context::create();
/// let module = context.create_module("ret");
/// let builder = context.create_builder();
/// let i32_type = context.i32_type();
/// #[cfg(not(any(feature = "llvm15-0", feature = "llvm16-0", feature = "llvm17-0", feature = "llvm18-0")))]
/// let i32_ptr_type = i32_type.ptr_type(AddressSpace::default());
/// #[cfg(any(feature = "llvm15-0", feature = "llvm16-0", feature = "llvm17-0", feature = "llvm18-0"))]
/// let i32_ptr_type = context.ptr_type(AddressSpace::default());
/// let fn_type = i32_type.fn_type(&[i32_ptr_type.into()], false);
/// let fn_value = module.add_function("ret", fn_type, None);
/// let entry = context.append_basic_block(fn_value, "entry");
/// let i32_ptr_param = fn_value.get_first_param().unwrap().into_pointer_value();
///
/// builder.position_at_end(entry);
///
/// let pointee = builder.build_load(i32_ptr_param, "load").unwrap();
///
/// builder.build_return(Some(&pointee)).unwrap();
/// ```
#[llvm_versions(4.0..=14.0)]
pub fn build_load(&self, ptr: PointerValue<'ctx>, name: &str) -> Result<BasicValueEnum<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe { LLVMBuildLoad(self.builder, ptr.as_value_ref(), c_string.as_ptr()) };
unsafe { Ok(BasicValueEnum::new(value)) }
}
/// Builds a load2 instruction. It allows you to retrieve a value of type `T` from a pointer to a type `T`.
///
/// # Example
///
/// ```no_run
/// use inkwell::context::Context;
/// use inkwell::AddressSpace;
///
/// // Builds a function which takes an i32 pointer and returns the pointed at i32.
/// let context = Context::create();
/// let module = context.create_module("ret");
/// let builder = context.create_builder();
/// let i32_type = context.i32_type();
/// #[cfg(not(any(feature = "llvm15-0", feature = "llvm16-0", feature = "llvm17-0", feature = "llvm18-0")))]
/// let i32_ptr_type = i32_type.ptr_type(AddressSpace::default());
/// #[cfg(any(feature = "llvm15-0", feature = "llvm16-0", feature = "llvm17-0", feature = "llvm18-0"))]
/// let i32_ptr_type = context.ptr_type(AddressSpace::default());
/// let fn_type = i32_type.fn_type(&[i32_ptr_type.into()], false);
/// let fn_value = module.add_function("ret", fn_type, None);
/// let entry = context.append_basic_block(fn_value, "entry");
/// let i32_ptr_param = fn_value.get_first_param().unwrap().into_pointer_value();
///
/// builder.position_at_end(entry);
///
/// let pointee = builder.build_load(i32_type, i32_ptr_param, "load2").unwrap();
///
/// builder.build_return(Some(&pointee)).unwrap();
/// ```
#[llvm_versions(15.0..=latest)]
pub fn build_load<T: BasicType<'ctx>>(
&self,
pointee_ty: T,
ptr: PointerValue<'ctx>,
name: &str,
) -> Result<BasicValueEnum<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe {
LLVMBuildLoad2(
self.builder,
pointee_ty.as_type_ref(),
ptr.as_value_ref(),
c_string.as_ptr(),
)
};
unsafe { Ok(BasicValueEnum::new(value)) }
}
// TODOC: Stack allocation
pub fn build_alloca<T: BasicType<'ctx>>(&self, ty: T, name: &str) -> Result<PointerValue<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe { LLVMBuildAlloca(self.builder, ty.as_type_ref(), c_string.as_ptr()) };
unsafe { Ok(PointerValue::new(value)) }
}
// TODOC: Stack allocation
pub fn build_array_alloca<T: BasicType<'ctx>>(
&self,
ty: T,
size: IntValue<'ctx>,
name: &str,
) -> Result<PointerValue<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value =
unsafe { LLVMBuildArrayAlloca(self.builder, ty.as_type_ref(), size.as_value_ref(), c_string.as_ptr()) };
unsafe { Ok(PointerValue::new(value)) }
}
/// Build a [memcpy](https://llvm.org/docs/LangRef.html#llvm-memcpy-intrinsic) instruction.
///
/// Alignment arguments are specified in bytes, and should always be
/// both a power of 2 and under 2^64.
///
/// The final argument should be a pointer-sized integer.
///
/// Returns an `Err(BuilderError::AlignmentError)` if the source or destination alignments are not a power of 2.
///
/// [`TargetData::ptr_sized_int_type_in_context`](https://thedan64.github.io/inkwell/inkwell/targets/struct.TargetData.html#method.ptr_sized_int_type_in_context) will get you one of those.
#[llvm_versions(8.0..=latest)]
pub fn build_memcpy(
&self,
dest: PointerValue<'ctx>,
dest_align_bytes: u32,
src: PointerValue<'ctx>,
src_align_bytes: u32,
size: IntValue<'ctx>,
) -> Result<PointerValue<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
if !is_alignment_ok(src_align_bytes) {
return Err(BuilderError::AlignmentError(
"The src_align_bytes argument to build_memcpy was not a power of 2.",
));
}
if !is_alignment_ok(dest_align_bytes) {
return Err(BuilderError::AlignmentError(
"The dest_align_bytes argument to build_memcpy was not a power of 2.",
));
}
let value = unsafe {
LLVMBuildMemCpy(
self.builder,
dest.as_value_ref(),
dest_align_bytes,
src.as_value_ref(),
src_align_bytes,
size.as_value_ref(),
)
};
unsafe { Ok(PointerValue::new(value)) }
}
/// Build a [memmove](http://llvm.org/docs/LangRef.html#llvm-memmove-intrinsic) instruction.
///
/// Alignment arguments are specified in bytes, and should always be
/// both a power of 2 and under 2^64.
///
/// The final argument should be a pointer-sized integer.
///
/// Returns an `Err(BuilderError::AlignmentError)` if the source or destination alignments are not a power of 2 under 2^64.
///
/// [`TargetData::ptr_sized_int_type_in_context`](https://thedan64.github.io/inkwell/inkwell/targets/struct.TargetData.html#method.ptr_sized_int_type_in_context) will get you one of those.
#[llvm_versions(8.0..=latest)]
pub fn build_memmove(
&self,
dest: PointerValue<'ctx>,
dest_align_bytes: u32,
src: PointerValue<'ctx>,
src_align_bytes: u32,
size: IntValue<'ctx>,
) -> Result<PointerValue<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
if !is_alignment_ok(src_align_bytes) {
return Err(BuilderError::AlignmentError(
"The src_align_bytes argument to build_memmove was not a power of 2 under 2^64.",
));
}
if !is_alignment_ok(dest_align_bytes) {
return Err(BuilderError::AlignmentError(
"The dest_align_bytes argument to build_memmove was not a power of 2 under 2^64.",
));
}
let value = unsafe {
LLVMBuildMemMove(
self.builder,
dest.as_value_ref(),
dest_align_bytes,
src.as_value_ref(),
src_align_bytes,
size.as_value_ref(),
)
};
unsafe { Ok(PointerValue::new(value)) }
}
/// Build a [memset](http://llvm.org/docs/LangRef.html#llvm-memset-intrinsics) instruction.
///
/// Alignment arguments are specified in bytes, and should always be
/// both a power of 2 and under 2^64.
///
/// The final argument should be a pointer-sized integer.
///
/// Returns an `Err(BuilderError::AlignmentError)` if the source alignment is not a power of 2 under 2^64.
///
/// [`TargetData::ptr_sized_int_type_in_context`](https://thedan64.github.io/inkwell/inkwell/targets/struct.TargetData.html#method.ptr_sized_int_type_in_context) will get you one of those.
#[llvm_versions(8.0..=latest)]
pub fn build_memset(
&self,
dest: PointerValue<'ctx>,
dest_align_bytes: u32,
val: IntValue<'ctx>,
size: IntValue<'ctx>,
) -> Result<PointerValue<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
if !is_alignment_ok(dest_align_bytes) {
return Err(BuilderError::AlignmentError(
"The src_align_bytes argument to build_memmove was not a power of 2 under 2^64.",
));
}
let value = unsafe {
LLVMBuildMemSet(
self.builder,
dest.as_value_ref(),
val.as_value_ref(),
size.as_value_ref(),
dest_align_bytes,
)
};
unsafe { Ok(PointerValue::new(value)) }
}
// TODOC: Heap allocation
/// Returns `Err(BuilderError::AlignmentError)` if the type is unsized.
pub fn build_malloc<T: BasicType<'ctx>>(&self, ty: T, name: &str) -> Result<PointerValue<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
// LLVMBuildMalloc segfaults if ty is unsized
if !ty.is_sized() {
return Err(BuilderError::AlignmentError(
"Cannot build malloc call for an unsized type",
));
}
let c_string = to_c_str(name);
let value = unsafe { LLVMBuildMalloc(self.builder, ty.as_type_ref(), c_string.as_ptr()) };
unsafe { Ok(PointerValue::new(value)) }
}
// TODOC: Heap allocation
/// Returns `Err(BuilderError::AlignmentError)` if the type is unsized.
pub fn build_array_malloc<T: BasicType<'ctx>>(
&self,
ty: T,
size: IntValue<'ctx>,
name: &str,
) -> Result<PointerValue<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
// LLVMBuildArrayMalloc segfaults if ty is unsized
if !ty.is_sized() {
return Err(BuilderError::AlignmentError(
"Cannot build array malloc call for an unsized type",
));
}
let c_string = to_c_str(name);
let value =
unsafe { LLVMBuildArrayMalloc(self.builder, ty.as_type_ref(), size.as_value_ref(), c_string.as_ptr()) };
unsafe { Ok(PointerValue::new(value)) }
}
// SubType: <P>(&self, ptr: PointerValue<P>) -> InstructionValue {
pub fn build_free(&self, ptr: PointerValue<'ctx>) -> Result<InstructionValue<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
unsafe { Ok(InstructionValue::new(LLVMBuildFree(self.builder, ptr.as_value_ref()))) }
}
pub fn insert_instruction(&self, instruction: &InstructionValue<'ctx>, name: Option<&str>) {
match name {
Some(name) => {
let c_string = to_c_str(name);
unsafe { LLVMInsertIntoBuilderWithName(self.builder, instruction.as_value_ref(), c_string.as_ptr()) }
},
None => unsafe {
LLVMInsertIntoBuilder(self.builder, instruction.as_value_ref());
},
}
}
pub fn get_insert_block(&self) -> Option<BasicBlock<'ctx>> {
unsafe { BasicBlock::new(LLVMGetInsertBlock(self.builder)) }
}
// TODO: Possibly make this generic over sign via struct metadata or subtypes
// SubType: <I: IntSubType>(&self, lhs: &IntValue<I>, rhs: &IntValue<I>, name: &str) -> IntValue<I> {
// if I::sign() == Unsigned { LLVMBuildUDiv() } else { LLVMBuildSDiv() }
pub fn build_int_unsigned_div<T: IntMathValue<'ctx>>(&self, lhs: T, rhs: T, name: &str) -> Result<T, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe { LLVMBuildUDiv(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr()) };
unsafe { Ok(T::new(value)) }
}
// TODO: Possibly make this generic over sign via struct metadata or subtypes
// SubType: <I>(&self, lhs: &IntValue<I>, rhs: &IntValue<I>, name: &str) -> IntValue<I> {
pub fn build_int_signed_div<T: IntMathValue<'ctx>>(&self, lhs: T, rhs: T, name: &str) -> Result<T, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe { LLVMBuildSDiv(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr()) };
unsafe { Ok(T::new(value)) }
}
// TODO: Possibly make this generic over sign via struct metadata or subtypes
// SubType: <I>(&self, lhs: &IntValue<I>, rhs: &IntValue<I>, name: &str) -> IntValue<I> {
pub fn build_int_exact_signed_div<T: IntMathValue<'ctx>>(
&self,
lhs: T,
rhs: T,
name: &str,
) -> Result<T, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value =
unsafe { LLVMBuildExactSDiv(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr()) };
unsafe { Ok(T::new(value)) }
}
// TODO: Possibly make this generic over sign via struct metadata or subtypes
// SubType: <I>(&self, lhs: &IntValue<I>, rhs: &IntValue<I>, name: &str) -> IntValue<I> {
pub fn build_int_unsigned_rem<T: IntMathValue<'ctx>>(&self, lhs: T, rhs: T, name: &str) -> Result<T, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe { LLVMBuildURem(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr()) };
unsafe { Ok(T::new(value)) }
}
// TODO: Possibly make this generic over sign via struct metadata or subtypes
// SubType: <I>(&self, lhs: &IntValue<I>, rhs: &IntValue<I>, name: &str) -> IntValue<I> {
pub fn build_int_signed_rem<T: IntMathValue<'ctx>>(&self, lhs: T, rhs: T, name: &str) -> Result<T, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe { LLVMBuildSRem(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr()) };
unsafe { Ok(T::new(value)) }
}
pub fn build_int_s_extend<T: IntMathValue<'ctx>>(
&self,
int_value: T,
int_type: T::BaseType,
name: &str,
) -> Result<T, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe {
LLVMBuildSExt(
self.builder,
int_value.as_value_ref(),
int_type.as_type_ref(),
c_string.as_ptr(),
)
};
unsafe { Ok(T::new(value)) }
}
// REVIEW: Does this need vector support?
pub fn build_address_space_cast(
&self,
ptr_val: PointerValue<'ctx>,
ptr_type: PointerType<'ctx>,
name: &str,
) -> Result<PointerValue<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe {
LLVMBuildAddrSpaceCast(
self.builder,
ptr_val.as_value_ref(),
ptr_type.as_type_ref(),
c_string.as_ptr(),
)
};
unsafe { Ok(PointerValue::new(value)) }
}
/// Builds a bitcast instruction. A bitcast reinterprets the bits of one value
/// into a value of another type which has the same bit width.
///
/// # Example
///
/// ```no_run
/// use inkwell::AddressSpace;
/// use inkwell::context::Context;
///
/// let context = Context::create();
/// let module = context.create_module("bc");
/// let void_type = context.void_type();
/// let f32_type = context.f32_type();
/// let i32_type = context.i32_type();
/// let arg_types = [i32_type.into()];
/// let fn_type = void_type.fn_type(&arg_types, false);
/// let fn_value = module.add_function("bc", fn_type, None);
/// let builder = context.create_builder();
/// let entry = context.append_basic_block(fn_value, "entry");
/// let i32_arg = fn_value.get_first_param().unwrap();
///
/// builder.position_at_end(entry);
///
/// builder.build_bit_cast(i32_arg, f32_type, "i32tof32").unwrap();
/// builder.build_return(None).unwrap();
///
/// assert!(module.verify().is_ok());
/// ```
pub fn build_bit_cast<T, V>(&self, val: V, ty: T, name: &str) -> Result<BasicValueEnum<'ctx>, BuilderError>
where
T: BasicType<'ctx>,
V: BasicValue<'ctx>,
{
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe { LLVMBuildBitCast(self.builder, val.as_value_ref(), ty.as_type_ref(), c_string.as_ptr()) };
unsafe { Ok(BasicValueEnum::new(value)) }
}
pub fn build_int_s_extend_or_bit_cast<T: IntMathValue<'ctx>>(
&self,
int_value: T,
int_type: T::BaseType,
name: &str,
) -> Result<T, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe {
LLVMBuildSExtOrBitCast(
self.builder,
int_value.as_value_ref(),
int_type.as_type_ref(),
c_string.as_ptr(),
)
};
unsafe { Ok(T::new(value)) }
}
pub fn build_int_z_extend<T: IntMathValue<'ctx>>(
&self,
int_value: T,
int_type: T::BaseType,
name: &str,
) -> Result<T, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe {
LLVMBuildZExt(
self.builder,
int_value.as_value_ref(),
int_type.as_type_ref(),
c_string.as_ptr(),
)
};
unsafe { Ok(T::new(value)) }
}
pub fn build_int_z_extend_or_bit_cast<T: IntMathValue<'ctx>>(
&self,
int_value: T,
int_type: T::BaseType,
name: &str,
) -> Result<T, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe {
LLVMBuildZExtOrBitCast(
self.builder,
int_value.as_value_ref(),
int_type.as_type_ref(),
c_string.as_ptr(),
)
};
unsafe { Ok(T::new(value)) }
}
pub fn build_int_truncate<T: IntMathValue<'ctx>>(
&self,
int_value: T,
int_type: T::BaseType,
name: &str,
) -> Result<T, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe {
LLVMBuildTrunc(
self.builder,
int_value.as_value_ref(),
int_type.as_type_ref(),
c_string.as_ptr(),
)
};
unsafe { Ok(T::new(value)) }
}
pub fn build_int_truncate_or_bit_cast<T: IntMathValue<'ctx>>(
&self,
int_value: T,
int_type: T::BaseType,
name: &str,
) -> Result<T, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe {
LLVMBuildTruncOrBitCast(
self.builder,
int_value.as_value_ref(),
int_type.as_type_ref(),
c_string.as_ptr(),
)
};
unsafe { Ok(T::new(value)) }
}
pub fn build_float_rem<T: FloatMathValue<'ctx>>(&self, lhs: T, rhs: T, name: &str) -> Result<T, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe { LLVMBuildFRem(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr()) };
unsafe { Ok(T::new(value)) }
}
// REVIEW: Consolidate these two casts into one via subtypes
pub fn build_float_to_unsigned_int<T: FloatMathValue<'ctx>>(
&self,
float: T,
int_type: <T::BaseType as FloatMathType<'ctx>>::MathConvType,
name: &str,
) -> Result<<<T::BaseType as FloatMathType<'ctx>>::MathConvType as IntMathType<'ctx>>::ValueType, BuilderError>
{
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe {
LLVMBuildFPToUI(
self.builder,
float.as_value_ref(),
int_type.as_type_ref(),
c_string.as_ptr(),
)
};
unsafe { Ok(<<T::BaseType as FloatMathType>::MathConvType as IntMathType>::ValueType::new(value)) }
}
pub fn build_float_to_signed_int<T: FloatMathValue<'ctx>>(
&self,
float: T,
int_type: <T::BaseType as FloatMathType<'ctx>>::MathConvType,
name: &str,
) -> Result<<<T::BaseType as FloatMathType<'ctx>>::MathConvType as IntMathType<'ctx>>::ValueType, BuilderError>
{
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe {
LLVMBuildFPToSI(
self.builder,
float.as_value_ref(),
int_type.as_type_ref(),
c_string.as_ptr(),
)
};
unsafe { Ok(<<T::BaseType as FloatMathType>::MathConvType as IntMathType>::ValueType::new(value)) }
}
// REVIEW: Consolidate these two casts into one via subtypes
pub fn build_unsigned_int_to_float<T: IntMathValue<'ctx>>(
&self,
int: T,
float_type: <T::BaseType as IntMathType<'ctx>>::MathConvType,
name: &str,
) -> Result<<<T::BaseType as IntMathType<'ctx>>::MathConvType as FloatMathType<'ctx>>::ValueType, BuilderError>
{
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe {
LLVMBuildUIToFP(
self.builder,
int.as_value_ref(),
float_type.as_type_ref(),
c_string.as_ptr(),
)
};
unsafe { Ok(<<T::BaseType as IntMathType>::MathConvType as FloatMathType>::ValueType::new(value)) }
}
pub fn build_signed_int_to_float<T: IntMathValue<'ctx>>(
&self,
int: T,
float_type: <T::BaseType as IntMathType<'ctx>>::MathConvType,
name: &str,
) -> Result<<<T::BaseType as IntMathType<'ctx>>::MathConvType as FloatMathType<'ctx>>::ValueType, BuilderError>
{
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe {
LLVMBuildSIToFP(
self.builder,
int.as_value_ref(),
float_type.as_type_ref(),
c_string.as_ptr(),
)
};
unsafe { Ok(<<T::BaseType as IntMathType>::MathConvType as FloatMathType>::ValueType::new(value)) }
}
pub fn build_float_trunc<T: FloatMathValue<'ctx>>(
&self,
float: T,
float_type: T::BaseType,
name: &str,
) -> Result<T, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe {
LLVMBuildFPTrunc(
self.builder,
float.as_value_ref(),
float_type.as_type_ref(),
c_string.as_ptr(),
)
};
unsafe { Ok(T::new(value)) }
}
pub fn build_float_ext<T: FloatMathValue<'ctx>>(
&self,
float: T,
float_type: T::BaseType,
name: &str,
) -> Result<T, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe {
LLVMBuildFPExt(
self.builder,
float.as_value_ref(),
float_type.as_type_ref(),
c_string.as_ptr(),
)
};
unsafe { Ok(T::new(value)) }
}
pub fn build_float_cast<T: FloatMathValue<'ctx>>(
&self,
float: T,
float_type: T::BaseType,
name: &str,
) -> Result<T, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe {
LLVMBuildFPCast(
self.builder,
float.as_value_ref(),
float_type.as_type_ref(),
c_string.as_ptr(),
)
};
unsafe { Ok(T::new(value)) }
}
// SubType: <L, R>(&self, lhs: &IntValue<L>, rhs: &IntType<R>, name: &str) -> IntValue<R> {
pub fn build_int_cast<T: IntMathValue<'ctx>>(
&self,
int: T,
int_type: T::BaseType,
name: &str,
) -> Result<T, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe {
LLVMBuildIntCast(
self.builder,
int.as_value_ref(),
int_type.as_type_ref(),
c_string.as_ptr(),
)
};
unsafe { Ok(T::new(value)) }
}
/// Like `build_int_cast`, but respects the signedness of the type being cast to.
#[llvm_versions(8.0..=latest)]
pub fn build_int_cast_sign_flag<T: IntMathValue<'ctx>>(
&self,
int: T,
int_type: T::BaseType,
is_signed: bool,
name: &str,
) -> Result<T, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe {
LLVMBuildIntCast2(
self.builder,
int.as_value_ref(),
int_type.as_type_ref(),
is_signed.into(),
c_string.as_ptr(),
)
};
unsafe { Ok(T::new(value)) }
}
pub fn build_float_div<T: FloatMathValue<'ctx>>(&self, lhs: T, rhs: T, name: &str) -> Result<T, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe { LLVMBuildFDiv(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr()) };
unsafe { Ok(T::new(value)) }
}
// SubType: <I>(&self, lhs: &IntValue<I>, rhs: &IntValue<I>, name: &str) -> IntValue<I> {
pub fn build_int_add<T: IntMathValue<'ctx>>(&self, lhs: T, rhs: T, name: &str) -> Result<T, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe { LLVMBuildAdd(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr()) };
unsafe { Ok(T::new(value)) }
}
// REVIEW: Possibly incorporate into build_int_add via flag param
// SubType: <I>(&self, lhs: &IntValue<I>, rhs: &IntValue<I>, name: &str) -> IntValue<I> {
pub fn build_int_nsw_add<T: IntMathValue<'ctx>>(&self, lhs: T, rhs: T, name: &str) -> Result<T, BuilderError> {
let c_string = to_c_str(name);
let value = unsafe { LLVMBuildNSWAdd(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr()) };
unsafe { Ok(T::new(value)) }
}
// REVIEW: Possibly incorporate into build_int_add via flag param
// SubType: <I>(&self, lhs: &IntValue<I>, rhs: &IntValue<I>, name: &str) -> IntValue<I> {
pub fn build_int_nuw_add<T: IntMathValue<'ctx>>(&self, lhs: T, rhs: T, name: &str) -> Result<T, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe { LLVMBuildNUWAdd(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr()) };
unsafe { Ok(T::new(value)) }
}
// SubType: <F>(&self, lhs: &FloatValue<F>, rhs: &FloatValue<F>, name: &str) -> FloatValue<F> {
pub fn build_float_add<T: FloatMathValue<'ctx>>(&self, lhs: T, rhs: T, name: &str) -> Result<T, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe { LLVMBuildFAdd(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr()) };
unsafe { Ok(T::new(value)) }
}
// SubType: (&self, lhs: &IntValue<bool>, rhs: &IntValue<bool>, name: &str) -> IntValue<bool> {
pub fn build_xor<T: IntMathValue<'ctx>>(&self, lhs: T, rhs: T, name: &str) -> Result<T, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe { LLVMBuildXor(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr()) };
unsafe { Ok(T::new(value)) }
}
// SubType: (&self, lhs: &IntValue<bool>, rhs: &IntValue<bool>, name: &str) -> IntValue<bool> {
pub fn build_and<T: IntMathValue<'ctx>>(&self, lhs: T, rhs: T, name: &str) -> Result<T, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe { LLVMBuildAnd(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr()) };
unsafe { Ok(T::new(value)) }
}
// SubType: (&self, lhs: &IntValue<bool>, rhs: &IntValue<bool>, name: &str) -> IntValue<bool> {
pub fn build_or<T: IntMathValue<'ctx>>(&self, lhs: T, rhs: T, name: &str) -> Result<T, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe { LLVMBuildOr(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr()) };
unsafe { Ok(T::new(value)) }
}
/// Builds an `IntValue` containing the result of a logical left shift instruction.
///
/// # Example
/// A logical left shift is an operation in which an integer value's bits are shifted left by N number of positions.
///
/// ```rust,no_run
/// assert_eq!(0b0000_0001 << 0, 0b0000_0001);
/// assert_eq!(0b0000_0001 << 1, 0b0000_0010);
/// assert_eq!(0b0000_0011 << 2, 0b0000_1100);
/// ```
///
/// In Rust, a function that could do this for 8bit values looks like:
///
/// ```rust,no_run
/// fn left_shift(value: u8, n: u8) -> u8 {
/// value << n
/// }
/// ```
///
/// And in Inkwell, the corresponding function would look roughly like:
///
/// ```rust,no_run
/// use inkwell::context::Context;
///
/// // Setup
/// let context = Context::create();
/// let module = context.create_module("my_module");
/// let builder = context.create_builder();
/// let i8_type = context.i8_type();
/// let fn_type = i8_type.fn_type(&[i8_type.into(), i8_type.into()], false);
///
/// // Function Definition
/// let function = module.add_function("left_shift", fn_type, None);
/// let value = function.get_first_param().unwrap().into_int_value();
/// let n = function.get_nth_param(1).unwrap().into_int_value();
/// let entry_block = context.append_basic_block(function, "entry");
///
/// builder.position_at_end(entry_block);
///
/// let shift = builder.build_left_shift(value, n, "left_shift").unwrap(); // value << n
///
/// builder.build_return(Some(&shift)).unwrap();
/// ```
pub fn build_left_shift<T: IntMathValue<'ctx>>(&self, lhs: T, rhs: T, name: &str) -> Result<T, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe { LLVMBuildShl(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr()) };
unsafe { Ok(T::new(value)) }
}
/// Builds an `IntValue` containing the result of a right shift instruction.
///
/// # Example
/// A right shift is an operation in which an integer value's bits are shifted right by N number of positions.
/// It may either be logical and have its leftmost N bit(s) filled with zeros or sign extended and filled with ones
/// if the leftmost bit was one.
///
/// ```rust,no_run
/// //fix doc error about overflowing_literals
/// //rendered rfc: https://github.com/rust-lang/rfcs/blob/master/text/2438-deny-integer-literal-overflow-lint.md
/// //tracking issue: https://github.com/rust-lang/rust/issues/54502
/// #![allow(overflowing_literals)]
///
/// // Logical Right Shift
/// assert_eq!(0b1100_0000u8 >> 2, 0b0011_0000);
/// assert_eq!(0b0000_0010u8 >> 1, 0b0000_0001);
/// assert_eq!(0b0000_1100u8 >> 2, 0b0000_0011);
///
/// // Sign Extended Right Shift
/// assert_eq!(0b0100_0000i8 >> 2, 0b0001_0000);
/// assert_eq!(0b1110_0000u8 as i8 >> 1, 0b1111_0000u8 as i8);
/// assert_eq!(0b1100_0000u8 as i8 >> 2, 0b1111_0000u8 as i8);
/// ```
///
/// In Rust, functions that could do this for 8bit values look like:
///
/// ```rust,no_run
/// fn logical_right_shift(value: u8, n: u8) -> u8 {
/// value >> n
/// }
///
/// fn sign_extended_right_shift(value: i8, n: u8) -> i8 {
/// value >> n
/// }
/// ```
/// Notice that, in Rust (and most other languages), whether or not a value is sign extended depends wholly on whether
/// or not the type is signed (ie an i8 is a signed 8 bit value). LLVM does not make this distinction for you.
///
/// In Inkwell, the corresponding functions would look roughly like:
///
/// ```rust,no_run
/// use inkwell::context::Context;
///
/// // Setup
/// let context = Context::create();
/// let module = context.create_module("my_module");
/// let builder = context.create_builder();
/// let i8_type = context.i8_type();
/// let fn_type = i8_type.fn_type(&[i8_type.into(), i8_type.into()], false);
///
/// // Function Definition
/// let function = module.add_function("right_shift", fn_type, None);
/// let value = function.get_first_param().unwrap().into_int_value();
/// let n = function.get_nth_param(1).unwrap().into_int_value();
/// let entry_block = context.append_basic_block(function, "entry");
///
/// builder.position_at_end(entry_block);
///
/// // Whether or not your right shift is sign extended (true) or logical (false) depends
/// // on the boolean input parameter:
/// let shift = builder.build_right_shift(value, n, false, "right_shift").unwrap(); // value >> n
///
/// builder.build_return(Some(&shift)).unwrap();
/// ```
pub fn build_right_shift<T: IntMathValue<'ctx>>(
&self,
lhs: T,
rhs: T,
sign_extend: bool,
name: &str,
) -> Result<T, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe {
if sign_extend {
LLVMBuildAShr(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
} else {
LLVMBuildLShr(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
}
};
unsafe { Ok(T::new(value)) }
}
// SubType: <I>(&self, lhs: &IntValue<I>, rhs: &IntValue<I>, name: &str) -> IntValue<I> {
pub fn build_int_sub<T: IntMathValue<'ctx>>(&self, lhs: T, rhs: T, name: &str) -> Result<T, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe { LLVMBuildSub(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr()) };
unsafe { Ok(T::new(value)) }
}
// REVIEW: Possibly incorporate into build_int_sub via flag param
pub fn build_int_nsw_sub<T: IntMathValue<'ctx>>(&self, lhs: T, rhs: T, name: &str) -> Result<T, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe { LLVMBuildNSWSub(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr()) };
unsafe { Ok(T::new(value)) }
}
// REVIEW: Possibly incorporate into build_int_sub via flag param
// SubType: <I>(&self, lhs: &IntValue<I>, rhs: &IntValue<I>, name: &str) -> IntValue<I> {
pub fn build_int_nuw_sub<T: IntMathValue<'ctx>>(&self, lhs: T, rhs: T, name: &str) -> Result<T, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe { LLVMBuildNUWSub(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr()) };
unsafe { Ok(T::new(value)) }
}
// SubType: <F>(&self, lhs: &FloatValue<F>, rhs: &FloatValue<F>, name: &str) -> FloatValue<F> {
pub fn build_float_sub<T: FloatMathValue<'ctx>>(&self, lhs: T, rhs: T, name: &str) -> Result<T, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe { LLVMBuildFSub(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr()) };
unsafe { Ok(T::new(value)) }
}
// SubType: <I>(&self, lhs: &IntValue<I>, rhs: &IntValue<I>, name: &str) -> IntValue<I> {
pub fn build_int_mul<T: IntMathValue<'ctx>>(&self, lhs: T, rhs: T, name: &str) -> Result<T, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe { LLVMBuildMul(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr()) };
unsafe { Ok(T::new(value)) }
}
// REVIEW: Possibly incorporate into build_int_mul via flag param
// SubType: <I>(&self, lhs: &IntValue<I>, rhs: &IntValue<I>, name: &str) -> IntValue<I> {
pub fn build_int_nsw_mul<T: IntMathValue<'ctx>>(&self, lhs: T, rhs: T, name: &str) -> Result<T, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe { LLVMBuildNSWMul(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr()) };
unsafe { Ok(T::new(value)) }
}
// REVIEW: Possibly incorporate into build_int_mul via flag param
// SubType: <I>(&self, lhs: &IntValue<I>, rhs: &IntValue<I>, name: &str) -> IntValue<I> {
pub fn build_int_nuw_mul<T: IntMathValue<'ctx>>(&self, lhs: T, rhs: T, name: &str) -> Result<T, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe { LLVMBuildNUWMul(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr()) };
unsafe { Ok(T::new(value)) }
}
// SubType: <F>(&self, lhs: &FloatValue<F>, rhs: &FloatValue<F>, name: &str) -> FloatValue<F> {
pub fn build_float_mul<T: FloatMathValue<'ctx>>(&self, lhs: T, rhs: T, name: &str) -> Result<T, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe { LLVMBuildFMul(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr()) };
unsafe { Ok(T::new(value)) }
}
pub fn build_cast<T: BasicType<'ctx>, V: BasicValue<'ctx>>(
&self,
op: InstructionOpcode,
from_value: V,
to_type: T,
name: &str,
) -> Result<BasicValueEnum<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe {
LLVMBuildCast(
self.builder,
op.into(),
from_value.as_value_ref(),
to_type.as_type_ref(),
c_string.as_ptr(),
)
};
unsafe { Ok(BasicValueEnum::new(value)) }
}
// SubType: <F, T>(&self, from: &PointerValue<F>, to: &PointerType<T>, name: &str) -> PointerValue<T> {
pub fn build_pointer_cast<T: PointerMathValue<'ctx>>(
&self,
from: T,
to: T::BaseType,
name: &str,
) -> Result<T, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value =
unsafe { LLVMBuildPointerCast(self.builder, from.as_value_ref(), to.as_type_ref(), c_string.as_ptr()) };
unsafe { Ok(T::new(value)) }
}
// SubType: <I>(&self, op, lhs: &IntValue<I>, rhs: &IntValue<I>, name) -> IntValue<bool> { ?
// Note: we need a way to get an appropriate return type, since this method's return value
// is always a bool (or vector of bools), not necessarily the same as the input value
// See https://github.com/TheDan64/inkwell/pull/47#discussion_r197599297
pub fn build_int_compare<T: IntMathValue<'ctx>>(
&self,
op: IntPredicate,
lhs: T,
rhs: T,
name: &str,
) -> Result<<T::BaseType as IntMathType<'ctx>>::ValueType, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe {
LLVMBuildICmp(
self.builder,
op.into(),
lhs.as_value_ref(),
rhs.as_value_ref(),
c_string.as_ptr(),
)
};
unsafe { Ok(<T::BaseType as IntMathType<'ctx>>::ValueType::new(value)) }
}
// SubType: <F>(&self, op, lhs: &FloatValue<F>, rhs: &FloatValue<F>, name) -> IntValue<bool> { ?
// Note: see comment on build_int_compare regarding return value type
pub fn build_float_compare<T: FloatMathValue<'ctx>>(
&self,
op: FloatPredicate,
lhs: T,
rhs: T,
name: &str,
) -> Result<<<T::BaseType as FloatMathType<'ctx>>::MathConvType as IntMathType<'ctx>>::ValueType, BuilderError>
{
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe {
LLVMBuildFCmp(
self.builder,
op.into(),
lhs.as_value_ref(),
rhs.as_value_ref(),
c_string.as_ptr(),
)
};
unsafe { Ok(<<T::BaseType as FloatMathType>::MathConvType as IntMathType>::ValueType::new(value)) }
}
pub fn build_unconditional_branch(
&self,
destination_block: BasicBlock<'ctx>,
) -> Result<InstructionValue<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let value = unsafe { LLVMBuildBr(self.builder, destination_block.basic_block) };
unsafe { Ok(InstructionValue::new(value)) }
}
pub fn build_conditional_branch(
&self,
comparison: IntValue<'ctx>,
then_block: BasicBlock<'ctx>,
else_block: BasicBlock<'ctx>,
) -> Result<InstructionValue<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let value = unsafe {
LLVMBuildCondBr(
self.builder,
comparison.as_value_ref(),
then_block.basic_block,
else_block.basic_block,
)
};
unsafe { Ok(InstructionValue::new(value)) }
}
pub fn build_indirect_branch<BV: BasicValue<'ctx>>(
&self,
address: BV,
destinations: &[BasicBlock<'ctx>],
) -> Result<InstructionValue<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let value = unsafe { LLVMBuildIndirectBr(self.builder, address.as_value_ref(), destinations.len() as u32) };
for destination in destinations {
unsafe { LLVMAddDestination(value, destination.basic_block) }
}
unsafe { Ok(InstructionValue::new(value)) }
}
// SubType: <I>(&self, value: &IntValue<I>, name) -> IntValue<I> {
pub fn build_int_neg<T: IntMathValue<'ctx>>(&self, value: T, name: &str) -> Result<T, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe { LLVMBuildNeg(self.builder, value.as_value_ref(), c_string.as_ptr()) };
unsafe { Ok(T::new(value)) }
}
// REVIEW: Possibly incorporate into build_int_neg via flag and subtypes
// SubType: <I>(&self, value: &IntValue<I>, name) -> IntValue<I> {
pub fn build_int_nsw_neg<T: IntMathValue<'ctx>>(&self, value: T, name: &str) -> Result<T, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe { LLVMBuildNSWNeg(self.builder, value.as_value_ref(), c_string.as_ptr()) };
unsafe { Ok(T::new(value)) }
}
// SubType: <I>(&self, value: &IntValue<I>, name) -> IntValue<I> {
pub fn build_int_nuw_neg<T: IntMathValue<'ctx>>(&self, value: T, name: &str) -> Result<T, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe { LLVMBuildNUWNeg(self.builder, value.as_value_ref(), c_string.as_ptr()) };
unsafe { Ok(T::new(value)) }
}
// SubType: <F>(&self, value: &FloatValue<F>, name) -> FloatValue<F> {
pub fn build_float_neg<T: FloatMathValue<'ctx>>(&self, value: T, name: &str) -> Result<T, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe { LLVMBuildFNeg(self.builder, value.as_value_ref(), c_string.as_ptr()) };
unsafe { Ok(T::new(value)) }
}
// SubType: <I>(&self, value: &IntValue<I>, name) -> IntValue<bool> { ?
pub fn build_not<T: IntMathValue<'ctx>>(&self, value: T, name: &str) -> Result<T, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe { LLVMBuildNot(self.builder, value.as_value_ref(), c_string.as_ptr()) };
unsafe { Ok(T::new(value)) }
}
// REVIEW: What if instruction and basic_block are completely unrelated?
// It'd be great if we could get the BB from the instruction behind the scenes
/// Set the position of the builder to after an instruction.
///
/// Be sure to call one of the `position_*` methods or all `build_*` methods will return `Err(BuilderError::UnsetPosition)`.
pub fn position_at(&self, basic_block: BasicBlock<'ctx>, instruction: &InstructionValue<'ctx>) {
self.positioned.set(PositionState::Set);
unsafe { LLVMPositionBuilder(self.builder, basic_block.basic_block, instruction.as_value_ref()) }
}
/// Set the position of the builder to before an instruction.
///
/// Be sure to call one of the `position_*` methods or all `build_*` methods will return `Err(BuilderError::UnsetPosition)`.
pub fn position_before(&self, instruction: &InstructionValue<'ctx>) {
self.positioned.set(PositionState::Set);
unsafe { LLVMPositionBuilderBefore(self.builder, instruction.as_value_ref()) }
}
/// Set the position of the builder to the end of a basic block.
///
/// Be sure to call one of the `position_*` methods or all `build_*` methods will return `Err(BuilderError::UnsetPosition)`.
pub fn position_at_end(&self, basic_block: BasicBlock<'ctx>) {
self.positioned.set(PositionState::Set);
unsafe {
LLVMPositionBuilderAtEnd(self.builder, basic_block.basic_block);
}
}
/// Builds an extract value instruction which extracts a `BasicValueEnum`
/// from a struct or array.
///
/// Returns `Err(BuilderError::ExtractOutOfRange)` if the provided index is out of bounds of the aggregate value length.
///
/// # Example
///
/// ```no_run
/// use inkwell::context::Context;
/// use inkwell::builder::BuilderError;
///
/// let context = Context::create();
/// let module = context.create_module("av");
/// let void_type = context.void_type();
/// let f32_type = context.f32_type();
/// let i32_type = context.i32_type();
/// let struct_type = context.struct_type(&[i32_type.into(), f32_type.into()], false);
/// let array_type = i32_type.array_type(3);
/// let fn_type = void_type.fn_type(&[], false);
/// let fn_value = module.add_function("av_fn", fn_type, None);
/// let builder = context.create_builder();
/// let entry = context.append_basic_block(fn_value, "entry");
///
/// builder.position_at_end(entry);
///
/// let array_alloca = builder.build_alloca(array_type, "array_alloca").unwrap();
///
/// #[cfg(any(
/// feature = "llvm4-0",
/// feature = "llvm5-0",
/// feature = "llvm6-0",
/// feature = "llvm7-0",
/// feature = "llvm8-0",
/// feature = "llvm9-0",
/// feature = "llvm10-0",
/// feature = "llvm11-0",
/// feature = "llvm12-0",
/// feature = "llvm13-0",
/// feature = "llvm14-0"
/// ))]
/// let array = builder.build_load(array_alloca, "array_load").unwrap().into_array_value();
/// #[cfg(any(feature = "llvm15-0", feature = "llvm16-0", feature = "llvm17-0", feature = "llvm18-0"))]
/// let array = builder.build_load(i32_type, array_alloca, "array_load").unwrap().into_array_value();
///
/// let const_int1 = i32_type.const_int(2, false);
/// let const_int2 = i32_type.const_int(5, false);
/// let const_int3 = i32_type.const_int(6, false);
///
/// assert!(builder.build_insert_value(array, const_int1, 0, "insert").is_ok());
/// assert!(builder.build_insert_value(array, const_int2, 1, "insert").is_ok());
/// assert!(builder.build_insert_value(array, const_int3, 2, "insert").is_ok());
/// assert!(builder.build_insert_value(array, const_int3, 3, "insert").is_err_and(|e| e == BuilderError::ExtractOutOfRange));
///
/// assert!(builder.build_extract_value(array, 0, "extract").unwrap().is_int_value());
/// assert!(builder.build_extract_value(array, 1, "extract").unwrap().is_int_value());
/// assert!(builder.build_extract_value(array, 2, "extract").unwrap().is_int_value());
/// assert!(builder.build_extract_value(array, 3, "extract").is_err_and(|e| e == BuilderError::ExtractOutOfRange));
/// ```
pub fn build_extract_value<AV: AggregateValue<'ctx>>(
&self,
agg: AV,
index: u32,
name: &str,
) -> Result<BasicValueEnum<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let size = match agg.as_aggregate_value_enum() {
AggregateValueEnum::ArrayValue(av) => av.get_type().len(),
AggregateValueEnum::StructValue(sv) => sv.get_type().count_fields(),
};
if index >= size {
return Err(BuilderError::ExtractOutOfRange);
}
let c_string = to_c_str(name);
let value = unsafe { LLVMBuildExtractValue(self.builder, agg.as_value_ref(), index, c_string.as_ptr()) };
unsafe { Ok(BasicValueEnum::new(value)) }
}
/// Builds an insert value instruction which inserts a `BasicValue` into a struct
/// or array and returns the resulting aggregate value.
///
/// Returns `Err(BuilderError::ExtractOutOfRange)` if the provided index is out of bounds of the aggregate value length.
///
/// # Example
///
/// ```no_run
/// use inkwell::context::Context;
/// use inkwell::builder::BuilderError;
///
/// let context = Context::create();
/// let module = context.create_module("av");
/// let void_type = context.void_type();
/// let f32_type = context.f32_type();
/// let i32_type = context.i32_type();
/// let struct_type = context.struct_type(&[i32_type.into(), f32_type.into()], false);
/// let array_type = i32_type.array_type(3);
/// let fn_type = void_type.fn_type(&[], false);
/// let fn_value = module.add_function("av_fn", fn_type, None);
/// let builder = context.create_builder();
/// let entry = context.append_basic_block(fn_value, "entry");
///
/// builder.position_at_end(entry);
///
/// let array_alloca = builder.build_alloca(array_type, "array_alloca").unwrap();
///
/// #[cfg(any(
/// feature = "llvm4-0",
/// feature = "llvm5-0",
/// feature = "llvm6-0",
/// feature = "llvm7-0",
/// feature = "llvm8-0",
/// feature = "llvm9-0",
/// feature = "llvm10-0",
/// feature = "llvm11-0",
/// feature = "llvm12-0",
/// feature = "llvm13-0",
/// feature = "llvm14-0"
/// ))]
/// let array = builder.build_load(array_alloca, "array_load").unwrap().into_array_value();
/// #[cfg(any(feature = "llvm15-0", feature = "llvm16-0", feature = "llvm17-0", feature = "llvm18-0"))]
/// let array = builder.build_load(i32_type, array_alloca, "array_load").unwrap().into_array_value();
///
/// let const_int1 = i32_type.const_int(2, false);
/// let const_int2 = i32_type.const_int(5, false);
/// let const_int3 = i32_type.const_int(6, false);
///
/// assert!(builder.build_insert_value(array, const_int1, 0, "insert").is_ok());
/// assert!(builder.build_insert_value(array, const_int2, 1, "insert").is_ok());
/// assert!(builder.build_insert_value(array, const_int3, 2, "insert").is_ok());
/// assert!(builder.build_insert_value(array, const_int3, 3, "insert").is_err_and(|e| e == BuilderError::ExtractOutOfRange));
/// ```
pub fn build_insert_value<AV, BV>(
&self,
agg: AV,
value: BV,
index: u32,
name: &str,
) -> Result<AggregateValueEnum<'ctx>, BuilderError>
where
AV: AggregateValue<'ctx>,
BV: BasicValue<'ctx>,
{
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let size = match agg.as_aggregate_value_enum() {
AggregateValueEnum::ArrayValue(av) => av.get_type().len(),
AggregateValueEnum::StructValue(sv) => sv.get_type().count_fields(),
};
if index >= size {
return Err(BuilderError::ExtractOutOfRange);
}
let c_string = to_c_str(name);
let value = unsafe {
LLVMBuildInsertValue(
self.builder,
agg.as_value_ref(),
value.as_value_ref(),
index,
c_string.as_ptr(),
)
};
unsafe { Ok(AggregateValueEnum::new(value)) }
}
/// Builds an extract element instruction which extracts a `BasicValueEnum`
/// from a vector.
/// # Example
///
/// ```no_run
/// use inkwell::context::Context;
///
/// let context = Context::create();
/// let module = context.create_module("av");
/// let i32_type = context.i32_type();
/// let i32_zero = i32_type.const_int(0, false);
/// let vec_type = i32_type.vec_type(2);
/// let fn_type = i32_type.fn_type(&[vec_type.into()], false);
/// let fn_value = module.add_function("vec_fn", fn_type, None);
/// let builder = context.create_builder();
/// let entry = context.append_basic_block(fn_value, "entry");
/// let vector_param = fn_value.get_first_param().unwrap().into_vector_value();
///
/// builder.position_at_end(entry);
///
/// let extracted = builder.build_extract_element(vector_param, i32_zero, "insert").unwrap();
///
/// builder.build_return(Some(&extracted)).unwrap();
/// ```
pub fn build_extract_element(
&self,
vector: VectorValue<'ctx>,
index: IntValue<'ctx>,
name: &str,
) -> Result<BasicValueEnum<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe {
LLVMBuildExtractElement(
self.builder,
vector.as_value_ref(),
index.as_value_ref(),
c_string.as_ptr(),
)
};
unsafe { Ok(BasicValueEnum::new(value)) }
}
/// Builds an insert element instruction which inserts a `BasicValue` into a vector
/// and returns the resulting vector.
///
/// # Example
///
/// ```no_run
/// use inkwell::context::Context;
///
/// let context = Context::create();
/// let module = context.create_module("av");
/// let void_type = context.void_type();
/// let i32_type = context.i32_type();
/// let i32_zero = i32_type.const_int(0, false);
/// let i32_seven = i32_type.const_int(7, false);
/// let vec_type = i32_type.vec_type(2);
/// let fn_type = void_type.fn_type(&[vec_type.into()], false);
/// let fn_value = module.add_function("vec_fn", fn_type, None);
/// let builder = context.create_builder();
/// let entry = context.append_basic_block(fn_value, "entry");
/// let vector_param = fn_value.get_first_param().unwrap().into_vector_value();
///
/// builder.position_at_end(entry);
/// builder.build_insert_element(vector_param, i32_seven, i32_zero, "insert").unwrap();
/// builder.build_return(None).unwrap();
/// ```
pub fn build_insert_element<V: BasicValue<'ctx>>(
&self,
vector: VectorValue<'ctx>,
element: V,
index: IntValue<'ctx>,
name: &str,
) -> Result<VectorValue<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe {
LLVMBuildInsertElement(
self.builder,
vector.as_value_ref(),
element.as_value_ref(),
index.as_value_ref(),
c_string.as_ptr(),
)
};
unsafe { Ok(VectorValue::new(value)) }
}
pub fn build_unreachable(&self) -> Result<InstructionValue<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let val = unsafe { LLVMBuildUnreachable(self.builder) };
unsafe { Ok(InstructionValue::new(val)) }
}
// REVIEW: Not sure if this should return InstructionValue or an actual value
// TODO: Better name for num?
pub fn build_fence(
&self,
atomic_ordering: AtomicOrdering,
num: i32,
name: &str,
) -> Result<InstructionValue<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let val = unsafe { LLVMBuildFence(self.builder, atomic_ordering.into(), num, c_string.as_ptr()) };
unsafe { Ok(InstructionValue::new(val)) }
}
// SubType: <P>(&self, ptr: &PointerValue<P>, name) -> IntValue<bool> {
pub fn build_is_null<T: PointerMathValue<'ctx>>(
&self,
ptr: T,
name: &str,
) -> Result<<<T::BaseType as PointerMathType<'ctx>>::PtrConvType as IntMathType<'ctx>>::ValueType, BuilderError>
{
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let val = unsafe { LLVMBuildIsNull(self.builder, ptr.as_value_ref(), c_string.as_ptr()) };
unsafe { Ok(<<T::BaseType as PointerMathType>::PtrConvType as IntMathType>::ValueType::new(val)) }
}
// SubType: <P>(&self, ptr: &PointerValue<P>, name) -> IntValue<bool> {
pub fn build_is_not_null<T: PointerMathValue<'ctx>>(
&self,
ptr: T,
name: &str,
) -> Result<<<T::BaseType as PointerMathType<'ctx>>::PtrConvType as IntMathType<'ctx>>::ValueType, BuilderError>
{
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let val = unsafe { LLVMBuildIsNotNull(self.builder, ptr.as_value_ref(), c_string.as_ptr()) };
unsafe { Ok(<<T::BaseType as PointerMathType>::PtrConvType as IntMathType>::ValueType::new(val)) }
}
// SubType: <I, P>(&self, int: &IntValue<I>, ptr_type: &PointerType<P>, name) -> PointerValue<P> {
pub fn build_int_to_ptr<T: IntMathValue<'ctx>>(
&self,
int: T,
ptr_type: <T::BaseType as IntMathType<'ctx>>::PtrConvType,
name: &str,
) -> Result<<<T::BaseType as IntMathType<'ctx>>::PtrConvType as PointerMathType<'ctx>>::ValueType, BuilderError>
{
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe {
LLVMBuildIntToPtr(
self.builder,
int.as_value_ref(),
ptr_type.as_type_ref(),
c_string.as_ptr(),
)
};
unsafe { Ok(<<T::BaseType as IntMathType>::PtrConvType as PointerMathType>::ValueType::new(value)) }
}
// SubType: <I, P>(&self, ptr: &PointerValue<P>, int_type: &IntType<I>, name) -> IntValue<I> {
pub fn build_ptr_to_int<T: PointerMathValue<'ctx>>(
&self,
ptr: T,
int_type: <T::BaseType as PointerMathType<'ctx>>::PtrConvType,
name: &str,
) -> Result<<<T::BaseType as PointerMathType<'ctx>>::PtrConvType as IntMathType<'ctx>>::ValueType, BuilderError>
{
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe {
LLVMBuildPtrToInt(
self.builder,
ptr.as_value_ref(),
int_type.as_type_ref(),
c_string.as_ptr(),
)
};
unsafe { Ok(<<T::BaseType as PointerMathType>::PtrConvType as IntMathType>::ValueType::new(value)) }
}
pub fn clear_insertion_position(&self) {
unsafe { LLVMClearInsertionPosition(self.builder) }
}
// REVIEW: Returning InstructionValue is the safe move here; but if the value means something
// (IE the result of the switch) it should probably return BasicValueEnum?
// SubTypes: I think value and case values must be the same subtype (maybe). Case value might need to be constants
pub fn build_switch(
&self,
value: IntValue<'ctx>,
else_block: BasicBlock<'ctx>,
cases: &[(IntValue<'ctx>, BasicBlock<'ctx>)],
) -> Result<InstructionValue<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let switch_value = unsafe {
LLVMBuildSwitch(
self.builder,
value.as_value_ref(),
else_block.basic_block,
cases.len() as u32,
)
};
for &(value, basic_block) in cases {
unsafe { LLVMAddCase(switch_value, value.as_value_ref(), basic_block.basic_block) }
}
unsafe { Ok(InstructionValue::new(switch_value)) }
}
// SubTypes: condition can only be IntValue<bool> or VectorValue<IntValue<Bool>>
pub fn build_select<BV: BasicValue<'ctx>, IMV: IntMathValue<'ctx>>(
&self,
condition: IMV,
then: BV,
else_: BV,
name: &str,
) -> Result<BasicValueEnum<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe {
LLVMBuildSelect(
self.builder,
condition.as_value_ref(),
then.as_value_ref(),
else_.as_value_ref(),
c_string.as_ptr(),
)
};
unsafe { Ok(BasicValueEnum::new(value)) }
}
// The unsafety of this function should be fixable with subtypes. See GH #32
pub unsafe fn build_global_string(&self, value: &str, name: &str) -> Result<GlobalValue<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string_value = to_c_str(value);
let c_string_name = to_c_str(name);
let value = LLVMBuildGlobalString(self.builder, c_string_value.as_ptr(), c_string_name.as_ptr());
Ok(GlobalValue::new(value))
}
// REVIEW: Does this similar fn have the same issue build_global_string does? If so, mark as unsafe
// and fix with subtypes.
pub fn build_global_string_ptr(&self, value: &str, name: &str) -> Result<GlobalValue<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string_value = to_c_str(value);
let c_string_name = to_c_str(name);
let value = unsafe { LLVMBuildGlobalStringPtr(self.builder, c_string_value.as_ptr(), c_string_name.as_ptr()) };
unsafe { Ok(GlobalValue::new(value)) }
}
// REVIEW: Do we need to constrain types here? subtypes?
pub fn build_shuffle_vector(
&self,
left: VectorValue<'ctx>,
right: VectorValue<'ctx>,
mask: VectorValue<'ctx>,
name: &str,
) -> Result<VectorValue<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe {
LLVMBuildShuffleVector(
self.builder,
left.as_value_ref(),
right.as_value_ref(),
mask.as_value_ref(),
c_string.as_ptr(),
)
};
unsafe { Ok(VectorValue::new(value)) }
}
// REVIEW: Is return type correct?
// SubTypes: I think this should be type: BT -> BT::Value
// https://llvm.org/docs/LangRef.html#i-va-arg
pub fn build_va_arg<BT: BasicType<'ctx>>(
&self,
list: PointerValue<'ctx>,
type_: BT,
name: &str,
) -> Result<BasicValueEnum<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let c_string = to_c_str(name);
let value = unsafe {
LLVMBuildVAArg(
self.builder,
list.as_value_ref(),
type_.as_type_ref(),
c_string.as_ptr(),
)
};
unsafe { Ok(BasicValueEnum::new(value)) }
}
/// Builds an atomicrmw instruction. It allows you to atomically modify memory.
///
/// May return of the following errors:
/// - `Err(BuilderError::BitwidthError)` if the bitwidth of the value is not a power of 2 and less than 8
/// - `Err(BuilderError:PointeeTypeMismatch)` if the pointee type does not match the value's type
///
/// # Example
///
/// ```
/// use inkwell::context::Context;
/// use inkwell::{AddressSpace, AtomicOrdering, AtomicRMWBinOp};
/// let context = Context::create();
/// let module = context.create_module("rmw");
/// let void_type = context.void_type();
/// let i32_type = context.i32_type();
/// let i32_seven = i32_type.const_int(7, false);
/// #[cfg(not(any(feature = "llvm15-0", feature = "llvm16-0", feature = "llvm17-0", feature = "llvm18-0")))]
/// let i32_ptr_type = i32_type.ptr_type(AddressSpace::default());
/// #[cfg(any(feature = "llvm15-0", feature = "llvm16-0", feature = "llvm17-0", feature = "llvm18-0"))]
/// let i32_ptr_type = context.ptr_type(AddressSpace::default());
/// let fn_type = void_type.fn_type(&[i32_ptr_type.into()], false);
/// let fn_value = module.add_function("rmw", fn_type, None);
/// let entry = context.append_basic_block(fn_value, "entry");
/// let i32_ptr_param = fn_value.get_first_param().unwrap().into_pointer_value();
/// let builder = context.create_builder();
/// builder.position_at_end(entry);
/// builder.build_atomicrmw(AtomicRMWBinOp::Add, i32_ptr_param, i32_seven, AtomicOrdering::Unordered).unwrap();
/// builder.build_return(None).unwrap();
/// ```
// https://llvm.org/docs/LangRef.html#atomicrmw-instruction
pub fn build_atomicrmw(
&self,
op: AtomicRMWBinOp,
ptr: PointerValue<'ctx>,
value: IntValue<'ctx>,
ordering: AtomicOrdering,
) -> Result<IntValue<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
// TODO: add support for fadd, fsub and xchg on floating point types in LLVM 9+.
// "The type of ‘<value>’ must be an integer type whose bit width is a power of two greater than or equal to eight and less than or equal to a target-specific size limit. The type of the ‘<pointer>’ operand must be a pointer to that type." -- https://releases.llvm.org/3.6.2/docs/LangRef.html#atomicrmw-instruction
if value.get_type().get_bit_width() < 8 || !value.get_type().get_bit_width().is_power_of_two() {
return Err(BuilderError::BitwidthError(
"The bitwidth of value must be a power of 2 and greater than 8.",
));
}
#[cfg(not(any(
feature = "llvm15-0",
feature = "llvm16-0",
feature = "llvm17-0",
feature = "llvm18-0"
)))]
if ptr.get_type().get_element_type() != value.get_type().into() {
return Err(BuilderError::PointeeTypeMismatch(
"Pointer's pointee type must match the value's type.",
));
}
let val = unsafe {
LLVMBuildAtomicRMW(
self.builder,
op.into(),
ptr.as_value_ref(),
value.as_value_ref(),
ordering.into(),
false as i32,
)
};
unsafe { Ok(IntValue::new(val)) }
}
/// Builds a cmpxchg instruction. It allows you to atomically compare and replace memory.
///
/// May return one of the following errors:
/// - `Err(BuilderError::PointeeTypeMismatch)` if the pointer does not point to an element of the value type
/// - `Err(BuilderError::ValueTypeMismatch)` if the value to compare and the new values are not of the same type, or if
/// the value does not have a pointer or integer type
/// - `Err(BuilderError::OrderingError)` if the following conditions are not satisfied:
/// - Both success and failure orderings are not Monotonic or stronger
/// - The failure ordering is stronger than the success ordering
/// - The failure ordering is release or acquire release
///
/// # Example
///
/// ```
/// use inkwell::context::Context;
/// use inkwell::{AddressSpace, AtomicOrdering};
/// let context = Context::create();
/// let module = context.create_module("cmpxchg");
/// let void_type = context.void_type();
/// let i32_type = context.i32_type();
/// #[cfg(not(any(feature = "llvm15-0", feature = "llvm16-0", feature = "llvm17-0", feature = "llvm18-0")))]
/// let i32_ptr_type = i32_type.ptr_type(AddressSpace::default());
/// #[cfg(any(feature = "llvm15-0", feature = "llvm16-0", feature = "llvm17-0", feature = "llvm18-0"))]
/// let i32_ptr_type = context.ptr_type(AddressSpace::default());
/// let fn_type = void_type.fn_type(&[i32_ptr_type.into()], false);
/// let fn_value = module.add_function("", fn_type, None);
/// let i32_ptr_param = fn_value.get_first_param().unwrap().into_pointer_value();
/// let i32_seven = i32_type.const_int(7, false);
/// let i32_eight = i32_type.const_int(8, false);
/// let entry = context.append_basic_block(fn_value, "entry");
/// let builder = context.create_builder();
/// builder.position_at_end(entry);
/// builder.build_cmpxchg(i32_ptr_param, i32_seven, i32_eight, AtomicOrdering::AcquireRelease, AtomicOrdering::Monotonic).unwrap();
/// builder.build_return(None).unwrap();
/// ```
// https://llvm.org/docs/LangRef.html#cmpxchg-instruction
pub fn build_cmpxchg<V: BasicValue<'ctx>>(
&self,
ptr: PointerValue<'ctx>,
cmp: V,
new: V,
success: AtomicOrdering,
failure: AtomicOrdering,
) -> Result<StructValue<'ctx>, BuilderError> {
if self.positioned.get() != PositionState::Set {
return Err(BuilderError::UnsetPosition);
}
let cmp = cmp.as_basic_value_enum();
let new = new.as_basic_value_enum();
if cmp.get_type() != new.get_type() {
return Err(BuilderError::ValueTypeMismatch(
"The value to compare against and the value to replace with must have the same type.",
));
}
if !cmp.is_int_value() && !cmp.is_pointer_value() {
return Err(BuilderError::ValueTypeMismatch(
"The values must have pointer or integer type.",
));
}
#[cfg(not(any(
feature = "llvm15-0",
feature = "llvm16-0",
feature = "llvm17-0",
feature = "llvm18-0"
)))]
if ptr.get_type().get_element_type().to_basic_type_enum() != cmp.get_type() {
return Err(BuilderError::PointeeTypeMismatch(
"The pointer does not point to an element of the value type.",
));
}
// "Both ordering parameters must be at least monotonic, the ordering constraint on failure must be no stronger than that on success, and the failure ordering cannot be either release or acq_rel." -- https://llvm.org/docs/LangRef.html#cmpxchg-instruction
if success < AtomicOrdering::Monotonic || failure < AtomicOrdering::Monotonic {
return Err(BuilderError::OrderingError(
"Both success and failure orderings must be Monotonic or stronger.",
));
}
if failure > success {
return Err(BuilderError::OrderingError(
"The failure ordering may not be stronger than the success ordering.",
));
}
if failure == AtomicOrdering::Release || failure == AtomicOrdering::AcquireRelease {
return Err(BuilderError::OrderingError(
"The failure ordering may not be release or acquire release.",
));
}
let val = unsafe {
LLVMBuildAtomicCmpXchg(
self.builder,
ptr.as_value_ref(),
cmp.as_value_ref(),
new.as_value_ref(),
success.into(),
failure.into(),
false as i32,
)
};
unsafe { Ok(StructValue::new(val)) }
}
/// Set the debug info source location of the instruction currently pointed at by the builder
#[llvm_versions(7.0..=8.0)]
pub fn set_current_debug_location(&self, context: impl AsContextRef<'ctx>, location: DILocation<'ctx>) {
use llvm_sys::core::LLVMMetadataAsValue;
use llvm_sys::core::LLVMSetCurrentDebugLocation;
unsafe {
LLVMSetCurrentDebugLocation(
self.builder,
LLVMMetadataAsValue(context.as_ctx_ref(), location.metadata_ref),
);
}
}
/// Set the debug info source location of the instruction currently pointed at by the builder
#[llvm_versions(9.0..=latest)]
pub fn set_current_debug_location(&self, location: DILocation<'ctx>) {
use llvm_sys::core::LLVMSetCurrentDebugLocation2;
unsafe {
LLVMSetCurrentDebugLocation2(self.builder, location.metadata_ref);
}
}
/// Get the debug info source location of the instruction currently pointed at by the builder,
/// if available.
#[llvm_versions(7.0..=latest)]
pub fn get_current_debug_location(&self) -> Option<DILocation<'ctx>> {
use llvm_sys::core::LLVMGetCurrentDebugLocation;
use llvm_sys::core::LLVMValueAsMetadata;
let metadata_ref = unsafe { LLVMGetCurrentDebugLocation(self.builder) };
if metadata_ref.is_null() {
return None;
}
Some(DILocation {
metadata_ref: unsafe { LLVMValueAsMetadata(metadata_ref) },
_marker: PhantomData,
})
}
/// Unset the debug info source location of the instruction currently pointed at by the
/// builder. If there isn't any debug info, this is a no-op.
#[llvm_versions(7.0..=8.0)]
pub fn unset_current_debug_location(&self) {
use llvm_sys::core::LLVMSetCurrentDebugLocation;
unsafe {
LLVMSetCurrentDebugLocation(self.builder, std::ptr::null_mut());
}
}
/// Unset the debug info source location of the instruction currently pointed at by the
/// builder. If there isn't any debug info, this is a no-op.
#[llvm_versions(9.0..=latest)]
pub fn unset_current_debug_location(&self) {
use llvm_sys::core::LLVMSetCurrentDebugLocation2;
unsafe {
LLVMSetCurrentDebugLocation2(self.builder, std::ptr::null_mut());
}
}
}
/// Used by build_memcpy and build_memmove
#[llvm_versions(8.0..=latest)]
fn is_alignment_ok(align: u32) -> bool {
// This replicates the assertions LLVM runs.
//
// See https://github.com/TheDan64/inkwell/issues/168
align > 0 && align.is_power_of_two() && (align as f64).log2() < 64.0
}
impl Drop for Builder<'_> {
fn drop(&mut self) {
unsafe {
LLVMDisposeBuilder(self.builder);
}
}
}