aboutsummaryrefslogtreecommitdiffstats
path: root/src/gallium/drivers/nouveau/codegen/nv50_ir_from_tgsi.cpp
blob: 9d0ab336c751bbdb3dba76e27c8baca36e46b9ca (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
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
/*
 * Copyright 2011 Christoph Bumiller
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

#include "tgsi/tgsi_build.h"
#include "tgsi/tgsi_dump.h"
#include "tgsi/tgsi_scan.h"
#include "tgsi/tgsi_util.h"

#include <set>

#include "codegen/nv50_ir.h"
#include "codegen/nv50_ir_from_common.h"
#include "codegen/nv50_ir_util.h"

namespace tgsi {

class Source;

static nv50_ir::operation translateOpcode(uint opcode);
static nv50_ir::DataFile translateFile(uint file);
static nv50_ir::TexTarget translateTexture(uint texTarg);
static nv50_ir::SVSemantic translateSysVal(uint sysval);
static nv50_ir::CacheMode translateCacheMode(uint qualifier);
static nv50_ir::ImgFormat translateImgFormat(uint format);

class Instruction
{
public:
   Instruction(const struct tgsi_full_instruction *inst) : insn(inst) { }

   class SrcRegister
   {
   public:
      SrcRegister(const struct tgsi_full_src_register *src)
         : reg(src->Register),
           fsr(src)
      { }

      SrcRegister(const struct tgsi_src_register& src) : reg(src), fsr(NULL) { }

      SrcRegister(const struct tgsi_ind_register& ind)
         : reg(tgsi_util_get_src_from_ind(&ind)),
           fsr(NULL)
      { }

      struct tgsi_src_register offsetToSrc(struct tgsi_texture_offset off)
      {
         struct tgsi_src_register reg;
         memset(&reg, 0, sizeof(reg));
         reg.Index = off.Index;
         reg.File = off.File;
         reg.SwizzleX = off.SwizzleX;
         reg.SwizzleY = off.SwizzleY;
         reg.SwizzleZ = off.SwizzleZ;
         return reg;
      }

      SrcRegister(const struct tgsi_texture_offset& off) :
         reg(offsetToSrc(off)),
         fsr(NULL)
      { }

      uint getFile() const { return reg.File; }

      bool is2D() const { return reg.Dimension; }

      bool isIndirect(int dim) const
      {
         return (dim && fsr) ? fsr->Dimension.Indirect : reg.Indirect;
      }

      int getIndex(int dim) const
      {
         return (dim && fsr) ? fsr->Dimension.Index : reg.Index;
      }

      int getSwizzle(int chan) const
      {
         return tgsi_util_get_src_register_swizzle(&reg, chan);
      }

      int getArrayId() const
      {
         if (isIndirect(0))
            return fsr->Indirect.ArrayID;
         return 0;
      }

      nv50_ir::Modifier getMod(int chan) const;

      SrcRegister getIndirect(int dim) const
      {
         assert(fsr && isIndirect(dim));
         if (dim)
            return SrcRegister(fsr->DimIndirect);
         return SrcRegister(fsr->Indirect);
      }

      uint32_t getValueU32(int c, const struct nv50_ir_prog_info *info) const
      {
         assert(reg.File == TGSI_FILE_IMMEDIATE);
         assert(!reg.Absolute);
         assert(!reg.Negate);
         return info->immd.data[reg.Index * 4 + getSwizzle(c)];
      }

   private:
      const struct tgsi_src_register reg;
      const struct tgsi_full_src_register *fsr;
   };

   class DstRegister
   {
   public:
      DstRegister(const struct tgsi_full_dst_register *dst)
         : reg(dst->Register),
           fdr(dst)
      { }

      DstRegister(const struct tgsi_dst_register& dst) : reg(dst), fdr(NULL) { }

      uint getFile() const { return reg.File; }

      bool is2D() const { return reg.Dimension; }

      bool isIndirect(int dim) const
      {
         return (dim && fdr) ? fdr->Dimension.Indirect : reg.Indirect;
      }

      int getIndex(int dim) const
      {
         return (dim && fdr) ? fdr->Dimension.Dimension : reg.Index;
      }

      unsigned int getMask() const { return reg.WriteMask; }

      bool isMasked(int chan) const { return !(getMask() & (1 << chan)); }

      SrcRegister getIndirect(int dim) const
      {
         assert(fdr && isIndirect(dim));
         if (dim)
            return SrcRegister(fdr->DimIndirect);
         return SrcRegister(fdr->Indirect);
      }

      struct tgsi_full_src_register asSrc()
      {
         assert(fdr);
         return tgsi_full_src_register_from_dst(fdr);
      }

      int getArrayId() const
      {
         if (isIndirect(0))
            return fdr->Indirect.ArrayID;
         return 0;
      }

   private:
      const struct tgsi_dst_register reg;
      const struct tgsi_full_dst_register *fdr;
   };

   inline uint getOpcode() const { return insn->Instruction.Opcode; }

   unsigned int srcCount() const { return insn->Instruction.NumSrcRegs; }
   unsigned int dstCount() const { return insn->Instruction.NumDstRegs; }

   // mask of used components of source s
   unsigned int srcMask(unsigned int s) const;
   unsigned int texOffsetMask() const;

   SrcRegister getSrc(unsigned int s) const
   {
      assert(s < srcCount());
      return SrcRegister(&insn->Src[s]);
   }

   DstRegister getDst(unsigned int d) const
   {
      assert(d < dstCount());
      return DstRegister(&insn->Dst[d]);
   }

   SrcRegister getTexOffset(unsigned int i) const
   {
      assert(i < TGSI_FULL_MAX_TEX_OFFSETS);
      return SrcRegister(insn->TexOffsets[i]);
   }

   unsigned int getNumTexOffsets() const { return insn->Texture.NumOffsets; }

   bool checkDstSrcAliasing() const;

   inline nv50_ir::operation getOP() const {
      return translateOpcode(getOpcode()); }

   nv50_ir::DataType inferSrcType() const;
   nv50_ir::DataType inferDstType() const;

   nv50_ir::CondCode getSetCond() const;

   nv50_ir::TexInstruction::Target getTexture(const Source *, int s) const;

   const nv50_ir::TexInstruction::ImgFormatDesc *getImageFormat() const {
      return &nv50_ir::TexInstruction::formatTable[
            translateImgFormat(insn->Memory.Format)];
   }

   nv50_ir::TexTarget getImageTarget() const {
      return translateTexture(insn->Memory.Texture);
   }

   nv50_ir::CacheMode getCacheMode() const {
      if (!insn->Instruction.Memory)
         return nv50_ir::CACHE_CA;
      return translateCacheMode(insn->Memory.Qualifier);
   }

   inline uint getLabel() { return insn->Label.Label; }

   unsigned getSaturate() const { return insn->Instruction.Saturate; }

   void print() const
   {
      tgsi_dump_instruction(insn, 1);
   }

private:
   const struct tgsi_full_instruction *insn;
};

unsigned int Instruction::texOffsetMask() const
{
   const struct tgsi_instruction_texture *tex = &insn->Texture;
   assert(insn->Instruction.Texture);

   switch (tex->Texture) {
   case TGSI_TEXTURE_BUFFER:
   case TGSI_TEXTURE_1D:
   case TGSI_TEXTURE_SHADOW1D:
   case TGSI_TEXTURE_1D_ARRAY:
   case TGSI_TEXTURE_SHADOW1D_ARRAY:
      return 0x1;
   case TGSI_TEXTURE_2D:
   case TGSI_TEXTURE_SHADOW2D:
   case TGSI_TEXTURE_2D_ARRAY:
   case TGSI_TEXTURE_SHADOW2D_ARRAY:
   case TGSI_TEXTURE_RECT:
   case TGSI_TEXTURE_SHADOWRECT:
   case TGSI_TEXTURE_2D_MSAA:
   case TGSI_TEXTURE_2D_ARRAY_MSAA:
      return 0x3;
   case TGSI_TEXTURE_3D:
      return 0x7;
   default:
      assert(!"Unexpected texture target");
      return 0xf;
   }
}

unsigned int Instruction::srcMask(unsigned int s) const
{
   unsigned int mask = insn->Dst[0].Register.WriteMask;

   switch (insn->Instruction.Opcode) {
   case TGSI_OPCODE_COS:
   case TGSI_OPCODE_SIN:
      return (mask & 0x8) | ((mask & 0x7) ? 0x1 : 0x0);
   case TGSI_OPCODE_DP2:
      return 0x3;
   case TGSI_OPCODE_DP3:
      return 0x7;
   case TGSI_OPCODE_DP4:
   case TGSI_OPCODE_KILL_IF: /* WriteMask ignored */
      return 0xf;
   case TGSI_OPCODE_DST:
      return mask & (s ? 0xa : 0x6);
   case TGSI_OPCODE_EX2:
   case TGSI_OPCODE_EXP:
   case TGSI_OPCODE_LG2:
   case TGSI_OPCODE_LOG:
   case TGSI_OPCODE_POW:
   case TGSI_OPCODE_RCP:
   case TGSI_OPCODE_RSQ:
      return 0x1;
   case TGSI_OPCODE_IF:
   case TGSI_OPCODE_UIF:
      return 0x1;
   case TGSI_OPCODE_LIT:
      return 0xb;
   case TGSI_OPCODE_TEX2:
   case TGSI_OPCODE_TXB2:
   case TGSI_OPCODE_TXL2:
      return (s == 0) ? 0xf : 0x3;
   case TGSI_OPCODE_TEX:
   case TGSI_OPCODE_TXB:
   case TGSI_OPCODE_TXD:
   case TGSI_OPCODE_TXL:
   case TGSI_OPCODE_TXP:
   case TGSI_OPCODE_TXF:
   case TGSI_OPCODE_TG4:
   case TGSI_OPCODE_TEX_LZ:
   case TGSI_OPCODE_TXF_LZ:
   case TGSI_OPCODE_LODQ:
   {
      const struct tgsi_instruction_texture *tex = &insn->Texture;

      assert(insn->Instruction.Texture);

      mask = 0x7;
      if (insn->Instruction.Opcode != TGSI_OPCODE_TEX &&
          insn->Instruction.Opcode != TGSI_OPCODE_TEX_LZ &&
          insn->Instruction.Opcode != TGSI_OPCODE_TXF_LZ &&
          insn->Instruction.Opcode != TGSI_OPCODE_TXD)
         mask |= 0x8; /* bias, lod or proj */

      switch (tex->Texture) {
      case TGSI_TEXTURE_1D:
         mask &= 0x9;
         break;
      case TGSI_TEXTURE_SHADOW1D:
         mask &= 0xd;
         break;
      case TGSI_TEXTURE_1D_ARRAY:
      case TGSI_TEXTURE_2D:
      case TGSI_TEXTURE_RECT:
         mask &= 0xb;
         break;
      case TGSI_TEXTURE_CUBE_ARRAY:
      case TGSI_TEXTURE_SHADOW2D_ARRAY:
      case TGSI_TEXTURE_SHADOWCUBE:
      case TGSI_TEXTURE_SHADOWCUBE_ARRAY:
         mask |= 0x8;
         break;
      default:
         break;
      }
   }
      return mask;
   case TGSI_OPCODE_TXQ:
      return 1;
   case TGSI_OPCODE_D2I:
   case TGSI_OPCODE_D2U:
   case TGSI_OPCODE_D2F:
   case TGSI_OPCODE_DSLT:
   case TGSI_OPCODE_DSGE:
   case TGSI_OPCODE_DSEQ:
   case TGSI_OPCODE_DSNE:
   case TGSI_OPCODE_U64SEQ:
   case TGSI_OPCODE_U64SNE:
   case TGSI_OPCODE_I64SLT:
   case TGSI_OPCODE_U64SLT:
   case TGSI_OPCODE_I64SGE:
   case TGSI_OPCODE_U64SGE:
   case TGSI_OPCODE_I642F:
   case TGSI_OPCODE_U642F:
      switch (util_bitcount(mask)) {
      case 1: return 0x3;
      case 2: return 0xf;
      default:
         assert(!"unexpected mask");
         return 0xf;
      }
   case TGSI_OPCODE_I2D:
   case TGSI_OPCODE_U2D:
   case TGSI_OPCODE_F2D: {
      unsigned int x = 0;
      if ((mask & 0x3) == 0x3)
         x |= 1;
      if ((mask & 0xc) == 0xc)
         x |= 2;
      return x;
   }
   case TGSI_OPCODE_PK2H:
      return 0x3;
   case TGSI_OPCODE_UP2H:
      return 0x1;
   default:
      break;
   }

   return mask;
}

nv50_ir::Modifier Instruction::SrcRegister::getMod(int chan) const
{
   nv50_ir::Modifier m(0);

   if (reg.Absolute)
      m = m | nv50_ir::Modifier(NV50_IR_MOD_ABS);
   if (reg.Negate)
      m = m | nv50_ir::Modifier(NV50_IR_MOD_NEG);
   return m;
}

static nv50_ir::DataFile translateFile(uint file)
{
   switch (file) {
   case TGSI_FILE_CONSTANT:        return nv50_ir::FILE_MEMORY_CONST;
   case TGSI_FILE_INPUT:           return nv50_ir::FILE_SHADER_INPUT;
   case TGSI_FILE_OUTPUT:          return nv50_ir::FILE_SHADER_OUTPUT;
   case TGSI_FILE_TEMPORARY:       return nv50_ir::FILE_GPR;
   case TGSI_FILE_ADDRESS:         return nv50_ir::FILE_ADDRESS;
   case TGSI_FILE_IMMEDIATE:       return nv50_ir::FILE_IMMEDIATE;
   case TGSI_FILE_SYSTEM_VALUE:    return nv50_ir::FILE_SYSTEM_VALUE;
   case TGSI_FILE_BUFFER:          return nv50_ir::FILE_MEMORY_BUFFER;
   case TGSI_FILE_IMAGE:           return nv50_ir::FILE_MEMORY_GLOBAL;
   case TGSI_FILE_MEMORY:          return nv50_ir::FILE_MEMORY_GLOBAL;
   case TGSI_FILE_SAMPLER:
   case TGSI_FILE_NULL:
   default:
      return nv50_ir::FILE_NULL;
   }
}

static nv50_ir::SVSemantic translateSysVal(uint sysval)
{
   switch (sysval) {
   case TGSI_SEMANTIC_FACE:       return nv50_ir::SV_FACE;
   case TGSI_SEMANTIC_PSIZE:      return nv50_ir::SV_POINT_SIZE;
   case TGSI_SEMANTIC_PRIMID:     return nv50_ir::SV_PRIMITIVE_ID;
   case TGSI_SEMANTIC_INSTANCEID: return nv50_ir::SV_INSTANCE_ID;
   case TGSI_SEMANTIC_VERTEXID:   return nv50_ir::SV_VERTEX_ID;
   case TGSI_SEMANTIC_GRID_SIZE:  return nv50_ir::SV_NCTAID;
   case TGSI_SEMANTIC_BLOCK_ID:   return nv50_ir::SV_CTAID;
   case TGSI_SEMANTIC_BLOCK_SIZE: return nv50_ir::SV_NTID;
   case TGSI_SEMANTIC_THREAD_ID:  return nv50_ir::SV_TID;
   case TGSI_SEMANTIC_SAMPLEID:   return nv50_ir::SV_SAMPLE_INDEX;
   case TGSI_SEMANTIC_SAMPLEPOS:  return nv50_ir::SV_SAMPLE_POS;
   case TGSI_SEMANTIC_SAMPLEMASK: return nv50_ir::SV_SAMPLE_MASK;
   case TGSI_SEMANTIC_INVOCATIONID: return nv50_ir::SV_INVOCATION_ID;
   case TGSI_SEMANTIC_TESSCOORD:  return nv50_ir::SV_TESS_COORD;
   case TGSI_SEMANTIC_TESSOUTER:  return nv50_ir::SV_TESS_OUTER;
   case TGSI_SEMANTIC_TESSINNER:  return nv50_ir::SV_TESS_INNER;
   case TGSI_SEMANTIC_VERTICESIN: return nv50_ir::SV_VERTEX_COUNT;
   case TGSI_SEMANTIC_HELPER_INVOCATION: return nv50_ir::SV_THREAD_KILL;
   case TGSI_SEMANTIC_BASEVERTEX: return nv50_ir::SV_BASEVERTEX;
   case TGSI_SEMANTIC_BASEINSTANCE: return nv50_ir::SV_BASEINSTANCE;
   case TGSI_SEMANTIC_DRAWID:     return nv50_ir::SV_DRAWID;
   case TGSI_SEMANTIC_WORK_DIM:   return nv50_ir::SV_WORK_DIM;
   case TGSI_SEMANTIC_SUBGROUP_INVOCATION: return nv50_ir::SV_LANEID;
   case TGSI_SEMANTIC_SUBGROUP_EQ_MASK: return nv50_ir::SV_LANEMASK_EQ;
   case TGSI_SEMANTIC_SUBGROUP_LT_MASK: return nv50_ir::SV_LANEMASK_LT;
   case TGSI_SEMANTIC_SUBGROUP_LE_MASK: return nv50_ir::SV_LANEMASK_LE;
   case TGSI_SEMANTIC_SUBGROUP_GT_MASK: return nv50_ir::SV_LANEMASK_GT;
   case TGSI_SEMANTIC_SUBGROUP_GE_MASK: return nv50_ir::SV_LANEMASK_GE;
   default:
      assert(0);
      return nv50_ir::SV_CLOCK;
   }
}

#define NV50_IR_TEX_TARG_CASE(a, b) \
   case TGSI_TEXTURE_##a: return nv50_ir::TEX_TARGET_##b;

static nv50_ir::TexTarget translateTexture(uint tex)
{
   switch (tex) {
   NV50_IR_TEX_TARG_CASE(1D, 1D);
   NV50_IR_TEX_TARG_CASE(2D, 2D);
   NV50_IR_TEX_TARG_CASE(2D_MSAA, 2D_MS);
   NV50_IR_TEX_TARG_CASE(3D, 3D);
   NV50_IR_TEX_TARG_CASE(CUBE, CUBE);
   NV50_IR_TEX_TARG_CASE(RECT, RECT);
   NV50_IR_TEX_TARG_CASE(1D_ARRAY, 1D_ARRAY);
   NV50_IR_TEX_TARG_CASE(2D_ARRAY, 2D_ARRAY);
   NV50_IR_TEX_TARG_CASE(2D_ARRAY_MSAA, 2D_MS_ARRAY);
   NV50_IR_TEX_TARG_CASE(CUBE_ARRAY, CUBE_ARRAY);
   NV50_IR_TEX_TARG_CASE(SHADOW1D, 1D_SHADOW);
   NV50_IR_TEX_TARG_CASE(SHADOW2D, 2D_SHADOW);
   NV50_IR_TEX_TARG_CASE(SHADOWCUBE, CUBE_SHADOW);
   NV50_IR_TEX_TARG_CASE(SHADOWRECT, RECT_SHADOW);
   NV50_IR_TEX_TARG_CASE(SHADOW1D_ARRAY, 1D_ARRAY_SHADOW);
   NV50_IR_TEX_TARG_CASE(SHADOW2D_ARRAY, 2D_ARRAY_SHADOW);
   NV50_IR_TEX_TARG_CASE(SHADOWCUBE_ARRAY, CUBE_ARRAY_SHADOW);
   NV50_IR_TEX_TARG_CASE(BUFFER, BUFFER);

   case TGSI_TEXTURE_UNKNOWN:
   default:
      assert(!"invalid texture target");
      return nv50_ir::TEX_TARGET_2D;
   }
}

static nv50_ir::CacheMode translateCacheMode(uint qualifier)
{
   if (qualifier & TGSI_MEMORY_VOLATILE)
      return nv50_ir::CACHE_CV;
   if (qualifier & TGSI_MEMORY_COHERENT)
      return nv50_ir::CACHE_CG;
   return nv50_ir::CACHE_CA;
}

static nv50_ir::ImgFormat translateImgFormat(uint format)
{

#define FMT_CASE(a, b) \
  case PIPE_FORMAT_ ## a: return nv50_ir::FMT_ ## b

   switch (format) {
   FMT_CASE(NONE, NONE);

   FMT_CASE(R32G32B32A32_FLOAT, RGBA32F);
   FMT_CASE(R16G16B16A16_FLOAT, RGBA16F);
   FMT_CASE(R32G32_FLOAT, RG32F);
   FMT_CASE(R16G16_FLOAT, RG16F);
   FMT_CASE(R11G11B10_FLOAT, R11G11B10F);
   FMT_CASE(R32_FLOAT, R32F);
   FMT_CASE(R16_FLOAT, R16F);

   FMT_CASE(R32G32B32A32_UINT, RGBA32UI);
   FMT_CASE(R16G16B16A16_UINT, RGBA16UI);
   FMT_CASE(R10G10B10A2_UINT, RGB10A2UI);
   FMT_CASE(R8G8B8A8_UINT, RGBA8UI);
   FMT_CASE(R32G32_UINT, RG32UI);
   FMT_CASE(R16G16_UINT, RG16UI);
   FMT_CASE(R8G8_UINT, RG8UI);
   FMT_CASE(R32_UINT, R32UI);
   FMT_CASE(R16_UINT, R16UI);
   FMT_CASE(R8_UINT, R8UI);

   FMT_CASE(R32G32B32A32_SINT, RGBA32I);
   FMT_CASE(R16G16B16A16_SINT, RGBA16I);
   FMT_CASE(R8G8B8A8_SINT, RGBA8I);
   FMT_CASE(R32G32_SINT, RG32I);
   FMT_CASE(R16G16_SINT, RG16I);
   FMT_CASE(R8G8_SINT, RG8I);
   FMT_CASE(R32_SINT, R32I);
   FMT_CASE(R16_SINT, R16I);
   FMT_CASE(R8_SINT, R8I);

   FMT_CASE(R16G16B16A16_UNORM, RGBA16);
   FMT_CASE(R10G10B10A2_UNORM, RGB10A2);
   FMT_CASE(R8G8B8A8_UNORM, RGBA8);
   FMT_CASE(R16G16_UNORM, RG16);
   FMT_CASE(R8G8_UNORM, RG8);
   FMT_CASE(R16_UNORM, R16);
   FMT_CASE(R8_UNORM, R8);

   FMT_CASE(R16G16B16A16_SNORM, RGBA16_SNORM);
   FMT_CASE(R8G8B8A8_SNORM, RGBA8_SNORM);
   FMT_CASE(R16G16_SNORM, RG16_SNORM);
   FMT_CASE(R8G8_SNORM, RG8_SNORM);
   FMT_CASE(R16_SNORM, R16_SNORM);
   FMT_CASE(R8_SNORM, R8_SNORM);

   FMT_CASE(B8G8R8A8_UNORM, BGRA8);
   }

   assert(!"Unexpected format");
   return nv50_ir::FMT_NONE;
}

nv50_ir::DataType Instruction::inferSrcType() const
{
   switch (getOpcode()) {
   case TGSI_OPCODE_UIF:
   case TGSI_OPCODE_AND:
   case TGSI_OPCODE_OR:
   case TGSI_OPCODE_XOR:
   case TGSI_OPCODE_NOT:
   case TGSI_OPCODE_SHL:
   case TGSI_OPCODE_U2F:
   case TGSI_OPCODE_U2D:
   case TGSI_OPCODE_U2I64:
   case TGSI_OPCODE_UADD:
   case TGSI_OPCODE_UDIV:
   case TGSI_OPCODE_UMOD:
   case TGSI_OPCODE_UMAD:
   case TGSI_OPCODE_UMUL:
   case TGSI_OPCODE_UMUL_HI:
   case TGSI_OPCODE_UMAX:
   case TGSI_OPCODE_UMIN:
   case TGSI_OPCODE_USEQ:
   case TGSI_OPCODE_USGE:
   case TGSI_OPCODE_USLT:
   case TGSI_OPCODE_USNE:
   case TGSI_OPCODE_USHR:
   case TGSI_OPCODE_ATOMUADD:
   case TGSI_OPCODE_ATOMXCHG:
   case TGSI_OPCODE_ATOMCAS:
   case TGSI_OPCODE_ATOMAND:
   case TGSI_OPCODE_ATOMOR:
   case TGSI_OPCODE_ATOMXOR:
   case TGSI_OPCODE_ATOMUMIN:
   case TGSI_OPCODE_ATOMUMAX:
   case TGSI_OPCODE_UBFE:
   case TGSI_OPCODE_UMSB:
   case TGSI_OPCODE_UP2H:
   case TGSI_OPCODE_VOTE_ALL:
   case TGSI_OPCODE_VOTE_ANY:
   case TGSI_OPCODE_VOTE_EQ:
      return nv50_ir::TYPE_U32;
   case TGSI_OPCODE_I2F:
   case TGSI_OPCODE_I2D:
   case TGSI_OPCODE_I2I64:
   case TGSI_OPCODE_IDIV:
   case TGSI_OPCODE_IMUL_HI:
   case TGSI_OPCODE_IMAX:
   case TGSI_OPCODE_IMIN:
   case TGSI_OPCODE_IABS:
   case TGSI_OPCODE_INEG:
   case TGSI_OPCODE_ISGE:
   case TGSI_OPCODE_ISHR:
   case TGSI_OPCODE_ISLT:
   case TGSI_OPCODE_ISSG:
   case TGSI_OPCODE_MOD:
   case TGSI_OPCODE_UARL:
   case TGSI_OPCODE_ATOMIMIN:
   case TGSI_OPCODE_ATOMIMAX:
   case TGSI_OPCODE_IBFE:
   case TGSI_OPCODE_IMSB:
      return nv50_ir::TYPE_S32;
   case TGSI_OPCODE_D2F:
   case TGSI_OPCODE_D2I:
   case TGSI_OPCODE_D2U:
   case TGSI_OPCODE_D2I64:
   case TGSI_OPCODE_D2U64:
   case TGSI_OPCODE_DABS:
   case TGSI_OPCODE_DNEG:
   case TGSI_OPCODE_DADD:
   case TGSI_OPCODE_DMUL:
   case TGSI_OPCODE_DDIV:
   case TGSI_OPCODE_DMAX:
   case TGSI_OPCODE_DMIN:
   case TGSI_OPCODE_DSLT:
   case TGSI_OPCODE_DSGE:
   case TGSI_OPCODE_DSEQ:
   case TGSI_OPCODE_DSNE:
   case TGSI_OPCODE_DRCP:
   case TGSI_OPCODE_DSQRT:
   case TGSI_OPCODE_DMAD:
   case TGSI_OPCODE_DFMA:
   case TGSI_OPCODE_DFRAC:
   case TGSI_OPCODE_DRSQ:
   case TGSI_OPCODE_DTRUNC:
   case TGSI_OPCODE_DCEIL:
   case TGSI_OPCODE_DFLR:
   case TGSI_OPCODE_DROUND:
      return nv50_ir::TYPE_F64;
   case TGSI_OPCODE_U64SEQ:
   case TGSI_OPCODE_U64SNE:
   case TGSI_OPCODE_U64SLT:
   case TGSI_OPCODE_U64SGE:
   case TGSI_OPCODE_U64MIN:
   case TGSI_OPCODE_U64MAX:
   case TGSI_OPCODE_U64ADD:
   case TGSI_OPCODE_U64MUL:
   case TGSI_OPCODE_U64SHL:
   case TGSI_OPCODE_U64SHR:
   case TGSI_OPCODE_U64DIV:
   case TGSI_OPCODE_U64MOD:
   case TGSI_OPCODE_U642F:
   case TGSI_OPCODE_U642D:
      return nv50_ir::TYPE_U64;
   case TGSI_OPCODE_I64ABS:
   case TGSI_OPCODE_I64SSG:
   case TGSI_OPCODE_I64NEG:
   case TGSI_OPCODE_I64SLT:
   case TGSI_OPCODE_I64SGE:
   case TGSI_OPCODE_I64MIN:
   case TGSI_OPCODE_I64MAX:
   case TGSI_OPCODE_I64SHR:
   case TGSI_OPCODE_I64DIV:
   case TGSI_OPCODE_I64MOD:
   case TGSI_OPCODE_I642F:
   case TGSI_OPCODE_I642D:
      return nv50_ir::TYPE_S64;
   default:
      return nv50_ir::TYPE_F32;
   }
}

nv50_ir::DataType Instruction::inferDstType() const
{
   switch (getOpcode()) {
   case TGSI_OPCODE_D2U:
   case TGSI_OPCODE_F2U: return nv50_ir::TYPE_U32;
   case TGSI_OPCODE_D2I:
   case TGSI_OPCODE_F2I: return nv50_ir::TYPE_S32;
   case TGSI_OPCODE_FSEQ:
   case TGSI_OPCODE_FSGE:
   case TGSI_OPCODE_FSLT:
   case TGSI_OPCODE_FSNE:
   case TGSI_OPCODE_DSEQ:
   case TGSI_OPCODE_DSGE:
   case TGSI_OPCODE_DSLT:
   case TGSI_OPCODE_DSNE:
   case TGSI_OPCODE_I64SLT:
   case TGSI_OPCODE_I64SGE:
   case TGSI_OPCODE_U64SEQ:
   case TGSI_OPCODE_U64SNE:
   case TGSI_OPCODE_U64SLT:
   case TGSI_OPCODE_U64SGE:
   case TGSI_OPCODE_PK2H:
      return nv50_ir::TYPE_U32;
   case TGSI_OPCODE_I2F:
   case TGSI_OPCODE_U2F:
   case TGSI_OPCODE_D2F:
   case TGSI_OPCODE_I642F:
   case TGSI_OPCODE_U642F:
   case TGSI_OPCODE_UP2H:
      return nv50_ir::TYPE_F32;
   case TGSI_OPCODE_I2D:
   case TGSI_OPCODE_U2D:
   case TGSI_OPCODE_F2D:
   case TGSI_OPCODE_I642D:
   case TGSI_OPCODE_U642D:
      return nv50_ir::TYPE_F64;
   case TGSI_OPCODE_I2I64:
   case TGSI_OPCODE_U2I64:
   case TGSI_OPCODE_F2I64:
   case TGSI_OPCODE_D2I64:
      return nv50_ir::TYPE_S64;
   case TGSI_OPCODE_F2U64:
   case TGSI_OPCODE_D2U64:
      return nv50_ir::TYPE_U64;
   default:
      return inferSrcType();
   }
}

nv50_ir::CondCode Instruction::getSetCond() const
{
   using namespace nv50_ir;

   switch (getOpcode()) {
   case TGSI_OPCODE_SLT:
   case TGSI_OPCODE_ISLT:
   case TGSI_OPCODE_USLT:
   case TGSI_OPCODE_FSLT:
   case TGSI_OPCODE_DSLT:
   case TGSI_OPCODE_I64SLT:
   case TGSI_OPCODE_U64SLT:
      return CC_LT;
   case TGSI_OPCODE_SLE:
      return CC_LE;
   case TGSI_OPCODE_SGE:
   case TGSI_OPCODE_ISGE:
   case TGSI_OPCODE_USGE:
   case TGSI_OPCODE_FSGE:
   case TGSI_OPCODE_DSGE:
   case TGSI_OPCODE_I64SGE:
   case TGSI_OPCODE_U64SGE:
      return CC_GE;
   case TGSI_OPCODE_SGT:
      return CC_GT;
   case TGSI_OPCODE_SEQ:
   case TGSI_OPCODE_USEQ:
   case TGSI_OPCODE_FSEQ:
   case TGSI_OPCODE_DSEQ:
   case TGSI_OPCODE_U64SEQ:
      return CC_EQ;
   case TGSI_OPCODE_SNE:
   case TGSI_OPCODE_FSNE:
   case TGSI_OPCODE_DSNE:
   case TGSI_OPCODE_U64SNE:
      return CC_NEU;
   case TGSI_OPCODE_USNE:
      return CC_NE;
   default:
      return CC_ALWAYS;
   }
}

#define NV50_IR_OPCODE_CASE(a, b) case TGSI_OPCODE_##a: return nv50_ir::OP_##b

static nv50_ir::operation translateOpcode(uint opcode)
{
   switch (opcode) {
   NV50_IR_OPCODE_CASE(ARL, SHL);
   NV50_IR_OPCODE_CASE(MOV, MOV);

   NV50_IR_OPCODE_CASE(RCP, RCP);
   NV50_IR_OPCODE_CASE(RSQ, RSQ);
   NV50_IR_OPCODE_CASE(SQRT, SQRT);

   NV50_IR_OPCODE_CASE(MUL, MUL);
   NV50_IR_OPCODE_CASE(ADD, ADD);

   NV50_IR_OPCODE_CASE(MIN, MIN);
   NV50_IR_OPCODE_CASE(MAX, MAX);
   NV50_IR_OPCODE_CASE(SLT, SET);
   NV50_IR_OPCODE_CASE(SGE, SET);
   NV50_IR_OPCODE_CASE(MAD, MAD);
   NV50_IR_OPCODE_CASE(FMA, FMA);

   NV50_IR_OPCODE_CASE(FLR, FLOOR);
   NV50_IR_OPCODE_CASE(ROUND, CVT);
   NV50_IR_OPCODE_CASE(EX2, EX2);
   NV50_IR_OPCODE_CASE(LG2, LG2);
   NV50_IR_OPCODE_CASE(POW, POW);

   NV50_IR_OPCODE_CASE(COS, COS);
   NV50_IR_OPCODE_CASE(DDX, DFDX);
   NV50_IR_OPCODE_CASE(DDX_FINE, DFDX);
   NV50_IR_OPCODE_CASE(DDY, DFDY);
   NV50_IR_OPCODE_CASE(DDY_FINE, DFDY);
   NV50_IR_OPCODE_CASE(KILL, DISCARD);

   NV50_IR_OPCODE_CASE(SEQ, SET);
   NV50_IR_OPCODE_CASE(SGT, SET);
   NV50_IR_OPCODE_CASE(SIN, SIN);
   NV50_IR_OPCODE_CASE(SLE, SET);
   NV50_IR_OPCODE_CASE(SNE, SET);
   NV50_IR_OPCODE_CASE(TEX, TEX);
   NV50_IR_OPCODE_CASE(TXD, TXD);
   NV50_IR_OPCODE_CASE(TXP, TEX);

   NV50_IR_OPCODE_CASE(CAL, CALL);
   NV50_IR_OPCODE_CASE(RET, RET);
   NV50_IR_OPCODE_CASE(CMP, SLCT);

   NV50_IR_OPCODE_CASE(TXB, TXB);

   NV50_IR_OPCODE_CASE(DIV, DIV);

   NV50_IR_OPCODE_CASE(TXL, TXL);
   NV50_IR_OPCODE_CASE(TEX_LZ, TXL);

   NV50_IR_OPCODE_CASE(CEIL, CEIL);
   NV50_IR_OPCODE_CASE(I2F, CVT);
   NV50_IR_OPCODE_CASE(NOT, NOT);
   NV50_IR_OPCODE_CASE(TRUNC, TRUNC);
   NV50_IR_OPCODE_CASE(SHL, SHL);

   NV50_IR_OPCODE_CASE(AND, AND);
   NV50_IR_OPCODE_CASE(OR, OR);
   NV50_IR_OPCODE_CASE(MOD, MOD);
   NV50_IR_OPCODE_CASE(XOR, XOR);
   NV50_IR_OPCODE_CASE(TXF, TXF);
   NV50_IR_OPCODE_CASE(TXF_LZ, TXF);
   NV50_IR_OPCODE_CASE(TXQ, TXQ);
   NV50_IR_OPCODE_CASE(TXQS, TXQ);
   NV50_IR_OPCODE_CASE(TG4, TXG);
   NV50_IR_OPCODE_CASE(LODQ, TXLQ);

   NV50_IR_OPCODE_CASE(EMIT, EMIT);
   NV50_IR_OPCODE_CASE(ENDPRIM, RESTART);

   NV50_IR_OPCODE_CASE(KILL_IF, DISCARD);

   NV50_IR_OPCODE_CASE(F2I, CVT);
   NV50_IR_OPCODE_CASE(FSEQ, SET);
   NV50_IR_OPCODE_CASE(FSGE, SET);
   NV50_IR_OPCODE_CASE(FSLT, SET);
   NV50_IR_OPCODE_CASE(FSNE, SET);
   NV50_IR_OPCODE_CASE(IDIV, DIV);
   NV50_IR_OPCODE_CASE(IMAX, MAX);
   NV50_IR_OPCODE_CASE(IMIN, MIN);
   NV50_IR_OPCODE_CASE(IABS, ABS);
   NV50_IR_OPCODE_CASE(INEG, NEG);
   NV50_IR_OPCODE_CASE(ISGE, SET);
   NV50_IR_OPCODE_CASE(ISHR, SHR);
   NV50_IR_OPCODE_CASE(ISLT, SET);
   NV50_IR_OPCODE_CASE(F2U, CVT);
   NV50_IR_OPCODE_CASE(U2F, CVT);
   NV50_IR_OPCODE_CASE(UADD, ADD);
   NV50_IR_OPCODE_CASE(UDIV, DIV);
   NV50_IR_OPCODE_CASE(UMAD, MAD);
   NV50_IR_OPCODE_CASE(UMAX, MAX);
   NV50_IR_OPCODE_CASE(UMIN, MIN);
   NV50_IR_OPCODE_CASE(UMOD, MOD);
   NV50_IR_OPCODE_CASE(UMUL, MUL);
   NV50_IR_OPCODE_CASE(USEQ, SET);
   NV50_IR_OPCODE_CASE(USGE, SET);
   NV50_IR_OPCODE_CASE(USHR, SHR);
   NV50_IR_OPCODE_CASE(USLT, SET);
   NV50_IR_OPCODE_CASE(USNE, SET);

   NV50_IR_OPCODE_CASE(DABS, ABS);
   NV50_IR_OPCODE_CASE(DNEG, NEG);
   NV50_IR_OPCODE_CASE(DADD, ADD);
   NV50_IR_OPCODE_CASE(DMUL, MUL);
   NV50_IR_OPCODE_CASE(DDIV, DIV);
   NV50_IR_OPCODE_CASE(DMAX, MAX);
   NV50_IR_OPCODE_CASE(DMIN, MIN);
   NV50_IR_OPCODE_CASE(DSLT, SET);
   NV50_IR_OPCODE_CASE(DSGE, SET);
   NV50_IR_OPCODE_CASE(DSEQ, SET);
   NV50_IR_OPCODE_CASE(DSNE, SET);
   NV50_IR_OPCODE_CASE(DRCP, RCP);
   NV50_IR_OPCODE_CASE(DSQRT, SQRT);
   NV50_IR_OPCODE_CASE(DMAD, MAD);
   NV50_IR_OPCODE_CASE(DFMA, FMA);
   NV50_IR_OPCODE_CASE(D2I, CVT);
   NV50_IR_OPCODE_CASE(D2U, CVT);
   NV50_IR_OPCODE_CASE(I2D, CVT);
   NV50_IR_OPCODE_CASE(U2D, CVT);
   NV50_IR_OPCODE_CASE(DRSQ, RSQ);
   NV50_IR_OPCODE_CASE(DTRUNC, TRUNC);
   NV50_IR_OPCODE_CASE(DCEIL, CEIL);
   NV50_IR_OPCODE_CASE(DFLR, FLOOR);
   NV50_IR_OPCODE_CASE(DROUND, CVT);

   NV50_IR_OPCODE_CASE(U64SEQ, SET);
   NV50_IR_OPCODE_CASE(U64SNE, SET);
   NV50_IR_OPCODE_CASE(U64SLT, SET);
   NV50_IR_OPCODE_CASE(U64SGE, SET);
   NV50_IR_OPCODE_CASE(I64SLT, SET);
   NV50_IR_OPCODE_CASE(I64SGE, SET);
   NV50_IR_OPCODE_CASE(I2I64, CVT);
   NV50_IR_OPCODE_CASE(U2I64, CVT);
   NV50_IR_OPCODE_CASE(F2I64, CVT);
   NV50_IR_OPCODE_CASE(F2U64, CVT);
   NV50_IR_OPCODE_CASE(D2I64, CVT);
   NV50_IR_OPCODE_CASE(D2U64, CVT);
   NV50_IR_OPCODE_CASE(I642F, CVT);
   NV50_IR_OPCODE_CASE(U642F, CVT);
   NV50_IR_OPCODE_CASE(I642D, CVT);
   NV50_IR_OPCODE_CASE(U642D, CVT);

   NV50_IR_OPCODE_CASE(I64MIN, MIN);
   NV50_IR_OPCODE_CASE(U64MIN, MIN);
   NV50_IR_OPCODE_CASE(I64MAX, MAX);
   NV50_IR_OPCODE_CASE(U64MAX, MAX);
   NV50_IR_OPCODE_CASE(I64ABS, ABS);
   NV50_IR_OPCODE_CASE(I64NEG, NEG);
   NV50_IR_OPCODE_CASE(U64ADD, ADD);
   NV50_IR_OPCODE_CASE(U64MUL, MUL);
   NV50_IR_OPCODE_CASE(U64SHL, SHL);
   NV50_IR_OPCODE_CASE(I64SHR, SHR);
   NV50_IR_OPCODE_CASE(U64SHR, SHR);

   NV50_IR_OPCODE_CASE(IMUL_HI, MUL);
   NV50_IR_OPCODE_CASE(UMUL_HI, MUL);

   NV50_IR_OPCODE_CASE(SAMPLE, TEX);
   NV50_IR_OPCODE_CASE(SAMPLE_B, TXB);
   NV50_IR_OPCODE_CASE(SAMPLE_C, TEX);
   NV50_IR_OPCODE_CASE(SAMPLE_C_LZ, TEX);
   NV50_IR_OPCODE_CASE(SAMPLE_D, TXD);
   NV50_IR_OPCODE_CASE(SAMPLE_L, TXL);
   NV50_IR_OPCODE_CASE(SAMPLE_I, TXF);
   NV50_IR_OPCODE_CASE(SAMPLE_I_MS, TXF);
   NV50_IR_OPCODE_CASE(GATHER4, TXG);
   NV50_IR_OPCODE_CASE(SVIEWINFO, TXQ);

   NV50_IR_OPCODE_CASE(ATOMUADD, ATOM);
   NV50_IR_OPCODE_CASE(ATOMXCHG, ATOM);
   NV50_IR_OPCODE_CASE(ATOMCAS, ATOM);
   NV50_IR_OPCODE_CASE(ATOMAND, ATOM);
   NV50_IR_OPCODE_CASE(ATOMOR, ATOM);
   NV50_IR_OPCODE_CASE(ATOMXOR, ATOM);
   NV50_IR_OPCODE_CASE(ATOMUMIN, ATOM);
   NV50_IR_OPCODE_CASE(ATOMUMAX, ATOM);
   NV50_IR_OPCODE_CASE(ATOMIMIN, ATOM);
   NV50_IR_OPCODE_CASE(ATOMIMAX, ATOM);
   NV50_IR_OPCODE_CASE(ATOMFADD, ATOM);

   NV50_IR_OPCODE_CASE(TEX2, TEX);
   NV50_IR_OPCODE_CASE(TXB2, TXB);
   NV50_IR_OPCODE_CASE(TXL2, TXL);

   NV50_IR_OPCODE_CASE(IBFE, EXTBF);
   NV50_IR_OPCODE_CASE(UBFE, EXTBF);
   NV50_IR_OPCODE_CASE(BFI, INSBF);
   NV50_IR_OPCODE_CASE(BREV, EXTBF);
   NV50_IR_OPCODE_CASE(POPC, POPCNT);
   NV50_IR_OPCODE_CASE(LSB, BFIND);
   NV50_IR_OPCODE_CASE(IMSB, BFIND);
   NV50_IR_OPCODE_CASE(UMSB, BFIND);

   NV50_IR_OPCODE_CASE(VOTE_ALL, VOTE);
   NV50_IR_OPCODE_CASE(VOTE_ANY, VOTE);
   NV50_IR_OPCODE_CASE(VOTE_EQ, VOTE);

   NV50_IR_OPCODE_CASE(BALLOT, VOTE);
   NV50_IR_OPCODE_CASE(READ_INVOC, SHFL);
   NV50_IR_OPCODE_CASE(READ_FIRST, SHFL);

   NV50_IR_OPCODE_CASE(END, EXIT);

   default:
      return nv50_ir::OP_NOP;
   }
}

static uint16_t opcodeToSubOp(uint opcode)
{
   switch (opcode) {
   case TGSI_OPCODE_ATOMUADD: return NV50_IR_SUBOP_ATOM_ADD;
   case TGSI_OPCODE_ATOMXCHG: return NV50_IR_SUBOP_ATOM_EXCH;
   case TGSI_OPCODE_ATOMCAS:  return NV50_IR_SUBOP_ATOM_CAS;
   case TGSI_OPCODE_ATOMAND:  return NV50_IR_SUBOP_ATOM_AND;
   case TGSI_OPCODE_ATOMOR:   return NV50_IR_SUBOP_ATOM_OR;
   case TGSI_OPCODE_ATOMXOR:  return NV50_IR_SUBOP_ATOM_XOR;
   case TGSI_OPCODE_ATOMUMIN: return NV50_IR_SUBOP_ATOM_MIN;
   case TGSI_OPCODE_ATOMIMIN: return NV50_IR_SUBOP_ATOM_MIN;
   case TGSI_OPCODE_ATOMUMAX: return NV50_IR_SUBOP_ATOM_MAX;
   case TGSI_OPCODE_ATOMIMAX: return NV50_IR_SUBOP_ATOM_MAX;
   case TGSI_OPCODE_ATOMFADD: return NV50_IR_SUBOP_ATOM_ADD;
   case TGSI_OPCODE_IMUL_HI:
   case TGSI_OPCODE_UMUL_HI:
      return NV50_IR_SUBOP_MUL_HIGH;
   case TGSI_OPCODE_VOTE_ALL: return NV50_IR_SUBOP_VOTE_ALL;
   case TGSI_OPCODE_VOTE_ANY: return NV50_IR_SUBOP_VOTE_ANY;
   case TGSI_OPCODE_VOTE_EQ: return NV50_IR_SUBOP_VOTE_UNI;
   default:
      return 0;
   }
}

bool Instruction::checkDstSrcAliasing() const
{
   if (insn->Dst[0].Register.Indirect) // no danger if indirect, using memory
      return false;

   for (int s = 0; s < TGSI_FULL_MAX_SRC_REGISTERS; ++s) {
      if (insn->Src[s].Register.File == TGSI_FILE_NULL)
         break;
      if (insn->Src[s].Register.File == insn->Dst[0].Register.File &&
          insn->Src[s].Register.Index == insn->Dst[0].Register.Index)
         return true;
   }
   return false;
}

class Source
{
public:
   Source(struct nv50_ir_prog_info *);
   ~Source();

public:
   bool scanSource();
   unsigned fileSize(unsigned file) const { return scan.file_max[file] + 1; }

public:
   struct tgsi_shader_info scan;
   struct tgsi_full_instruction *insns;
   const struct tgsi_token *tokens;
   struct nv50_ir_prog_info *info;

   nv50_ir::DynArray tempArrays;
   nv50_ir::DynArray immdArrays;

   typedef nv50_ir::BuildUtil::Location Location;
   // these registers are per-subroutine, cannot be used for parameter passing
   std::set<Location> locals;

   std::set<int> indirectTempArrays;
   std::map<int, int> indirectTempOffsets;
   std::map<int, std::pair<int, int> > tempArrayInfo;
   std::vector<int> tempArrayId;

   int clipVertexOutput;

   struct TextureView {
      uint8_t target; // TGSI_TEXTURE_*
   };
   std::vector<TextureView> textureViews;

   /*
   struct Resource {
      uint8_t target; // TGSI_TEXTURE_*
      bool raw;
      uint8_t slot; // $surface index
   };
   std::vector<Resource> resources;
   */

   struct MemoryFile {
      uint8_t mem_type; // TGSI_MEMORY_TYPE_*
   };
   std::vector<MemoryFile> memoryFiles;

   std::vector<bool> bufferAtomics;

private:
   int inferSysValDirection(unsigned sn) const;
   bool scanDeclaration(const struct tgsi_full_declaration *);
   bool scanInstruction(const struct tgsi_full_instruction *);
   void scanInstructionSrc(const Instruction& insn,
                           const Instruction::SrcRegister& src,
                           unsigned mask);
   void scanProperty(const struct tgsi_full_property *);
   void scanImmediate(const struct tgsi_full_immediate *);

   inline bool isEdgeFlagPassthrough(const Instruction&) const;
};

Source::Source(struct nv50_ir_prog_info *prog) : info(prog)
{
   tokens = (const struct tgsi_token *)info->bin.source;

   if (prog->dbgFlags & NV50_IR_DEBUG_BASIC)
      tgsi_dump(tokens, 0);
}

Source::~Source()
{
   if (insns)
      FREE(insns);

   if (info->immd.data)
      FREE(info->immd.data);
   if (info->immd.type)
      FREE(info->immd.type);
}

bool Source::scanSource()
{
   unsigned insnCount = 0;
   struct tgsi_parse_context parse;

   tgsi_scan_shader(tokens, &scan);

   insns = (struct tgsi_full_instruction *)MALLOC(scan.num_instructions *
                                                  sizeof(insns[0]));
   if (!insns)
      return false;

   clipVertexOutput = -1;

   textureViews.resize(scan.file_max[TGSI_FILE_SAMPLER_VIEW] + 1);
   //resources.resize(scan.file_max[TGSI_FILE_RESOURCE] + 1);
   tempArrayId.resize(scan.file_max[TGSI_FILE_TEMPORARY] + 1);
   memoryFiles.resize(scan.file_max[TGSI_FILE_MEMORY] + 1);
   bufferAtomics.resize(scan.file_max[TGSI_FILE_BUFFER] + 1);

   info->immd.bufSize = 0;

   info->numInputs = scan.file_max[TGSI_FILE_INPUT] + 1;
   info->numOutputs = scan.file_max[TGSI_FILE_OUTPUT] + 1;
   info->numSysVals = scan.file_max[TGSI_FILE_SYSTEM_VALUE] + 1;

   if (info->type == PIPE_SHADER_FRAGMENT) {
      info->prop.fp.writesDepth = scan.writes_z;
      info->prop.fp.usesDiscard = scan.uses_kill || info->io.alphaRefBase;
   } else
   if (info->type == PIPE_SHADER_GEOMETRY) {
      info->prop.gp.instanceCount = 1; // default value
   }

   info->io.viewportId = -1;

   info->immd.data = (uint32_t *)MALLOC(scan.immediate_count * 16);
   info->immd.type = (ubyte *)MALLOC(scan.immediate_count * sizeof(ubyte));

   tgsi_parse_init(&parse, tokens);
   while (!tgsi_parse_end_of_tokens(&parse)) {
      tgsi_parse_token(&parse);

      switch (parse.FullToken.Token.Type) {
      case TGSI_TOKEN_TYPE_IMMEDIATE:
         scanImmediate(&parse.FullToken.FullImmediate);
         break;
      case TGSI_TOKEN_TYPE_DECLARATION:
         scanDeclaration(&parse.FullToken.FullDeclaration);
         break;
      case TGSI_TOKEN_TYPE_INSTRUCTION:
         insns[insnCount++] = parse.FullToken.FullInstruction;
         scanInstruction(&parse.FullToken.FullInstruction);
         break;
      case TGSI_TOKEN_TYPE_PROPERTY:
         scanProperty(&parse.FullToken.FullProperty);
         break;
      default:
         INFO("unknown TGSI token type: %d\n", parse.FullToken.Token.Type);
         break;
      }
   }
   tgsi_parse_free(&parse);

   if (indirectTempArrays.size()) {
      int tempBase = 0;
      for (std::set<int>::const_iterator it = indirectTempArrays.begin();
           it != indirectTempArrays.end(); ++it) {
         std::pair<int, int>& info = tempArrayInfo[*it];
         indirectTempOffsets.insert(std::make_pair(*it, tempBase - info.first));
         tempBase += info.second;
      }
      info->bin.tlsSpace += tempBase * 16;
   }

   if (info->io.genUserClip > 0) {
      info->io.clipDistances = info->io.genUserClip;

      const unsigned int nOut = (info->io.genUserClip + 3) / 4;

      for (unsigned int n = 0; n < nOut; ++n) {
         unsigned int i = info->numOutputs++;
         info->out[i].id = i;
         info->out[i].sn = TGSI_SEMANTIC_CLIPDIST;
         info->out[i].si = n;
         info->out[i].mask = ((1 << info->io.clipDistances) - 1) >> (n * 4);
      }
   }

   return info->assignSlots(info) == 0;
}

void Source::scanProperty(const struct tgsi_full_property *prop)
{
   switch (prop->Property.PropertyName) {
   case TGSI_PROPERTY_GS_OUTPUT_PRIM:
      info->prop.gp.outputPrim = prop->u[0].Data;
      break;
   case TGSI_PROPERTY_GS_INPUT_PRIM:
      info->prop.gp.inputPrim = prop->u[0].Data;
      break;
   case TGSI_PROPERTY_GS_MAX_OUTPUT_VERTICES:
      info->prop.gp.maxVertices = prop->u[0].Data;
      break;
   case TGSI_PROPERTY_GS_INVOCATIONS:
      info->prop.gp.instanceCount = prop->u[0].Data;
      break;
   case TGSI_PROPERTY_FS_COLOR0_WRITES_ALL_CBUFS:
      info->prop.fp.separateFragData = true;
      break;
   case TGSI_PROPERTY_FS_COORD_ORIGIN:
   case TGSI_PROPERTY_FS_COORD_PIXEL_CENTER:
   case TGSI_PROPERTY_FS_DEPTH_LAYOUT:
      // we don't care
      break;
   case TGSI_PROPERTY_VS_PROHIBIT_UCPS:
      info->io.genUserClip = -1;
      break;
   case TGSI_PROPERTY_TCS_VERTICES_OUT:
      info->prop.tp.outputPatchSize = prop->u[0].Data;
      break;
   case TGSI_PROPERTY_TES_PRIM_MODE:
      info->prop.tp.domain = prop->u[0].Data;
      break;
   case TGSI_PROPERTY_TES_SPACING:
      info->prop.tp.partitioning = prop->u[0].Data;
      break;
   case TGSI_PROPERTY_TES_VERTEX_ORDER_CW:
      info->prop.tp.winding = prop->u[0].Data;
      break;
   case TGSI_PROPERTY_TES_POINT_MODE:
      if (prop->u[0].Data)
         info->prop.tp.outputPrim = PIPE_PRIM_POINTS;
      else
         info->prop.tp.outputPrim = PIPE_PRIM_TRIANGLES; /* anything but points */
      break;
   case TGSI_PROPERTY_CS_FIXED_BLOCK_WIDTH:
      info->prop.cp.numThreads[0] = prop->u[0].Data;
      break;
   case TGSI_PROPERTY_CS_FIXED_BLOCK_HEIGHT:
      info->prop.cp.numThreads[1] = prop->u[0].Data;
      break;
   case TGSI_PROPERTY_CS_FIXED_BLOCK_DEPTH:
      info->prop.cp.numThreads[2] = prop->u[0].Data;
      break;
   case TGSI_PROPERTY_NUM_CLIPDIST_ENABLED:
      info->io.clipDistances = prop->u[0].Data;
      break;
   case TGSI_PROPERTY_NUM_CULLDIST_ENABLED:
      info->io.cullDistances = prop->u[0].Data;
      break;
   case TGSI_PROPERTY_NEXT_SHADER:
      /* Do not need to know the next shader stage. */
      break;
   case TGSI_PROPERTY_FS_EARLY_DEPTH_STENCIL:
      info->prop.fp.earlyFragTests = prop->u[0].Data;
      break;
   case TGSI_PROPERTY_FS_POST_DEPTH_COVERAGE:
      info->prop.fp.postDepthCoverage = prop->u[0].Data;
      break;
   case TGSI_PROPERTY_MUL_ZERO_WINS:
      info->io.mul_zero_wins = prop->u[0].Data;
      break;
   default:
      INFO("unhandled TGSI property %d\n", prop->Property.PropertyName);
      break;
   }
}

void Source::scanImmediate(const struct tgsi_full_immediate *imm)
{
   const unsigned n = info->immd.count++;

   assert(n < scan.immediate_count);

   for (int c = 0; c < 4; ++c)
      info->immd.data[n * 4 + c] = imm->u[c].Uint;

   info->immd.type[n] = imm->Immediate.DataType;
}

int Source::inferSysValDirection(unsigned sn) const
{
   switch (sn) {
   case TGSI_SEMANTIC_INSTANCEID:
   case TGSI_SEMANTIC_VERTEXID:
      return 1;
   case TGSI_SEMANTIC_LAYER:
#if 0
   case TGSI_SEMANTIC_VIEWPORTINDEX:
      return 0;
#endif
   case TGSI_SEMANTIC_PRIMID:
      return (info->type == PIPE_SHADER_FRAGMENT) ? 1 : 0;
   default:
      return 0;
   }
}

bool Source::scanDeclaration(const struct tgsi_full_declaration *decl)
{
   unsigned i, c;
   unsigned sn = TGSI_SEMANTIC_GENERIC;
   unsigned si = 0;
   const unsigned first = decl->Range.First, last = decl->Range.Last;
   const int arrayId = decl->Array.ArrayID;

   if (decl->Declaration.Semantic) {
      sn = decl->Semantic.Name;
      si = decl->Semantic.Index;
   }

   if (decl->Declaration.Local || decl->Declaration.File == TGSI_FILE_ADDRESS) {
      for (i = first; i <= last; ++i) {
         for (c = 0; c < 4; ++c) {
            locals.insert(
               Location(decl->Declaration.File, decl->Dim.Index2D, i, c));
         }
      }
   }

   switch (decl->Declaration.File) {
   case TGSI_FILE_INPUT:
      if (info->type == PIPE_SHADER_VERTEX) {
         // all vertex attributes are equal
         for (i = first; i <= last; ++i) {
            info->in[i].sn = TGSI_SEMANTIC_GENERIC;
            info->in[i].si = i;
         }
      } else {
         for (i = first; i <= last; ++i, ++si) {
            info->in[i].id = i;
            info->in[i].sn = sn;
            info->in[i].si = si;
            if (info->type == PIPE_SHADER_FRAGMENT) {
               // translate interpolation mode
               switch (decl->Interp.Interpolate) {
               case TGSI_INTERPOLATE_CONSTANT:
                  info->in[i].flat = 1;
                  break;
               case TGSI_INTERPOLATE_COLOR:
                  info->in[i].sc = 1;
                  break;
               case TGSI_INTERPOLATE_LINEAR:
                  info->in[i].linear = 1;
                  break;
               default:
                  break;
               }
               if (decl->Interp.Location)
                  info->in[i].centroid = 1;
            }

            if (sn == TGSI_SEMANTIC_PATCH)
               info->in[i].patch = 1;
            if (sn == TGSI_SEMANTIC_PATCH)
               info->numPatchConstants = MAX2(info->numPatchConstants, si + 1);
         }
      }
      break;
   case TGSI_FILE_OUTPUT:
      for (i = first; i <= last; ++i, ++si) {
         switch (sn) {
         case TGSI_SEMANTIC_POSITION:
            if (info->type == PIPE_SHADER_FRAGMENT)
               info->io.fragDepth = i;
            else
            if (clipVertexOutput < 0)
               clipVertexOutput = i;
            break;
         case TGSI_SEMANTIC_COLOR:
            if (info->type == PIPE_SHADER_FRAGMENT)
               info->prop.fp.numColourResults++;
            break;
         case TGSI_SEMANTIC_EDGEFLAG:
            info->io.edgeFlagOut = i;
            break;
         case TGSI_SEMANTIC_CLIPVERTEX:
            clipVertexOutput = i;
            break;
         case TGSI_SEMANTIC_CLIPDIST:
            info->io.genUserClip = -1;
            break;
         case TGSI_SEMANTIC_SAMPLEMASK:
            info->io.sampleMask = i;
            break;
         case TGSI_SEMANTIC_VIEWPORT_INDEX:
            info->io.viewportId = i;
            break;
         case TGSI_SEMANTIC_PATCH:
            info->numPatchConstants = MAX2(info->numPatchConstants, si + 1);
            /* fallthrough */
         case TGSI_SEMANTIC_TESSOUTER:
         case TGSI_SEMANTIC_TESSINNER:
            info->out[i].patch = 1;
            break;
         default:
            break;
         }
         info->out[i].id = i;
         info->out[i].sn = sn;
         info->out[i].si = si;
      }
      break;
   case TGSI_FILE_SYSTEM_VALUE:
      switch (sn) {
      case TGSI_SEMANTIC_INSTANCEID:
         info->io.instanceId = first;
         break;
      case TGSI_SEMANTIC_VERTEXID:
         info->io.vertexId = first;
         break;
      case TGSI_SEMANTIC_BASEVERTEX:
      case TGSI_SEMANTIC_BASEINSTANCE:
      case TGSI_SEMANTIC_DRAWID:
         info->prop.vp.usesDrawParameters = true;
         break;
      case TGSI_SEMANTIC_SAMPLEID:
      case TGSI_SEMANTIC_SAMPLEPOS:
         info->prop.fp.persampleInvocation = true;
         break;
      case TGSI_SEMANTIC_SAMPLEMASK:
         info->prop.fp.usesSampleMaskIn = true;
         break;
      default:
         break;
      }
      for (i = first; i <= last; ++i, ++si) {
         info->sv[i].sn = sn;
         info->sv[i].si = si;
         info->sv[i].input = inferSysValDirection(sn);

         switch (sn) {
         case TGSI_SEMANTIC_TESSOUTER:
         case TGSI_SEMANTIC_TESSINNER:
            info->sv[i].patch = 1;
            break;
         }
      }
      break;
/*
   case TGSI_FILE_RESOURCE:
      for (i = first; i <= last; ++i) {
         resources[i].target = decl->Resource.Resource;
         resources[i].raw = decl->Resource.Raw;
         resources[i].slot = i;
      }
      break;
*/
   case TGSI_FILE_SAMPLER_VIEW:
      for (i = first; i <= last; ++i)
         textureViews[i].target = decl->SamplerView.Resource;
      break;
   case TGSI_FILE_MEMORY:
      for (i = first; i <= last; ++i)
         memoryFiles[i].mem_type = decl->Declaration.MemType;
      break;
   case TGSI_FILE_NULL:
   case TGSI_FILE_TEMPORARY:
      for (i = first; i <= last; ++i)
         tempArrayId[i] = arrayId;
      if (arrayId)
         tempArrayInfo.insert(std::make_pair(arrayId, std::make_pair(
                                                   first, last - first + 1)));
      break;
   case TGSI_FILE_BUFFER:
      for (i = first; i <= last; ++i)
         bufferAtomics[i] = decl->Declaration.Atomic;
      break;
   case TGSI_FILE_ADDRESS:
   case TGSI_FILE_CONSTANT:
   case TGSI_FILE_IMMEDIATE:
   case TGSI_FILE_SAMPLER:
   case TGSI_FILE_IMAGE:
      break;
   default:
      ERROR("unhandled TGSI_FILE %d\n", decl->Declaration.File);
      return false;
   }
   return true;
}

inline bool Source::isEdgeFlagPassthrough(const Instruction& insn) const
{
   return insn.getOpcode() == TGSI_OPCODE_MOV &&
      insn.getDst(0).getIndex(0) == info->io.edgeFlagOut &&
      insn.getSrc(0).getFile() == TGSI_FILE_INPUT;
}

void Source::scanInstructionSrc(const Instruction& insn,
                                const Instruction::SrcRegister& src,
                                unsigned mask)
{
   if (src.getFile() == TGSI_FILE_TEMPORARY) {
      if (src.isIndirect(0))
         indirectTempArrays.insert(src.getArrayId());
   } else
   if (src.getFile() == TGSI_FILE_OUTPUT) {
      if (src.isIndirect(0)) {
         // We don't know which one is accessed, just mark everything for
         // reading. This is an extremely unlikely occurrence.
         for (unsigned i = 0; i < info->numOutputs; ++i)
            info->out[i].oread = 1;
      } else {
         info->out[src.getIndex(0)].oread = 1;
      }
   }
   if (src.getFile() == TGSI_FILE_SYSTEM_VALUE) {
      if (info->sv[src.getIndex(0)].sn == TGSI_SEMANTIC_SAMPLEPOS)
         info->prop.fp.readsSampleLocations = true;
   }
   if (src.getFile() != TGSI_FILE_INPUT)
      return;

   if (src.isIndirect(0)) {
      for (unsigned i = 0; i < info->numInputs; ++i)
         info->in[i].mask = 0xf;
   } else {
      const int i = src.getIndex(0);
      for (unsigned c = 0; c < 4; ++c) {
         if (!(mask & (1 << c)))
            continue;
         int k = src.getSwizzle(c);
         if (k <= TGSI_SWIZZLE_W)
            info->in[i].mask |= 1 << k;
      }
      switch (info->in[i].sn) {
      case TGSI_SEMANTIC_PSIZE:
      case TGSI_SEMANTIC_PRIMID:
      case TGSI_SEMANTIC_FOG:
         info->in[i].mask &= 0x1;
         break;
      case TGSI_SEMANTIC_PCOORD:
         info->in[i].mask &= 0x3;
         break;
      default:
         break;
      }
   }
}

bool Source::scanInstruction(const struct tgsi_full_instruction *inst)
{
   Instruction insn(inst);

   if (insn.getOpcode() == TGSI_OPCODE_BARRIER)
      info->numBarriers = 1;

   if (insn.getOpcode() == TGSI_OPCODE_FBFETCH)
      info->prop.fp.readsFramebuffer = true;

   if (insn.getOpcode() == TGSI_OPCODE_INTERP_SAMPLE)
      info->prop.fp.readsSampleLocations = true;

   if (insn.dstCount()) {
      Instruction::DstRegister dst = insn.getDst(0);

      if (insn.getOpcode() == TGSI_OPCODE_STORE &&
          dst.getFile() != TGSI_FILE_MEMORY) {
         info->io.globalAccess |= 0x2;
      }

      if (dst.getFile() == TGSI_FILE_OUTPUT) {
         if (dst.isIndirect(0))
            for (unsigned i = 0; i < info->numOutputs; ++i)
               info->out[i].mask = 0xf;
         else
            info->out[dst.getIndex(0)].mask |= dst.getMask();

         if (info->out[dst.getIndex(0)].sn == TGSI_SEMANTIC_PSIZE ||
             info->out[dst.getIndex(0)].sn == TGSI_SEMANTIC_PRIMID ||
             info->out[dst.getIndex(0)].sn == TGSI_SEMANTIC_LAYER ||
             info->out[dst.getIndex(0)].sn == TGSI_SEMANTIC_VIEWPORT_INDEX ||
             info->out[dst.getIndex(0)].sn == TGSI_SEMANTIC_FOG)
            info->out[dst.getIndex(0)].mask &= 1;

         if (isEdgeFlagPassthrough(insn))
            info->io.edgeFlagIn = insn.getSrc(0).getIndex(0);
      } else
      if (dst.getFile() == TGSI_FILE_TEMPORARY) {
         if (dst.isIndirect(0))
            indirectTempArrays.insert(dst.getArrayId());
      } else
      if (dst.getFile() == TGSI_FILE_BUFFER ||
          dst.getFile() == TGSI_FILE_IMAGE ||
          (dst.getFile() == TGSI_FILE_MEMORY &&
           memoryFiles[dst.getIndex(0)].mem_type == TGSI_MEMORY_TYPE_GLOBAL)) {
         info->io.globalAccess |= 0x2;
      }
   }

   if (insn.srcCount() && (
             insn.getSrc(0).getFile() != TGSI_FILE_MEMORY ||
             memoryFiles[insn.getSrc(0).getIndex(0)].mem_type ==
             TGSI_MEMORY_TYPE_GLOBAL)) {
      switch (insn.getOpcode()) {
      case TGSI_OPCODE_ATOMUADD:
      case TGSI_OPCODE_ATOMXCHG:
      case TGSI_OPCODE_ATOMCAS:
      case TGSI_OPCODE_ATOMAND:
      case TGSI_OPCODE_ATOMOR:
      case TGSI_OPCODE_ATOMXOR:
      case TGSI_OPCODE_ATOMUMIN:
      case TGSI_OPCODE_ATOMIMIN:
      case TGSI_OPCODE_ATOMUMAX:
      case TGSI_OPCODE_ATOMIMAX:
      case TGSI_OPCODE_ATOMFADD:
      case TGSI_OPCODE_LOAD:
         info->io.globalAccess |= (insn.getOpcode() == TGSI_OPCODE_LOAD) ?
            0x1 : 0x2;
         break;
      }
   }


   for (unsigned s = 0; s < insn.srcCount(); ++s)
      scanInstructionSrc(insn, insn.getSrc(s), insn.srcMask(s));

   for (unsigned s = 0; s < insn.getNumTexOffsets(); ++s)
      scanInstructionSrc(insn, insn.getTexOffset(s), insn.texOffsetMask());

   return true;
}

nv50_ir::TexInstruction::Target
Instruction::getTexture(const tgsi::Source *code, int s) const
{
   // XXX: indirect access
   unsigned int r;

   switch (getSrc(s).getFile()) {
/*
   case TGSI_FILE_RESOURCE:
      r = getSrc(s).getIndex(0);
      return translateTexture(code->resources.at(r).target);
*/
   case TGSI_FILE_SAMPLER_VIEW:
      r = getSrc(s).getIndex(0);
      return translateTexture(code->textureViews.at(r).target);
   default:
      return translateTexture(insn->Texture.Texture);
   }
}

} // namespace tgsi

namespace {

using namespace nv50_ir;

class Converter : public ConverterCommon
{
public:
   Converter(Program *, const tgsi::Source *);
   ~Converter();

   bool run();

private:
   Value *shiftAddress(Value *);
   Value *getVertexBase(int s);
   Value *getOutputBase(int s);
   DataArray *getArrayForFile(unsigned file, int idx);
   Value *fetchSrc(int s, int c);
   Value *fetchDst(int d, int c);
   Value *acquireDst(int d, int c);
   void storeDst(int d, int c, Value *);

   Value *fetchSrc(const tgsi::Instruction::SrcRegister src, int c, Value *ptr);
   void storeDst(const tgsi::Instruction::DstRegister dst, int c,
                 Value *val, Value *ptr);

   void adjustTempIndex(int arrayId, int &idx, int &idx2d) const;
   Value *applySrcMod(Value *, int s, int c);

   Symbol *makeSym(uint file, int fileIndex, int idx, int c, uint32_t addr);
   Symbol *srcToSym(tgsi::Instruction::SrcRegister, int c);
   Symbol *dstToSym(tgsi::Instruction::DstRegister, int c);

   bool isSubGroupMask(uint8_t semantic);

   bool handleInstruction(const struct tgsi_full_instruction *);
   void exportOutputs();
   inline bool isEndOfSubroutine(uint ip);

   void loadProjTexCoords(Value *dst[4], Value *src[4], unsigned int mask);

   // R,S,L,C,Dx,Dy encode TGSI sources for respective values (0xSf for auto)
   void setTexRS(TexInstruction *, unsigned int& s, int R, int S);
   void handleTEX(Value *dst0[4], int R, int S, int L, int C, int Dx, int Dy);
   void handleTXF(Value *dst0[4], int R, int L_M);
   void handleTXQ(Value *dst0[4], enum TexQuery, int R);
   void handleFBFETCH(Value *dst0[4]);
   void handleLIT(Value *dst0[4]);

   // Symbol *getResourceBase(int r);
   void getImageCoords(std::vector<Value *>&, int s);

   void handleLOAD(Value *dst0[4]);
   void handleSTORE();
   void handleATOM(Value *dst0[4], DataType, uint16_t subOp);

   void handleINTERP(Value *dst0[4]);

   Value *interpolate(tgsi::Instruction::SrcRegister, int c, Value *ptr);

   void insertConvergenceOps(BasicBlock *conv, BasicBlock *fork);

   Value *buildDot(int dim);

   class BindArgumentsPass : public Pass {
   public:
      BindArgumentsPass(Converter &conv) : conv(conv) { }

   private:
      Converter &conv;
      Subroutine *sub;

      inline const Location *getValueLocation(Subroutine *, Value *);

      template<typename T> inline void
      updateCallArgs(Instruction *i, void (Instruction::*setArg)(int, Value *),
                     T (Function::*proto));

      template<typename T> inline void
      updatePrototype(BitSet *set, void (Function::*updateSet)(),
                      T (Function::*proto));

   protected:
      bool visit(Function *);
      bool visit(BasicBlock *bb) { return false; }
   };

private:
   const tgsi::Source *code;

   uint ip; // instruction pointer

   tgsi::Instruction tgsi;

   DataType dstTy;
   DataType srcTy;

   DataArray tData; // TGSI_FILE_TEMPORARY
   DataArray lData; // TGSI_FILE_TEMPORARY, for indirect arrays
   DataArray aData; // TGSI_FILE_ADDRESS
   DataArray oData; // TGSI_FILE_OUTPUT (if outputs in registers)

   Value *zero;

   Value *vtxBase[5]; // base address of vertex in primitive (for TP/GP)
   uint8_t vtxBaseValid;

   Stack condBBs;  // fork BB, then else clause BB
   Stack joinBBs;  // fork BB, for inserting join ops on ENDIF
   Stack loopBBs;  // loop headers
   Stack breakBBs; // end of / after loop

   Value *viewport;
};

Symbol *
Converter::srcToSym(tgsi::Instruction::SrcRegister src, int c)
{
   const int swz = src.getSwizzle(c);

   /* TODO: Use Array ID when it's available for the index */
   return makeSym(src.getFile(),
                  src.is2D() ? src.getIndex(1) : 0,
                  src.getIndex(0), swz,
                  src.getIndex(0) * 16 + swz * 4);
}

Symbol *
Converter::dstToSym(tgsi::Instruction::DstRegister dst, int c)
{
   /* TODO: Use Array ID when it's available for the index */
   return makeSym(dst.getFile(),
                  dst.is2D() ? dst.getIndex(1) : 0,
                  dst.getIndex(0), c,
                  dst.getIndex(0) * 16 + c * 4);
}

Symbol *
Converter::makeSym(uint tgsiFile, int fileIdx, int idx, int c, uint32_t address)
{
   Symbol *sym = new_Symbol(prog, tgsi::translateFile(tgsiFile));

   sym->reg.fileIndex = fileIdx;

   if (tgsiFile == TGSI_FILE_MEMORY) {
      switch (code->memoryFiles[fileIdx].mem_type) {
      case TGSI_MEMORY_TYPE_GLOBAL:
         /* No-op this is the default for TGSI_FILE_MEMORY */
         sym->setFile(FILE_MEMORY_GLOBAL);
         break;
      case TGSI_MEMORY_TYPE_SHARED:
         sym->setFile(FILE_MEMORY_SHARED);
         break;
      case TGSI_MEMORY_TYPE_INPUT:
         assert(prog->getType() == Program::TYPE_COMPUTE);
         assert(idx == -1);
         sym->setFile(FILE_SHADER_INPUT);
         address += info->prop.cp.inputOffset;
         break;
      default:
         assert(0); /* TODO: Add support for global and private memory */
      }
   }

   if (idx >= 0) {
      if (sym->reg.file == FILE_SHADER_INPUT)
         sym->setOffset(info->in[idx].slot[c] * 4);
      else
      if (sym->reg.file == FILE_SHADER_OUTPUT)
         sym->setOffset(info->out[idx].slot[c] * 4);
      else
      if (sym->reg.file == FILE_SYSTEM_VALUE)
         sym->setSV(tgsi::translateSysVal(info->sv[idx].sn), c);
      else
         sym->setOffset(address);
   } else {
      sym->setOffset(address);
   }
   return sym;
}

Value *
Converter::interpolate(tgsi::Instruction::SrcRegister src, int c, Value *ptr)
{
   operation op;

   // XXX: no way to know interpolation mode if we don't know what's accessed
   const uint8_t mode = translateInterpMode(&info->in[ptr ? 0 :
                                                      src.getIndex(0)], op);

   Instruction *insn = new_Instruction(func, op, TYPE_F32);

   insn->setDef(0, getScratch());
   insn->setSrc(0, srcToSym(src, c));
   if (op == OP_PINTERP)
      insn->setSrc(1, fragCoord[3]);
   if (ptr)
      insn->setIndirect(0, 0, ptr);

   insn->setInterpolate(mode);

   bb->insertTail(insn);
   return insn->getDef(0);
}

Value *
Converter::applySrcMod(Value *val, int s, int c)
{
   Modifier m = tgsi.getSrc(s).getMod(c);
   DataType ty = tgsi.inferSrcType();

   if (m & Modifier(NV50_IR_MOD_ABS))
      val = mkOp1v(OP_ABS, ty, getScratch(), val);

   if (m & Modifier(NV50_IR_MOD_NEG))
      val = mkOp1v(OP_NEG, ty, getScratch(), val);

   return val;
}

Value *
Converter::getVertexBase(int s)
{
   assert(s < 5);
   if (!(vtxBaseValid & (1 << s))) {
      const int index = tgsi.getSrc(s).getIndex(1);
      Value *rel = NULL;
      if (tgsi.getSrc(s).isIndirect(1))
         rel = fetchSrc(tgsi.getSrc(s).getIndirect(1), 0, NULL);
      vtxBaseValid |= 1 << s;
      vtxBase[s] = mkOp2v(OP_PFETCH, TYPE_U32, getSSA(4, FILE_ADDRESS),
                          mkImm(index), rel);
   }
   return vtxBase[s];
}

Value *
Converter::getOutputBase(int s)
{
   assert(s < 5);
   if (!(vtxBaseValid & (1 << s))) {
      Value *offset = loadImm(NULL, tgsi.getSrc(s).getIndex(1));
      if (tgsi.getSrc(s).isIndirect(1))
         offset = mkOp2v(OP_ADD, TYPE_U32, getSSA(),
                         fetchSrc(tgsi.getSrc(s).getIndirect(1), 0, NULL),
                         offset);
      vtxBaseValid |= 1 << s;
      vtxBase[s] = mkOp2v(OP_ADD, TYPE_U32, getSSA(), outBase, offset);
   }
   return vtxBase[s];
}

Value *
Converter::fetchSrc(int s, int c)
{
   Value *res;
   Value *ptr = NULL, *dimRel = NULL;

   tgsi::Instruction::SrcRegister src = tgsi.getSrc(s);

   if (src.isIndirect(0))
      ptr = fetchSrc(src.getIndirect(0), 0, NULL);

   if (src.is2D()) {
      switch (src.getFile()) {
      case TGSI_FILE_OUTPUT:
         dimRel = getOutputBase(s);
         break;
      case TGSI_FILE_INPUT:
         dimRel = getVertexBase(s);
         break;
      case TGSI_FILE_CONSTANT:
         // on NVC0, this is valid and c{I+J}[k] == cI[(J << 16) + k]
         if (src.isIndirect(1))
            dimRel = fetchSrc(src.getIndirect(1), 0, 0);
         break;
      default:
         break;
      }
   }

   res = fetchSrc(src, c, ptr);

   if (dimRel)
      res->getInsn()->setIndirect(0, 1, dimRel);

   return applySrcMod(res, s, c);
}

Value *
Converter::fetchDst(int d, int c)
{
   Value *res;
   Value *ptr = NULL, *dimRel = NULL;

   tgsi::Instruction::DstRegister dst = tgsi.getDst(d);

   if (dst.isIndirect(0))
      ptr = fetchSrc(dst.getIndirect(0), 0, NULL);

   if (dst.is2D()) {
      switch (dst.getFile()) {
      case TGSI_FILE_OUTPUT:
         assert(0); // TODO
         dimRel = NULL;
         break;
      case TGSI_FILE_INPUT:
         assert(0); // TODO
         dimRel = NULL;
         break;
      case TGSI_FILE_CONSTANT:
         // on NVC0, this is valid and c{I+J}[k] == cI[(J << 16) + k]
         if (dst.isIndirect(1))
            dimRel = fetchSrc(dst.getIndirect(1), 0, 0);
         break;
      default:
         break;
      }
   }

   struct tgsi_full_src_register fsr = dst.asSrc();
   tgsi::Instruction::SrcRegister src(&fsr);
   res = fetchSrc(src, c, ptr);

   if (dimRel)
      res->getInsn()->setIndirect(0, 1, dimRel);

   return res;
}

Converter::DataArray *
Converter::getArrayForFile(unsigned file, int idx)
{
   switch (file) {
   case TGSI_FILE_TEMPORARY:
      return idx == 0 ? &tData : &lData;
   case TGSI_FILE_ADDRESS:
      return &aData;
   case TGSI_FILE_OUTPUT:
      assert(prog->getType() == Program::TYPE_FRAGMENT);
      return &oData;
   default:
      assert(!"invalid/unhandled TGSI source file");
      return NULL;
   }
}

Value *
Converter::shiftAddress(Value *index)
{
   if (!index)
      return NULL;
   return mkOp2v(OP_SHL, TYPE_U32, getSSA(4, FILE_ADDRESS), index, mkImm(4));
}

void
Converter::adjustTempIndex(int arrayId, int &idx, int &idx2d) const
{
   std::map<int, int>::const_iterator it =
      code->indirectTempOffsets.find(arrayId);
   if (it == code->indirectTempOffsets.end())
      return;

   idx2d = 1;
   idx += it->second;
}

bool
Converter::isSubGroupMask(uint8_t semantic)
{
   switch (semantic) {
      case TGSI_SEMANTIC_SUBGROUP_EQ_MASK:
      case TGSI_SEMANTIC_SUBGROUP_LT_MASK:
      case TGSI_SEMANTIC_SUBGROUP_LE_MASK:
      case TGSI_SEMANTIC_SUBGROUP_GT_MASK:
      case TGSI_SEMANTIC_SUBGROUP_GE_MASK:
         return true;
      default:
         return false;
   }
}

Value *
Converter::fetchSrc(tgsi::Instruction::SrcRegister src, int c, Value *ptr)
{
   int idx2d = src.is2D() ? src.getIndex(1) : 0;
   int idx = src.getIndex(0);
   const int swz = src.getSwizzle(c);
   Instruction *ld;

   switch (src.getFile()) {
   case TGSI_FILE_IMMEDIATE:
      assert(!ptr);
      return loadImm(NULL, info->immd.data[idx * 4 + swz]);
   case TGSI_FILE_CONSTANT:
      return mkLoadv(TYPE_U32, srcToSym(src, c), shiftAddress(ptr));
   case TGSI_FILE_INPUT:
      if (prog->getType() == Program::TYPE_FRAGMENT) {
         // don't load masked inputs, won't be assigned a slot
         if (!ptr && !(info->in[idx].mask & (1 << swz)))
            return loadImm(NULL, swz == TGSI_SWIZZLE_W ? 1.0f : 0.0f);
         return interpolate(src, c, shiftAddress(ptr));
      } else
      if (prog->getType() == Program::TYPE_GEOMETRY) {
         if (!ptr && info->in[idx].sn == TGSI_SEMANTIC_PRIMID)
            return mkOp1v(OP_RDSV, TYPE_U32, getSSA(), mkSysVal(SV_PRIMITIVE_ID, 0));
         // XXX: This is going to be a problem with scalar arrays, i.e. when
         // we cannot assume that the address is given in units of vec4.
         //
         // nv50 and nvc0 need different things here, so let the lowering
         // passes decide what to do with the address
         if (ptr)
            return mkLoadv(TYPE_U32, srcToSym(src, c), ptr);
      }
      ld = mkLoad(TYPE_U32, getSSA(), srcToSym(src, c), shiftAddress(ptr));
      ld->perPatch = info->in[idx].patch;
      return ld->getDef(0);
   case TGSI_FILE_OUTPUT:
      assert(prog->getType() == Program::TYPE_TESSELLATION_CONTROL);
      ld = mkLoad(TYPE_U32, getSSA(), srcToSym(src, c), shiftAddress(ptr));
      ld->perPatch = info->out[idx].patch;
      return ld->getDef(0);
   case TGSI_FILE_SYSTEM_VALUE:
      assert(!ptr);
      if (info->sv[idx].sn == TGSI_SEMANTIC_THREAD_ID &&
          info->prop.cp.numThreads[swz] == 1)
         return loadImm(NULL, 0u);
      if (isSubGroupMask(info->sv[idx].sn) && swz > 0)
         return loadImm(NULL, 0u);
      if (info->sv[idx].sn == TGSI_SEMANTIC_SUBGROUP_SIZE)
         return loadImm(NULL, 32u);
      ld = mkOp1(OP_RDSV, TYPE_U32, getSSA(), srcToSym(src, c));
      ld->perPatch = info->sv[idx].patch;
      return ld->getDef(0);
   case TGSI_FILE_TEMPORARY: {
      int arrayid = src.getArrayId();
      if (!arrayid)
         arrayid = code->tempArrayId[idx];
      adjustTempIndex(arrayid, idx, idx2d);
   }
      /* fallthrough */
   default:
      return getArrayForFile(src.getFile(), idx2d)->load(
         sub.cur->values, idx, swz, shiftAddress(ptr));
   }
}

Value *
Converter::acquireDst(int d, int c)
{
   const tgsi::Instruction::DstRegister dst = tgsi.getDst(d);
   const unsigned f = dst.getFile();
   int idx = dst.getIndex(0);
   int idx2d = dst.is2D() ? dst.getIndex(1) : 0;

   if (dst.isMasked(c) || f == TGSI_FILE_BUFFER || f == TGSI_FILE_MEMORY ||
       f == TGSI_FILE_IMAGE)
      return NULL;

   if (dst.isIndirect(0) ||
       f == TGSI_FILE_SYSTEM_VALUE ||
       (f == TGSI_FILE_OUTPUT && prog->getType() != Program::TYPE_FRAGMENT))
      return getScratch();

   if (f == TGSI_FILE_TEMPORARY) {
      int arrayid = dst.getArrayId();
      if (!arrayid)
         arrayid = code->tempArrayId[idx];
      adjustTempIndex(arrayid, idx, idx2d);
   }

   return getArrayForFile(f, idx2d)-> acquire(sub.cur->values, idx, c);
}

void
Converter::storeDst(int d, int c, Value *val)
{
   const tgsi::Instruction::DstRegister dst = tgsi.getDst(d);

   if (tgsi.getSaturate()) {
      mkOp1(OP_SAT, dstTy, val, val);
   }

   Value *ptr = NULL;
   if (dst.isIndirect(0))
      ptr = shiftAddress(fetchSrc(dst.getIndirect(0), 0, NULL));

   if (info->io.genUserClip > 0 &&
       dst.getFile() == TGSI_FILE_OUTPUT &&
       !dst.isIndirect(0) && dst.getIndex(0) == code->clipVertexOutput) {
      mkMov(clipVtx[c], val);
      val = clipVtx[c];
   }

   storeDst(dst, c, val, ptr);
}

void
Converter::storeDst(const tgsi::Instruction::DstRegister dst, int c,
                    Value *val, Value *ptr)
{
   const unsigned f = dst.getFile();
   int idx = dst.getIndex(0);
   int idx2d = dst.is2D() ? dst.getIndex(1) : 0;

   if (f == TGSI_FILE_SYSTEM_VALUE) {
      assert(!ptr);
      mkOp2(OP_WRSV, TYPE_U32, NULL, dstToSym(dst, c), val);
   } else
   if (f == TGSI_FILE_OUTPUT && prog->getType() != Program::TYPE_FRAGMENT) {

      if (ptr || (info->out[idx].mask & (1 << c))) {
         /* Save the viewport index into a scratch register so that it can be
            exported at EMIT time */
         if (info->out[idx].sn == TGSI_SEMANTIC_VIEWPORT_INDEX &&
             prog->getType() == Program::TYPE_GEOMETRY &&
             viewport != NULL)
            mkOp1(OP_MOV, TYPE_U32, viewport, val);
         else
            mkStore(OP_EXPORT, TYPE_U32, dstToSym(dst, c), ptr, val)->perPatch =
               info->out[idx].patch;
      }
   } else
   if (f == TGSI_FILE_TEMPORARY ||
       f == TGSI_FILE_ADDRESS ||
       f == TGSI_FILE_OUTPUT) {
      if (f == TGSI_FILE_TEMPORARY) {
         int arrayid = dst.getArrayId();
         if (!arrayid)
            arrayid = code->tempArrayId[idx];
         adjustTempIndex(arrayid, idx, idx2d);
      }

      getArrayForFile(f, idx2d)->store(sub.cur->values, idx, c, ptr, val);
   } else {
      assert(!"invalid dst file");
   }
}

#define FOR_EACH_DST_ENABLED_CHANNEL(d, chan, inst) \
   for (chan = 0; chan < 4; ++chan)                 \
      if (!inst.getDst(d).isMasked(chan))

Value *
Converter::buildDot(int dim)
{
   assert(dim > 0);

   Value *src0 = fetchSrc(0, 0), *src1 = fetchSrc(1, 0);
   Value *dotp = getScratch();

   mkOp2(OP_MUL, TYPE_F32, dotp, src0, src1)
      ->dnz = info->io.mul_zero_wins;

   for (int c = 1; c < dim; ++c) {
      src0 = fetchSrc(0, c);
      src1 = fetchSrc(1, c);
      mkOp3(OP_MAD, TYPE_F32, dotp, src0, src1, dotp)
         ->dnz = info->io.mul_zero_wins;
   }
   return dotp;
}

void
Converter::insertConvergenceOps(BasicBlock *conv, BasicBlock *fork)
{
   FlowInstruction *join = new_FlowInstruction(func, OP_JOIN, NULL);
   join->fixed = 1;
   conv->insertHead(join);

   assert(!fork->joinAt);
   fork->joinAt = new_FlowInstruction(func, OP_JOINAT, conv);
   fork->insertBefore(fork->getExit(), fork->joinAt);
}

void
Converter::setTexRS(TexInstruction *tex, unsigned int& s, int R, int S)
{
   unsigned rIdx = 0, sIdx = 0;

   if (R >= 0 && tgsi.getSrc(R).getFile() != TGSI_FILE_SAMPLER) {
      // This is the bindless case. We have to get the actual value and pass
      // it in. This will be the complete handle.
      tex->tex.rIndirectSrc = s;
      tex->setSrc(s++, fetchSrc(R, 0));
      tex->setTexture(tgsi.getTexture(code, R), 0xff, 0x1f);
      tex->tex.bindless = true;
      return;
   }

   if (R >= 0)
      rIdx = tgsi.getSrc(R).getIndex(0);
   if (S >= 0)
      sIdx = tgsi.getSrc(S).getIndex(0);

   tex->setTexture(tgsi.getTexture(code, R), rIdx, sIdx);

   if (tgsi.getSrc(R).isIndirect(0)) {
      tex->tex.rIndirectSrc = s;
      tex->setSrc(s++, fetchSrc(tgsi.getSrc(R).getIndirect(0), 0, NULL));
   }
   if (S >= 0 && tgsi.getSrc(S).isIndirect(0)) {
      tex->tex.sIndirectSrc = s;
      tex->setSrc(s++, fetchSrc(tgsi.getSrc(S).getIndirect(0), 0, NULL));
   }
}

void
Converter::handleTXQ(Value *dst0[4], enum TexQuery query, int R)
{
   TexInstruction *tex = new_TexInstruction(func, OP_TXQ);
   tex->tex.query = query;
   unsigned int c, d;

   for (d = 0, c = 0; c < 4; ++c) {
      if (!dst0[c])
         continue;
      tex->tex.mask |= 1 << c;
      tex->setDef(d++, dst0[c]);
   }
   if (query == TXQ_DIMS)
      tex->setSrc((c = 0), fetchSrc(0, 0)); // mip level
   else
      tex->setSrc((c = 0), zero);

   setTexRS(tex, ++c, R, -1);

   bb->insertTail(tex);
}

void
Converter::loadProjTexCoords(Value *dst[4], Value *src[4], unsigned int mask)
{
   Value *proj = fetchSrc(0, 3);
   Instruction *insn = proj->getUniqueInsn();
   int c;

   if (insn->op == OP_PINTERP) {
      bb->insertTail(insn = cloneForward(func, insn));
      insn->op = OP_LINTERP;
      insn->setInterpolate(NV50_IR_INTERP_LINEAR | insn->getSampleMode());
      insn->setSrc(1, NULL);
      proj = insn->getDef(0);
   }
   proj = mkOp1v(OP_RCP, TYPE_F32, getSSA(), proj);

   for (c = 0; c < 4; ++c) {
      if (!(mask & (1 << c)))
         continue;
      if ((insn = src[c]->getUniqueInsn())->op != OP_PINTERP)
         continue;
      mask &= ~(1 << c);

      bb->insertTail(insn = cloneForward(func, insn));
      insn->setInterpolate(NV50_IR_INTERP_PERSPECTIVE | insn->getSampleMode());
      insn->setSrc(1, proj);
      dst[c] = insn->getDef(0);
   }
   if (!mask)
      return;

   proj = mkOp1v(OP_RCP, TYPE_F32, getSSA(), fetchSrc(0, 3));

   for (c = 0; c < 4; ++c)
      if (mask & (1 << c))
         dst[c] = mkOp2v(OP_MUL, TYPE_F32, getSSA(), src[c], proj);
}

// order of nv50 ir sources: x y z layer lod/bias shadow
// order of TGSI TEX sources: x y z layer shadow lod/bias
//  lowering will finally set the hw specific order (like array first on nvc0)
void
Converter::handleTEX(Value *dst[4], int R, int S, int L, int C, int Dx, int Dy)
{
   Value *arg[4], *src[8];
   Value *lod = NULL, *shd = NULL;
   unsigned int s, c, d;
   TexInstruction *texi = new_TexInstruction(func, tgsi.getOP());

   TexInstruction::Target tgt = tgsi.getTexture(code, R);

   for (s = 0; s < tgt.getArgCount(); ++s)
      arg[s] = src[s] = fetchSrc(0, s);

   if (tgsi.getOpcode() == TGSI_OPCODE_TEX_LZ)
      lod = loadImm(NULL, 0);
   else if (texi->op == OP_TXL || texi->op == OP_TXB)
      lod = fetchSrc(L >> 4, L & 3);

   if (C == 0x0f)
      C = 0x00 | MAX2(tgt.getArgCount(), 2); // guess DC src

   if (tgsi.getOpcode() == TGSI_OPCODE_TG4 &&
       tgt == TEX_TARGET_CUBE_ARRAY_SHADOW)
      shd = fetchSrc(1, 0);
   else if (tgt.isShadow())
      shd = fetchSrc(C >> 4, C & 3);

   if (texi->op == OP_TXD) {
      for (c = 0; c < tgt.getDim() + tgt.isCube(); ++c) {
         texi->dPdx[c].set(fetchSrc(Dx >> 4, (Dx & 3) + c));
         texi->dPdy[c].set(fetchSrc(Dy >> 4, (Dy & 3) + c));
      }
   }

   // cube textures don't care about projection value, it's divided out
   if (tgsi.getOpcode() == TGSI_OPCODE_TXP && !tgt.isCube() && !tgt.isArray()) {
      unsigned int n = tgt.getDim();
      if (shd) {
         arg[n] = shd;
         ++n;
         assert(tgt.getDim() == tgt.getArgCount());
      }
      loadProjTexCoords(src, arg, (1 << n) - 1);
      if (shd)
         shd = src[n - 1];
   }

   for (c = 0, d = 0; c < 4; ++c) {
      if (dst[c]) {
         texi->setDef(d++, dst[c]);
         texi->tex.mask |= 1 << c;
      } else {
         // NOTE: maybe hook up def too, for CSE
      }
   }
   for (s = 0; s < tgt.getArgCount(); ++s)
      texi->setSrc(s, src[s]);
   if (lod)
      texi->setSrc(s++, lod);
   if (shd)
      texi->setSrc(s++, shd);

   setTexRS(texi, s, R, S);

   if (tgsi.getOpcode() == TGSI_OPCODE_SAMPLE_C_LZ)
      texi->tex.levelZero = true;
   if (prog->getType() != Program::TYPE_FRAGMENT &&
       (tgsi.getOpcode() == TGSI_OPCODE_TEX ||
        tgsi.getOpcode() == TGSI_OPCODE_TEX2 ||
        tgsi.getOpcode() == TGSI_OPCODE_TXP))
      texi->tex.levelZero = true;
   if (tgsi.getOpcode() == TGSI_OPCODE_TG4 && !tgt.isShadow())
      texi->tex.gatherComp = tgsi.getSrc(1).getValueU32(0, info);

   texi->tex.useOffsets = tgsi.getNumTexOffsets();
   for (s = 0; s < tgsi.getNumTexOffsets(); ++s) {
      for (c = 0; c < 3; ++c) {
         texi->offset[s][c].set(fetchSrc(tgsi.getTexOffset(s), c, NULL));
         texi->offset[s][c].setInsn(texi);
      }
   }

   bb->insertTail(texi);
}

// 1st source: xyz = coordinates, w = lod/sample
// 2nd source: offset
void
Converter::handleTXF(Value *dst[4], int R, int L_M)
{
   TexInstruction *texi = new_TexInstruction(func, tgsi.getOP());
   int ms;
   unsigned int c, d, s;

   texi->tex.target = tgsi.getTexture(code, R);

   ms = texi->tex.target.isMS() ? 1 : 0;
   texi->tex.levelZero = ms; /* MS textures don't have mip-maps */

   for (c = 0, d = 0; c < 4; ++c) {
      if (dst[c]) {
         texi->setDef(d++, dst[c]);
         texi->tex.mask |= 1 << c;
      }
   }
   for (c = 0; c < (texi->tex.target.getArgCount() - ms); ++c)
      texi->setSrc(c, fetchSrc(0, c));
   if (!ms && tgsi.getOpcode() == TGSI_OPCODE_TXF_LZ)
      texi->setSrc(c++, loadImm(NULL, 0));
   else
      texi->setSrc(c++, fetchSrc(L_M >> 4, L_M & 3)); // lod or ms

   setTexRS(texi, c, R, -1);

   texi->tex.useOffsets = tgsi.getNumTexOffsets();
   for (s = 0; s < tgsi.getNumTexOffsets(); ++s) {
      for (c = 0; c < 3; ++c) {
         texi->offset[s][c].set(fetchSrc(tgsi.getTexOffset(s), c, NULL));
         texi->offset[s][c].setInsn(texi);
      }
   }

   bb->insertTail(texi);
}

void
Converter::handleFBFETCH(Value *dst[4])
{
   TexInstruction *texi = new_TexInstruction(func, OP_TXF);
   unsigned int c, d;

   texi->tex.target = TEX_TARGET_2D_MS_ARRAY;
   texi->tex.levelZero = 1;
   texi->tex.useOffsets = 0;

   for (c = 0, d = 0; c < 4; ++c) {
      if (dst[c]) {
         texi->setDef(d++, dst[c]);
         texi->tex.mask |= 1 << c;
      }
   }

   Value *x = mkOp1v(OP_RDSV, TYPE_F32, getScratch(), mkSysVal(SV_POSITION, 0));
   Value *y = mkOp1v(OP_RDSV, TYPE_F32, getScratch(), mkSysVal(SV_POSITION, 1));
   Value *z = mkOp1v(OP_RDSV, TYPE_U32, getScratch(), mkSysVal(SV_LAYER, 0));
   Value *ms = mkOp1v(OP_RDSV, TYPE_U32, getScratch(), mkSysVal(SV_SAMPLE_INDEX, 0));

   mkCvt(OP_CVT, TYPE_U32, x, TYPE_F32, x)->rnd = ROUND_Z;
   mkCvt(OP_CVT, TYPE_U32, y, TYPE_F32, y)->rnd = ROUND_Z;
   texi->setSrc(0, x);
   texi->setSrc(1, y);
   texi->setSrc(2, z);
   texi->setSrc(3, ms);

   texi->tex.r = texi->tex.s = -1;

   bb->insertTail(texi);
}

void
Converter::handleLIT(Value *dst0[4])
{
   Value *val0 = NULL;
   unsigned int mask = tgsi.getDst(0).getMask();

   if (mask & (1 << 0))
      loadImm(dst0[0], 1.0f);

   if (mask & (1 << 3))
      loadImm(dst0[3], 1.0f);

   if (mask & (3 << 1)) {
      val0 = getScratch();
      mkOp2(OP_MAX, TYPE_F32, val0, fetchSrc(0, 0), zero);
      if (mask & (1 << 1))
         mkMov(dst0[1], val0);
   }

   if (mask & (1 << 2)) {
      Value *src1 = fetchSrc(0, 1), *src3 = fetchSrc(0, 3);
      Value *val1 = getScratch(), *val3 = getScratch();

      Value *pos128 = loadImm(NULL, +127.999999f);
      Value *neg128 = loadImm(NULL, -127.999999f);

      mkOp2(OP_MAX, TYPE_F32, val1, src1, zero);
      mkOp2(OP_MAX, TYPE_F32, val3, src3, neg128);
      mkOp2(OP_MIN, TYPE_F32, val3, val3, pos128);
      mkOp2(OP_POW, TYPE_F32, val3, val1, val3);

      mkCmp(OP_SLCT, CC_GT, TYPE_F32, dst0[2], TYPE_F32, val3, zero, val0);
   }
}

/* Keep this around for now as reference when adding img support
static inline bool
isResourceSpecial(const int r)
{
   return (r == TGSI_RESOURCE_GLOBAL ||
           r == TGSI_RESOURCE_LOCAL ||
           r == TGSI_RESOURCE_PRIVATE ||
           r == TGSI_RESOURCE_INPUT);
}

static inline bool
isResourceRaw(const tgsi::Source *code, const int r)
{
   return isResourceSpecial(r) || code->resources[r].raw;
}

static inline nv50_ir::TexTarget
getResourceTarget(const tgsi::Source *code, int r)
{
   if (isResourceSpecial(r))
      return nv50_ir::TEX_TARGET_BUFFER;
   return tgsi::translateTexture(code->resources.at(r).target);
}

Symbol *
Converter::getResourceBase(const int r)
{
   Symbol *sym = NULL;

   switch (r) {
   case TGSI_RESOURCE_GLOBAL:
      sym = new_Symbol(prog, nv50_ir::FILE_MEMORY_GLOBAL,
                       info->io.auxCBSlot);
      break;
   case TGSI_RESOURCE_LOCAL:
      assert(prog->getType() == Program::TYPE_COMPUTE);
      sym = mkSymbol(nv50_ir::FILE_MEMORY_SHARED, 0, TYPE_U32,
                     info->prop.cp.sharedOffset);
      break;
   case TGSI_RESOURCE_PRIVATE:
      sym = mkSymbol(nv50_ir::FILE_MEMORY_LOCAL, 0, TYPE_U32,
                     info->bin.tlsSpace);
      break;
   case TGSI_RESOURCE_INPUT:
      assert(prog->getType() == Program::TYPE_COMPUTE);
      sym = mkSymbol(nv50_ir::FILE_SHADER_INPUT, 0, TYPE_U32,
                     info->prop.cp.inputOffset);
      break;
   default:
      sym = new_Symbol(prog,
                       nv50_ir::FILE_MEMORY_GLOBAL, code->resources.at(r).slot);
      break;
   }
   return sym;
}

void
Converter::getResourceCoords(std::vector<Value *> &coords, int r, int s)
{
   const int arg =
      TexInstruction::Target(getResourceTarget(code, r)).getArgCount();

   for (int c = 0; c < arg; ++c)
      coords.push_back(fetchSrc(s, c));

   // NOTE: TGSI_RESOURCE_GLOBAL needs FILE_GPR; this is an nv50 quirk
   if (r == TGSI_RESOURCE_LOCAL ||
       r == TGSI_RESOURCE_PRIVATE ||
       r == TGSI_RESOURCE_INPUT)
      coords[0] = mkOp1v(OP_MOV, TYPE_U32, getScratch(4, FILE_ADDRESS),
                         coords[0]);
}

static inline int
partitionLoadStore(uint8_t comp[2], uint8_t size[2], uint8_t mask)
{
   int n = 0;

   while (mask) {
      if (mask & 1) {
         size[n]++;
      } else {
         if (size[n])
            comp[n = 1] = size[0] + 1;
         else
            comp[n]++;
      }
      mask >>= 1;
   }
   if (size[0] == 3) {
      n = 1;
      size[0] = (comp[0] == 1) ? 1 : 2;
      size[1] = 3 - size[0];
      comp[1] = comp[0] + size[0];
   }
   return n + 1;
}
*/
void
Converter::getImageCoords(std::vector<Value *> &coords, int s)
{
   TexInstruction::Target t =
      TexInstruction::Target(tgsi.getImageTarget());
   const int arg = t.getDim() + (t.isArray() || t.isCube());

   for (int c = 0; c < arg; ++c)
      coords.push_back(fetchSrc(s, c));

   if (t.isMS())
      coords.push_back(fetchSrc(s, 3));
}

// For raw loads, granularity is 4 byte.
// Usage of the texture read mask on OP_SULDP is not allowed.
void
Converter::handleLOAD(Value *dst0[4])
{
   const int r = tgsi.getSrc(0).getIndex(0);
   int c;
   std::vector<Value *> off, src, ldv, def;
   Value *ind = NULL;

   if (tgsi.getSrc(0).isIndirect(0))
      ind = fetchSrc(tgsi.getSrc(0).getIndirect(0), 0, 0);

   switch (tgsi.getSrc(0).getFile()) {
   case TGSI_FILE_BUFFER:
   case TGSI_FILE_MEMORY:
      for (c = 0; c < 4; ++c) {
         if (!dst0[c])
            continue;

         Value *off;
         Symbol *sym;
         uint32_t src0_component_offset = tgsi.getSrc(0).getSwizzle(c) * 4;

         if (tgsi.getSrc(1).getFile() == TGSI_FILE_IMMEDIATE) {
            off = NULL;
            sym = makeSym(tgsi.getSrc(0).getFile(), r, -1, c,
                          tgsi.getSrc(1).getValueU32(0, info) +
                          src0_component_offset);
         } else {
            // yzw are ignored for buffers
            off = fetchSrc(1, 0);
            sym = makeSym(tgsi.getSrc(0).getFile(), r, -1, c,
                          src0_component_offset);
         }

         Instruction *ld = mkLoad(TYPE_U32, dst0[c], sym, off);
         if (tgsi.getSrc(0).getFile() == TGSI_FILE_BUFFER &&
             code->bufferAtomics[r])
            ld->cache = nv50_ir::CACHE_CG;
         else
            ld->cache = tgsi.getCacheMode();
         if (ind)
            ld->setIndirect(0, 1, ind);
      }
      break;
   default: {
      getImageCoords(off, 1);
      def.resize(4);

      for (c = 0; c < 4; ++c) {
         if (!dst0[c] || tgsi.getSrc(0).getSwizzle(c) != (TGSI_SWIZZLE_X + c))
            def[c] = getScratch();
         else
            def[c] = dst0[c];
      }

      bool bindless = tgsi.getSrc(0).getFile() != TGSI_FILE_IMAGE;
      if (bindless)
         ind = fetchSrc(0, 0);

      TexInstruction *ld =
         mkTex(OP_SULDP, tgsi.getImageTarget(), 0, 0, def, off);
      ld->tex.mask = tgsi.getDst(0).getMask();
      ld->tex.format = tgsi.getImageFormat();
      ld->cache = tgsi.getCacheMode();
      ld->tex.bindless = bindless;
      if (!bindless)
         ld->tex.r = r;
      if (ind)
         ld->setIndirectR(ind);

      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi)
         if (dst0[c] != def[c])
            mkMov(dst0[c], def[tgsi.getSrc(0).getSwizzle(c)]);
      break;
   }
   }


/* Keep this around for now as reference when adding img support
   getResourceCoords(off, r, 1);

   if (isResourceRaw(code, r)) {
      uint8_t mask = 0;
      uint8_t comp[2] = { 0, 0 };
      uint8_t size[2] = { 0, 0 };

      Symbol *base = getResourceBase(r);

      // determine the base and size of the at most 2 load ops
      for (c = 0; c < 4; ++c)
         if (!tgsi.getDst(0).isMasked(c))
            mask |= 1 << (tgsi.getSrc(0).getSwizzle(c) - TGSI_SWIZZLE_X);

      int n = partitionLoadStore(comp, size, mask);

      src = off;

      def.resize(4); // index by component, the ones we need will be non-NULL
      for (c = 0; c < 4; ++c) {
         if (dst0[c] && tgsi.getSrc(0).getSwizzle(c) == (TGSI_SWIZZLE_X + c))
            def[c] = dst0[c];
         else
         if (mask & (1 << c))
            def[c] = getScratch();
      }

      const bool useLd = isResourceSpecial(r) ||
         (info->io.nv50styleSurfaces &&
          code->resources[r].target == TGSI_TEXTURE_BUFFER);

      for (int i = 0; i < n; ++i) {
         ldv.assign(def.begin() + comp[i], def.begin() + comp[i] + size[i]);

         if (comp[i]) // adjust x component of source address if necessary
            src[0] = mkOp2v(OP_ADD, TYPE_U32, getSSA(4, off[0]->reg.file),
                            off[0], mkImm(comp[i] * 4));
         else
            src[0] = off[0];

         if (useLd) {
            Instruction *ld =
               mkLoad(typeOfSize(size[i] * 4), ldv[0], base, src[0]);
            for (size_t c = 1; c < ldv.size(); ++c)
               ld->setDef(c, ldv[c]);
         } else {
            mkTex(OP_SULDB, getResourceTarget(code, r), code->resources[r].slot,
                  0, ldv, src)->dType = typeOfSize(size[i] * 4);
         }
      }
   } else {
      def.resize(4);
      for (c = 0; c < 4; ++c) {
         if (!dst0[c] || tgsi.getSrc(0).getSwizzle(c) != (TGSI_SWIZZLE_X + c))
            def[c] = getScratch();
         else
            def[c] = dst0[c];
      }

      mkTex(OP_SULDP, getResourceTarget(code, r), code->resources[r].slot, 0,
            def, off);
   }
   FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi)
      if (dst0[c] != def[c])
         mkMov(dst0[c], def[tgsi.getSrc(0).getSwizzle(c)]);
*/
}

// For formatted stores, the write mask on OP_SUSTP can be used.
// Raw stores have to be split.
void
Converter::handleSTORE()
{
   const int r = tgsi.getDst(0).getIndex(0);
   int c;
   std::vector<Value *> off, src, dummy;
   Value *ind = NULL;

   if (tgsi.getDst(0).isIndirect(0))
      ind = fetchSrc(tgsi.getDst(0).getIndirect(0), 0, 0);

   switch (tgsi.getDst(0).getFile()) {
   case TGSI_FILE_BUFFER:
   case TGSI_FILE_MEMORY:
      for (c = 0; c < 4; ++c) {
         if (!(tgsi.getDst(0).getMask() & (1 << c)))
            continue;

         Symbol *sym;
         Value *off;
         if (tgsi.getSrc(0).getFile() == TGSI_FILE_IMMEDIATE) {
            off = NULL;
            sym = makeSym(tgsi.getDst(0).getFile(), r, -1, c,
                          tgsi.getSrc(0).getValueU32(0, info) + 4 * c);
         } else {
            // yzw are ignored for buffers
            off = fetchSrc(0, 0);
            sym = makeSym(tgsi.getDst(0).getFile(), r, -1, c, 4 * c);
         }

         Instruction *st = mkStore(OP_STORE, TYPE_U32, sym, off, fetchSrc(1, c));
         st->cache = tgsi.getCacheMode();
         if (ind)
            st->setIndirect(0, 1, ind);
      }
      break;
   default: {
      getImageCoords(off, 0);
      src = off;

      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi)
         src.push_back(fetchSrc(1, c));

      bool bindless = tgsi.getDst(0).getFile() != TGSI_FILE_IMAGE;
      if (bindless)
         ind = fetchDst(0, 0);

      TexInstruction *st =
         mkTex(OP_SUSTP, tgsi.getImageTarget(), 0, 0, dummy, src);
      st->tex.mask = tgsi.getDst(0).getMask();
      st->tex.format = tgsi.getImageFormat();
      st->cache = tgsi.getCacheMode();
      st->tex.bindless = bindless;
      if (!bindless)
         st->tex.r = r;
      if (ind)
         st->setIndirectR(ind);

      break;
   }
   }

/* Keep this around for now as reference when adding img support
   getResourceCoords(off, r, 0);
   src = off;
   const int s = src.size();

   if (isResourceRaw(code, r)) {
      uint8_t comp[2] = { 0, 0 };
      uint8_t size[2] = { 0, 0 };

      int n = partitionLoadStore(comp, size, tgsi.getDst(0).getMask());

      Symbol *base = getResourceBase(r);

      const bool useSt = isResourceSpecial(r) ||
         (info->io.nv50styleSurfaces &&
          code->resources[r].target == TGSI_TEXTURE_BUFFER);

      for (int i = 0; i < n; ++i) {
         if (comp[i]) // adjust x component of source address if necessary
            src[0] = mkOp2v(OP_ADD, TYPE_U32, getSSA(4, off[0]->reg.file),
                            off[0], mkImm(comp[i] * 4));
         else
            src[0] = off[0];

         const DataType stTy = typeOfSize(size[i] * 4);

         if (useSt) {
            Instruction *st =
               mkStore(OP_STORE, stTy, base, NULL, fetchSrc(1, comp[i]));
            for (c = 1; c < size[i]; ++c)
               st->setSrc(1 + c, fetchSrc(1, comp[i] + c));
            st->setIndirect(0, 0, src[0]);
         } else {
            // attach values to be stored
            src.resize(s + size[i]);
            for (c = 0; c < size[i]; ++c)
               src[s + c] = fetchSrc(1, comp[i] + c);
            mkTex(OP_SUSTB, getResourceTarget(code, r), code->resources[r].slot,
                  0, dummy, src)->setType(stTy);
         }
      }
   } else {
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi)
         src.push_back(fetchSrc(1, c));

      mkTex(OP_SUSTP, getResourceTarget(code, r), code->resources[r].slot, 0,
            dummy, src)->tex.mask = tgsi.getDst(0).getMask();
   }
*/
}

// XXX: These only work on resources with the single-component u32/s32 formats.
// Therefore the result is replicated. This might not be intended by TGSI, but
// operating on more than 1 component would produce undefined results because
// they do not exist.
void
Converter::handleATOM(Value *dst0[4], DataType ty, uint16_t subOp)
{
   const int r = tgsi.getSrc(0).getIndex(0);
   std::vector<Value *> srcv;
   std::vector<Value *> defv;
   LValue *dst = getScratch();
   Value *ind = NULL;

   if (tgsi.getSrc(0).isIndirect(0))
      ind = fetchSrc(tgsi.getSrc(0).getIndirect(0), 0, 0);

   switch (tgsi.getSrc(0).getFile()) {
   case TGSI_FILE_BUFFER:
   case TGSI_FILE_MEMORY:
      for (int c = 0; c < 4; ++c) {
         if (!dst0[c])
            continue;

         Instruction *insn;
         Value *off = fetchSrc(1, c);
         Value *sym;
         if (tgsi.getSrc(1).getFile() == TGSI_FILE_IMMEDIATE)
            sym = makeSym(tgsi.getSrc(0).getFile(), r, -1, c,
                          tgsi.getSrc(1).getValueU32(c, info));
         else
            sym = makeSym(tgsi.getSrc(0).getFile(), r, -1, c, 0);
         if (subOp == NV50_IR_SUBOP_ATOM_CAS)
            insn = mkOp3(OP_ATOM, ty, dst, sym, fetchSrc(2, c), fetchSrc(3, c));
         else
            insn = mkOp2(OP_ATOM, ty, dst, sym, fetchSrc(2, c));
         if (tgsi.getSrc(1).getFile() != TGSI_FILE_IMMEDIATE)
            insn->setIndirect(0, 0, off);
         if (ind)
            insn->setIndirect(0, 1, ind);
         insn->subOp = subOp;
      }
      for (int c = 0; c < 4; ++c)
         if (dst0[c])
            dst0[c] = dst; // not equal to rDst so handleInstruction will do mkMov
      break;
   default: {
      getImageCoords(srcv, 1);
      defv.push_back(dst);
      srcv.push_back(fetchSrc(2, 0));

      if (subOp == NV50_IR_SUBOP_ATOM_CAS)
         srcv.push_back(fetchSrc(3, 0));

      bool bindless = tgsi.getSrc(0).getFile() != TGSI_FILE_IMAGE;
      if (bindless)
         ind = fetchSrc(0, 0);

      TexInstruction *tex = mkTex(OP_SUREDP, tgsi.getImageTarget(),
                                  0, 0, defv, srcv);
      tex->subOp = subOp;
      tex->tex.mask = 1;
      tex->tex.format = tgsi.getImageFormat();
      tex->setType(ty);
      tex->tex.bindless = bindless;
      if (!bindless)
         tex->tex.r = r;
      if (ind)
         tex->setIndirectR(ind);

      for (int c = 0; c < 4; ++c)
         if (dst0[c])
            dst0[c] = dst; // not equal to rDst so handleInstruction will do mkMov
      break;
   }
   }

/* Keep this around for now as reference when adding img support
   getResourceCoords(srcv, r, 1);

   if (isResourceSpecial(r)) {
      assert(r != TGSI_RESOURCE_INPUT);
      Instruction *insn;
      insn = mkOp2(OP_ATOM, ty, dst, getResourceBase(r), fetchSrc(2, 0));
      insn->subOp = subOp;
      if (subOp == NV50_IR_SUBOP_ATOM_CAS)
         insn->setSrc(2, fetchSrc(3, 0));
      insn->setIndirect(0, 0, srcv.at(0));
   } else {
      operation op = isResourceRaw(code, r) ? OP_SUREDB : OP_SUREDP;
      TexTarget targ = getResourceTarget(code, r);
      int idx = code->resources[r].slot;
      defv.push_back(dst);
      srcv.push_back(fetchSrc(2, 0));
      if (subOp == NV50_IR_SUBOP_ATOM_CAS)
         srcv.push_back(fetchSrc(3, 0));
      TexInstruction *tex = mkTex(op, targ, idx, 0, defv, srcv);
      tex->subOp = subOp;
      tex->tex.mask = 1;
      tex->setType(ty);
   }

   for (int c = 0; c < 4; ++c)
      if (dst0[c])
         dst0[c] = dst; // not equal to rDst so handleInstruction will do mkMov
*/
}

void
Converter::handleINTERP(Value *dst[4])
{
   // Check whether the input is linear. All other attributes ignored.
   Instruction *insn;
   Value *offset = NULL, *ptr = NULL, *w = NULL;
   Symbol *sym[4] = { NULL };
   bool linear;
   operation op = OP_NOP;
   int c, mode = 0;

   tgsi::Instruction::SrcRegister src = tgsi.getSrc(0);

   // In some odd cases, in large part due to varying packing, the source
   // might not actually be an input. This is illegal TGSI, but it's easier to
   // account for it here than it is to fix it where the TGSI is being
   // generated. In that case, it's going to be a straight up mov (or sequence
   // of mov's) from the input in question. We follow the mov chain to see
   // which input we need to use.
   if (src.getFile() != TGSI_FILE_INPUT) {
      if (src.isIndirect(0)) {
         ERROR("Ignoring indirect input interpolation\n");
         return;
      }
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi) {
         Value *val = fetchSrc(0, c);
         assert(val->defs.size() == 1);
         insn = val->getInsn();
         while (insn->op == OP_MOV) {
            assert(insn->getSrc(0)->defs.size() == 1);
            insn = insn->getSrc(0)->getInsn();
            if (!insn) {
               ERROR("Miscompiling shader due to unhandled INTERP\n");
               return;
            }
         }
         if (insn->op != OP_LINTERP && insn->op != OP_PINTERP) {
            ERROR("Trying to interpolate non-input, this is not allowed.\n");
            return;
         }
         sym[c] = insn->getSrc(0)->asSym();
         assert(sym[c]);
         op = insn->op;
         mode = insn->ipa;
         ptr = insn->getIndirect(0, 0);
      }
   } else {
      if (src.isIndirect(0))
         ptr = shiftAddress(fetchSrc(src.getIndirect(0), 0, NULL));

      // We can assume that the fixed index will point to an input of the same
      // interpolation type in case of an indirect.
      // TODO: Make use of ArrayID.
      linear = info->in[src.getIndex(0)].linear;
      if (linear) {
         op = OP_LINTERP;
         mode = NV50_IR_INTERP_LINEAR;
      } else {
         op = OP_PINTERP;
         mode = NV50_IR_INTERP_PERSPECTIVE;
      }
   }

   switch (tgsi.getOpcode()) {
   case TGSI_OPCODE_INTERP_CENTROID:
      mode |= NV50_IR_INTERP_CENTROID;
      break;
   case TGSI_OPCODE_INTERP_SAMPLE:
      insn = mkOp1(OP_PIXLD, TYPE_U32, (offset = getScratch()), fetchSrc(1, 0));
      insn->subOp = NV50_IR_SUBOP_PIXLD_OFFSET;
      mode |= NV50_IR_INTERP_OFFSET;
      break;
   case TGSI_OPCODE_INTERP_OFFSET: {
      // The input in src1.xy is float, but we need a single 32-bit value
      // where the upper and lower 16 bits are encoded in S0.12 format. We need
      // to clamp the input coordinates to (-0.5, 0.4375), multiply by 4096,
      // and then convert to s32.
      Value *offs[2];
      for (c = 0; c < 2; c++) {
         offs[c] = getScratch();
         mkOp2(OP_MIN, TYPE_F32, offs[c], fetchSrc(1, c), loadImm(NULL, 0.4375f));
         mkOp2(OP_MAX, TYPE_F32, offs[c], offs[c], loadImm(NULL, -0.5f));
         mkOp2(OP_MUL, TYPE_F32, offs[c], offs[c], loadImm(NULL, 4096.0f));
         mkCvt(OP_CVT, TYPE_S32, offs[c], TYPE_F32, offs[c]);
      }
      offset = mkOp3v(OP_INSBF, TYPE_U32, getScratch(),
                      offs[1], mkImm(0x1010), offs[0]);
      mode |= NV50_IR_INTERP_OFFSET;
      break;
   }
   }

   if (op == OP_PINTERP) {
      if (offset) {
         w = mkOp2v(OP_RDSV, TYPE_F32, getSSA(), mkSysVal(SV_POSITION, 3), offset);
         mkOp1(OP_RCP, TYPE_F32, w, w);
      } else {
         w = fragCoord[3];
      }
   }


   FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi) {
      insn = mkOp1(op, TYPE_F32, dst[c], sym[c] ? sym[c] : srcToSym(src, c));
      if (op == OP_PINTERP)
         insn->setSrc(1, w);
      if (offset)
         insn->setSrc(op == OP_PINTERP ? 2 : 1, offset);
      if (ptr)
         insn->setIndirect(0, 0, ptr);

      insn->setInterpolate(mode);
   }
}

bool
Converter::isEndOfSubroutine(uint ip)
{
   assert(ip < code->scan.num_instructions);
   tgsi::Instruction insn(&code->insns[ip]);
   return (insn.getOpcode() == TGSI_OPCODE_END ||
           insn.getOpcode() == TGSI_OPCODE_ENDSUB ||
           // does END occur at end of main or the very end ?
           insn.getOpcode() == TGSI_OPCODE_BGNSUB);
}

bool
Converter::handleInstruction(const struct tgsi_full_instruction *insn)
{
   Instruction *geni;

   Value *dst0[4], *rDst0[4];
   Value *src0, *src1, *src2, *src3;
   Value *val0, *val1;
   int c;

   tgsi = tgsi::Instruction(insn);

   bool useScratchDst = tgsi.checkDstSrcAliasing();

   operation op = tgsi.getOP();
   dstTy = tgsi.inferDstType();
   srcTy = tgsi.inferSrcType();

   unsigned int mask = tgsi.dstCount() ? tgsi.getDst(0).getMask() : 0;

   if (tgsi.dstCount() && tgsi.getOpcode() != TGSI_OPCODE_STORE) {
      for (c = 0; c < 4; ++c) {
         rDst0[c] = acquireDst(0, c);
         dst0[c] = (useScratchDst && rDst0[c]) ? getScratch() : rDst0[c];
      }
   }

   switch (tgsi.getOpcode()) {
   case TGSI_OPCODE_ADD:
   case TGSI_OPCODE_UADD:
   case TGSI_OPCODE_AND:
   case TGSI_OPCODE_DIV:
   case TGSI_OPCODE_IDIV:
   case TGSI_OPCODE_UDIV:
   case TGSI_OPCODE_MAX:
   case TGSI_OPCODE_MIN:
   case TGSI_OPCODE_IMAX:
   case TGSI_OPCODE_IMIN:
   case TGSI_OPCODE_UMAX:
   case TGSI_OPCODE_UMIN:
   case TGSI_OPCODE_MOD:
   case TGSI_OPCODE_UMOD:
   case TGSI_OPCODE_MUL:
   case TGSI_OPCODE_UMUL:
   case TGSI_OPCODE_IMUL_HI:
   case TGSI_OPCODE_UMUL_HI:
   case TGSI_OPCODE_OR:
   case TGSI_OPCODE_SHL:
   case TGSI_OPCODE_ISHR:
   case TGSI_OPCODE_USHR:
   case TGSI_OPCODE_XOR:
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi) {
         src0 = fetchSrc(0, c);
         src1 = fetchSrc(1, c);
         geni = mkOp2(op, dstTy, dst0[c], src0, src1);
         geni->subOp = tgsi::opcodeToSubOp(tgsi.getOpcode());
         if (op == OP_MUL && dstTy == TYPE_F32)
            geni->dnz = info->io.mul_zero_wins;
         geni->precise = insn->Instruction.Precise;
      }
      break;
   case TGSI_OPCODE_MAD:
   case TGSI_OPCODE_UMAD:
   case TGSI_OPCODE_FMA:
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi) {
         src0 = fetchSrc(0, c);
         src1 = fetchSrc(1, c);
         src2 = fetchSrc(2, c);
         geni = mkOp3(op, dstTy, dst0[c], src0, src1, src2);
         if (dstTy == TYPE_F32)
            geni->dnz = info->io.mul_zero_wins;
         geni->precise = insn->Instruction.Precise;
      }
      break;
   case TGSI_OPCODE_MOV:
   case TGSI_OPCODE_CEIL:
   case TGSI_OPCODE_FLR:
   case TGSI_OPCODE_TRUNC:
   case TGSI_OPCODE_RCP:
   case TGSI_OPCODE_SQRT:
   case TGSI_OPCODE_IABS:
   case TGSI_OPCODE_INEG:
   case TGSI_OPCODE_NOT:
   case TGSI_OPCODE_DDX:
   case TGSI_OPCODE_DDY:
   case TGSI_OPCODE_DDX_FINE:
   case TGSI_OPCODE_DDY_FINE:
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi)
         mkOp1(op, dstTy, dst0[c], fetchSrc(0, c));
      break;
   case TGSI_OPCODE_RSQ:
      src0 = fetchSrc(0, 0);
      val0 = getScratch();
      mkOp1(OP_ABS, TYPE_F32, val0, src0);
      mkOp1(OP_RSQ, TYPE_F32, val0, val0);
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi)
         mkMov(dst0[c], val0);
      break;
   case TGSI_OPCODE_ARL:
   case TGSI_OPCODE_ARR:
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi) {
         const RoundMode rnd =
            tgsi.getOpcode() == TGSI_OPCODE_ARR ? ROUND_N : ROUND_M;
         src0 = fetchSrc(0, c);
         mkCvt(OP_CVT, TYPE_S32, dst0[c], TYPE_F32, src0)->rnd = rnd;
      }
      break;
   case TGSI_OPCODE_UARL:
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi)
         mkOp1(OP_MOV, TYPE_U32, dst0[c], fetchSrc(0, c));
      break;
   case TGSI_OPCODE_POW:
      val0 = mkOp2v(op, TYPE_F32, getScratch(), fetchSrc(0, 0), fetchSrc(1, 0));
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi)
         mkOp1(OP_MOV, TYPE_F32, dst0[c], val0);
      break;
   case TGSI_OPCODE_EX2:
   case TGSI_OPCODE_LG2:
      val0 = mkOp1(op, TYPE_F32, getScratch(), fetchSrc(0, 0))->getDef(0);
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi)
         mkOp1(OP_MOV, TYPE_F32, dst0[c], val0);
      break;
   case TGSI_OPCODE_COS:
   case TGSI_OPCODE_SIN:
      val0 = getScratch();
      if (mask & 7) {
         mkOp1(OP_PRESIN, TYPE_F32, val0, fetchSrc(0, 0));
         mkOp1(op, TYPE_F32, val0, val0);
         for (c = 0; c < 3; ++c)
            if (dst0[c])
               mkMov(dst0[c], val0);
      }
      if (dst0[3]) {
         mkOp1(OP_PRESIN, TYPE_F32, val0, fetchSrc(0, 3));
         mkOp1(op, TYPE_F32, dst0[3], val0);
      }
      break;
   case TGSI_OPCODE_EXP:
      src0 = fetchSrc(0, 0);
      val0 = mkOp1v(OP_FLOOR, TYPE_F32, getSSA(), src0);
      if (dst0[1])
         mkOp2(OP_SUB, TYPE_F32, dst0[1], src0, val0);
      if (dst0[0])
         mkOp1(OP_EX2, TYPE_F32, dst0[0], val0);
      if (dst0[2])
         mkOp1(OP_EX2, TYPE_F32, dst0[2], src0);
      if (dst0[3])
         loadImm(dst0[3], 1.0f);
      break;
   case TGSI_OPCODE_LOG:
      src0 = mkOp1v(OP_ABS, TYPE_F32, getSSA(), fetchSrc(0, 0));
      val0 = mkOp1v(OP_LG2, TYPE_F32, dst0[2] ? dst0[2] : getSSA(), src0);
      if (dst0[0] || dst0[1])
         val1 = mkOp1v(OP_FLOOR, TYPE_F32, dst0[0] ? dst0[0] : getSSA(), val0);
      if (dst0[1]) {
         mkOp1(OP_EX2, TYPE_F32, dst0[1], val1);
         mkOp1(OP_RCP, TYPE_F32, dst0[1], dst0[1]);
         mkOp2(OP_MUL, TYPE_F32, dst0[1], dst0[1], src0)
            ->dnz = info->io.mul_zero_wins;
      }
      if (dst0[3])
         loadImm(dst0[3], 1.0f);
      break;
   case TGSI_OPCODE_DP2:
      val0 = buildDot(2);
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi)
         mkMov(dst0[c], val0);
      break;
   case TGSI_OPCODE_DP3:
      val0 = buildDot(3);
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi)
         mkMov(dst0[c], val0);
      break;
   case TGSI_OPCODE_DP4:
      val0 = buildDot(4);
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi)
         mkMov(dst0[c], val0);
      break;
   case TGSI_OPCODE_DST:
      if (dst0[0])
         loadImm(dst0[0], 1.0f);
      if (dst0[1]) {
         src0 = fetchSrc(0, 1);
         src1 = fetchSrc(1, 1);
         mkOp2(OP_MUL, TYPE_F32, dst0[1], src0, src1)
            ->dnz = info->io.mul_zero_wins;
      }
      if (dst0[2])
         mkMov(dst0[2], fetchSrc(0, 2));
      if (dst0[3])
         mkMov(dst0[3], fetchSrc(1, 3));
      break;
   case TGSI_OPCODE_LRP:
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi) {
         src0 = fetchSrc(0, c);
         src1 = fetchSrc(1, c);
         src2 = fetchSrc(2, c);
         mkOp3(OP_MAD, TYPE_F32, dst0[c],
               mkOp2v(OP_SUB, TYPE_F32, getSSA(), src1, src2), src0, src2)
            ->dnz = info->io.mul_zero_wins;
      }
      break;
   case TGSI_OPCODE_LIT:
      handleLIT(dst0);
      break;
   case TGSI_OPCODE_ISSG:
   case TGSI_OPCODE_SSG:
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi) {
         src0 = fetchSrc(0, c);
         val0 = getScratch();
         val1 = getScratch();
         mkCmp(OP_SET, CC_GT, srcTy, val0, srcTy, src0, zero);
         mkCmp(OP_SET, CC_LT, srcTy, val1, srcTy, src0, zero);
         if (srcTy == TYPE_F32)
            mkOp2(OP_SUB, TYPE_F32, dst0[c], val0, val1);
         else
            mkOp2(OP_SUB, TYPE_S32, dst0[c], val1, val0);
      }
      break;
   case TGSI_OPCODE_UCMP:
      srcTy = TYPE_U32;
      /* fallthrough */
   case TGSI_OPCODE_CMP:
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi) {
         src0 = fetchSrc(0, c);
         src1 = fetchSrc(1, c);
         src2 = fetchSrc(2, c);
         if (src1 == src2)
            mkMov(dst0[c], src1);
         else
            mkCmp(OP_SLCT, (srcTy == TYPE_F32) ? CC_LT : CC_NE,
                  srcTy, dst0[c], srcTy, src1, src2, src0);
      }
      break;
   case TGSI_OPCODE_FRC:
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi) {
         src0 = fetchSrc(0, c);
         val0 = getScratch();
         mkOp1(OP_FLOOR, TYPE_F32, val0, src0);
         mkOp2(OP_SUB, TYPE_F32, dst0[c], src0, val0);
      }
      break;
   case TGSI_OPCODE_ROUND:
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi)
         mkCvt(OP_CVT, TYPE_F32, dst0[c], TYPE_F32, fetchSrc(0, c))
         ->rnd = ROUND_NI;
      break;
   case TGSI_OPCODE_SLT:
   case TGSI_OPCODE_SGE:
   case TGSI_OPCODE_SEQ:
   case TGSI_OPCODE_SGT:
   case TGSI_OPCODE_SLE:
   case TGSI_OPCODE_SNE:
   case TGSI_OPCODE_FSEQ:
   case TGSI_OPCODE_FSGE:
   case TGSI_OPCODE_FSLT:
   case TGSI_OPCODE_FSNE:
   case TGSI_OPCODE_ISGE:
   case TGSI_OPCODE_ISLT:
   case TGSI_OPCODE_USEQ:
   case TGSI_OPCODE_USGE:
   case TGSI_OPCODE_USLT:
   case TGSI_OPCODE_USNE:
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi) {
         src0 = fetchSrc(0, c);
         src1 = fetchSrc(1, c);
         mkCmp(op, tgsi.getSetCond(), dstTy, dst0[c], srcTy, src0, src1);
      }
      break;
   case TGSI_OPCODE_VOTE_ALL:
   case TGSI_OPCODE_VOTE_ANY:
   case TGSI_OPCODE_VOTE_EQ:
      val0 = new_LValue(func, FILE_PREDICATE);
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi) {
         mkCmp(OP_SET, CC_NE, TYPE_U32, val0, TYPE_U32, fetchSrc(0, c), zero);
         mkOp1(op, dstTy, val0, val0)
            ->subOp = tgsi::opcodeToSubOp(tgsi.getOpcode());
         mkCvt(OP_CVT, TYPE_U32, dst0[c], TYPE_U8, val0);
      }
      break;
   case TGSI_OPCODE_BALLOT:
      if (!tgsi.getDst(0).isMasked(0)) {
         val0 = new_LValue(func, FILE_PREDICATE);
         mkCmp(OP_SET, CC_NE, TYPE_U32, val0, TYPE_U32, fetchSrc(0, 0), zero);
         mkOp1(op, TYPE_U32, dst0[0], val0)->subOp = NV50_IR_SUBOP_VOTE_ANY;
      }
      if (!tgsi.getDst(0).isMasked(1))
         mkMov(dst0[1], zero, TYPE_U32);
      break;
   case TGSI_OPCODE_READ_FIRST:
      // ReadFirstInvocationARB(src) is implemented as
      // ReadInvocationARB(src, findLSB(ballot(true)))
      val0 = getScratch();
      mkOp1(OP_VOTE, TYPE_U32, val0, mkImm(1))->subOp = NV50_IR_SUBOP_VOTE_ANY;
      mkOp2(OP_EXTBF, TYPE_U32, val0, val0, mkImm(0x2000))
         ->subOp = NV50_IR_SUBOP_EXTBF_REV;
      mkOp1(OP_BFIND, TYPE_U32, val0, val0)->subOp = NV50_IR_SUBOP_BFIND_SAMT;
      src1 = val0;
      /* fallthrough */
   case TGSI_OPCODE_READ_INVOC:
      if (tgsi.getOpcode() == TGSI_OPCODE_READ_INVOC)
         src1 = fetchSrc(1, 0);
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi) {
         geni = mkOp3(op, dstTy, dst0[c], fetchSrc(0, c), src1, mkImm(0x1f));
         geni->subOp = NV50_IR_SUBOP_SHFL_IDX;
      }
      break;
   case TGSI_OPCODE_CLOCK:
      // Stick the 32-bit clock into the high dword of the logical result.
      if (!tgsi.getDst(0).isMasked(0))
         mkOp1(OP_MOV, TYPE_U32, dst0[0], zero);
      if (!tgsi.getDst(0).isMasked(1))
         mkOp1(OP_RDSV, TYPE_U32, dst0[1], mkSysVal(SV_CLOCK, 0))->fixed = 1;
      break;
   case TGSI_OPCODE_KILL_IF:
      val0 = new_LValue(func, FILE_PREDICATE);
      mask = 0;
      for (c = 0; c < 4; ++c) {
         const int s = tgsi.getSrc(0).getSwizzle(c);
         if (mask & (1 << s))
            continue;
         mask |= 1 << s;
         mkCmp(OP_SET, CC_LT, TYPE_F32, val0, TYPE_F32, fetchSrc(0, c), zero);
         mkOp(OP_DISCARD, TYPE_NONE, NULL)->setPredicate(CC_P, val0);
      }
      break;
   case TGSI_OPCODE_KILL:
      mkOp(OP_DISCARD, TYPE_NONE, NULL);
      break;
   case TGSI_OPCODE_TEX:
   case TGSI_OPCODE_TEX_LZ:
   case TGSI_OPCODE_TXB:
   case TGSI_OPCODE_TXL:
   case TGSI_OPCODE_TXP:
   case TGSI_OPCODE_LODQ:
      //              R  S     L     C    Dx    Dy
      handleTEX(dst0, 1, 1, 0x03, 0x0f, 0x00, 0x00);
      break;
   case TGSI_OPCODE_TXD:
      handleTEX(dst0, 3, 3, 0x03, 0x0f, 0x10, 0x20);
      break;
   case TGSI_OPCODE_TG4:
      handleTEX(dst0, 2, 2, 0x03, 0x0f, 0x00, 0x00);
      break;
   case TGSI_OPCODE_TEX2:
      handleTEX(dst0, 2, 2, 0x03, 0x10, 0x00, 0x00);
      break;
   case TGSI_OPCODE_TXB2:
   case TGSI_OPCODE_TXL2:
      handleTEX(dst0, 2, 2, 0x10, 0x0f, 0x00, 0x00);
      break;
   case TGSI_OPCODE_SAMPLE:
   case TGSI_OPCODE_SAMPLE_B:
   case TGSI_OPCODE_SAMPLE_D:
   case TGSI_OPCODE_SAMPLE_L:
   case TGSI_OPCODE_SAMPLE_C:
   case TGSI_OPCODE_SAMPLE_C_LZ:
      handleTEX(dst0, 1, 2, 0x30, 0x30, 0x30, 0x40);
      break;
   case TGSI_OPCODE_TXF_LZ:
   case TGSI_OPCODE_TXF:
      handleTXF(dst0, 1, 0x03);
      break;
   case TGSI_OPCODE_SAMPLE_I:
      handleTXF(dst0, 1, 0x03);
      break;
   case TGSI_OPCODE_SAMPLE_I_MS:
      handleTXF(dst0, 1, 0x20);
      break;
   case TGSI_OPCODE_TXQ:
   case TGSI_OPCODE_SVIEWINFO:
      handleTXQ(dst0, TXQ_DIMS, 1);
      break;
   case TGSI_OPCODE_TXQS:
      // The TXQ_TYPE query returns samples in its 3rd arg, but we need it to
      // be in .x
      dst0[1] = dst0[2] = dst0[3] = NULL;
      std::swap(dst0[0], dst0[2]);
      handleTXQ(dst0, TXQ_TYPE, 0);
      std::swap(dst0[0], dst0[2]);
      break;
   case TGSI_OPCODE_FBFETCH:
      handleFBFETCH(dst0);
      break;
   case TGSI_OPCODE_F2I:
   case TGSI_OPCODE_F2U:
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi)
         mkCvt(OP_CVT, dstTy, dst0[c], srcTy, fetchSrc(0, c))->rnd = ROUND_Z;
      break;
   case TGSI_OPCODE_I2F:
   case TGSI_OPCODE_U2F:
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi)
         mkCvt(OP_CVT, dstTy, dst0[c], srcTy, fetchSrc(0, c));
      break;
   case TGSI_OPCODE_PK2H:
      val0 = getScratch();
      val1 = getScratch();
      mkCvt(OP_CVT, TYPE_F16, val0, TYPE_F32, fetchSrc(0, 0));
      mkCvt(OP_CVT, TYPE_F16, val1, TYPE_F32, fetchSrc(0, 1));
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi)
         mkOp3(OP_INSBF, TYPE_U32, dst0[c], val1, mkImm(0x1010), val0);
      break;
   case TGSI_OPCODE_UP2H:
      src0 = fetchSrc(0, 0);
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi) {
         geni = mkCvt(OP_CVT, TYPE_F32, dst0[c], TYPE_F16, src0);
         geni->subOp = c & 1;
      }
      break;
   case TGSI_OPCODE_EMIT:
      /* export the saved viewport index */
      if (viewport != NULL) {
         Symbol *vpSym = mkSymbol(FILE_SHADER_OUTPUT, 0, TYPE_U32,
                                  info->out[info->io.viewportId].slot[0] * 4);
         mkStore(OP_EXPORT, TYPE_U32, vpSym, NULL, viewport);
      }
      /* handle user clip planes for each emitted vertex */
      if (info->io.genUserClip > 0)
         handleUserClipPlanes();
      /* fallthrough */
   case TGSI_OPCODE_ENDPRIM:
   {
      // get vertex stream (must be immediate)
      unsigned int stream = tgsi.getSrc(0).getValueU32(0, info);
      if (stream && op == OP_RESTART)
         break;
      if (info->prop.gp.maxVertices == 0)
         break;
      src0 = mkImm(stream);
      mkOp1(op, TYPE_U32, NULL, src0)->fixed = 1;
      break;
   }
   case TGSI_OPCODE_IF:
   case TGSI_OPCODE_UIF:
   {
      BasicBlock *ifBB = new BasicBlock(func);

      bb->cfg.attach(&ifBB->cfg, Graph::Edge::TREE);
      condBBs.push(bb);
      joinBBs.push(bb);

      mkFlow(OP_BRA, NULL, CC_NOT_P, fetchSrc(0, 0))->setType(srcTy);

      setPosition(ifBB, true);
   }
      break;
   case TGSI_OPCODE_ELSE:
   {
      BasicBlock *elseBB = new BasicBlock(func);
      BasicBlock *forkBB = reinterpret_cast<BasicBlock *>(condBBs.pop().u.p);

      forkBB->cfg.attach(&elseBB->cfg, Graph::Edge::TREE);
      condBBs.push(bb);

      forkBB->getExit()->asFlow()->target.bb = elseBB;
      if (!bb->isTerminated())
         mkFlow(OP_BRA, NULL, CC_ALWAYS, NULL);

      setPosition(elseBB, true);
   }
      break;
   case TGSI_OPCODE_ENDIF:
   {
      BasicBlock *convBB = new BasicBlock(func);
      BasicBlock *prevBB = reinterpret_cast<BasicBlock *>(condBBs.pop().u.p);
      BasicBlock *forkBB = reinterpret_cast<BasicBlock *>(joinBBs.pop().u.p);

      if (!bb->isTerminated()) {
         // we only want join if none of the clauses ended with CONT/BREAK/RET
         if (prevBB->getExit()->op == OP_BRA && joinBBs.getSize() < 6)
            insertConvergenceOps(convBB, forkBB);
         mkFlow(OP_BRA, convBB, CC_ALWAYS, NULL);
         bb->cfg.attach(&convBB->cfg, Graph::Edge::FORWARD);
      }

      if (prevBB->getExit()->op == OP_BRA) {
         prevBB->cfg.attach(&convBB->cfg, Graph::Edge::FORWARD);
         prevBB->getExit()->asFlow()->target.bb = convBB;
      }
      setPosition(convBB, true);
   }
      break;
   case TGSI_OPCODE_BGNLOOP:
   {
      BasicBlock *lbgnBB = new BasicBlock(func);
      BasicBlock *lbrkBB = new BasicBlock(func);

      loopBBs.push(lbgnBB);
      breakBBs.push(lbrkBB);
      if (loopBBs.getSize() > func->loopNestingBound)
         func->loopNestingBound++;

      mkFlow(OP_PREBREAK, lbrkBB, CC_ALWAYS, NULL);

      bb->cfg.attach(&lbgnBB->cfg, Graph::Edge::TREE);
      setPosition(lbgnBB, true);
      mkFlow(OP_PRECONT, lbgnBB, CC_ALWAYS, NULL);
   }
      break;
   case TGSI_OPCODE_ENDLOOP:
   {
      BasicBlock *loopBB = reinterpret_cast<BasicBlock *>(loopBBs.pop().u.p);

      if (!bb->isTerminated()) {
         mkFlow(OP_CONT, loopBB, CC_ALWAYS, NULL);
         bb->cfg.attach(&loopBB->cfg, Graph::Edge::BACK);
      }
      setPosition(reinterpret_cast<BasicBlock *>(breakBBs.pop().u.p), true);

      // If the loop never breaks (e.g. only has RET's inside), then there
      // will be no way to get to the break bb. However BGNLOOP will have
      // already made a PREBREAK to it, so it must be in the CFG.
      if (getBB()->cfg.incidentCount() == 0)
         loopBB->cfg.attach(&getBB()->cfg, Graph::Edge::TREE);
   }
      break;
   case TGSI_OPCODE_BRK:
   {
      if (bb->isTerminated())
         break;
      BasicBlock *brkBB = reinterpret_cast<BasicBlock *>(breakBBs.peek().u.p);
      mkFlow(OP_BREAK, brkBB, CC_ALWAYS, NULL);
      bb->cfg.attach(&brkBB->cfg, Graph::Edge::CROSS);
   }
      break;
   case TGSI_OPCODE_CONT:
   {
      if (bb->isTerminated())
         break;
      BasicBlock *contBB = reinterpret_cast<BasicBlock *>(loopBBs.peek().u.p);
      mkFlow(OP_CONT, contBB, CC_ALWAYS, NULL);
      contBB->explicitCont = true;
      bb->cfg.attach(&contBB->cfg, Graph::Edge::BACK);
   }
      break;
   case TGSI_OPCODE_BGNSUB:
   {
      Subroutine *s = getSubroutine(ip);
      BasicBlock *entry = new BasicBlock(s->f);
      BasicBlock *leave = new BasicBlock(s->f);

      // multiple entrypoints possible, keep the graph connected
      if (prog->getType() == Program::TYPE_COMPUTE)
         prog->main->call.attach(&s->f->call, Graph::Edge::TREE);

      sub.cur = s;
      s->f->setEntry(entry);
      s->f->setExit(leave);
      setPosition(entry, true);
      return true;
   }
   case TGSI_OPCODE_ENDSUB:
   {
      sub.cur = getSubroutine(prog->main);
      setPosition(BasicBlock::get(sub.cur->f->cfg.getRoot()), true);
      return true;
   }
   case TGSI_OPCODE_CAL:
   {
      Subroutine *s = getSubroutine(tgsi.getLabel());
      mkFlow(OP_CALL, s->f, CC_ALWAYS, NULL);
      func->call.attach(&s->f->call, Graph::Edge::TREE);
      return true;
   }
   case TGSI_OPCODE_RET:
   {
      if (bb->isTerminated())
         return true;
      BasicBlock *leave = BasicBlock::get(func->cfgExit);

      if (!isEndOfSubroutine(ip + 1)) {
         // insert a PRERET at the entry if this is an early return
         // (only needed for sharing code in the epilogue)
         BasicBlock *root = BasicBlock::get(func->cfg.getRoot());
         if (root->getEntry() == NULL || root->getEntry()->op != OP_PRERET) {
            BasicBlock *pos = getBB();
            setPosition(root, false);
            mkFlow(OP_PRERET, leave, CC_ALWAYS, NULL)->fixed = 1;
            setPosition(pos, true);
         }
      }
      mkFlow(OP_RET, NULL, CC_ALWAYS, NULL)->fixed = 1;
      bb->cfg.attach(&leave->cfg, Graph::Edge::CROSS);
   }
      break;
   case TGSI_OPCODE_END:
   {
      // attach and generate epilogue code
      BasicBlock *epilogue = BasicBlock::get(func->cfgExit);
      bb->cfg.attach(&epilogue->cfg, Graph::Edge::TREE);
      setPosition(epilogue, true);
      if (prog->getType() == Program::TYPE_FRAGMENT)
         exportOutputs();
      if ((prog->getType() == Program::TYPE_VERTEX ||
           prog->getType() == Program::TYPE_TESSELLATION_EVAL
          ) && info->io.genUserClip > 0)
         handleUserClipPlanes();
      mkOp(OP_EXIT, TYPE_NONE, NULL)->terminator = 1;
   }
      break;
   case TGSI_OPCODE_SWITCH:
   case TGSI_OPCODE_CASE:
      ERROR("switch/case opcode encountered, should have been lowered\n");
      abort();
      break;
   case TGSI_OPCODE_LOAD:
      handleLOAD(dst0);
      break;
   case TGSI_OPCODE_STORE:
      handleSTORE();
      break;
   case TGSI_OPCODE_BARRIER:
      geni = mkOp2(OP_BAR, TYPE_U32, NULL, mkImm(0), mkImm(0));
      geni->fixed = 1;
      geni->subOp = NV50_IR_SUBOP_BAR_SYNC;
      break;
   case TGSI_OPCODE_MEMBAR:
   {
      uint32_t level = tgsi.getSrc(0).getValueU32(0, info);
      geni = mkOp(OP_MEMBAR, TYPE_NONE, NULL);
      geni->fixed = 1;
      if (!(level & ~(TGSI_MEMBAR_THREAD_GROUP | TGSI_MEMBAR_SHARED)))
         geni->subOp = NV50_IR_SUBOP_MEMBAR(M, CTA);
      else
         geni->subOp = NV50_IR_SUBOP_MEMBAR(M, GL);
   }
      break;
   case TGSI_OPCODE_ATOMUADD:
   case TGSI_OPCODE_ATOMXCHG:
   case TGSI_OPCODE_ATOMCAS:
   case TGSI_OPCODE_ATOMAND:
   case TGSI_OPCODE_ATOMOR:
   case TGSI_OPCODE_ATOMXOR:
   case TGSI_OPCODE_ATOMUMIN:
   case TGSI_OPCODE_ATOMIMIN:
   case TGSI_OPCODE_ATOMUMAX:
   case TGSI_OPCODE_ATOMIMAX:
   case TGSI_OPCODE_ATOMFADD:
      handleATOM(dst0, dstTy, tgsi::opcodeToSubOp(tgsi.getOpcode()));
      break;
   case TGSI_OPCODE_RESQ:
      if (tgsi.getSrc(0).getFile() == TGSI_FILE_BUFFER) {
         Value *ind = NULL;
         if (tgsi.getSrc(0).isIndirect(0))
            ind = fetchSrc(tgsi.getSrc(0).getIndirect(0), 0, 0);
         geni = mkOp1(OP_BUFQ, TYPE_U32, dst0[0],
                      makeSym(tgsi.getSrc(0).getFile(),
                              tgsi.getSrc(0).getIndex(0), -1, 0, 0));
         if (ind)
            geni->setIndirect(0, 1, ind);
      } else {
         TexInstruction *texi = new_TexInstruction(func, OP_SUQ);
         for (int c = 0, d = 0; c < 4; ++c) {
            if (dst0[c]) {
               texi->setDef(d++, dst0[c]);
               texi->tex.mask |= 1 << c;
            }
         }
         if (tgsi.getSrc(0).getFile() == TGSI_FILE_IMAGE) {
            texi->tex.r = tgsi.getSrc(0).getIndex(0);
            if (tgsi.getSrc(0).isIndirect(0))
               texi->setIndirectR(fetchSrc(tgsi.getSrc(0).getIndirect(0), 0, NULL));
         } else {
            texi->tex.bindless = true;
            texi->setIndirectR(fetchSrc(0, 0));
         }
         texi->tex.target = tgsi.getImageTarget();

         bb->insertTail(texi);
      }
      break;
   case TGSI_OPCODE_IBFE:
   case TGSI_OPCODE_UBFE:
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi) {
         src0 = fetchSrc(0, c);
         val0 = getScratch();
         if (tgsi.getSrc(1).getFile() == TGSI_FILE_IMMEDIATE &&
             tgsi.getSrc(2).getFile() == TGSI_FILE_IMMEDIATE) {
            loadImm(val0, (tgsi.getSrc(2).getValueU32(c, info) << 8) |
                    tgsi.getSrc(1).getValueU32(c, info));
         } else {
            src1 = fetchSrc(1, c);
            src2 = fetchSrc(2, c);
            mkOp3(OP_INSBF, TYPE_U32, val0, src2, mkImm(0x808), src1);
         }
         mkOp2(OP_EXTBF, dstTy, dst0[c], src0, val0);
      }
      break;
   case TGSI_OPCODE_BFI:
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi) {
         src0 = fetchSrc(0, c);
         src1 = fetchSrc(1, c);
         src2 = fetchSrc(2, c);
         src3 = fetchSrc(3, c);
         val0 = getScratch();
         mkOp3(OP_INSBF, TYPE_U32, val0, src3, mkImm(0x808), src2);
         mkOp3(OP_INSBF, TYPE_U32, dst0[c], src1, val0, src0);
      }
      break;
   case TGSI_OPCODE_LSB:
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi) {
         src0 = fetchSrc(0, c);
         val0 = getScratch();
         geni = mkOp2(OP_EXTBF, TYPE_U32, val0, src0, mkImm(0x2000));
         geni->subOp = NV50_IR_SUBOP_EXTBF_REV;
         geni = mkOp1(OP_BFIND, TYPE_U32, dst0[c], val0);
         geni->subOp = NV50_IR_SUBOP_BFIND_SAMT;
      }
      break;
   case TGSI_OPCODE_IMSB:
   case TGSI_OPCODE_UMSB:
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi) {
         src0 = fetchSrc(0, c);
         mkOp1(OP_BFIND, srcTy, dst0[c], src0);
      }
      break;
   case TGSI_OPCODE_BREV:
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi) {
         src0 = fetchSrc(0, c);
         geni = mkOp2(OP_EXTBF, TYPE_U32, dst0[c], src0, mkImm(0x2000));
         geni->subOp = NV50_IR_SUBOP_EXTBF_REV;
      }
      break;
   case TGSI_OPCODE_POPC:
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi) {
         src0 = fetchSrc(0, c);
         mkOp2(OP_POPCNT, TYPE_U32, dst0[c], src0, src0);
      }
      break;
   case TGSI_OPCODE_INTERP_CENTROID:
   case TGSI_OPCODE_INTERP_SAMPLE:
   case TGSI_OPCODE_INTERP_OFFSET:
      handleINTERP(dst0);
      break;
   case TGSI_OPCODE_I642F:
   case TGSI_OPCODE_U642F:
   case TGSI_OPCODE_D2I:
   case TGSI_OPCODE_D2U:
   case TGSI_OPCODE_D2F: {
      int pos = 0;
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi) {
         Value *dreg = getSSA(8);
         src0 = fetchSrc(0, pos);
         src1 = fetchSrc(0, pos + 1);
         mkOp2(OP_MERGE, TYPE_U64, dreg, src0, src1);
         Instruction *cvt = mkCvt(OP_CVT, dstTy, dst0[c], srcTy, dreg);
         if (!isFloatType(dstTy))
            cvt->rnd = ROUND_Z;
         pos += 2;
      }
      break;
   }
   case TGSI_OPCODE_I2I64:
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi) {
         dst0[c] = fetchSrc(0, c / 2);
         mkOp2(OP_SHR, TYPE_S32, dst0[c + 1], dst0[c], loadImm(NULL, 31));
         c++;
      }
      break;
   case TGSI_OPCODE_U2I64:
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi) {
         dst0[c] = fetchSrc(0, c / 2);
         dst0[c + 1] = zero;
         c++;
      }
      break;
   case TGSI_OPCODE_F2I64:
   case TGSI_OPCODE_F2U64:
   case TGSI_OPCODE_I2D:
   case TGSI_OPCODE_U2D:
   case TGSI_OPCODE_F2D:
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi) {
         Value *dreg = getSSA(8);
         Instruction *cvt = mkCvt(OP_CVT, dstTy, dreg, srcTy, fetchSrc(0, c / 2));
         if (!isFloatType(dstTy))
            cvt->rnd = ROUND_Z;
         mkSplit(&dst0[c], 4, dreg);
         c++;
      }
      break;
   case TGSI_OPCODE_D2I64:
   case TGSI_OPCODE_D2U64:
   case TGSI_OPCODE_I642D:
   case TGSI_OPCODE_U642D:
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi) {
         src0 = getSSA(8);
         Value *dst = getSSA(8), *tmp[2];
         tmp[0] = fetchSrc(0, c);
         tmp[1] = fetchSrc(0, c + 1);
         mkOp2(OP_MERGE, TYPE_U64, src0, tmp[0], tmp[1]);
         Instruction *cvt = mkCvt(OP_CVT, dstTy, dst, srcTy, src0);
         if (!isFloatType(dstTy))
            cvt->rnd = ROUND_Z;
         mkSplit(&dst0[c], 4, dst);
         c++;
      }
      break;
   case TGSI_OPCODE_I64NEG:
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi) {
         src0 = getSSA(8);
         Value *dst = getSSA(8), *tmp[2];
         tmp[0] = fetchSrc(0, c);
         tmp[1] = fetchSrc(0, c + 1);
         mkOp2(OP_MERGE, TYPE_U64, src0, tmp[0], tmp[1]);
         mkOp2(OP_SUB, dstTy, dst, zero, src0);
         mkSplit(&dst0[c], 4, dst);
         c++;
      }
      break;
   case TGSI_OPCODE_I64ABS:
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi) {
         src0 = getSSA(8);
         Value *neg = getSSA(8), *srcComp[2], *negComp[2];
         srcComp[0] = fetchSrc(0, c);
         srcComp[1] = fetchSrc(0, c + 1);
         mkOp2(OP_MERGE, TYPE_U64, src0, srcComp[0], srcComp[1]);
         mkOp2(OP_SUB, dstTy, neg, zero, src0);
         mkSplit(negComp, 4, neg);
         mkCmp(OP_SLCT, CC_LT, TYPE_S32, dst0[c], TYPE_S32,
               negComp[0], srcComp[0], srcComp[1]);
         mkCmp(OP_SLCT, CC_LT, TYPE_S32, dst0[c + 1], TYPE_S32,
               negComp[1], srcComp[1], srcComp[1]);
         c++;
      }
      break;
   case TGSI_OPCODE_DABS:
   case TGSI_OPCODE_DNEG:
   case TGSI_OPCODE_DRCP:
   case TGSI_OPCODE_DSQRT:
   case TGSI_OPCODE_DRSQ:
   case TGSI_OPCODE_DTRUNC:
   case TGSI_OPCODE_DCEIL:
   case TGSI_OPCODE_DFLR:
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi) {
         src0 = getSSA(8);
         Value *dst = getSSA(8), *tmp[2];
         tmp[0] = fetchSrc(0, c);
         tmp[1] = fetchSrc(0, c + 1);
         mkOp2(OP_MERGE, TYPE_U64, src0, tmp[0], tmp[1]);
         mkOp1(op, dstTy, dst, src0);
         mkSplit(&dst0[c], 4, dst);
         c++;
      }
      break;
   case TGSI_OPCODE_DFRAC:
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi) {
         src0 = getSSA(8);
         Value *dst = getSSA(8), *tmp[2];
         tmp[0] = fetchSrc(0, c);
         tmp[1] = fetchSrc(0, c + 1);
         mkOp2(OP_MERGE, TYPE_U64, src0, tmp[0], tmp[1]);
         mkOp1(OP_FLOOR, TYPE_F64, dst, src0);
         mkOp2(OP_SUB, TYPE_F64, dst, src0, dst);
         mkSplit(&dst0[c], 4, dst);
         c++;
      }
      break;
   case TGSI_OPCODE_U64SEQ:
   case TGSI_OPCODE_U64SNE:
   case TGSI_OPCODE_U64SLT:
   case TGSI_OPCODE_U64SGE:
   case TGSI_OPCODE_I64SLT:
   case TGSI_OPCODE_I64SGE:
   case TGSI_OPCODE_DSLT:
   case TGSI_OPCODE_DSGE:
   case TGSI_OPCODE_DSEQ:
   case TGSI_OPCODE_DSNE: {
      int pos = 0;
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi) {
         Value *tmp[2];

         src0 = getSSA(8);
         src1 = getSSA(8);
         tmp[0] = fetchSrc(0, pos);
         tmp[1] = fetchSrc(0, pos + 1);
         mkOp2(OP_MERGE, TYPE_U64, src0, tmp[0], tmp[1]);
         tmp[0] = fetchSrc(1, pos);
         tmp[1] = fetchSrc(1, pos + 1);
         mkOp2(OP_MERGE, TYPE_U64, src1, tmp[0], tmp[1]);
         mkCmp(op, tgsi.getSetCond(), dstTy, dst0[c], srcTy, src0, src1);
         pos += 2;
      }
      break;
   }
   case TGSI_OPCODE_U64MIN:
   case TGSI_OPCODE_U64MAX:
   case TGSI_OPCODE_I64MIN:
   case TGSI_OPCODE_I64MAX: {
      dstTy = isSignedIntType(dstTy) ? TYPE_S32 : TYPE_U32;
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi) {
         Value *flag = getSSA(1, FILE_FLAGS);
         src0 = fetchSrc(0, c + 1);
         src1 = fetchSrc(1, c + 1);
         geni = mkOp2(op, dstTy, dst0[c + 1], src0, src1);
         geni->subOp = NV50_IR_SUBOP_MINMAX_HIGH;
         geni->setFlagsDef(1, flag);

         src0 = fetchSrc(0, c);
         src1 = fetchSrc(1, c);
         geni = mkOp2(op, TYPE_U32, dst0[c], src0, src1);
         geni->subOp = NV50_IR_SUBOP_MINMAX_LOW;
         geni->setFlagsSrc(2, flag);

         c++;
      }
      break;
   }
   case TGSI_OPCODE_U64SHL:
   case TGSI_OPCODE_I64SHR:
   case TGSI_OPCODE_U64SHR:
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi) {
         src0 = getSSA(8);
         Value *dst = getSSA(8), *tmp[2];
         tmp[0] = fetchSrc(0, c);
         tmp[1] = fetchSrc(0, c + 1);
         mkOp2(OP_MERGE, TYPE_U64, src0, tmp[0], tmp[1]);
         // Theoretically src1 is a 64-bit value but in practice only the low
         // bits matter. The IR expects this to be a 32-bit value.
         src1 = fetchSrc(1, c);
         mkOp2(op, dstTy, dst, src0, src1);
         mkSplit(&dst0[c], 4, dst);
         c++;
      }
      break;
   case TGSI_OPCODE_U64ADD:
   case TGSI_OPCODE_U64MUL:
   case TGSI_OPCODE_DADD:
   case TGSI_OPCODE_DMUL:
   case TGSI_OPCODE_DDIV:
   case TGSI_OPCODE_DMAX:
   case TGSI_OPCODE_DMIN:
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi) {
         src0 = getSSA(8);
         src1 = getSSA(8);
         Value *dst = getSSA(8), *tmp[2];
         tmp[0] = fetchSrc(0, c);
         tmp[1] = fetchSrc(0, c + 1);
         mkOp2(OP_MERGE, TYPE_U64, src0, tmp[0], tmp[1]);
         tmp[0] = fetchSrc(1, c);
         tmp[1] = fetchSrc(1, c + 1);
         mkOp2(OP_MERGE, TYPE_U64, src1, tmp[0], tmp[1]);
         mkOp2(op, dstTy, dst, src0, src1);
         mkSplit(&dst0[c], 4, dst);
         c++;
      }
      break;
   case TGSI_OPCODE_DMAD:
   case TGSI_OPCODE_DFMA:
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi) {
         src0 = getSSA(8);
         src1 = getSSA(8);
         src2 = getSSA(8);
         Value *dst = getSSA(8), *tmp[2];
         tmp[0] = fetchSrc(0, c);
         tmp[1] = fetchSrc(0, c + 1);
         mkOp2(OP_MERGE, TYPE_U64, src0, tmp[0], tmp[1]);
         tmp[0] = fetchSrc(1, c);
         tmp[1] = fetchSrc(1, c + 1);
         mkOp2(OP_MERGE, TYPE_U64, src1, tmp[0], tmp[1]);
         tmp[0] = fetchSrc(2, c);
         tmp[1] = fetchSrc(2, c + 1);
         mkOp2(OP_MERGE, TYPE_U64, src2, tmp[0], tmp[1]);
         mkOp3(op, dstTy, dst, src0, src1, src2);
         mkSplit(&dst0[c], 4, dst);
         c++;
      }
      break;
   case TGSI_OPCODE_DROUND:
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi) {
         src0 = getSSA(8);
         Value *dst = getSSA(8), *tmp[2];
         tmp[0] = fetchSrc(0, c);
         tmp[1] = fetchSrc(0, c + 1);
         mkOp2(OP_MERGE, TYPE_U64, src0, tmp[0], tmp[1]);
         mkCvt(OP_CVT, TYPE_F64, dst, TYPE_F64, src0)
         ->rnd = ROUND_NI;
         mkSplit(&dst0[c], 4, dst);
         c++;
      }
      break;
   case TGSI_OPCODE_DSSG:
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi) {
         src0 = getSSA(8);
         Value *dst = getSSA(8), *dstF32 = getSSA(), *tmp[2];
         tmp[0] = fetchSrc(0, c);
         tmp[1] = fetchSrc(0, c + 1);
         mkOp2(OP_MERGE, TYPE_U64, src0, tmp[0], tmp[1]);

         val0 = getScratch();
         val1 = getScratch();
         // The zero is wrong here since it's only 32-bit, but it works out in
         // the end since it gets replaced with $r63.
         mkCmp(OP_SET, CC_GT, TYPE_F32, val0, TYPE_F64, src0, zero);
         mkCmp(OP_SET, CC_LT, TYPE_F32, val1, TYPE_F64, src0, zero);
         mkOp2(OP_SUB, TYPE_F32, dstF32, val0, val1);
         mkCvt(OP_CVT, TYPE_F64, dst, TYPE_F32, dstF32);
         mkSplit(&dst0[c], 4, dst);
         c++;
      }
      break;
   case TGSI_OPCODE_I64SSG:
      FOR_EACH_DST_ENABLED_CHANNEL(0, c, tgsi) {
         src0 = getSSA(8);
         Value *tmp[2];
         tmp[0] = fetchSrc(0, c);
         tmp[1] = fetchSrc(0, c + 1);
         mkOp2(OP_MERGE, TYPE_U64, src0, tmp[0], tmp[1]);

         val0 = getScratch();
         val1 = getScratch();
         mkCmp(OP_SET, CC_GT, TYPE_U32, val0, TYPE_S64, src0, zero);
         mkCmp(OP_SET, CC_LT, TYPE_U32, val1, TYPE_S64, src0, zero);
         mkOp2(OP_SUB, TYPE_S32, dst0[c], val1, val0);
         mkOp2(OP_SHR, TYPE_S32, dst0[c + 1], dst0[c], loadImm(0, 31));
         c++;
      }
      break;
   default:
      ERROR("unhandled TGSI opcode: %u\n", tgsi.getOpcode());
      assert(0);
      break;
   }

   if (tgsi.dstCount() && tgsi.getOpcode() != TGSI_OPCODE_STORE) {
      for (c = 0; c < 4; ++c) {
         if (!dst0[c])
            continue;
         if (dst0[c] != rDst0[c])
            mkMov(rDst0[c], dst0[c]);
         storeDst(0, c, rDst0[c]);
      }
   }
   vtxBaseValid = 0;

   return true;
}

void
Converter::exportOutputs()
{
   if (info->io.alphaRefBase) {
      for (unsigned int i = 0; i < info->numOutputs; ++i) {
         if (info->out[i].sn != TGSI_SEMANTIC_COLOR ||
             info->out[i].si != 0)
            continue;
         const unsigned int c = 3;
         if (!oData.exists(sub.cur->values, i, c))
            continue;
         Value *val = oData.load(sub.cur->values, i, c, NULL);
         if (!val)
            continue;

         Symbol *ref = mkSymbol(FILE_MEMORY_CONST, info->io.auxCBSlot,
                                TYPE_U32, info->io.alphaRefBase);
         Value *pred = new_LValue(func, FILE_PREDICATE);
         mkCmp(OP_SET, CC_TR, TYPE_U32, pred, TYPE_F32, val,
               mkLoadv(TYPE_U32, ref, NULL))
            ->subOp = 1;
         mkOp(OP_DISCARD, TYPE_NONE, NULL)->setPredicate(CC_NOT_P, pred);
      }
   }

   for (unsigned int i = 0; i < info->numOutputs; ++i) {
      for (unsigned int c = 0; c < 4; ++c) {
         if (!oData.exists(sub.cur->values, i, c))
            continue;
         Symbol *sym = mkSymbol(FILE_SHADER_OUTPUT, 0, TYPE_F32,
                                info->out[i].slot[c] * 4);
         Value *val = oData.load(sub.cur->values, i, c, NULL);
         if (val) {
            if (info->out[i].sn == TGSI_SEMANTIC_POSITION)
               mkOp1(OP_SAT, TYPE_F32, val, val);
            mkStore(OP_EXPORT, TYPE_F32, sym, NULL, val);
         }
      }
   }
}

Converter::Converter(Program *ir, const tgsi::Source *code) : ConverterCommon(ir, code->info),
     code(code),
     tgsi(NULL),
     tData(this), lData(this), aData(this), oData(this)
{
   const unsigned tSize = code->fileSize(TGSI_FILE_TEMPORARY);
   const unsigned aSize = code->fileSize(TGSI_FILE_ADDRESS);
   const unsigned oSize = code->fileSize(TGSI_FILE_OUTPUT);

   tData.setup(TGSI_FILE_TEMPORARY, 0, 0, tSize, 4, 4, FILE_GPR, 0);
   lData.setup(TGSI_FILE_TEMPORARY, 1, 0, tSize, 4, 4, FILE_MEMORY_LOCAL, 0);
   aData.setup(TGSI_FILE_ADDRESS, 0, 0, aSize, 4, 4, FILE_GPR, 0);
   oData.setup(TGSI_FILE_OUTPUT, 0, 0, oSize, 4, 4, FILE_GPR, 0);

   zero = mkImm((uint32_t)0);

   vtxBaseValid = 0;
}

Converter::~Converter()
{
}

inline const Converter::Location *
Converter::BindArgumentsPass::getValueLocation(Subroutine *s, Value *v)
{
   ValueMap::l_iterator it = s->values.l.find(v);
   return it == s->values.l.end() ? NULL : &it->second;
}

template<typename T> inline void
Converter::BindArgumentsPass::updateCallArgs(
   Instruction *i, void (Instruction::*setArg)(int, Value *),
   T (Function::*proto))
{
   Function *g = i->asFlow()->target.fn;
   Subroutine *subg = conv.getSubroutine(g);

   for (unsigned a = 0; a < (g->*proto).size(); ++a) {
      Value *v = (g->*proto)[a].get();
      const Converter::Location &l = *getValueLocation(subg, v);
      Converter::DataArray *array = conv.getArrayForFile(l.array, l.arrayIdx);

      (i->*setArg)(a, array->acquire(sub->values, l.i, l.c));
   }
}

template<typename T> inline void
Converter::BindArgumentsPass::updatePrototype(
   BitSet *set, void (Function::*updateSet)(), T (Function::*proto))
{
   (func->*updateSet)();

   for (unsigned i = 0; i < set->getSize(); ++i) {
      Value *v = func->getLValue(i);
      const Converter::Location *l = getValueLocation(sub, v);

      // only include values with a matching TGSI register
      if (set->test(i) && l && !conv.code->locals.count(*l))
         (func->*proto).push_back(v);
   }
}

bool
Converter::BindArgumentsPass::visit(Function *f)
{
   sub = conv.getSubroutine(f);

   for (ArrayList::Iterator bi = f->allBBlocks.iterator();
        !bi.end(); bi.next()) {
      for (Instruction *i = BasicBlock::get(bi)->getFirst();
           i; i = i->next) {
         if (i->op == OP_CALL && !i->asFlow()->builtin) {
            updateCallArgs(i, &Instruction::setSrc, &Function::ins);
            updateCallArgs(i, &Instruction::setDef, &Function::outs);
         }
      }
   }

   if (func == prog->main && prog->getType() != Program::TYPE_COMPUTE)
      return true;
   updatePrototype(&BasicBlock::get(f->cfg.getRoot())->liveSet,
                   &Function::buildLiveSets, &Function::ins);
   updatePrototype(&BasicBlock::get(f->cfgExit)->defSet,
                   &Function::buildDefSets, &Function::outs);

   return true;
}

bool
Converter::run()
{
   BasicBlock *entry = new BasicBlock(prog->main);
   BasicBlock *leave = new BasicBlock(prog->main);

   prog->main->setEntry(entry);
   prog->main->setExit(leave);

   setPosition(entry, true);
   sub.cur = getSubroutine(prog->main);

   if (info->io.genUserClip > 0) {
      for (int c = 0; c < 4; ++c)
         clipVtx[c] = getScratch();
   }

   switch (prog->getType()) {
   case Program::TYPE_TESSELLATION_CONTROL:
      outBase = mkOp2v(
         OP_SUB, TYPE_U32, getSSA(),
         mkOp1v(OP_RDSV, TYPE_U32, getSSA(), mkSysVal(SV_LANEID, 0)),
         mkOp1v(OP_RDSV, TYPE_U32, getSSA(), mkSysVal(SV_INVOCATION_ID, 0)));
      break;
   case Program::TYPE_FRAGMENT: {
      Symbol *sv = mkSysVal(SV_POSITION, 3);
      fragCoord[3] = mkOp1v(OP_RDSV, TYPE_F32, getSSA(), sv);
      mkOp1(OP_RCP, TYPE_F32, fragCoord[3], fragCoord[3]);
      break;
   }
   default:
      break;
   }

   if (info->io.viewportId >= 0)
      viewport = getScratch();
   else
      viewport = NULL;

   for (ip = 0; ip < code->scan.num_instructions; ++ip) {
      if (!handleInstruction(&code->insns[ip]))
         return false;
   }

   if (!BindArgumentsPass(*this).run(prog))
      return false;

   return true;
}

} // unnamed namespace

namespace nv50_ir {

bool
Program::makeFromTGSI(struct nv50_ir_prog_info *info)
{
   tgsi::Source src(info);
   if (!src.scanSource())
      return false;
   tlsSize = info->bin.tlsSpace;

   Converter builder(this, &src);
   return builder.run();
}

} // namespace nv50_ir