summaryrefslogtreecommitdiffstats
path: root/src/mesa/shader/slang/slang_codegen.c
blob: 26be14a0565b8da8f1f2dd30dd4c494e31d43a5d (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
/*
 * Mesa 3-D graphics library
 * Version:  6.5.3
 *
 * Copyright (C) 2005-2007  Brian Paul   All Rights Reserved.
 *
 * 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
 * BRIAN PAUL 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.
 */

/**
 * \file slang_codegen.c
 * Generate IR tree from AST.
 * \author Brian Paul
 */


/***
 *** NOTES:
 *** The new_() functions return a new instance of a simple IR node.
 *** The gen_() functions generate larger IR trees from the simple nodes.
 ***/



#include "imports.h"
#include "macros.h"
#include "mtypes.h"
#include "program.h"
#include "prog_instruction.h"
#include "prog_parameter.h"
#include "prog_statevars.h"
#include "slang_typeinfo.h"
#include "slang_codegen.h"
#include "slang_compile.h"
#include "slang_label.h"
#include "slang_simplify.h"
#include "slang_emit.h"
#include "slang_vartable.h"
#include "slang_ir.h"
#include "slang_print.h"


static slang_ir_node *
_slang_gen_operation(slang_assemble_ctx * A, slang_operation *oper);


static GLboolean
is_sampler_type(const slang_fully_specified_type *t)
{
   switch (t->specifier.type) {
   case SLANG_SPEC_SAMPLER1D:
   case SLANG_SPEC_SAMPLER2D:
   case SLANG_SPEC_SAMPLER3D:
   case SLANG_SPEC_SAMPLERCUBE:
   case SLANG_SPEC_SAMPLER1DSHADOW:
   case SLANG_SPEC_SAMPLER2DSHADOW:
      return GL_TRUE;
   default:
      return GL_FALSE;
   }
}


GLuint
_slang_sizeof_type_specifier(const slang_type_specifier *spec)
{
   switch (spec->type) {
   case SLANG_SPEC_VOID:
      return 0;
   case SLANG_SPEC_BOOL:
      return 1;
   case SLANG_SPEC_BVEC2:
      return 2;
   case SLANG_SPEC_BVEC3:
      return 3;
   case SLANG_SPEC_BVEC4:
      return 4;
   case SLANG_SPEC_INT:
      return 1;
   case SLANG_SPEC_IVEC2:
      return 2;
   case SLANG_SPEC_IVEC3:
      return 3;
   case SLANG_SPEC_IVEC4:
      return 4;
   case SLANG_SPEC_FLOAT:
      return 1;
   case SLANG_SPEC_VEC2:
      return 2;
   case SLANG_SPEC_VEC3:
      return 3;
   case SLANG_SPEC_VEC4:
      return 4;
   case SLANG_SPEC_MAT2:
      return 2 * 2;
   case SLANG_SPEC_MAT3:
      return 3 * 3;
   case SLANG_SPEC_MAT4:
      return 4 * 4;
   case SLANG_SPEC_SAMPLER1D:
   case SLANG_SPEC_SAMPLER2D:
   case SLANG_SPEC_SAMPLER3D:
   case SLANG_SPEC_SAMPLERCUBE:
   case SLANG_SPEC_SAMPLER1DSHADOW:
   case SLANG_SPEC_SAMPLER2DSHADOW:
      return 1; /* special case */
   case SLANG_SPEC_STRUCT:
      {
         GLuint sum = 0, i;
         for (i = 0; i < spec->_struct->fields->num_variables; i++) {
            slang_variable *v = spec->_struct->fields->variables[i];
            GLuint sz = _slang_sizeof_type_specifier(&v->type.specifier);
            /* XXX verify padding */
            if (sz < 4)
               sz = 4;
            sum += sz;
         }
         return sum;
      }
   case SLANG_SPEC_ARRAY:
      return _slang_sizeof_type_specifier(spec->_array);
   default:
      _mesa_problem(NULL, "Unexpected type in _slang_sizeof_type_specifier()");
      return 0;
   }
   return 0;
}


/**
 * Establish the binding between a slang_ir_node and a slang_variable.
 * Then, allocate/attach a slang_ir_storage object to the IR node if needed.
 * The IR node must be a IR_VAR or IR_VAR_DECL node.
 * \param n  the IR node
 * \param var  the variable to associate with the IR node
 */
static void
_slang_attach_storage(slang_ir_node *n, slang_variable *var)
{
   assert(n);
   assert(var);
   assert(n->Opcode == IR_VAR || n->Opcode == IR_VAR_DECL);
   assert(!n->Var || n->Var == var);

   n->Var = var;

   if (!n->Store) {
      /* need to setup storage */
      if (n->Var && n->Var->aux) {
         /* node storage info = var storage info */
         n->Store = (slang_ir_storage *) n->Var->aux;
      }
      else {
         /* alloc new storage info */
         n->Store = _slang_new_ir_storage(PROGRAM_UNDEFINED, -1, -5);
         if (n->Var)
            n->Var->aux = n->Store;
         assert(n->Var->aux);
      }
   }
}


/**
 * Return the TEXTURE_*_INDEX value that corresponds to a sampler type,
 * or -1 if the type is not a sampler.
 */
static GLint
sampler_to_texture_index(const slang_type_specifier_type type)
{
   switch (type) {
   case SLANG_SPEC_SAMPLER1D:
      return TEXTURE_1D_INDEX;
   case SLANG_SPEC_SAMPLER2D:
      return TEXTURE_2D_INDEX;
   case SLANG_SPEC_SAMPLER3D:
      return TEXTURE_3D_INDEX;
   case SLANG_SPEC_SAMPLERCUBE:
      return TEXTURE_CUBE_INDEX;
   case SLANG_SPEC_SAMPLER1DSHADOW:
      return TEXTURE_1D_INDEX; /* XXX fix */
   case SLANG_SPEC_SAMPLER2DSHADOW:
      return TEXTURE_2D_INDEX; /* XXX fix */
   default:
      return -1;
   }
}


/**
 * Return the VERT_ATTRIB_* or FRAG_ATTRIB_* value that corresponds to
 * a vertex or fragment program input variable.  Return -1 if the input
 * name is invalid.
 * XXX return size too
 */
static GLint
_slang_input_index(const char *name, GLenum target)
{
   struct input_info {
      const char *Name;
      GLuint Attrib;
   };
   static const struct input_info vertInputs[] = {
      { "gl_Vertex", VERT_ATTRIB_POS },
      { "gl_Normal", VERT_ATTRIB_NORMAL },
      { "gl_Color", VERT_ATTRIB_COLOR0 },
      { "gl_SecondaryColor", VERT_ATTRIB_COLOR1 },
      { "gl_FogCoord", VERT_ATTRIB_FOG },
      { "gl_MultiTexCoord0", VERT_ATTRIB_TEX0 },
      { "gl_MultiTexCoord1", VERT_ATTRIB_TEX1 },
      { "gl_MultiTexCoord2", VERT_ATTRIB_TEX2 },
      { "gl_MultiTexCoord3", VERT_ATTRIB_TEX3 },
      { "gl_MultiTexCoord4", VERT_ATTRIB_TEX4 },
      { "gl_MultiTexCoord5", VERT_ATTRIB_TEX5 },
      { "gl_MultiTexCoord6", VERT_ATTRIB_TEX6 },
      { "gl_MultiTexCoord7", VERT_ATTRIB_TEX7 },
      { NULL, 0 }
   };
   static const struct input_info fragInputs[] = {
      { "gl_FragCoord", FRAG_ATTRIB_WPOS },
      { "gl_Color", FRAG_ATTRIB_COL0 },
      { "gl_SecondaryColor", FRAG_ATTRIB_COL1 },
      { "gl_FogFragCoord", FRAG_ATTRIB_FOGC },
      { "gl_TexCoord", FRAG_ATTRIB_TEX0 },
      { NULL, 0 }
   };
   GLuint i;
   const struct input_info *inputs
      = (target == GL_VERTEX_PROGRAM_ARB) ? vertInputs : fragInputs;

   ASSERT(MAX_TEXTURE_UNITS == 8); /* if this fails, fix vertInputs above */

   for (i = 0; inputs[i].Name; i++) {
      if (strcmp(inputs[i].Name, name) == 0) {
         /* found */
         return inputs[i].Attrib;
      }
   }
   return -1;
}


/**
 * Return the VERT_RESULT_* or FRAG_RESULT_* value that corresponds to
 * a vertex or fragment program output variable.  Return -1 for an invalid
 * output name.
 */
static GLint
_slang_output_index(const char *name, GLenum target)
{
   struct output_info {
      const char *Name;
      GLuint Attrib;
   };
   static const struct output_info vertOutputs[] = {
      { "gl_Position", VERT_RESULT_HPOS },
      { "gl_FrontColor", VERT_RESULT_COL0 },
      { "gl_BackColor", VERT_RESULT_BFC0 },
      { "gl_FrontSecondaryColor", VERT_RESULT_COL1 },
      { "gl_BackSecondaryColor", VERT_RESULT_BFC1 },
      { "gl_TexCoord", VERT_RESULT_TEX0 }, /* XXX indexed */
      { "gl_FogFragCoord", VERT_RESULT_FOGC },
      { "gl_PointSize", VERT_RESULT_PSIZ },
      { NULL, 0 }
   };
   static const struct output_info fragOutputs[] = {
      { "gl_FragColor", FRAG_RESULT_COLR },
      { "gl_FragDepth", FRAG_RESULT_DEPR },
      { NULL, 0 }
   };
   GLuint i;
   const struct output_info *outputs
      = (target == GL_VERTEX_PROGRAM_ARB) ? vertOutputs : fragOutputs;

   for (i = 0; outputs[i].Name; i++) {
      if (strcmp(outputs[i].Name, name) == 0) {
         /* found */
         return outputs[i].Attrib;
      }
   }
   return -1;
}



/**********************************************************************/


/**
 * Map "_asm foo" to IR_FOO, etc.
 */
typedef struct
{
   const char *Name;
   slang_ir_opcode Opcode;
   GLuint HaveRetValue, NumParams;
} slang_asm_info;


static slang_asm_info AsmInfo[] = {
   /* vec4 binary op */
   { "vec4_add", IR_ADD, 1, 2 },
   { "vec4_subtract", IR_SUB, 1, 2 },
   { "vec4_multiply", IR_MUL, 1, 2 },
   { "vec4_dot", IR_DOT4, 1, 2 },
   { "vec3_dot", IR_DOT3, 1, 2 },
   { "vec3_cross", IR_CROSS, 1, 2 },
   { "vec4_lrp", IR_LRP, 1, 3 },
   { "vec4_min", IR_MIN, 1, 2 },
   { "vec4_max", IR_MAX, 1, 2 },
   { "vec4_clamp", IR_CLAMP, 1, 3 },
   { "vec4_seq", IR_SEQ, 1, 2 },
   { "vec4_sge", IR_SGE, 1, 2 },
   { "vec4_sgt", IR_SGT, 1, 2 },
   /* vec4 unary */
   { "vec4_floor", IR_FLOOR, 1, 1 },
   { "vec4_frac", IR_FRAC, 1, 1 },
   { "vec4_abs", IR_ABS, 1, 1 },
   { "vec4_negate", IR_NEG, 1, 1 },
   { "vec4_ddx", IR_DDX, 1, 1 },
   { "vec4_ddy", IR_DDY, 1, 1 },
   /* float binary op */
   { "float_add", IR_ADD, 1, 2 },
   { "float_multiply", IR_MUL, 1, 2 },
   { "float_divide", IR_DIV, 1, 2 },
   { "float_power", IR_POW, 1, 2 },
   /* texture / sampler */
   { "vec4_tex1d", IR_TEX, 1, 2 },
   { "vec4_texb1d", IR_TEXB, 1, 2 },  /* 1d w/ bias */
   { "vec4_texp1d", IR_TEXP, 1, 2 },  /* 1d w/ projection */
   { "vec4_tex2d", IR_TEX, 1, 2 },
   { "vec4_texb2d", IR_TEXB, 1, 2 },  /* 2d w/ bias */
   { "vec4_texp2d", IR_TEXP, 1, 2 },  /* 2d w/ projection */
   { "vec4_tex3d", IR_TEX, 1, 2 },
   { "vec4_texb3d", IR_TEXB, 1, 2 },  /* 3d w/ bias */
   { "vec4_texp3d", IR_TEXP, 1, 2 },  /* 3d w/ projection */
   { "vec4_texcube", IR_TEX, 1, 2 },  /* cubemap */

   /* unary op */
   { "int_to_float", IR_I_TO_F, 1, 1 },
   { "float_to_int", IR_F_TO_I, 1, 1 },
   { "float_exp", IR_EXP, 1, 1 },
   { "float_exp2", IR_EXP2, 1, 1 },
   { "float_log2", IR_LOG2, 1, 1 },
   { "float_rsq", IR_RSQ, 1, 1 },
   { "float_rcp", IR_RCP, 1, 1 },
   { "float_sine", IR_SIN, 1, 1 },
   { "float_cosine", IR_COS, 1, 1 },
   { "float_noise1", IR_NOISE1, 1, 1},
   { "float_noise2", IR_NOISE2, 1, 1},
   { "float_noise3", IR_NOISE3, 1, 1},
   { "float_noise4", IR_NOISE4, 1, 1},

   { NULL, IR_NOP, 0, 0 }
};


/**
 * Recursively free an IR tree.
 */
static void
_slang_free_ir_tree(slang_ir_node *n)
{
#if 1
   GLuint i;
   if (!n)
      return;
   for (i = 0; i < 3; i++)
      _slang_free_ir_tree(n->Children[i]);
   /* Do not free n->BranchNode since it's a child elsewhere */
   free(n);
#endif
}


static slang_ir_node *
new_node3(slang_ir_opcode op,
          slang_ir_node *c0, slang_ir_node *c1, slang_ir_node *c2)
{
   slang_ir_node *n = (slang_ir_node *) calloc(1, sizeof(slang_ir_node));
   if (n) {
      n->Opcode = op;
      n->Children[0] = c0;
      n->Children[1] = c1;
      n->Children[2] = c2;
      n->Writemask = WRITEMASK_XYZW;
      n->InstLocation = -1;
   }
   return n;
}

static slang_ir_node *
new_node2(slang_ir_opcode op, slang_ir_node *c0, slang_ir_node *c1)
{
   return new_node3(op, c0, c1, NULL);
}

static slang_ir_node *
new_node1(slang_ir_opcode op, slang_ir_node *c0)
{
   return new_node3(op, c0, NULL, NULL);
}

static slang_ir_node *
new_node0(slang_ir_opcode op)
{
   return new_node3(op, NULL, NULL, NULL);
}


static slang_ir_node *
new_seq(slang_ir_node *left, slang_ir_node *right)
{
   if (!left)
      return right;
   if (!right)
      return left;
   return new_node2(IR_SEQ, left, right);
}

static slang_ir_node *
new_label(slang_label *label)
{
   slang_ir_node *n = new_node0(IR_LABEL);
   if (n)
      n->Label = label;
   return n;
}

static slang_ir_node *
new_float_literal(const float v[4])
{
   const GLuint size = (v[0] == v[1] && v[0] == v[2] && v[0] == v[3]) ? 1 : 4;
   slang_ir_node *n = new_node0(IR_FLOAT);
   COPY_4V(n->Value, v);
   /* allocate a storage object, but compute actual location (Index) later */
   n->Store = _slang_new_ir_storage(PROGRAM_CONSTANT, -1, size);
   return n;
}

/**
 * Conditional jump.
 * \param zeroOrOne indicates if the jump is to be taken on zero, or non-zero
 *                  condition code state.
 */
static slang_ir_node *
new_cjump(slang_label *dest, GLuint zeroOrOne)
{
   slang_ir_node *n = new_node0(zeroOrOne ? IR_CJUMP1 : IR_CJUMP0);
   if (n)
      n->Label = dest;
   return n;
}

/**
 * Unconditional jump.
 */
static slang_ir_node *
new_jump(slang_label *dest)
{
   slang_ir_node *n = new_node0(IR_JUMP);
   if (n)
      n->Label = dest;
   return n;
}


static slang_ir_node *
new_loop(slang_ir_node *body)
{
   return new_node1(IR_LOOP, body);
}


static slang_ir_node *
new_break(slang_ir_node *loopNode)
{
   slang_ir_node *n = new_node0(IR_BREAK);
   assert(loopNode);
   assert(loopNode->Opcode == IR_LOOP);
   if (n) {
      /* insert this node at head of linked list */
      n->BranchNode = loopNode->BranchNode;
      loopNode->BranchNode = n;
   }
   return n;
}


/**
 * Make new IR_BREAK_IF_TRUE or IR_BREAK_IF_FALSE node.
 */
static slang_ir_node *
new_break_if(slang_ir_node *loopNode, slang_ir_node *cond, GLboolean breakTrue)
{
   slang_ir_node *n;
   assert(loopNode);
   assert(loopNode->Opcode == IR_LOOP);
   n = new_node1(breakTrue ? IR_BREAK_IF_TRUE : IR_BREAK_IF_FALSE, cond);
   if (n) {
      /* insert this node at head of linked list */
      n->BranchNode = loopNode->BranchNode;
      loopNode->BranchNode = n;
   }
   return n;
}


/**
 * Make new IR_CONT_IF_TRUE or IR_CONT_IF_FALSE node.
 */
static slang_ir_node *
new_cont_if(slang_ir_node *loopNode, slang_ir_node *cond, GLboolean contTrue)
{
   slang_ir_node *n;
   assert(loopNode);
   assert(loopNode->Opcode == IR_LOOP);
   n = new_node1(contTrue ? IR_CONT_IF_TRUE : IR_CONT_IF_FALSE, cond);
   if (n) {
      /* insert this node at head of linked list */
      n->BranchNode = loopNode->BranchNode;
      loopNode->BranchNode = n;
   }
   return n;
}


static slang_ir_node *
new_cont(slang_ir_node *loopNode)
{
   slang_ir_node *n = new_node0(IR_CONT);
   assert(loopNode);
   assert(loopNode->Opcode == IR_LOOP);
   if (n) {
      /* insert this node at head of linked list */
      n->BranchNode = loopNode->BranchNode;
      loopNode->BranchNode = n;
   }
   return n;
}


static slang_ir_node *
new_cond(slang_ir_node *n)
{
   slang_ir_node *c = new_node1(IR_COND, n);
   return c;
}


static slang_ir_node *
new_if(slang_ir_node *cond, slang_ir_node *ifPart, slang_ir_node *elsePart)
{
   return new_node3(IR_IF, cond, ifPart, elsePart);
}


/**
 * New IR_VAR node - a reference to a previously declared variable.
 */
static slang_ir_node *
new_var(slang_assemble_ctx *A, slang_operation *oper, slang_atom name)
{
   slang_ir_node *n;
   slang_variable *var = _slang_locate_variable(oper->locals, name, GL_TRUE);
   if (!var)
      return NULL;

   assert(!oper->var || oper->var == var);

   n = new_node0(IR_VAR);
   if (n) {
      _slang_attach_storage(n, var);
   }
   return n;
}


/**
 * Check if the given function is really just a wrapper for a
 * basic assembly instruction.
 */
static GLboolean
slang_is_asm_function(const slang_function *fun)
{
   if (fun->body->type == SLANG_OPER_BLOCK_NO_NEW_SCOPE &&
       fun->body->num_children == 1 &&
       fun->body->children[0].type == SLANG_OPER_ASM) {
      return GL_TRUE;
   }
   return GL_FALSE;
}


static GLboolean
_slang_is_noop(const slang_operation *oper)
{
   if (!oper ||
       oper->type == SLANG_OPER_VOID ||
       (oper->num_children == 1 && oper->children[0].type == SLANG_OPER_VOID))
      return GL_TRUE;
   else
      return GL_FALSE;
}


/**
 * Produce inline code for a call to an assembly instruction.
 */
static slang_operation *
slang_inline_asm_function(slang_assemble_ctx *A,
                          slang_function *fun, slang_operation *oper)
{
   const GLuint numArgs = oper->num_children;
   const slang_operation *args = oper->children;
   GLuint i;
   slang_operation *inlined = slang_operation_new(1);

   /*assert(oper->type == SLANG_OPER_CALL);  or vec4_add, etc */
   /*
   printf("Inline asm %s\n", (char*) fun->header.a_name);
   */
   inlined->type = fun->body->children[0].type;
   inlined->a_id = fun->body->children[0].a_id;
   inlined->num_children = numArgs;
   inlined->children = slang_operation_new(numArgs);
   inlined->locals->outer_scope = oper->locals->outer_scope;

   for (i = 0; i < numArgs; i++) {
      slang_operation_copy(inlined->children + i, args + i);
   }

   return inlined;
}


static void
slang_resolve_variable(slang_operation *oper)
{
   if (oper->type == SLANG_OPER_IDENTIFIER && !oper->var) {
      oper->var = _slang_locate_variable(oper->locals, oper->a_id, GL_TRUE);
   }
}


/**
 * Replace particular variables (SLANG_OPER_IDENTIFIER) with new expressions.
 */
static void
slang_substitute(slang_assemble_ctx *A, slang_operation *oper,
                 GLuint substCount, slang_variable **substOld,
		 slang_operation **substNew, GLboolean isLHS)
{
   switch (oper->type) {
   case SLANG_OPER_VARIABLE_DECL:
      {
         slang_variable *v = _slang_locate_variable(oper->locals,
                                                    oper->a_id, GL_TRUE);
         assert(v);
         if (v->initializer && oper->num_children == 0) {
            /* set child of oper to copy of initializer */
            oper->num_children = 1;
            oper->children = slang_operation_new(1);
            slang_operation_copy(&oper->children[0], v->initializer);
         }
         if (oper->num_children == 1) {
            /* the initializer */
            slang_substitute(A, &oper->children[0], substCount,
                             substOld, substNew, GL_FALSE);
         }
      }
      break;
   case SLANG_OPER_IDENTIFIER:
      assert(oper->num_children == 0);
      if (1/**!isLHS XXX FIX */) {
         slang_atom id = oper->a_id;
         slang_variable *v;
	 GLuint i;
         v = _slang_locate_variable(oper->locals, id, GL_TRUE);
	 if (!v) {
	    printf("var %s not found!\n", (char *) oper->a_id);
            _slang_print_var_scope(oper->locals, 6);

            abort();
	    break;
	 }

	 /* look for a substitution */
	 for (i = 0; i < substCount; i++) {
	    if (v == substOld[i]) {
               /* OK, replace this SLANG_OPER_IDENTIFIER with a new expr */
#if 0 /* DEBUG only */
	       if (substNew[i]->type == SLANG_OPER_IDENTIFIER) {
                  assert(substNew[i]->var);
                  assert(substNew[i]->var->a_name);
		  printf("Substitute %s with %s in id node %p\n",
			 (char*)v->a_name, (char*) substNew[i]->var->a_name,
			 (void*) oper);
               }
	       else {
		  printf("Substitute %s with %f in id node %p\n",
			 (char*)v->a_name, substNew[i]->literal[0],
			 (void*) oper);
               }
#endif
	       slang_operation_copy(oper, substNew[i]);
	       break;
	    }
	 }
      }
      break;

   case SLANG_OPER_RETURN:
      /* do return replacement here too */
      assert(oper->num_children == 0 || oper->num_children == 1);
      if (!_slang_is_noop(oper)) {
         /* replace:
          *   return expr;
          * with:
          *   __retVal = expr;
          *   return;
          * then do substitutions on the assignment.
          */
         slang_operation *blockOper, *assignOper, *returnOper;
         blockOper = slang_operation_new(1);
         blockOper->type = SLANG_OPER_BLOCK_NO_NEW_SCOPE;
         blockOper->num_children = 2;
         blockOper->locals->outer_scope = oper->locals->outer_scope;
         blockOper->children = slang_operation_new(2);
         assignOper = blockOper->children + 0;
         returnOper = blockOper->children + 1;

         assignOper->type = SLANG_OPER_ASSIGN;
         assignOper->num_children = 2;
         assignOper->locals->outer_scope = blockOper->locals;
         assignOper->children = slang_operation_new(2);
         assignOper->children[0].type = SLANG_OPER_IDENTIFIER;
         assignOper->children[0].a_id = slang_atom_pool_atom(A->atoms, "__retVal");
         assignOper->children[0].locals->outer_scope = assignOper->locals;

         slang_operation_copy(&assignOper->children[1],
                              &oper->children[0]);

         returnOper->type = SLANG_OPER_RETURN;
         assert(returnOper->num_children == 0);

         /* do substitutions on the "__retVal = expr" sub-tree */
         slang_substitute(A, assignOper,
                          substCount, substOld, substNew, GL_FALSE);

         /* install new code */
         slang_operation_copy(oper, blockOper);
         slang_operation_destruct(blockOper);
      }
      break;

   case SLANG_OPER_ASSIGN:
   case SLANG_OPER_SUBSCRIPT:
      /* special case:
       * child[0] can't have substitutions but child[1] can.
       */
      slang_substitute(A, &oper->children[0],
                       substCount, substOld, substNew, GL_TRUE);
      slang_substitute(A, &oper->children[1],
                       substCount, substOld, substNew, GL_FALSE);
      break;
   case SLANG_OPER_FIELD:
      /* XXX NEW - test */
      slang_substitute(A, &oper->children[0],
                       substCount, substOld, substNew, GL_TRUE);
      break;
   default:
      {
         GLuint i;
         for (i = 0; i < oper->num_children; i++) 
            slang_substitute(A, &oper->children[i],
                             substCount, substOld, substNew, GL_FALSE);
      }
   }
}



/**
 * Inline the given function call operation.
 * Return a new slang_operation that corresponds to the inlined code.
 */
static slang_operation *
slang_inline_function_call(slang_assemble_ctx * A, slang_function *fun,
			   slang_operation *oper, slang_operation *returnOper)
{
   typedef enum {
      SUBST = 1,
      COPY_IN,
      COPY_OUT
   } ParamMode;
   ParamMode *paramMode;
   const GLboolean haveRetValue = _slang_function_has_return_value(fun);
   const GLuint numArgs = oper->num_children;
   const GLuint totalArgs = numArgs + haveRetValue;
   slang_operation *args = oper->children;
   slang_operation *inlined, *top;
   slang_variable **substOld;
   slang_operation **substNew;
   GLuint substCount, numCopyIn, i;

   /*assert(oper->type == SLANG_OPER_CALL); (or (matrix) multiply, etc) */
   assert(fun->param_count == totalArgs);

   /* allocate temporary arrays */
   paramMode = (ParamMode *)
      _mesa_calloc(totalArgs * sizeof(ParamMode));
   substOld = (slang_variable **)
      _mesa_calloc(totalArgs * sizeof(slang_variable *));
   substNew = (slang_operation **)
      _mesa_calloc(totalArgs * sizeof(slang_operation *));

#if 0
   printf("Inline call to %s  (total vars=%d  nparams=%d)\n",
	  (char *) fun->header.a_name,
	  fun->parameters->num_variables, numArgs);
#endif

   if (haveRetValue && !returnOper) {
      /* Create 3-child comma sequence for inlined code:
       * child[0]:  declare __resultTmp
       * child[1]:  inlined function body
       * child[2]:  __resultTmp
       */
      slang_operation *commaSeq;
      slang_operation *declOper = NULL;
      slang_variable *resultVar;

      commaSeq = slang_operation_new(1);
      commaSeq->type = SLANG_OPER_SEQUENCE;
      assert(commaSeq->locals);
      commaSeq->locals->outer_scope = oper->locals->outer_scope;
      commaSeq->num_children = 3;
      commaSeq->children = slang_operation_new(3);
      /* allocate the return var */
      resultVar = slang_variable_scope_grow(commaSeq->locals);
      /*
      printf("Alloc __resultTmp in scope %p for retval of calling %s\n",
             (void*)commaSeq->locals, (char *) fun->header.a_name);
      */

      resultVar->a_name = slang_atom_pool_atom(A->atoms, "__resultTmp");
      resultVar->type = fun->header.type; /* XXX copy? */
      resultVar->isTemp = GL_TRUE;

      /* child[0] = __resultTmp declaration */
      declOper = &commaSeq->children[0];
      declOper->type = SLANG_OPER_VARIABLE_DECL;
      declOper->a_id = resultVar->a_name;
      declOper->locals->outer_scope = commaSeq->locals;

      /* child[1] = function body */
      inlined = &commaSeq->children[1];
      inlined->locals->outer_scope = commaSeq->locals;

      /* child[2] = __resultTmp reference */
      returnOper = &commaSeq->children[2];
      returnOper->type = SLANG_OPER_IDENTIFIER;
      returnOper->a_id = resultVar->a_name;
      returnOper->locals->outer_scope = commaSeq->locals;

      top = commaSeq;
   }
   else {
      top = inlined = slang_operation_new(1);
      /* XXXX this may be inappropriate!!!! */
      inlined->locals->outer_scope = oper->locals->outer_scope;
   }


   assert(inlined->locals);

   /* Examine the parameters, look for inout/out params, look for possible
    * substitutions, etc:
    *    param type      behaviour
    *     in             copy actual to local
    *     const in       substitute param with actual
    *     out            copy out
    */
   substCount = 0;
   for (i = 0; i < totalArgs; i++) {
      slang_variable *p = fun->parameters->variables[i];
      /*
      printf("Param %d: %s %s \n", i,
             slang_type_qual_string(p->type.qualifier),
	     (char *) p->a_name);
      */
      if (p->type.qualifier == SLANG_QUAL_INOUT ||
	  p->type.qualifier == SLANG_QUAL_OUT) {
	 /* an output param */
         slang_operation *arg;
         if (i < numArgs)
            arg = &args[i];
         else
            arg = returnOper;
	 paramMode[i] = SUBST;

	 if (arg->type == SLANG_OPER_IDENTIFIER)
            slang_resolve_variable(arg);

         /* replace parameter 'p' with argument 'arg' */
	 substOld[substCount] = p;
	 substNew[substCount] = arg; /* will get copied */
	 substCount++;
      }
      else if (p->type.qualifier == SLANG_QUAL_CONST) {
	 /* a constant input param */
	 if (args[i].type == SLANG_OPER_IDENTIFIER ||
	     args[i].type == SLANG_OPER_LITERAL_FLOAT) {
	    /* replace all occurances of this parameter variable with the
	     * actual argument variable or a literal.
	     */
	    paramMode[i] = SUBST;
            slang_resolve_variable(&args[i]);
	    substOld[substCount] = p;
	    substNew[substCount] = &args[i]; /* will get copied */
	    substCount++;
	 }
	 else {
	    paramMode[i] = COPY_IN;
	 }
      }
      else {
	 paramMode[i] = COPY_IN;
      }
      assert(paramMode[i]);
   }

   /* actual code inlining: */
   slang_operation_copy(inlined, fun->body);

   /*** XXX review this */
   assert(inlined->type = SLANG_OPER_BLOCK_NO_NEW_SCOPE);
   inlined->type = SLANG_OPER_BLOCK_NEW_SCOPE;

#if 0
   printf("======================= orig body code ======================\n");
   printf("=== params scope = %p\n", (void*) fun->parameters);
   slang_print_tree(fun->body, 8);
   printf("======================= copied code =========================\n");
   slang_print_tree(inlined, 8);
#endif

   /* do parameter substitution in inlined code: */
   slang_substitute(A, inlined, substCount, substOld, substNew, GL_FALSE);

#if 0
   printf("======================= subst code ==========================\n");
   slang_print_tree(inlined, 8);
   printf("=============================================================\n");
#endif

   /* New prolog statements: (inserted before the inlined code)
    * Copy the 'in' arguments.
    */
   numCopyIn = 0;
   for (i = 0; i < numArgs; i++) {
      if (paramMode[i] == COPY_IN) {
	 slang_variable *p = fun->parameters->variables[i];
	 /* declare parameter 'p' */
	 slang_operation *decl = slang_operation_insert(&inlined->num_children,
							&inlined->children,
							numCopyIn);
         /*
         printf("COPY_IN %s from expr\n", (char*)p->a_name);
         */
	 decl->type = SLANG_OPER_VARIABLE_DECL;
         assert(decl->locals);
         decl->locals->outer_scope = inlined->locals;
	 decl->a_id = p->a_name;
	 decl->num_children = 1;
	 decl->children = slang_operation_new(1);

         /* child[0] is the var's initializer */
         slang_operation_copy(&decl->children[0], args + i);

	 numCopyIn++;
      }
   }

   /* New epilog statements:
    * 1. Create end of function label to jump to from return statements.
    * 2. Copy the 'out' parameter vars
    */
   {
      slang_operation *lab = slang_operation_insert(&inlined->num_children,
                                                    &inlined->children,
                                                    inlined->num_children);
      lab->type = SLANG_OPER_LABEL;
      lab->label = A->CurFunction->end_label;
   }

   for (i = 0; i < totalArgs; i++) {
      if (paramMode[i] == COPY_OUT) {
	 const slang_variable *p = fun->parameters->variables[i];
	 /* actualCallVar = outParam */
	 /*if (i > 0 || !haveRetValue)*/
	 slang_operation *ass = slang_operation_insert(&inlined->num_children,
						       &inlined->children,
						       inlined->num_children);
	 ass->type = SLANG_OPER_ASSIGN;
	 ass->num_children = 2;
         ass->locals->outer_scope = inlined->locals;
	 ass->children = slang_operation_new(2);
	 ass->children[0] = args[i]; /*XXX copy */
	 ass->children[1].type = SLANG_OPER_IDENTIFIER;
	 ass->children[1].a_id = p->a_name;
         ass->children[1].locals->outer_scope = ass->locals;
      }
   }

   _mesa_free(paramMode);
   _mesa_free(substOld);
   _mesa_free(substNew);

#if 0
   printf("Done Inline call to %s  (total vars=%d  nparams=%d)\n",
	  (char *) fun->header.a_name,
	  fun->parameters->num_variables, numArgs);
   slang_print_tree(top, 0);
#endif
   return top;
}


static slang_ir_node *
_slang_gen_function_call(slang_assemble_ctx *A, slang_function *fun,
                         slang_operation *oper, slang_operation *dest)
{
   slang_ir_node *n;
   slang_operation *inlined;
   slang_function *prevFunc;

   prevFunc = A->CurFunction;
   A->CurFunction = fun;

   if (!A->CurFunction->end_label) {
      char name[200];
      sprintf(name, "__endOfFunc_%s_", (char *) A->CurFunction->header.a_name);
      A->CurFunction->end_label = _slang_label_new(name);
   }

   if (slang_is_asm_function(fun) && !dest) {
      /* assemble assembly function - tree style */
      inlined = slang_inline_asm_function(A, fun, oper);
   }
   else {
      /* non-assembly function */
      inlined = slang_inline_function_call(A, fun, oper, dest);
   }

   /* Replace the function call with the inlined block */
#if 0
   slang_operation_construct(oper);
   slang_operation_copy(oper, inlined);
#else
   *oper = *inlined;
#endif


#if 0
   assert(inlined->locals);
   printf("*** Inlined code for call to %s:\n",
          (char*) fun->header.a_name);
   slang_print_tree(oper, 10);
   printf("\n");
#endif

   n = _slang_gen_operation(A, oper);

   A->CurFunction->end_label = NULL; /* XXX delete/free? */

   A->CurFunction = prevFunc;

   return n;
}


static slang_asm_info *
slang_find_asm_info(const char *name)
{
   GLuint i;
   for (i = 0; AsmInfo[i].Name; i++) {
      if (_mesa_strcmp(AsmInfo[i].Name, name) == 0) {
         return AsmInfo + i;
      }
   }
   return NULL;
}


static GLuint
make_writemask(const char *field)
{
   GLuint mask = 0x0;
   while (*field) {
      switch (*field) {
      case 'x':
         mask |= WRITEMASK_X;
         break;
      case 'y':
         mask |= WRITEMASK_Y;
         break;
      case 'z':
         mask |= WRITEMASK_Z;
         break;
      case 'w':
         mask |= WRITEMASK_W;
         break;
      default:
         abort();
      }
      field++;
   }
   if (mask == 0x0)
      return WRITEMASK_XYZW;
   else
      return mask;
}


/**
 * Generate IR tree for an asm instruction/operation such as:
 *    __asm vec4_dot __retVal.x, v1, v2;
 */
static slang_ir_node *
_slang_gen_asm(slang_assemble_ctx *A, slang_operation *oper,
               slang_operation *dest)
{
   const slang_asm_info *info;
   slang_ir_node *kids[3], *n;
   GLuint j, firstOperand;

   assert(oper->type == SLANG_OPER_ASM);

   info = slang_find_asm_info((char *) oper->a_id);
   if (!info) {
      _mesa_problem(NULL, "undefined __asm function %s\n",
                    (char *) oper->a_id);
      assert(info);
   }
   assert(info->NumParams <= 3);

   if (info->NumParams == oper->num_children) {
      /* Storage for result is not specified.
       * Children[0], [1] are the operands.
       */
      firstOperand = 0;
   }
   else {
      /* Storage for result (child[0]) is specified.
       * Children[1], [2] are the operands.
       */
      firstOperand = 1;
   }

   /* assemble child(ren) */
   kids[0] = kids[1] = kids[2] = NULL;
   for (j = 0; j < info->NumParams; j++) {
      kids[j] = _slang_gen_operation(A, &oper->children[firstOperand + j]);
   }

   n = new_node3(info->Opcode, kids[0], kids[1], kids[2]);

   if (firstOperand) {
      /* Setup n->Store to be a particular location.  Otherwise, storage
       * for the result (a temporary) will be allocated later.
       */
      GLuint writemask = WRITEMASK_XYZW;
      slang_operation *dest_oper;
      slang_ir_node *n0;

      dest_oper = &oper->children[0];
      while (dest_oper->type == SLANG_OPER_FIELD) {
         /* writemask */
         writemask &= make_writemask((char*) dest_oper->a_id);
         dest_oper = &dest_oper->children[0];
      }

      n0 = _slang_gen_operation(A, dest_oper);
      assert(n0->Var);
      assert(n0->Store);
      assert(!n->Store);
      n->Store = n0->Store;
      n->Writemask = writemask;

      free(n0);
   }

   return n;
}


static void
print_funcs(struct slang_function_scope_ *scope, const char *name)
{
   GLuint i;
   for (i = 0; i < scope->num_functions; i++) {
      slang_function *f = &scope->functions[i];
      if (!name || strcmp(name, (char*) f->header.a_name) == 0)
          printf("  %s (%d args)\n", name, f->param_count);

   }
   if (scope->outer_scope)
      print_funcs(scope->outer_scope, name);
}


/**
 * Return first function in the scope that has the given name.
 * This is the function we'll try to call when there is no exact match
 * between function parameters and call arguments.
 *
 * XXX we should really create a list of candidate functions and try
 * all of them...
 */
static slang_function *
_slang_first_function(struct slang_function_scope_ *scope, const char *name)
{
   GLuint i;
   for (i = 0; i < scope->num_functions; i++) {
      slang_function *f = &scope->functions[i];
      if (strcmp(name, (char*) f->header.a_name) == 0)
         return f;
   }
   if (scope->outer_scope)
      return _slang_first_function(scope->outer_scope, name);
   return NULL;
}



/**
 * Assemble a function call, given a particular function name.
 * \param name  the function's name (operators like '*' are possible).
 */
static slang_ir_node *
_slang_gen_function_call_name(slang_assemble_ctx *A, const char *name,
                              slang_operation *oper, slang_operation *dest)
{
   slang_operation *params = oper->children;
   const GLuint param_count = oper->num_children;
   slang_atom atom;
   slang_function *fun;

   atom = slang_atom_pool_atom(A->atoms, name);
   if (atom == SLANG_ATOM_NULL)
      return NULL;

   /*
    * Use 'name' to find the function to call
    */
   fun = _slang_locate_function(A->space.funcs, atom, params, param_count,
				&A->space, A->atoms, A->log);
   if (!fun) {
      /* A function with exactly the right parameters/types was not found.
       * Try adapting the parameters.
       */
      fun = _slang_first_function(A->space.funcs, name);
      if (!_slang_adapt_call(oper, fun, &A->space, A->atoms, A->log)) {
         slang_info_log_error(A->log, "Undefined function '%s'", name);
         return NULL;
      }
      assert(fun);
   }

   return _slang_gen_function_call(A, fun, oper, dest);
}


static GLboolean
_slang_is_constant_cond(const slang_operation *oper, GLboolean *value)
{
   if (oper->type == SLANG_OPER_LITERAL_FLOAT ||
       oper->type == SLANG_OPER_LITERAL_INT ||
       oper->type == SLANG_OPER_LITERAL_BOOL) {
      if (oper->literal[0])
         *value = GL_TRUE;
      else
         *value = GL_FALSE;
      return GL_TRUE;
   }
   else if (oper->type == SLANG_OPER_EXPRESSION &&
            oper->num_children == 1) {
      return _slang_is_constant_cond(&oper->children[0], value);
   }
   return GL_FALSE;
}



/**
 * Generate loop code using high-level IR_LOOP instruction
 */
static slang_ir_node *
_slang_gen_while(slang_assemble_ctx * A, const slang_operation *oper)
{
   /*
    * LOOP:
    *    BREAK if !expr (child[0])
    *    body code (child[1])
    */
   slang_ir_node *prevLoop, *loop, *cond, *breakIf, *body;
   GLboolean isConst, constTrue;

   /* Check if loop condition is a constant */
   isConst = _slang_is_constant_cond(&oper->children[0], &constTrue);

   if (isConst && !constTrue) {
      /* loop is never executed! */
      return new_node0(IR_NOP);
   }

   loop = new_loop(NULL);

   /* save old, push new loop */
   prevLoop = A->CurLoop;
   A->CurLoop = loop;

   cond = new_cond(_slang_gen_operation(A, &oper->children[0]));
   if (isConst && constTrue) {
      /* while(nonzero constant), no conditional break */
      breakIf = NULL;
   }
   else {
      breakIf = new_break_if(A->CurLoop, cond, GL_FALSE);
   }
   body = _slang_gen_operation(A, &oper->children[1]);
   loop->Children[0] = new_seq(breakIf, body);

   /* Do infinite loop detection */
   if (loop->BranchNode == 0 && isConst && constTrue) {
      /* infinite loop detected */
      A->CurLoop = prevLoop; /* clean-up */
      slang_info_log_error(A->log, "Infinite loop detected!");
      return NULL;
   }

   /* pop loop, restore prev */
   A->CurLoop = prevLoop;

   return loop;
}


/**
 * Generate IR tree for a do-while loop using high-level LOOP, IF instructions.
 */
static slang_ir_node *
_slang_gen_do(slang_assemble_ctx * A, const slang_operation *oper)
{
   /*
    * LOOP:
    *    body code (child[0])
    *    BREAK if !expr (child[1])
    */
   slang_ir_node *prevLoop, *loop, *cond, *breakIf, *body;
   GLboolean isConst, constTrue;

   /* Check if loop condition is a constant */
   isConst = _slang_is_constant_cond(&oper->children[0], &constTrue);

   loop = new_loop(NULL);

   /* save old, push new loop */
   prevLoop = A->CurLoop;
   A->CurLoop = loop;

   body = _slang_gen_operation(A, &oper->children[0]);
   cond = new_cond(_slang_gen_operation(A, &oper->children[1]));
   if (isConst && constTrue) {
      /* while(nonzero constant), no conditional break */
      breakIf = NULL;
   }
   else {
      breakIf = new_break_if(A->CurLoop, cond, GL_FALSE);
   }
   loop->Children[0] = new_seq(body, breakIf);

   /* pop loop, restore prev */
   A->CurLoop = prevLoop;

   return loop;
}


/**
 * Generate for-loop using high-level IR_LOOP instruction.
 */
static slang_ir_node *
_slang_gen_for(slang_assemble_ctx * A, const slang_operation *oper)
{
   /*
    * init (child[0])
    * LOOP:
    *    BREAK if !expr (child[1])
    *    body code (child[3])
    *    incr code (child[2])   // XXX continue here
    */
   slang_ir_node *prevLoop, *loop, *cond, *breakIf, *body, *init, *incr;

   init = _slang_gen_operation(A, &oper->children[0]);
   loop = new_loop(NULL);

   /* save old, push new loop */
   prevLoop = A->CurLoop;
   A->CurLoop = loop;

   cond = new_cond(_slang_gen_operation(A, &oper->children[1]));
   breakIf = new_break_if(A->CurLoop, cond, GL_FALSE);
   body = _slang_gen_operation(A, &oper->children[3]);
   incr = _slang_gen_operation(A, &oper->children[2]);
   loop->Children[0] = new_seq(breakIf,
                               new_seq(body, incr));

   /* pop loop, restore prev */
   A->CurLoop = prevLoop;

   return new_seq(init, loop);
}


/**
 * Determine if the given operation is of a specific type.
 */
static GLboolean
is_operation_type(const const slang_operation *oper, slang_operation_type type)
{
   if (oper->type == type)
      return GL_TRUE;
   else if ((oper->type == SLANG_OPER_BLOCK_NEW_SCOPE ||
             oper->type == SLANG_OPER_BLOCK_NO_NEW_SCOPE) &&
            oper->num_children == 1)
      return is_operation_type(&oper->children[0], type);
   else
      return GL_FALSE;
}


/**
 * Generate IR tree for an if/then/else conditional using high-level
 * IR_IF instruction.
 */
static slang_ir_node *
_slang_gen_hl_if(slang_assemble_ctx * A, const slang_operation *oper)
{
   /*
    * eval expr (child[0]), updating condcodes
    * IF expr THEN
    *    if-body code
    * ELSE
    *    else-body code
    * ENDIF
    */
   const GLboolean haveElseClause = !_slang_is_noop(&oper->children[2]);
   slang_ir_node *ifNode, *cond, *ifBody, *elseBody;

   cond = _slang_gen_operation(A, &oper->children[0]);
   cond = new_cond(cond);

   if (is_operation_type(&oper->children[1], SLANG_OPER_BREAK)) {
      /* Special case: generate a conditional break */
      ifBody = new_break_if(A->CurLoop, cond, GL_TRUE);
      if (haveElseClause) {
         elseBody = _slang_gen_operation(A, &oper->children[2]);
         return new_seq(ifBody, elseBody);
      }
      return ifBody;
   }
   else if (is_operation_type(&oper->children[1], SLANG_OPER_CONTINUE)) {
      /* Special case: generate a conditional break */
      ifBody = new_cont_if(A->CurLoop, cond, GL_TRUE);
      if (haveElseClause) {
         elseBody = _slang_gen_operation(A, &oper->children[2]);
         return new_seq(ifBody, elseBody);
      }
      return ifBody;
   }
   else {
      /* general case */
      ifBody = _slang_gen_operation(A, &oper->children[1]);
      if (haveElseClause)
         elseBody = _slang_gen_operation(A, &oper->children[2]);
      else
         elseBody = NULL;
      ifNode = new_if(cond, ifBody, elseBody);
      return ifNode;
   }
}



/**
 * Generate IR node for storage of a temporary of given size.
 */
static slang_ir_node *
_slang_gen_temporary(GLint size)
{
   slang_ir_storage *store;
   slang_ir_node *n;

   store = _slang_new_ir_storage(PROGRAM_TEMPORARY, -1, size);
   if (store) {
      n = new_node0(IR_VAR_DECL);
      if (n) {
         n->Store = store;
      }
      else {
         free(store);
      }
   }
   return n;
}


/**
 * Generate IR node for allocating/declaring a variable.
 */
static slang_ir_node *
_slang_gen_var_decl(slang_assemble_ctx *A, slang_variable *var)
{
   slang_ir_node *n;
   assert(!is_sampler_type(&var->type));
   n = new_node0(IR_VAR_DECL);
   if (n) {
      _slang_attach_storage(n, var);

      assert(var->aux);
      assert(n->Store == var->aux);
      assert(n->Store);
      assert(n->Store->Index < 0);

      n->Store->File = PROGRAM_TEMPORARY;
      n->Store->Size = _slang_sizeof_type_specifier(&n->Var->type.specifier);
      assert(n->Store->Size > 0);
   }
   return n;
}


/**
 * Generate code for a selection expression:   b ? x : y
 * XXX in some cases we could implement a selection expression
 * with an LRP instruction (use the boolean as the interpolant).
 */
static slang_ir_node *
_slang_gen_select(slang_assemble_ctx *A, slang_operation *oper)
{
   slang_label *altLabel, *endLabel;
   slang_ir_node *altLab, *endLab;
   slang_ir_node *tree, *tmpDecl, *tmpVar, *cond, *cjump, *jump;
   slang_ir_node *bodx, *body, *assignx, *assigny;
   slang_typeinfo type;
   int size;

   assert(oper->type == SLANG_OPER_SELECT);
   assert(oper->num_children == 3);

   altLabel = _slang_label_new("selectAlt");
   endLabel = _slang_label_new("selectEnd");

   /* size of x or y's type */
   slang_typeinfo_construct(&type);
   _slang_typeof_operation(A, &oper->children[1], &type);
   size = _slang_sizeof_type_specifier(&type.spec);
   assert(size > 0);

   /* temporary var */
   tmpDecl = _slang_gen_temporary(size);

   /* eval condition */
   cond = _slang_gen_operation(A, &oper->children[0]);
   cond = new_cond(cond);
   tree = new_seq(tmpDecl, cond);

   /* jump if false to "alt" label */
   cjump = new_cjump(altLabel, 0);
   tree = new_seq(tree, cjump);

   /* evaluate child 1 (x) and assign to tmp */
   tmpVar = new_node0(IR_VAR);
   tmpVar->Store = tmpDecl->Store;
   body = _slang_gen_operation(A, &oper->children[1]);
   assigny = new_node2(IR_MOVE, tmpVar, body);
   tree = new_seq(tree, assigny);

   /* jump to "end" label */
   jump = new_jump(endLabel);
   tree = new_seq(tree, jump);

   /* "alt" label */
   altLab = new_label(altLabel);
   tree = new_seq(tree, altLab);

   /* evaluate child 2 (y) and assign to tmp */
   tmpVar = new_node0(IR_VAR);
   tmpVar->Store = tmpDecl->Store;
   bodx = _slang_gen_operation(A, &oper->children[2]);
   assignx = new_node2(IR_MOVE, tmpVar, bodx);
   tree = new_seq(tree, assignx);

   /* "end" label */
   endLab = new_label(endLabel);
   tree = new_seq(tree, endLab);
   
   /* tmp var value */
   tmpVar = new_node0(IR_VAR);
   tmpVar->Store = tmpDecl->Store;
   tree = new_seq(tree, tmpVar);

   return tree;
}


/**
 * Generate code for &&.
 */
static slang_ir_node *
_slang_gen_logical_and(slang_assemble_ctx *A, slang_operation *oper)
{
   /* rewrite "a && b" as  "a ? b : false" */
   slang_operation *select;
   slang_ir_node *n;

   select = slang_operation_new(1);
   select->type = SLANG_OPER_SELECT;
   select->num_children = 3;
   select->children = slang_operation_new(3);

   slang_operation_copy(&select->children[0], &oper->children[0]);
   slang_operation_copy(&select->children[1], &oper->children[1]);
   select->children[2].type = SLANG_OPER_LITERAL_BOOL;
   ASSIGN_4V(select->children[2].literal, 0, 0, 0, 0);
   select->children[2].literal_size = 2;

   n = _slang_gen_select(A, select);

   /* xxx wrong */
   free(select->children);
   free(select);

   return n;
}


/**
 * Generate code for ||.
 */
static slang_ir_node *
_slang_gen_logical_or(slang_assemble_ctx *A, slang_operation *oper)
{
   /* rewrite "a || b" as  "a ? true : b" */
   slang_operation *select;
   slang_ir_node *n;

   select = slang_operation_new(1);
   select->type = SLANG_OPER_SELECT;
   select->num_children = 3;
   select->children = slang_operation_new(3);

   slang_operation_copy(&select->children[0], &oper->children[0]);
   select->children[1].type = SLANG_OPER_LITERAL_BOOL;
   ASSIGN_4V(select->children[2].literal, 1, 1, 1, 1);
   slang_operation_copy(&select->children[2], &oper->children[1]);
   select->children[2].literal_size = 2;

   n = _slang_gen_select(A, select);

   /* xxx wrong */
   free(select->children);
   free(select);

   return n;
}


/**
 * Generate IR tree for a return statement.
 */
static slang_ir_node *
_slang_gen_return(slang_assemble_ctx * A, slang_operation *oper)
{
   if (oper->num_children == 0 ||
       (oper->num_children == 1 &&
        oper->children[0].type == SLANG_OPER_VOID)) {
      /* Convert from:
       *   return;
       * To:
       *   goto __endOfFunction;
       */
      slang_ir_node *n;
      slang_operation gotoOp;
      slang_operation_construct(&gotoOp);
      gotoOp.type = SLANG_OPER_GOTO;
      gotoOp.label = A->CurFunction->end_label;

      /* assemble the new code */
      n = _slang_gen_operation(A, &gotoOp);
      /* destroy temp code */
      slang_operation_destruct(&gotoOp);
      return n;
   }
   else {
      /*
       * Convert from:
       *   return expr;
       * To:
       *   __retVal = expr;
       *   goto __endOfFunction;
       */
      slang_operation *block, *assign, *jump;
      slang_atom a_retVal;
      slang_ir_node *n;

      a_retVal = slang_atom_pool_atom(A->atoms, "__retVal");
      assert(a_retVal);

#if 1 /* DEBUG */
      {
         slang_variable *v
            = _slang_locate_variable(oper->locals, a_retVal, GL_TRUE);
         assert(v);
      }
#endif

      block = slang_operation_new(1);
      block->type = SLANG_OPER_BLOCK_NO_NEW_SCOPE;
      assert(block->locals);
      block->locals->outer_scope = oper->locals->outer_scope;
      block->num_children = 2;
      block->children = slang_operation_new(2);

      /* child[0]: __retVal = expr; */
      assign = &block->children[0];
      assign->type = SLANG_OPER_ASSIGN;
      assign->locals->outer_scope = block->locals;
      assign->num_children = 2;
      assign->children = slang_operation_new(2);
      /* lhs (__retVal) */
      assign->children[0].type = SLANG_OPER_IDENTIFIER;
      assign->children[0].a_id = a_retVal;
      assign->children[0].locals->outer_scope = assign->locals;
      /* rhs (expr) */
      /* XXX we might be able to avoid this copy someday */
      slang_operation_copy(&assign->children[1], &oper->children[0]);

      /* child[1]: goto __endOfFunction */
      jump = &block->children[1];
      jump->type = SLANG_OPER_GOTO;
      assert(A->CurFunction->end_label);
      /* XXX don't call function? */
      jump->label = A->CurFunction->end_label;

#if 0 /* debug */
      printf("NEW RETURN:\n");
      slang_print_tree(block, 0);
#endif

      /* assemble the new code */
      n = _slang_gen_operation(A, block);
      slang_operation_delete(block);
      return n;
   }
}


/**
 * Generate IR tree for a variable declaration.
 */
static slang_ir_node *
_slang_gen_declaration(slang_assemble_ctx *A, slang_operation *oper)
{
   slang_ir_node *n;
   slang_ir_node *varDecl;
   slang_variable *v;
   const char *varName = (char *) oper->a_id;

   assert(oper->num_children == 0 || oper->num_children == 1);

   v = _slang_locate_variable(oper->locals, oper->a_id, GL_TRUE);
   assert(v);

   varDecl = _slang_gen_var_decl(A, v);

   if (oper->num_children > 0) {
      /* child is initializer */
      slang_ir_node *var, *init, *rhs;
      assert(oper->num_children == 1);
      var = new_var(A, oper, oper->a_id);
      if (!var) {
         slang_info_log_error(A->log, "undefined variable '%s'", varName);
         return NULL;
      }
      /* XXX make copy of this initializer? */
      rhs = _slang_gen_operation(A, &oper->children[0]);
      assert(rhs);
      init = new_node2(IR_MOVE, var, rhs);
      /*assert(rhs->Opcode != IR_SEQ);*/
      n = new_seq(varDecl, init);
   }
   else if (v->initializer) {
      slang_ir_node *var, *init, *rhs;
      var = new_var(A, oper, oper->a_id);
      if (!var) {
         slang_info_log_error(A->log, "undefined variable '%s'", varName);
         return NULL;
      }
#if 0
      /* XXX make copy of this initializer? */
      {
         slang_operation dup;
         slang_operation_construct(&dup);
         slang_operation_copy(&dup, v->initializer);
         _slang_simplify(&dup, &A->space, A->atoms); 
         rhs = _slang_gen_operation(A, &dup);
      }
#else
      _slang_simplify(v->initializer, &A->space, A->atoms); 
      rhs = _slang_gen_operation(A, v->initializer);
#endif
      assert(rhs);
      init = new_node2(IR_MOVE, var, rhs);
      /*
        assert(rhs->Opcode != IR_SEQ);
      */
      n = new_seq(varDecl, init);
   }
   else {
      n = varDecl;
   }
   return n;
}


/**
 * Generate IR tree for a variable (such as in an expression).
 */
static slang_ir_node *
_slang_gen_variable(slang_assemble_ctx * A, slang_operation *oper)
{
   /* If there's a variable associated with this oper (from inlining)
    * use it.  Otherwise, use the oper's var id.
    */
   slang_atom aVar = oper->var ? oper->var->a_name : oper->a_id;
   slang_ir_node *n = new_var(A, oper, aVar);
   if (!n) {
      slang_info_log_error(A->log, "undefined variable '%s'", (char *) aVar);
      return NULL;
   }
   return n;
}


/**
 * Some write-masked assignments are simple, but others are hard.
 * Simple example:
 *    vec3 v;
 *    v.xy = vec2(a, b);
 * Hard example:
 *    vec3 v;
 *    v.yz = vec2(a, b);
 * this would have to be transformed/swizzled into:
 *    v.yz = vec2(a, b).*xy*         (* = don't care)
 * Instead, we'll effectively do this:
 *    v.y = vec2(a, b).xxxx;
 *    v.z = vec2(a, b).yyyy;
 *
 */
static GLboolean
_slang_simple_writemask(GLuint writemask)
{
   switch (writemask) {
   case WRITEMASK_X:
   case WRITEMASK_Y:
   case WRITEMASK_Z:
   case WRITEMASK_W:
   case WRITEMASK_XY:
   case WRITEMASK_XYZ:
   case WRITEMASK_XYZW:
      return GL_TRUE;
   default:
      return GL_FALSE;
   }
}


/**
 * Convert the given swizzle into a writemask.  In some cases this
 * is trivial, in other cases, we'll need to also swizzle the right
 * hand side to put components in the right places.
 * \param swizzle  the incoming swizzle
 * \param writemaskOut  returns the writemask
 * \param swizzleOut  swizzle to apply to the right-hand-side
 * \return GL_FALSE for simple writemasks, GL_TRUE for non-simple
 */
static GLboolean
swizzle_to_writemask(GLuint swizzle,
                     GLuint *writemaskOut, GLuint *swizzleOut)
{
   GLuint mask = 0x0, newSwizzle[4];
   GLint i, size;

   /* make new dst writemask, compute size */
   for (i = 0; i < 4; i++) {
      const GLuint swz = GET_SWZ(swizzle, i);
      if (swz == SWIZZLE_NIL) {
         /* end */
         break;
      }
      assert(swz >= 0 && swz <= 3);
      mask |= (1 << swz);
   }
   assert(mask <= 0xf);
   size = i;  /* number of components in mask/swizzle */

   *writemaskOut = mask;

   /* make new src swizzle, by inversion */
   for (i = 0; i < 4; i++) {
      newSwizzle[i] = i; /*identity*/
   }
   for (i = 0; i < size; i++) {
      const GLuint swz = GET_SWZ(swizzle, i);
      newSwizzle[swz] = i;
   }
   *swizzleOut = MAKE_SWIZZLE4(newSwizzle[0],
                               newSwizzle[1],
                               newSwizzle[2],
                               newSwizzle[3]);

   if (_slang_simple_writemask(mask)) {
      if (size >= 1)
         assert(GET_SWZ(*swizzleOut, 0) == SWIZZLE_X);
      if (size >= 2)
         assert(GET_SWZ(*swizzleOut, 1) == SWIZZLE_Y);
      if (size >= 3)
         assert(GET_SWZ(*swizzleOut, 2) == SWIZZLE_Z);
      if (size >= 4)
         assert(GET_SWZ(*swizzleOut, 3) == SWIZZLE_W);
      return GL_TRUE;
   }
   else
      return GL_FALSE;
}


static slang_ir_node *
_slang_gen_swizzle(slang_ir_node *child, GLuint swizzle)
{
   slang_ir_node *n = new_node1(IR_SWIZZLE, child);
   if (n) {
      n->Store = _slang_new_ir_storage(PROGRAM_UNDEFINED, -1, -1);
      n->Store->Swizzle = swizzle;
   }
   return n;
}


/**
 * Generate IR tree for an assignment (=).
 */
static slang_ir_node *
_slang_gen_assignment(slang_assemble_ctx * A, slang_operation *oper)
{
   if (oper->children[0].type == SLANG_OPER_IDENTIFIER &&
       oper->children[1].type == SLANG_OPER_CALL) {
      /* Special case of:  x = f(a, b)
       * Replace with f(a, b, x)  (where x == hidden __retVal out param)
       *
       * XXX this could be even more effective if we could accomodate
       * cases such as "v.x = f();"  - would help with typical vertex
       * transformation.
       */
      slang_ir_node *n;
      n = _slang_gen_function_call_name(A,
                                      (const char *) oper->children[1].a_id,
                                      &oper->children[1], &oper->children[0]);
      return n;
   }
   else {
      slang_ir_node *n, *lhs, *rhs;
      lhs = _slang_gen_operation(A, &oper->children[0]);
      rhs = _slang_gen_operation(A, &oper->children[1]);
      if (lhs && rhs) {
         /* convert lhs swizzle into writemask */
         GLuint writemask, newSwizzle;
         if (!swizzle_to_writemask(lhs->Store->Swizzle,
                                   &writemask, &newSwizzle)) {
            /* Non-simple writemask, need to swizzle right hand side in
             * order to put components into the right place.
             */
            rhs = _slang_gen_swizzle(rhs, newSwizzle);
         }
         n = new_node2(IR_MOVE, lhs, rhs);
         n->Writemask = writemask;
         return n;
      }
      else {
         return NULL;
      }
   }
}


/**
 * Generate IR tree for referencing a field in a struct (or basic vector type)
 */
static slang_ir_node *
_slang_gen_field(slang_assemble_ctx * A, slang_operation *oper)
{
   slang_typeinfo ti;

   slang_typeinfo_construct(&ti);
   _slang_typeof_operation(A, &oper->children[0], &ti);

   if (_slang_type_is_vector(ti.spec.type)) {
      /* the field should be a swizzle */
      const GLuint rows = _slang_type_dim(ti.spec.type);
      slang_swizzle swz;
      slang_ir_node *n;
      GLuint swizzle;
      if (!_slang_is_swizzle((char *) oper->a_id, rows, &swz)) {
         slang_info_log_error(A->log, "Bad swizzle");
      }
      swizzle = MAKE_SWIZZLE4(swz.swizzle[0],
                              swz.swizzle[1],
                              swz.swizzle[2],
                              swz.swizzle[3]);

      n = _slang_gen_operation(A, &oper->children[0]);
      /* create new parent node with swizzle */
      n = _slang_gen_swizzle(n, swizzle);
      return n;
   }
   else if (ti.spec.type == SLANG_SPEC_FLOAT) {
      const GLuint rows = 1;
      slang_swizzle swz;
      slang_ir_node *n;
      GLuint swizzle;
      if (!_slang_is_swizzle((char *) oper->a_id, rows, &swz)) {
         slang_info_log_error(A->log, "Bad swizzle");
      }
      swizzle = MAKE_SWIZZLE4(swz.swizzle[0],
                              swz.swizzle[1],
                              swz.swizzle[2],
                              swz.swizzle[3]);
      n = _slang_gen_operation(A, &oper->children[0]);
      /* create new parent node with swizzle */
      n = _slang_gen_swizzle(n, swizzle);
      return n;
   }
   else {
      /* the field is a structure member (base.field) */
      /* oper->children[0] is the base */
      /* oper->a_id is the field name */
      slang_ir_node *base, *n;
      GLint size = 4; /* XXX fix? */

      base = _slang_gen_operation(A, &oper->children[0]);

      n = new_node1(IR_FIELD, base);
      if (n) {
         n->Field = (char *) oper->a_id;
         n->Store = _slang_new_ir_storage(base->Store->File,
                                          base->Store->Index,
                                          size);
      }
      return n;

#if 0
      _mesa_problem(NULL, "glsl structs/fields not supported yet");
      return NULL;
#endif
   }
}


/**
 * Gen code for array indexing.
 */
static slang_ir_node *
_slang_gen_subscript(slang_assemble_ctx * A, slang_operation *oper)
{
   slang_typeinfo array_ti;

   /* get array's type info */
   slang_typeinfo_construct(&array_ti);
   _slang_typeof_operation(A, &oper->children[0], &array_ti);

   if (_slang_type_is_vector(array_ti.spec.type)) {
      /* indexing a simple vector type: "vec4 v; v[0]=p;" */
      /* translate the index into a swizzle/writemask: "v.x=p" */
      const GLuint max = _slang_type_dim(array_ti.spec.type);
      GLint index;
      slang_ir_node *n;

      index = (GLint) oper->children[1].literal[0];
      if (oper->children[1].type != SLANG_OPER_LITERAL_INT ||
          index >= max) {
         slang_info_log_error(A->log, "Invalid array index for vector type");
      }

      n = _slang_gen_operation(A, &oper->children[0]);
      if (n) {
         /* use swizzle to access the element */
         GLuint swizzle = MAKE_SWIZZLE4(SWIZZLE_X + index,
                                        SWIZZLE_NIL,
                                        SWIZZLE_NIL,
                                        SWIZZLE_NIL);
         n = _slang_gen_swizzle(n, swizzle);
         /*n->Store = _slang_clone_ir_storage_swz(n->Store, */
         n->Writemask = WRITEMASK_X << index;
      }
      return n;
   }
   else {
      /* conventional array */
      slang_typeinfo elem_ti;
      slang_ir_node *elem, *array, *index;
      GLint elemSize;

      /* size of array element */
      slang_typeinfo_construct(&elem_ti);
      _slang_typeof_operation(A, oper, &elem_ti);
      elemSize = _slang_sizeof_type_specifier(&elem_ti.spec);
      assert(elemSize >= 1);

      array = _slang_gen_operation(A, &oper->children[0]);
      index = _slang_gen_operation(A, &oper->children[1]);
      if (array && index) {
         elem = new_node2(IR_ELEMENT, array, index);
         elem->Store = _slang_new_ir_storage(array->Store->File,
                                             array->Store->Index,
                                             elemSize);
         /* XXX try to do some array bounds checking here */
         return elem;
      }
      else {
         return NULL;
      }
   }
}



/**
 * Generate IR tree for a slang_operation (AST node)
 */
static slang_ir_node *
_slang_gen_operation(slang_assemble_ctx * A, slang_operation *oper)
{
   switch (oper->type) {
   case SLANG_OPER_BLOCK_NEW_SCOPE:
      {
         slang_ir_node *n;

         _slang_push_var_table(A->vartable);

         oper->type = SLANG_OPER_BLOCK_NO_NEW_SCOPE; /* temp change */
         n = _slang_gen_operation(A, oper);
         oper->type = SLANG_OPER_BLOCK_NEW_SCOPE; /* restore */

         _slang_pop_var_table(A->vartable);

         if (n)
            n = new_node1(IR_SCOPE, n);
         return n;
      }
      break;

   case SLANG_OPER_BLOCK_NO_NEW_SCOPE:
      /* list of operations */
      if (oper->num_children > 0)
      {
         slang_ir_node *n, *tree = NULL;
         GLuint i;

         for (i = 0; i < oper->num_children; i++) {
            n = _slang_gen_operation(A, &oper->children[i]);
            if (!n) {
               _slang_free_ir_tree(tree);
               return NULL; /* error must have occured */
            }
            tree = tree ? new_seq(tree, n) : n;
         }

#if 00
         if (oper->locals->num_variables > 0) {
            int i;
            /*
            printf("\n****** Deallocate vars in scope!\n");
            */
            for (i = 0; i < oper->locals->num_variables; i++) {
               slang_variable *v = oper->locals->variables + i;
               if (v->aux) {
                  slang_ir_storage *store = (slang_ir_storage *) v->aux;
                  /*
                  printf("  Deallocate var %s\n", (char*) v->a_name);
                  */
                  assert(store->File == PROGRAM_TEMPORARY);
                  assert(store->Index >= 0);
                  _slang_free_temp(A->vartable, store->Index, store->Size);
               }
            }
         }
#endif
         return tree;
      }
      break;
   case SLANG_OPER_EXPRESSION:
      return _slang_gen_operation(A, &oper->children[0]);

   case SLANG_OPER_FOR:
      return _slang_gen_for(A, oper);
   case SLANG_OPER_DO:
      return _slang_gen_do(A, oper);
   case SLANG_OPER_WHILE:
      return _slang_gen_while(A, oper);
   case SLANG_OPER_BREAK:
      if (!A->CurLoop) {
         slang_info_log_error(A->log, "'break' not in loop");
      }
      return new_break(A->CurLoop);
   case SLANG_OPER_CONTINUE:
      if (!A->CurLoop) {
         slang_info_log_error(A->log, "'continue' not in loop");
      }
      return new_cont(A->CurLoop);
   case SLANG_OPER_DISCARD:
      return new_node0(IR_KILL);

   case SLANG_OPER_EQUAL:
      return new_node2(IR_SEQUAL,
                      _slang_gen_operation(A, &oper->children[0]),
                      _slang_gen_operation(A, &oper->children[1]));
   case SLANG_OPER_NOTEQUAL:
      return new_node2(IR_SNEQUAL,
                      _slang_gen_operation(A, &oper->children[0]),
                      _slang_gen_operation(A, &oper->children[1]));
   case SLANG_OPER_GREATER:
      return new_node2(IR_SGT,
                      _slang_gen_operation(A, &oper->children[0]),
                      _slang_gen_operation(A, &oper->children[1]));
   case SLANG_OPER_LESS:
      /* child[0] < child[1]  ---->   child[1] > child[0] */
      return new_node2(IR_SGT,
                      _slang_gen_operation(A, &oper->children[1]),
                      _slang_gen_operation(A, &oper->children[0]));
   case SLANG_OPER_GREATERequal:
      return new_node2(IR_SGE,
                      _slang_gen_operation(A, &oper->children[0]),
                      _slang_gen_operation(A, &oper->children[1]));
   case SLANG_OPER_LESSequal:
      /* child[0] <= child[1]  ---->   child[1] >= child[0] */
      return new_node2(IR_SGE,
                      _slang_gen_operation(A, &oper->children[1]),
                      _slang_gen_operation(A, &oper->children[0]));
   case SLANG_OPER_ADD:
      {
	 slang_ir_node *n;
         assert(oper->num_children == 2);
	 n = _slang_gen_function_call_name(A, "+", oper, NULL);
	 return n;
      }
   case SLANG_OPER_SUBTRACT:
      {
	 slang_ir_node *n;
         assert(oper->num_children == 2);
	 n = _slang_gen_function_call_name(A, "-", oper, NULL);
	 return n;
      }
   case SLANG_OPER_MULTIPLY:
      {
	 slang_ir_node *n;
         assert(oper->num_children == 2);
         n = _slang_gen_function_call_name(A, "*", oper, NULL);
	 return n;
      }
   case SLANG_OPER_DIVIDE:
      {
         slang_ir_node *n;
         assert(oper->num_children == 2);
	 n = _slang_gen_function_call_name(A, "/", oper, NULL);
	 return n;
      }
   case SLANG_OPER_MINUS:
      {
         slang_ir_node *n;
         assert(oper->num_children == 1);
	 n = _slang_gen_function_call_name(A, "-", oper, NULL);
	 return n;
      }
   case SLANG_OPER_PLUS:
      /* +expr   --> do nothing */
      return _slang_gen_operation(A, &oper->children[0]);
   case SLANG_OPER_VARIABLE_DECL:
      return _slang_gen_declaration(A, oper);
   case SLANG_OPER_ASSIGN:
      return _slang_gen_assignment(A, oper);
   case SLANG_OPER_ADDASSIGN:
      {
	 slang_ir_node *n;
         assert(oper->num_children == 2);
	 n = _slang_gen_function_call_name(A, "+=", oper, &oper->children[0]);
	 return n;
      }
   case SLANG_OPER_SUBASSIGN:
      {
	 slang_ir_node *n;
         assert(oper->num_children == 2);
	 n = _slang_gen_function_call_name(A, "-=", oper, &oper->children[0]);
	 return n;
      }
      break;
   case SLANG_OPER_MULASSIGN:
      {
	 slang_ir_node *n;
         assert(oper->num_children == 2);
	 n = _slang_gen_function_call_name(A, "*=", oper, &oper->children[0]);
	 return n;
      }
   case SLANG_OPER_DIVASSIGN:
      {
	 slang_ir_node *n;
         assert(oper->num_children == 2);
	 n = _slang_gen_function_call_name(A, "/=", oper, &oper->children[0]);
	 return n;
      }
   case SLANG_OPER_LOGICALAND:
      {
	 slang_ir_node *n;
         assert(oper->num_children == 2);
	 n = _slang_gen_logical_and(A, oper);
	 return n;
      }
   case SLANG_OPER_LOGICALOR:
      {
	 slang_ir_node *n;
         assert(oper->num_children == 2);
	 n = _slang_gen_logical_or(A, oper);
	 return n;
      }
   case SLANG_OPER_LOGICALXOR:
      {
	 slang_ir_node *n;
         assert(oper->num_children == 2);
	 n = _slang_gen_function_call_name(A, "__logicalXor", oper, NULL);
	 return n;
      }
   case SLANG_OPER_NOT:
      {
	 slang_ir_node *n;
         assert(oper->num_children == 1);
	 n = _slang_gen_function_call_name(A, "__logicalNot", oper, NULL);
	 return n;
      }

   case SLANG_OPER_SELECT:  /* b ? x : y */
      {
	 slang_ir_node *n;
         assert(oper->num_children == 3);
	 n = _slang_gen_select(A, oper);
	 return n;
      }

   case SLANG_OPER_ASM:
      return _slang_gen_asm(A, oper, NULL);
   case SLANG_OPER_CALL:
      return _slang_gen_function_call_name(A, (const char *) oper->a_id,
                                           oper, NULL);
   case SLANG_OPER_RETURN:
      return _slang_gen_return(A, oper);
   case SLANG_OPER_GOTO:
      return new_jump(oper->label);
   case SLANG_OPER_LABEL:
      return new_label(oper->label);
   case SLANG_OPER_IDENTIFIER:
      return _slang_gen_variable(A, oper);
   case SLANG_OPER_IF:
      return _slang_gen_hl_if(A, oper);
   case SLANG_OPER_FIELD:
      return _slang_gen_field(A, oper);
   case SLANG_OPER_SUBSCRIPT:
      return _slang_gen_subscript(A, oper);
   case SLANG_OPER_LITERAL_FLOAT:
      /* fall-through */
   case SLANG_OPER_LITERAL_INT:
      /* fall-through */
   case SLANG_OPER_LITERAL_BOOL:
      return new_float_literal(oper->literal);

   case SLANG_OPER_POSTINCREMENT:   /* var++ */
      {
	 slang_ir_node *n;
         assert(oper->num_children == 1);
	 n = _slang_gen_function_call_name(A, "__postIncr", oper, NULL);
	 return n;
      }
   case SLANG_OPER_POSTDECREMENT:   /* var-- */
      {
	 slang_ir_node *n;
         assert(oper->num_children == 1);
	 n = _slang_gen_function_call_name(A, "__postDecr", oper, NULL);
	 return n;
      }
   case SLANG_OPER_PREINCREMENT:   /* ++var */
      {
	 slang_ir_node *n;
         assert(oper->num_children == 1);
	 n = _slang_gen_function_call_name(A, "++", oper, NULL);
	 return n;
      }
   case SLANG_OPER_PREDECREMENT:   /* --var */
      {
	 slang_ir_node *n;
         assert(oper->num_children == 1);
	 n = _slang_gen_function_call_name(A, "--", oper, NULL);
	 return n;
      }

   case SLANG_OPER_SEQUENCE:
      {
         slang_ir_node *tree = NULL;
         GLuint i;
         for (i = 0; i < oper->num_children; i++) {
            slang_ir_node *n = _slang_gen_operation(A, &oper->children[i]);
            tree = tree ? new_seq(tree, n) : n;
         }
         return tree;
      }

   case SLANG_OPER_NONE:
      return NULL;
   case SLANG_OPER_VOID:
      return NULL;

   default:
      printf("Unhandled node type %d\n", oper->type);
      abort();
      return new_node0(IR_NOP);
   }

   return NULL;
}



/**
 * Called by compiler when a global variable has been parsed/compiled.
 * Here we examine the variable's type to determine what kind of register
 * storage will be used.
 *
 * A uniform such as "gl_Position" will become the register specification
 * (PROGRAM_OUTPUT, VERT_RESULT_HPOS).  Or, uniform "gl_FogFragCoord"
 * will be (PROGRAM_INPUT, FRAG_ATTRIB_FOGC).
 *
 * Samplers are interesting.  For "uniform sampler2D tex;" we'll specify
 * (PROGRAM_SAMPLER, index) where index is resolved at link-time to an
 * actual texture unit (as specified by the user calling glUniform1i()).
 */
GLboolean
_slang_codegen_global_variable(slang_assemble_ctx *A, slang_variable *var,
                               slang_unit_type type)
{
   struct gl_program *prog = A->program;
   const char *varName = (char *) var->a_name;
   GLboolean success = GL_TRUE;
   GLint texIndex;
   slang_ir_storage *store = NULL;
   int dbg = 0;

   texIndex = sampler_to_texture_index(var->type.specifier.type);

   if (texIndex != -1) {
      /* Texture sampler:
       * store->File = PROGRAM_SAMPLER
       * store->Index = sampler uniform location
       * store->Size = texture type index (1D, 2D, 3D, cube, etc)
       */
      GLint samplerUniform = _mesa_add_sampler(prog->Parameters, varName);
      store = _slang_new_ir_storage(PROGRAM_SAMPLER, samplerUniform, texIndex);
      if (dbg) printf("SAMPLER ");
   }
   else if (var->type.qualifier == SLANG_QUAL_UNIFORM) {
      /* Uniform variable */
      const GLint size = _slang_sizeof_type_specifier(&var->type.specifier)
                         * MAX2(var->array_len, 1);
      if (prog) {
         /* user-defined uniform */
         GLint uniformLoc = _mesa_add_uniform(prog->Parameters, varName, size);
         store = _slang_new_ir_storage(PROGRAM_UNIFORM, uniformLoc, size);
      }
      else {
         /* pre-defined uniform, like gl_ModelviewMatrix */
         /* We know it's a uniform, but don't allocate storage unless
          * it's really used.
          */
         store = _slang_new_ir_storage(PROGRAM_STATE_VAR, -1, size);
      }
      if (dbg) printf("UNIFORM (sz %d) ", size);
   }
   else if (var->type.qualifier == SLANG_QUAL_VARYING) {
      const GLint size = 4; /* XXX fix */
      if (prog) {
         /* user-defined varying */
         GLint varyingLoc = _mesa_add_varying(prog->Varying, varName, size);
         store = _slang_new_ir_storage(PROGRAM_VARYING, varyingLoc, size);
      }
      else {
         /* pre-defined varying, like gl_Color or gl_TexCoord */
         if (type == SLANG_UNIT_FRAGMENT_BUILTIN) {
            GLint index = _slang_input_index(varName, GL_FRAGMENT_PROGRAM_ARB);
            assert(index >= 0);
            store = _slang_new_ir_storage(PROGRAM_INPUT, index, size);
            assert(index < FRAG_ATTRIB_MAX);
         }
         else {
            GLint index = _slang_output_index(varName, GL_VERTEX_PROGRAM_ARB);
            assert(index >= 0);
            assert(type == SLANG_UNIT_VERTEX_BUILTIN);
            store = _slang_new_ir_storage(PROGRAM_OUTPUT, index, size);
            assert(index < VERT_RESULT_MAX);
         }
         if (dbg) printf("V/F ");
      }
      if (dbg) printf("VARYING ");
   }
   else if (var->type.qualifier == SLANG_QUAL_ATTRIBUTE) {
      if (prog) {
         /* user-defined vertex attribute */
         const GLint size = _slang_sizeof_type_specifier(&var->type.specifier);
         const GLint attr = -1; /* unknown */
         GLint index = _mesa_add_attribute(prog->Attributes, varName,
                                           size, attr);
         assert(index >= 0);
         store = _slang_new_ir_storage(PROGRAM_INPUT,
                                       VERT_ATTRIB_GENERIC0 + index, size);
      }
      else {
         /* pre-defined vertex attrib */
         GLint index = _slang_input_index(varName, GL_VERTEX_PROGRAM_ARB);
         GLint size = 4; /* XXX? */
         assert(index >= 0);
         store = _slang_new_ir_storage(PROGRAM_INPUT, index, size);
      }
      if (dbg) printf("ATTRIB ");
   }
   else if (var->type.qualifier == SLANG_QUAL_FIXEDINPUT) {
      GLint index = _slang_input_index(varName, GL_FRAGMENT_PROGRAM_ARB);
      GLint size = 4; /* XXX? */
      store = _slang_new_ir_storage(PROGRAM_INPUT, index, size);
      if (dbg) printf("INPUT ");
   }
   else if (var->type.qualifier == SLANG_QUAL_FIXEDOUTPUT) {
      if (type == SLANG_UNIT_VERTEX_BUILTIN) {
         GLint index = _slang_output_index(varName, GL_VERTEX_PROGRAM_ARB);
         GLint size = 4; /* XXX? */
         store = _slang_new_ir_storage(PROGRAM_OUTPUT, index, size);
      }
      else {
         assert(type == SLANG_UNIT_FRAGMENT_BUILTIN);
         GLint index = _slang_output_index(varName, GL_FRAGMENT_PROGRAM_ARB);
         GLint size = 4; /* XXX? */
         store = _slang_new_ir_storage(PROGRAM_OUTPUT, index, size);
      }
      if (dbg) printf("OUTPUT ");
   }
   else if (var->type.qualifier == SLANG_QUAL_CONST && !prog) {
      /* pre-defined global constant, like gl_MaxLights */
      const GLint size = _slang_sizeof_type_specifier(&var->type.specifier);
      store = _slang_new_ir_storage(PROGRAM_CONSTANT, -1, size);
      if (dbg) printf("CONST ");
   }
   else {
      /* ordinary variable (may be const) */
      slang_ir_node *n;

      /* IR node to declare the variable */
      n = _slang_gen_var_decl(A, var);

      /* IR code for the var's initializer, if present */
      if (var->initializer) {
         slang_ir_node *lhs, *rhs, *init;

         /* Generate IR_MOVE instruction to initialize the variable */
         lhs = new_node0(IR_VAR);
         lhs->Var = var;
         lhs->Store = n->Store;

         /* constant folding, etc */
         _slang_simplify(var->initializer, &A->space, A->atoms);

         rhs = _slang_gen_operation(A, var->initializer);
         assert(rhs);
         init = new_node2(IR_MOVE, lhs, rhs);
         n = new_seq(n, init);
      }

      success = _slang_emit_code(n, A->vartable, A->program, GL_FALSE, A->log);

      _slang_free_ir_tree(n);
   }

   if (dbg) printf("GLOBAL VAR %s  idx %d\n", (char*) var->a_name,
                   store ? store->Index : -2);

   if (store)
      var->aux = store;  /* save var's storage info */

   return success;
}


/**
 * Produce an IR tree from a function AST (fun->body).
 * Then call the code emitter to convert the IR tree into gl_program
 * instructions.
 */
GLboolean
_slang_codegen_function(slang_assemble_ctx * A, slang_function * fun)
{
   slang_ir_node *n;
   GLboolean success = GL_TRUE;

   if (_mesa_strcmp((char *) fun->header.a_name, "main") != 0) {
      /* we only really generate code for main, all other functions get
       * inlined.
       */
      return GL_TRUE;  /* not an error */
   }

#if 1
   printf("\n*********** codegen_function %s\n", (char *) fun->header.a_name);
#endif
#if 0
   slang_print_function(fun, 1);
#endif

   /* should have been allocated earlier: */
   assert(A->program->Parameters );
   assert(A->program->Varying);
   assert(A->vartable);

   /* fold constant expressions, etc. */
   _slang_simplify(fun->body, &A->space, A->atoms);

   A->CurFunction = fun;

   /* Create an end-of-function label */
   if (!A->CurFunction->end_label)
      A->CurFunction->end_label = _slang_label_new("__endOfFunc__main");

   /* push new vartable scope */
   _slang_push_var_table(A->vartable);

   /* Generate IR tree for the function body code */
   n = _slang_gen_operation(A, fun->body);
   if (n)
      n = new_node1(IR_SCOPE, n);

   /* pop vartable, restore previous */
   _slang_pop_var_table(A->vartable);

   if (!n) {
      /* XXX record error */
      return GL_FALSE;
   }

   /* append an end-of-function-label to IR tree */
   n = new_seq(n, new_label(fun->end_label));

   A->CurFunction = NULL;

#if 0
   printf("************* New AST for %s *****\n", (char*)fun->header.a_name);
   slang_print_function(fun, 1);
#endif
#if 0
   printf("************* IR for %s *******\n", (char*)fun->header.a_name);
   slang_print_ir(n, 0);
#endif
#if 1
   printf("************* End codegen function ************\n\n");
#endif

   /* Emit program instructions */
   success = _slang_emit_code(n, A->vartable, A->program, GL_TRUE, A->log);
   _slang_free_ir_tree(n);

   /* free codegen context */
   /*
   _mesa_free(A->codegen);
   */

   return success;
}