aboutsummaryrefslogtreecommitdiff
path: root/src/share/vm/adlc/output_c.cpp
blob: 68a0ff818f809ccbc7cd336a2e0c40cb3523104f (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
/*
 * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 *
 */

// output_c.cpp - Class CPP file output routines for architecture definition

#include "adlc.hpp"

// Utilities to characterize effect statements
static bool is_def(int usedef) {
  switch(usedef) {
  case Component::DEF:
  case Component::USE_DEF: return true; break;
  }
  return false;
}

static bool is_use(int usedef) {
  switch(usedef) {
  case Component::USE:
  case Component::USE_DEF:
  case Component::USE_KILL: return true; break;
  }
  return false;
}

static bool is_kill(int usedef) {
  switch(usedef) {
  case Component::KILL:
  case Component::USE_KILL: return true; break;
  }
  return false;
}

// Define  an array containing the machine register names, strings.
static void defineRegNames(FILE *fp, RegisterForm *registers) {
  if (registers) {
    fprintf(fp,"\n");
    fprintf(fp,"// An array of character pointers to machine register names.\n");
    fprintf(fp,"const char *Matcher::regName[REG_COUNT] = {\n");

    // Output the register name for each register in the allocation classes
    RegDef *reg_def = NULL;
    RegDef *next = NULL;
    registers->reset_RegDefs();
    for( reg_def = registers->iter_RegDefs(); reg_def != NULL; reg_def = next ) {
      next = registers->iter_RegDefs();
      const char *comma = (next != NULL) ? "," : " // no trailing comma";
      fprintf(fp,"  \"%s\"%s\n",
                 reg_def->_regname, comma );
    }

    // Finish defining enumeration
    fprintf(fp,"};\n");

    fprintf(fp,"\n");
    fprintf(fp,"// An array of character pointers to machine register names.\n");
    fprintf(fp,"const VMReg OptoReg::opto2vm[REG_COUNT] = {\n");
    reg_def = NULL;
    next = NULL;
    registers->reset_RegDefs();
    for( reg_def = registers->iter_RegDefs(); reg_def != NULL; reg_def = next ) {
      next = registers->iter_RegDefs();
      const char *comma = (next != NULL) ? "," : " // no trailing comma";
      fprintf(fp,"\t%s%s\n", reg_def->_concrete, comma );
    }
    // Finish defining array
    fprintf(fp,"\t};\n");
    fprintf(fp,"\n");

    fprintf(fp," OptoReg::Name OptoReg::vm2opto[ConcreteRegisterImpl::number_of_registers];\n");

  }
}

// Define an array containing the machine register encoding values
static void defineRegEncodes(FILE *fp, RegisterForm *registers) {
  if (registers) {
    fprintf(fp,"\n");
    fprintf(fp,"// An array of the machine register encode values\n");
    fprintf(fp,"const unsigned char Matcher::_regEncode[REG_COUNT] = {\n");

    // Output the register encoding for each register in the allocation classes
    RegDef *reg_def = NULL;
    RegDef *next    = NULL;
    registers->reset_RegDefs();
    for( reg_def = registers->iter_RegDefs(); reg_def != NULL; reg_def = next ) {
      next = registers->iter_RegDefs();
      const char* register_encode = reg_def->register_encode();
      const char *comma = (next != NULL) ? "," : " // no trailing comma";
      int encval;
      if (!ADLParser::is_int_token(register_encode, encval)) {
        fprintf(fp,"  %s%s  // %s\n",
                register_encode, comma, reg_def->_regname );
      } else {
        // Output known constants in hex char format (backward compatibility).
        assert(encval < 256, "Exceeded supported width for register encoding");
        fprintf(fp,"  (unsigned char)'\\x%X'%s  // %s\n",
                encval,          comma, reg_def->_regname );
      }
    }
    // Finish defining enumeration
    fprintf(fp,"};\n");

  } // Done defining array
}

// Output an enumeration of register class names
static void defineRegClassEnum(FILE *fp, RegisterForm *registers) {
  if (registers) {
    // Output an enumeration of register class names
    fprintf(fp,"\n");
    fprintf(fp,"// Enumeration of register class names\n");
    fprintf(fp, "enum machRegisterClass {\n");
    registers->_rclasses.reset();
    for( const char *class_name = NULL;
         (class_name = registers->_rclasses.iter()) != NULL; ) {
      fprintf(fp,"  %s,\n", toUpper( class_name ));
    }
    // Finish defining enumeration
    fprintf(fp, "  _last_Mach_Reg_Class\n");
    fprintf(fp, "};\n");
  }
}

// Declare an enumeration of user-defined register classes
// and a list of register masks, one for each class.
void ArchDesc::declare_register_masks(FILE *fp_hpp) {
  const char  *rc_name;

  if( _register ) {
    // Build enumeration of user-defined register classes.
    defineRegClassEnum(fp_hpp, _register);

    // Generate a list of register masks, one for each class.
    fprintf(fp_hpp,"\n");
    fprintf(fp_hpp,"// Register masks, one for each register class.\n");
    _register->_rclasses.reset();
    for( rc_name = NULL;
         (rc_name = _register->_rclasses.iter()) != NULL; ) {
      const char *prefix    = "";
      RegClass   *reg_class = _register->getRegClass(rc_name);
      assert( reg_class, "Using an undefined register class");

      if (reg_class->_user_defined == NULL) {
        fprintf(fp_hpp, "extern const RegMask _%s%s_mask;\n", prefix, toUpper( rc_name ) );
        fprintf(fp_hpp, "inline const RegMask &%s%s_mask() { return _%s%s_mask; }\n", prefix, toUpper( rc_name ), prefix, toUpper( rc_name ));
      } else {
        fprintf(fp_hpp, "inline const RegMask &%s%s_mask() { %s }\n", prefix, toUpper( rc_name ), reg_class->_user_defined);
      }

      if( reg_class->_stack_or_reg ) {
        assert(reg_class->_user_defined == NULL, "no user defined reg class here");
        fprintf(fp_hpp, "extern const RegMask _%sSTACK_OR_%s_mask;\n", prefix, toUpper( rc_name ) );
        fprintf(fp_hpp, "inline const RegMask &%sSTACK_OR_%s_mask() { return _%sSTACK_OR_%s_mask; }\n", prefix, toUpper( rc_name ), prefix, toUpper( rc_name ) );
      }
    }
  }
}

// Generate an enumeration of user-defined register classes
// and a list of register masks, one for each class.
void ArchDesc::build_register_masks(FILE *fp_cpp) {
  const char  *rc_name;

  if( _register ) {
    // Generate a list of register masks, one for each class.
    fprintf(fp_cpp,"\n");
    fprintf(fp_cpp,"// Register masks, one for each register class.\n");
    _register->_rclasses.reset();
    for( rc_name = NULL;
         (rc_name = _register->_rclasses.iter()) != NULL; ) {
      const char *prefix    = "";
      RegClass   *reg_class = _register->getRegClass(rc_name);
      assert( reg_class, "Using an undefined register class");

      if (reg_class->_user_defined != NULL) continue;

      int len = RegisterForm::RegMask_Size();
      fprintf(fp_cpp, "const RegMask _%s%s_mask(", prefix, toUpper( rc_name ) );
      { int i;
        for( i = 0; i < len-1; i++ )
          fprintf(fp_cpp," 0x%x,",reg_class->regs_in_word(i,false));
        fprintf(fp_cpp," 0x%x );\n",reg_class->regs_in_word(i,false));
      }

      if( reg_class->_stack_or_reg ) {
        int i;
        fprintf(fp_cpp, "const RegMask _%sSTACK_OR_%s_mask(", prefix, toUpper( rc_name ) );
        for( i = 0; i < len-1; i++ )
          fprintf(fp_cpp," 0x%x,",reg_class->regs_in_word(i,true));
        fprintf(fp_cpp," 0x%x );\n",reg_class->regs_in_word(i,true));
      }
    }
  }
}

// Compute an index for an array in the pipeline_reads_NNN arrays
static int pipeline_reads_initializer(FILE *fp_cpp, NameList &pipeline_reads, PipeClassForm *pipeclass)
{
  int templen = 1;
  int paramcount = 0;
  const char *paramname;

  if (pipeclass->_parameters.count() == 0)
    return -1;

  pipeclass->_parameters.reset();
  paramname = pipeclass->_parameters.iter();
  const PipeClassOperandForm *pipeopnd =
    (const PipeClassOperandForm *)pipeclass->_localUsage[paramname];
  if (pipeopnd && !pipeopnd->isWrite() && strcmp(pipeopnd->_stage, "Universal"))
    pipeclass->_parameters.reset();

  while ( (paramname = pipeclass->_parameters.iter()) != NULL ) {
    const PipeClassOperandForm *tmppipeopnd =
        (const PipeClassOperandForm *)pipeclass->_localUsage[paramname];

    if (tmppipeopnd)
      templen += 10 + (int)strlen(tmppipeopnd->_stage);
    else
      templen += 19;

    paramcount++;
  }

  // See if the count is zero
  if (paramcount == 0) {
    return -1;
  }

  char *operand_stages = new char [templen];
  operand_stages[0] = 0;
  int i = 0;
  templen = 0;

  pipeclass->_parameters.reset();
  paramname = pipeclass->_parameters.iter();
  pipeopnd = (const PipeClassOperandForm *)pipeclass->_localUsage[paramname];
  if (pipeopnd && !pipeopnd->isWrite() && strcmp(pipeopnd->_stage, "Universal"))
    pipeclass->_parameters.reset();

  while ( (paramname = pipeclass->_parameters.iter()) != NULL ) {
    const PipeClassOperandForm *tmppipeopnd =
        (const PipeClassOperandForm *)pipeclass->_localUsage[paramname];
    templen += sprintf(&operand_stages[templen], "  stage_%s%c\n",
      tmppipeopnd ? tmppipeopnd->_stage : "undefined",
      (++i < paramcount ? ',' : ' ') );
  }

  // See if the same string is in the table
  int ndx = pipeline_reads.index(operand_stages);

  // No, add it to the table
  if (ndx < 0) {
    pipeline_reads.addName(operand_stages);
    ndx = pipeline_reads.index(operand_stages);

    fprintf(fp_cpp, "static const enum machPipelineStages pipeline_reads_%03d[%d] = {\n%s};\n\n",
      ndx+1, paramcount, operand_stages);
  }
  else
    delete [] operand_stages;

  return (ndx);
}

// Compute an index for an array in the pipeline_res_stages_NNN arrays
static int pipeline_res_stages_initializer(
  FILE *fp_cpp,
  PipelineForm *pipeline,
  NameList &pipeline_res_stages,
  PipeClassForm *pipeclass)
{
  const PipeClassResourceForm *piperesource;
  int * res_stages = new int [pipeline->_rescount];
  int i;

  for (i = 0; i < pipeline->_rescount; i++)
     res_stages[i] = 0;

  for (pipeclass->_resUsage.reset();
       (piperesource = (const PipeClassResourceForm *)pipeclass->_resUsage.iter()) != NULL; ) {
    int used_mask = pipeline->_resdict[piperesource->_resource]->is_resource()->mask();
    for (i = 0; i < pipeline->_rescount; i++)
      if ((1 << i) & used_mask) {
        int stage = pipeline->_stages.index(piperesource->_stage);
        if (res_stages[i] < stage+1)
          res_stages[i] = stage+1;
      }
  }

  // Compute the length needed for the resource list
  int commentlen = 0;
  int max_stage = 0;
  for (i = 0; i < pipeline->_rescount; i++) {
    if (res_stages[i] == 0) {
      if (max_stage < 9)
        max_stage = 9;
    }
    else {
      int stagelen = (int)strlen(pipeline->_stages.name(res_stages[i]-1));
      if (max_stage < stagelen)
        max_stage = stagelen;
    }

    commentlen += (int)strlen(pipeline->_reslist.name(i));
  }

  int templen = 1 + commentlen + pipeline->_rescount * (max_stage + 14);

  // Allocate space for the resource list
  char * resource_stages = new char [templen];

  templen = 0;
  for (i = 0; i < pipeline->_rescount; i++) {
    const char * const resname =
      res_stages[i] == 0 ? "undefined" : pipeline->_stages.name(res_stages[i]-1);

    templen += sprintf(&resource_stages[templen], "  stage_%s%-*s // %s\n",
      resname, max_stage - (int)strlen(resname) + 1,
      (i < pipeline->_rescount-1) ? "," : "",
      pipeline->_reslist.name(i));
  }

  // See if the same string is in the table
  int ndx = pipeline_res_stages.index(resource_stages);

  // No, add it to the table
  if (ndx < 0) {
    pipeline_res_stages.addName(resource_stages);
    ndx = pipeline_res_stages.index(resource_stages);

    fprintf(fp_cpp, "static const enum machPipelineStages pipeline_res_stages_%03d[%d] = {\n%s};\n\n",
      ndx+1, pipeline->_rescount, resource_stages);
  }
  else
    delete [] resource_stages;

  delete [] res_stages;

  return (ndx);
}

// Compute an index for an array in the pipeline_res_cycles_NNN arrays
static int pipeline_res_cycles_initializer(
  FILE *fp_cpp,
  PipelineForm *pipeline,
  NameList &pipeline_res_cycles,
  PipeClassForm *pipeclass)
{
  const PipeClassResourceForm *piperesource;
  int * res_cycles = new int [pipeline->_rescount];
  int i;

  for (i = 0; i < pipeline->_rescount; i++)
     res_cycles[i] = 0;

  for (pipeclass->_resUsage.reset();
       (piperesource = (const PipeClassResourceForm *)pipeclass->_resUsage.iter()) != NULL; ) {
    int used_mask = pipeline->_resdict[piperesource->_resource]->is_resource()->mask();
    for (i = 0; i < pipeline->_rescount; i++)
      if ((1 << i) & used_mask) {
        int cycles = piperesource->_cycles;
        if (res_cycles[i] < cycles)
          res_cycles[i] = cycles;
      }
  }

  // Pre-compute the string length
  int templen;
  int cyclelen = 0, commentlen = 0;
  int max_cycles = 0;
  char temp[32];

  for (i = 0; i < pipeline->_rescount; i++) {
    if (max_cycles < res_cycles[i])
      max_cycles = res_cycles[i];
    templen = sprintf(temp, "%d", res_cycles[i]);
    if (cyclelen < templen)
      cyclelen = templen;
    commentlen += (int)strlen(pipeline->_reslist.name(i));
  }

  templen = 1 + commentlen + (cyclelen + 8) * pipeline->_rescount;

  // Allocate space for the resource list
  char * resource_cycles = new char [templen];

  templen = 0;

  for (i = 0; i < pipeline->_rescount; i++) {
    templen += sprintf(&resource_cycles[templen], "  %*d%c // %s\n",
      cyclelen, res_cycles[i], (i < pipeline->_rescount-1) ? ',' : ' ', pipeline->_reslist.name(i));
  }

  // See if the same string is in the table
  int ndx = pipeline_res_cycles.index(resource_cycles);

  // No, add it to the table
  if (ndx < 0) {
    pipeline_res_cycles.addName(resource_cycles);
    ndx = pipeline_res_cycles.index(resource_cycles);

    fprintf(fp_cpp, "static const uint pipeline_res_cycles_%03d[%d] = {\n%s};\n\n",
      ndx+1, pipeline->_rescount, resource_cycles);
  }
  else
    delete [] resource_cycles;

  delete [] res_cycles;

  return (ndx);
}

//typedef unsigned long long uint64_t;

// Compute an index for an array in the pipeline_res_mask_NNN arrays
static int pipeline_res_mask_initializer(
  FILE *fp_cpp,
  PipelineForm *pipeline,
  NameList &pipeline_res_mask,
  NameList &pipeline_res_args,
  PipeClassForm *pipeclass)
{
  const PipeClassResourceForm *piperesource;
  const uint rescount      = pipeline->_rescount;
  const uint maxcycleused  = pipeline->_maxcycleused;
  const uint cyclemasksize = (maxcycleused + 31) >> 5;

  int i, j;
  int element_count = 0;
  uint *res_mask = new uint [cyclemasksize];
  uint resources_used             = 0;
  uint resources_used_exclusively = 0;

  for (pipeclass->_resUsage.reset();
       (piperesource = (const PipeClassResourceForm *)pipeclass->_resUsage.iter()) != NULL; )
    element_count++;

  // Pre-compute the string length
  int templen;
  int commentlen = 0;
  int max_cycles = 0;

  int cyclelen = ((maxcycleused + 3) >> 2);
  int masklen = (rescount + 3) >> 2;

  int cycledigit = 0;
  for (i = maxcycleused; i > 0; i /= 10)
    cycledigit++;

  int maskdigit = 0;
  for (i = rescount; i > 0; i /= 10)
    maskdigit++;

  static const char * pipeline_use_cycle_mask = "Pipeline_Use_Cycle_Mask";
  static const char * pipeline_use_element    = "Pipeline_Use_Element";

  templen = 1 +
    (int)(strlen(pipeline_use_cycle_mask) + (int)strlen(pipeline_use_element) +
     (cyclemasksize * 12) + masklen + (cycledigit * 2) + 30) * element_count;

  // Allocate space for the resource list
  char * resource_mask = new char [templen];
  char * last_comma = NULL;

  templen = 0;

  for (pipeclass->_resUsage.reset();
       (piperesource = (const PipeClassResourceForm *)pipeclass->_resUsage.iter()) != NULL; ) {
    int used_mask = pipeline->_resdict[piperesource->_resource]->is_resource()->mask();

    if (!used_mask)
      fprintf(stderr, "*** used_mask is 0 ***\n");

    resources_used |= used_mask;

    uint lb, ub;

    for (lb =  0; (used_mask & (1 << lb)) == 0; lb++);
    for (ub = 31; (used_mask & (1 << ub)) == 0; ub--);

    if (lb == ub)
      resources_used_exclusively |= used_mask;

    int formatlen =
      sprintf(&resource_mask[templen], "  %s(0x%0*x, %*d, %*d, %s %s(",
        pipeline_use_element,
        masklen, used_mask,
        cycledigit, lb, cycledigit, ub,
        ((used_mask & (used_mask-1)) != 0) ? "true, " : "false,",
        pipeline_use_cycle_mask);

    templen += formatlen;

    memset(res_mask, 0, cyclemasksize * sizeof(uint));

    int cycles = piperesource->_cycles;
    uint stage          = pipeline->_stages.index(piperesource->_stage);
    uint upper_limit    = stage+cycles-1;
    uint lower_limit    = stage-1;
    uint upper_idx      = upper_limit >> 5;
    uint lower_idx      = lower_limit >> 5;
    uint upper_position = upper_limit & 0x1f;
    uint lower_position = lower_limit & 0x1f;

    uint mask = (((uint)1) << upper_position) - 1;

    while ( upper_idx > lower_idx ) {
      res_mask[upper_idx--] |= mask;
      mask = (uint)-1;
    }

    mask -= (((uint)1) << lower_position) - 1;
    res_mask[upper_idx] |= mask;

    for (j = cyclemasksize-1; j >= 0; j--) {
      formatlen =
        sprintf(&resource_mask[templen], "0x%08x%s", res_mask[j], j > 0 ? ", " : "");
      templen += formatlen;
    }

    resource_mask[templen++] = ')';
    resource_mask[templen++] = ')';
    last_comma = &resource_mask[templen];
    resource_mask[templen++] = ',';
    resource_mask[templen++] = '\n';
  }

  resource_mask[templen] = 0;
  if (last_comma)
    last_comma[0] = ' ';

  // See if the same string is in the table
  int ndx = pipeline_res_mask.index(resource_mask);

  // No, add it to the table
  if (ndx < 0) {
    pipeline_res_mask.addName(resource_mask);
    ndx = pipeline_res_mask.index(resource_mask);

    if (strlen(resource_mask) > 0)
      fprintf(fp_cpp, "static const Pipeline_Use_Element pipeline_res_mask_%03d[%d] = {\n%s};\n\n",
        ndx+1, element_count, resource_mask);

    char * args = new char [9 + 2*masklen + maskdigit];

    sprintf(args, "0x%0*x, 0x%0*x, %*d",
      masklen, resources_used,
      masklen, resources_used_exclusively,
      maskdigit, element_count);

    pipeline_res_args.addName(args);
  }
  else
    delete [] resource_mask;

  delete [] res_mask;
//delete [] res_masks;

  return (ndx);
}

void ArchDesc::build_pipe_classes(FILE *fp_cpp) {
  const char *classname;
  const char *resourcename;
  int resourcenamelen = 0;
  NameList pipeline_reads;
  NameList pipeline_res_stages;
  NameList pipeline_res_cycles;
  NameList pipeline_res_masks;
  NameList pipeline_res_args;
  const int default_latency = 1;
  const int non_operand_latency = 0;
  const int node_latency = 0;

  if (!_pipeline) {
    fprintf(fp_cpp, "uint Node::latency(uint i) const {\n");
    fprintf(fp_cpp, "  // assert(false, \"pipeline functionality is not defined\");\n");
    fprintf(fp_cpp, "  return %d;\n", non_operand_latency);
    fprintf(fp_cpp, "}\n");
    return;
  }

  fprintf(fp_cpp, "\n");
  fprintf(fp_cpp, "//------------------Pipeline Methods-----------------------------------------\n");
  fprintf(fp_cpp, "#ifndef PRODUCT\n");
  fprintf(fp_cpp, "const char * Pipeline::stageName(uint s) {\n");
  fprintf(fp_cpp, "  static const char * const _stage_names[] = {\n");
  fprintf(fp_cpp, "    \"undefined\"");

  for (int s = 0; s < _pipeline->_stagecnt; s++)
    fprintf(fp_cpp, ", \"%s\"", _pipeline->_stages.name(s));

  fprintf(fp_cpp, "\n  };\n\n");
  fprintf(fp_cpp, "  return (s <= %d ? _stage_names[s] : \"???\");\n",
    _pipeline->_stagecnt);
  fprintf(fp_cpp, "}\n");
  fprintf(fp_cpp, "#endif\n\n");

  fprintf(fp_cpp, "uint Pipeline::functional_unit_latency(uint start, const Pipeline *pred) const {\n");
  fprintf(fp_cpp, "  // See if the functional units overlap\n");
#if 0
  fprintf(fp_cpp, "\n#ifndef PRODUCT\n");
  fprintf(fp_cpp, "  if (TraceOptoOutput) {\n");
  fprintf(fp_cpp, "    tty->print(\"#   functional_unit_latency: start == %%d, this->exclusively == 0x%%03x, pred->exclusively == 0x%%03x\\n\", start, resourcesUsedExclusively(), pred->resourcesUsedExclusively());\n");
  fprintf(fp_cpp, "  }\n");
  fprintf(fp_cpp, "#endif\n\n");
#endif
  fprintf(fp_cpp, "  uint mask = resourcesUsedExclusively() & pred->resourcesUsedExclusively();\n");
  fprintf(fp_cpp, "  if (mask == 0)\n    return (start);\n\n");
#if 0
  fprintf(fp_cpp, "\n#ifndef PRODUCT\n");
  fprintf(fp_cpp, "  if (TraceOptoOutput) {\n");
  fprintf(fp_cpp, "    tty->print(\"#   functional_unit_latency: mask == 0x%%x\\n\", mask);\n");
  fprintf(fp_cpp, "  }\n");
  fprintf(fp_cpp, "#endif\n\n");
#endif
  fprintf(fp_cpp, "  for (uint i = 0; i < pred->resourceUseCount(); i++) {\n");
  fprintf(fp_cpp, "    const Pipeline_Use_Element *predUse = pred->resourceUseElement(i);\n");
  fprintf(fp_cpp, "    if (predUse->multiple())\n");
  fprintf(fp_cpp, "      continue;\n\n");
  fprintf(fp_cpp, "    for (uint j = 0; j < resourceUseCount(); j++) {\n");
  fprintf(fp_cpp, "      const Pipeline_Use_Element *currUse = resourceUseElement(j);\n");
  fprintf(fp_cpp, "      if (currUse->multiple())\n");
  fprintf(fp_cpp, "        continue;\n\n");
  fprintf(fp_cpp, "      if (predUse->used() & currUse->used()) {\n");
  fprintf(fp_cpp, "        Pipeline_Use_Cycle_Mask x = predUse->mask();\n");
  fprintf(fp_cpp, "        Pipeline_Use_Cycle_Mask y = currUse->mask();\n\n");
  fprintf(fp_cpp, "        for ( y <<= start; x.overlaps(y); start++ )\n");
  fprintf(fp_cpp, "          y <<= 1;\n");
  fprintf(fp_cpp, "      }\n");
  fprintf(fp_cpp, "    }\n");
  fprintf(fp_cpp, "  }\n\n");
  fprintf(fp_cpp, "  // There is the potential for overlap\n");
  fprintf(fp_cpp, "  return (start);\n");
  fprintf(fp_cpp, "}\n\n");
  fprintf(fp_cpp, "// The following two routines assume that the root Pipeline_Use entity\n");
  fprintf(fp_cpp, "// consists of exactly 1 element for each functional unit\n");
  fprintf(fp_cpp, "// start is relative to the current cycle; used for latency-based info\n");
  fprintf(fp_cpp, "uint Pipeline_Use::full_latency(uint delay, const Pipeline_Use &pred) const {\n");
  fprintf(fp_cpp, "  for (uint i = 0; i < pred._count; i++) {\n");
  fprintf(fp_cpp, "    const Pipeline_Use_Element *predUse = pred.element(i);\n");
  fprintf(fp_cpp, "    if (predUse->_multiple) {\n");
  fprintf(fp_cpp, "      uint min_delay = %d;\n",
    _pipeline->_maxcycleused+1);
  fprintf(fp_cpp, "      // Multiple possible functional units, choose first unused one\n");
  fprintf(fp_cpp, "      for (uint j = predUse->_lb; j <= predUse->_ub; j++) {\n");
  fprintf(fp_cpp, "        const Pipeline_Use_Element *currUse = element(j);\n");
  fprintf(fp_cpp, "        uint curr_delay = delay;\n");
  fprintf(fp_cpp, "        if (predUse->_used & currUse->_used) {\n");
  fprintf(fp_cpp, "          Pipeline_Use_Cycle_Mask x = predUse->_mask;\n");
  fprintf(fp_cpp, "          Pipeline_Use_Cycle_Mask y = currUse->_mask;\n\n");
  fprintf(fp_cpp, "          for ( y <<= curr_delay; x.overlaps(y); curr_delay++ )\n");
  fprintf(fp_cpp, "            y <<= 1;\n");
  fprintf(fp_cpp, "        }\n");
  fprintf(fp_cpp, "        if (min_delay > curr_delay)\n          min_delay = curr_delay;\n");
  fprintf(fp_cpp, "      }\n");
  fprintf(fp_cpp, "      if (delay < min_delay)\n      delay = min_delay;\n");
  fprintf(fp_cpp, "    }\n");
  fprintf(fp_cpp, "    else {\n");
  fprintf(fp_cpp, "      for (uint j = predUse->_lb; j <= predUse->_ub; j++) {\n");
  fprintf(fp_cpp, "        const Pipeline_Use_Element *currUse = element(j);\n");
  fprintf(fp_cpp, "        if (predUse->_used & currUse->_used) {\n");
  fprintf(fp_cpp, "          Pipeline_Use_Cycle_Mask x = predUse->_mask;\n");
  fprintf(fp_cpp, "          Pipeline_Use_Cycle_Mask y = currUse->_mask;\n\n");
  fprintf(fp_cpp, "          for ( y <<= delay; x.overlaps(y); delay++ )\n");
  fprintf(fp_cpp, "            y <<= 1;\n");
  fprintf(fp_cpp, "        }\n");
  fprintf(fp_cpp, "      }\n");
  fprintf(fp_cpp, "    }\n");
  fprintf(fp_cpp, "  }\n\n");
  fprintf(fp_cpp, "  return (delay);\n");
  fprintf(fp_cpp, "}\n\n");
  fprintf(fp_cpp, "void Pipeline_Use::add_usage(const Pipeline_Use &pred) {\n");
  fprintf(fp_cpp, "  for (uint i = 0; i < pred._count; i++) {\n");
  fprintf(fp_cpp, "    const Pipeline_Use_Element *predUse = pred.element(i);\n");
  fprintf(fp_cpp, "    if (predUse->_multiple) {\n");
  fprintf(fp_cpp, "      // Multiple possible functional units, choose first unused one\n");
  fprintf(fp_cpp, "      for (uint j = predUse->_lb; j <= predUse->_ub; j++) {\n");
  fprintf(fp_cpp, "        Pipeline_Use_Element *currUse = element(j);\n");
  fprintf(fp_cpp, "        if ( !predUse->_mask.overlaps(currUse->_mask) ) {\n");
  fprintf(fp_cpp, "          currUse->_used |= (1 << j);\n");
  fprintf(fp_cpp, "          _resources_used |= (1 << j);\n");
  fprintf(fp_cpp, "          currUse->_mask.Or(predUse->_mask);\n");
  fprintf(fp_cpp, "          break;\n");
  fprintf(fp_cpp, "        }\n");
  fprintf(fp_cpp, "      }\n");
  fprintf(fp_cpp, "    }\n");
  fprintf(fp_cpp, "    else {\n");
  fprintf(fp_cpp, "      for (uint j = predUse->_lb; j <= predUse->_ub; j++) {\n");
  fprintf(fp_cpp, "        Pipeline_Use_Element *currUse = element(j);\n");
  fprintf(fp_cpp, "        currUse->_used |= (1 << j);\n");
  fprintf(fp_cpp, "        _resources_used |= (1 << j);\n");
  fprintf(fp_cpp, "        currUse->_mask.Or(predUse->_mask);\n");
  fprintf(fp_cpp, "      }\n");
  fprintf(fp_cpp, "    }\n");
  fprintf(fp_cpp, "  }\n");
  fprintf(fp_cpp, "}\n\n");

  fprintf(fp_cpp, "uint Pipeline::operand_latency(uint opnd, const Pipeline *pred) const {\n");
  fprintf(fp_cpp, "  int const default_latency = 1;\n");
  fprintf(fp_cpp, "\n");
#if 0
  fprintf(fp_cpp, "#ifndef PRODUCT\n");
  fprintf(fp_cpp, "  if (TraceOptoOutput) {\n");
  fprintf(fp_cpp, "    tty->print(\"#   operand_latency(%%d), _read_stage_count = %%d\\n\", opnd, _read_stage_count);\n");
  fprintf(fp_cpp, "  }\n");
  fprintf(fp_cpp, "#endif\n\n");
#endif
  fprintf(fp_cpp, "  assert(this, \"NULL pipeline info\");\n");
  fprintf(fp_cpp, "  assert(pred, \"NULL predecessor pipline info\");\n\n");
  fprintf(fp_cpp, "  if (pred->hasFixedLatency())\n    return (pred->fixedLatency());\n\n");
  fprintf(fp_cpp, "  // If this is not an operand, then assume a dependence with 0 latency\n");
  fprintf(fp_cpp, "  if (opnd > _read_stage_count)\n    return (0);\n\n");
  fprintf(fp_cpp, "  uint writeStage = pred->_write_stage;\n");
  fprintf(fp_cpp, "  uint readStage  = _read_stages[opnd-1];\n");
#if 0
  fprintf(fp_cpp, "\n#ifndef PRODUCT\n");
  fprintf(fp_cpp, "  if (TraceOptoOutput) {\n");
  fprintf(fp_cpp, "    tty->print(\"#   operand_latency: writeStage=%%s readStage=%%s, opnd=%%d\\n\", stageName(writeStage), stageName(readStage), opnd);\n");
  fprintf(fp_cpp, "  }\n");
  fprintf(fp_cpp, "#endif\n\n");
#endif
  fprintf(fp_cpp, "\n");
  fprintf(fp_cpp, "  if (writeStage == stage_undefined || readStage == stage_undefined)\n");
  fprintf(fp_cpp, "    return (default_latency);\n");
  fprintf(fp_cpp, "\n");
  fprintf(fp_cpp, "  int delta = writeStage - readStage;\n");
  fprintf(fp_cpp, "  if (delta < 0) delta = 0;\n\n");
#if 0
  fprintf(fp_cpp, "\n#ifndef PRODUCT\n");
  fprintf(fp_cpp, "  if (TraceOptoOutput) {\n");
  fprintf(fp_cpp, "    tty->print(\"# operand_latency: delta=%%d\\n\", delta);\n");
  fprintf(fp_cpp, "  }\n");
  fprintf(fp_cpp, "#endif\n\n");
#endif
  fprintf(fp_cpp, "  return (delta);\n");
  fprintf(fp_cpp, "}\n\n");

  if (!_pipeline)
    /* Do Nothing */;

  else if (_pipeline->_maxcycleused <=
#ifdef SPARC
    64
#else
    32
#endif
      ) {
    fprintf(fp_cpp, "Pipeline_Use_Cycle_Mask operator&(const Pipeline_Use_Cycle_Mask &in1, const Pipeline_Use_Cycle_Mask &in2) {\n");
    fprintf(fp_cpp, "  return Pipeline_Use_Cycle_Mask(in1._mask & in2._mask);\n");
    fprintf(fp_cpp, "}\n\n");
    fprintf(fp_cpp, "Pipeline_Use_Cycle_Mask operator|(const Pipeline_Use_Cycle_Mask &in1, const Pipeline_Use_Cycle_Mask &in2) {\n");
    fprintf(fp_cpp, "  return Pipeline_Use_Cycle_Mask(in1._mask | in2._mask);\n");
    fprintf(fp_cpp, "}\n\n");
  }
  else {
    uint l;
    uint masklen = (_pipeline->_maxcycleused + 31) >> 5;
    fprintf(fp_cpp, "Pipeline_Use_Cycle_Mask operator&(const Pipeline_Use_Cycle_Mask &in1, const Pipeline_Use_Cycle_Mask &in2) {\n");
    fprintf(fp_cpp, "  return Pipeline_Use_Cycle_Mask(");
    for (l = 1; l <= masklen; l++)
      fprintf(fp_cpp, "in1._mask%d & in2._mask%d%s\n", l, l, l < masklen ? ", " : "");
    fprintf(fp_cpp, ");\n");
    fprintf(fp_cpp, "}\n\n");
    fprintf(fp_cpp, "Pipeline_Use_Cycle_Mask operator|(const Pipeline_Use_Cycle_Mask &in1, const Pipeline_Use_Cycle_Mask &in2) {\n");
    fprintf(fp_cpp, "  return Pipeline_Use_Cycle_Mask(");
    for (l = 1; l <= masklen; l++)
      fprintf(fp_cpp, "in1._mask%d | in2._mask%d%s", l, l, l < masklen ? ", " : "");
    fprintf(fp_cpp, ");\n");
    fprintf(fp_cpp, "}\n\n");
    fprintf(fp_cpp, "void Pipeline_Use_Cycle_Mask::Or(const Pipeline_Use_Cycle_Mask &in2) {\n ");
    for (l = 1; l <= masklen; l++)
      fprintf(fp_cpp, " _mask%d |= in2._mask%d;", l, l);
    fprintf(fp_cpp, "\n}\n\n");
  }

  /* Get the length of all the resource names */
  for (_pipeline->_reslist.reset(), resourcenamelen = 0;
       (resourcename = _pipeline->_reslist.iter()) != NULL;
       resourcenamelen += (int)strlen(resourcename));

  // Create the pipeline class description

  fprintf(fp_cpp, "static const Pipeline pipeline_class_Zero_Instructions(0, 0, true, 0, 0, false, false, false, false, NULL, NULL, NULL, Pipeline_Use(0, 0, 0, NULL));\n\n");
  fprintf(fp_cpp, "static const Pipeline pipeline_class_Unknown_Instructions(0, 0, true, 0, 0, false, true, true, false, NULL, NULL, NULL, Pipeline_Use(0, 0, 0, NULL));\n\n");

  fprintf(fp_cpp, "const Pipeline_Use_Element Pipeline_Use::elaborated_elements[%d] = {\n", _pipeline->_rescount);
  for (int i1 = 0; i1 < _pipeline->_rescount; i1++) {
    fprintf(fp_cpp, "  Pipeline_Use_Element(0, %d, %d, false, Pipeline_Use_Cycle_Mask(", i1, i1);
    uint masklen = (_pipeline->_maxcycleused + 31) >> 5;
    for (int i2 = masklen-1; i2 >= 0; i2--)
      fprintf(fp_cpp, "0%s", i2 > 0 ? ", " : "");
    fprintf(fp_cpp, "))%s\n", i1 < (_pipeline->_rescount-1) ? "," : "");
  }
  fprintf(fp_cpp, "};\n\n");

  fprintf(fp_cpp, "const Pipeline_Use Pipeline_Use::elaborated_use(0, 0, %d, (Pipeline_Use_Element *)&elaborated_elements[0]);\n\n",
    _pipeline->_rescount);

  for (_pipeline->_classlist.reset(); (classname = _pipeline->_classlist.iter()) != NULL; ) {
    fprintf(fp_cpp, "\n");
    fprintf(fp_cpp, "// Pipeline Class \"%s\"\n", classname);
    PipeClassForm *pipeclass = _pipeline->_classdict[classname]->is_pipeclass();
    int maxWriteStage = -1;
    int maxMoreInstrs = 0;
    int paramcount = 0;
    int i = 0;
    const char *paramname;
    int resource_count = (_pipeline->_rescount + 3) >> 2;

    // Scan the operands, looking for last output stage and number of inputs
    for (pipeclass->_parameters.reset(); (paramname = pipeclass->_parameters.iter()) != NULL; ) {
      const PipeClassOperandForm *pipeopnd =
          (const PipeClassOperandForm *)pipeclass->_localUsage[paramname];
      if (pipeopnd) {
        if (pipeopnd->_iswrite) {
           int stagenum  = _pipeline->_stages.index(pipeopnd->_stage);
           int moreinsts = pipeopnd->_more_instrs;
          if ((maxWriteStage+maxMoreInstrs) < (stagenum+moreinsts)) {
            maxWriteStage = stagenum;
            maxMoreInstrs = moreinsts;
          }
        }
      }

      if (i++ > 0 || (pipeopnd && !pipeopnd->isWrite()))
        paramcount++;
    }

    // Create the list of stages for the operands that are read
    // Note that we will build a NameList to reduce the number of copies

    int pipeline_reads_index = pipeline_reads_initializer(fp_cpp, pipeline_reads, pipeclass);

    int pipeline_res_stages_index = pipeline_res_stages_initializer(
      fp_cpp, _pipeline, pipeline_res_stages, pipeclass);

    int pipeline_res_cycles_index = pipeline_res_cycles_initializer(
      fp_cpp, _pipeline, pipeline_res_cycles, pipeclass);

    int pipeline_res_mask_index = pipeline_res_mask_initializer(
      fp_cpp, _pipeline, pipeline_res_masks, pipeline_res_args, pipeclass);

#if 0
    // Process the Resources
    const PipeClassResourceForm *piperesource;

    unsigned resources_used = 0;
    unsigned exclusive_resources_used = 0;
    unsigned resource_groups = 0;
    for (pipeclass->_resUsage.reset();
         (piperesource = (const PipeClassResourceForm *)pipeclass->_resUsage.iter()) != NULL; ) {
      int used_mask = _pipeline->_resdict[piperesource->_resource]->is_resource()->mask();
      if (used_mask)
        resource_groups++;
      resources_used |= used_mask;
      if ((used_mask & (used_mask-1)) == 0)
        exclusive_resources_used |= used_mask;
    }

    if (resource_groups > 0) {
      fprintf(fp_cpp, "static const uint pipeline_res_or_masks_%03d[%d] = {",
        pipeclass->_num, resource_groups);
      for (pipeclass->_resUsage.reset(), i = 1;
           (piperesource = (const PipeClassResourceForm *)pipeclass->_resUsage.iter()) != NULL;
           i++ ) {
        int used_mask = _pipeline->_resdict[piperesource->_resource]->is_resource()->mask();
        if (used_mask) {
          fprintf(fp_cpp, " 0x%0*x%c", resource_count, used_mask, i < (int)resource_groups ? ',' : ' ');
        }
      }
      fprintf(fp_cpp, "};\n\n");
    }
#endif

    // Create the pipeline class description
    fprintf(fp_cpp, "static const Pipeline pipeline_class_%03d(",
      pipeclass->_num);
    if (maxWriteStage < 0)
      fprintf(fp_cpp, "(uint)stage_undefined");
    else if (maxMoreInstrs == 0)
      fprintf(fp_cpp, "(uint)stage_%s", _pipeline->_stages.name(maxWriteStage));
    else
      fprintf(fp_cpp, "((uint)stage_%s)+%d", _pipeline->_stages.name(maxWriteStage), maxMoreInstrs);
    fprintf(fp_cpp, ", %d, %s, %d, %d, %s, %s, %s, %s,\n",
      paramcount,
      pipeclass->hasFixedLatency() ? "true" : "false",
      pipeclass->fixedLatency(),
      pipeclass->InstructionCount(),
      pipeclass->hasBranchDelay() ? "true" : "false",
      pipeclass->hasMultipleBundles() ? "true" : "false",
      pipeclass->forceSerialization() ? "true" : "false",
      pipeclass->mayHaveNoCode() ? "true" : "false" );
    if (paramcount > 0) {
      fprintf(fp_cpp, "\n  (enum machPipelineStages * const) pipeline_reads_%03d,\n ",
        pipeline_reads_index+1);
    }
    else
      fprintf(fp_cpp, " NULL,");
    fprintf(fp_cpp, "  (enum machPipelineStages * const) pipeline_res_stages_%03d,\n",
      pipeline_res_stages_index+1);
    fprintf(fp_cpp, "  (uint * const) pipeline_res_cycles_%03d,\n",
      pipeline_res_cycles_index+1);
    fprintf(fp_cpp, "  Pipeline_Use(%s, (Pipeline_Use_Element *)",
      pipeline_res_args.name(pipeline_res_mask_index));
    if (strlen(pipeline_res_masks.name(pipeline_res_mask_index)) > 0)
      fprintf(fp_cpp, "&pipeline_res_mask_%03d[0]",
        pipeline_res_mask_index+1);
    else
      fprintf(fp_cpp, "NULL");
    fprintf(fp_cpp, "));\n");
  }

  // Generate the Node::latency method if _pipeline defined
  fprintf(fp_cpp, "\n");
  fprintf(fp_cpp, "//------------------Inter-Instruction Latency--------------------------------\n");
  fprintf(fp_cpp, "uint Node::latency(uint i) {\n");
  if (_pipeline) {
#if 0
    fprintf(fp_cpp, "#ifndef PRODUCT\n");
    fprintf(fp_cpp, " if (TraceOptoOutput) {\n");
    fprintf(fp_cpp, "    tty->print(\"# %%4d->latency(%%d)\\n\", _idx, i);\n");
    fprintf(fp_cpp, " }\n");
    fprintf(fp_cpp, "#endif\n");
#endif
    fprintf(fp_cpp, "  uint j;\n");
    fprintf(fp_cpp, "  // verify in legal range for inputs\n");
    fprintf(fp_cpp, "  assert(i < len(), \"index not in range\");\n\n");
    fprintf(fp_cpp, "  // verify input is not null\n");
    fprintf(fp_cpp, "  Node *pred = in(i);\n");
    fprintf(fp_cpp, "  if (!pred)\n    return %d;\n\n",
      non_operand_latency);
    fprintf(fp_cpp, "  if (pred->is_Proj())\n    pred = pred->in(0);\n\n");
    fprintf(fp_cpp, "  // if either node does not have pipeline info, use default\n");
    fprintf(fp_cpp, "  const Pipeline *predpipe = pred->pipeline();\n");
    fprintf(fp_cpp, "  assert(predpipe, \"no predecessor pipeline info\");\n\n");
    fprintf(fp_cpp, "  if (predpipe->hasFixedLatency())\n    return predpipe->fixedLatency();\n\n");
    fprintf(fp_cpp, "  const Pipeline *currpipe = pipeline();\n");
    fprintf(fp_cpp, "  assert(currpipe, \"no pipeline info\");\n\n");
    fprintf(fp_cpp, "  if (!is_Mach())\n    return %d;\n\n",
      node_latency);
    fprintf(fp_cpp, "  const MachNode *m = as_Mach();\n");
    fprintf(fp_cpp, "  j = m->oper_input_base();\n");
    fprintf(fp_cpp, "  if (i < j)\n    return currpipe->functional_unit_latency(%d, predpipe);\n\n",
      non_operand_latency);
    fprintf(fp_cpp, "  // determine which operand this is in\n");
    fprintf(fp_cpp, "  uint n = m->num_opnds();\n");
    fprintf(fp_cpp, "  int delta = %d;\n\n",
      non_operand_latency);
    fprintf(fp_cpp, "  uint k;\n");
    fprintf(fp_cpp, "  for (k = 1; k < n; k++) {\n");
    fprintf(fp_cpp, "    j += m->_opnds[k]->num_edges();\n");
    fprintf(fp_cpp, "    if (i < j)\n");
    fprintf(fp_cpp, "      break;\n");
    fprintf(fp_cpp, "  }\n");
    fprintf(fp_cpp, "  if (k < n)\n");
    fprintf(fp_cpp, "    delta = currpipe->operand_latency(k,predpipe);\n\n");
    fprintf(fp_cpp, "  return currpipe->functional_unit_latency(delta, predpipe);\n");
  }
  else {
    fprintf(fp_cpp, "  // assert(false, \"pipeline functionality is not defined\");\n");
    fprintf(fp_cpp, "  return %d;\n",
      non_operand_latency);
  }
  fprintf(fp_cpp, "}\n\n");

  // Output the list of nop nodes
  fprintf(fp_cpp, "// Descriptions for emitting different functional unit nops\n");
  const char *nop;
  int nopcnt = 0;
  for ( _pipeline->_noplist.reset(); (nop = _pipeline->_noplist.iter()) != NULL; nopcnt++ );

  fprintf(fp_cpp, "void Bundle::initialize_nops(MachNode * nop_list[%d], Compile *C) {\n", nopcnt);
  int i = 0;
  for ( _pipeline->_noplist.reset(); (nop = _pipeline->_noplist.iter()) != NULL; i++ ) {
    fprintf(fp_cpp, "  nop_list[%d] = (MachNode *) new (C) %sNode();\n", i, nop);
  }
  fprintf(fp_cpp, "};\n\n");
  fprintf(fp_cpp, "#ifndef PRODUCT\n");
  fprintf(fp_cpp, "void Bundle::dump() const {\n");
  fprintf(fp_cpp, "  static const char * bundle_flags[] = {\n");
  fprintf(fp_cpp, "    \"\",\n");
  fprintf(fp_cpp, "    \"use nop delay\",\n");
  fprintf(fp_cpp, "    \"use unconditional delay\",\n");
  fprintf(fp_cpp, "    \"use conditional delay\",\n");
  fprintf(fp_cpp, "    \"used in conditional delay\",\n");
  fprintf(fp_cpp, "    \"used in unconditional delay\",\n");
  fprintf(fp_cpp, "    \"used in all conditional delays\",\n");
  fprintf(fp_cpp, "  };\n\n");

  fprintf(fp_cpp, "  static const char *resource_names[%d] = {", _pipeline->_rescount);
  for (i = 0; i < _pipeline->_rescount; i++)
    fprintf(fp_cpp, " \"%s\"%c", _pipeline->_reslist.name(i), i < _pipeline->_rescount-1 ? ',' : ' ');
  fprintf(fp_cpp, "};\n\n");

  // See if the same string is in the table
  fprintf(fp_cpp, "  bool needs_comma = false;\n\n");
  fprintf(fp_cpp, "  if (_flags) {\n");
  fprintf(fp_cpp, "    tty->print(\"%%s\", bundle_flags[_flags]);\n");
  fprintf(fp_cpp, "    needs_comma = true;\n");
  fprintf(fp_cpp, "  };\n");
  fprintf(fp_cpp, "  if (instr_count()) {\n");
  fprintf(fp_cpp, "    tty->print(\"%%s%%d instr%%s\", needs_comma ? \", \" : \"\", instr_count(), instr_count() != 1 ? \"s\" : \"\");\n");
  fprintf(fp_cpp, "    needs_comma = true;\n");
  fprintf(fp_cpp, "  };\n");
  fprintf(fp_cpp, "  uint r = resources_used();\n");
  fprintf(fp_cpp, "  if (r) {\n");
  fprintf(fp_cpp, "    tty->print(\"%%sresource%%s:\", needs_comma ? \", \" : \"\", (r & (r-1)) != 0 ? \"s\" : \"\");\n");
  fprintf(fp_cpp, "    for (uint i = 0; i < %d; i++)\n", _pipeline->_rescount);
  fprintf(fp_cpp, "      if ((r & (1 << i)) != 0)\n");
  fprintf(fp_cpp, "        tty->print(\" %%s\", resource_names[i]);\n");
  fprintf(fp_cpp, "    needs_comma = true;\n");
  fprintf(fp_cpp, "  };\n");
  fprintf(fp_cpp, "  tty->print(\"\\n\");\n");
  fprintf(fp_cpp, "}\n");
  fprintf(fp_cpp, "#endif\n");
}

// ---------------------------------------------------------------------------
//------------------------------Utilities to build Instruction Classes--------
// ---------------------------------------------------------------------------

static void defineOut_RegMask(FILE *fp, const char *node, const char *regMask) {
  fprintf(fp,"const RegMask &%sNode::out_RegMask() const { return (%s); }\n",
          node, regMask);
}

// Scan the peepmatch and output a test for each instruction
static void check_peepmatch_instruction_tree(FILE *fp, PeepMatch *pmatch, PeepConstraint *pconstraint) {
  int         parent        = -1;
  int         inst_position = 0;
  const char* inst_name     = NULL;
  int         input         = 0;
  fprintf(fp, "      // Check instruction sub-tree\n");
  pmatch->reset();
  for( pmatch->next_instruction( parent, inst_position, inst_name, input );
       inst_name != NULL;
       pmatch->next_instruction( parent, inst_position, inst_name, input ) ) {
    // If this is not a placeholder
    if( ! pmatch->is_placeholder() ) {
      // Define temporaries 'inst#', based on parent and parent's input index
      if( parent != -1 ) {                // root was initialized
        fprintf(fp, "  inst%d = inst%d->in(%d);\n",
                inst_position, parent, input);
      }

      // When not the root
      // Test we have the correct instruction by comparing the rule
      if( parent != -1 ) {
        fprintf(fp, "  matches = matches &&  ( inst%d->rule() == %s_rule );",
                inst_position, inst_name);
      }
    } else {
      // Check that user did not try to constrain a placeholder
      assert( ! pconstraint->constrains_instruction(inst_position),
              "fatal(): Can not constrain a placeholder instruction");
    }
  }
}

static void print_block_index(FILE *fp, int inst_position) {
  assert( inst_position >= 0, "Instruction number less than zero");
  fprintf(fp, "block_index");
  if( inst_position != 0 ) {
    fprintf(fp, " - %d", inst_position);
  }
}

// Scan the peepmatch and output a test for each instruction
static void check_peepmatch_instruction_sequence(FILE *fp, PeepMatch *pmatch, PeepConstraint *pconstraint) {
  int         parent        = -1;
  int         inst_position = 0;
  const char* inst_name     = NULL;
  int         input         = 0;
  fprintf(fp, "  // Check instruction sub-tree\n");
  pmatch->reset();
  for( pmatch->next_instruction( parent, inst_position, inst_name, input );
       inst_name != NULL;
       pmatch->next_instruction( parent, inst_position, inst_name, input ) ) {
    // If this is not a placeholder
    if( ! pmatch->is_placeholder() ) {
      // Define temporaries 'inst#', based on parent and parent's input index
      if( parent != -1 ) {                // root was initialized
        fprintf(fp, "  // Identify previous instruction if inside this block\n");
        fprintf(fp, "  if( ");
        print_block_index(fp, inst_position);
        fprintf(fp, " > 0 ) {\n    Node *n = block->_nodes.at(");
        print_block_index(fp, inst_position);
        fprintf(fp, ");\n    inst%d = (n->is_Mach()) ? ", inst_position);
        fprintf(fp, "n->as_Mach() : NULL;\n  }\n");
      }

      // When not the root
      // Test we have the correct instruction by comparing the rule.
      if( parent != -1 ) {
        fprintf(fp, "  matches = matches && (inst%d != NULL) && (inst%d->rule() == %s_rule);\n",
                inst_position, inst_position, inst_name);
      }
    } else {
      // Check that user did not try to constrain a placeholder
      assert( ! pconstraint->constrains_instruction(inst_position),
              "fatal(): Can not constrain a placeholder instruction");
    }
  }
}

// Build mapping for register indices, num_edges to input
static void build_instruction_index_mapping( FILE *fp, FormDict &globals, PeepMatch *pmatch ) {
  int         parent        = -1;
  int         inst_position = 0;
  const char* inst_name     = NULL;
  int         input         = 0;
  fprintf(fp, "      // Build map to register info\n");
  pmatch->reset();
  for( pmatch->next_instruction( parent, inst_position, inst_name, input );
       inst_name != NULL;
       pmatch->next_instruction( parent, inst_position, inst_name, input ) ) {
    // If this is not a placeholder
    if( ! pmatch->is_placeholder() ) {
      // Define temporaries 'inst#', based on self's inst_position
      InstructForm *inst = globals[inst_name]->is_instruction();
      if( inst != NULL ) {
        char inst_prefix[]  = "instXXXX_";
        sprintf(inst_prefix, "inst%d_",   inst_position);
        char receiver[]     = "instXXXX->";
        sprintf(receiver,    "inst%d->", inst_position);
        inst->index_temps( fp, globals, inst_prefix, receiver );
      }
    }
  }
}

// Generate tests for the constraints
static void check_peepconstraints(FILE *fp, FormDict &globals, PeepMatch *pmatch, PeepConstraint *pconstraint) {
  fprintf(fp, "\n");
  fprintf(fp, "      // Check constraints on sub-tree-leaves\n");

  // Build mapping from num_edges to local variables
  build_instruction_index_mapping( fp, globals, pmatch );

  // Build constraint tests
  if( pconstraint != NULL ) {
    fprintf(fp, "      matches = matches &&");
    bool   first_constraint = true;
    while( pconstraint != NULL ) {
      // indentation and connecting '&&'
      const char *indentation = "      ";
      fprintf(fp, "\n%s%s", indentation, (!first_constraint ? "&& " : "  "));

      // Only have '==' relation implemented
      if( strcmp(pconstraint->_relation,"==") != 0 ) {
        assert( false, "Unimplemented()" );
      }

      // LEFT
      int left_index       = pconstraint->_left_inst;
      const char *left_op  = pconstraint->_left_op;
      // Access info on the instructions whose operands are compared
      InstructForm *inst_left = globals[pmatch->instruction_name(left_index)]->is_instruction();
      assert( inst_left, "Parser should guaranty this is an instruction");
      int left_op_base  = inst_left->oper_input_base(globals);
      // Access info on the operands being compared
      int left_op_index  = inst_left->operand_position(left_op, Component::USE);
      if( left_op_index == -1 ) {
        left_op_index = inst_left->operand_position(left_op, Component::DEF);
        if( left_op_index == -1 ) {
          left_op_index = inst_left->operand_position(left_op, Component::USE_DEF);
        }
      }
      assert( left_op_index  != NameList::Not_in_list, "Did not find operand in instruction");
      ComponentList components_left = inst_left->_components;
      const char *left_comp_type = components_left.at(left_op_index)->_type;
      OpClassForm *left_opclass = globals[left_comp_type]->is_opclass();
      Form::InterfaceType left_interface_type = left_opclass->interface_type(globals);


      // RIGHT
      int right_op_index = -1;
      int right_index      = pconstraint->_right_inst;
      const char *right_op = pconstraint->_right_op;
      if( right_index != -1 ) { // Match operand
        // Access info on the instructions whose operands are compared
        InstructForm *inst_right = globals[pmatch->instruction_name(right_index)]->is_instruction();
        assert( inst_right, "Parser should guaranty this is an instruction");
        int right_op_base = inst_right->oper_input_base(globals);
        // Access info on the operands being compared
        right_op_index = inst_right->operand_position(right_op, Component::USE);
        if( right_op_index == -1 ) {
          right_op_index = inst_right->operand_position(right_op, Component::DEF);
          if( right_op_index == -1 ) {
            right_op_index = inst_right->operand_position(right_op, Component::USE_DEF);
          }
        }
        assert( right_op_index != NameList::Not_in_list, "Did not find operand in instruction");
        ComponentList components_right = inst_right->_components;
        const char *right_comp_type = components_right.at(right_op_index)->_type;
        OpClassForm *right_opclass = globals[right_comp_type]->is_opclass();
        Form::InterfaceType right_interface_type = right_opclass->interface_type(globals);
        assert( right_interface_type == left_interface_type, "Both must be same interface");

      } else {                  // Else match register
        // assert( false, "should be a register" );
      }

      //
      // Check for equivalence
      //
      // fprintf(fp, "phase->eqv( ");
      // fprintf(fp, "inst%d->in(%d+%d) /* %s */, inst%d->in(%d+%d) /* %s */",
      //         left_index,  left_op_base,  left_op_index,  left_op,
      //         right_index, right_op_base, right_op_index, right_op );
      // fprintf(fp, ")");
      //
      switch( left_interface_type ) {
      case Form::register_interface: {
        // Check that they are allocated to the same register
        // Need parameter for index position if not result operand
        char left_reg_index[] = ",instXXXX_idxXXXX";
        if( left_op_index != 0 ) {
          assert( (left_index <= 9999) && (left_op_index <= 9999), "exceed string size");
          // Must have index into operands
          sprintf(left_reg_index,",inst%d_idx%d", left_index, left_op_index);
        } else {
          strcpy(left_reg_index, "");
        }
        fprintf(fp, "(inst%d->_opnds[%d]->reg(ra_,inst%d%s)  /* %d.%s */",
                left_index,  left_op_index, left_index, left_reg_index, left_index, left_op );
        fprintf(fp, " == ");

        if( right_index != -1 ) {
          char right_reg_index[18] = ",instXXXX_idxXXXX";
          if( right_op_index != 0 ) {
            assert( (right_index <= 9999) && (right_op_index <= 9999), "exceed string size");
            // Must have index into operands
            sprintf(right_reg_index,",inst%d_idx%d", right_index, right_op_index);
          } else {
            strcpy(right_reg_index, "");
          }
          fprintf(fp, "/* %d.%s */ inst%d->_opnds[%d]->reg(ra_,inst%d%s)",
                  right_index, right_op, right_index, right_op_index, right_index, right_reg_index );
        } else {
          fprintf(fp, "%s_enc", right_op );
        }
        fprintf(fp,")");
        break;
      }
      case Form::constant_interface: {
        // Compare the '->constant()' values
        fprintf(fp, "(inst%d->_opnds[%d]->constant()  /* %d.%s */",
                left_index,  left_op_index,  left_index, left_op );
        fprintf(fp, " == ");
        fprintf(fp, "/* %d.%s */ inst%d->_opnds[%d]->constant())",
                right_index, right_op, right_index, right_op_index );
        break;
      }
      case Form::memory_interface: {
        // Compare 'base', 'index', 'scale', and 'disp'
        // base
        fprintf(fp, "( \n");
        fprintf(fp, "  (inst%d->_opnds[%d]->base(ra_,inst%d,inst%d_idx%d)  /* %d.%s$$base */",
          left_index, left_op_index, left_index, left_index, left_op_index, left_index, left_op );
        fprintf(fp, " == ");
        fprintf(fp, "/* %d.%s$$base */ inst%d->_opnds[%d]->base(ra_,inst%d,inst%d_idx%d)) &&\n",
                right_index, right_op, right_index, right_op_index, right_index, right_index, right_op_index );
        // index
        fprintf(fp, "  (inst%d->_opnds[%d]->index(ra_,inst%d,inst%d_idx%d)  /* %d.%s$$index */",
                left_index, left_op_index, left_index, left_index, left_op_index, left_index, left_op );
        fprintf(fp, " == ");
        fprintf(fp, "/* %d.%s$$index */ inst%d->_opnds[%d]->index(ra_,inst%d,inst%d_idx%d)) &&\n",
                right_index, right_op, right_index, right_op_index, right_index, right_index, right_op_index );
        // scale
        fprintf(fp, "  (inst%d->_opnds[%d]->scale()  /* %d.%s$$scale */",
                left_index,  left_op_index,  left_index, left_op );
        fprintf(fp, " == ");
        fprintf(fp, "/* %d.%s$$scale */ inst%d->_opnds[%d]->scale()) &&\n",
                right_index, right_op, right_index, right_op_index );
        // disp
        fprintf(fp, "  (inst%d->_opnds[%d]->disp(ra_,inst%d,inst%d_idx%d)  /* %d.%s$$disp */",
                left_index, left_op_index, left_index, left_index, left_op_index, left_index, left_op );
        fprintf(fp, " == ");
        fprintf(fp, "/* %d.%s$$disp */ inst%d->_opnds[%d]->disp(ra_,inst%d,inst%d_idx%d))\n",
                right_index, right_op, right_index, right_op_index, right_index, right_index, right_op_index );
        fprintf(fp, ") \n");
        break;
      }
      case Form::conditional_interface: {
        // Compare the condition code being tested
        assert( false, "Unimplemented()" );
        break;
      }
      default: {
        assert( false, "ShouldNotReachHere()" );
        break;
      }
      }

      // Advance to next constraint
      pconstraint = pconstraint->next();
      first_constraint = false;
    }

    fprintf(fp, ";\n");
  }
}

// // EXPERIMENTAL -- TEMPORARY code
// static Form::DataType get_operand_type(FormDict &globals, InstructForm *instr, const char *op_name ) {
//   int op_index = instr->operand_position(op_name, Component::USE);
//   if( op_index == -1 ) {
//     op_index = instr->operand_position(op_name, Component::DEF);
//     if( op_index == -1 ) {
//       op_index = instr->operand_position(op_name, Component::USE_DEF);
//     }
//   }
//   assert( op_index != NameList::Not_in_list, "Did not find operand in instruction");
//
//   ComponentList components_right = instr->_components;
//   char *right_comp_type = components_right.at(op_index)->_type;
//   OpClassForm *right_opclass = globals[right_comp_type]->is_opclass();
//   Form::InterfaceType  right_interface_type = right_opclass->interface_type(globals);
//
//   return;
// }

// Construct the new sub-tree
static void generate_peepreplace( FILE *fp, FormDict &globals, PeepMatch *pmatch, PeepConstraint *pconstraint, PeepReplace *preplace, int max_position ) {
  fprintf(fp, "      // IF instructions and constraints matched\n");
  fprintf(fp, "      if( matches ) {\n");
  fprintf(fp, "        // generate the new sub-tree\n");
  fprintf(fp, "        assert( true, \"Debug stopping point\");\n");
  if( preplace != NULL ) {
    // Get the root of the new sub-tree
    const char *root_inst = NULL;
    preplace->next_instruction(root_inst);
    InstructForm *root_form = globals[root_inst]->is_instruction();
    assert( root_form != NULL, "Replacement instruction was not previously defined");
    fprintf(fp, "        %sNode *root = new (C) %sNode();\n", root_inst, root_inst);

    int         inst_num;
    const char *op_name;
    int         opnds_index = 0;            // define result operand
    // Then install the use-operands for the new sub-tree
    // preplace->reset();             // reset breaks iteration
    for( preplace->next_operand( inst_num, op_name );
         op_name != NULL;
         preplace->next_operand( inst_num, op_name ) ) {
      InstructForm *inst_form;
      inst_form  = globals[pmatch->instruction_name(inst_num)]->is_instruction();
      assert( inst_form, "Parser should guaranty this is an instruction");
      int inst_op_num = inst_form->operand_position(op_name, Component::USE);
      if( inst_op_num == NameList::Not_in_list )
        inst_op_num = inst_form->operand_position(op_name, Component::USE_DEF);
      assert( inst_op_num != NameList::Not_in_list, "Did not find operand as USE");
      // find the name of the OperandForm from the local name
      const Form *form   = inst_form->_localNames[op_name];
      OperandForm  *op_form = form->is_operand();
      if( opnds_index == 0 ) {
        // Initial setup of new instruction
        fprintf(fp, "        // ----- Initial setup -----\n");
        //
        // Add control edge for this node
        fprintf(fp, "        root->add_req(_in[0]);                // control edge\n");
        // Add unmatched edges from root of match tree
        int op_base = root_form->oper_input_base(globals);
        for( int unmatched_edge = 1; unmatched_edge < op_base; ++unmatched_edge ) {
          fprintf(fp, "        root->add_req(inst%d->in(%d));        // unmatched ideal edge\n",
                                          inst_num, unmatched_edge);
        }
        // If new instruction captures bottom type
        if( root_form->captures_bottom_type(globals) ) {
          // Get bottom type from instruction whose result we are replacing
          fprintf(fp, "        root->_bottom_type = inst%d->bottom_type();\n", inst_num);
        }
        // Define result register and result operand
        fprintf(fp, "        ra_->add_reference(root, inst%d);\n", inst_num);
        fprintf(fp, "        ra_->set_oop (root, ra_->is_oop(inst%d));\n", inst_num);
        fprintf(fp, "        ra_->set_pair(root->_idx, ra_->get_reg_second(inst%d), ra_->get_reg_first(inst%d));\n", inst_num, inst_num);
        fprintf(fp, "        root->_opnds[0] = inst%d->_opnds[0]->clone(C); // result\n", inst_num);
        fprintf(fp, "        // ----- Done with initial setup -----\n");
      } else {
        if( (op_form == NULL) || (op_form->is_base_constant(globals) == Form::none) ) {
          // Do not have ideal edges for constants after matching
          fprintf(fp, "        for( unsigned x%d = inst%d_idx%d; x%d < inst%d_idx%d; x%d++ )\n",
                  inst_op_num, inst_num, inst_op_num,
                  inst_op_num, inst_num, inst_op_num+1, inst_op_num );
          fprintf(fp, "          root->add_req( inst%d->in(x%d) );\n",
                  inst_num, inst_op_num );
        } else {
          fprintf(fp, "        // no ideal edge for constants after matching\n");
        }
        fprintf(fp, "        root->_opnds[%d] = inst%d->_opnds[%d]->clone(C);\n",
                opnds_index, inst_num, inst_op_num );
      }
      ++opnds_index;
    }
  }else {
    // Replacing subtree with empty-tree
    assert( false, "ShouldNotReachHere();");
  }

  // Return the new sub-tree
  fprintf(fp, "        deleted = %d;\n", max_position+1 /*zero to one based*/);
  fprintf(fp, "        return root;  // return new root;\n");
  fprintf(fp, "      }\n");
}


// Define the Peephole method for an instruction node
void ArchDesc::definePeephole(FILE *fp, InstructForm *node) {
  // Generate Peephole function header
  fprintf(fp, "MachNode *%sNode::peephole( Block *block, int block_index, PhaseRegAlloc *ra_, int &deleted, Compile* C ) {\n", node->_ident);
  fprintf(fp, "  bool  matches = true;\n");

  // Identify the maximum instruction position,
  // generate temporaries that hold current instruction
  //
  //   MachNode  *inst0 = NULL;
  //   ...
  //   MachNode  *instMAX = NULL;
  //
  int max_position = 0;
  Peephole *peep;
  for( peep = node->peepholes(); peep != NULL; peep = peep->next() ) {
    PeepMatch *pmatch = peep->match();
    assert( pmatch != NULL, "fatal(), missing peepmatch rule");
    if( max_position < pmatch->max_position() )  max_position = pmatch->max_position();
  }
  for( int i = 0; i <= max_position; ++i ) {
    if( i == 0 ) {
      fprintf(fp, "  MachNode *inst0 = this;\n");
    } else {
      fprintf(fp, "  MachNode *inst%d = NULL;\n", i);
    }
  }

  // For each peephole rule in architecture description
  //   Construct a test for the desired instruction sub-tree
  //   then check the constraints
  //   If these match, Generate the new subtree
  for( peep = node->peepholes(); peep != NULL; peep = peep->next() ) {
    int         peephole_number = peep->peephole_number();
    PeepMatch      *pmatch      = peep->match();
    PeepConstraint *pconstraint = peep->constraints();
    PeepReplace    *preplace    = peep->replacement();

    // Root of this peephole is the current MachNode
    assert( true, // %%name?%% strcmp( node->_ident, pmatch->name(0) ) == 0,
            "root of PeepMatch does not match instruction");

    // Make each peephole rule individually selectable
    fprintf(fp, "  if( (OptoPeepholeAt == -1) || (OptoPeepholeAt==%d) ) {\n", peephole_number);
    fprintf(fp, "    matches = true;\n");
    // Scan the peepmatch and output a test for each instruction
    check_peepmatch_instruction_sequence( fp, pmatch, pconstraint );

    // Check constraints and build replacement inside scope
    fprintf(fp, "    // If instruction subtree matches\n");
    fprintf(fp, "    if( matches ) {\n");

    // Generate tests for the constraints
    check_peepconstraints( fp, _globalNames, pmatch, pconstraint );

    // Construct the new sub-tree
    generate_peepreplace( fp, _globalNames, pmatch, pconstraint, preplace, max_position );

    // End of scope for this peephole's constraints
    fprintf(fp, "    }\n");
    // Closing brace '}' to make each peephole rule individually selectable
    fprintf(fp, "  } // end of peephole rule #%d\n", peephole_number);
    fprintf(fp, "\n");
  }

  fprintf(fp, "  return NULL;  // No peephole rules matched\n");
  fprintf(fp, "}\n");
  fprintf(fp, "\n");
}

// Define the Expand method for an instruction node
void ArchDesc::defineExpand(FILE *fp, InstructForm *node) {
  unsigned      cnt  = 0;          // Count nodes we have expand into
  unsigned      i;

  // Generate Expand function header
  fprintf(fp, "MachNode* %sNode::Expand(State* state, Node_List& proj_list, Node* mem) {\n", node->_ident);
  fprintf(fp, "  Compile* C = Compile::current();\n");
  // Generate expand code
  if( node->expands() ) {
    const char   *opid;
    int           new_pos, exp_pos;
    const char   *new_id   = NULL;
    const Form   *frm      = NULL;
    InstructForm *new_inst = NULL;
    OperandForm  *new_oper = NULL;
    unsigned      numo     = node->num_opnds() +
                                node->_exprule->_newopers.count();

    // If necessary, generate any operands created in expand rule
    if (node->_exprule->_newopers.count()) {
      for(node->_exprule->_newopers.reset();
          (new_id = node->_exprule->_newopers.iter()) != NULL; cnt++) {
        frm = node->_localNames[new_id];
        assert(frm, "Invalid entry in new operands list of expand rule");
        new_oper = frm->is_operand();
        char *tmp = (char *)node->_exprule->_newopconst[new_id];
        if (tmp == NULL) {
          fprintf(fp,"  MachOper *op%d = new (C) %sOper();\n",
                  cnt, new_oper->_ident);
        }
        else {
          fprintf(fp,"  MachOper *op%d = new (C) %sOper(%s);\n",
                  cnt, new_oper->_ident, tmp);
        }
      }
    }
    cnt = 0;
    // Generate the temps to use for DAG building
    for(i = 0; i < numo; i++) {
      if (i < node->num_opnds()) {
        fprintf(fp,"  MachNode *tmp%d = this;\n", i);
      }
      else {
        fprintf(fp,"  MachNode *tmp%d = NULL;\n", i);
      }
    }
    // Build mapping from num_edges to local variables
    fprintf(fp,"  unsigned num0 = 0;\n");
    for( i = 1; i < node->num_opnds(); i++ ) {
      fprintf(fp,"  unsigned num%d = opnd_array(%d)->num_edges();\n",i,i);
    }

    // Build a mapping from operand index to input edges
    fprintf(fp,"  unsigned idx0 = oper_input_base();\n");

    // The order in which the memory input is added to a node is very
    // strange.  Store nodes get a memory input before Expand is
    // called and other nodes get it afterwards or before depending on
    // match order so oper_input_base is wrong during expansion.  This
    // code adjusts it so that expansion will work correctly.
    int has_memory_edge = node->_matrule->needs_ideal_memory_edge(_globalNames);
    if (has_memory_edge) {
      fprintf(fp,"  if (mem == (Node*)1) {\n");
      fprintf(fp,"    idx0--; // Adjust base because memory edge hasn't been inserted yet\n");
      fprintf(fp,"  }\n");
    }

    for( i = 0; i < node->num_opnds(); i++ ) {
      fprintf(fp,"  unsigned idx%d = idx%d + num%d;\n",
              i+1,i,i);
    }

    // Declare variable to hold root of expansion
    fprintf(fp,"  MachNode *result = NULL;\n");

    // Iterate over the instructions 'node' expands into
    ExpandRule  *expand       = node->_exprule;
    NameAndList *expand_instr = NULL;
    for(expand->reset_instructions();
        (expand_instr = expand->iter_instructions()) != NULL; cnt++) {
      new_id = expand_instr->name();

      InstructForm* expand_instruction = (InstructForm*)globalAD->globalNames()[new_id];
      if (expand_instruction->has_temps()) {
        globalAD->syntax_err(node->_linenum, "In %s: expand rules using instructs with TEMPs aren't supported: %s",
                             node->_ident, new_id);
      }

      // Build the node for the instruction
      fprintf(fp,"\n  %sNode *n%d = new (C) %sNode();\n", new_id, cnt, new_id);
      // Add control edge for this node
      fprintf(fp,"  n%d->add_req(_in[0]);\n", cnt);
      // Build the operand for the value this node defines.
      Form *form = (Form*)_globalNames[new_id];
      assert( form, "'new_id' must be a defined form name");
      // Grab the InstructForm for the new instruction
      new_inst = form->is_instruction();
      assert( new_inst, "'new_id' must be an instruction name");
      if( node->is_ideal_if() && new_inst->is_ideal_if() ) {
        fprintf(fp, "  ((MachIfNode*)n%d)->_prob = _prob;\n",cnt);
        fprintf(fp, "  ((MachIfNode*)n%d)->_fcnt = _fcnt;\n",cnt);
      }

      if( node->is_ideal_fastlock() && new_inst->is_ideal_fastlock() ) {
        fprintf(fp, "  ((MachFastLockNode*)n%d)->_counters = _counters;\n",cnt);
      }

      const char *resultOper = new_inst->reduce_result();
      fprintf(fp,"  n%d->set_opnd_array(0, state->MachOperGenerator( %s, C ));\n",
              cnt, machOperEnum(resultOper));

      // get the formal operand NameList
      NameList *formal_lst = &new_inst->_parameters;
      formal_lst->reset();

      // Handle any memory operand
      int memory_operand = new_inst->memory_operand(_globalNames);
      if( memory_operand != InstructForm::NO_MEMORY_OPERAND ) {
        int node_mem_op = node->memory_operand(_globalNames);
        assert( node_mem_op != InstructForm::NO_MEMORY_OPERAND,
                "expand rule member needs memory but top-level inst doesn't have any" );
        if (has_memory_edge) {
          // Copy memory edge
          fprintf(fp,"  if (mem != (Node*)1) {\n");
          fprintf(fp,"    n%d->add_req(_in[1]);\t// Add memory edge\n", cnt);
          fprintf(fp,"  }\n");
        }
      }

      // Iterate over the new instruction's operands
      int prev_pos = -1;
      for( expand_instr->reset(); (opid = expand_instr->iter()) != NULL; ) {
        // Use 'parameter' at current position in list of new instruction's formals
        // instead of 'opid' when looking up info internal to new_inst
        const char *parameter = formal_lst->iter();
        // Check for an operand which is created in the expand rule
        if ((exp_pos = node->_exprule->_newopers.index(opid)) != -1) {
          new_pos = new_inst->operand_position(parameter,Component::USE);
          exp_pos += node->num_opnds();
          // If there is no use of the created operand, just skip it
          if (new_pos != -1) {
            //Copy the operand from the original made above
            fprintf(fp,"  n%d->set_opnd_array(%d, op%d->clone(C)); // %s\n",
                    cnt, new_pos, exp_pos-node->num_opnds(), opid);
            // Check for who defines this operand & add edge if needed
            fprintf(fp,"  if(tmp%d != NULL)\n", exp_pos);
            fprintf(fp,"    n%d->add_req(tmp%d);\n", cnt, exp_pos);
          }
        }
        else {
          // Use operand name to get an index into instruction component list
          // ins = (InstructForm *) _globalNames[new_id];
          exp_pos = node->operand_position_format(opid);
          assert(exp_pos != -1, "Bad expand rule");
          if (prev_pos > exp_pos && expand_instruction->_matrule != NULL) {
            // For the add_req calls below to work correctly they need
            // to added in the same order that a match would add them.
            // This means that they would need to be in the order of
            // the components list instead of the formal parameters.
            // This is a sort of hidden invariant that previously
            // wasn't checked and could lead to incorrectly
            // constructed nodes.
            syntax_err(node->_linenum, "For expand in %s to work, parameter declaration order in %s must follow matchrule\n",
                       node->_ident, new_inst->_ident);
          }
          prev_pos = exp_pos;

          new_pos = new_inst->operand_position(parameter,Component::USE);
          if (new_pos != -1) {
            // Copy the operand from the ExpandNode to the new node
            fprintf(fp,"  n%d->set_opnd_array(%d, opnd_array(%d)->clone(C)); // %s\n",
                    cnt, new_pos, exp_pos, opid);
            // For each operand add appropriate input edges by looking at tmp's
            fprintf(fp,"  if(tmp%d == this) {\n", exp_pos);
            // Grab corresponding edges from ExpandNode and insert them here
            fprintf(fp,"    for(unsigned i = 0; i < num%d; i++) {\n", exp_pos);
            fprintf(fp,"      n%d->add_req(_in[i + idx%d]);\n", cnt, exp_pos);
            fprintf(fp,"    }\n");
            fprintf(fp,"  }\n");
            // This value is generated by one of the new instructions
            fprintf(fp,"  else n%d->add_req(tmp%d);\n", cnt, exp_pos);
          }
        }

        // Update the DAG tmp's for values defined by this instruction
        int new_def_pos = new_inst->operand_position(parameter,Component::DEF);
        Effect *eform = (Effect *)new_inst->_effects[parameter];
        // If this operand is a definition in either an effects rule
        // or a match rule
        if((eform) && (is_def(eform->_use_def))) {
          // Update the temp associated with this operand
          fprintf(fp,"  tmp%d = n%d;\n", exp_pos, cnt);
        }
        else if( new_def_pos != -1 ) {
          // Instruction defines a value but user did not declare it
          // in the 'effect' clause
          fprintf(fp,"  tmp%d = n%d;\n", exp_pos, cnt);
        }
      } // done iterating over a new instruction's operands

      // Invoke Expand() for the newly created instruction.
      fprintf(fp,"  result = n%d->Expand( state, proj_list, mem );\n", cnt);
      assert( !new_inst->expands(), "Do not have complete support for recursive expansion");
    } // done iterating over new instructions
    fprintf(fp,"\n");
  } // done generating expand rule

  // Generate projections for instruction's additional DEFs and KILLs
  if( ! node->expands() && (node->needs_projections() || node->has_temps())) {
    // Get string representing the MachNode that projections point at
    const char *machNode = "this";
    // Generate the projections
    fprintf(fp,"  // Add projection edges for additional defs or kills\n");

    // Examine each component to see if it is a DEF or KILL
    node->_components.reset();
    // Skip the first component, if already handled as (SET dst (...))
    Component *comp = NULL;
    // For kills, the choice of projection numbers is arbitrary
    int proj_no = 1;
    bool declared_def  = false;
    bool declared_kill = false;

    while( (comp = node->_components.iter()) != NULL ) {
      // Lookup register class associated with operand type
      Form        *form = (Form*)_globalNames[comp->_type];
      assert( form, "component type must be a defined form");
      OperandForm *op   = form->is_operand();

      if (comp->is(Component::TEMP)) {
        fprintf(fp, "  // TEMP %s\n", comp->_name);
        if (!declared_def) {
          // Define the variable "def" to hold new MachProjNodes
          fprintf(fp, "  MachTempNode *def;\n");
          declared_def = true;
        }
        if (op && op->_interface && op->_interface->is_RegInterface()) {
          fprintf(fp,"  def = new (C) MachTempNode(state->MachOperGenerator( %s, C ));\n",
                  machOperEnum(op->_ident));
          fprintf(fp,"  add_req(def);\n");
          // The operand for TEMP is already constructed during
          // this mach node construction, see buildMachNode().
          //
          // int idx  = node->operand_position_format(comp->_name);
          // fprintf(fp,"  set_opnd_array(%d, state->MachOperGenerator( %s, C ));\n",
          //         idx, machOperEnum(op->_ident));
        } else {
          assert(false, "can't have temps which aren't registers");
        }
      } else if (comp->isa(Component::KILL)) {
        fprintf(fp, "  // DEF/KILL %s\n", comp->_name);

        if (!declared_kill) {
          // Define the variable "kill" to hold new MachProjNodes
          fprintf(fp, "  MachProjNode *kill;\n");
          declared_kill = true;
        }

        assert( op, "Support additional KILLS for base operands");
        const char *regmask    = reg_mask(*op);
        const char *ideal_type = op->ideal_type(_globalNames, _register);

        if (!op->is_bound_register()) {
          syntax_err(node->_linenum, "In %s only bound registers can be killed: %s %s\n",
                     node->_ident, comp->_type, comp->_name);
        }

        fprintf(fp,"  kill = ");
        fprintf(fp,"new (C, 1) MachProjNode( %s, %d, (%s), Op_%s );\n",
                machNode, proj_no++, regmask, ideal_type);
        fprintf(fp,"  proj_list.push(kill);\n");
      }
    }
  }

  if( !node->expands() && node->_matrule != NULL ) {
    // Remove duplicated operands and inputs which use the same name.
    // Seach through match operands for the same name usage.
    uint cur_num_opnds = node->num_opnds();
    if( cur_num_opnds > 1 && cur_num_opnds != node->num_unique_opnds() ) {
      Component *comp = NULL;
      // Build mapping from num_edges to local variables
      fprintf(fp,"  unsigned num0 = 0;\n");
      for( i = 1; i < cur_num_opnds; i++ ) {
        fprintf(fp,"  unsigned num%d = opnd_array(%d)->num_edges();\n",i,i);
      }
      // Build a mapping from operand index to input edges
      fprintf(fp,"  unsigned idx0 = oper_input_base();\n");
      for( i = 0; i < cur_num_opnds; i++ ) {
        fprintf(fp,"  unsigned idx%d = idx%d + num%d;\n",
                i+1,i,i);
      }

      uint new_num_opnds = 1;
      node->_components.reset();
      // Skip first unique operands.
      for( i = 1; i < cur_num_opnds; i++ ) {
        comp = node->_components.iter();
        if( (int)i != node->unique_opnds_idx(i) ) {
          break;
        }
        new_num_opnds++;
      }
      // Replace not unique operands with next unique operands.
      for( ; i < cur_num_opnds; i++ ) {
        comp = node->_components.iter();
        int j = node->unique_opnds_idx(i);
        // unique_opnds_idx(i) is unique if unique_opnds_idx(j) is not unique.
        if( j != node->unique_opnds_idx(j) ) {
          fprintf(fp,"  set_opnd_array(%d, opnd_array(%d)->clone(C)); // %s\n",
                  new_num_opnds, i, comp->_name);
          // delete not unique edges here
          fprintf(fp,"  for(unsigned i = 0; i < num%d; i++) {\n", i);
          fprintf(fp,"    set_req(i + idx%d, _in[i + idx%d]);\n", new_num_opnds, i);
          fprintf(fp,"  }\n");
          fprintf(fp,"  num%d = num%d;\n", new_num_opnds, i);
          fprintf(fp,"  idx%d = idx%d + num%d;\n", new_num_opnds+1, new_num_opnds, new_num_opnds);
          new_num_opnds++;
        }
      }
      // delete the rest of edges
      fprintf(fp,"  for(int i = idx%d - 1; i >= (int)idx%d; i--) {\n", cur_num_opnds, new_num_opnds);
      fprintf(fp,"    del_req(i);\n");
      fprintf(fp,"  }\n");
      fprintf(fp,"  _num_opnds = %d;\n", new_num_opnds);
      assert(new_num_opnds == node->num_unique_opnds(), "what?");
    }
  }

  // If the node is a MachConstantNode, insert the MachConstantBaseNode edge.
  // NOTE: this edge must be the last input (see MachConstantNode::mach_constant_base_node_input).
  if (node->is_mach_constant()) {
    fprintf(fp,"  add_req(C->mach_constant_base_node());\n");
  }

  fprintf(fp,"\n");
  if( node->expands() ) {
    fprintf(fp,"  return result;\n");
  } else {
    fprintf(fp,"  return this;\n");
  }
  fprintf(fp,"}\n");
  fprintf(fp,"\n");
}


//------------------------------Emit Routines----------------------------------
// Special classes and routines for defining node emit routines which output
// target specific instruction object encodings.
// Define the ___Node::emit() routine
//
// (1) void  ___Node::emit(CodeBuffer &cbuf, PhaseRegAlloc *ra_) const {
// (2)   // ...  encoding defined by user
// (3)
// (4) }
//

class DefineEmitState {
private:
  enum reloc_format { RELOC_NONE        = -1,
                      RELOC_IMMEDIATE   =  0,
                      RELOC_DISP        =  1,
                      RELOC_CALL_DISP   =  2 };
  enum literal_status{ LITERAL_NOT_SEEN  = 0,
                       LITERAL_SEEN      = 1,
                       LITERAL_ACCESSED  = 2,
                       LITERAL_OUTPUT    = 3 };
  // Temporaries that describe current operand
  bool          _cleared;
  OpClassForm  *_opclass;
  OperandForm  *_operand;
  int           _operand_idx;
  const char   *_local_name;
  const char   *_operand_name;
  bool          _doing_disp;
  bool          _doing_constant;
  Form::DataType _constant_type;
  DefineEmitState::literal_status _constant_status;
  DefineEmitState::literal_status _reg_status;
  bool          _doing_emit8;
  bool          _doing_emit_d32;
  bool          _doing_emit_d16;
  bool          _doing_emit_hi;
  bool          _doing_emit_lo;
  bool          _may_reloc;
  reloc_format  _reloc_form;
  const char *  _reloc_type;
  bool          _processing_noninput;

  NameList      _strings_to_emit;

  // Stable state, set by constructor
  ArchDesc     &_AD;
  FILE         *_fp;
  EncClass     &_encoding;
  InsEncode    &_ins_encode;
  InstructForm &_inst;

public:
  DefineEmitState(FILE *fp, ArchDesc &AD, EncClass &encoding,
                  InsEncode &ins_encode, InstructForm &inst)
    : _AD(AD), _fp(fp), _encoding(encoding), _ins_encode(ins_encode), _inst(inst) {
      clear();
  }

  void clear() {
    _cleared       = true;
    _opclass       = NULL;
    _operand       = NULL;
    _operand_idx   = 0;
    _local_name    = "";
    _operand_name  = "";
    _doing_disp    = false;
    _doing_constant= false;
    _constant_type = Form::none;
    _constant_status = LITERAL_NOT_SEEN;
    _reg_status      = LITERAL_NOT_SEEN;
    _doing_emit8   = false;
    _doing_emit_d32= false;
    _doing_emit_d16= false;
    _doing_emit_hi = false;
    _doing_emit_lo = false;
    _may_reloc     = false;
    _reloc_form    = RELOC_NONE;
    _reloc_type    = AdlcVMDeps::none_reloc_type();
    _strings_to_emit.clear();
  }

  // Track necessary state when identifying a replacement variable
  void update_state(const char *rep_var) {
    // A replacement variable or one of its subfields
    // Obtain replacement variable from list
    if ( (*rep_var) != '$' ) {
      // A replacement variable, '$' prefix
      // check_rep_var( rep_var );
      if ( Opcode::as_opcode_type(rep_var) != Opcode::NOT_AN_OPCODE ) {
        // No state needed.
        assert( _opclass == NULL,
                "'primary', 'secondary' and 'tertiary' don't follow operand.");
      }
      else if ((strcmp(rep_var, "constanttablebase") == 0) ||
               (strcmp(rep_var, "constantoffset")    == 0) ||
               (strcmp(rep_var, "constantaddress")   == 0)) {
        if (!_inst.is_mach_constant()) {
          _AD.syntax_err(_encoding._linenum,
                         "Replacement variable %s not allowed in instruct %s (only in MachConstantNode).\n",
                         rep_var, _encoding._name);
        }
      }
      else {
        // Lookup its position in parameter list
        int   param_no  = _encoding.rep_var_index(rep_var);
        if ( param_no == -1 ) {
          _AD.syntax_err( _encoding._linenum,
                          "Replacement variable %s not found in enc_class %s.\n",
                          rep_var, _encoding._name);
        }

        // Lookup the corresponding ins_encode parameter
        const char *inst_rep_var = _ins_encode.rep_var_name(_inst, param_no);
        if (inst_rep_var == NULL) {
          _AD.syntax_err( _ins_encode._linenum,
                          "Parameter %s not passed to enc_class %s from instruct %s.\n",
                          rep_var, _encoding._name, _inst._ident);
        }

        // Check if instruction's actual parameter is a local name in the instruction
        const Form  *local     = _inst._localNames[inst_rep_var];
        OpClassForm *opc       = (local != NULL) ? local->is_opclass() : NULL;
        // Note: assert removed to allow constant and symbolic parameters
        // assert( opc, "replacement variable was not found in local names");
        // Lookup the index position iff the replacement variable is a localName
        int idx  = (opc != NULL) ? _inst.operand_position_format(inst_rep_var) : -1;

        if ( idx != -1 ) {
          // This is a local in the instruction
          // Update local state info.
          _opclass        = opc;
          _operand_idx    = idx;
          _local_name     = rep_var;
          _operand_name   = inst_rep_var;

          // !!!!!
          // Do not support consecutive operands.
          assert( _operand == NULL, "Unimplemented()");
          _operand = opc->is_operand();
        }
        else if( ADLParser::is_literal_constant(inst_rep_var) ) {
          // Instruction provided a constant expression
          // Check later that encoding specifies $$$constant to resolve as constant
          _constant_status   = LITERAL_SEEN;
        }
        else if( Opcode::as_opcode_type(inst_rep_var) != Opcode::NOT_AN_OPCODE ) {
          // Instruction provided an opcode: "primary", "secondary", "tertiary"
          // Check later that encoding specifies $$$constant to resolve as constant
          _constant_status   = LITERAL_SEEN;
        }
        else if((_AD.get_registers() != NULL ) && (_AD.get_registers()->getRegDef(inst_rep_var) != NULL)) {
          // Instruction provided a literal register name for this parameter
          // Check that encoding specifies $$$reg to resolve.as register.
          _reg_status        = LITERAL_SEEN;
        }
        else {
          // Check for unimplemented functionality before hard failure
          assert( strcmp(opc->_ident,"label")==0, "Unimplemented() Label");
          assert( false, "ShouldNotReachHere()");
        }
      } // done checking which operand this is.
    } else {
      //
      // A subfield variable, '$$' prefix
      // Check for fields that may require relocation information.
      // Then check that literal register parameters are accessed with 'reg' or 'constant'
      //
      if ( strcmp(rep_var,"$disp") == 0 ) {
        _doing_disp = true;
        assert( _opclass, "Must use operand or operand class before '$disp'");
        if( _operand == NULL ) {
          // Only have an operand class, generate run-time check for relocation
          _may_reloc    = true;
          _reloc_form   = RELOC_DISP;
          _reloc_type   = AdlcVMDeps::oop_reloc_type();
        } else {
          // Do precise check on operand: is it a ConP or not
          //
          // Check interface for value of displacement
          assert( ( _operand->_interface != NULL ),
                  "$disp can only follow memory interface operand");
          MemInterface *mem_interface= _operand->_interface->is_MemInterface();
          assert( mem_interface != NULL,
                  "$disp can only follow memory interface operand");
          const char *disp = mem_interface->_disp;

          if( disp != NULL && (*disp == '$') ) {
            // MemInterface::disp contains a replacement variable,
            // Check if this matches a ConP
            //
            // Lookup replacement variable, in operand's component list
            const char *rep_var_name = disp + 1; // Skip '$'
            const Component *comp = _operand->_components.search(rep_var_name);
            assert( comp != NULL,"Replacement variable not found in components");
            const char      *type = comp->_type;
            // Lookup operand form for replacement variable's type
            const Form *form = _AD.globalNames()[type];
            assert( form != NULL, "Replacement variable's type not found");
            OperandForm *op = form->is_operand();
            assert( op, "Attempting to emit a non-register or non-constant");
            // Check if this is a constant
            if (op->_matrule && op->_matrule->is_base_constant(_AD.globalNames())) {
              // Check which constant this name maps to: _c0, _c1, ..., _cn
              // const int idx = _operand.constant_position(_AD.globalNames(), comp);
              // assert( idx != -1, "Constant component not found in operand");
              Form::DataType dtype = op->is_base_constant(_AD.globalNames());
              if ( dtype == Form::idealP ) {
                _may_reloc    = true;
                // No longer true that idealP is always an oop
                _reloc_form   = RELOC_DISP;
                _reloc_type   = AdlcVMDeps::oop_reloc_type();
              }
            }

            else if( _operand->is_user_name_for_sReg() != Form::none ) {
              // The only non-constant allowed access to disp is an operand sRegX in a stackSlotX
              assert( op->ideal_to_sReg_type(type) != Form::none, "StackSlots access displacements using 'sRegs'");
              _may_reloc   = false;
            } else {
              assert( false, "fatal(); Only stackSlots can access a non-constant using 'disp'");
            }
          }
        } // finished with precise check of operand for relocation.
      } // finished with subfield variable
      else if ( strcmp(rep_var,"$constant") == 0 ) {
        _doing_constant = true;
        if ( _constant_status == LITERAL_NOT_SEEN ) {
          // Check operand for type of constant
          assert( _operand, "Must use operand before '$$constant'");
          Form::DataType dtype = _operand->is_base_constant(_AD.globalNames());
          _constant_type = dtype;
          if ( dtype == Form::idealP ) {
            _may_reloc    = true;
            // No longer true that idealP is always an oop
            // // _must_reloc   = true;
            _reloc_form   = RELOC_IMMEDIATE;
            _reloc_type   = AdlcVMDeps::oop_reloc_type();
          } else {
            // No relocation information needed
          }
        } else {
          // User-provided literals may not require relocation information !!!!!
          assert( _constant_status == LITERAL_SEEN, "Must know we are processing a user-provided literal");
        }
      }
      else if ( strcmp(rep_var,"$label") == 0 ) {
        // Calls containing labels require relocation
        if ( _inst.is_ideal_call() )  {
          _may_reloc    = true;
          // !!!!! !!!!!
          _reloc_type   = AdlcVMDeps::none_reloc_type();
        }
      }

      // literal register parameter must be accessed as a 'reg' field.
      if ( _reg_status != LITERAL_NOT_SEEN ) {
        assert( _reg_status == LITERAL_SEEN, "Must have seen register literal before now");
        if (strcmp(rep_var,"$reg") == 0 || reg_conversion(rep_var) != NULL) {
          _reg_status  = LITERAL_ACCESSED;
        } else {
          assert( false, "invalid access to literal register parameter");
        }
      }
      // literal constant parameters must be accessed as a 'constant' field
      if ( _constant_status != LITERAL_NOT_SEEN ) {
        assert( _constant_status == LITERAL_SEEN, "Must have seen constant literal before now");
        if( strcmp(rep_var,"$constant") == 0 ) {
          _constant_status  = LITERAL_ACCESSED;
        } else {
          assert( false, "invalid access to literal constant parameter");
        }
      }
    } // end replacement and/or subfield

  }

  void add_rep_var(const char *rep_var) {
    // Handle subfield and replacement variables.
    if ( ( *rep_var == '$' ) && ( *(rep_var+1) == '$' ) ) {
      // Check for emit prefix, '$$emit32'
      assert( _cleared, "Can not nest $$$emit32");
      if ( strcmp(rep_var,"$$emit32") == 0 ) {
        _doing_emit_d32 = true;
      }
      else if ( strcmp(rep_var,"$$emit16") == 0 ) {
        _doing_emit_d16 = true;
      }
      else if ( strcmp(rep_var,"$$emit_hi") == 0 ) {
        _doing_emit_hi  = true;
      }
      else if ( strcmp(rep_var,"$$emit_lo") == 0 ) {
        _doing_emit_lo  = true;
      }
      else if ( strcmp(rep_var,"$$emit8") == 0 ) {
        _doing_emit8    = true;
      }
      else {
        _AD.syntax_err(_encoding._linenum, "Unsupported $$operation '%s'\n",rep_var);
        assert( false, "fatal();");
      }
    }
    else {
      // Update state for replacement variables
      update_state( rep_var );
      _strings_to_emit.addName(rep_var);
    }
    _cleared  = false;
  }

  void emit_replacement() {
    // A replacement variable or one of its subfields
    // Obtain replacement variable from list
    // const char *ec_rep_var = encoding->_rep_vars.iter();
    const char *rep_var;
    _strings_to_emit.reset();
    while ( (rep_var = _strings_to_emit.iter()) != NULL ) {

      if ( (*rep_var) == '$' ) {
        // A subfield variable, '$$' prefix
        emit_field( rep_var );
      } else {
        if (_strings_to_emit.peek() != NULL &&
            strcmp(_strings_to_emit.peek(), "$Address") == 0) {
          fprintf(_fp, "Address::make_raw(");

          emit_rep_var( rep_var );
          fprintf(_fp,"->base(ra_,this,idx%d), ", _operand_idx);

          _reg_status = LITERAL_ACCESSED;
          emit_rep_var( rep_var );
          fprintf(_fp,"->index(ra_,this,idx%d), ", _operand_idx);

          _reg_status = LITERAL_ACCESSED;
          emit_rep_var( rep_var );
          fprintf(_fp,"->scale(), ");

          _reg_status = LITERAL_ACCESSED;
          emit_rep_var( rep_var );
          Form::DataType stack_type = _operand ? _operand->is_user_name_for_sReg() : Form::none;
          if( _operand  && _operand_idx==0 && stack_type != Form::none ) {
            fprintf(_fp,"->disp(ra_,this,0), ");
          } else {
            fprintf(_fp,"->disp(ra_,this,idx%d), ", _operand_idx);
          }

          _reg_status = LITERAL_ACCESSED;
          emit_rep_var( rep_var );
          fprintf(_fp,"->disp_reloc())");

          // skip trailing $Address
          _strings_to_emit.iter();
        } else {
          // A replacement variable, '$' prefix
          const char* next = _strings_to_emit.peek();
          const char* next2 = _strings_to_emit.peek(2);
          if (next != NULL && next2 != NULL && strcmp(next2, "$Register") == 0 &&
              (strcmp(next, "$base") == 0 || strcmp(next, "$index") == 0)) {
            // handle $rev_var$$base$$Register and $rev_var$$index$$Register by
            // producing as_Register(opnd_array(#)->base(ra_,this,idx1)).
            fprintf(_fp, "as_Register(");
            // emit the operand reference
            emit_rep_var( rep_var );
            rep_var = _strings_to_emit.iter();
            assert(strcmp(rep_var, "$base") == 0 || strcmp(rep_var, "$index") == 0, "bad pattern");
            // handle base or index
            emit_field(rep_var);
            rep_var = _strings_to_emit.iter();
            assert(strcmp(rep_var, "$Register") == 0, "bad pattern");
            // close up the parens
            fprintf(_fp, ")");
          } else {
            emit_rep_var( rep_var );
          }
        }
      } // end replacement and/or subfield
    }
  }

  void emit_reloc_type(const char* type) {
    fprintf(_fp, "%s", type)
      ;
  }


  void emit() {
    //
    //   "emit_d32_reloc(" or "emit_hi_reloc" or "emit_lo_reloc"
    //
    // Emit the function name when generating an emit function
    if ( _doing_emit_d32 || _doing_emit_hi || _doing_emit_lo ) {
      const char *d32_hi_lo = _doing_emit_d32 ? "d32" : (_doing_emit_hi ? "hi" : "lo");
      // In general, relocatable isn't known at compiler compile time.
      // Check results of prior scan
      if ( ! _may_reloc ) {
        // Definitely don't need relocation information
        fprintf( _fp, "emit_%s(cbuf, ", d32_hi_lo );
        emit_replacement(); fprintf(_fp, ")");
      }
      else {
        // Emit RUNTIME CHECK to see if value needs relocation info
        // If emitting a relocatable address, use 'emit_d32_reloc'
        const char *disp_constant = _doing_disp ? "disp" : _doing_constant ? "constant" : "INVALID";
        assert( (_doing_disp || _doing_constant)
                && !(_doing_disp && _doing_constant),
                "Must be emitting either a displacement or a constant");
        fprintf(_fp,"\n");
        fprintf(_fp,"if ( opnd_array(%d)->%s_reloc() != relocInfo::none ) {\n",
                _operand_idx, disp_constant);
        fprintf(_fp,"  ");
        fprintf(_fp,"emit_%s_reloc(cbuf, ", d32_hi_lo );
        emit_replacement();             fprintf(_fp,", ");
        fprintf(_fp,"opnd_array(%d)->%s_reloc(), ",
                _operand_idx, disp_constant);
        fprintf(_fp, "%d", _reloc_form);fprintf(_fp, ");");
        fprintf(_fp,"\n");
        fprintf(_fp,"} else {\n");
        fprintf(_fp,"  emit_%s(cbuf, ", d32_hi_lo);
        emit_replacement(); fprintf(_fp, ");\n"); fprintf(_fp,"}");
      }
    }
    else if ( _doing_emit_d16 ) {
      // Relocation of 16-bit values is not supported
      fprintf(_fp,"emit_d16(cbuf, ");
      emit_replacement(); fprintf(_fp, ")");
      // No relocation done for 16-bit values
    }
    else if ( _doing_emit8 ) {
      // Relocation of 8-bit values is not supported
      fprintf(_fp,"emit_d8(cbuf, ");
      emit_replacement(); fprintf(_fp, ")");
      // No relocation done for 8-bit values
    }
    else {
      // Not an emit# command, just output the replacement string.
      emit_replacement();
    }

    // Get ready for next state collection.
    clear();
  }

private:

  // recognizes names which represent MacroAssembler register types
  // and return the conversion function to build them from OptoReg
  const char* reg_conversion(const char* rep_var) {
    if (strcmp(rep_var,"$Register") == 0)      return "as_Register";
    if (strcmp(rep_var,"$FloatRegister") == 0) return "as_FloatRegister";
#if defined(IA32) || defined(AMD64)
    if (strcmp(rep_var,"$XMMRegister") == 0)   return "as_XMMRegister";
#endif
    return NULL;
  }

  void emit_field(const char *rep_var) {
    const char* reg_convert = reg_conversion(rep_var);

    // A subfield variable, '$$subfield'
    if ( strcmp(rep_var, "$reg") == 0 || reg_convert != NULL) {
      // $reg form or the $Register MacroAssembler type conversions
      assert( _operand_idx != -1,
              "Must use this subfield after operand");
      if( _reg_status == LITERAL_NOT_SEEN ) {
        if (_processing_noninput) {
          const Form  *local     = _inst._localNames[_operand_name];
          OperandForm *oper      = local->is_operand();
          const RegDef* first = oper->get_RegClass()->find_first_elem();
          if (reg_convert != NULL) {
            fprintf(_fp, "%s(%s_enc)", reg_convert, first->_regname);
          } else {
            fprintf(_fp, "%s_enc", first->_regname);
          }
        } else {
          fprintf(_fp,"->%s(ra_,this", reg_convert != NULL ? reg_convert : "reg");
          // Add parameter for index position, if not result operand
          if( _operand_idx != 0 ) fprintf(_fp,",idx%d", _operand_idx);
          fprintf(_fp,")");
        }
      } else {
        assert( _reg_status == LITERAL_OUTPUT, "should have output register literal in emit_rep_var");
        // Register literal has already been sent to output file, nothing more needed
      }
    }
    else if ( strcmp(rep_var,"$base") == 0 ) {
      assert( _operand_idx != -1,
              "Must use this subfield after operand");
      assert( ! _may_reloc, "UnImplemented()");
      fprintf(_fp,"->base(ra_,this,idx%d)", _operand_idx);
    }
    else if ( strcmp(rep_var,"$index") == 0 ) {
      assert( _operand_idx != -1,
              "Must use this subfield after operand");
      assert( ! _may_reloc, "UnImplemented()");
      fprintf(_fp,"->index(ra_,this,idx%d)", _operand_idx);
    }
    else if ( strcmp(rep_var,"$scale") == 0 ) {
      assert( ! _may_reloc, "UnImplemented()");
      fprintf(_fp,"->scale()");
    }
    else if ( strcmp(rep_var,"$cmpcode") == 0 ) {
      assert( ! _may_reloc, "UnImplemented()");
      fprintf(_fp,"->ccode()");
    }
    else if ( strcmp(rep_var,"$constant") == 0 ) {
      if( _constant_status == LITERAL_NOT_SEEN ) {
        if ( _constant_type == Form::idealD ) {
          fprintf(_fp,"->constantD()");
        } else if ( _constant_type == Form::idealF ) {
          fprintf(_fp,"->constantF()");
        } else if ( _constant_type == Form::idealL ) {
          fprintf(_fp,"->constantL()");
        } else {
          fprintf(_fp,"->constant()");
        }
      } else {
        assert( _constant_status == LITERAL_OUTPUT, "should have output constant literal in emit_rep_var");
        // Cosntant literal has already been sent to output file, nothing more needed
      }
    }
    else if ( strcmp(rep_var,"$disp") == 0 ) {
      Form::DataType stack_type = _operand ? _operand->is_user_name_for_sReg() : Form::none;
      if( _operand  && _operand_idx==0 && stack_type != Form::none ) {
        fprintf(_fp,"->disp(ra_,this,0)");
      } else {
        fprintf(_fp,"->disp(ra_,this,idx%d)", _operand_idx);
      }
    }
    else if ( strcmp(rep_var,"$label") == 0 ) {
      fprintf(_fp,"->label()");
    }
    else if ( strcmp(rep_var,"$method") == 0 ) {
      fprintf(_fp,"->method()");
    }
    else {
      printf("emit_field: %s\n",rep_var);
      assert( false, "UnImplemented()");
    }
  }


  void emit_rep_var(const char *rep_var) {
    _processing_noninput = false;
    // A replacement variable, originally '$'
    if ( Opcode::as_opcode_type(rep_var) != Opcode::NOT_AN_OPCODE ) {
      if (!_inst._opcode->print_opcode(_fp, Opcode::as_opcode_type(rep_var) )) {
        // Missing opcode
        _AD.syntax_err( _inst._linenum,
                        "Missing $%s opcode definition in %s, used by encoding %s\n",
                        rep_var, _inst._ident, _encoding._name);
      }
    }
    else if (strcmp(rep_var, "constanttablebase") == 0) {
      fprintf(_fp, "as_Register(ra_->get_encode(in(mach_constant_base_node_input())))");
    }
    else if (strcmp(rep_var, "constantoffset") == 0) {
      fprintf(_fp, "constant_offset()");
    }
    else if (strcmp(rep_var, "constantaddress") == 0) {
      fprintf(_fp, "InternalAddress(__ code()->consts()->start() + constant_offset())");
    }
    else {
      // Lookup its position in parameter list
      int   param_no  = _encoding.rep_var_index(rep_var);
      if ( param_no == -1 ) {
        _AD.syntax_err( _encoding._linenum,
                        "Replacement variable %s not found in enc_class %s.\n",
                        rep_var, _encoding._name);
      }
      // Lookup the corresponding ins_encode parameter
      const char *inst_rep_var = _ins_encode.rep_var_name(_inst, param_no);

      // Check if instruction's actual parameter is a local name in the instruction
      const Form  *local     = _inst._localNames[inst_rep_var];
      OpClassForm *opc       = (local != NULL) ? local->is_opclass() : NULL;
      // Note: assert removed to allow constant and symbolic parameters
      // assert( opc, "replacement variable was not found in local names");
      // Lookup the index position iff the replacement variable is a localName
      int idx  = (opc != NULL) ? _inst.operand_position_format(inst_rep_var) : -1;
      if( idx != -1 ) {
        if (_inst.is_noninput_operand(idx)) {
          // This operand isn't a normal input so printing it is done
          // specially.
          _processing_noninput = true;
        } else {
          // Output the emit code for this operand
          fprintf(_fp,"opnd_array(%d)",idx);
        }
        assert( _operand == opc->is_operand(),
                "Previous emit $operand does not match current");
      }
      else if( ADLParser::is_literal_constant(inst_rep_var) ) {
        // else check if it is a constant expression
        // Removed following assert to allow primitive C types as arguments to encodings
        // assert( _constant_status == LITERAL_ACCESSED, "Must be processing a literal constant parameter");
        fprintf(_fp,"(%s)", inst_rep_var);
        _constant_status = LITERAL_OUTPUT;
      }
      else if( Opcode::as_opcode_type(inst_rep_var) != Opcode::NOT_AN_OPCODE ) {
        // else check if "primary", "secondary", "tertiary"
        assert( _constant_status == LITERAL_ACCESSED, "Must be processing a literal constant parameter");
        if (!_inst._opcode->print_opcode(_fp, Opcode::as_opcode_type(inst_rep_var) )) {
          // Missing opcode
          _AD.syntax_err( _inst._linenum,
                          "Missing $%s opcode definition in %s\n",
                          rep_var, _inst._ident);

        }
        _constant_status = LITERAL_OUTPUT;
      }
      else if((_AD.get_registers() != NULL ) && (_AD.get_registers()->getRegDef(inst_rep_var) != NULL)) {
        // Instruction provided a literal register name for this parameter
        // Check that encoding specifies $$$reg to resolve.as register.
        assert( _reg_status == LITERAL_ACCESSED, "Must be processing a literal register parameter");
        fprintf(_fp,"(%s_enc)", inst_rep_var);
        _reg_status = LITERAL_OUTPUT;
      }
      else {
        // Check for unimplemented functionality before hard failure
        assert( strcmp(opc->_ident,"label")==0, "Unimplemented() Label");
        assert( false, "ShouldNotReachHere()");
      }
      // all done
    }
  }

};  // end class DefineEmitState


void ArchDesc::defineSize(FILE *fp, InstructForm &inst) {

  //(1)
  // Output instruction's emit prototype
  fprintf(fp,"uint  %sNode::size(PhaseRegAlloc *ra_) const {\n",
          inst._ident);

  fprintf(fp, " assert(VerifyOops || MachNode::size(ra_) <= %s, \"bad fixed size\");\n", inst._size);

  //(2)
  // Print the size
  fprintf(fp, " return (VerifyOops ? MachNode::size(ra_) : %s);\n", inst._size);

  // (3) and (4)
  fprintf(fp,"}\n");
}

// defineEmit -----------------------------------------------------------------
void ArchDesc::defineEmit(FILE* fp, InstructForm& inst) {
  InsEncode* encode = inst._insencode;

  // (1)
  // Output instruction's emit prototype
  fprintf(fp, "void %sNode::emit(CodeBuffer& cbuf, PhaseRegAlloc* ra_) const {\n", inst._ident);

  // If user did not define an encode section,
  // provide stub that does not generate any machine code.
  if( (_encode == NULL) || (encode == NULL) ) {
    fprintf(fp, "  // User did not define an encode section.\n");
    fprintf(fp, "}\n");
    return;
  }

  // Save current instruction's starting address (helps with relocation).
  fprintf(fp, "  cbuf.set_insts_mark();\n");

  // For MachConstantNodes which are ideal jump nodes, fill the jump table.
  if (inst.is_mach_constant() && inst.is_ideal_jump()) {
    fprintf(fp, "  ra_->C->constant_table().fill_jump_table(cbuf, (MachConstantNode*) this, _index2label);\n");
  }

  // Output each operand's offset into the array of registers.
  inst.index_temps(fp, _globalNames);

  // Output this instruction's encodings
  const char *ec_name;
  bool        user_defined = false;
  encode->reset();
  while ((ec_name = encode->encode_class_iter()) != NULL) {
    fprintf(fp, "  {\n");
    // Output user-defined encoding
    user_defined           = true;

    const char *ec_code    = NULL;
    const char *ec_rep_var = NULL;
    EncClass   *encoding   = _encode->encClass(ec_name);
    if (encoding == NULL) {
      fprintf(stderr, "User did not define contents of this encode_class: %s\n", ec_name);
      abort();
    }

    if (encode->current_encoding_num_args() != encoding->num_args()) {
      globalAD->syntax_err(encode->_linenum, "In %s: passing %d arguments to %s but expecting %d",
                           inst._ident, encode->current_encoding_num_args(),
                           ec_name, encoding->num_args());
    }

    DefineEmitState pending(fp, *this, *encoding, *encode, inst);
    encoding->_code.reset();
    encoding->_rep_vars.reset();
    // Process list of user-defined strings,
    // and occurrences of replacement variables.
    // Replacement Vars are pushed into a list and then output
    while ((ec_code = encoding->_code.iter()) != NULL) {
      if (!encoding->_code.is_signal(ec_code)) {
        // Emit pending code
        pending.emit();
        pending.clear();
        // Emit this code section
        fprintf(fp, "%s", ec_code);
      } else {
        // A replacement variable or one of its subfields
        // Obtain replacement variable from list
        ec_rep_var  = encoding->_rep_vars.iter();
        pending.add_rep_var(ec_rep_var);
      }
    }
    // Emit pending code
    pending.emit();
    pending.clear();
    fprintf(fp, "  }\n");
  } // end while instruction's encodings

  // Check if user stated which encoding to user
  if ( user_defined == false ) {
    fprintf(fp, "  // User did not define which encode class to use.\n");
  }

  // (3) and (4)
  fprintf(fp, "}\n");
}

// defineEvalConstant ---------------------------------------------------------
void ArchDesc::defineEvalConstant(FILE* fp, InstructForm& inst) {
  InsEncode* encode = inst._constant;

  // (1)
  // Output instruction's emit prototype
  fprintf(fp, "void %sNode::eval_constant(Compile* C) {\n", inst._ident);

  // For ideal jump nodes, add a jump-table entry.
  if (inst.is_ideal_jump()) {
    fprintf(fp, "  _constant = C->constant_table().add_jump_table(this);\n");
  }

  // If user did not define an encode section,
  // provide stub that does not generate any machine code.
  if ((_encode == NULL) || (encode == NULL)) {
    fprintf(fp, "  // User did not define an encode section.\n");
    fprintf(fp, "}\n");
    return;
  }

  // Output this instruction's encodings
  const char *ec_name;
  bool        user_defined = false;
  encode->reset();
  while ((ec_name = encode->encode_class_iter()) != NULL) {
    fprintf(fp, "  {\n");
    // Output user-defined encoding
    user_defined           = true;

    const char *ec_code    = NULL;
    const char *ec_rep_var = NULL;
    EncClass   *encoding   = _encode->encClass(ec_name);
    if (encoding == NULL) {
      fprintf(stderr, "User did not define contents of this encode_class: %s\n", ec_name);
      abort();
    }

    if (encode->current_encoding_num_args() != encoding->num_args()) {
      globalAD->syntax_err(encode->_linenum, "In %s: passing %d arguments to %s but expecting %d",
                           inst._ident, encode->current_encoding_num_args(),
                           ec_name, encoding->num_args());
    }

    DefineEmitState pending(fp, *this, *encoding, *encode, inst);
    encoding->_code.reset();
    encoding->_rep_vars.reset();
    // Process list of user-defined strings,
    // and occurrences of replacement variables.
    // Replacement Vars are pushed into a list and then output
    while ((ec_code = encoding->_code.iter()) != NULL) {
      if (!encoding->_code.is_signal(ec_code)) {
        // Emit pending code
        pending.emit();
        pending.clear();
        // Emit this code section
        fprintf(fp, "%s", ec_code);
      } else {
        // A replacement variable or one of its subfields
        // Obtain replacement variable from list
        ec_rep_var  = encoding->_rep_vars.iter();
        pending.add_rep_var(ec_rep_var);
      }
    }
    // Emit pending code
    pending.emit();
    pending.clear();
    fprintf(fp, "  }\n");
  } // end while instruction's encodings

  // Check if user stated which encoding to user
  if (user_defined == false) {
    fprintf(fp, "  // User did not define which encode class to use.\n");
  }

  // (3) and (4)
  fprintf(fp, "}\n");
}

// ---------------------------------------------------------------------------
//--------Utilities to build MachOper and MachNode derived Classes------------
// ---------------------------------------------------------------------------

//------------------------------Utilities to build Operand Classes------------
static void defineIn_RegMask(FILE *fp, FormDict &globals, OperandForm &oper) {
  uint num_edges = oper.num_edges(globals);
  if( num_edges != 0 ) {
    // Method header
    fprintf(fp, "const RegMask *%sOper::in_RegMask(int index) const {\n",
            oper._ident);

    // Assert that the index is in range.
    fprintf(fp, "  assert(0 <= index && index < %d, \"index out of range\");\n",
            num_edges);

    // Figure out if all RegMasks are the same.
    const char* first_reg_class = oper.in_reg_class(0, globals);
    bool all_same = true;
    assert(first_reg_class != NULL, "did not find register mask");

    for (uint index = 1; all_same && index < num_edges; index++) {
      const char* some_reg_class = oper.in_reg_class(index, globals);
      assert(some_reg_class != NULL, "did not find register mask");
      if (strcmp(first_reg_class, some_reg_class) != 0) {
        all_same = false;
      }
    }

    if (all_same) {
      // Return the sole RegMask.
      if (strcmp(first_reg_class, "stack_slots") == 0) {
        fprintf(fp,"  return &(Compile::current()->FIRST_STACK_mask());\n");
      } else {
        fprintf(fp,"  return &%s_mask();\n", toUpper(first_reg_class));
      }
    } else {
      // Build a switch statement to return the desired mask.
      fprintf(fp,"  switch (index) {\n");

      for (uint index = 0; index < num_edges; index++) {
        const char *reg_class = oper.in_reg_class(index, globals);
        assert(reg_class != NULL, "did not find register mask");
        if( !strcmp(reg_class, "stack_slots") ) {
          fprintf(fp, "  case %d: return &(Compile::current()->FIRST_STACK_mask());\n", index);
        } else {
          fprintf(fp, "  case %d: return &%s_mask();\n", index, toUpper(reg_class));
        }
      }
      fprintf(fp,"  }\n");
      fprintf(fp,"  ShouldNotReachHere();\n");
      fprintf(fp,"  return NULL;\n");
    }

    // Method close
    fprintf(fp, "}\n\n");
  }
}

// generate code to create a clone for a class derived from MachOper
//
// (0)  MachOper  *MachOperXOper::clone(Compile* C) const {
// (1)    return new (C) MachXOper( _ccode, _c0, _c1, ..., _cn);
// (2)  }
//
static void defineClone(FILE *fp, FormDict &globalNames, OperandForm &oper) {
  fprintf(fp,"MachOper  *%sOper::clone(Compile* C) const {\n", oper._ident);
  // Check for constants that need to be copied over
  const int  num_consts    = oper.num_consts(globalNames);
  const bool is_ideal_bool = oper.is_ideal_bool();
  if( (num_consts > 0) ) {
    fprintf(fp,"  return  new (C) %sOper(", oper._ident);
    // generate parameters for constants
    int i = 0;
    fprintf(fp,"_c%d", i);
    for( i = 1; i < num_consts; ++i) {
      fprintf(fp,", _c%d", i);
    }
    // finish line (1)
    fprintf(fp,");\n");
  }
  else {
    assert( num_consts == 0, "Currently support zero or one constant per operand clone function");
    fprintf(fp,"  return  new (C) %sOper();\n", oper._ident);
  }
  // finish method
  fprintf(fp,"}\n");
}

static void define_hash(FILE *fp, char *operand) {
  fprintf(fp,"uint %sOper::hash() const { return 5; }\n", operand);
}

static void define_cmp(FILE *fp, char *operand) {
  fprintf(fp,"uint %sOper::cmp( const MachOper &oper ) const { return opcode() == oper.opcode(); }\n", operand);
}


// Helper functions for bug 4796752, abstracted with minimal modification
// from define_oper_interface()
OperandForm *rep_var_to_operand(const char *encoding, OperandForm &oper, FormDict &globals) {
  OperandForm *op = NULL;
  // Check for replacement variable
  if( *encoding == '$' ) {
    // Replacement variable
    const char *rep_var = encoding + 1;
    // Lookup replacement variable, rep_var, in operand's component list
    const Component *comp = oper._components.search(rep_var);
    assert( comp != NULL, "Replacement variable not found in components");
    // Lookup operand form for replacement variable's type
    const char      *type = comp->_type;
    Form            *form = (Form*)globals[type];
    assert( form != NULL, "Replacement variable's type not found");
    op = form->is_operand();
    assert( op, "Attempting to emit a non-register or non-constant");
  }

  return op;
}

int rep_var_to_constant_index(const char *encoding, OperandForm &oper, FormDict &globals) {
  int idx = -1;
  // Check for replacement variable
  if( *encoding == '$' ) {
    // Replacement variable
    const char *rep_var = encoding + 1;
    // Lookup replacement variable, rep_var, in operand's component list
    const Component *comp = oper._components.search(rep_var);
    assert( comp != NULL, "Replacement variable not found in components");
    // Lookup operand form for replacement variable's type
    const char      *type = comp->_type;
    Form            *form = (Form*)globals[type];
    assert( form != NULL, "Replacement variable's type not found");
    OperandForm *op = form->is_operand();
    assert( op, "Attempting to emit a non-register or non-constant");
    // Check that this is a constant and find constant's index:
    if (op->_matrule && op->_matrule->is_base_constant(globals)) {
      idx  = oper.constant_position(globals, comp);
    }
  }

  return idx;
}

bool is_regI(const char *encoding, OperandForm &oper, FormDict &globals ) {
  bool is_regI = false;

  OperandForm *op = rep_var_to_operand(encoding, oper, globals);
  if( op != NULL ) {
    // Check that this is a register
    if ( (op->_matrule && op->_matrule->is_base_register(globals)) ) {
      // Register
      const char* ideal  = op->ideal_type(globals);
      is_regI = (ideal && (op->ideal_to_Reg_type(ideal) == Form::idealI));
    }
  }

  return is_regI;
}

bool is_conP(const char *encoding, OperandForm &oper, FormDict &globals ) {
  bool is_conP = false;

  OperandForm *op = rep_var_to_operand(encoding, oper, globals);
  if( op != NULL ) {
    // Check that this is a constant pointer
    if (op->_matrule && op->_matrule->is_base_constant(globals)) {
      // Constant
      Form::DataType dtype = op->is_base_constant(globals);
      is_conP = (dtype == Form::idealP);
    }
  }

  return is_conP;
}


// Define a MachOper interface methods
void ArchDesc::define_oper_interface(FILE *fp, OperandForm &oper, FormDict &globals,
                                     const char *name, const char *encoding) {
  bool emit_position = false;
  int position = -1;

  fprintf(fp,"  virtual int            %s", name);
  // Generate access method for base, index, scale, disp, ...
  if( (strcmp(name,"base") == 0) || (strcmp(name,"index") == 0) ) {
    fprintf(fp,"(PhaseRegAlloc *ra_, const Node *node, int idx) const { \n");
    emit_position = true;
  } else if ( (strcmp(name,"disp") == 0) ) {
    fprintf(fp,"(PhaseRegAlloc *ra_, const Node *node, int idx) const { \n");
  } else {
    fprintf(fp,"() const { ");
  }

  // Check for hexadecimal value OR replacement variable
  if( *encoding == '$' ) {
    // Replacement variable
    const char *rep_var = encoding + 1;
    fprintf(fp,"// Replacement variable: %s\n", encoding+1);
    // Lookup replacement variable, rep_var, in operand's component list
    const Component *comp = oper._components.search(rep_var);
    assert( comp != NULL, "Replacement variable not found in components");
    // Lookup operand form for replacement variable's type
    const char      *type = comp->_type;
    Form            *form = (Form*)globals[type];
    assert( form != NULL, "Replacement variable's type not found");
    OperandForm *op = form->is_operand();
    assert( op, "Attempting to emit a non-register or non-constant");
    // Check that this is a register or a constant and generate code:
    if ( (op->_matrule && op->_matrule->is_base_register(globals)) ) {
      // Register
      int idx_offset = oper.register_position( globals, rep_var);
      position = idx_offset;
      fprintf(fp,"    return (int)ra_->get_encode(node->in(idx");
      if ( idx_offset > 0 ) fprintf(fp,                      "+%d",idx_offset);
      fprintf(fp,"));\n");
    } else if ( op->ideal_to_sReg_type(op->_ident) != Form::none ) {
      // StackSlot for an sReg comes either from input node or from self, when idx==0
      fprintf(fp,"    if( idx != 0 ) {\n");
      fprintf(fp,"      // Access register number for input operand\n");
      fprintf(fp,"      return ra_->reg2offset(ra_->get_reg_first(node->in(idx)));/* sReg */\n");
      fprintf(fp,"    }\n");
      fprintf(fp,"    // Access register number from myself\n");
      fprintf(fp,"    return ra_->reg2offset(ra_->get_reg_first(node));/* sReg */\n");
    } else if (op->_matrule && op->_matrule->is_base_constant(globals)) {
      // Constant
      // Check which constant this name maps to: _c0, _c1, ..., _cn
      const int idx = oper.constant_position(globals, comp);
      assert( idx != -1, "Constant component not found in operand");
      // Output code for this constant, type dependent.
      fprintf(fp,"    return (int)" );
      oper.access_constant(fp, globals, (uint)idx /* , const_type */);
      fprintf(fp,";\n");
    } else {
      assert( false, "Attempting to emit a non-register or non-constant");
    }
  }
  else if( *encoding == '0' && *(encoding+1) == 'x' ) {
    // Hex value
    fprintf(fp,"return %s;", encoding);
  } else {
    assert( false, "Do not support octal or decimal encode constants");
  }
  fprintf(fp,"  }\n");

  if( emit_position && (position != -1) && (oper.num_edges(globals) > 0) ) {
    fprintf(fp,"  virtual int            %s_position() const { return %d; }\n", name, position);
    MemInterface *mem_interface = oper._interface->is_MemInterface();
    const char *base = mem_interface->_base;
    const char *disp = mem_interface->_disp;
    if( emit_position && (strcmp(name,"base") == 0)
        && base != NULL && is_regI(base, oper, globals)
        && disp != NULL && is_conP(disp, oper, globals) ) {
      // Found a memory access using a constant pointer for a displacement
      // and a base register containing an integer offset.
      // In this case the base and disp are reversed with respect to what
      // is expected by MachNode::get_base_and_disp() and MachNode::adr_type().
      // Provide a non-NULL return for disp_as_type() that will allow adr_type()
      // to correctly compute the access type for alias analysis.
      //
      // See BugId 4796752, operand indOffset32X in i486.ad
      int idx = rep_var_to_constant_index(disp, oper, globals);
      fprintf(fp,"  virtual const TypePtr *disp_as_type() const { return _c%d; }\n", idx);
    }
  }
}

//
// Construct the method to copy _idx, inputs and operands to new node.
static void define_fill_new_machnode(bool used, FILE *fp_cpp) {
  fprintf(fp_cpp, "\n");
  fprintf(fp_cpp, "// Copy _idx, inputs and operands to new node\n");
  fprintf(fp_cpp, "void MachNode::fill_new_machnode( MachNode* node, Compile* C) const {\n");
  if( !used ) {
    fprintf(fp_cpp, "  // This architecture does not have cisc or short branch instructions\n");
    fprintf(fp_cpp, "  ShouldNotCallThis();\n");
    fprintf(fp_cpp, "}\n");
  } else {
    // New node must use same node index for access through allocator's tables
    fprintf(fp_cpp, "  // New node must use same node index\n");
    fprintf(fp_cpp, "  node->set_idx( _idx );\n");
    // Copy machine-independent inputs
    fprintf(fp_cpp, "  // Copy machine-independent inputs\n");
    fprintf(fp_cpp, "  for( uint j = 0; j < req(); j++ ) {\n");
    fprintf(fp_cpp, "    node->add_req(in(j));\n");
    fprintf(fp_cpp, "  }\n");
    // Copy machine operands to new MachNode
    fprintf(fp_cpp, "  // Copy my operands, except for cisc position\n");
    fprintf(fp_cpp, "  int nopnds = num_opnds();\n");
    fprintf(fp_cpp, "  assert( node->num_opnds() == (uint)nopnds, \"Must have same number of operands\");\n");
    fprintf(fp_cpp, "  MachOper **to = node->_opnds;\n");
    fprintf(fp_cpp, "  for( int i = 0; i < nopnds; i++ ) {\n");
    fprintf(fp_cpp, "    if( i != cisc_operand() ) \n");
    fprintf(fp_cpp, "      to[i] = _opnds[i]->clone(C);\n");
    fprintf(fp_cpp, "  }\n");
    fprintf(fp_cpp, "}\n");
  }
  fprintf(fp_cpp, "\n");
}

//------------------------------defineClasses----------------------------------
// Define members of MachNode and MachOper classes based on
// operand and instruction lists
void ArchDesc::defineClasses(FILE *fp) {

  // Define the contents of an array containing the machine register names
  defineRegNames(fp, _register);
  // Define an array containing the machine register encoding values
  defineRegEncodes(fp, _register);
  // Generate an enumeration of user-defined register classes
  // and a list of register masks, one for each class.
  // Only define the RegMask value objects in the expand file.
  // Declare each as an extern const RegMask ...; in ad_<arch>.hpp
  declare_register_masks(_HPP_file._fp);
  // build_register_masks(fp);
  build_register_masks(_CPP_EXPAND_file._fp);
  // Define the pipe_classes
  build_pipe_classes(_CPP_PIPELINE_file._fp);

  // Generate Machine Classes for each operand defined in AD file
  fprintf(fp,"\n");
  fprintf(fp,"\n");
  fprintf(fp,"//------------------Define classes derived from MachOper---------------------\n");
  // Iterate through all operands
  _operands.reset();
  OperandForm *oper;
  for( ; (oper = (OperandForm*)_operands.iter()) != NULL; ) {
    // Ensure this is a machine-world instruction
    if ( oper->ideal_only() ) continue;
    // !!!!!
    // The declaration of labelOper is in machine-independent file: machnode
    if ( strcmp(oper->_ident,"label") == 0 ) {
      defineIn_RegMask(_CPP_MISC_file._fp, _globalNames, *oper);

      fprintf(fp,"MachOper  *%sOper::clone(Compile* C) const {\n", oper->_ident);
      fprintf(fp,"  return  new (C) %sOper(_label, _block_num);\n", oper->_ident);
      fprintf(fp,"}\n");

      fprintf(fp,"uint %sOper::opcode() const { return %s; }\n",
              oper->_ident, machOperEnum(oper->_ident));
      // // Currently all XXXOper::Hash() methods are identical (990820)
      // define_hash(fp, oper->_ident);
      // // Currently all XXXOper::Cmp() methods are identical (990820)
      // define_cmp(fp, oper->_ident);
      fprintf(fp,"\n");

      continue;
    }

    // The declaration of methodOper is in machine-independent file: machnode
    if ( strcmp(oper->_ident,"method") == 0 ) {
      defineIn_RegMask(_CPP_MISC_file._fp, _globalNames, *oper);

      fprintf(fp,"MachOper  *%sOper::clone(Compile* C) const {\n", oper->_ident);
      fprintf(fp,"  return  new (C) %sOper(_method);\n", oper->_ident);
      fprintf(fp,"}\n");

      fprintf(fp,"uint %sOper::opcode() const { return %s; }\n",
              oper->_ident, machOperEnum(oper->_ident));
      // // Currently all XXXOper::Hash() methods are identical (990820)
      // define_hash(fp, oper->_ident);
      // // Currently all XXXOper::Cmp() methods are identical (990820)
      // define_cmp(fp, oper->_ident);
      fprintf(fp,"\n");

      continue;
    }

    defineIn_RegMask(fp, _globalNames, *oper);
    defineClone(_CPP_CLONE_file._fp, _globalNames, *oper);
    // // Currently all XXXOper::Hash() methods are identical (990820)
    // define_hash(fp, oper->_ident);
    // // Currently all XXXOper::Cmp() methods are identical (990820)
    // define_cmp(fp, oper->_ident);

    // side-call to generate output that used to be in the header file:
    extern void gen_oper_format(FILE *fp, FormDict &globals, OperandForm &oper, bool for_c_file);
    gen_oper_format(_CPP_FORMAT_file._fp, _globalNames, *oper, true);

  }


  // Generate Machine Classes for each instruction defined in AD file
  fprintf(fp,"//------------------Define members for classes derived from MachNode----------\n");
  // Output the definitions for out_RegMask() // & kill_RegMask()
  _instructions.reset();
  InstructForm *instr;
  MachNodeForm *machnode;
  for( ; (instr = (InstructForm*)_instructions.iter()) != NULL; ) {
    // Ensure this is a machine-world instruction
    if ( instr->ideal_only() ) continue;

    defineOut_RegMask(_CPP_MISC_file._fp, instr->_ident, reg_mask(*instr));
  }

  bool used = false;
  // Output the definitions for expand rules & peephole rules
  _instructions.reset();
  for( ; (instr = (InstructForm*)_instructions.iter()) != NULL; ) {
    // Ensure this is a machine-world instruction
    if ( instr->ideal_only() ) continue;
    // If there are multiple defs/kills, or an explicit expand rule, build rule
    if( instr->expands() || instr->needs_projections() ||
        instr->has_temps() ||
        instr->is_mach_constant() ||
        instr->_matrule != NULL &&
        instr->num_opnds() != instr->num_unique_opnds() )
      defineExpand(_CPP_EXPAND_file._fp, instr);
    // If there is an explicit peephole rule, build it
    if ( instr->peepholes() )
      definePeephole(_CPP_PEEPHOLE_file._fp, instr);

    // Output code to convert to the cisc version, if applicable
    used |= instr->define_cisc_version(*this, fp);

    // Output code to convert to the short branch version, if applicable
    used |= instr->define_short_branch_methods(*this, fp);
  }

  // Construct the method called by cisc_version() to copy inputs and operands.
  define_fill_new_machnode(used, fp);

  // Output the definitions for labels
  _instructions.reset();
  while( (instr = (InstructForm*)_instructions.iter()) != NULL ) {
    // Ensure this is a machine-world instruction
    if ( instr->ideal_only() ) continue;

    // Access the fields for operand Label
    int label_position = instr->label_position();
    if( label_position != -1 ) {
      // Set the label
      fprintf(fp,"void %sNode::label_set( Label* label, uint block_num ) {\n", instr->_ident);
      fprintf(fp,"  labelOper* oper  = (labelOper*)(opnd_array(%d));\n",
              label_position );
      fprintf(fp,"  oper->_label     = label;\n");
      fprintf(fp,"  oper->_block_num = block_num;\n");
      fprintf(fp,"}\n");
      // Save the label
      fprintf(fp,"void %sNode::save_label( Label** label, uint* block_num ) {\n", instr->_ident);
      fprintf(fp,"  labelOper* oper  = (labelOper*)(opnd_array(%d));\n",
              label_position );
      fprintf(fp,"  *label = oper->_label;\n");
      fprintf(fp,"  *block_num = oper->_block_num;\n");
      fprintf(fp,"}\n");
    }
  }

  // Output the definitions for methods
  _instructions.reset();
  while( (instr = (InstructForm*)_instructions.iter()) != NULL ) {
    // Ensure this is a machine-world instruction
    if ( instr->ideal_only() ) continue;

    // Access the fields for operand Label
    int method_position = instr->method_position();
    if( method_position != -1 ) {
      // Access the method's address
      fprintf(fp,"void %sNode::method_set( intptr_t method ) {\n", instr->_ident);
      fprintf(fp,"  ((methodOper*)opnd_array(%d))->_method = method;\n",
              method_position );
      fprintf(fp,"}\n");
      fprintf(fp,"\n");
    }
  }

  // Define this instruction's number of relocation entries, base is '0'
  _instructions.reset();
  while( (instr = (InstructForm*)_instructions.iter()) != NULL ) {
    // Output the definition for number of relocation entries
    uint reloc_size = instr->reloc(_globalNames);
    if ( reloc_size != 0 ) {
      fprintf(fp,"int  %sNode::reloc()   const {\n", instr->_ident);
      fprintf(fp,  "  return  %d;\n", reloc_size );
      fprintf(fp,"}\n");
      fprintf(fp,"\n");
    }
  }
  fprintf(fp,"\n");

  // Output the definitions for code generation
  //
  // address  ___Node::emit(address ptr, PhaseRegAlloc *ra_) const {
  //   // ...  encoding defined by user
  //   return ptr;
  // }
  //
  _instructions.reset();
  for( ; (instr = (InstructForm*)_instructions.iter()) != NULL; ) {
    // Ensure this is a machine-world instruction
    if ( instr->ideal_only() ) continue;

    if (instr->_insencode)         defineEmit        (fp, *instr);
    if (instr->is_mach_constant()) defineEvalConstant(fp, *instr);
    if (instr->_size)              defineSize        (fp, *instr);

    // side-call to generate output that used to be in the header file:
    extern void gen_inst_format(FILE *fp, FormDict &globals, InstructForm &oper, bool for_c_file);
    gen_inst_format(_CPP_FORMAT_file._fp, _globalNames, *instr, true);
  }

  // Output the definitions for alias analysis
  _instructions.reset();
  for( ; (instr = (InstructForm*)_instructions.iter()) != NULL; ) {
    // Ensure this is a machine-world instruction
    if ( instr->ideal_only() ) continue;

    // Analyze machine instructions that either USE or DEF memory.
    int memory_operand = instr->memory_operand(_globalNames);
    // Some guys kill all of memory
    if ( instr->is_wide_memory_kill(_globalNames) ) {
      memory_operand = InstructForm::MANY_MEMORY_OPERANDS;
    }

    if ( memory_operand != InstructForm::NO_MEMORY_OPERAND ) {
      if( memory_operand == InstructForm::MANY_MEMORY_OPERANDS ) {
        fprintf(fp,"const TypePtr *%sNode::adr_type() const { return TypePtr::BOTTOM; }\n", instr->_ident);
        fprintf(fp,"const MachOper* %sNode::memory_operand() const { return (MachOper*)-1; }\n", instr->_ident);
      } else {
        fprintf(fp,"const MachOper* %sNode::memory_operand() const { return _opnds[%d]; }\n", instr->_ident, memory_operand);
  }
    }
  }

  // Get the length of the longest identifier
  int max_ident_len = 0;
  _instructions.reset();

  for ( ; (instr = (InstructForm*)_instructions.iter()) != NULL; ) {
    if (instr->_ins_pipe && _pipeline->_classlist.search(instr->_ins_pipe)) {
      int ident_len = (int)strlen(instr->_ident);
      if( max_ident_len < ident_len )
        max_ident_len = ident_len;
    }
  }

  // Emit specifically for Node(s)
  fprintf(_CPP_PIPELINE_file._fp, "const Pipeline * %*s::pipeline_class() { return %s; }\n",
    max_ident_len, "Node", _pipeline ? "(&pipeline_class_Zero_Instructions)" : "NULL");
  fprintf(_CPP_PIPELINE_file._fp, "const Pipeline * %*s::pipeline() const { return %s; }\n",
    max_ident_len, "Node", _pipeline ? "(&pipeline_class_Zero_Instructions)" : "NULL");
  fprintf(_CPP_PIPELINE_file._fp, "\n");

  fprintf(_CPP_PIPELINE_file._fp, "const Pipeline * %*s::pipeline_class() { return %s; }\n",
    max_ident_len, "MachNode", _pipeline ? "(&pipeline_class_Unknown_Instructions)" : "NULL");
  fprintf(_CPP_PIPELINE_file._fp, "const Pipeline * %*s::pipeline() const { return pipeline_class(); }\n",
    max_ident_len, "MachNode");
  fprintf(_CPP_PIPELINE_file._fp, "\n");

  // Output the definitions for machine node specific pipeline data
  _machnodes.reset();

  for ( ; (machnode = (MachNodeForm*)_machnodes.iter()) != NULL; ) {
    fprintf(_CPP_PIPELINE_file._fp, "const Pipeline * %sNode::pipeline() const { return (&pipeline_class_%03d); }\n",
      machnode->_ident, ((class PipeClassForm *)_pipeline->_classdict[machnode->_machnode_pipe])->_num);
  }

  fprintf(_CPP_PIPELINE_file._fp, "\n");

  // Output the definitions for instruction pipeline static data references
  _instructions.reset();

  for ( ; (instr = (InstructForm*)_instructions.iter()) != NULL; ) {
    if (instr->_ins_pipe && _pipeline->_classlist.search(instr->_ins_pipe)) {
      fprintf(_CPP_PIPELINE_file._fp, "\n");
      fprintf(_CPP_PIPELINE_file._fp, "const Pipeline * %*sNode::pipeline_class() { return (&pipeline_class_%03d); }\n",
        max_ident_len, instr->_ident, ((class PipeClassForm *)_pipeline->_classdict[instr->_ins_pipe])->_num);
      fprintf(_CPP_PIPELINE_file._fp, "const Pipeline * %*sNode::pipeline() const { return (&pipeline_class_%03d); }\n",
        max_ident_len, instr->_ident, ((class PipeClassForm *)_pipeline->_classdict[instr->_ins_pipe])->_num);
    }
  }
}


// -------------------------------- maps ------------------------------------

// Information needed to generate the ReduceOp mapping for the DFA
class OutputReduceOp : public OutputMap {
public:
  OutputReduceOp(FILE *hpp, FILE *cpp, FormDict &globals, ArchDesc &AD)
    : OutputMap(hpp, cpp, globals, AD) {};

  void declaration() { fprintf(_hpp, "extern const int   reduceOp[];\n"); }
  void definition()  { fprintf(_cpp, "const        int   reduceOp[] = {\n"); }
  void closing()     { fprintf(_cpp, "  0 // no trailing comma\n");
                       OutputMap::closing();
  }
  void map(OpClassForm &opc)  {
    const char *reduce = opc._ident;
    if( reduce )  fprintf(_cpp, "  %s_rule", reduce);
    else          fprintf(_cpp, "  0");
  }
  void map(OperandForm &oper) {
    // Most operands without match rules, e.g.  eFlagsReg, do not have a result operand
    const char *reduce = (oper._matrule ? oper.reduce_result() : NULL);
    // operand stackSlot does not have a match rule, but produces a stackSlot
    if( oper.is_user_name_for_sReg() != Form::none ) reduce = oper.reduce_result();
    if( reduce )  fprintf(_cpp, "  %s_rule", reduce);
    else          fprintf(_cpp, "  0");
  }
  void map(InstructForm &inst) {
    const char *reduce = (inst._matrule ? inst.reduce_result() : NULL);
    if( reduce )  fprintf(_cpp, "  %s_rule", reduce);
    else          fprintf(_cpp, "  0");
  }
  void map(char         *reduce) {
    if( reduce )  fprintf(_cpp, "  %s_rule", reduce);
    else          fprintf(_cpp, "  0");
  }
};

// Information needed to generate the LeftOp mapping for the DFA
class OutputLeftOp : public OutputMap {
public:
  OutputLeftOp(FILE *hpp, FILE *cpp, FormDict &globals, ArchDesc &AD)
    : OutputMap(hpp, cpp, globals, AD) {};

  void declaration() { fprintf(_hpp, "extern const int   leftOp[];\n"); }
  void definition()  { fprintf(_cpp, "const        int   leftOp[] = {\n"); }
  void closing()     { fprintf(_cpp, "  0 // no trailing comma\n");
                       OutputMap::closing();
  }
  void map(OpClassForm &opc)  { fprintf(_cpp, "  0"); }
  void map(OperandForm &oper) {
    const char *reduce = oper.reduce_left(_globals);
    if( reduce )  fprintf(_cpp, "  %s_rule", reduce);
    else          fprintf(_cpp, "  0");
  }
  void map(char        *name) {
    const char *reduce = _AD.reduceLeft(name);
    if( reduce )  fprintf(_cpp, "  %s_rule", reduce);
    else          fprintf(_cpp, "  0");
  }
  void map(InstructForm &inst) {
    const char *reduce = inst.reduce_left(_globals);
    if( reduce )  fprintf(_cpp, "  %s_rule", reduce);
    else          fprintf(_cpp, "  0");
  }
};


// Information needed to generate the RightOp mapping for the DFA
class OutputRightOp : public OutputMap {
public:
  OutputRightOp(FILE *hpp, FILE *cpp, FormDict &globals, ArchDesc &AD)
    : OutputMap(hpp, cpp, globals, AD) {};

  void declaration() { fprintf(_hpp, "extern const int   rightOp[];\n"); }
  void definition()  { fprintf(_cpp, "const        int   rightOp[] = {\n"); }
  void closing()     { fprintf(_cpp, "  0 // no trailing comma\n");
                       OutputMap::closing();
  }
  void map(OpClassForm &opc)  { fprintf(_cpp, "  0"); }
  void map(OperandForm &oper) {
    const char *reduce = oper.reduce_right(_globals);
    if( reduce )  fprintf(_cpp, "  %s_rule", reduce);
    else          fprintf(_cpp, "  0");
  }
  void map(char        *name) {
    const char *reduce = _AD.reduceRight(name);
    if( reduce )  fprintf(_cpp, "  %s_rule", reduce);
    else          fprintf(_cpp, "  0");
  }
  void map(InstructForm &inst) {
    const char *reduce = inst.reduce_right(_globals);
    if( reduce )  fprintf(_cpp, "  %s_rule", reduce);
    else          fprintf(_cpp, "  0");
  }
};


// Information needed to generate the Rule names for the DFA
class OutputRuleName : public OutputMap {
public:
  OutputRuleName(FILE *hpp, FILE *cpp, FormDict &globals, ArchDesc &AD)
    : OutputMap(hpp, cpp, globals, AD) {};

  void declaration() { fprintf(_hpp, "extern const char *ruleName[];\n"); }
  void definition()  { fprintf(_cpp, "const char        *ruleName[] = {\n"); }
  void closing()     { fprintf(_cpp, "  \"no trailing comma\"\n");
                       OutputMap::closing();
  }
  void map(OpClassForm &opc)  { fprintf(_cpp, "  \"%s\"", _AD.machOperEnum(opc._ident) ); }
  void map(OperandForm &oper) { fprintf(_cpp, "  \"%s\"", _AD.machOperEnum(oper._ident) ); }
  void map(char        *name) { fprintf(_cpp, "  \"%s\"", name ? name : "0"); }
  void map(InstructForm &inst){ fprintf(_cpp, "  \"%s\"", inst._ident ? inst._ident : "0"); }
};


// Information needed to generate the swallowed mapping for the DFA
class OutputSwallowed : public OutputMap {
public:
  OutputSwallowed(FILE *hpp, FILE *cpp, FormDict &globals, ArchDesc &AD)
    : OutputMap(hpp, cpp, globals, AD) {};

  void declaration() { fprintf(_hpp, "extern const bool  swallowed[];\n"); }
  void definition()  { fprintf(_cpp, "const        bool  swallowed[] = {\n"); }
  void closing()     { fprintf(_cpp, "  false // no trailing comma\n");
                       OutputMap::closing();
  }
  void map(OperandForm &oper) { // Generate the entry for this opcode
    const char *swallowed = oper.swallowed(_globals) ? "true" : "false";
    fprintf(_cpp, "  %s", swallowed);
  }
  void map(OpClassForm &opc)  { fprintf(_cpp, "  false"); }
  void map(char        *name) { fprintf(_cpp, "  false"); }
  void map(InstructForm &inst){ fprintf(_cpp, "  false"); }
};


// Information needed to generate the decision array for instruction chain rule
class OutputInstChainRule : public OutputMap {
public:
  OutputInstChainRule(FILE *hpp, FILE *cpp, FormDict &globals, ArchDesc &AD)
    : OutputMap(hpp, cpp, globals, AD) {};

  void declaration() { fprintf(_hpp, "extern const bool  instruction_chain_rule[];\n"); }
  void definition()  { fprintf(_cpp, "const        bool  instruction_chain_rule[] = {\n"); }
  void closing()     { fprintf(_cpp, "  false // no trailing comma\n");
                       OutputMap::closing();
  }
  void map(OpClassForm &opc)   { fprintf(_cpp, "  false"); }
  void map(OperandForm &oper)  { fprintf(_cpp, "  false"); }
  void map(char        *name)  { fprintf(_cpp, "  false"); }
  void map(InstructForm &inst) { // Check for simple chain rule
    const char *chain = inst.is_simple_chain_rule(_globals) ? "true" : "false";
    fprintf(_cpp, "  %s", chain);
  }
};


//---------------------------build_map------------------------------------
// Build  mapping from enumeration for densely packed operands
// TO result and child types.
void ArchDesc::build_map(OutputMap &map) {
  FILE         *fp_hpp = map.decl_file();
  FILE         *fp_cpp = map.def_file();
  int           idx    = 0;
  OperandForm  *op;
  OpClassForm  *opc;
  InstructForm *inst;

  // Construct this mapping
  map.declaration();
  fprintf(fp_cpp,"\n");
  map.definition();

  // Output the mapping for operands
  map.record_position(OutputMap::BEGIN_OPERANDS, idx );
  _operands.reset();
  for(; (op = (OperandForm*)_operands.iter()) != NULL; ) {
    // Ensure this is a machine-world instruction
    if ( op->ideal_only() )  continue;

    // Generate the entry for this opcode
    map.map(*op);    fprintf(fp_cpp, ", // %d\n", idx);
    ++idx;
  };
  fprintf(fp_cpp, "  // last operand\n");

  // Place all user-defined operand classes into the mapping
  map.record_position(OutputMap::BEGIN_OPCLASSES, idx );
  _opclass.reset();
  for(; (opc = (OpClassForm*)_opclass.iter()) != NULL; ) {
    map.map(*opc);    fprintf(fp_cpp, ", // %d\n", idx);
    ++idx;
  };
  fprintf(fp_cpp, "  // last operand class\n");

  // Place all internally defined operands into the mapping
  map.record_position(OutputMap::BEGIN_INTERNALS, idx );
  _internalOpNames.reset();
  char *name = NULL;
  for(; (name = (char *)_internalOpNames.iter()) != NULL; ) {
    map.map(name);    fprintf(fp_cpp, ", // %d\n", idx);
    ++idx;
  };
  fprintf(fp_cpp, "  // last internally defined operand\n");

  // Place all user-defined instructions into the mapping
  if( map.do_instructions() ) {
    map.record_position(OutputMap::BEGIN_INSTRUCTIONS, idx );
    // Output all simple instruction chain rules first
    map.record_position(OutputMap::BEGIN_INST_CHAIN_RULES, idx );
    {
      _instructions.reset();
      for(; (inst = (InstructForm*)_instructions.iter()) != NULL; ) {
        // Ensure this is a machine-world instruction
        if ( inst->ideal_only() )  continue;
        if ( ! inst->is_simple_chain_rule(_globalNames) ) continue;
        if ( inst->rematerialize(_globalNames, get_registers()) ) continue;

        map.map(*inst);      fprintf(fp_cpp, ", // %d\n", idx);
        ++idx;
      };
      map.record_position(OutputMap::BEGIN_REMATERIALIZE, idx );
      _instructions.reset();
      for(; (inst = (InstructForm*)_instructions.iter()) != NULL; ) {
        // Ensure this is a machine-world instruction
        if ( inst->ideal_only() )  continue;
        if ( ! inst->is_simple_chain_rule(_globalNames) ) continue;
        if ( ! inst->rematerialize(_globalNames, get_registers()) ) continue;

        map.map(*inst);      fprintf(fp_cpp, ", // %d\n", idx);
        ++idx;
      };
      map.record_position(OutputMap::END_INST_CHAIN_RULES, idx );
    }
    // Output all instructions that are NOT simple chain rules
    {
      _instructions.reset();
      for(; (inst = (InstructForm*)_instructions.iter()) != NULL; ) {
        // Ensure this is a machine-world instruction
        if ( inst->ideal_only() )  continue;
        if ( inst->is_simple_chain_rule(_globalNames) ) continue;
        if ( ! inst->rematerialize(_globalNames, get_registers()) ) continue;

        map.map(*inst);      fprintf(fp_cpp, ", // %d\n", idx);
        ++idx;
      };
      map.record_position(OutputMap::END_REMATERIALIZE, idx );
      _instructions.reset();
      for(; (inst = (InstructForm*)_instructions.iter()) != NULL; ) {
        // Ensure this is a machine-world instruction
        if ( inst->ideal_only() )  continue;
        if ( inst->is_simple_chain_rule(_globalNames) ) continue;
        if ( inst->rematerialize(_globalNames, get_registers()) ) continue;

        map.map(*inst);      fprintf(fp_cpp, ", // %d\n", idx);
        ++idx;
      };
    }
    fprintf(fp_cpp, "  // last instruction\n");
    map.record_position(OutputMap::END_INSTRUCTIONS, idx );
  }
  // Finish defining table
  map.closing();
};


// Helper function for buildReduceMaps
char reg_save_policy(const char *calling_convention) {
  char callconv;

  if      (!strcmp(calling_convention, "NS"))  callconv = 'N';
  else if (!strcmp(calling_convention, "SOE")) callconv = 'E';
  else if (!strcmp(calling_convention, "SOC")) callconv = 'C';
  else if (!strcmp(calling_convention, "AS"))  callconv = 'A';
  else                                         callconv = 'Z';

  return callconv;
}

//---------------------------generate_assertion_checks-------------------
void ArchDesc::generate_adlc_verification(FILE *fp_cpp) {
  fprintf(fp_cpp, "\n");

  fprintf(fp_cpp, "#ifndef PRODUCT\n");
  fprintf(fp_cpp, "void Compile::adlc_verification() {\n");
  globalDefs().print_asserts(fp_cpp);
  fprintf(fp_cpp, "}\n");
  fprintf(fp_cpp, "#endif\n");
  fprintf(fp_cpp, "\n");
}

//---------------------------addSourceBlocks-----------------------------
void ArchDesc::addSourceBlocks(FILE *fp_cpp) {
  if (_source.count() > 0)
    _source.output(fp_cpp);

  generate_adlc_verification(fp_cpp);
}
//---------------------------addHeaderBlocks-----------------------------
void ArchDesc::addHeaderBlocks(FILE *fp_hpp) {
  if (_header.count() > 0)
    _header.output(fp_hpp);
}
//-------------------------addPreHeaderBlocks----------------------------
void ArchDesc::addPreHeaderBlocks(FILE *fp_hpp) {
  // Output #defines from definition block
  globalDefs().print_defines(fp_hpp);

  if (_pre_header.count() > 0)
    _pre_header.output(fp_hpp);
}

//---------------------------buildReduceMaps-----------------------------
// Build  mapping from enumeration for densely packed operands
// TO result and child types.
void ArchDesc::buildReduceMaps(FILE *fp_hpp, FILE *fp_cpp) {
  RegDef       *rdef;
  RegDef       *next;

  // The emit bodies currently require functions defined in the source block.

  // Build external declarations for mappings
  fprintf(fp_hpp, "\n");
  fprintf(fp_hpp, "extern const char  register_save_policy[];\n");
  fprintf(fp_hpp, "extern const char  c_reg_save_policy[];\n");
  fprintf(fp_hpp, "extern const int   register_save_type[];\n");
  fprintf(fp_hpp, "\n");

  // Construct Save-Policy array
  fprintf(fp_cpp, "// Map from machine-independent register number to register_save_policy\n");
  fprintf(fp_cpp, "const        char register_save_policy[] = {\n");
  _register->reset_RegDefs();
  for( rdef = _register->iter_RegDefs(); rdef != NULL; rdef = next ) {
    next              = _register->iter_RegDefs();
    char policy       = reg_save_policy(rdef->_callconv);
    const char *comma = (next != NULL) ? "," : " // no trailing comma";
    fprintf(fp_cpp, "  '%c'%s\n", policy, comma);
  }
  fprintf(fp_cpp, "};\n\n");

  // Construct Native Save-Policy array
  fprintf(fp_cpp, "// Map from machine-independent register number to c_reg_save_policy\n");
  fprintf(fp_cpp, "const        char c_reg_save_policy[] = {\n");
  _register->reset_RegDefs();
  for( rdef = _register->iter_RegDefs(); rdef != NULL; rdef = next ) {
    next        = _register->iter_RegDefs();
    char policy = reg_save_policy(rdef->_c_conv);
    const char *comma = (next != NULL) ? "," : " // no trailing comma";
    fprintf(fp_cpp, "  '%c'%s\n", policy, comma);
  }
  fprintf(fp_cpp, "};\n\n");

  // Construct Register Save Type array
  fprintf(fp_cpp, "// Map from machine-independent register number to register_save_type\n");
  fprintf(fp_cpp, "const        int register_save_type[] = {\n");
  _register->reset_RegDefs();
  for( rdef = _register->iter_RegDefs(); rdef != NULL; rdef = next ) {
    next = _register->iter_RegDefs();
    const char *comma = (next != NULL) ? "," : " // no trailing comma";
    fprintf(fp_cpp, "  %s%s\n", rdef->_idealtype, comma);
  }
  fprintf(fp_cpp, "};\n\n");

  // Construct the table for reduceOp
  OutputReduceOp output_reduce_op(fp_hpp, fp_cpp, _globalNames, *this);
  build_map(output_reduce_op);
  // Construct the table for leftOp
  OutputLeftOp output_left_op(fp_hpp, fp_cpp, _globalNames, *this);
  build_map(output_left_op);
  // Construct the table for rightOp
  OutputRightOp output_right_op(fp_hpp, fp_cpp, _globalNames, *this);
  build_map(output_right_op);
  // Construct the table of rule names
  OutputRuleName output_rule_name(fp_hpp, fp_cpp, _globalNames, *this);
  build_map(output_rule_name);
  // Construct the boolean table for subsumed operands
  OutputSwallowed output_swallowed(fp_hpp, fp_cpp, _globalNames, *this);
  build_map(output_swallowed);
  // // // Preserve in case we decide to use this table instead of another
  //// Construct the boolean table for instruction chain rules
  //OutputInstChainRule output_inst_chain(fp_hpp, fp_cpp, _globalNames, *this);
  //build_map(output_inst_chain);

}


//---------------------------buildMachOperGenerator---------------------------

// Recurse through match tree, building path through corresponding state tree,
// Until we reach the constant we are looking for.
static void path_to_constant(FILE *fp, FormDict &globals,
                             MatchNode *mnode, uint idx) {
  if ( ! mnode) return;

  unsigned    position = 0;
  const char *result   = NULL;
  const char *name     = NULL;
  const char *optype   = NULL;

  // Base Case: access constant in ideal node linked to current state node
  // Each type of constant has its own access function
  if ( (mnode->_lChild == NULL) && (mnode->_rChild == NULL)
       && mnode->base_operand(position, globals, result, name, optype) ) {
    if (         strcmp(optype,"ConI") == 0 ) {
      fprintf(fp, "_leaf->get_int()");
    } else if ( (strcmp(optype,"ConP") == 0) ) {
      fprintf(fp, "_leaf->bottom_type()->is_ptr()");
    } else if ( (strcmp(optype,"ConN") == 0) ) {
      fprintf(fp, "_leaf->bottom_type()->is_narrowoop()");
    } else if ( (strcmp(optype,"ConF") == 0) ) {
      fprintf(fp, "_leaf->getf()");
    } else if ( (strcmp(optype,"ConD") == 0) ) {
      fprintf(fp, "_leaf->getd()");
    } else if ( (strcmp(optype,"ConL") == 0) ) {
      fprintf(fp, "_leaf->get_long()");
    } else if ( (strcmp(optype,"Con")==0) ) {
      // !!!!! - Update if adding a machine-independent constant type
      fprintf(fp, "_leaf->get_int()");
      assert( false, "Unsupported constant type, pointer or indefinite");
    } else if ( (strcmp(optype,"Bool") == 0) ) {
      fprintf(fp, "_leaf->as_Bool()->_test._test");
    } else {
      assert( false, "Unsupported constant type");
    }
    return;
  }

  // If constant is in left child, build path and recurse
  uint lConsts = (mnode->_lChild) ? (mnode->_lChild->num_consts(globals) ) : 0;
  uint rConsts = (mnode->_rChild) ? (mnode->_rChild->num_consts(globals) ) : 0;
  if ( (mnode->_lChild) && (lConsts > idx) ) {
    fprintf(fp, "_kids[0]->");
    path_to_constant(fp, globals, mnode->_lChild, idx);
    return;
  }
  // If constant is in right child, build path and recurse
  if ( (mnode->_rChild) && (rConsts > (idx - lConsts) ) ) {
    idx = idx - lConsts;
    fprintf(fp, "_kids[1]->");
    path_to_constant(fp, globals, mnode->_rChild, idx);
    return;
  }
  assert( false, "ShouldNotReachHere()");
}

// Generate code that is executed when generating a specific Machine Operand
static void genMachOperCase(FILE *fp, FormDict &globalNames, ArchDesc &AD,
                            OperandForm &op) {
  const char *opName         = op._ident;
  const char *opEnumName     = AD.machOperEnum(opName);
  uint        num_consts     = op.num_consts(globalNames);

  // Generate the case statement for this opcode
  fprintf(fp, "  case %s:", opEnumName);
  fprintf(fp, "\n    return new (C) %sOper(", opName);
  // Access parameters for constructor from the stat object
  //
  // Build access to condition code value
  if ( (num_consts > 0) ) {
    uint i = 0;
    path_to_constant(fp, globalNames, op._matrule, i);
    for ( i = 1; i < num_consts; ++i ) {
      fprintf(fp, ", ");
      path_to_constant(fp, globalNames, op._matrule, i);
    }
  }
  fprintf(fp, " );\n");
}


// Build switch to invoke "new" MachNode or MachOper
void ArchDesc::buildMachOperGenerator(FILE *fp_cpp) {
  int idx = 0;

  // Build switch to invoke 'new' for a specific MachOper
  fprintf(fp_cpp, "\n");
  fprintf(fp_cpp, "\n");
  fprintf(fp_cpp,
          "//------------------------- MachOper Generator ---------------\n");
  fprintf(fp_cpp,
          "// A switch statement on the dense-packed user-defined type system\n"
          "// that invokes 'new' on the corresponding class constructor.\n");
  fprintf(fp_cpp, "\n");
  fprintf(fp_cpp, "MachOper *State::MachOperGenerator");
  fprintf(fp_cpp, "(int opcode, Compile* C)");
  fprintf(fp_cpp, "{\n");
  fprintf(fp_cpp, "\n");
  fprintf(fp_cpp, "  switch(opcode) {\n");

  // Place all user-defined operands into the mapping
  _operands.reset();
  int  opIndex = 0;
  OperandForm *op;
  for( ; (op =  (OperandForm*)_operands.iter()) != NULL; ) {
    // Ensure this is a machine-world instruction
    if ( op->ideal_only() )  continue;

    genMachOperCase(fp_cpp, _globalNames, *this, *op);
  };

  // Do not iterate over operand classes for the  operand generator!!!

  // Place all internal operands into the mapping
  _internalOpNames.reset();
  const char *iopn;
  for( ; (iopn =  _internalOpNames.iter()) != NULL; ) {
    const char *opEnumName = machOperEnum(iopn);
    // Generate the case statement for this opcode
    fprintf(fp_cpp, "  case %s:", opEnumName);
    fprintf(fp_cpp, "    return NULL;\n");
  };

  // Generate the default case for switch(opcode)
  fprintf(fp_cpp, "  \n");
  fprintf(fp_cpp, "  default:\n");
  fprintf(fp_cpp, "    fprintf(stderr, \"Default MachOper Generator invoked for: \\n\");\n");
  fprintf(fp_cpp, "    fprintf(stderr, \"   opcode = %cd\\n\", opcode);\n", '%');
  fprintf(fp_cpp, "    break;\n");
  fprintf(fp_cpp, "  }\n");

  // Generate the closing for method Matcher::MachOperGenerator
  fprintf(fp_cpp, "  return NULL;\n");
  fprintf(fp_cpp, "};\n");
}


//---------------------------buildMachNode-------------------------------------
// Build a new MachNode, for MachNodeGenerator or cisc-spilling
void ArchDesc::buildMachNode(FILE *fp_cpp, InstructForm *inst, const char *indent) {
  const char *opType  = NULL;
  const char *opClass = inst->_ident;

  // Create the MachNode object
  fprintf(fp_cpp, "%s %sNode *node = new (C) %sNode();\n",indent, opClass,opClass);

  if ( (inst->num_post_match_opnds() != 0) ) {
    // Instruction that contains operands which are not in match rule.
    //
    // Check if the first post-match component may be an interesting def
    bool           dont_care = false;
    ComponentList &comp_list = inst->_components;
    Component     *comp      = NULL;
    comp_list.reset();
    if ( comp_list.match_iter() != NULL )    dont_care = true;

    // Insert operands that are not in match-rule.
    // Only insert a DEF if the do_care flag is set
    comp_list.reset();
    while ( comp = comp_list.post_match_iter() ) {
      // Check if we don't care about DEFs or KILLs that are not USEs
      if ( dont_care && (! comp->isa(Component::USE)) ) {
        continue;
      }
      dont_care = true;
      // For each operand not in the match rule, call MachOperGenerator
      // with the enum for the opcode that needs to be built.
      ComponentList clist = inst->_components;
      int         index  = clist.operand_position(comp->_name, comp->_usedef);
      const char *opcode = machOperEnum(comp->_type);
      fprintf(fp_cpp, "%s node->set_opnd_array(%d, ", indent, index);
      fprintf(fp_cpp, "MachOperGenerator(%s, C));\n", opcode);
      }
  }
  else if ( inst->is_chain_of_constant(_globalNames, opType) ) {
    // An instruction that chains from a constant!
    // In this case, we need to subsume the constant into the node
    // at operand position, oper_input_base().
    //
    // Fill in the constant
    fprintf(fp_cpp, "%s node->_opnd_array[%d] = ", indent,
            inst->oper_input_base(_globalNames));
    // #####
    // Check for multiple constants and then fill them in.
    // Just like MachOperGenerator
    const char *opName = inst->_matrule->_rChild->_opType;
    fprintf(fp_cpp, "new (C) %sOper(", opName);
    // Grab operand form
    OperandForm *op = (_globalNames[opName])->is_operand();
    // Look up the number of constants
    uint num_consts = op->num_consts(_globalNames);
    if ( (num_consts > 0) ) {
      uint i = 0;
      path_to_constant(fp_cpp, _globalNames, op->_matrule, i);
      for ( i = 1; i < num_consts; ++i ) {
        fprintf(fp_cpp, ", ");
        path_to_constant(fp_cpp, _globalNames, op->_matrule, i);
      }
    }
    fprintf(fp_cpp, " );\n");
    // #####
  }

  // Fill in the bottom_type where requested
  if ( inst->captures_bottom_type(_globalNames) ) {
    fprintf(fp_cpp, "%s node->_bottom_type = _leaf->bottom_type();\n", indent);
  }
  if( inst->is_ideal_if() ) {
    fprintf(fp_cpp, "%s node->_prob = _leaf->as_If()->_prob;\n", indent);
    fprintf(fp_cpp, "%s node->_fcnt = _leaf->as_If()->_fcnt;\n", indent);
  }
  if( inst->is_ideal_fastlock() ) {
    fprintf(fp_cpp, "%s node->_counters = _leaf->as_FastLock()->counters();\n", indent);
  }

}

//---------------------------declare_cisc_version------------------------------
// Build CISC version of this instruction
void InstructForm::declare_cisc_version(ArchDesc &AD, FILE *fp_hpp) {
  if( AD.can_cisc_spill() ) {
    InstructForm *inst_cisc = cisc_spill_alternate();
    if (inst_cisc != NULL) {
      fprintf(fp_hpp, "  virtual int            cisc_operand() const { return %d; }\n", cisc_spill_operand());
      fprintf(fp_hpp, "  virtual MachNode      *cisc_version(int offset, Compile* C);\n");
      fprintf(fp_hpp, "  virtual void           use_cisc_RegMask();\n");
      fprintf(fp_hpp, "  virtual const RegMask *cisc_RegMask() const { return _cisc_RegMask; }\n");
    }
  }
}

//---------------------------define_cisc_version-------------------------------
// Build CISC version of this instruction
bool InstructForm::define_cisc_version(ArchDesc &AD, FILE *fp_cpp) {
  InstructForm *inst_cisc = this->cisc_spill_alternate();
  if( AD.can_cisc_spill() && (inst_cisc != NULL) ) {
    const char   *name      = inst_cisc->_ident;
    assert( inst_cisc->num_opnds() == this->num_opnds(), "Must have same number of operands");
    OperandForm *cisc_oper = AD.cisc_spill_operand();
    assert( cisc_oper != NULL, "insanity check");
    const char *cisc_oper_name  = cisc_oper->_ident;
    assert( cisc_oper_name != NULL, "insanity check");
    //
    // Set the correct reg_mask_or_stack for the cisc operand
    fprintf(fp_cpp, "\n");
    fprintf(fp_cpp, "void %sNode::use_cisc_RegMask() {\n", this->_ident);
    // Lookup the correct reg_mask_or_stack
    const char *reg_mask_name = cisc_reg_mask_name();
    fprintf(fp_cpp, "  _cisc_RegMask = &STACK_OR_%s;\n", reg_mask_name);
    fprintf(fp_cpp, "}\n");
    //
    // Construct CISC version of this instruction
    fprintf(fp_cpp, "\n");
    fprintf(fp_cpp, "// Build CISC version of this instruction\n");
    fprintf(fp_cpp, "MachNode *%sNode::cisc_version( int offset, Compile* C ) {\n", this->_ident);
    // Create the MachNode object
    fprintf(fp_cpp, "  %sNode *node = new (C) %sNode();\n", name, name);
    // Fill in the bottom_type where requested
    if ( this->captures_bottom_type(AD.globalNames()) ) {
      fprintf(fp_cpp, "  node->_bottom_type = bottom_type();\n");
    }

    uint cur_num_opnds = num_opnds();
    if (cur_num_opnds > 1 && cur_num_opnds != num_unique_opnds()) {
      fprintf(fp_cpp,"  node->_num_opnds = %d;\n", num_unique_opnds());
    }

    fprintf(fp_cpp, "\n");
    fprintf(fp_cpp, "  // Copy _idx, inputs and operands to new node\n");
    fprintf(fp_cpp, "  fill_new_machnode(node, C);\n");
    // Construct operand to access [stack_pointer + offset]
    fprintf(fp_cpp, "  // Construct operand to access [stack_pointer + offset]\n");
    fprintf(fp_cpp, "  node->set_opnd_array(cisc_operand(), new (C) %sOper(offset));\n", cisc_oper_name);
    fprintf(fp_cpp, "\n");

    // Return result and exit scope
    fprintf(fp_cpp, "  return node;\n");
    fprintf(fp_cpp, "}\n");
    fprintf(fp_cpp, "\n");
    return true;
  }
  return false;
}

//---------------------------declare_short_branch_methods----------------------
// Build prototypes for short branch methods
void InstructForm::declare_short_branch_methods(FILE *fp_hpp) {
  if (has_short_branch_form()) {
    fprintf(fp_hpp, "  virtual MachNode      *short_branch_version(Compile* C);\n");
  }
}

//---------------------------define_short_branch_methods-----------------------
// Build definitions for short branch methods
bool InstructForm::define_short_branch_methods(ArchDesc &AD, FILE *fp_cpp) {
  if (has_short_branch_form()) {
    InstructForm *short_branch = short_branch_form();
    const char   *name         = short_branch->_ident;

    // Construct short_branch_version() method.
    fprintf(fp_cpp, "// Build short branch version of this instruction\n");
    fprintf(fp_cpp, "MachNode *%sNode::short_branch_version(Compile* C) {\n", this->_ident);
    // Create the MachNode object
    fprintf(fp_cpp, "  %sNode *node = new (C) %sNode();\n", name, name);
    if( is_ideal_if() ) {
      fprintf(fp_cpp, "  node->_prob = _prob;\n");
      fprintf(fp_cpp, "  node->_fcnt = _fcnt;\n");
    }
    // Fill in the bottom_type where requested
    if ( this->captures_bottom_type(AD.globalNames()) ) {
      fprintf(fp_cpp, "  node->_bottom_type = bottom_type();\n");
    }

    fprintf(fp_cpp, "\n");
    // Short branch version must use same node index for access
    // through allocator's tables
    fprintf(fp_cpp, "  // Copy _idx, inputs and operands to new node\n");
    fprintf(fp_cpp, "  fill_new_machnode(node, C);\n");

    // Return result and exit scope
    fprintf(fp_cpp, "  return node;\n");
    fprintf(fp_cpp, "}\n");
    fprintf(fp_cpp,"\n");
    return true;
  }
  return false;
}


//---------------------------buildMachNodeGenerator----------------------------
// Build switch to invoke appropriate "new" MachNode for an opcode
void ArchDesc::buildMachNodeGenerator(FILE *fp_cpp) {

  // Build switch to invoke 'new' for a specific MachNode
  fprintf(fp_cpp, "\n");
  fprintf(fp_cpp, "\n");
  fprintf(fp_cpp,
          "//------------------------- MachNode Generator ---------------\n");
  fprintf(fp_cpp,
          "// A switch statement on the dense-packed user-defined type system\n"
          "// that invokes 'new' on the corresponding class constructor.\n");
  fprintf(fp_cpp, "\n");
  fprintf(fp_cpp, "MachNode *State::MachNodeGenerator");
  fprintf(fp_cpp, "(int opcode, Compile* C)");
  fprintf(fp_cpp, "{\n");
  fprintf(fp_cpp, "  switch(opcode) {\n");

  // Provide constructor for all user-defined instructions
  _instructions.reset();
  int  opIndex = operandFormCount();
  InstructForm *inst;
  for( ; (inst = (InstructForm*)_instructions.iter()) != NULL; ) {
    // Ensure that matrule is defined.
    if ( inst->_matrule == NULL ) continue;

    int         opcode  = opIndex++;
    const char *opClass = inst->_ident;
    char       *opType  = NULL;

    // Generate the case statement for this instruction
    fprintf(fp_cpp, "  case %s_rule:", opClass);

    // Start local scope
    fprintf(fp_cpp, "  {\n");
    // Generate code to construct the new MachNode
    buildMachNode(fp_cpp, inst, "     ");
    // Return result and exit scope
    fprintf(fp_cpp, "      return node;\n");
    fprintf(fp_cpp, "    }\n");
  }

  // Generate the default case for switch(opcode)
  fprintf(fp_cpp, "  \n");
  fprintf(fp_cpp, "  default:\n");
  fprintf(fp_cpp, "    fprintf(stderr, \"Default MachNode Generator invoked for: \\n\");\n");
  fprintf(fp_cpp, "    fprintf(stderr, \"   opcode = %cd\\n\", opcode);\n", '%');
  fprintf(fp_cpp, "    break;\n");
  fprintf(fp_cpp, "  };\n");

  // Generate the closing for method Matcher::MachNodeGenerator
  fprintf(fp_cpp, "  return NULL;\n");
  fprintf(fp_cpp, "}\n");
}


//---------------------------buildInstructMatchCheck--------------------------
// Output the method to Matcher which checks whether or not a specific
// instruction has a matching rule for the host architecture.
void ArchDesc::buildInstructMatchCheck(FILE *fp_cpp) const {
  fprintf(fp_cpp, "\n\n");
  fprintf(fp_cpp, "const bool Matcher::has_match_rule(int opcode) {\n");
  fprintf(fp_cpp, "  assert(_last_machine_leaf < opcode && opcode < _last_opcode, \"opcode in range\");\n");
  fprintf(fp_cpp, "  return _hasMatchRule[opcode];\n");
  fprintf(fp_cpp, "}\n\n");

  fprintf(fp_cpp, "const bool Matcher::_hasMatchRule[_last_opcode] = {\n");
  int i;
  for (i = 0; i < _last_opcode - 1; i++) {
    fprintf(fp_cpp, "    %-5s,  // %s\n",
            _has_match_rule[i] ? "true" : "false",
            NodeClassNames[i]);
  }
  fprintf(fp_cpp, "    %-5s   // %s\n",
          _has_match_rule[i] ? "true" : "false",
          NodeClassNames[i]);
  fprintf(fp_cpp, "};\n");
}

//---------------------------buildFrameMethods---------------------------------
// Output the methods to Matcher which specify frame behavior
void ArchDesc::buildFrameMethods(FILE *fp_cpp) {
  fprintf(fp_cpp,"\n\n");
  // Stack Direction
  fprintf(fp_cpp,"bool Matcher::stack_direction() const { return %s; }\n\n",
          _frame->_direction ? "true" : "false");
  // Sync Stack Slots
  fprintf(fp_cpp,"int Compile::sync_stack_slots() const { return %s; }\n\n",
          _frame->_sync_stack_slots);
  // Java Stack Alignment
  fprintf(fp_cpp,"uint Matcher::stack_alignment_in_bytes() { return %s; }\n\n",
          _frame->_alignment);
  // Java Return Address Location
  fprintf(fp_cpp,"OptoReg::Name Matcher::return_addr() const {");
  if (_frame->_return_addr_loc) {
    fprintf(fp_cpp," return OptoReg::Name(%s_num); }\n\n",
            _frame->_return_addr);
  }
  else {
    fprintf(fp_cpp," return OptoReg::stack2reg(%s); }\n\n",
            _frame->_return_addr);
  }
  // Java Stack Slot Preservation
  fprintf(fp_cpp,"uint Compile::in_preserve_stack_slots() ");
  fprintf(fp_cpp,"{ return %s; }\n\n", _frame->_in_preserve_slots);
  // Top Of Stack Slot Preservation, for both Java and C
  fprintf(fp_cpp,"uint Compile::out_preserve_stack_slots() ");
  fprintf(fp_cpp,"{ return SharedRuntime::out_preserve_stack_slots(); }\n\n");
  // varargs C out slots killed
  fprintf(fp_cpp,"uint Compile::varargs_C_out_slots_killed() const ");
  fprintf(fp_cpp,"{ return %s; }\n\n", _frame->_varargs_C_out_slots_killed);
  // Java Argument Position
  fprintf(fp_cpp,"void Matcher::calling_convention(BasicType *sig_bt, VMRegPair *regs, uint length, bool is_outgoing) {\n");
  fprintf(fp_cpp,"%s\n", _frame->_calling_convention);
  fprintf(fp_cpp,"}\n\n");
  // Native Argument Position
  fprintf(fp_cpp,"void Matcher::c_calling_convention(BasicType *sig_bt, VMRegPair *regs, uint length) {\n");
  fprintf(fp_cpp,"%s\n", _frame->_c_calling_convention);
  fprintf(fp_cpp,"}\n\n");
  // Java Return Value Location
  fprintf(fp_cpp,"OptoRegPair Matcher::return_value(int ideal_reg, bool is_outgoing) {\n");
  fprintf(fp_cpp,"%s\n", _frame->_return_value);
  fprintf(fp_cpp,"}\n\n");
  // Native Return Value Location
  fprintf(fp_cpp,"OptoRegPair Matcher::c_return_value(int ideal_reg, bool is_outgoing) {\n");
  fprintf(fp_cpp,"%s\n", _frame->_c_return_value);
  fprintf(fp_cpp,"}\n\n");

  // Inline Cache Register, mask definition, and encoding
  fprintf(fp_cpp,"OptoReg::Name Matcher::inline_cache_reg() {");
  fprintf(fp_cpp," return OptoReg::Name(%s_num); }\n\n",
          _frame->_inline_cache_reg);
  fprintf(fp_cpp,"int Matcher::inline_cache_reg_encode() {");
  fprintf(fp_cpp," return _regEncode[inline_cache_reg()]; }\n\n");

  // Interpreter's Method Oop Register, mask definition, and encoding
  fprintf(fp_cpp,"OptoReg::Name Matcher::interpreter_method_oop_reg() {");
  fprintf(fp_cpp," return OptoReg::Name(%s_num); }\n\n",
          _frame->_interpreter_method_oop_reg);
  fprintf(fp_cpp,"int Matcher::interpreter_method_oop_reg_encode() {");
  fprintf(fp_cpp," return _regEncode[interpreter_method_oop_reg()]; }\n\n");

  // Interpreter's Frame Pointer Register, mask definition, and encoding
  fprintf(fp_cpp,"OptoReg::Name Matcher::interpreter_frame_pointer_reg() {");
  if (_frame->_interpreter_frame_pointer_reg == NULL)
    fprintf(fp_cpp," return OptoReg::Bad; }\n\n");
  else
    fprintf(fp_cpp," return OptoReg::Name(%s_num); }\n\n",
            _frame->_interpreter_frame_pointer_reg);

  // Frame Pointer definition
  /* CNC - I can not contemplate having a different frame pointer between
     Java and native code; makes my head hurt to think about it.
  fprintf(fp_cpp,"OptoReg::Name Matcher::frame_pointer() const {");
  fprintf(fp_cpp," return OptoReg::Name(%s_num); }\n\n",
          _frame->_frame_pointer);
  */
  // (Native) Frame Pointer definition
  fprintf(fp_cpp,"OptoReg::Name Matcher::c_frame_pointer() const {");
  fprintf(fp_cpp," return OptoReg::Name(%s_num); }\n\n",
          _frame->_frame_pointer);

  // Number of callee-save + always-save registers for calling convention
  fprintf(fp_cpp, "// Number of callee-save + always-save registers\n");
  fprintf(fp_cpp, "int  Matcher::number_of_saved_registers() {\n");
  RegDef *rdef;
  int nof_saved_registers = 0;
  _register->reset_RegDefs();
  while( (rdef = _register->iter_RegDefs()) != NULL ) {
    if( !strcmp(rdef->_callconv, "SOE") ||  !strcmp(rdef->_callconv, "AS") )
      ++nof_saved_registers;
  }
  fprintf(fp_cpp, "  return %d;\n", nof_saved_registers);
  fprintf(fp_cpp, "};\n\n");
}




static int PrintAdlcCisc = 0;
//---------------------------identify_cisc_spilling----------------------------
// Get info for the CISC_oracle and MachNode::cisc_version()
void ArchDesc::identify_cisc_spill_instructions() {

  // Find the user-defined operand for cisc-spilling
  if( _frame->_cisc_spilling_operand_name != NULL ) {
    const Form *form = _globalNames[_frame->_cisc_spilling_operand_name];
    OperandForm *oper = form ? form->is_operand() : NULL;
    // Verify the user's suggestion
    if( oper != NULL ) {
      // Ensure that match field is defined.
      if ( oper->_matrule != NULL )  {
        MatchRule &mrule = *oper->_matrule;
        if( strcmp(mrule._opType,"AddP") == 0 ) {
          MatchNode *left = mrule._lChild;
          MatchNode *right= mrule._rChild;
          if( left != NULL && right != NULL ) {
            const Form *left_op  = _globalNames[left->_opType]->is_operand();
            const Form *right_op = _globalNames[right->_opType]->is_operand();
            if(  (left_op != NULL && right_op != NULL)
              && (left_op->interface_type(_globalNames) == Form::register_interface)
              && (right_op->interface_type(_globalNames) == Form::constant_interface) ) {
              // Successfully verified operand
              set_cisc_spill_operand( oper );
              if( _cisc_spill_debug ) {
                fprintf(stderr, "\n\nVerified CISC-spill operand %s\n\n", oper->_ident);
             }
            }
          }
        }
      }
    }
  }

  if( cisc_spill_operand() != NULL ) {
    // N^2 comparison of instructions looking for a cisc-spilling version
    _instructions.reset();
    InstructForm *instr;
    for( ; (instr = (InstructForm*)_instructions.iter()) != NULL; ) {
      // Ensure that match field is defined.
      if ( instr->_matrule == NULL )  continue;

      MatchRule &mrule = *instr->_matrule;
      Predicate *pred  =  instr->build_predicate();

      // Grab the machine type of the operand
      const char *rootOp = instr->_ident;
      mrule._machType    = rootOp;

      // Find result type for match
      const char *result = instr->reduce_result();

      if( PrintAdlcCisc ) fprintf(stderr, "  new instruction %s \n", instr->_ident ? instr->_ident : " ");
      bool  found_cisc_alternate = false;
      _instructions.reset2();
      InstructForm *instr2;
      for( ; !found_cisc_alternate && (instr2 = (InstructForm*)_instructions.iter2()) != NULL; ) {
        // Ensure that match field is defined.
        if( PrintAdlcCisc ) fprintf(stderr, "  instr2 == %s \n", instr2->_ident ? instr2->_ident : " ");
        if ( instr2->_matrule != NULL
            && (instr != instr2 )                // Skip self
            && (instr2->reduce_result() != NULL) // want same result
            && (strcmp(result, instr2->reduce_result()) == 0)) {
          MatchRule &mrule2 = *instr2->_matrule;
          Predicate *pred2  =  instr2->build_predicate();
          found_cisc_alternate = instr->cisc_spills_to(*this, instr2);
        }
      }
    }
  }
}

//---------------------------build_cisc_spilling-------------------------------
// Get info for the CISC_oracle and MachNode::cisc_version()
void ArchDesc::build_cisc_spill_instructions(FILE *fp_hpp, FILE *fp_cpp) {
  // Output the table for cisc spilling
  fprintf(fp_cpp, "//  The following instructions can cisc-spill\n");
  _instructions.reset();
  InstructForm *inst = NULL;
  for(; (inst = (InstructForm*)_instructions.iter()) != NULL; ) {
    // Ensure this is a machine-world instruction
    if ( inst->ideal_only() )  continue;
    const char *inst_name = inst->_ident;
    int   operand   = inst->cisc_spill_operand();
    if( operand != AdlcVMDeps::Not_cisc_spillable ) {
      InstructForm *inst2 = inst->cisc_spill_alternate();
      fprintf(fp_cpp, "//  %s can cisc-spill operand %d to %s\n", inst->_ident, operand, inst2->_ident);
    }
  }
  fprintf(fp_cpp, "\n\n");
}

//---------------------------identify_short_branches----------------------------
// Get info for our short branch replacement oracle.
void ArchDesc::identify_short_branches() {
  // Walk over all instructions, checking to see if they match a short
  // branching alternate.
  _instructions.reset();
  InstructForm *instr;
  while( (instr = (InstructForm*)_instructions.iter()) != NULL ) {
    // The instruction must have a match rule.
    if (instr->_matrule != NULL &&
        instr->is_short_branch()) {

      _instructions.reset2();
      InstructForm *instr2;
      while( (instr2 = (InstructForm*)_instructions.iter2()) != NULL ) {
        instr2->check_branch_variant(*this, instr);
      }
    }
  }
}


//---------------------------identify_unique_operands---------------------------
// Identify unique operands.
void ArchDesc::identify_unique_operands() {
  // Walk over all instructions.
  _instructions.reset();
  InstructForm *instr;
  while( (instr = (InstructForm*)_instructions.iter()) != NULL ) {
    // Ensure this is a machine-world instruction
    if (!instr->ideal_only()) {
      instr->set_unique_opnds();
    }
  }
}