isl_map_simplify.c 144 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219
/*
 * Copyright 2008-2009 Katholieke Universiteit Leuven
 * Copyright 2012-2013 Ecole Normale Superieure
 * Copyright 2014-2015 INRIA Rocquencourt
 * Copyright 2016      Sven Verdoolaege
 *
 * Use of this software is governed by the MIT license
 *
 * Written by Sven Verdoolaege, K.U.Leuven, Departement
 * Computerwetenschappen, Celestijnenlaan 200A, B-3001 Leuven, Belgium
 * and Ecole Normale Superieure, 45 rue d’Ulm, 75230 Paris, France
 * and Inria Paris - Rocquencourt, Domaine de Voluceau - Rocquencourt,
 * B.P. 105 - 78153 Le Chesnay, France
 */

#include <isl_ctx_private.h>
#include <isl_map_private.h>
#include "isl_equalities.h"
#include <isl/map.h>
#include <isl_seq.h>
#include "isl_tab.h"
#include <isl_space_private.h>
#include <isl_mat_private.h>
#include <isl_vec_private.h>

#include <bset_to_bmap.c>
#include <bset_from_bmap.c>
#include <set_to_map.c>
#include <set_from_map.c>

static void swap_equality(struct isl_basic_map *bmap, int a, int b)
{
	isl_int *t = bmap->eq[a];
	bmap->eq[a] = bmap->eq[b];
	bmap->eq[b] = t;
}

static void swap_inequality(struct isl_basic_map *bmap, int a, int b)
{
	if (a != b) {
		isl_int *t = bmap->ineq[a];
		bmap->ineq[a] = bmap->ineq[b];
		bmap->ineq[b] = t;
	}
}

__isl_give isl_basic_map *isl_basic_map_normalize_constraints(
	__isl_take isl_basic_map *bmap)
{
	int i;
	isl_int gcd;
	unsigned total = isl_basic_map_total_dim(bmap);

	if (!bmap)
		return NULL;

	isl_int_init(gcd);
	for (i = bmap->n_eq - 1; i >= 0; --i) {
		isl_seq_gcd(bmap->eq[i]+1, total, &gcd);
		if (isl_int_is_zero(gcd)) {
			if (!isl_int_is_zero(bmap->eq[i][0])) {
				bmap = isl_basic_map_set_to_empty(bmap);
				break;
			}
			isl_basic_map_drop_equality(bmap, i);
			continue;
		}
		if (ISL_F_ISSET(bmap, ISL_BASIC_MAP_RATIONAL))
			isl_int_gcd(gcd, gcd, bmap->eq[i][0]);
		if (isl_int_is_one(gcd))
			continue;
		if (!isl_int_is_divisible_by(bmap->eq[i][0], gcd)) {
			bmap = isl_basic_map_set_to_empty(bmap);
			break;
		}
		isl_seq_scale_down(bmap->eq[i], bmap->eq[i], gcd, 1+total);
	}

	for (i = bmap->n_ineq - 1; i >= 0; --i) {
		isl_seq_gcd(bmap->ineq[i]+1, total, &gcd);
		if (isl_int_is_zero(gcd)) {
			if (isl_int_is_neg(bmap->ineq[i][0])) {
				bmap = isl_basic_map_set_to_empty(bmap);
				break;
			}
			isl_basic_map_drop_inequality(bmap, i);
			continue;
		}
		if (ISL_F_ISSET(bmap, ISL_BASIC_MAP_RATIONAL))
			isl_int_gcd(gcd, gcd, bmap->ineq[i][0]);
		if (isl_int_is_one(gcd))
			continue;
		isl_int_fdiv_q(bmap->ineq[i][0], bmap->ineq[i][0], gcd);
		isl_seq_scale_down(bmap->ineq[i]+1, bmap->ineq[i]+1, gcd, total);
	}
	isl_int_clear(gcd);

	return bmap;
}

__isl_give isl_basic_set *isl_basic_set_normalize_constraints(
	__isl_take isl_basic_set *bset)
{
	isl_basic_map *bmap = bset_to_bmap(bset);
	return bset_from_bmap(isl_basic_map_normalize_constraints(bmap));
}

/* Reduce the coefficient of the variable at position "pos"
 * in integer division "div", such that it lies in the half-open
 * interval (1/2,1/2], extracting any excess value from this integer division.
 * "pos" is as determined by isl_basic_map_offset, i.e., pos == 0
 * corresponds to the constant term.
 *
 * That is, the integer division is of the form
 *
 *	floor((... + (c * d + r) * x_pos + ...)/d)
 *
 * with -d < 2 * r <= d.
 * Replace it by
 *
 *	floor((... + r * x_pos + ...)/d) + c * x_pos
 *
 * If 2 * ((c * d + r) % d) <= d, then c = floor((c * d + r)/d).
 * Otherwise, c = floor((c * d + r)/d) + 1.
 *
 * This is the same normalization that is performed by isl_aff_floor.
 */
static __isl_give isl_basic_map *reduce_coefficient_in_div(
	__isl_take isl_basic_map *bmap, int div, int pos)
{
	isl_int shift;
	int add_one;

	isl_int_init(shift);
	isl_int_fdiv_r(shift, bmap->div[div][1 + pos], bmap->div[div][0]);
	isl_int_mul_ui(shift, shift, 2);
	add_one = isl_int_gt(shift, bmap->div[div][0]);
	isl_int_fdiv_q(shift, bmap->div[div][1 + pos], bmap->div[div][0]);
	if (add_one)
		isl_int_add_ui(shift, shift, 1);
	isl_int_neg(shift, shift);
	bmap = isl_basic_map_shift_div(bmap, div, pos, shift);
	isl_int_clear(shift);

	return bmap;
}

/* Does the coefficient of the variable at position "pos"
 * in integer division "div" need to be reduced?
 * That is, does it lie outside the half-open interval (1/2,1/2]?
 * The coefficient c/d lies outside this interval if abs(2 * c) >= d and
 * 2 * c != d.
 */
static isl_bool needs_reduction(__isl_keep isl_basic_map *bmap, int div,
	int pos)
{
	isl_bool r;

	if (isl_int_is_zero(bmap->div[div][1 + pos]))
		return isl_bool_false;

	isl_int_mul_ui(bmap->div[div][1 + pos], bmap->div[div][1 + pos], 2);
	r = isl_int_abs_ge(bmap->div[div][1 + pos], bmap->div[div][0]) &&
	    !isl_int_eq(bmap->div[div][1 + pos], bmap->div[div][0]);
	isl_int_divexact_ui(bmap->div[div][1 + pos],
			    bmap->div[div][1 + pos], 2);

	return r;
}

/* Reduce the coefficients (including the constant term) of
 * integer division "div", if needed.
 * In particular, make sure all coefficients lie in
 * the half-open interval (1/2,1/2].
 */
static __isl_give isl_basic_map *reduce_div_coefficients_of_div(
	__isl_take isl_basic_map *bmap, int div)
{
	int i;
	unsigned total = 1 + isl_basic_map_total_dim(bmap);

	for (i = 0; i < total; ++i) {
		isl_bool reduce;

		reduce = needs_reduction(bmap, div, i);
		if (reduce < 0)
			return isl_basic_map_free(bmap);
		if (!reduce)
			continue;
		bmap = reduce_coefficient_in_div(bmap, div, i);
		if (!bmap)
			break;
	}

	return bmap;
}

/* Reduce the coefficients (including the constant term) of
 * the known integer divisions, if needed
 * In particular, make sure all coefficients lie in
 * the half-open interval (1/2,1/2].
 */
static __isl_give isl_basic_map *reduce_div_coefficients(
	__isl_take isl_basic_map *bmap)
{
	int i;

	if (!bmap)
		return NULL;
	if (bmap->n_div == 0)
		return bmap;

	for (i = 0; i < bmap->n_div; ++i) {
		if (isl_int_is_zero(bmap->div[i][0]))
			continue;
		bmap = reduce_div_coefficients_of_div(bmap, i);
		if (!bmap)
			break;
	}

	return bmap;
}

/* Remove any common factor in numerator and denominator of the div expression,
 * not taking into account the constant term.
 * That is, if the div is of the form
 *
 *	floor((a + m f(x))/(m d))
 *
 * then replace it by
 *
 *	floor((floor(a/m) + f(x))/d)
 *
 * The difference {a/m}/d in the argument satisfies 0 <= {a/m}/d < 1/d
 * and can therefore not influence the result of the floor.
 */
static void normalize_div_expression(__isl_keep isl_basic_map *bmap, int div)
{
	unsigned total = isl_basic_map_total_dim(bmap);
	isl_ctx *ctx = bmap->ctx;

	if (isl_int_is_zero(bmap->div[div][0]))
		return;
	isl_seq_gcd(bmap->div[div] + 2, total, &ctx->normalize_gcd);
	isl_int_gcd(ctx->normalize_gcd, ctx->normalize_gcd, bmap->div[div][0]);
	if (isl_int_is_one(ctx->normalize_gcd))
		return;
	isl_int_fdiv_q(bmap->div[div][1], bmap->div[div][1],
			ctx->normalize_gcd);
	isl_int_divexact(bmap->div[div][0], bmap->div[div][0],
			ctx->normalize_gcd);
	isl_seq_scale_down(bmap->div[div] + 2, bmap->div[div] + 2,
			ctx->normalize_gcd, total);
}

/* Remove any common factor in numerator and denominator of a div expression,
 * not taking into account the constant term.
 * That is, look for any div of the form
 *
 *	floor((a + m f(x))/(m d))
 *
 * and replace it by
 *
 *	floor((floor(a/m) + f(x))/d)
 *
 * The difference {a/m}/d in the argument satisfies 0 <= {a/m}/d < 1/d
 * and can therefore not influence the result of the floor.
 */
static __isl_give isl_basic_map *normalize_div_expressions(
	__isl_take isl_basic_map *bmap)
{
	int i;

	if (!bmap)
		return NULL;
	if (bmap->n_div == 0)
		return bmap;

	for (i = 0; i < bmap->n_div; ++i)
		normalize_div_expression(bmap, i);

	return bmap;
}

/* Assumes divs have been ordered if keep_divs is set.
 */
static void eliminate_var_using_equality(struct isl_basic_map *bmap,
	unsigned pos, isl_int *eq, int keep_divs, int *progress)
{
	unsigned total;
	unsigned space_total;
	int k;
	int last_div;

	total = isl_basic_map_total_dim(bmap);
	space_total = isl_space_dim(bmap->dim, isl_dim_all);
	last_div = isl_seq_last_non_zero(eq + 1 + space_total, bmap->n_div);
	for (k = 0; k < bmap->n_eq; ++k) {
		if (bmap->eq[k] == eq)
			continue;
		if (isl_int_is_zero(bmap->eq[k][1+pos]))
			continue;
		if (progress)
			*progress = 1;
		isl_seq_elim(bmap->eq[k], eq, 1+pos, 1+total, NULL);
		isl_seq_normalize(bmap->ctx, bmap->eq[k], 1 + total);
	}

	for (k = 0; k < bmap->n_ineq; ++k) {
		if (isl_int_is_zero(bmap->ineq[k][1+pos]))
			continue;
		if (progress)
			*progress = 1;
		isl_seq_elim(bmap->ineq[k], eq, 1+pos, 1+total, NULL);
		isl_seq_normalize(bmap->ctx, bmap->ineq[k], 1 + total);
		ISL_F_CLR(bmap, ISL_BASIC_MAP_NORMALIZED);
	}

	for (k = 0; k < bmap->n_div; ++k) {
		if (isl_int_is_zero(bmap->div[k][0]))
			continue;
		if (isl_int_is_zero(bmap->div[k][1+1+pos]))
			continue;
		if (progress)
			*progress = 1;
		/* We need to be careful about circular definitions,
		 * so for now we just remove the definition of div k
		 * if the equality contains any divs.
		 * If keep_divs is set, then the divs have been ordered
		 * and we can keep the definition as long as the result
		 * is still ordered.
		 */
		if (last_div == -1 || (keep_divs && last_div < k)) {
			isl_seq_elim(bmap->div[k]+1, eq,
					1+pos, 1+total, &bmap->div[k][0]);
			normalize_div_expression(bmap, k);
		} else
			isl_seq_clr(bmap->div[k], 1 + total);
		ISL_F_CLR(bmap, ISL_BASIC_MAP_NORMALIZED);
	}
}

/* Assumes divs have been ordered if keep_divs is set.
 */
static __isl_give isl_basic_map *eliminate_div(__isl_take isl_basic_map *bmap,
	isl_int *eq, unsigned div, int keep_divs)
{
	unsigned pos = isl_space_dim(bmap->dim, isl_dim_all) + div;

	eliminate_var_using_equality(bmap, pos, eq, keep_divs, NULL);

	bmap = isl_basic_map_drop_div(bmap, div);

	return bmap;
}

/* Check if elimination of div "div" using equality "eq" would not
 * result in a div depending on a later div.
 */
static isl_bool ok_to_eliminate_div(__isl_keep isl_basic_map *bmap, isl_int *eq,
	unsigned div)
{
	int k;
	int last_div;
	unsigned space_total = isl_space_dim(bmap->dim, isl_dim_all);
	unsigned pos = space_total + div;

	last_div = isl_seq_last_non_zero(eq + 1 + space_total, bmap->n_div);
	if (last_div < 0 || last_div <= div)
		return isl_bool_true;

	for (k = 0; k <= last_div; ++k) {
		if (isl_int_is_zero(bmap->div[k][0]))
			continue;
		if (!isl_int_is_zero(bmap->div[k][1 + 1 + pos]))
			return isl_bool_false;
	}

	return isl_bool_true;
}

/* Eliminate divs based on equalities
 */
static __isl_give isl_basic_map *eliminate_divs_eq(
	__isl_take isl_basic_map *bmap, int *progress)
{
	int d;
	int i;
	int modified = 0;
	unsigned off;

	bmap = isl_basic_map_order_divs(bmap);

	if (!bmap)
		return NULL;

	off = 1 + isl_space_dim(bmap->dim, isl_dim_all);

	for (d = bmap->n_div - 1; d >= 0 ; --d) {
		for (i = 0; i < bmap->n_eq; ++i) {
			isl_bool ok;

			if (!isl_int_is_one(bmap->eq[i][off + d]) &&
			    !isl_int_is_negone(bmap->eq[i][off + d]))
				continue;
			ok = ok_to_eliminate_div(bmap, bmap->eq[i], d);
			if (ok < 0)
				return isl_basic_map_free(bmap);
			if (!ok)
				continue;
			modified = 1;
			*progress = 1;
			bmap = eliminate_div(bmap, bmap->eq[i], d, 1);
			if (isl_basic_map_drop_equality(bmap, i) < 0)
				return isl_basic_map_free(bmap);
			break;
		}
	}
	if (modified)
		return eliminate_divs_eq(bmap, progress);
	return bmap;
}

/* Eliminate divs based on inequalities
 */
static __isl_give isl_basic_map *eliminate_divs_ineq(
	__isl_take isl_basic_map *bmap, int *progress)
{
	int d;
	int i;
	unsigned off;
	struct isl_ctx *ctx;

	if (!bmap)
		return NULL;

	ctx = bmap->ctx;
	off = 1 + isl_space_dim(bmap->dim, isl_dim_all);

	for (d = bmap->n_div - 1; d >= 0 ; --d) {
		for (i = 0; i < bmap->n_eq; ++i)
			if (!isl_int_is_zero(bmap->eq[i][off + d]))
				break;
		if (i < bmap->n_eq)
			continue;
		for (i = 0; i < bmap->n_ineq; ++i)
			if (isl_int_abs_gt(bmap->ineq[i][off + d], ctx->one))
				break;
		if (i < bmap->n_ineq)
			continue;
		*progress = 1;
		bmap = isl_basic_map_eliminate_vars(bmap, (off-1)+d, 1);
		if (!bmap || ISL_F_ISSET(bmap, ISL_BASIC_MAP_EMPTY))
			break;
		bmap = isl_basic_map_drop_div(bmap, d);
		if (!bmap)
			break;
	}
	return bmap;
}

/* Does the equality constraint at position "eq" in "bmap" involve
 * any local variables in the range [first, first + n)
 * that are not marked as having an explicit representation?
 */
static isl_bool bmap_eq_involves_unknown_divs(__isl_keep isl_basic_map *bmap,
	int eq, unsigned first, unsigned n)
{
	unsigned o_div;
	int i;

	if (!bmap)
		return isl_bool_error;

	o_div = isl_basic_map_offset(bmap, isl_dim_div);
	for (i = 0; i < n; ++i) {
		isl_bool unknown;

		if (isl_int_is_zero(bmap->eq[eq][o_div + first + i]))
			continue;
		unknown = isl_basic_map_div_is_marked_unknown(bmap, first + i);
		if (unknown < 0)
			return isl_bool_error;
		if (unknown)
			return isl_bool_true;
	}

	return isl_bool_false;
}

/* The last local variable involved in the equality constraint
 * at position "eq" in "bmap" is the local variable at position "div".
 * It can therefore be used to extract an explicit representation
 * for that variable.
 * Do so unless the local variable already has an explicit representation or
 * the explicit representation would involve any other local variables
 * that in turn do not have an explicit representation.
 * An equality constraint involving local variables without an explicit
 * representation can be used in isl_basic_map_drop_redundant_divs
 * to separate out an independent local variable.  Introducing
 * an explicit representation here would block this transformation,
 * while the partial explicit representation in itself is not very useful.
 * Set *progress if anything is changed.
 *
 * The equality constraint is of the form
 *
 *	f(x) + n e >= 0
 *
 * with n a positive number.  The explicit representation derived from
 * this constraint is
 *
 *	floor((-f(x))/n)
 */
static __isl_give isl_basic_map *set_div_from_eq(__isl_take isl_basic_map *bmap,
	int div, int eq, int *progress)
{
	unsigned total, o_div;
	isl_bool involves;

	if (!bmap)
		return NULL;

	if (!isl_int_is_zero(bmap->div[div][0]))
		return bmap;

	involves = bmap_eq_involves_unknown_divs(bmap, eq, 0, div);
	if (involves < 0)
		return isl_basic_map_free(bmap);
	if (involves)
		return bmap;

	total = isl_basic_map_dim(bmap, isl_dim_all);
	o_div = isl_basic_map_offset(bmap, isl_dim_div);
	isl_seq_neg(bmap->div[div] + 1, bmap->eq[eq], 1 + total);
	isl_int_set_si(bmap->div[div][1 + o_div + div], 0);
	isl_int_set(bmap->div[div][0], bmap->eq[eq][o_div + div]);
	if (progress)
		*progress = 1;
	ISL_F_CLR(bmap, ISL_BASIC_MAP_NORMALIZED);

	return bmap;
}

__isl_give isl_basic_map *isl_basic_map_gauss(__isl_take isl_basic_map *bmap,
	int *progress)
{
	int k;
	int done;
	int last_var;
	unsigned total_var;
	unsigned total;

	bmap = isl_basic_map_order_divs(bmap);

	if (!bmap)
		return NULL;

	total = isl_basic_map_total_dim(bmap);
	total_var = total - bmap->n_div;

	last_var = total - 1;
	for (done = 0; done < bmap->n_eq; ++done) {
		for (; last_var >= 0; --last_var) {
			for (k = done; k < bmap->n_eq; ++k)
				if (!isl_int_is_zero(bmap->eq[k][1+last_var]))
					break;
			if (k < bmap->n_eq)
				break;
		}
		if (last_var < 0)
			break;
		if (k != done)
			swap_equality(bmap, k, done);
		if (isl_int_is_neg(bmap->eq[done][1+last_var]))
			isl_seq_neg(bmap->eq[done], bmap->eq[done], 1+total);

		eliminate_var_using_equality(bmap, last_var, bmap->eq[done], 1,
						progress);

		if (last_var >= total_var)
			bmap = set_div_from_eq(bmap, last_var - total_var,
						done, progress);
		if (!bmap)
			return NULL;
	}
	if (done == bmap->n_eq)
		return bmap;
	for (k = done; k < bmap->n_eq; ++k) {
		if (isl_int_is_zero(bmap->eq[k][0]))
			continue;
		return isl_basic_map_set_to_empty(bmap);
	}
	isl_basic_map_free_equality(bmap, bmap->n_eq-done);
	return bmap;
}

__isl_give isl_basic_set *isl_basic_set_gauss(
	__isl_take isl_basic_set *bset, int *progress)
{
	return bset_from_bmap(isl_basic_map_gauss(bset_to_bmap(bset),
							progress));
}


static unsigned int round_up(unsigned int v)
{
	int old_v = v;

	while (v) {
		old_v = v;
		v ^= v & -v;
	}
	return old_v << 1;
}

/* Hash table of inequalities in a basic map.
 * "index" is an array of addresses of inequalities in the basic map, some
 * of which are NULL.  The inequalities are hashed on the coefficients
 * except the constant term.
 * "size" is the number of elements in the array and is always a power of two
 * "bits" is the number of bits need to represent an index into the array.
 * "total" is the total dimension of the basic map.
 */
struct isl_constraint_index {
	unsigned int size;
	int bits;
	isl_int ***index;
	unsigned total;
};

/* Fill in the "ci" data structure for holding the inequalities of "bmap".
 */
static isl_stat create_constraint_index(struct isl_constraint_index *ci,
	__isl_keep isl_basic_map *bmap)
{
	isl_ctx *ctx;

	ci->index = NULL;
	if (!bmap)
		return isl_stat_error;
	ci->total = isl_basic_set_total_dim(bmap);
	if (bmap->n_ineq == 0)
		return isl_stat_ok;
	ci->size = round_up(4 * (bmap->n_ineq + 1) / 3 - 1);
	ci->bits = ffs(ci->size) - 1;
	ctx = isl_basic_map_get_ctx(bmap);
	ci->index = isl_calloc_array(ctx, isl_int **, ci->size);
	if (!ci->index)
		return isl_stat_error;

	return isl_stat_ok;
}

/* Free the memory allocated by create_constraint_index.
 */
static void constraint_index_free(struct isl_constraint_index *ci)
{
	free(ci->index);
}

/* Return the position in ci->index that contains the address of
 * an inequality that is equal to *ineq up to the constant term,
 * provided this address is not identical to "ineq".
 * If there is no such inequality, then return the position where
 * such an inequality should be inserted.
 */
static int hash_index_ineq(struct isl_constraint_index *ci, isl_int **ineq)
{
	int h;
	uint32_t hash = isl_seq_get_hash_bits((*ineq) + 1, ci->total, ci->bits);
	for (h = hash; ci->index[h]; h = (h+1) % ci->size)
		if (ineq != ci->index[h] &&
		    isl_seq_eq((*ineq) + 1, ci->index[h][0]+1, ci->total))
			break;
	return h;
}

/* Return the position in ci->index that contains the address of
 * an inequality that is equal to the k'th inequality of "bmap"
 * up to the constant term, provided it does not point to the very
 * same inequality.
 * If there is no such inequality, then return the position where
 * such an inequality should be inserted.
 */
static int hash_index(struct isl_constraint_index *ci,
	__isl_keep isl_basic_map *bmap, int k)
{
	return hash_index_ineq(ci, &bmap->ineq[k]);
}

static int set_hash_index(struct isl_constraint_index *ci,
	__isl_keep isl_basic_set *bset, int k)
{
	return hash_index(ci, bset, k);
}

/* Fill in the "ci" data structure with the inequalities of "bset".
 */
static isl_stat setup_constraint_index(struct isl_constraint_index *ci,
	__isl_keep isl_basic_set *bset)
{
	int k, h;

	if (create_constraint_index(ci, bset) < 0)
		return isl_stat_error;

	for (k = 0; k < bset->n_ineq; ++k) {
		h = set_hash_index(ci, bset, k);
		ci->index[h] = &bset->ineq[k];
	}

	return isl_stat_ok;
}

/* Is the inequality ineq (obviously) redundant with respect
 * to the constraints in "ci"?
 *
 * Look for an inequality in "ci" with the same coefficients and then
 * check if the contant term of "ineq" is greater than or equal
 * to the constant term of that inequality.  If so, "ineq" is clearly
 * redundant.
 *
 * Note that hash_index_ineq ignores a stored constraint if it has
 * the same address as the passed inequality.  It is ok to pass
 * the address of a local variable here since it will never be
 * the same as the address of a constraint in "ci".
 */
static isl_bool constraint_index_is_redundant(struct isl_constraint_index *ci,
	isl_int *ineq)
{
	int h;

	h = hash_index_ineq(ci, &ineq);
	if (!ci->index[h])
		return isl_bool_false;
	return isl_int_ge(ineq[0], (*ci->index[h])[0]);
}

/* If we can eliminate more than one div, then we need to make
 * sure we do it from last div to first div, in order not to
 * change the position of the other divs that still need to
 * be removed.
 */
static __isl_give isl_basic_map *remove_duplicate_divs(
	__isl_take isl_basic_map *bmap, int *progress)
{
	unsigned int size;
	int *index;
	int *elim_for;
	int k, l, h;
	int bits;
	struct isl_blk eq;
	unsigned total_var;
	unsigned total;
	struct isl_ctx *ctx;

	bmap = isl_basic_map_order_divs(bmap);
	if (!bmap || bmap->n_div <= 1)
		return bmap;

	total_var = isl_space_dim(bmap->dim, isl_dim_all);
	total = total_var + bmap->n_div;

	ctx = bmap->ctx;
	for (k = bmap->n_div - 1; k >= 0; --k)
		if (!isl_int_is_zero(bmap->div[k][0]))
			break;
	if (k <= 0)
		return bmap;

	size = round_up(4 * bmap->n_div / 3 - 1);
	if (size == 0)
		return bmap;
	elim_for = isl_calloc_array(ctx, int, bmap->n_div);
	bits = ffs(size) - 1;
	index = isl_calloc_array(ctx, int, size);
	if (!elim_for || !index)
		goto out;
	eq = isl_blk_alloc(ctx, 1+total);
	if (isl_blk_is_error(eq))
		goto out;

	isl_seq_clr(eq.data, 1+total);
	index[isl_seq_get_hash_bits(bmap->div[k], 2+total, bits)] = k + 1;
	for (--k; k >= 0; --k) {
		uint32_t hash;

		if (isl_int_is_zero(bmap->div[k][0]))
			continue;

		hash = isl_seq_get_hash_bits(bmap->div[k], 2+total, bits);
		for (h = hash; index[h]; h = (h+1) % size)
			if (isl_seq_eq(bmap->div[k],
				       bmap->div[index[h]-1], 2+total))
				break;
		if (index[h]) {
			*progress = 1;
			l = index[h] - 1;
			elim_for[l] = k + 1;
		}
		index[h] = k+1;
	}
	for (l = bmap->n_div - 1; l >= 0; --l) {
		if (!elim_for[l])
			continue;
		k = elim_for[l] - 1;
		isl_int_set_si(eq.data[1+total_var+k], -1);
		isl_int_set_si(eq.data[1+total_var+l], 1);
		bmap = eliminate_div(bmap, eq.data, l, 1);
		if (!bmap)
			break;
		isl_int_set_si(eq.data[1+total_var+k], 0);
		isl_int_set_si(eq.data[1+total_var+l], 0);
	}

	isl_blk_free(ctx, eq);
out:
	free(index);
	free(elim_for);
	return bmap;
}

static int n_pure_div_eq(struct isl_basic_map *bmap)
{
	int i, j;
	unsigned total;

	total = isl_space_dim(bmap->dim, isl_dim_all);
	for (i = 0, j = bmap->n_div-1; i < bmap->n_eq; ++i) {
		while (j >= 0 && isl_int_is_zero(bmap->eq[i][1 + total + j]))
			--j;
		if (j < 0)
			break;
		if (isl_seq_first_non_zero(bmap->eq[i] + 1 + total, j) != -1)
			return 0;
	}
	return i;
}

/* Normalize divs that appear in equalities.
 *
 * In particular, we assume that bmap contains some equalities
 * of the form
 *
 *	a x = m * e_i
 *
 * and we want to replace the set of e_i by a minimal set and
 * such that the new e_i have a canonical representation in terms
 * of the vector x.
 * If any of the equalities involves more than one divs, then
 * we currently simply bail out.
 *
 * Let us first additionally assume that all equalities involve
 * a div.  The equalities then express modulo constraints on the
 * remaining variables and we can use "parameter compression"
 * to find a minimal set of constraints.  The result is a transformation
 *
 *	x = T(x') = x_0 + G x'
 *
 * with G a lower-triangular matrix with all elements below the diagonal
 * non-negative and smaller than the diagonal element on the same row.
 * We first normalize x_0 by making the same property hold in the affine
 * T matrix.
 * The rows i of G with a 1 on the diagonal do not impose any modulo
 * constraint and simply express x_i = x'_i.
 * For each of the remaining rows i, we introduce a div and a corresponding
 * equality.  In particular
 *
 *	g_ii e_j = x_i - g_i(x')
 *
 * where each x'_k is replaced either by x_k (if g_kk = 1) or the
 * corresponding div (if g_kk != 1).
 *
 * If there are any equalities not involving any div, then we
 * first apply a variable compression on the variables x:
 *
 *	x = C x''	x'' = C_2 x
 *
 * and perform the above parameter compression on A C instead of on A.
 * The resulting compression is then of the form
 *
 *	x'' = T(x') = x_0 + G x'
 *
 * and in constructing the new divs and the corresponding equalities,
 * we have to replace each x'', i.e., the x'_k with (g_kk = 1),
 * by the corresponding row from C_2.
 */
static __isl_give isl_basic_map *normalize_divs(__isl_take isl_basic_map *bmap,
	int *progress)
{
	int i, j, k;
	int total;
	int div_eq;
	struct isl_mat *B;
	struct isl_vec *d;
	struct isl_mat *T = NULL;
	struct isl_mat *C = NULL;
	struct isl_mat *C2 = NULL;
	isl_int v;
	int *pos = NULL;
	int dropped, needed;

	if (!bmap)
		return NULL;

	if (bmap->n_div == 0)
		return bmap;

	if (bmap->n_eq == 0)
		return bmap;

	if (ISL_F_ISSET(bmap, ISL_BASIC_MAP_NORMALIZED_DIVS))
		return bmap;

	total = isl_space_dim(bmap->dim, isl_dim_all);
	div_eq = n_pure_div_eq(bmap);
	if (div_eq == 0)
		return bmap;

	if (div_eq < bmap->n_eq) {
		B = isl_mat_sub_alloc6(bmap->ctx, bmap->eq, div_eq,
					bmap->n_eq - div_eq, 0, 1 + total);
		C = isl_mat_variable_compression(B, &C2);
		if (!C || !C2)
			goto error;
		if (C->n_col == 0) {
			bmap = isl_basic_map_set_to_empty(bmap);
			isl_mat_free(C);
			isl_mat_free(C2);
			goto done;
		}
	}

	d = isl_vec_alloc(bmap->ctx, div_eq);
	if (!d)
		goto error;
	for (i = 0, j = bmap->n_div-1; i < div_eq; ++i) {
		while (j >= 0 && isl_int_is_zero(bmap->eq[i][1 + total + j]))
			--j;
		isl_int_set(d->block.data[i], bmap->eq[i][1 + total + j]);
	}
	B = isl_mat_sub_alloc6(bmap->ctx, bmap->eq, 0, div_eq, 0, 1 + total);

	if (C) {
		B = isl_mat_product(B, C);
		C = NULL;
	}

	T = isl_mat_parameter_compression(B, d);
	if (!T)
		goto error;
	if (T->n_col == 0) {
		bmap = isl_basic_map_set_to_empty(bmap);
		isl_mat_free(C2);
		isl_mat_free(T);
		goto done;
	}
	isl_int_init(v);
	for (i = 0; i < T->n_row - 1; ++i) {
		isl_int_fdiv_q(v, T->row[1 + i][0], T->row[1 + i][1 + i]);
		if (isl_int_is_zero(v))
			continue;
		isl_mat_col_submul(T, 0, v, 1 + i);
	}
	isl_int_clear(v);
	pos = isl_alloc_array(bmap->ctx, int, T->n_row);
	if (!pos)
		goto error;
	/* We have to be careful because dropping equalities may reorder them */
	dropped = 0;
	for (j = bmap->n_div - 1; j >= 0; --j) {
		for (i = 0; i < bmap->n_eq; ++i)
			if (!isl_int_is_zero(bmap->eq[i][1 + total + j]))
				break;
		if (i < bmap->n_eq) {
			bmap = isl_basic_map_drop_div(bmap, j);
			isl_basic_map_drop_equality(bmap, i);
			++dropped;
		}
	}
	pos[0] = 0;
	needed = 0;
	for (i = 1; i < T->n_row; ++i) {
		if (isl_int_is_one(T->row[i][i]))
			pos[i] = i;
		else
			needed++;
	}
	if (needed > dropped) {
		bmap = isl_basic_map_extend_space(bmap, isl_space_copy(bmap->dim),
				needed, needed, 0);
		if (!bmap)
			goto error;
	}
	for (i = 1; i < T->n_row; ++i) {
		if (isl_int_is_one(T->row[i][i]))
			continue;
		k = isl_basic_map_alloc_div(bmap);
		pos[i] = 1 + total + k;
		isl_seq_clr(bmap->div[k] + 1, 1 + total + bmap->n_div);
		isl_int_set(bmap->div[k][0], T->row[i][i]);
		if (C2)
			isl_seq_cpy(bmap->div[k] + 1, C2->row[i], 1 + total);
		else
			isl_int_set_si(bmap->div[k][1 + i], 1);
		for (j = 0; j < i; ++j) {
			if (isl_int_is_zero(T->row[i][j]))
				continue;
			if (pos[j] < T->n_row && C2)
				isl_seq_submul(bmap->div[k] + 1, T->row[i][j],
						C2->row[pos[j]], 1 + total);
			else
				isl_int_neg(bmap->div[k][1 + pos[j]],
								T->row[i][j]);
		}
		j = isl_basic_map_alloc_equality(bmap);
		isl_seq_neg(bmap->eq[j], bmap->div[k]+1, 1+total+bmap->n_div);
		isl_int_set(bmap->eq[j][pos[i]], bmap->div[k][0]);
	}
	free(pos);
	isl_mat_free(C2);
	isl_mat_free(T);

	if (progress)
		*progress = 1;
done:
	ISL_F_SET(bmap, ISL_BASIC_MAP_NORMALIZED_DIVS);

	return bmap;
error:
	free(pos);
	isl_mat_free(C);
	isl_mat_free(C2);
	isl_mat_free(T);
	return bmap;
}

static __isl_give isl_basic_map *set_div_from_lower_bound(
	__isl_take isl_basic_map *bmap, int div, int ineq)
{
	unsigned total = 1 + isl_space_dim(bmap->dim, isl_dim_all);

	isl_seq_neg(bmap->div[div] + 1, bmap->ineq[ineq], total + bmap->n_div);
	isl_int_set(bmap->div[div][0], bmap->ineq[ineq][total + div]);
	isl_int_add(bmap->div[div][1], bmap->div[div][1], bmap->div[div][0]);
	isl_int_sub_ui(bmap->div[div][1], bmap->div[div][1], 1);
	isl_int_set_si(bmap->div[div][1 + total + div], 0);

	return bmap;
}

/* Check whether it is ok to define a div based on an inequality.
 * To avoid the introduction of circular definitions of divs, we
 * do not allow such a definition if the resulting expression would refer to
 * any other undefined divs or if any known div is defined in
 * terms of the unknown div.
 */
static isl_bool ok_to_set_div_from_bound(__isl_keep isl_basic_map *bmap,
	int div, int ineq)
{
	int j;
	unsigned total = 1 + isl_space_dim(bmap->dim, isl_dim_all);

	/* Not defined in terms of unknown divs */
	for (j = 0; j < bmap->n_div; ++j) {
		if (div == j)
			continue;
		if (isl_int_is_zero(bmap->ineq[ineq][total + j]))
			continue;
		if (isl_int_is_zero(bmap->div[j][0]))
			return isl_bool_false;
	}

	/* No other div defined in terms of this one => avoid loops */
	for (j = 0; j < bmap->n_div; ++j) {
		if (div == j)
			continue;
		if (isl_int_is_zero(bmap->div[j][0]))
			continue;
		if (!isl_int_is_zero(bmap->div[j][1 + total + div]))
			return isl_bool_false;
	}

	return isl_bool_true;
}

/* Would an expression for div "div" based on inequality "ineq" of "bmap"
 * be a better expression than the current one?
 *
 * If we do not have any expression yet, then any expression would be better.
 * Otherwise we check if the last variable involved in the inequality
 * (disregarding the div that it would define) is in an earlier position
 * than the last variable involved in the current div expression.
 */
static isl_bool better_div_constraint(__isl_keep isl_basic_map *bmap,
	int div, int ineq)
{
	unsigned total = 1 + isl_space_dim(bmap->dim, isl_dim_all);
	int last_div;
	int last_ineq;

	if (isl_int_is_zero(bmap->div[div][0]))
		return isl_bool_true;

	if (isl_seq_last_non_zero(bmap->ineq[ineq] + total + div + 1,
				  bmap->n_div - (div + 1)) >= 0)
		return isl_bool_false;

	last_ineq = isl_seq_last_non_zero(bmap->ineq[ineq], total + div);
	last_div = isl_seq_last_non_zero(bmap->div[div] + 1,
					 total + bmap->n_div);

	return last_ineq < last_div;
}

/* Given two constraints "k" and "l" that are opposite to each other,
 * except for the constant term, check if we can use them
 * to obtain an expression for one of the hitherto unknown divs or
 * a "better" expression for a div for which we already have an expression.
 * "sum" is the sum of the constant terms of the constraints.
 * If this sum is strictly smaller than the coefficient of one
 * of the divs, then this pair can be used define the div.
 * To avoid the introduction of circular definitions of divs, we
 * do not use the pair if the resulting expression would refer to
 * any other undefined divs or if any known div is defined in
 * terms of the unknown div.
 */
static __isl_give isl_basic_map *check_for_div_constraints(
	__isl_take isl_basic_map *bmap, int k, int l, isl_int sum,
	int *progress)
{
	int i;
	unsigned total = 1 + isl_space_dim(bmap->dim, isl_dim_all);

	for (i = 0; i < bmap->n_div; ++i) {
		isl_bool set_div;

		if (isl_int_is_zero(bmap->ineq[k][total + i]))
			continue;
		if (isl_int_abs_ge(sum, bmap->ineq[k][total + i]))
			continue;
		set_div = better_div_constraint(bmap, i, k);
		if (set_div >= 0 && set_div)
			set_div = ok_to_set_div_from_bound(bmap, i, k);
		if (set_div < 0)
			return isl_basic_map_free(bmap);
		if (!set_div)
			break;
		if (isl_int_is_pos(bmap->ineq[k][total + i]))
			bmap = set_div_from_lower_bound(bmap, i, k);
		else
			bmap = set_div_from_lower_bound(bmap, i, l);
		if (progress)
			*progress = 1;
		break;
	}
	return bmap;
}

__isl_give isl_basic_map *isl_basic_map_remove_duplicate_constraints(
	__isl_take isl_basic_map *bmap, int *progress, int detect_divs)
{
	struct isl_constraint_index ci;
	int k, l, h;
	unsigned total = isl_basic_map_total_dim(bmap);
	isl_int sum;

	if (!bmap || bmap->n_ineq <= 1)
		return bmap;

	if (create_constraint_index(&ci, bmap) < 0)
		return bmap;

	h = isl_seq_get_hash_bits(bmap->ineq[0] + 1, total, ci.bits);
	ci.index[h] = &bmap->ineq[0];
	for (k = 1; k < bmap->n_ineq; ++k) {
		h = hash_index(&ci, bmap, k);
		if (!ci.index[h]) {
			ci.index[h] = &bmap->ineq[k];
			continue;
		}
		if (progress)
			*progress = 1;
		l = ci.index[h] - &bmap->ineq[0];
		if (isl_int_lt(bmap->ineq[k][0], bmap->ineq[l][0]))
			swap_inequality(bmap, k, l);
		isl_basic_map_drop_inequality(bmap, k);
		--k;
	}
	isl_int_init(sum);
	for (k = 0; k < bmap->n_ineq-1; ++k) {
		isl_seq_neg(bmap->ineq[k]+1, bmap->ineq[k]+1, total);
		h = hash_index(&ci, bmap, k);
		isl_seq_neg(bmap->ineq[k]+1, bmap->ineq[k]+1, total);
		if (!ci.index[h])
			continue;
		l = ci.index[h] - &bmap->ineq[0];
		isl_int_add(sum, bmap->ineq[k][0], bmap->ineq[l][0]);
		if (isl_int_is_pos(sum)) {
			if (detect_divs)
				bmap = check_for_div_constraints(bmap, k, l,
								 sum, progress);
			continue;
		}
		if (isl_int_is_zero(sum)) {
			/* We need to break out of the loop after these
			 * changes since the contents of the hash
			 * will no longer be valid.
			 * Plus, we probably we want to regauss first.
			 */
			if (progress)
				*progress = 1;
			isl_basic_map_drop_inequality(bmap, l);
			isl_basic_map_inequality_to_equality(bmap, k);
		} else
			bmap = isl_basic_map_set_to_empty(bmap);
		break;
	}
	isl_int_clear(sum);

	constraint_index_free(&ci);
	return bmap;
}

/* Detect all pairs of inequalities that form an equality.
 *
 * isl_basic_map_remove_duplicate_constraints detects at most one such pair.
 * Call it repeatedly while it is making progress.
 */
__isl_give isl_basic_map *isl_basic_map_detect_inequality_pairs(
	__isl_take isl_basic_map *bmap, int *progress)
{
	int duplicate;

	do {
		duplicate = 0;
		bmap = isl_basic_map_remove_duplicate_constraints(bmap,
								&duplicate, 0);
		if (progress && duplicate)
			*progress = 1;
	} while (duplicate);

	return bmap;
}

/* Eliminate knowns divs from constraints where they appear with
 * a (positive or negative) unit coefficient.
 *
 * That is, replace
 *
 *	floor(e/m) + f >= 0
 *
 * by
 *
 *	e + m f >= 0
 *
 * and
 *
 *	-floor(e/m) + f >= 0
 *
 * by
 *
 *	-e + m f + m - 1 >= 0
 *
 * The first conversion is valid because floor(e/m) >= -f is equivalent
 * to e/m >= -f because -f is an integral expression.
 * The second conversion follows from the fact that
 *
 *	-floor(e/m) = ceil(-e/m) = floor((-e + m - 1)/m)
 *
 *
 * Note that one of the div constraints may have been eliminated
 * due to being redundant with respect to the constraint that is
 * being modified by this function.  The modified constraint may
 * no longer imply this div constraint, so we add it back to make
 * sure we do not lose any information.
 *
 * We skip integral divs, i.e., those with denominator 1, as we would
 * risk eliminating the div from the div constraints.  We do not need
 * to handle those divs here anyway since the div constraints will turn
 * out to form an equality and this equality can then be used to eliminate
 * the div from all constraints.
 */
static __isl_give isl_basic_map *eliminate_unit_divs(
	__isl_take isl_basic_map *bmap, int *progress)
{
	int i, j;
	isl_ctx *ctx;
	unsigned total;

	if (!bmap)
		return NULL;

	ctx = isl_basic_map_get_ctx(bmap);
	total = 1 + isl_space_dim(bmap->dim, isl_dim_all);

	for (i = 0; i < bmap->n_div; ++i) {
		if (isl_int_is_zero(bmap->div[i][0]))
			continue;
		if (isl_int_is_one(bmap->div[i][0]))
			continue;
		for (j = 0; j < bmap->n_ineq; ++j) {
			int s;

			if (!isl_int_is_one(bmap->ineq[j][total + i]) &&
			    !isl_int_is_negone(bmap->ineq[j][total + i]))
				continue;

			*progress = 1;

			s = isl_int_sgn(bmap->ineq[j][total + i]);
			isl_int_set_si(bmap->ineq[j][total + i], 0);
			if (s < 0)
				isl_seq_combine(bmap->ineq[j],
					ctx->negone, bmap->div[i] + 1,
					bmap->div[i][0], bmap->ineq[j],
					total + bmap->n_div);
			else
				isl_seq_combine(bmap->ineq[j],
					ctx->one, bmap->div[i] + 1,
					bmap->div[i][0], bmap->ineq[j],
					total + bmap->n_div);
			if (s < 0) {
				isl_int_add(bmap->ineq[j][0],
					bmap->ineq[j][0], bmap->div[i][0]);
				isl_int_sub_ui(bmap->ineq[j][0],
					bmap->ineq[j][0], 1);
			}

			bmap = isl_basic_map_extend_constraints(bmap, 0, 1);
			if (isl_basic_map_add_div_constraint(bmap, i, s) < 0)
				return isl_basic_map_free(bmap);
		}
	}

	return bmap;
}

__isl_give isl_basic_map *isl_basic_map_simplify(__isl_take isl_basic_map *bmap)
{
	int progress = 1;
	if (!bmap)
		return NULL;
	while (progress) {
		isl_bool empty;

		progress = 0;
		empty = isl_basic_map_plain_is_empty(bmap);
		if (empty < 0)
			return isl_basic_map_free(bmap);
		if (empty)
			break;
		bmap = isl_basic_map_normalize_constraints(bmap);
		bmap = reduce_div_coefficients(bmap);
		bmap = normalize_div_expressions(bmap);
		bmap = remove_duplicate_divs(bmap, &progress);
		bmap = eliminate_unit_divs(bmap, &progress);
		bmap = eliminate_divs_eq(bmap, &progress);
		bmap = eliminate_divs_ineq(bmap, &progress);
		bmap = isl_basic_map_gauss(bmap, &progress);
		/* requires equalities in normal form */
		bmap = normalize_divs(bmap, &progress);
		bmap = isl_basic_map_remove_duplicate_constraints(bmap,
								&progress, 1);
		if (bmap && progress)
			ISL_F_CLR(bmap, ISL_BASIC_MAP_REDUCED_COEFFICIENTS);
	}
	return bmap;
}

struct isl_basic_set *isl_basic_set_simplify(struct isl_basic_set *bset)
{
	return bset_from_bmap(isl_basic_map_simplify(bset_to_bmap(bset)));
}


isl_bool isl_basic_map_is_div_constraint(__isl_keep isl_basic_map *bmap,
	isl_int *constraint, unsigned div)
{
	unsigned pos;

	if (!bmap)
		return isl_bool_error;

	pos = 1 + isl_space_dim(bmap->dim, isl_dim_all) + div;

	if (isl_int_eq(constraint[pos], bmap->div[div][0])) {
		int neg;
		isl_int_sub(bmap->div[div][1],
				bmap->div[div][1], bmap->div[div][0]);
		isl_int_add_ui(bmap->div[div][1], bmap->div[div][1], 1);
		neg = isl_seq_is_neg(constraint, bmap->div[div]+1, pos);
		isl_int_sub_ui(bmap->div[div][1], bmap->div[div][1], 1);
		isl_int_add(bmap->div[div][1],
				bmap->div[div][1], bmap->div[div][0]);
		if (!neg)
			return isl_bool_false;
		if (isl_seq_first_non_zero(constraint+pos+1,
					    bmap->n_div-div-1) != -1)
			return isl_bool_false;
	} else if (isl_int_abs_eq(constraint[pos], bmap->div[div][0])) {
		if (!isl_seq_eq(constraint, bmap->div[div]+1, pos))
			return isl_bool_false;
		if (isl_seq_first_non_zero(constraint+pos+1,
					    bmap->n_div-div-1) != -1)
			return isl_bool_false;
	} else
		return isl_bool_false;

	return isl_bool_true;
}

isl_bool isl_basic_set_is_div_constraint(__isl_keep isl_basic_set *bset,
	isl_int *constraint, unsigned div)
{
	return isl_basic_map_is_div_constraint(bset, constraint, div);
}


/* If the only constraints a div d=floor(f/m)
 * appears in are its two defining constraints
 *
 *	f - m d >=0
 *	-(f - (m - 1)) + m d >= 0
 *
 * then it can safely be removed.
 */
static isl_bool div_is_redundant(__isl_keep isl_basic_map *bmap, int div)
{
	int i;
	unsigned pos = 1 + isl_space_dim(bmap->dim, isl_dim_all) + div;

	for (i = 0; i < bmap->n_eq; ++i)
		if (!isl_int_is_zero(bmap->eq[i][pos]))
			return isl_bool_false;

	for (i = 0; i < bmap->n_ineq; ++i) {
		isl_bool red;

		if (isl_int_is_zero(bmap->ineq[i][pos]))
			continue;
		red = isl_basic_map_is_div_constraint(bmap, bmap->ineq[i], div);
		if (red < 0 || !red)
			return red;
	}

	for (i = 0; i < bmap->n_div; ++i) {
		if (isl_int_is_zero(bmap->div[i][0]))
			continue;
		if (!isl_int_is_zero(bmap->div[i][1+pos]))
			return isl_bool_false;
	}

	return isl_bool_true;
}

/*
 * Remove divs that don't occur in any of the constraints or other divs.
 * These can arise when dropping constraints from a basic map or
 * when the divs of a basic map have been temporarily aligned
 * with the divs of another basic map.
 */
static __isl_give isl_basic_map *remove_redundant_divs(
	__isl_take isl_basic_map *bmap)
{
	int i;

	if (!bmap)
		return NULL;

	for (i = bmap->n_div-1; i >= 0; --i) {
		isl_bool redundant;

		redundant = div_is_redundant(bmap, i);
		if (redundant < 0)
			return isl_basic_map_free(bmap);
		if (!redundant)
			continue;
		bmap = isl_basic_map_drop_div(bmap, i);
	}
	return bmap;
}

/* Mark "bmap" as final, without checking for obviously redundant
 * integer divisions.  This function should be used when "bmap"
 * is known not to involve any such integer divisions.
 */
__isl_give isl_basic_map *isl_basic_map_mark_final(
	__isl_take isl_basic_map *bmap)
{
	if (!bmap)
		return NULL;
	ISL_F_SET(bmap, ISL_BASIC_SET_FINAL);
	return bmap;
}

/* Mark "bmap" as final, after removing obviously redundant integer divisions.
 */
__isl_give isl_basic_map *isl_basic_map_finalize(__isl_take isl_basic_map *bmap)
{
	bmap = remove_redundant_divs(bmap);
	bmap = isl_basic_map_mark_final(bmap);
	return bmap;
}

struct isl_basic_set *isl_basic_set_finalize(struct isl_basic_set *bset)
{
	return bset_from_bmap(isl_basic_map_finalize(bset_to_bmap(bset)));
}

/* Remove definition of any div that is defined in terms of the given variable.
 * The div itself is not removed.  Functions such as
 * eliminate_divs_ineq depend on the other divs remaining in place.
 */
static __isl_give isl_basic_map *remove_dependent_vars(
	__isl_take isl_basic_map *bmap, int pos)
{
	int i;

	if (!bmap)
		return NULL;

	for (i = 0; i < bmap->n_div; ++i) {
		if (isl_int_is_zero(bmap->div[i][0]))
			continue;
		if (isl_int_is_zero(bmap->div[i][1+1+pos]))
			continue;
		bmap = isl_basic_map_mark_div_unknown(bmap, i);
		if (!bmap)
			return NULL;
	}
	return bmap;
}

/* Eliminate the specified variables from the constraints using
 * Fourier-Motzkin.  The variables themselves are not removed.
 */
__isl_give isl_basic_map *isl_basic_map_eliminate_vars(
	__isl_take isl_basic_map *bmap, unsigned pos, unsigned n)
{
	int d;
	int i, j, k;
	unsigned total;
	int need_gauss = 0;

	if (n == 0)
		return bmap;
	if (!bmap)
		return NULL;
	total = isl_basic_map_total_dim(bmap);

	bmap = isl_basic_map_cow(bmap);
	for (d = pos + n - 1; d >= 0 && d >= pos; --d)
		bmap = remove_dependent_vars(bmap, d);
	if (!bmap)
		return NULL;

	for (d = pos + n - 1;
	     d >= 0 && d >= total - bmap->n_div && d >= pos; --d)
		isl_seq_clr(bmap->div[d-(total-bmap->n_div)], 2+total);
	for (d = pos + n - 1; d >= 0 && d >= pos; --d) {
		int n_lower, n_upper;
		if (!bmap)
			return NULL;
		for (i = 0; i < bmap->n_eq; ++i) {
			if (isl_int_is_zero(bmap->eq[i][1+d]))
				continue;
			eliminate_var_using_equality(bmap, d, bmap->eq[i], 0, NULL);
			isl_basic_map_drop_equality(bmap, i);
			need_gauss = 1;
			break;
		}
		if (i < bmap->n_eq)
			continue;
		n_lower = 0;
		n_upper = 0;
		for (i = 0; i < bmap->n_ineq; ++i) {
			if (isl_int_is_pos(bmap->ineq[i][1+d]))
				n_lower++;
			else if (isl_int_is_neg(bmap->ineq[i][1+d]))
				n_upper++;
		}
		bmap = isl_basic_map_extend_constraints(bmap,
				0, n_lower * n_upper);
		if (!bmap)
			goto error;
		for (i = bmap->n_ineq - 1; i >= 0; --i) {
			int last;
			if (isl_int_is_zero(bmap->ineq[i][1+d]))
				continue;
			last = -1;
			for (j = 0; j < i; ++j) {
				if (isl_int_is_zero(bmap->ineq[j][1+d]))
					continue;
				last = j;
				if (isl_int_sgn(bmap->ineq[i][1+d]) ==
				    isl_int_sgn(bmap->ineq[j][1+d]))
					continue;
				k = isl_basic_map_alloc_inequality(bmap);
				if (k < 0)
					goto error;
				isl_seq_cpy(bmap->ineq[k], bmap->ineq[i],
						1+total);
				isl_seq_elim(bmap->ineq[k], bmap->ineq[j],
						1+d, 1+total, NULL);
			}
			isl_basic_map_drop_inequality(bmap, i);
			i = last + 1;
		}
		if (n_lower > 0 && n_upper > 0) {
			bmap = isl_basic_map_normalize_constraints(bmap);
			bmap = isl_basic_map_remove_duplicate_constraints(bmap,
								    NULL, 0);
			bmap = isl_basic_map_gauss(bmap, NULL);
			bmap = isl_basic_map_remove_redundancies(bmap);
			need_gauss = 0;
			if (!bmap)
				goto error;
			if (ISL_F_ISSET(bmap, ISL_BASIC_MAP_EMPTY))
				break;
		}
	}
	ISL_F_CLR(bmap, ISL_BASIC_MAP_NORMALIZED);
	if (need_gauss)
		bmap = isl_basic_map_gauss(bmap, NULL);
	return bmap;
error:
	isl_basic_map_free(bmap);
	return NULL;
}

struct isl_basic_set *isl_basic_set_eliminate_vars(
	struct isl_basic_set *bset, unsigned pos, unsigned n)
{
	return bset_from_bmap(isl_basic_map_eliminate_vars(bset_to_bmap(bset),
								pos, n));
}

/* Eliminate the specified n dimensions starting at first from the
 * constraints, without removing the dimensions from the space.
 * If the set is rational, the dimensions are eliminated using Fourier-Motzkin.
 * Otherwise, they are projected out and the original space is restored.
 */
__isl_give isl_basic_map *isl_basic_map_eliminate(
	__isl_take isl_basic_map *bmap,
	enum isl_dim_type type, unsigned first, unsigned n)
{
	isl_space *space;

	if (!bmap)
		return NULL;
	if (n == 0)
		return bmap;

	if (first + n > isl_basic_map_dim(bmap, type) || first + n < first)
		isl_die(bmap->ctx, isl_error_invalid,
			"index out of bounds", goto error);

	if (ISL_F_ISSET(bmap, ISL_BASIC_MAP_RATIONAL)) {
		first += isl_basic_map_offset(bmap, type) - 1;
		bmap = isl_basic_map_eliminate_vars(bmap, first, n);
		return isl_basic_map_finalize(bmap);
	}

	space = isl_basic_map_get_space(bmap);
	bmap = isl_basic_map_project_out(bmap, type, first, n);
	bmap = isl_basic_map_insert_dims(bmap, type, first, n);
	bmap = isl_basic_map_reset_space(bmap, space);
	return bmap;
error:
	isl_basic_map_free(bmap);
	return NULL;
}

__isl_give isl_basic_set *isl_basic_set_eliminate(
	__isl_take isl_basic_set *bset,
	enum isl_dim_type type, unsigned first, unsigned n)
{
	return isl_basic_map_eliminate(bset, type, first, n);
}

/* Remove all constraints from "bmap" that reference any unknown local
 * variables (directly or indirectly).
 *
 * Dropping all constraints on a local variable will make it redundant,
 * so it will get removed implicitly by
 * isl_basic_map_drop_constraints_involving_dims.  Some other local
 * variables may also end up becoming redundant if they only appear
 * in constraints together with the unknown local variable.
 * Therefore, start over after calling
 * isl_basic_map_drop_constraints_involving_dims.
 */
__isl_give isl_basic_map *isl_basic_map_drop_constraint_involving_unknown_divs(
	__isl_take isl_basic_map *bmap)
{
	isl_bool known;
	int i, n_div, o_div;

	known = isl_basic_map_divs_known(bmap);
	if (known < 0)
		return isl_basic_map_free(bmap);
	if (known)
		return bmap;

	n_div = isl_basic_map_dim(bmap, isl_dim_div);
	o_div = isl_basic_map_offset(bmap, isl_dim_div) - 1;

	for (i = 0; i < n_div; ++i) {
		known = isl_basic_map_div_is_known(bmap, i);
		if (known < 0)
			return isl_basic_map_free(bmap);
		if (known)
			continue;
		bmap = remove_dependent_vars(bmap, o_div + i);
		bmap = isl_basic_map_drop_constraints_involving_dims(bmap,
							    isl_dim_div, i, 1);
		if (!bmap)
			return NULL;
		n_div = isl_basic_map_dim(bmap, isl_dim_div);
		i = -1;
	}

	return bmap;
}

/* Remove all constraints from "map" that reference any unknown local
 * variables (directly or indirectly).
 *
 * Since constraints may get dropped from the basic maps,
 * they may no longer be disjoint from each other.
 */
__isl_give isl_map *isl_map_drop_constraint_involving_unknown_divs(
	__isl_take isl_map *map)
{
	int i;
	isl_bool known;

	known = isl_map_divs_known(map);
	if (known < 0)
		return isl_map_free(map);
	if (known)
		return map;

	map = isl_map_cow(map);
	if (!map)
		return NULL;

	for (i = 0; i < map->n; ++i) {
		map->p[i] =
		    isl_basic_map_drop_constraint_involving_unknown_divs(
								    map->p[i]);
		if (!map->p[i])
			return isl_map_free(map);
	}

	if (map->n > 1)
		ISL_F_CLR(map, ISL_MAP_DISJOINT);

	return map;
}

/* Don't assume equalities are in order, because align_divs
 * may have changed the order of the divs.
 */
static void compute_elimination_index(__isl_keep isl_basic_map *bmap, int *elim)
{
	int d, i;
	unsigned total;

	total = isl_space_dim(bmap->dim, isl_dim_all);
	for (d = 0; d < total; ++d)
		elim[d] = -1;
	for (i = 0; i < bmap->n_eq; ++i) {
		for (d = total - 1; d >= 0; --d) {
			if (isl_int_is_zero(bmap->eq[i][1+d]))
				continue;
			elim[d] = i;
			break;
		}
	}
}

static void set_compute_elimination_index(__isl_keep isl_basic_set *bset,
	int *elim)
{
	compute_elimination_index(bset_to_bmap(bset), elim);
}

static int reduced_using_equalities(isl_int *dst, isl_int *src,
	__isl_keep isl_basic_map *bmap, int *elim)
{
	int d;
	int copied = 0;
	unsigned total;

	total = isl_space_dim(bmap->dim, isl_dim_all);
	for (d = total - 1; d >= 0; --d) {
		if (isl_int_is_zero(src[1+d]))
			continue;
		if (elim[d] == -1)
			continue;
		if (!copied) {
			isl_seq_cpy(dst, src, 1 + total);
			copied = 1;
		}
		isl_seq_elim(dst, bmap->eq[elim[d]], 1 + d, 1 + total, NULL);
	}
	return copied;
}

static int set_reduced_using_equalities(isl_int *dst, isl_int *src,
	__isl_keep isl_basic_set *bset, int *elim)
{
	return reduced_using_equalities(dst, src,
					bset_to_bmap(bset), elim);
}

static __isl_give isl_basic_set *isl_basic_set_reduce_using_equalities(
	__isl_take isl_basic_set *bset, __isl_take isl_basic_set *context)
{
	int i;
	int *elim;

	if (!bset || !context)
		goto error;

	if (context->n_eq == 0) {
		isl_basic_set_free(context);
		return bset;
	}

	bset = isl_basic_set_cow(bset);
	if (!bset)
		goto error;

	elim = isl_alloc_array(bset->ctx, int, isl_basic_set_n_dim(bset));
	if (!elim)
		goto error;
	set_compute_elimination_index(context, elim);
	for (i = 0; i < bset->n_eq; ++i)
		set_reduced_using_equalities(bset->eq[i], bset->eq[i],
							context, elim);
	for (i = 0; i < bset->n_ineq; ++i)
		set_reduced_using_equalities(bset->ineq[i], bset->ineq[i],
							context, elim);
	isl_basic_set_free(context);
	free(elim);
	bset = isl_basic_set_simplify(bset);
	bset = isl_basic_set_finalize(bset);
	return bset;
error:
	isl_basic_set_free(bset);
	isl_basic_set_free(context);
	return NULL;
}

/* For each inequality in "ineq" that is a shifted (more relaxed)
 * copy of an inequality in "context", mark the corresponding entry
 * in "row" with -1.
 * If an inequality only has a non-negative constant term, then
 * mark it as well.
 */
static isl_stat mark_shifted_constraints(__isl_keep isl_mat *ineq,
	__isl_keep isl_basic_set *context, int *row)
{
	struct isl_constraint_index ci;
	int n_ineq;
	unsigned total;
	int k;

	if (!ineq || !context)
		return isl_stat_error;
	if (context->n_ineq == 0)
		return isl_stat_ok;
	if (setup_constraint_index(&ci, context) < 0)
		return isl_stat_error;

	n_ineq = isl_mat_rows(ineq);
	total = isl_mat_cols(ineq) - 1;
	for (k = 0; k < n_ineq; ++k) {
		int l;
		isl_bool redundant;

		l = isl_seq_first_non_zero(ineq->row[k] + 1, total);
		if (l < 0 && isl_int_is_nonneg(ineq->row[k][0])) {
			row[k] = -1;
			continue;
		}
		redundant = constraint_index_is_redundant(&ci, ineq->row[k]);
		if (redundant < 0)
			goto error;
		if (!redundant)
			continue;
		row[k] = -1;
	}
	constraint_index_free(&ci);
	return isl_stat_ok;
error:
	constraint_index_free(&ci);
	return isl_stat_error;
}

static __isl_give isl_basic_set *remove_shifted_constraints(
	__isl_take isl_basic_set *bset, __isl_keep isl_basic_set *context)
{
	struct isl_constraint_index ci;
	int k;

	if (!bset || !context)
		return bset;

	if (context->n_ineq == 0)
		return bset;
	if (setup_constraint_index(&ci, context) < 0)
		return bset;

	for (k = 0; k < bset->n_ineq; ++k) {
		isl_bool redundant;

		redundant = constraint_index_is_redundant(&ci, bset->ineq[k]);
		if (redundant < 0)
			goto error;
		if (!redundant)
			continue;
		bset = isl_basic_set_cow(bset);
		if (!bset)
			goto error;
		isl_basic_set_drop_inequality(bset, k);
		--k;
	}
	constraint_index_free(&ci);
	return bset;
error:
	constraint_index_free(&ci);
	return bset;
}

/* Remove constraints from "bmap" that are identical to constraints
 * in "context" or that are more relaxed (greater constant term).
 *
 * We perform the test for shifted copies on the pure constraints
 * in remove_shifted_constraints.
 */
static __isl_give isl_basic_map *isl_basic_map_remove_shifted_constraints(
	__isl_take isl_basic_map *bmap, __isl_take isl_basic_map *context)
{
	isl_basic_set *bset, *bset_context;

	if (!bmap || !context)
		goto error;

	if (bmap->n_ineq == 0 || context->n_ineq == 0) {
		isl_basic_map_free(context);
		return bmap;
	}

	context = isl_basic_map_align_divs(context, bmap);
	bmap = isl_basic_map_align_divs(bmap, context);

	bset = isl_basic_map_underlying_set(isl_basic_map_copy(bmap));
	bset_context = isl_basic_map_underlying_set(context);
	bset = remove_shifted_constraints(bset, bset_context);
	isl_basic_set_free(bset_context);

	bmap = isl_basic_map_overlying_set(bset, bmap);

	return bmap;
error:
	isl_basic_map_free(bmap);
	isl_basic_map_free(context);
	return NULL;
}

/* Does the (linear part of a) constraint "c" involve any of the "len"
 * "relevant" dimensions?
 */
static int is_related(isl_int *c, int len, int *relevant)
{
	int i;

	for (i = 0; i < len; ++i) {
		if (!relevant[i])
			continue;
		if (!isl_int_is_zero(c[i]))
			return 1;
	}

	return 0;
}

/* Drop constraints from "bmap" that do not involve any of
 * the dimensions marked "relevant".
 */
static __isl_give isl_basic_map *drop_unrelated_constraints(
	__isl_take isl_basic_map *bmap, int *relevant)
{
	int i, dim;

	dim = isl_basic_map_dim(bmap, isl_dim_all);
	for (i = 0; i < dim; ++i)
		if (!relevant[i])
			break;
	if (i >= dim)
		return bmap;

	for (i = bmap->n_eq - 1; i >= 0; --i)
		if (!is_related(bmap->eq[i] + 1, dim, relevant)) {
			bmap = isl_basic_map_cow(bmap);
			if (isl_basic_map_drop_equality(bmap, i) < 0)
				return isl_basic_map_free(bmap);
		}

	for (i = bmap->n_ineq - 1; i >= 0; --i)
		if (!is_related(bmap->ineq[i] + 1, dim, relevant)) {
			bmap = isl_basic_map_cow(bmap);
			if (isl_basic_map_drop_inequality(bmap, i) < 0)
				return isl_basic_map_free(bmap);
		}

	return bmap;
}

/* Update the groups in "group" based on the (linear part of a) constraint "c".
 *
 * In particular, for any variable involved in the constraint,
 * find the actual group id from before and replace the group
 * of the corresponding variable by the minimal group of all
 * the variables involved in the constraint considered so far
 * (if this minimum is smaller) or replace the minimum by this group
 * (if the minimum is larger).
 *
 * At the end, all the variables in "c" will (indirectly) point
 * to the minimal of the groups that they referred to originally.
 */
static void update_groups(int dim, int *group, isl_int *c)
{
	int j;
	int min = dim;

	for (j = 0; j < dim; ++j) {
		if (isl_int_is_zero(c[j]))
			continue;
		while (group[j] >= 0 && group[group[j]] != group[j])
			group[j] = group[group[j]];
		if (group[j] == min)
			continue;
		if (group[j] < min) {
			if (min >= 0 && min < dim)
				group[min] = group[j];
			min = group[j];
		} else
			group[group[j]] = min;
	}
}

/* Allocate an array of groups of variables, one for each variable
 * in "context", initialized to zero.
 */
static int *alloc_groups(__isl_keep isl_basic_set *context)
{
	isl_ctx *ctx;
	int dim;

	dim = isl_basic_set_dim(context, isl_dim_set);
	ctx = isl_basic_set_get_ctx(context);
	return isl_calloc_array(ctx, int, dim);
}

/* Drop constraints from "bmap" that only involve variables that are
 * not related to any of the variables marked with a "-1" in "group".
 *
 * We construct groups of variables that collect variables that
 * (indirectly) appear in some common constraint of "bmap".
 * Each group is identified by the first variable in the group,
 * except for the special group of variables that was already identified
 * in the input as -1 (or are related to those variables).
 * If group[i] is equal to i (or -1), then the group of i is i (or -1),
 * otherwise the group of i is the group of group[i].
 *
 * We first initialize groups for the remaining variables.
 * Then we iterate over the constraints of "bmap" and update the
 * group of the variables in the constraint by the smallest group.
 * Finally, we resolve indirect references to groups by running over
 * the variables.
 *
 * After computing the groups, we drop constraints that do not involve
 * any variables in the -1 group.
 */
__isl_give isl_basic_map *isl_basic_map_drop_unrelated_constraints(
	__isl_take isl_basic_map *bmap, __isl_take int *group)
{
	int dim;
	int i;
	int last;

	if (!bmap)
		return NULL;

	dim = isl_basic_map_dim(bmap, isl_dim_all);

	last = -1;
	for (i = 0; i < dim; ++i)
		if (group[i] >= 0)
			last = group[i] = i;
	if (last < 0) {
		free(group);
		return bmap;
	}

	for (i = 0; i < bmap->n_eq; ++i)
		update_groups(dim, group, bmap->eq[i] + 1);
	for (i = 0; i < bmap->n_ineq; ++i)
		update_groups(dim, group, bmap->ineq[i] + 1);

	for (i = 0; i < dim; ++i)
		if (group[i] >= 0)
			group[i] = group[group[i]];

	for (i = 0; i < dim; ++i)
		group[i] = group[i] == -1;

	bmap = drop_unrelated_constraints(bmap, group);

	free(group);
	return bmap;
}

/* Drop constraints from "context" that are irrelevant for computing
 * the gist of "bset".
 *
 * In particular, drop constraints in variables that are not related
 * to any of the variables involved in the constraints of "bset"
 * in the sense that there is no sequence of constraints that connects them.
 *
 * We first mark all variables that appear in "bset" as belonging
 * to a "-1" group and then continue with group_and_drop_irrelevant_constraints.
 */
static __isl_give isl_basic_set *drop_irrelevant_constraints(
	__isl_take isl_basic_set *context, __isl_keep isl_basic_set *bset)
{
	int *group;
	int dim;
	int i, j;

	if (!context || !bset)
		return isl_basic_set_free(context);

	group = alloc_groups(context);

	if (!group)
		return isl_basic_set_free(context);

	dim = isl_basic_set_dim(bset, isl_dim_set);
	for (i = 0; i < dim; ++i) {
		for (j = 0; j < bset->n_eq; ++j)
			if (!isl_int_is_zero(bset->eq[j][1 + i]))
				break;
		if (j < bset->n_eq) {
			group[i] = -1;
			continue;
		}
		for (j = 0; j < bset->n_ineq; ++j)
			if (!isl_int_is_zero(bset->ineq[j][1 + i]))
				break;
		if (j < bset->n_ineq)
			group[i] = -1;
	}

	return isl_basic_map_drop_unrelated_constraints(context, group);
}

/* Drop constraints from "context" that are irrelevant for computing
 * the gist of the inequalities "ineq".
 * Inequalities in "ineq" for which the corresponding element of row
 * is set to -1 have already been marked for removal and should be ignored.
 *
 * In particular, drop constraints in variables that are not related
 * to any of the variables involved in "ineq"
 * in the sense that there is no sequence of constraints that connects them.
 *
 * We first mark all variables that appear in "bset" as belonging
 * to a "-1" group and then continue with group_and_drop_irrelevant_constraints.
 */
static __isl_give isl_basic_set *drop_irrelevant_constraints_marked(
	__isl_take isl_basic_set *context, __isl_keep isl_mat *ineq, int *row)
{
	int *group;
	int dim;
	int i, j, n;

	if (!context || !ineq)
		return isl_basic_set_free(context);

	group = alloc_groups(context);

	if (!group)
		return isl_basic_set_free(context);

	dim = isl_basic_set_dim(context, isl_dim_set);
	n = isl_mat_rows(ineq);
	for (i = 0; i < dim; ++i) {
		for (j = 0; j < n; ++j) {
			if (row[j] < 0)
				continue;
			if (!isl_int_is_zero(ineq->row[j][1 + i]))
				break;
		}
		if (j < n)
			group[i] = -1;
	}

	return isl_basic_map_drop_unrelated_constraints(context, group);
}

/* Do all "n" entries of "row" contain a negative value?
 */
static int all_neg(int *row, int n)
{
	int i;

	for (i = 0; i < n; ++i)
		if (row[i] >= 0)
			return 0;

	return 1;
}

/* Update the inequalities in "bset" based on the information in "row"
 * and "tab".
 *
 * In particular, the array "row" contains either -1, meaning that
 * the corresponding inequality of "bset" is redundant, or the index
 * of an inequality in "tab".
 *
 * If the row entry is -1, then drop the inequality.
 * Otherwise, if the constraint is marked redundant in the tableau,
 * then drop the inequality.  Similarly, if it is marked as an equality
 * in the tableau, then turn the inequality into an equality and
 * perform Gaussian elimination.
 */
static __isl_give isl_basic_set *update_ineq(__isl_take isl_basic_set *bset,
	__isl_keep int *row, struct isl_tab *tab)
{
	int i;
	unsigned n_ineq;
	unsigned n_eq;
	int found_equality = 0;

	if (!bset)
		return NULL;
	if (tab && tab->empty)
		return isl_basic_set_set_to_empty(bset);

	n_ineq = bset->n_ineq;
	for (i = n_ineq - 1; i >= 0; --i) {
		if (row[i] < 0) {
			if (isl_basic_set_drop_inequality(bset, i) < 0)
				return isl_basic_set_free(bset);
			continue;
		}
		if (!tab)
			continue;
		n_eq = tab->n_eq;
		if (isl_tab_is_equality(tab, n_eq + row[i])) {
			isl_basic_map_inequality_to_equality(bset, i);
			found_equality = 1;
		} else if (isl_tab_is_redundant(tab, n_eq + row[i])) {
			if (isl_basic_set_drop_inequality(bset, i) < 0)
				return isl_basic_set_free(bset);
		}
	}

	if (found_equality)
		bset = isl_basic_set_gauss(bset, NULL);
	bset = isl_basic_set_finalize(bset);
	return bset;
}

/* Update the inequalities in "bset" based on the information in "row"
 * and "tab" and free all arguments (other than "bset").
 */
static __isl_give isl_basic_set *update_ineq_free(
	__isl_take isl_basic_set *bset, __isl_take isl_mat *ineq,
	__isl_take isl_basic_set *context, __isl_take int *row,
	struct isl_tab *tab)
{
	isl_mat_free(ineq);
	isl_basic_set_free(context);

	bset = update_ineq(bset, row, tab);

	free(row);
	isl_tab_free(tab);
	return bset;
}

/* Remove all information from bset that is redundant in the context
 * of context.
 * "ineq" contains the (possibly transformed) inequalities of "bset",
 * in the same order.
 * The (explicit) equalities of "bset" are assumed to have been taken
 * into account by the transformation such that only the inequalities
 * are relevant.
 * "context" is assumed not to be empty.
 *
 * "row" keeps track of the constraint index of a "bset" inequality in "tab".
 * A value of -1 means that the inequality is obviously redundant and may
 * not even appear in  "tab".
 *
 * We first mark the inequalities of "bset"
 * that are obviously redundant with respect to some inequality in "context".
 * Then we remove those constraints from "context" that have become
 * irrelevant for computing the gist of "bset".
 * Note that this removal of constraints cannot be replaced by
 * a factorization because factors in "bset" may still be connected
 * to each other through constraints in "context".
 *
 * If there are any inequalities left, we construct a tableau for
 * the context and then add the inequalities of "bset".
 * Before adding these inequalities, we freeze all constraints such that
 * they won't be considered redundant in terms of the constraints of "bset".
 * Then we detect all redundant constraints (among the
 * constraints that weren't frozen), first by checking for redundancy in the
 * the tableau and then by checking if replacing a constraint by its negation
 * would lead to an empty set.  This last step is fairly expensive
 * and could be optimized by more reuse of the tableau.
 * Finally, we update bset according to the results.
 */
static __isl_give isl_basic_set *uset_gist_full(__isl_take isl_basic_set *bset,
	__isl_take isl_mat *ineq, __isl_take isl_basic_set *context)
{
	int i, r;
	int *row = NULL;
	isl_ctx *ctx;
	isl_basic_set *combined = NULL;
	struct isl_tab *tab = NULL;
	unsigned n_eq, context_ineq;

	if (!bset || !ineq || !context)
		goto error;

	if (bset->n_ineq == 0 || isl_basic_set_plain_is_universe(context)) {
		isl_basic_set_free(context);
		isl_mat_free(ineq);
		return bset;
	}

	ctx = isl_basic_set_get_ctx(context);
	row = isl_calloc_array(ctx, int, bset->n_ineq);
	if (!row)
		goto error;

	if (mark_shifted_constraints(ineq, context, row) < 0)
		goto error;
	if (all_neg(row, bset->n_ineq))
		return update_ineq_free(bset, ineq, context, row, NULL);

	context = drop_irrelevant_constraints_marked(context, ineq, row);
	if (!context)
		goto error;
	if (isl_basic_set_plain_is_universe(context))
		return update_ineq_free(bset, ineq, context, row, NULL);

	n_eq = context->n_eq;
	context_ineq = context->n_ineq;
	combined = isl_basic_set_cow(isl_basic_set_copy(context));
	combined = isl_basic_set_extend_constraints(combined, 0, bset->n_ineq);
	tab = isl_tab_from_basic_set(combined, 0);
	for (i = 0; i < context_ineq; ++i)
		if (isl_tab_freeze_constraint(tab, n_eq + i) < 0)
			goto error;
	if (isl_tab_extend_cons(tab, bset->n_ineq) < 0)
		goto error;
	r = context_ineq;
	for (i = 0; i < bset->n_ineq; ++i) {
		if (row[i] < 0)
			continue;
		combined = isl_basic_set_add_ineq(combined, ineq->row[i]);
		if (isl_tab_add_ineq(tab, ineq->row[i]) < 0)
			goto error;
		row[i] = r++;
	}
	if (isl_tab_detect_implicit_equalities(tab) < 0)
		goto error;
	if (isl_tab_detect_redundant(tab) < 0)
		goto error;
	for (i = bset->n_ineq - 1; i >= 0; --i) {
		isl_basic_set *test;
		int is_empty;

		if (row[i] < 0)
			continue;
		r = row[i];
		if (tab->con[n_eq + r].is_redundant)
			continue;
		test = isl_basic_set_dup(combined);
		if (isl_inequality_negate(test, r) < 0)
			test = isl_basic_set_free(test);
		test = isl_basic_set_update_from_tab(test, tab);
		is_empty = isl_basic_set_is_empty(test);
		isl_basic_set_free(test);
		if (is_empty < 0)
			goto error;
		if (is_empty)
			tab->con[n_eq + r].is_redundant = 1;
	}
	bset = update_ineq_free(bset, ineq, context, row, tab);
	if (bset) {
		ISL_F_SET(bset, ISL_BASIC_SET_NO_IMPLICIT);
		ISL_F_SET(bset, ISL_BASIC_SET_NO_REDUNDANT);
	}

	isl_basic_set_free(combined);
	return bset;
error:
	free(row);
	isl_mat_free(ineq);
	isl_tab_free(tab);
	isl_basic_set_free(combined);
	isl_basic_set_free(context);
	isl_basic_set_free(bset);
	return NULL;
}

/* Extract the inequalities of "bset" as an isl_mat.
 */
static __isl_give isl_mat *extract_ineq(__isl_keep isl_basic_set *bset)
{
	unsigned total;
	isl_ctx *ctx;
	isl_mat *ineq;

	if (!bset)
		return NULL;

	ctx = isl_basic_set_get_ctx(bset);
	total = isl_basic_set_total_dim(bset);
	ineq = isl_mat_sub_alloc6(ctx, bset->ineq, 0, bset->n_ineq,
				    0, 1 + total);

	return ineq;
}

/* Remove all information from "bset" that is redundant in the context
 * of "context", for the case where both "bset" and "context" are
 * full-dimensional.
 */
static __isl_give isl_basic_set *uset_gist_uncompressed(
	__isl_take isl_basic_set *bset, __isl_take isl_basic_set *context)
{
	isl_mat *ineq;

	ineq = extract_ineq(bset);
	return uset_gist_full(bset, ineq, context);
}

/* Remove all information from "bset" that is redundant in the context
 * of "context", for the case where the combined equalities of
 * "bset" and "context" allow for a compression that can be obtained
 * by preapplication of "T".
 *
 * "bset" itself is not transformed by "T".  Instead, the inequalities
 * are extracted from "bset" and those are transformed by "T".
 * uset_gist_full then determines which of the transformed inequalities
 * are redundant with respect to the transformed "context" and removes
 * the corresponding inequalities from "bset".
 *
 * After preapplying "T" to the inequalities, any common factor is
 * removed from the coefficients.  If this results in a tightening
 * of the constant term, then the same tightening is applied to
 * the corresponding untransformed inequality in "bset".
 * That is, if after plugging in T, a constraint f(x) >= 0 is of the form
 *
 *	g f'(x) + r >= 0
 *
 * with 0 <= r < g, then it is equivalent to
 *
 *	f'(x) >= 0
 *
 * This means that f(x) >= 0 is equivalent to f(x) - r >= 0 in the affine
 * subspace compressed by T since the latter would be transformed to
 *
 *	g f'(x) >= 0
 */
static __isl_give isl_basic_set *uset_gist_compressed(
	__isl_take isl_basic_set *bset, __isl_take isl_basic_set *context,
	__isl_take isl_mat *T)
{
	isl_ctx *ctx;
	isl_mat *ineq;
	int i, n_row, n_col;
	isl_int rem;

	ineq = extract_ineq(bset);
	ineq = isl_mat_product(ineq, isl_mat_copy(T));
	context = isl_basic_set_preimage(context, T);

	if (!ineq || !context)
		goto error;
	if (isl_basic_set_plain_is_empty(context)) {
		isl_mat_free(ineq);
		isl_basic_set_free(context);
		return isl_basic_set_set_to_empty(bset);
	}

	ctx = isl_mat_get_ctx(ineq);
	n_row = isl_mat_rows(ineq);
	n_col = isl_mat_cols(ineq);
	isl_int_init(rem);
	for (i = 0; i < n_row; ++i) {
		isl_seq_gcd(ineq->row[i] + 1, n_col - 1, &ctx->normalize_gcd);
		if (isl_int_is_zero(ctx->normalize_gcd))
			continue;
		if (isl_int_is_one(ctx->normalize_gcd))
			continue;
		isl_seq_scale_down(ineq->row[i] + 1, ineq->row[i] + 1,
				    ctx->normalize_gcd, n_col - 1);
		isl_int_fdiv_r(rem, ineq->row[i][0], ctx->normalize_gcd);
		isl_int_fdiv_q(ineq->row[i][0],
				ineq->row[i][0], ctx->normalize_gcd);
		if (isl_int_is_zero(rem))
			continue;
		bset = isl_basic_set_cow(bset);
		if (!bset)
			break;
		isl_int_sub(bset->ineq[i][0], bset->ineq[i][0], rem);
	}
	isl_int_clear(rem);

	return uset_gist_full(bset, ineq, context);
error:
	isl_mat_free(ineq);
	isl_basic_set_free(context);
	isl_basic_set_free(bset);
	return NULL;
}

/* Project "bset" onto the variables that are involved in "template".
 */
static __isl_give isl_basic_set *project_onto_involved(
	__isl_take isl_basic_set *bset, __isl_keep isl_basic_set *template)
{
	int i, n;

	if (!bset || !template)
		return isl_basic_set_free(bset);

	n = isl_basic_set_dim(template, isl_dim_set);

	for (i = 0; i < n; ++i) {
		isl_bool involved;

		involved = isl_basic_set_involves_dims(template,
							isl_dim_set, i, 1);
		if (involved < 0)
			return isl_basic_set_free(bset);
		if (involved)
			continue;
		bset = isl_basic_set_eliminate_vars(bset, i, 1);
	}

	return bset;
}

/* Remove all information from bset that is redundant in the context
 * of context.  In particular, equalities that are linear combinations
 * of those in context are removed.  Then the inequalities that are
 * redundant in the context of the equalities and inequalities of
 * context are removed.
 *
 * First of all, we drop those constraints from "context"
 * that are irrelevant for computing the gist of "bset".
 * Alternatively, we could factorize the intersection of "context" and "bset".
 *
 * We first compute the intersection of the integer affine hulls
 * of "bset" and "context",
 * compute the gist inside this intersection and then reduce
 * the constraints with respect to the equalities of the context
 * that only involve variables already involved in the input.
 *
 * If two constraints are mutually redundant, then uset_gist_full
 * will remove the second of those constraints.  We therefore first
 * sort the constraints so that constraints not involving existentially
 * quantified variables are given precedence over those that do.
 * We have to perform this sorting before the variable compression,
 * because that may effect the order of the variables.
 */
static __isl_give isl_basic_set *uset_gist(__isl_take isl_basic_set *bset,
	__isl_take isl_basic_set *context)
{
	isl_mat *eq;
	isl_mat *T;
	isl_basic_set *aff;
	isl_basic_set *aff_context;
	unsigned total;

	if (!bset || !context)
		goto error;

	context = drop_irrelevant_constraints(context, bset);

	bset = isl_basic_set_detect_equalities(bset);
	aff = isl_basic_set_copy(bset);
	aff = isl_basic_set_plain_affine_hull(aff);
	context = isl_basic_set_detect_equalities(context);
	aff_context = isl_basic_set_copy(context);
	aff_context = isl_basic_set_plain_affine_hull(aff_context);
	aff = isl_basic_set_intersect(aff, aff_context);
	if (!aff)
		goto error;
	if (isl_basic_set_plain_is_empty(aff)) {
		isl_basic_set_free(bset);
		isl_basic_set_free(context);
		return aff;
	}
	bset = isl_basic_set_sort_constraints(bset);
	if (aff->n_eq == 0) {
		isl_basic_set_free(aff);
		return uset_gist_uncompressed(bset, context);
	}
	total = isl_basic_set_total_dim(bset);
	eq = isl_mat_sub_alloc6(bset->ctx, aff->eq, 0, aff->n_eq, 0, 1 + total);
	eq = isl_mat_cow(eq);
	T = isl_mat_variable_compression(eq, NULL);
	isl_basic_set_free(aff);
	if (T && T->n_col == 0) {
		isl_mat_free(T);
		isl_basic_set_free(context);
		return isl_basic_set_set_to_empty(bset);
	}

	aff_context = isl_basic_set_affine_hull(isl_basic_set_copy(context));
	aff_context = project_onto_involved(aff_context, bset);

	bset = uset_gist_compressed(bset, context, T);
	bset = isl_basic_set_reduce_using_equalities(bset, aff_context);

	if (bset) {
		ISL_F_SET(bset, ISL_BASIC_SET_NO_IMPLICIT);
		ISL_F_SET(bset, ISL_BASIC_SET_NO_REDUNDANT);
	}

	return bset;
error:
	isl_basic_set_free(bset);
	isl_basic_set_free(context);
	return NULL;
}

/* Return the number of equality constraints in "bmap" that involve
 * local variables.  This function assumes that Gaussian elimination
 * has been applied to the equality constraints.
 */
static int n_div_eq(__isl_keep isl_basic_map *bmap)
{
	int i;
	int total, n_div;

	if (!bmap)
		return -1;

	if (bmap->n_eq == 0)
		return 0;

	total = isl_basic_map_dim(bmap, isl_dim_all);
	n_div = isl_basic_map_dim(bmap, isl_dim_div);
	total -= n_div;

	for (i = 0; i < bmap->n_eq; ++i)
		if (isl_seq_first_non_zero(bmap->eq[i] + 1 + total,
					    n_div) == -1)
			return i;

	return bmap->n_eq;
}

/* Construct a basic map in "space" defined by the equality constraints in "eq".
 * The constraints are assumed not to involve any local variables.
 */
static __isl_give isl_basic_map *basic_map_from_equalities(
	__isl_take isl_space *space, __isl_take isl_mat *eq)
{
	int i, k;
	isl_basic_map *bmap = NULL;

	if (!space || !eq)
		goto error;

	if (1 + isl_space_dim(space, isl_dim_all) != eq->n_col)
		isl_die(isl_space_get_ctx(space), isl_error_internal,
			"unexpected number of columns", goto error);

	bmap = isl_basic_map_alloc_space(isl_space_copy(space),
					    0, eq->n_row, 0);
	for (i = 0; i < eq->n_row; ++i) {
		k = isl_basic_map_alloc_equality(bmap);
		if (k < 0)
			goto error;
		isl_seq_cpy(bmap->eq[k], eq->row[i], eq->n_col);
	}

	isl_space_free(space);
	isl_mat_free(eq);
	return bmap;
error:
	isl_space_free(space);
	isl_mat_free(eq);
	isl_basic_map_free(bmap);
	return NULL;
}

/* Construct and return a variable compression based on the equality
 * constraints in "bmap1" and "bmap2" that do not involve the local variables.
 * "n1" is the number of (initial) equality constraints in "bmap1"
 * that do involve local variables.
 * "n2" is the number of (initial) equality constraints in "bmap2"
 * that do involve local variables.
 * "total" is the total number of other variables.
 * This function assumes that Gaussian elimination
 * has been applied to the equality constraints in both "bmap1" and "bmap2"
 * such that the equality constraints not involving local variables
 * are those that start at "n1" or "n2".
 *
 * If either of "bmap1" and "bmap2" does not have such equality constraints,
 * then simply compute the compression based on the equality constraints
 * in the other basic map.
 * Otherwise, combine the equality constraints from both into a new
 * basic map such that Gaussian elimination can be applied to this combination
 * and then construct a variable compression from the resulting
 * equality constraints.
 */
static __isl_give isl_mat *combined_variable_compression(
	__isl_keep isl_basic_map *bmap1, int n1,
	__isl_keep isl_basic_map *bmap2, int n2, int total)
{
	isl_ctx *ctx;
	isl_mat *E1, *E2, *V;
	isl_basic_map *bmap;

	ctx = isl_basic_map_get_ctx(bmap1);
	if (bmap1->n_eq == n1) {
		E2 = isl_mat_sub_alloc6(ctx, bmap2->eq,
					n2, bmap2->n_eq - n2, 0, 1 + total);
		return isl_mat_variable_compression(E2, NULL);
	}
	if (bmap2->n_eq == n2) {
		E1 = isl_mat_sub_alloc6(ctx, bmap1->eq,
					n1, bmap1->n_eq - n1, 0, 1 + total);
		return isl_mat_variable_compression(E1, NULL);
	}
	E1 = isl_mat_sub_alloc6(ctx, bmap1->eq,
				n1, bmap1->n_eq - n1, 0, 1 + total);
	E2 = isl_mat_sub_alloc6(ctx, bmap2->eq,
				n2, bmap2->n_eq - n2, 0, 1 + total);
	E1 = isl_mat_concat(E1, E2);
	bmap = basic_map_from_equalities(isl_basic_map_get_space(bmap1), E1);
	bmap = isl_basic_map_gauss(bmap, NULL);
	if (!bmap)
		return NULL;
	E1 = isl_mat_sub_alloc6(ctx, bmap->eq, 0, bmap->n_eq, 0, 1 + total);
	V = isl_mat_variable_compression(E1, NULL);
	isl_basic_map_free(bmap);

	return V;
}

/* Extract the stride constraints from "bmap", compressed
 * with respect to both the stride constraints in "context" and
 * the remaining equality constraints in both "bmap" and "context".
 * "bmap_n_eq" is the number of (initial) stride constraints in "bmap".
 * "context_n_eq" is the number of (initial) stride constraints in "context".
 *
 * Let x be all variables in "bmap" (and "context") other than the local
 * variables.  First compute a variable compression
 *
 *	x = V x'
 *
 * based on the non-stride equality constraints in "bmap" and "context".
 * Consider the stride constraints of "context",
 *
 *	A(x) + B(y) = 0
 *
 * with y the local variables and plug in the variable compression,
 * resulting in
 *
 *	A(V x') + B(y) = 0
 *
 * Use these constraints to compute a parameter compression on x'
 *
 *	x' = T x''
 *
 * Now consider the stride constraints of "bmap"
 *
 *	C(x) + D(y) = 0
 *
 * and plug in x = V*T x''.
 * That is, return A = [C*V*T D].
 */
static __isl_give isl_mat *extract_compressed_stride_constraints(
	__isl_keep isl_basic_map *bmap, int bmap_n_eq,
	__isl_keep isl_basic_map *context, int context_n_eq)
{
	int total, n_div;
	isl_ctx *ctx;
	isl_mat *A, *B, *T, *V;

	total = isl_basic_map_dim(context, isl_dim_all);
	n_div = isl_basic_map_dim(context, isl_dim_div);
	total -= n_div;

	ctx = isl_basic_map_get_ctx(bmap);

	V = combined_variable_compression(bmap, bmap_n_eq,
						context, context_n_eq, total);

	A = isl_mat_sub_alloc6(ctx, context->eq, 0, context_n_eq, 0, 1 + total);
	B = isl_mat_sub_alloc6(ctx, context->eq,
				0, context_n_eq, 1 + total, n_div);
	A = isl_mat_product(A, isl_mat_copy(V));
	T = isl_mat_parameter_compression_ext(A, B);
	T = isl_mat_product(V, T);

	n_div = isl_basic_map_dim(bmap, isl_dim_div);
	T = isl_mat_diagonal(T, isl_mat_identity(ctx, n_div));

	A = isl_mat_sub_alloc6(ctx, bmap->eq,
				0, bmap_n_eq, 0, 1 + total + n_div);
	A = isl_mat_product(A, T);

	return A;
}

/* Remove the prime factors from *g that have an exponent that
 * is strictly smaller than the exponent in "c".
 * All exponents in *g are known to be smaller than or equal
 * to those in "c".
 *
 * That is, if *g is equal to
 *
 *	p_1^{e_1} p_2^{e_2} ... p_n^{e_n}
 *
 * and "c" is equal to
 *
 *	p_1^{f_1} p_2^{f_2} ... p_n^{f_n}
 *
 * then update *g to
 *
 *	p_1^{e_1 * (e_1 = f_1)} p_2^{e_2 * (e_2 = f_2)} ...
 *		p_n^{e_n * (e_n = f_n)}
 *
 * If e_i = f_i, then c / *g does not have any p_i factors and therefore
 * neither does the gcd of *g and c / *g.
 * If e_i < f_i, then the gcd of *g and c / *g has a positive
 * power min(e_i, s_i) of p_i with s_i = f_i - e_i among its factors.
 * Dividing *g by this gcd therefore strictly reduces the exponent
 * of the prime factors that need to be removed, while leaving the
 * other prime factors untouched.
 * Repeating this process until gcd(*g, c / *g) = 1 therefore
 * removes all undesired factors, without removing any others.
 */
static void remove_incomplete_powers(isl_int *g, isl_int c)
{
	isl_int t;

	isl_int_init(t);
	for (;;) {
		isl_int_divexact(t, c, *g);
		isl_int_gcd(t, t, *g);
		if (isl_int_is_one(t))
			break;
		isl_int_divexact(*g, *g, t);
	}
	isl_int_clear(t);
}

/* Reduce the "n" stride constraints in "bmap" based on a copy "A"
 * of the same stride constraints in a compressed space that exploits
 * all equalities in the context and the other equalities in "bmap".
 *
 * If the stride constraints of "bmap" are of the form
 *
 *	C(x) + D(y) = 0
 *
 * then A is of the form
 *
 *	B(x') + D(y) = 0
 *
 * If any of these constraints involves only a single local variable y,
 * then the constraint appears as
 *
 *	f(x) + m y_i = 0
 *
 * in "bmap" and as
 *
 *	h(x') + m y_i = 0
 *
 * in "A".
 *
 * Let g be the gcd of m and the coefficients of h.
 * Then, in particular, g is a divisor of the coefficients of h and
 *
 *	f(x) = h(x')
 *
 * is known to be a multiple of g.
 * If some prime factor in m appears with the same exponent in g,
 * then it can be removed from m because f(x) is already known
 * to be a multiple of g and therefore in particular of this power
 * of the prime factors.
 * Prime factors that appear with a smaller exponent in g cannot
 * be removed from m.
 * Let g' be the divisor of g containing all prime factors that
 * appear with the same exponent in m and g, then
 *
 *	f(x) + m y_i = 0
 *
 * can be replaced by
 *
 *	f(x) + m/g' y_i' = 0
 *
 * Note that (if g' != 1) this changes the explicit representation
 * of y_i to that of y_i', so the integer division at position i
 * is marked unknown and later recomputed by a call to
 * isl_basic_map_gauss.
 */
static __isl_give isl_basic_map *reduce_stride_constraints(
	__isl_take isl_basic_map *bmap, int n, __isl_keep isl_mat *A)
{
	int i;
	int total, n_div;
	int any = 0;
	isl_int gcd;

	if (!bmap || !A)
		return isl_basic_map_free(bmap);

	total = isl_basic_map_dim(bmap, isl_dim_all);
	n_div = isl_basic_map_dim(bmap, isl_dim_div);
	total -= n_div;

	isl_int_init(gcd);
	for (i = 0; i < n; ++i) {
		int div;

		div = isl_seq_first_non_zero(bmap->eq[i] + 1 + total, n_div);
		if (div < 0)
			isl_die(isl_basic_map_get_ctx(bmap), isl_error_internal,
				"equality constraints modified unexpectedly",
				goto error);
		if (isl_seq_first_non_zero(bmap->eq[i] + 1 + total + div + 1,
						n_div - div - 1) != -1)
			continue;
		if (isl_mat_row_gcd(A, i, &gcd) < 0)
			goto error;
		if (isl_int_is_one(gcd))
			continue;
		remove_incomplete_powers(&gcd, bmap->eq[i][1 + total + div]);
		if (isl_int_is_one(gcd))
			continue;
		isl_int_divexact(bmap->eq[i][1 + total + div],
				bmap->eq[i][1 + total + div], gcd);
		bmap = isl_basic_map_mark_div_unknown(bmap, div);
		if (!bmap)
			goto error;
		any = 1;
	}
	isl_int_clear(gcd);

	if (any)
		bmap = isl_basic_map_gauss(bmap, NULL);

	return bmap;
error:
	isl_int_clear(gcd);
	isl_basic_map_free(bmap);
	return NULL;
}

/* Simplify the stride constraints in "bmap" based on
 * the remaining equality constraints in "bmap" and all equality
 * constraints in "context".
 * Only do this if both "bmap" and "context" have stride constraints.
 *
 * First extract a copy of the stride constraints in "bmap" in a compressed
 * space exploiting all the other equality constraints and then
 * use this compressed copy to simplify the original stride constraints.
 */
static __isl_give isl_basic_map *gist_strides(__isl_take isl_basic_map *bmap,
	__isl_keep isl_basic_map *context)
{
	int bmap_n_eq, context_n_eq;
	isl_mat *A;

	if (!bmap || !context)
		return isl_basic_map_free(bmap);

	bmap_n_eq = n_div_eq(bmap);
	context_n_eq = n_div_eq(context);

	if (bmap_n_eq < 0 || context_n_eq < 0)
		return isl_basic_map_free(bmap);
	if (bmap_n_eq == 0 || context_n_eq == 0)
		return bmap;

	A = extract_compressed_stride_constraints(bmap, bmap_n_eq,
						    context, context_n_eq);
	bmap = reduce_stride_constraints(bmap, bmap_n_eq, A);

	isl_mat_free(A);

	return bmap;
}

/* Return a basic map that has the same intersection with "context" as "bmap"
 * and that is as "simple" as possible.
 *
 * The core computation is performed on the pure constraints.
 * When we add back the meaning of the integer divisions, we need
 * to (re)introduce the div constraints.  If we happen to have
 * discovered that some of these integer divisions are equal to
 * some affine combination of other variables, then these div
 * constraints may end up getting simplified in terms of the equalities,
 * resulting in extra inequalities on the other variables that
 * may have been removed already or that may not even have been
 * part of the input.  We try and remove those constraints of
 * this form that are most obviously redundant with respect to
 * the context.  We also remove those div constraints that are
 * redundant with respect to the other constraints in the result.
 *
 * The stride constraints among the equality constraints in "bmap" are
 * also simplified with respecting to the other equality constraints
 * in "bmap" and with respect to all equality constraints in "context".
 */
__isl_give isl_basic_map *isl_basic_map_gist(__isl_take isl_basic_map *bmap,
	__isl_take isl_basic_map *context)
{
	isl_basic_set *bset, *eq;
	isl_basic_map *eq_bmap;
	unsigned total, n_div, extra, n_eq, n_ineq;

	if (!bmap || !context)
		goto error;

	if (isl_basic_map_plain_is_universe(bmap)) {
		isl_basic_map_free(context);
		return bmap;
	}
	if (isl_basic_map_plain_is_empty(context)) {
		isl_space *space = isl_basic_map_get_space(bmap);
		isl_basic_map_free(bmap);
		isl_basic_map_free(context);
		return isl_basic_map_universe(space);
	}
	if (isl_basic_map_plain_is_empty(bmap)) {
		isl_basic_map_free(context);
		return bmap;
	}

	bmap = isl_basic_map_remove_redundancies(bmap);
	context = isl_basic_map_remove_redundancies(context);
	context = isl_basic_map_align_divs(context, bmap);
	if (!context)
		goto error;

	n_div = isl_basic_map_dim(context, isl_dim_div);
	total = isl_basic_map_dim(bmap, isl_dim_all);
	extra = n_div - isl_basic_map_dim(bmap, isl_dim_div);

	bset = isl_basic_map_underlying_set(isl_basic_map_copy(bmap));
	bset = isl_basic_set_add_dims(bset, isl_dim_set, extra);
	bset = uset_gist(bset,
		    isl_basic_map_underlying_set(isl_basic_map_copy(context)));
	bset = isl_basic_set_project_out(bset, isl_dim_set, total, extra);

	if (!bset || bset->n_eq == 0 || n_div == 0 ||
	    isl_basic_set_plain_is_empty(bset)) {
		isl_basic_map_free(context);
		return isl_basic_map_overlying_set(bset, bmap);
	}

	n_eq = bset->n_eq;
	n_ineq = bset->n_ineq;
	eq = isl_basic_set_copy(bset);
	eq = isl_basic_set_cow(eq);
	if (isl_basic_set_free_inequality(eq, n_ineq) < 0)
		eq = isl_basic_set_free(eq);
	if (isl_basic_set_free_equality(bset, n_eq) < 0)
		bset = isl_basic_set_free(bset);

	eq_bmap = isl_basic_map_overlying_set(eq, isl_basic_map_copy(bmap));
	eq_bmap = gist_strides(eq_bmap, context);
	eq_bmap = isl_basic_map_remove_shifted_constraints(eq_bmap, context);
	bmap = isl_basic_map_overlying_set(bset, bmap);
	bmap = isl_basic_map_intersect(bmap, eq_bmap);
	bmap = isl_basic_map_remove_redundancies(bmap);

	return bmap;
error:
	isl_basic_map_free(bmap);
	isl_basic_map_free(context);
	return NULL;
}

/*
 * Assumes context has no implicit divs.
 */
__isl_give isl_map *isl_map_gist_basic_map(__isl_take isl_map *map,
	__isl_take isl_basic_map *context)
{
	int i;

	if (!map || !context)
		goto error;

	if (isl_basic_map_plain_is_empty(context)) {
		isl_space *space = isl_map_get_space(map);
		isl_map_free(map);
		isl_basic_map_free(context);
		return isl_map_universe(space);
	}

	context = isl_basic_map_remove_redundancies(context);
	map = isl_map_cow(map);
	if (!map || !context)
		goto error;
	isl_assert(map->ctx, isl_space_is_equal(map->dim, context->dim), goto error);
	map = isl_map_compute_divs(map);
	if (!map)
		goto error;
	for (i = map->n - 1; i >= 0; --i) {
		map->p[i] = isl_basic_map_gist(map->p[i],
						isl_basic_map_copy(context));
		if (!map->p[i])
			goto error;
		if (isl_basic_map_plain_is_empty(map->p[i])) {
			isl_basic_map_free(map->p[i]);
			if (i != map->n - 1)
				map->p[i] = map->p[map->n - 1];
			map->n--;
		}
	}
	isl_basic_map_free(context);
	ISL_F_CLR(map, ISL_MAP_NORMALIZED);
	return map;
error:
	isl_map_free(map);
	isl_basic_map_free(context);
	return NULL;
}

/* Drop all inequalities from "bmap" that also appear in "context".
 * "context" is assumed to have only known local variables and
 * the initial local variables of "bmap" are assumed to be the same
 * as those of "context".
 * The constraints of both "bmap" and "context" are assumed
 * to have been sorted using isl_basic_map_sort_constraints.
 *
 * Run through the inequality constraints of "bmap" and "context"
 * in sorted order.
 * If a constraint of "bmap" involves variables not in "context",
 * then it cannot appear in "context".
 * If a matching constraint is found, it is removed from "bmap".
 */
static __isl_give isl_basic_map *drop_inequalities(
	__isl_take isl_basic_map *bmap, __isl_keep isl_basic_map *context)
{
	int i1, i2;
	unsigned total, extra;

	if (!bmap || !context)
		return isl_basic_map_free(bmap);

	total = isl_basic_map_total_dim(context);
	extra = isl_basic_map_total_dim(bmap) - total;

	i1 = bmap->n_ineq - 1;
	i2 = context->n_ineq - 1;
	while (bmap && i1 >= 0 && i2 >= 0) {
		int cmp;

		if (isl_seq_first_non_zero(bmap->ineq[i1] + 1 + total,
					    extra) != -1) {
			--i1;
			continue;
		}
		cmp = isl_basic_map_constraint_cmp(context, bmap->ineq[i1],
							context->ineq[i2]);
		if (cmp < 0) {
			--i2;
			continue;
		}
		if (cmp > 0) {
			--i1;
			continue;
		}
		if (isl_int_eq(bmap->ineq[i1][0], context->ineq[i2][0])) {
			bmap = isl_basic_map_cow(bmap);
			if (isl_basic_map_drop_inequality(bmap, i1) < 0)
				bmap = isl_basic_map_free(bmap);
		}
		--i1;
		--i2;
	}

	return bmap;
}

/* Drop all equalities from "bmap" that also appear in "context".
 * "context" is assumed to have only known local variables and
 * the initial local variables of "bmap" are assumed to be the same
 * as those of "context".
 *
 * Run through the equality constraints of "bmap" and "context"
 * in sorted order.
 * If a constraint of "bmap" involves variables not in "context",
 * then it cannot appear in "context".
 * If a matching constraint is found, it is removed from "bmap".
 */
static __isl_give isl_basic_map *drop_equalities(
	__isl_take isl_basic_map *bmap, __isl_keep isl_basic_map *context)
{
	int i1, i2;
	unsigned total, extra;

	if (!bmap || !context)
		return isl_basic_map_free(bmap);

	total = isl_basic_map_total_dim(context);
	extra = isl_basic_map_total_dim(bmap) - total;

	i1 = bmap->n_eq - 1;
	i2 = context->n_eq - 1;

	while (bmap && i1 >= 0 && i2 >= 0) {
		int last1, last2;

		if (isl_seq_first_non_zero(bmap->eq[i1] + 1 + total,
					    extra) != -1)
			break;
		last1 = isl_seq_last_non_zero(bmap->eq[i1] + 1, total);
		last2 = isl_seq_last_non_zero(context->eq[i2] + 1, total);
		if (last1 > last2) {
			--i2;
			continue;
		}
		if (last1 < last2) {
			--i1;
			continue;
		}
		if (isl_seq_eq(bmap->eq[i1], context->eq[i2], 1 + total)) {
			bmap = isl_basic_map_cow(bmap);
			if (isl_basic_map_drop_equality(bmap, i1) < 0)
				bmap = isl_basic_map_free(bmap);
		}
		--i1;
		--i2;
	}

	return bmap;
}

/* Remove the constraints in "context" from "bmap".
 * "context" is assumed to have explicit representations
 * for all local variables.
 *
 * First align the divs of "bmap" to those of "context" and
 * sort the constraints.  Then drop all constraints from "bmap"
 * that appear in "context".
 */
__isl_give isl_basic_map *isl_basic_map_plain_gist(
	__isl_take isl_basic_map *bmap, __isl_take isl_basic_map *context)
{
	isl_bool done, known;

	done = isl_basic_map_plain_is_universe(context);
	if (done == isl_bool_false)
		done = isl_basic_map_plain_is_universe(bmap);
	if (done == isl_bool_false)
		done = isl_basic_map_plain_is_empty(context);
	if (done == isl_bool_false)
		done = isl_basic_map_plain_is_empty(bmap);
	if (done < 0)
		goto error;
	if (done) {
		isl_basic_map_free(context);
		return bmap;
	}
	known = isl_basic_map_divs_known(context);
	if (known < 0)
		goto error;
	if (!known)
		isl_die(isl_basic_map_get_ctx(bmap), isl_error_invalid,
			"context has unknown divs", goto error);

	bmap = isl_basic_map_align_divs(bmap, context);
	bmap = isl_basic_map_gauss(bmap, NULL);
	bmap = isl_basic_map_sort_constraints(bmap);
	context = isl_basic_map_sort_constraints(context);

	bmap = drop_inequalities(bmap, context);
	bmap = drop_equalities(bmap, context);

	isl_basic_map_free(context);
	bmap = isl_basic_map_finalize(bmap);
	return bmap;
error:
	isl_basic_map_free(bmap);
	isl_basic_map_free(context);
	return NULL;
}

/* Replace "map" by the disjunct at position "pos" and free "context".
 */
static __isl_give isl_map *replace_by_disjunct(__isl_take isl_map *map,
	int pos, __isl_take isl_basic_map *context)
{
	isl_basic_map *bmap;

	bmap = isl_basic_map_copy(map->p[pos]);
	isl_map_free(map);
	isl_basic_map_free(context);
	return isl_map_from_basic_map(bmap);
}

/* Remove the constraints in "context" from "map".
 * If any of the disjuncts in the result turns out to be the universe,
 * then return this universe.
 * "context" is assumed to have explicit representations
 * for all local variables.
 */
__isl_give isl_map *isl_map_plain_gist_basic_map(__isl_take isl_map *map,
	__isl_take isl_basic_map *context)
{
	int i;
	isl_bool univ, known;

	univ = isl_basic_map_plain_is_universe(context);
	if (univ < 0)
		goto error;
	if (univ) {
		isl_basic_map_free(context);
		return map;
	}
	known = isl_basic_map_divs_known(context);
	if (known < 0)
		goto error;
	if (!known)
		isl_die(isl_map_get_ctx(map), isl_error_invalid,
			"context has unknown divs", goto error);

	map = isl_map_cow(map);
	if (!map)
		goto error;
	for (i = 0; i < map->n; ++i) {
		map->p[i] = isl_basic_map_plain_gist(map->p[i],
						isl_basic_map_copy(context));
		univ = isl_basic_map_plain_is_universe(map->p[i]);
		if (univ < 0)
			goto error;
		if (univ && map->n > 1)
			return replace_by_disjunct(map, i, context);
	}

	isl_basic_map_free(context);
	ISL_F_CLR(map, ISL_MAP_NORMALIZED);
	if (map->n > 1)
		ISL_F_CLR(map, ISL_MAP_DISJOINT);
	return map;
error:
	isl_map_free(map);
	isl_basic_map_free(context);
	return NULL;
}

/* Remove the constraints in "context" from "set".
 * If any of the disjuncts in the result turns out to be the universe,
 * then return this universe.
 * "context" is assumed to have explicit representations
 * for all local variables.
 */
__isl_give isl_set *isl_set_plain_gist_basic_set(__isl_take isl_set *set,
	__isl_take isl_basic_set *context)
{
	return set_from_map(isl_map_plain_gist_basic_map(set_to_map(set),
							bset_to_bmap(context)));
}

/* Remove the constraints in "context" from "map".
 * If any of the disjuncts in the result turns out to be the universe,
 * then return this universe.
 * "context" is assumed to consist of a single disjunct and
 * to have explicit representations for all local variables.
 */
__isl_give isl_map *isl_map_plain_gist(__isl_take isl_map *map,
	__isl_take isl_map *context)
{
	isl_basic_map *hull;

	hull = isl_map_unshifted_simple_hull(context);
	return isl_map_plain_gist_basic_map(map, hull);
}

/* Replace "map" by a universe map in the same space and free "drop".
 */
static __isl_give isl_map *replace_by_universe(__isl_take isl_map *map,
	__isl_take isl_map *drop)
{
	isl_map *res;

	res = isl_map_universe(isl_map_get_space(map));
	isl_map_free(map);
	isl_map_free(drop);
	return res;
}

/* Return a map that has the same intersection with "context" as "map"
 * and that is as "simple" as possible.
 *
 * If "map" is already the universe, then we cannot make it any simpler.
 * Similarly, if "context" is the universe, then we cannot exploit it
 * to simplify "map"
 * If "map" and "context" are identical to each other, then we can
 * return the corresponding universe.
 *
 * If either "map" or "context" consists of multiple disjuncts,
 * then check if "context" happens to be a subset of "map",
 * in which case all constraints can be removed.
 * In case of multiple disjuncts, the standard procedure
 * may not be able to detect that all constraints can be removed.
 *
 * If none of these cases apply, we have to work a bit harder.
 * During this computation, we make use of a single disjunct context,
 * so if the original context consists of more than one disjunct
 * then we need to approximate the context by a single disjunct set.
 * Simply taking the simple hull may drop constraints that are
 * only implicitly available in each disjunct.  We therefore also
 * look for constraints among those defining "map" that are valid
 * for the context.  These can then be used to simplify away
 * the corresponding constraints in "map".
 */
static __isl_give isl_map *map_gist(__isl_take isl_map *map,
	__isl_take isl_map *context)
{
	int equal;
	int is_universe;
	int single_disjunct_map, single_disjunct_context;
	isl_bool subset;
	isl_basic_map *hull;

	is_universe = isl_map_plain_is_universe(map);
	if (is_universe >= 0 && !is_universe)
		is_universe = isl_map_plain_is_universe(context);
	if (is_universe < 0)
		goto error;
	if (is_universe) {
		isl_map_free(context);
		return map;
	}

	equal = isl_map_plain_is_equal(map, context);
	if (equal < 0)
		goto error;
	if (equal)
		return replace_by_universe(map, context);

	single_disjunct_map = isl_map_n_basic_map(map) == 1;
	single_disjunct_context = isl_map_n_basic_map(context) == 1;
	if (!single_disjunct_map || !single_disjunct_context) {
		subset = isl_map_is_subset(context, map);
		if (subset < 0)
			goto error;
		if (subset)
			return replace_by_universe(map, context);
	}

	context = isl_map_compute_divs(context);
	if (!context)
		goto error;
	if (single_disjunct_context) {
		hull = isl_map_simple_hull(context);
	} else {
		isl_ctx *ctx;
		isl_map_list *list;

		ctx = isl_map_get_ctx(map);
		list = isl_map_list_alloc(ctx, 2);
		list = isl_map_list_add(list, isl_map_copy(context));
		list = isl_map_list_add(list, isl_map_copy(map));
		hull = isl_map_unshifted_simple_hull_from_map_list(context,
								    list);
	}
	return isl_map_gist_basic_map(map, hull);
error:
	isl_map_free(map);
	isl_map_free(context);
	return NULL;
}

__isl_give isl_map *isl_map_gist(__isl_take isl_map *map,
	__isl_take isl_map *context)
{
	return isl_map_align_params_map_map_and(map, context, &map_gist);
}

struct isl_basic_set *isl_basic_set_gist(struct isl_basic_set *bset,
						struct isl_basic_set *context)
{
	return bset_from_bmap(isl_basic_map_gist(bset_to_bmap(bset),
						bset_to_bmap(context)));
}

__isl_give isl_set *isl_set_gist_basic_set(__isl_take isl_set *set,
	__isl_take isl_basic_set *context)
{
	return set_from_map(isl_map_gist_basic_map(set_to_map(set),
					bset_to_bmap(context)));
}

__isl_give isl_set *isl_set_gist_params_basic_set(__isl_take isl_set *set,
	__isl_take isl_basic_set *context)
{
	isl_space *space = isl_set_get_space(set);
	isl_basic_set *dom_context = isl_basic_set_universe(space);
	dom_context = isl_basic_set_intersect_params(dom_context, context);
	return isl_set_gist_basic_set(set, dom_context);
}

__isl_give isl_set *isl_set_gist(__isl_take isl_set *set,
	__isl_take isl_set *context)
{
	return set_from_map(isl_map_gist(set_to_map(set), set_to_map(context)));
}

/* Compute the gist of "bmap" with respect to the constraints "context"
 * on the domain.
 */
__isl_give isl_basic_map *isl_basic_map_gist_domain(
	__isl_take isl_basic_map *bmap, __isl_take isl_basic_set *context)
{
	isl_space *space = isl_basic_map_get_space(bmap);
	isl_basic_map *bmap_context = isl_basic_map_universe(space);

	bmap_context = isl_basic_map_intersect_domain(bmap_context, context);
	return isl_basic_map_gist(bmap, bmap_context);
}

__isl_give isl_map *isl_map_gist_domain(__isl_take isl_map *map,
	__isl_take isl_set *context)
{
	isl_map *map_context = isl_map_universe(isl_map_get_space(map));
	map_context = isl_map_intersect_domain(map_context, context);
	return isl_map_gist(map, map_context);
}

__isl_give isl_map *isl_map_gist_range(__isl_take isl_map *map,
	__isl_take isl_set *context)
{
	isl_map *map_context = isl_map_universe(isl_map_get_space(map));
	map_context = isl_map_intersect_range(map_context, context);
	return isl_map_gist(map, map_context);
}

__isl_give isl_map *isl_map_gist_params(__isl_take isl_map *map,
	__isl_take isl_set *context)
{
	isl_map *map_context = isl_map_universe(isl_map_get_space(map));
	map_context = isl_map_intersect_params(map_context, context);
	return isl_map_gist(map, map_context);
}

__isl_give isl_set *isl_set_gist_params(__isl_take isl_set *set,
	__isl_take isl_set *context)
{
	return isl_map_gist_params(set, context);
}

/* Quick check to see if two basic maps are disjoint.
 * In particular, we reduce the equalities and inequalities of
 * one basic map in the context of the equalities of the other
 * basic map and check if we get a contradiction.
 */
isl_bool isl_basic_map_plain_is_disjoint(__isl_keep isl_basic_map *bmap1,
	__isl_keep isl_basic_map *bmap2)
{
	struct isl_vec *v = NULL;
	int *elim = NULL;
	unsigned total;
	int i;

	if (!bmap1 || !bmap2)
		return isl_bool_error;
	isl_assert(bmap1->ctx, isl_space_is_equal(bmap1->dim, bmap2->dim),
			return isl_bool_error);
	if (bmap1->n_div || bmap2->n_div)
		return isl_bool_false;
	if (!bmap1->n_eq && !bmap2->n_eq)
		return isl_bool_false;

	total = isl_space_dim(bmap1->dim, isl_dim_all);
	if (total == 0)
		return isl_bool_false;
	v = isl_vec_alloc(bmap1->ctx, 1 + total);
	if (!v)
		goto error;
	elim = isl_alloc_array(bmap1->ctx, int, total);
	if (!elim)
		goto error;
	compute_elimination_index(bmap1, elim);
	for (i = 0; i < bmap2->n_eq; ++i) {
		int reduced;
		reduced = reduced_using_equalities(v->block.data, bmap2->eq[i],
							bmap1, elim);
		if (reduced && !isl_int_is_zero(v->block.data[0]) &&
		    isl_seq_first_non_zero(v->block.data + 1, total) == -1)
			goto disjoint;
	}
	for (i = 0; i < bmap2->n_ineq; ++i) {
		int reduced;
		reduced = reduced_using_equalities(v->block.data,
						bmap2->ineq[i], bmap1, elim);
		if (reduced && isl_int_is_neg(v->block.data[0]) &&
		    isl_seq_first_non_zero(v->block.data + 1, total) == -1)
			goto disjoint;
	}
	compute_elimination_index(bmap2, elim);
	for (i = 0; i < bmap1->n_ineq; ++i) {
		int reduced;
		reduced = reduced_using_equalities(v->block.data,
						bmap1->ineq[i], bmap2, elim);
		if (reduced && isl_int_is_neg(v->block.data[0]) &&
		    isl_seq_first_non_zero(v->block.data + 1, total) == -1)
			goto disjoint;
	}
	isl_vec_free(v);
	free(elim);
	return isl_bool_false;
disjoint:
	isl_vec_free(v);
	free(elim);
	return isl_bool_true;
error:
	isl_vec_free(v);
	free(elim);
	return isl_bool_error;
}

int isl_basic_set_plain_is_disjoint(__isl_keep isl_basic_set *bset1,
	__isl_keep isl_basic_set *bset2)
{
	return isl_basic_map_plain_is_disjoint(bset_to_bmap(bset1),
					      bset_to_bmap(bset2));
}

/* Does "test" hold for all pairs of basic maps in "map1" and "map2"?
 */
static isl_bool all_pairs(__isl_keep isl_map *map1, __isl_keep isl_map *map2,
	isl_bool (*test)(__isl_keep isl_basic_map *bmap1,
		__isl_keep isl_basic_map *bmap2))
{
	int i, j;

	if (!map1 || !map2)
		return isl_bool_error;

	for (i = 0; i < map1->n; ++i) {
		for (j = 0; j < map2->n; ++j) {
			isl_bool d = test(map1->p[i], map2->p[j]);
			if (d != isl_bool_true)
				return d;
		}
	}

	return isl_bool_true;
}

/* Are "map1" and "map2" obviously disjoint, based on information
 * that can be derived without looking at the individual basic maps?
 *
 * In particular, if one of them is empty or if they live in different spaces
 * (ignoring parameters), then they are clearly disjoint.
 */
static isl_bool isl_map_plain_is_disjoint_global(__isl_keep isl_map *map1,
	__isl_keep isl_map *map2)
{
	isl_bool disjoint;
	isl_bool match;

	if (!map1 || !map2)
		return isl_bool_error;

	disjoint = isl_map_plain_is_empty(map1);
	if (disjoint < 0 || disjoint)
		return disjoint;

	disjoint = isl_map_plain_is_empty(map2);
	if (disjoint < 0 || disjoint)
		return disjoint;

	match = isl_space_tuple_is_equal(map1->dim, isl_dim_in,
				map2->dim, isl_dim_in);
	if (match < 0 || !match)
		return match < 0 ? isl_bool_error : isl_bool_true;

	match = isl_space_tuple_is_equal(map1->dim, isl_dim_out,
				map2->dim, isl_dim_out);
	if (match < 0 || !match)
		return match < 0 ? isl_bool_error : isl_bool_true;

	return isl_bool_false;
}

/* Are "map1" and "map2" obviously disjoint?
 *
 * If one of them is empty or if they live in different spaces (ignoring
 * parameters), then they are clearly disjoint.
 * This is checked by isl_map_plain_is_disjoint_global.
 *
 * If they have different parameters, then we skip any further tests.
 *
 * If they are obviously equal, but not obviously empty, then we will
 * not be able to detect if they are disjoint.
 *
 * Otherwise we check if each basic map in "map1" is obviously disjoint
 * from each basic map in "map2".
 */
isl_bool isl_map_plain_is_disjoint(__isl_keep isl_map *map1,
	__isl_keep isl_map *map2)
{
	isl_bool disjoint;
	isl_bool intersect;
	isl_bool match;

	disjoint = isl_map_plain_is_disjoint_global(map1, map2);
	if (disjoint < 0 || disjoint)
		return disjoint;

	match = isl_map_has_equal_params(map1, map2);
	if (match < 0 || !match)
		return match < 0 ? isl_bool_error : isl_bool_false;

	intersect = isl_map_plain_is_equal(map1, map2);
	if (intersect < 0 || intersect)
		return intersect < 0 ? isl_bool_error : isl_bool_false;

	return all_pairs(map1, map2, &isl_basic_map_plain_is_disjoint);
}

/* Are "map1" and "map2" disjoint?
 * The parameters are assumed to have been aligned.
 *
 * In particular, check whether all pairs of basic maps are disjoint.
 */
static isl_bool isl_map_is_disjoint_aligned(__isl_keep isl_map *map1,
	__isl_keep isl_map *map2)
{
	return all_pairs(map1, map2, &isl_basic_map_is_disjoint);
}

/* Are "map1" and "map2" disjoint?
 *
 * They are disjoint if they are "obviously disjoint" or if one of them
 * is empty.  Otherwise, they are not disjoint if one of them is universal.
 * If the two inputs are (obviously) equal and not empty, then they are
 * not disjoint.
 * If none of these cases apply, then check if all pairs of basic maps
 * are disjoint after aligning the parameters.
 */
isl_bool isl_map_is_disjoint(__isl_keep isl_map *map1, __isl_keep isl_map *map2)
{
	isl_bool disjoint;
	isl_bool intersect;

	disjoint = isl_map_plain_is_disjoint_global(map1, map2);
	if (disjoint < 0 || disjoint)
		return disjoint;

	disjoint = isl_map_is_empty(map1);
	if (disjoint < 0 || disjoint)
		return disjoint;

	disjoint = isl_map_is_empty(map2);
	if (disjoint < 0 || disjoint)
		return disjoint;

	intersect = isl_map_plain_is_universe(map1);
	if (intersect < 0 || intersect)
		return intersect < 0 ? isl_bool_error : isl_bool_false;

	intersect = isl_map_plain_is_universe(map2);
	if (intersect < 0 || intersect)
		return intersect < 0 ? isl_bool_error : isl_bool_false;

	intersect = isl_map_plain_is_equal(map1, map2);
	if (intersect < 0 || intersect)
		return isl_bool_not(intersect);

	return isl_map_align_params_map_map_and_test(map1, map2,
						&isl_map_is_disjoint_aligned);
}

/* Are "bmap1" and "bmap2" disjoint?
 *
 * They are disjoint if they are "obviously disjoint" or if one of them
 * is empty.  Otherwise, they are not disjoint if one of them is universal.
 * If none of these cases apply, we compute the intersection and see if
 * the result is empty.
 */
isl_bool isl_basic_map_is_disjoint(__isl_keep isl_basic_map *bmap1,
	__isl_keep isl_basic_map *bmap2)
{
	isl_bool disjoint;
	isl_bool intersect;
	isl_basic_map *test;

	disjoint = isl_basic_map_plain_is_disjoint(bmap1, bmap2);
	if (disjoint < 0 || disjoint)
		return disjoint;

	disjoint = isl_basic_map_is_empty(bmap1);
	if (disjoint < 0 || disjoint)
		return disjoint;

	disjoint = isl_basic_map_is_empty(bmap2);
	if (disjoint < 0 || disjoint)
		return disjoint;

	intersect = isl_basic_map_plain_is_universe(bmap1);
	if (intersect < 0 || intersect)
		return intersect < 0 ? isl_bool_error : isl_bool_false;

	intersect = isl_basic_map_plain_is_universe(bmap2);
	if (intersect < 0 || intersect)
		return intersect < 0 ? isl_bool_error : isl_bool_false;

	test = isl_basic_map_intersect(isl_basic_map_copy(bmap1),
		isl_basic_map_copy(bmap2));
	disjoint = isl_basic_map_is_empty(test);
	isl_basic_map_free(test);

	return disjoint;
}

/* Are "bset1" and "bset2" disjoint?
 */
isl_bool isl_basic_set_is_disjoint(__isl_keep isl_basic_set *bset1,
	__isl_keep isl_basic_set *bset2)
{
	return isl_basic_map_is_disjoint(bset1, bset2);
}

isl_bool isl_set_plain_is_disjoint(__isl_keep isl_set *set1,
	__isl_keep isl_set *set2)
{
	return isl_map_plain_is_disjoint(set_to_map(set1), set_to_map(set2));
}

/* Are "set1" and "set2" disjoint?
 */
isl_bool isl_set_is_disjoint(__isl_keep isl_set *set1, __isl_keep isl_set *set2)
{
	return isl_map_is_disjoint(set1, set2);
}

/* Is "v" equal to 0, 1 or -1?
 */
static int is_zero_or_one(isl_int v)
{
	return isl_int_is_zero(v) || isl_int_is_one(v) || isl_int_is_negone(v);
}

/* Check if we can combine a given div with lower bound l and upper
 * bound u with some other div and if so return that other div.
 * Otherwise return -1.
 *
 * We first check that
 *	- the bounds are opposites of each other (except for the constant
 *	  term)
 *	- the bounds do not reference any other div
 *	- no div is defined in terms of this div
 *
 * Let m be the size of the range allowed on the div by the bounds.
 * That is, the bounds are of the form
 *
 *	e <= a <= e + m - 1
 *
 * with e some expression in the other variables.
 * We look for another div b such that no third div is defined in terms
 * of this second div b and such that in any constraint that contains
 * a (except for the given lower and upper bound), also contains b
 * with a coefficient that is m times that of b.
 * That is, all constraints (except for the lower and upper bound)
 * are of the form
 *
 *	e + f (a + m b) >= 0
 *
 * Furthermore, in the constraints that only contain b, the coefficient
 * of b should be equal to 1 or -1.
 * If so, we return b so that "a + m b" can be replaced by
 * a single div "c = a + m b".
 */
static int div_find_coalesce(struct isl_basic_map *bmap, int *pairs,
	unsigned div, unsigned l, unsigned u)
{
	int i, j;
	unsigned dim;
	int coalesce = -1;

	if (bmap->n_div <= 1)
		return -1;
	dim = isl_space_dim(bmap->dim, isl_dim_all);
	if (isl_seq_first_non_zero(bmap->ineq[l] + 1 + dim, div) != -1)
		return -1;
	if (isl_seq_first_non_zero(bmap->ineq[l] + 1 + dim + div + 1,
				   bmap->n_div - div - 1) != -1)
		return -1;
	if (!isl_seq_is_neg(bmap->ineq[l] + 1, bmap->ineq[u] + 1,
			    dim + bmap->n_div))
		return -1;

	for (i = 0; i < bmap->n_div; ++i) {
		if (isl_int_is_zero(bmap->div[i][0]))
			continue;
		if (!isl_int_is_zero(bmap->div[i][1 + 1 + dim + div]))
			return -1;
	}

	isl_int_add(bmap->ineq[l][0], bmap->ineq[l][0], bmap->ineq[u][0]);
	if (isl_int_is_neg(bmap->ineq[l][0])) {
		isl_int_sub(bmap->ineq[l][0],
			    bmap->ineq[l][0], bmap->ineq[u][0]);
		bmap = isl_basic_map_copy(bmap);
		bmap = isl_basic_map_set_to_empty(bmap);
		isl_basic_map_free(bmap);
		return -1;
	}
	isl_int_add_ui(bmap->ineq[l][0], bmap->ineq[l][0], 1);
	for (i = 0; i < bmap->n_div; ++i) {
		if (i == div)
			continue;
		if (!pairs[i])
			continue;
		for (j = 0; j < bmap->n_div; ++j) {
			if (isl_int_is_zero(bmap->div[j][0]))
				continue;
			if (!isl_int_is_zero(bmap->div[j][1 + 1 + dim + i]))
				break;
		}
		if (j < bmap->n_div)
			continue;
		for (j = 0; j < bmap->n_ineq; ++j) {
			int valid;
			if (j == l || j == u)
				continue;
			if (isl_int_is_zero(bmap->ineq[j][1 + dim + div])) {
				if (is_zero_or_one(bmap->ineq[j][1 + dim + i]))
					continue;
				break;
			}
			if (isl_int_is_zero(bmap->ineq[j][1 + dim + i]))
				break;
			isl_int_mul(bmap->ineq[j][1 + dim + div],
				    bmap->ineq[j][1 + dim + div],
				    bmap->ineq[l][0]);
			valid = isl_int_eq(bmap->ineq[j][1 + dim + div],
					   bmap->ineq[j][1 + dim + i]);
			isl_int_divexact(bmap->ineq[j][1 + dim + div],
					 bmap->ineq[j][1 + dim + div],
					 bmap->ineq[l][0]);
			if (!valid)
				break;
		}
		if (j < bmap->n_ineq)
			continue;
		coalesce = i;
		break;
	}
	isl_int_sub_ui(bmap->ineq[l][0], bmap->ineq[l][0], 1);
	isl_int_sub(bmap->ineq[l][0], bmap->ineq[l][0], bmap->ineq[u][0]);
	return coalesce;
}

/* Internal data structure used during the construction and/or evaluation of
 * an inequality that ensures that a pair of bounds always allows
 * for an integer value.
 *
 * "tab" is the tableau in which the inequality is evaluated.  It may
 * be NULL until it is actually needed.
 * "v" contains the inequality coefficients.
 * "g", "fl" and "fu" are temporary scalars used during the construction and
 * evaluation.
 */
struct test_ineq_data {
	struct isl_tab *tab;
	isl_vec *v;
	isl_int g;
	isl_int fl;
	isl_int fu;
};

/* Free all the memory allocated by the fields of "data".
 */
static void test_ineq_data_clear(struct test_ineq_data *data)
{
	isl_tab_free(data->tab);
	isl_vec_free(data->v);
	isl_int_clear(data->g);
	isl_int_clear(data->fl);
	isl_int_clear(data->fu);
}

/* Is the inequality stored in data->v satisfied by "bmap"?
 * That is, does it only attain non-negative values?
 * data->tab is a tableau corresponding to "bmap".
 */
static isl_bool test_ineq_is_satisfied(__isl_keep isl_basic_map *bmap,
	struct test_ineq_data *data)
{
	isl_ctx *ctx;
	enum isl_lp_result res;

	ctx = isl_basic_map_get_ctx(bmap);
	if (!data->tab)
		data->tab = isl_tab_from_basic_map(bmap, 0);
	res = isl_tab_min(data->tab, data->v->el, ctx->one, &data->g, NULL, 0);
	if (res == isl_lp_error)
		return isl_bool_error;
	return res == isl_lp_ok && isl_int_is_nonneg(data->g);
}

/* Given a lower and an upper bound on div i, do they always allow
 * for an integer value of the given div?
 * Determine this property by constructing an inequality
 * such that the property is guaranteed when the inequality is nonnegative.
 * The lower bound is inequality l, while the upper bound is inequality u.
 * The constructed inequality is stored in data->v.
 *
 * Let the upper bound be
 *
 *	-n_u a + e_u >= 0
 *
 * and the lower bound
 *
 *	n_l a + e_l >= 0
 *
 * Let n_u = f_u g and n_l = f_l g, with g = gcd(n_u, n_l).
 * We have
 *
 *	- f_u e_l <= f_u f_l g a <= f_l e_u
 *
 * Since all variables are integer valued, this is equivalent to
 *
 *	- f_u e_l - (f_u - 1) <= f_u f_l g a <= f_l e_u + (f_l - 1)
 *
 * If this interval is at least f_u f_l g, then it contains at least
 * one integer value for a.
 * That is, the test constraint is
 *
 *	f_l e_u + f_u e_l + f_l - 1 + f_u - 1 + 1 >= f_u f_l g
 *
 * or
 *
 *	f_l e_u + f_u e_l + f_l - 1 + f_u - 1 + 1 - f_u f_l g >= 0
 *
 * If the coefficients of f_l e_u + f_u e_l have a common divisor g',
 * then the constraint can be scaled down by a factor g',
 * with the constant term replaced by
 * floor((f_l e_{u,0} + f_u e_{l,0} + f_l - 1 + f_u - 1 + 1 - f_u f_l g)/g').
 * Note that the result of applying Fourier-Motzkin to this pair
 * of constraints is
 *
 *	f_l e_u + f_u e_l >= 0
 *
 * If the constant term of the scaled down version of this constraint,
 * i.e., floor((f_l e_{u,0} + f_u e_{l,0})/g') is equal to the constant
 * term of the scaled down test constraint, then the test constraint
 * is known to hold and no explicit evaluation is required.
 * This is essentially the Omega test.
 *
 * If the test constraint consists of only a constant term, then
 * it is sufficient to look at the sign of this constant term.
 */
static isl_bool int_between_bounds(__isl_keep isl_basic_map *bmap, int i,
	int l, int u, struct test_ineq_data *data)
{
	unsigned offset, n_div;
	offset = isl_basic_map_offset(bmap, isl_dim_div);
	n_div = isl_basic_map_dim(bmap, isl_dim_div);

	isl_int_gcd(data->g,
		    bmap->ineq[l][offset + i], bmap->ineq[u][offset + i]);
	isl_int_divexact(data->fl, bmap->ineq[l][offset + i], data->g);
	isl_int_divexact(data->fu, bmap->ineq[u][offset + i], data->g);
	isl_int_neg(data->fu, data->fu);
	isl_seq_combine(data->v->el, data->fl, bmap->ineq[u],
			data->fu, bmap->ineq[l], offset + n_div);
	isl_int_mul(data->g, data->g, data->fl);
	isl_int_mul(data->g, data->g, data->fu);
	isl_int_sub(data->g, data->g, data->fl);
	isl_int_sub(data->g, data->g, data->fu);
	isl_int_add_ui(data->g, data->g, 1);
	isl_int_sub(data->fl, data->v->el[0], data->g);

	isl_seq_gcd(data->v->el + 1, offset - 1 + n_div, &data->g);
	if (isl_int_is_zero(data->g))
		return isl_int_is_nonneg(data->fl);
	if (isl_int_is_one(data->g)) {
		isl_int_set(data->v->el[0], data->fl);
		return test_ineq_is_satisfied(bmap, data);
	}
	isl_int_fdiv_q(data->fl, data->fl, data->g);
	isl_int_fdiv_q(data->v->el[0], data->v->el[0], data->g);
	if (isl_int_eq(data->fl, data->v->el[0]))
		return isl_bool_true;
	isl_int_set(data->v->el[0], data->fl);
	isl_seq_scale_down(data->v->el + 1, data->v->el + 1, data->g,
			    offset - 1 + n_div);

	return test_ineq_is_satisfied(bmap, data);
}

/* Remove more kinds of divs that are not strictly needed.
 * In particular, if all pairs of lower and upper bounds on a div
 * are such that they allow at least one integer value of the div,
 * then we can eliminate the div using Fourier-Motzkin without
 * introducing any spurious solutions.
 *
 * If at least one of the two constraints has a unit coefficient for the div,
 * then the presence of such a value is guaranteed so there is no need to check.
 * In particular, the value attained by the bound with unit coefficient
 * can serve as this intermediate value.
 */
static __isl_give isl_basic_map *drop_more_redundant_divs(
	__isl_take isl_basic_map *bmap, __isl_take int *pairs, int n)
{
	isl_ctx *ctx;
	struct test_ineq_data data = { NULL, NULL };
	unsigned off, n_div;
	int remove = -1;

	isl_int_init(data.g);
	isl_int_init(data.fl);
	isl_int_init(data.fu);

	if (!bmap)
		goto error;

	ctx = isl_basic_map_get_ctx(bmap);
	off = isl_basic_map_offset(bmap, isl_dim_div);
	n_div = isl_basic_map_dim(bmap, isl_dim_div);
	data.v = isl_vec_alloc(ctx, off + n_div);
	if (!data.v)
		goto error;

	while (n > 0) {
		int i, l, u;
		int best = -1;
		isl_bool has_int;

		for (i = 0; i < n_div; ++i) {
			if (!pairs[i])
				continue;
			if (best >= 0 && pairs[best] <= pairs[i])
				continue;
			best = i;
		}

		i = best;
		for (l = 0; l < bmap->n_ineq; ++l) {
			if (!isl_int_is_pos(bmap->ineq[l][off + i]))
				continue;
			if (isl_int_is_one(bmap->ineq[l][off + i]))
				continue;
			for (u = 0; u < bmap->n_ineq; ++u) {
				if (!isl_int_is_neg(bmap->ineq[u][off + i]))
					continue;
				if (isl_int_is_negone(bmap->ineq[u][off + i]))
					continue;
				has_int = int_between_bounds(bmap, i, l, u,
								&data);
				if (has_int < 0)
					goto error;
				if (data.tab && data.tab->empty)
					break;
				if (!has_int)
					break;
			}
			if (u < bmap->n_ineq)
				break;
		}
		if (data.tab && data.tab->empty) {
			bmap = isl_basic_map_set_to_empty(bmap);
			break;
		}
		if (l == bmap->n_ineq) {
			remove = i;
			break;
		}
		pairs[i] = 0;
		--n;
	}

	test_ineq_data_clear(&data);

	free(pairs);

	if (remove < 0)
		return bmap;

	bmap = isl_basic_map_remove_dims(bmap, isl_dim_div, remove, 1);
	return isl_basic_map_drop_redundant_divs(bmap);
error:
	free(pairs);
	isl_basic_map_free(bmap);
	test_ineq_data_clear(&data);
	return NULL;
}

/* Given a pair of divs div1 and div2 such that, except for the lower bound l
 * and the upper bound u, div1 always occurs together with div2 in the form
 * (div1 + m div2), where m is the constant range on the variable div1
 * allowed by l and u, replace the pair div1 and div2 by a single
 * div that is equal to div1 + m div2.
 *
 * The new div will appear in the location that contains div2.
 * We need to modify all constraints that contain
 * div2 = (div - div1) / m
 * The coefficient of div2 is known to be equal to 1 or -1.
 * (If a constraint does not contain div2, it will also not contain div1.)
 * If the constraint also contains div1, then we know they appear
 * as f (div1 + m div2) and we can simply replace (div1 + m div2) by div,
 * i.e., the coefficient of div is f.
 *
 * Otherwise, we first need to introduce div1 into the constraint.
 * Let l be
 *
 *	div1 + f >=0
 *
 * and u
 *
 *	-div1 + f' >= 0
 *
 * A lower bound on div2
 *
 *	div2 + t >= 0
 *
 * can be replaced by
 *
 *	m div2 + div1 + m t + f >= 0
 *
 * An upper bound
 *
 *	-div2 + t >= 0
 *
 * can be replaced by
 *
 *	-(m div2 + div1) + m t + f' >= 0
 *
 * These constraint are those that we would obtain from eliminating
 * div1 using Fourier-Motzkin.
 *
 * After all constraints have been modified, we drop the lower and upper
 * bound and then drop div1.
 * Since the new div is only placed in the same location that used
 * to store div2, but otherwise has a different meaning, any possible
 * explicit representation of the original div2 is removed.
 */
static __isl_give isl_basic_map *coalesce_divs(__isl_take isl_basic_map *bmap,
	unsigned div1, unsigned div2, unsigned l, unsigned u)
{
	isl_ctx *ctx;
	isl_int m;
	unsigned dim, total;
	int i;

	ctx = isl_basic_map_get_ctx(bmap);

	dim = isl_space_dim(bmap->dim, isl_dim_all);
	total = 1 + dim + bmap->n_div;

	isl_int_init(m);
	isl_int_add(m, bmap->ineq[l][0], bmap->ineq[u][0]);
	isl_int_add_ui(m, m, 1);

	for (i = 0; i < bmap->n_ineq; ++i) {
		if (i == l || i == u)
			continue;
		if (isl_int_is_zero(bmap->ineq[i][1 + dim + div2]))
			continue;
		if (isl_int_is_zero(bmap->ineq[i][1 + dim + div1])) {
			if (isl_int_is_pos(bmap->ineq[i][1 + dim + div2]))
				isl_seq_combine(bmap->ineq[i], m, bmap->ineq[i],
						ctx->one, bmap->ineq[l], total);
			else
				isl_seq_combine(bmap->ineq[i], m, bmap->ineq[i],
						ctx->one, bmap->ineq[u], total);
		}
		isl_int_set(bmap->ineq[i][1 + dim + div2],
			    bmap->ineq[i][1 + dim + div1]);
		isl_int_set_si(bmap->ineq[i][1 + dim + div1], 0);
	}

	isl_int_clear(m);
	if (l > u) {
		isl_basic_map_drop_inequality(bmap, l);
		isl_basic_map_drop_inequality(bmap, u);
	} else {
		isl_basic_map_drop_inequality(bmap, u);
		isl_basic_map_drop_inequality(bmap, l);
	}
	bmap = isl_basic_map_mark_div_unknown(bmap, div2);
	bmap = isl_basic_map_drop_div(bmap, div1);
	return bmap;
}

/* First check if we can coalesce any pair of divs and
 * then continue with dropping more redundant divs.
 *
 * We loop over all pairs of lower and upper bounds on a div
 * with coefficient 1 and -1, respectively, check if there
 * is any other div "c" with which we can coalesce the div
 * and if so, perform the coalescing.
 */
static __isl_give isl_basic_map *coalesce_or_drop_more_redundant_divs(
	__isl_take isl_basic_map *bmap, int *pairs, int n)
{
	int i, l, u;
	unsigned dim;

	dim = isl_space_dim(bmap->dim, isl_dim_all);

	for (i = 0; i < bmap->n_div; ++i) {
		if (!pairs[i])
			continue;
		for (l = 0; l < bmap->n_ineq; ++l) {
			if (!isl_int_is_one(bmap->ineq[l][1 + dim + i]))
				continue;
			for (u = 0; u < bmap->n_ineq; ++u) {
				int c;

				if (!isl_int_is_negone(bmap->ineq[u][1+dim+i]))
					continue;
				c = div_find_coalesce(bmap, pairs, i, l, u);
				if (c < 0)
					continue;
				free(pairs);
				bmap = coalesce_divs(bmap, i, c, l, u);
				return isl_basic_map_drop_redundant_divs(bmap);
			}
		}
	}

	if (ISL_F_ISSET(bmap, ISL_BASIC_MAP_EMPTY)) {
		free(pairs);
		return bmap;
	}

	return drop_more_redundant_divs(bmap, pairs, n);
}

/* Are the "n" coefficients starting at "first" of inequality constraints
 * "i" and "j" of "bmap" equal to each other?
 */
static int is_parallel_part(__isl_keep isl_basic_map *bmap, int i, int j,
	int first, int n)
{
	return isl_seq_eq(bmap->ineq[i] + first, bmap->ineq[j] + first, n);
}

/* Are the "n" coefficients starting at "first" of inequality constraints
 * "i" and "j" of "bmap" opposite to each other?
 */
static int is_opposite_part(__isl_keep isl_basic_map *bmap, int i, int j,
	int first, int n)
{
	return isl_seq_is_neg(bmap->ineq[i] + first, bmap->ineq[j] + first, n);
}

/* Are inequality constraints "i" and "j" of "bmap" opposite to each other,
 * apart from the constant term?
 */
static isl_bool is_opposite(__isl_keep isl_basic_map *bmap, int i, int j)
{
	unsigned total;

	total = isl_basic_map_dim(bmap, isl_dim_all);
	return is_opposite_part(bmap, i, j, 1, total);
}

/* Are inequality constraints "i" and "j" of "bmap" equal to each other,
 * apart from the constant term and the coefficient at position "pos"?
 */
static int is_parallel_except(__isl_keep isl_basic_map *bmap, int i, int j,
	int pos)
{
	unsigned total;

	total = isl_basic_map_dim(bmap, isl_dim_all);
	return is_parallel_part(bmap, i, j, 1, pos - 1) &&
		is_parallel_part(bmap, i, j, pos + 1, total - pos);
}

/* Are inequality constraints "i" and "j" of "bmap" opposite to each other,
 * apart from the constant term and the coefficient at position "pos"?
 */
static int is_opposite_except(__isl_keep isl_basic_map *bmap, int i, int j,
	int pos)
{
	unsigned total;

	total = isl_basic_map_dim(bmap, isl_dim_all);
	return is_opposite_part(bmap, i, j, 1, pos - 1) &&
		is_opposite_part(bmap, i, j, pos + 1, total - pos);
}

/* Restart isl_basic_map_drop_redundant_divs after "bmap" has
 * been modified, simplying it if "simplify" is set.
 * Free the temporary data structure "pairs" that was associated
 * to the old version of "bmap".
 */
static __isl_give isl_basic_map *drop_redundant_divs_again(
	__isl_take isl_basic_map *bmap, __isl_take int *pairs, int simplify)
{
	if (simplify)
		bmap = isl_basic_map_simplify(bmap);
	free(pairs);
	return isl_basic_map_drop_redundant_divs(bmap);
}

/* Is "div" the single unknown existentially quantified variable
 * in inequality constraint "ineq" of "bmap"?
 * "div" is known to have a non-zero coefficient in "ineq".
 */
static isl_bool single_unknown(__isl_keep isl_basic_map *bmap, int ineq,
	int div)
{
	int i;
	unsigned n_div, o_div;
	isl_bool known;

	known = isl_basic_map_div_is_known(bmap, div);
	if (known < 0 || known)
		return isl_bool_not(known);
	n_div = isl_basic_map_dim(bmap, isl_dim_div);
	if (n_div == 1)
		return isl_bool_true;
	o_div = isl_basic_map_offset(bmap, isl_dim_div);
	for (i = 0; i < n_div; ++i) {
		isl_bool known;

		if (i == div)
			continue;
		if (isl_int_is_zero(bmap->ineq[ineq][o_div + i]))
			continue;
		known = isl_basic_map_div_is_known(bmap, i);
		if (known < 0 || !known)
			return known;
	}

	return isl_bool_true;
}

/* Does integer division "div" have coefficient 1 in inequality constraint
 * "ineq" of "map"?
 */
static isl_bool has_coef_one(__isl_keep isl_basic_map *bmap, int div, int ineq)
{
	unsigned o_div;

	o_div = isl_basic_map_offset(bmap, isl_dim_div);
	if (isl_int_is_one(bmap->ineq[ineq][o_div + div]))
		return isl_bool_true;

	return isl_bool_false;
}

/* Turn inequality constraint "ineq" of "bmap" into an equality and
 * then try and drop redundant divs again,
 * freeing the temporary data structure "pairs" that was associated
 * to the old version of "bmap".
 */
static __isl_give isl_basic_map *set_eq_and_try_again(
	__isl_take isl_basic_map *bmap, int ineq, __isl_take int *pairs)
{
	bmap = isl_basic_map_cow(bmap);
	isl_basic_map_inequality_to_equality(bmap, ineq);
	return drop_redundant_divs_again(bmap, pairs, 1);
}

/* Drop the integer division at position "div", along with the two
 * inequality constraints "ineq1" and "ineq2" in which it appears
 * from "bmap" and then try and drop redundant divs again,
 * freeing the temporary data structure "pairs" that was associated
 * to the old version of "bmap".
 */
static __isl_give isl_basic_map *drop_div_and_try_again(
	__isl_take isl_basic_map *bmap, int div, int ineq1, int ineq2,
	__isl_take int *pairs)
{
	if (ineq1 > ineq2) {
		isl_basic_map_drop_inequality(bmap, ineq1);
		isl_basic_map_drop_inequality(bmap, ineq2);
	} else {
		isl_basic_map_drop_inequality(bmap, ineq2);
		isl_basic_map_drop_inequality(bmap, ineq1);
	}
	bmap = isl_basic_map_drop_div(bmap, div);
	return drop_redundant_divs_again(bmap, pairs, 0);
}

/* Given two inequality constraints
 *
 *	f(x) + n d + c >= 0,		(ineq)
 *
 * with d the variable at position "pos", and
 *
 *	f(x) + c0 >= 0,			(lower)
 *
 * compute the maximal value of the lower bound ceil((-f(x) - c)/n)
 * determined by the first constraint.
 * That is, store
 *
 *	ceil((c0 - c)/n)
 *
 * in *l.
 */
static void lower_bound_from_parallel(__isl_keep isl_basic_map *bmap,
	int ineq, int lower, int pos, isl_int *l)
{
	isl_int_neg(*l, bmap->ineq[ineq][0]);
	isl_int_add(*l, *l, bmap->ineq[lower][0]);
	isl_int_cdiv_q(*l, *l, bmap->ineq[ineq][pos]);
}

/* Given two inequality constraints
 *
 *	f(x) + n d + c >= 0,		(ineq)
 *
 * with d the variable at position "pos", and
 *
 *	-f(x) - c0 >= 0,		(upper)
 *
 * compute the minimal value of the lower bound ceil((-f(x) - c)/n)
 * determined by the first constraint.
 * That is, store
 *
 *	ceil((-c1 - c)/n)
 *
 * in *u.
 */
static void lower_bound_from_opposite(__isl_keep isl_basic_map *bmap,
	int ineq, int upper, int pos, isl_int *u)
{
	isl_int_neg(*u, bmap->ineq[ineq][0]);
	isl_int_sub(*u, *u, bmap->ineq[upper][0]);
	isl_int_cdiv_q(*u, *u, bmap->ineq[ineq][pos]);
}

/* Given a lower bound constraint "ineq" on "div" in "bmap",
 * does the corresponding lower bound have a fixed value in "bmap"?
 *
 * In particular, "ineq" is of the form
 *
 *	f(x) + n d + c >= 0
 *
 * with n > 0, c the constant term and
 * d the existentially quantified variable "div".
 * That is, the lower bound is
 *
 *	ceil((-f(x) - c)/n)
 *
 * Look for a pair of constraints
 *
 *	f(x) + c0 >= 0
 *	-f(x) + c1 >= 0
 *
 * i.e., -c1 <= -f(x) <= c0, that fix ceil((-f(x) - c)/n) to a constant value.
 * That is, check that
 *
 *	ceil((-c1 - c)/n) = ceil((c0 - c)/n)
 *
 * If so, return the index of inequality f(x) + c0 >= 0.
 * Otherwise, return -1.
 */
static int lower_bound_is_cst(__isl_keep isl_basic_map *bmap, int div, int ineq)
{
	int i;
	int lower = -1, upper = -1;
	unsigned o_div;
	isl_int l, u;
	int equal;

	o_div = isl_basic_map_offset(bmap, isl_dim_div);
	for (i = 0; i < bmap->n_ineq && (lower < 0 || upper < 0); ++i) {
		if (i == ineq)
			continue;
		if (!isl_int_is_zero(bmap->ineq[i][o_div + div]))
			continue;
		if (lower < 0 &&
		    is_parallel_except(bmap, ineq, i, o_div + div)) {
			lower = i;
			continue;
		}
		if (upper < 0 &&
		    is_opposite_except(bmap, ineq, i, o_div + div)) {
			upper = i;
		}
	}

	if (lower < 0 || upper < 0)
		return -1;

	isl_int_init(l);
	isl_int_init(u);

	lower_bound_from_parallel(bmap, ineq, lower, o_div + div, &l);
	lower_bound_from_opposite(bmap, ineq, upper, o_div + div, &u);

	equal = isl_int_eq(l, u);

	isl_int_clear(l);
	isl_int_clear(u);

	return equal ? lower : -1;
}

/* Given a lower bound constraint "ineq" on the existentially quantified
 * variable "div", such that the corresponding lower bound has
 * a fixed value in "bmap", assign this fixed value to the variable and
 * then try and drop redundant divs again,
 * freeing the temporary data structure "pairs" that was associated
 * to the old version of "bmap".
 * "lower" determines the constant value for the lower bound.
 *
 * In particular, "ineq" is of the form
 *
 *	f(x) + n d + c >= 0,
 *
 * while "lower" is of the form
 *
 *	f(x) + c0 >= 0
 *
 * The lower bound is ceil((-f(x) - c)/n) and its constant value
 * is ceil((c0 - c)/n).
 */
static __isl_give isl_basic_map *fix_cst_lower(__isl_take isl_basic_map *bmap,
	int div, int ineq, int lower, int *pairs)
{
	isl_int c;
	unsigned o_div;

	isl_int_init(c);

	o_div = isl_basic_map_offset(bmap, isl_dim_div);
	lower_bound_from_parallel(bmap, ineq, lower, o_div + div, &c);
	bmap = isl_basic_map_fix(bmap, isl_dim_div, div, c);
	free(pairs);

	isl_int_clear(c);

	return isl_basic_map_drop_redundant_divs(bmap);
}

/* Remove divs that are not strictly needed based on the inequality
 * constraints.
 * In particular, if a div only occurs positively (or negatively)
 * in constraints, then it can simply be dropped.
 * Also, if a div occurs in only two constraints and if moreover
 * those two constraints are opposite to each other, except for the constant
 * term and if the sum of the constant terms is such that for any value
 * of the other values, there is always at least one integer value of the
 * div, i.e., if one plus this sum is greater than or equal to
 * the (absolute value) of the coefficient of the div in the constraints,
 * then we can also simply drop the div.
 *
 * If an existentially quantified variable does not have an explicit
 * representation, appears in only a single lower bound that does not
 * involve any other such existentially quantified variables and appears
 * in this lower bound with coefficient 1,
 * then fix the variable to the value of the lower bound.  That is,
 * turn the inequality into an equality.
 * If for any value of the other variables, there is any value
 * for the existentially quantified variable satisfying the constraints,
 * then this lower bound also satisfies the constraints.
 * It is therefore safe to pick this lower bound.
 *
 * The same reasoning holds even if the coefficient is not one.
 * However, fixing the variable to the value of the lower bound may
 * in general introduce an extra integer division, in which case
 * it may be better to pick another value.
 * If this integer division has a known constant value, then plugging
 * in this constant value removes the existentially quantified variable
 * completely.  In particular, if the lower bound is of the form
 * ceil((-f(x) - c)/n) and there are two constraints, f(x) + c0 >= 0 and
 * -f(x) + c1 >= 0 such that ceil((-c1 - c)/n) = ceil((c0 - c)/n),
 * then the existentially quantified variable can be assigned this
 * shared value.
 *
 * We skip divs that appear in equalities or in the definition of other divs.
 * Divs that appear in the definition of other divs usually occur in at least
 * 4 constraints, but the constraints may have been simplified.
 *
 * If any divs are left after these simple checks then we move on
 * to more complicated cases in drop_more_redundant_divs.
 */
static __isl_give isl_basic_map *isl_basic_map_drop_redundant_divs_ineq(
	__isl_take isl_basic_map *bmap)
{
	int i, j;
	unsigned off;
	int *pairs = NULL;
	int n = 0;

	if (!bmap)
		goto error;
	if (bmap->n_div == 0)
		return bmap;

	off = isl_space_dim(bmap->dim, isl_dim_all);
	pairs = isl_calloc_array(bmap->ctx, int, bmap->n_div);
	if (!pairs)
		goto error;

	for (i = 0; i < bmap->n_div; ++i) {
		int pos, neg;
		int last_pos, last_neg;
		int redundant;
		int defined;
		isl_bool opp, set_div;

		defined = !isl_int_is_zero(bmap->div[i][0]);
		for (j = i; j < bmap->n_div; ++j)
			if (!isl_int_is_zero(bmap->div[j][1 + 1 + off + i]))
				break;
		if (j < bmap->n_div)
			continue;
		for (j = 0; j < bmap->n_eq; ++j)
			if (!isl_int_is_zero(bmap->eq[j][1 + off + i]))
				break;
		if (j < bmap->n_eq)
			continue;
		++n;
		pos = neg = 0;
		for (j = 0; j < bmap->n_ineq; ++j) {
			if (isl_int_is_pos(bmap->ineq[j][1 + off + i])) {
				last_pos = j;
				++pos;
			}
			if (isl_int_is_neg(bmap->ineq[j][1 + off + i])) {
				last_neg = j;
				++neg;
			}
		}
		pairs[i] = pos * neg;
		if (pairs[i] == 0) {
			for (j = bmap->n_ineq - 1; j >= 0; --j)
				if (!isl_int_is_zero(bmap->ineq[j][1+off+i]))
					isl_basic_map_drop_inequality(bmap, j);
			bmap = isl_basic_map_drop_div(bmap, i);
			return drop_redundant_divs_again(bmap, pairs, 0);
		}
		if (pairs[i] != 1)
			opp = isl_bool_false;
		else
			opp = is_opposite(bmap, last_pos, last_neg);
		if (opp < 0)
			goto error;
		if (!opp) {
			int lower;
			isl_bool single, one;

			if (pos != 1)
				continue;
			single = single_unknown(bmap, last_pos, i);
			if (single < 0)
				goto error;
			if (!single)
				continue;
			one = has_coef_one(bmap, i, last_pos);
			if (one < 0)
				goto error;
			if (one)
				return set_eq_and_try_again(bmap, last_pos,
							    pairs);
			lower = lower_bound_is_cst(bmap, i, last_pos);
			if (lower >= 0)
				return fix_cst_lower(bmap, i, last_pos, lower,
						pairs);
			continue;
		}

		isl_int_add(bmap->ineq[last_pos][0],
			    bmap->ineq[last_pos][0], bmap->ineq[last_neg][0]);
		isl_int_add_ui(bmap->ineq[last_pos][0],
			       bmap->ineq[last_pos][0], 1);
		redundant = isl_int_ge(bmap->ineq[last_pos][0],
				bmap->ineq[last_pos][1+off+i]);
		isl_int_sub_ui(bmap->ineq[last_pos][0],
			       bmap->ineq[last_pos][0], 1);
		isl_int_sub(bmap->ineq[last_pos][0],
			    bmap->ineq[last_pos][0], bmap->ineq[last_neg][0]);
		if (redundant)
			return drop_div_and_try_again(bmap, i,
						    last_pos, last_neg, pairs);
		if (defined)
			set_div = isl_bool_false;
		else
			set_div = ok_to_set_div_from_bound(bmap, i, last_pos);
		if (set_div < 0)
			return isl_basic_map_free(bmap);
		if (set_div) {
			bmap = set_div_from_lower_bound(bmap, i, last_pos);
			return drop_redundant_divs_again(bmap, pairs, 1);
		}
		pairs[i] = 0;
		--n;
	}

	if (n > 0)
		return coalesce_or_drop_more_redundant_divs(bmap, pairs, n);

	free(pairs);
	return bmap;
error:
	free(pairs);
	isl_basic_map_free(bmap);
	return NULL;
}

/* Consider the coefficients at "c" as a row vector and replace
 * them with their product with "T".  "T" is assumed to be a square matrix.
 */
static isl_stat preimage(isl_int *c, __isl_keep isl_mat *T)
{
	int n;
	isl_ctx *ctx;
	isl_vec *v;

	if (!T)
		return isl_stat_error;
	n = isl_mat_rows(T);
	if (isl_seq_first_non_zero(c, n) == -1)
		return isl_stat_ok;
	ctx = isl_mat_get_ctx(T);
	v = isl_vec_alloc(ctx, n);
	if (!v)
		return isl_stat_error;
	isl_seq_swp_or_cpy(v->el, c, n);
	v = isl_vec_mat_product(v, isl_mat_copy(T));
	if (!v)
		return isl_stat_error;
	isl_seq_swp_or_cpy(c, v->el, n);
	isl_vec_free(v);

	return isl_stat_ok;
}

/* Plug in T for the variables in "bmap" starting at "pos".
 * T is a linear unimodular matrix, i.e., without constant term.
 */
static __isl_give isl_basic_map *isl_basic_map_preimage_vars(
	__isl_take isl_basic_map *bmap, unsigned pos, __isl_take isl_mat *T)
{
	int i;
	unsigned n, total;

	bmap = isl_basic_map_cow(bmap);
	if (!bmap || !T)
		goto error;

	n = isl_mat_cols(T);
	if (n != isl_mat_rows(T))
		isl_die(isl_mat_get_ctx(T), isl_error_invalid,
			"expecting square matrix", goto error);

	total = isl_basic_map_dim(bmap, isl_dim_all);
	if (pos + n > total || pos + n < pos)
		isl_die(isl_mat_get_ctx(T), isl_error_invalid,
			"invalid range", goto error);

	for (i = 0; i < bmap->n_eq; ++i)
		if (preimage(bmap->eq[i] + 1 + pos, T) < 0)
			goto error;
	for (i = 0; i < bmap->n_ineq; ++i)
		if (preimage(bmap->ineq[i] + 1 + pos, T) < 0)
			goto error;
	for (i = 0; i < bmap->n_div; ++i) {
		if (isl_basic_map_div_is_marked_unknown(bmap, i))
			continue;
		if (preimage(bmap->div[i] + 1 + 1 + pos, T) < 0)
			goto error;
	}

	isl_mat_free(T);
	return bmap;
error:
	isl_basic_map_free(bmap);
	isl_mat_free(T);
	return NULL;
}

/* Remove divs that are not strictly needed.
 *
 * First look for an equality constraint involving two or more
 * existentially quantified variables without an explicit
 * representation.  Replace the combination that appears
 * in the equality constraint by a single existentially quantified
 * variable such that the equality can be used to derive
 * an explicit representation for the variable.
 * If there are no more such equality constraints, then continue
 * with isl_basic_map_drop_redundant_divs_ineq.
 *
 * In particular, if the equality constraint is of the form
 *
 *	f(x) + \sum_i c_i a_i = 0
 *
 * with a_i existentially quantified variable without explicit
 * representation, then apply a transformation on the existentially
 * quantified variables to turn the constraint into
 *
 *	f(x) + g a_1' = 0
 *
 * with g the gcd of the c_i.
 * In order to easily identify which existentially quantified variables
 * have a complete explicit representation, i.e., without being defined
 * in terms of other existentially quantified variables without
 * an explicit representation, the existentially quantified variables
 * are first sorted.
 *
 * The variable transformation is computed by extending the row
 * [c_1/g ... c_n/g] to a unimodular matrix, obtaining the transformation
 *
 *	[a_1']   [c_1/g ... c_n/g]   [ a_1 ]
 *	[a_2']                       [ a_2 ]
 *	 ...   =         U             ....
 *	[a_n']            	     [ a_n ]
 *
 * with [c_1/g ... c_n/g] representing the first row of U.
 * The inverse of U is then plugged into the original constraints.
 * The call to isl_basic_map_simplify makes sure the explicit
 * representation for a_1' is extracted from the equality constraint.
 */
__isl_give isl_basic_map *isl_basic_map_drop_redundant_divs(
	__isl_take isl_basic_map *bmap)
{
	int first;
	int i;
	unsigned o_div, n_div;
	int l;
	isl_ctx *ctx;
	isl_mat *T;

	if (!bmap)
		return NULL;
	if (isl_basic_map_divs_known(bmap))
		return isl_basic_map_drop_redundant_divs_ineq(bmap);
	if (bmap->n_eq == 0)
		return isl_basic_map_drop_redundant_divs_ineq(bmap);
	bmap = isl_basic_map_sort_divs(bmap);
	if (!bmap)
		return NULL;

	first = isl_basic_map_first_unknown_div(bmap);
	if (first < 0)
		return isl_basic_map_free(bmap);

	o_div = isl_basic_map_offset(bmap, isl_dim_div);
	n_div = isl_basic_map_dim(bmap, isl_dim_div);

	for (i = 0; i < bmap->n_eq; ++i) {
		l = isl_seq_first_non_zero(bmap->eq[i] + o_div + first,
					    n_div - (first));
		if (l < 0)
			continue;
		l += first;
		if (isl_seq_first_non_zero(bmap->eq[i] + o_div + l + 1,
					    n_div - (l + 1)) == -1)
			continue;
		break;
	}
	if (i >= bmap->n_eq)
		return isl_basic_map_drop_redundant_divs_ineq(bmap);

	ctx = isl_basic_map_get_ctx(bmap);
	T = isl_mat_alloc(ctx, n_div - l, n_div - l);
	if (!T)
		return isl_basic_map_free(bmap);
	isl_seq_cpy(T->row[0], bmap->eq[i] + o_div + l, n_div - l);
	T = isl_mat_normalize_row(T, 0);
	T = isl_mat_unimodular_complete(T, 1);
	T = isl_mat_right_inverse(T);

	for (i = l; i < n_div; ++i)
		bmap = isl_basic_map_mark_div_unknown(bmap, i);
	bmap = isl_basic_map_preimage_vars(bmap, o_div - 1 + l, T);
	bmap = isl_basic_map_simplify(bmap);

	return isl_basic_map_drop_redundant_divs(bmap);
}

/* Does "bmap" satisfy any equality that involves more than 2 variables
 * and/or has coefficients different from -1 and 1?
 */
static int has_multiple_var_equality(__isl_keep isl_basic_map *bmap)
{
	int i;
	unsigned total;

	total = isl_basic_map_dim(bmap, isl_dim_all);

	for (i = 0; i < bmap->n_eq; ++i) {
		int j, k;

		j = isl_seq_first_non_zero(bmap->eq[i] + 1, total);
		if (j < 0)
			continue;
		if (!isl_int_is_one(bmap->eq[i][1 + j]) &&
		    !isl_int_is_negone(bmap->eq[i][1 + j]))
			return 1;

		j += 1;
		k = isl_seq_first_non_zero(bmap->eq[i] + 1 + j, total - j);
		if (k < 0)
			continue;
		j += k;
		if (!isl_int_is_one(bmap->eq[i][1 + j]) &&
		    !isl_int_is_negone(bmap->eq[i][1 + j]))
			return 1;

		j += 1;
		k = isl_seq_first_non_zero(bmap->eq[i] + 1 + j, total - j);
		if (k >= 0)
			return 1;
	}

	return 0;
}

/* Remove any common factor g from the constraint coefficients in "v".
 * The constant term is stored in the first position and is replaced
 * by floor(c/g).  If any common factor is removed and if this results
 * in a tightening of the constraint, then set *tightened.
 */
static __isl_give isl_vec *normalize_constraint(__isl_take isl_vec *v,
	int *tightened)
{
	isl_ctx *ctx;

	if (!v)
		return NULL;
	ctx = isl_vec_get_ctx(v);
	isl_seq_gcd(v->el + 1, v->size - 1, &ctx->normalize_gcd);
	if (isl_int_is_zero(ctx->normalize_gcd))
		return v;
	if (isl_int_is_one(ctx->normalize_gcd))
		return v;
	v = isl_vec_cow(v);
	if (!v)
		return NULL;
	if (tightened && !isl_int_is_divisible_by(v->el[0], ctx->normalize_gcd))
		*tightened = 1;
	isl_int_fdiv_q(v->el[0], v->el[0], ctx->normalize_gcd);
	isl_seq_scale_down(v->el + 1, v->el + 1, ctx->normalize_gcd,
				v->size - 1);
	return v;
}

/* If "bmap" is an integer set that satisfies any equality involving
 * more than 2 variables and/or has coefficients different from -1 and 1,
 * then use variable compression to reduce the coefficients by removing
 * any (hidden) common factor.
 * In particular, apply the variable compression to each constraint,
 * factor out any common factor in the non-constant coefficients and
 * then apply the inverse of the compression.
 * At the end, we mark the basic map as having reduced constants.
 * If this flag is still set on the next invocation of this function,
 * then we skip the computation.
 *
 * Removing a common factor may result in a tightening of some of
 * the constraints.  If this happens, then we may end up with two
 * opposite inequalities that can be replaced by an equality.
 * We therefore call isl_basic_map_detect_inequality_pairs,
 * which checks for such pairs of inequalities as well as eliminate_divs_eq
 * and isl_basic_map_gauss if such a pair was found.
 *
 * Note that this function may leave the result in an inconsistent state.
 * In particular, the constraints may not be gaussed.
 * Unfortunately, isl_map_coalesce actually depends on this inconsistent state
 * for some of the test cases to pass successfully.
 * Any potential modification of the representation is therefore only
 * performed on a single copy of the basic map.
 */
__isl_give isl_basic_map *isl_basic_map_reduce_coefficients(
	__isl_take isl_basic_map *bmap)
{
	unsigned total;
	isl_ctx *ctx;
	isl_vec *v;
	isl_mat *eq, *T, *T2;
	int i;
	int tightened;

	if (!bmap)
		return NULL;
	if (ISL_F_ISSET(bmap, ISL_BASIC_MAP_REDUCED_COEFFICIENTS))
		return bmap;
	if (isl_basic_map_is_rational(bmap))
		return bmap;
	if (bmap->n_eq == 0)
		return bmap;
	if (!has_multiple_var_equality(bmap))
		return bmap;

	total = isl_basic_map_dim(bmap, isl_dim_all);
	ctx = isl_basic_map_get_ctx(bmap);
	v = isl_vec_alloc(ctx, 1 + total);
	if (!v)
		return isl_basic_map_free(bmap);

	eq = isl_mat_sub_alloc6(ctx, bmap->eq, 0, bmap->n_eq, 0, 1 + total);
	T = isl_mat_variable_compression(eq, &T2);
	if (!T || !T2)
		goto error;
	if (T->n_col == 0) {
		isl_mat_free(T);
		isl_mat_free(T2);
		isl_vec_free(v);
		return isl_basic_map_set_to_empty(bmap);
	}

	bmap = isl_basic_map_cow(bmap);
	if (!bmap)
		goto error;

	tightened = 0;
	for (i = 0; i < bmap->n_ineq; ++i) {
		isl_seq_cpy(v->el, bmap->ineq[i], 1 + total);
		v = isl_vec_mat_product(v, isl_mat_copy(T));
		v = normalize_constraint(v, &tightened);
		v = isl_vec_mat_product(v, isl_mat_copy(T2));
		if (!v)
			goto error;
		isl_seq_cpy(bmap->ineq[i], v->el, 1 + total);
	}

	isl_mat_free(T);
	isl_mat_free(T2);
	isl_vec_free(v);

	ISL_F_SET(bmap, ISL_BASIC_MAP_REDUCED_COEFFICIENTS);

	if (tightened) {
		int progress = 0;

		bmap = isl_basic_map_detect_inequality_pairs(bmap, &progress);
		if (progress) {
			bmap = eliminate_divs_eq(bmap, &progress);
			bmap = isl_basic_map_gauss(bmap, NULL);
		}
	}

	return bmap;
error:
	isl_mat_free(T);
	isl_mat_free(T2);
	isl_vec_free(v);
	return isl_basic_map_free(bmap);
}

/* Shift the integer division at position "div" of "bmap"
 * by "shift" times the variable at position "pos".
 * "pos" is as determined by isl_basic_map_offset, i.e., pos == 0
 * corresponds to the constant term.
 *
 * That is, if the integer division has the form
 *
 *	floor(f(x)/d)
 *
 * then replace it by
 *
 *	floor((f(x) + shift * d * x_pos)/d) - shift * x_pos
 */
__isl_give isl_basic_map *isl_basic_map_shift_div(
	__isl_take isl_basic_map *bmap, int div, int pos, isl_int shift)
{
	int i;
	unsigned total;

	if (isl_int_is_zero(shift))
		return bmap;
	if (!bmap)
		return NULL;

	total = isl_basic_map_dim(bmap, isl_dim_all);
	total -= isl_basic_map_dim(bmap, isl_dim_div);

	isl_int_addmul(bmap->div[div][1 + pos], shift, bmap->div[div][0]);

	for (i = 0; i < bmap->n_eq; ++i) {
		if (isl_int_is_zero(bmap->eq[i][1 + total + div]))
			continue;
		isl_int_submul(bmap->eq[i][pos],
				shift, bmap->eq[i][1 + total + div]);
	}
	for (i = 0; i < bmap->n_ineq; ++i) {
		if (isl_int_is_zero(bmap->ineq[i][1 + total + div]))
			continue;
		isl_int_submul(bmap->ineq[i][pos],
				shift, bmap->ineq[i][1 + total + div]);
	}
	for (i = 0; i < bmap->n_div; ++i) {
		if (isl_int_is_zero(bmap->div[i][0]))
			continue;
		if (isl_int_is_zero(bmap->div[i][1 + 1 + total + div]))
			continue;
		isl_int_submul(bmap->div[i][1 + pos],
				shift, bmap->div[i][1 + 1 + total + div]);
	}

	return bmap;
}