summaryrefslogtreecommitdiff
path: root/projects/Stacker/lib/compiler/StackerCompiler.cpp
blob: 339c8afb3cd21c1652dafaf185983a2fbed90202 (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
//===-- StackerCompiler.cpp - Parser for llvm assembly files ----*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by Reid Spencer and donated to the LLVM research
// group and is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//  This file implements the compiler for the "Stacker" language.
//
//===----------------------------------------------------------------------===//

//===----------------------------------------------------------------------===//
//            Globasl - Global variables we use
//===----------------------------------------------------------------------===//

#include "llvm/PassManager.h"
#include "llvm/Analysis/LoadValueNumbering.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Assembly/Parser.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Instructions.h"
#include "llvm/ADT/Statistic.h"
#include "StackerCompiler.h"
#include "StackerParser.h"
#include <string>

// Lexer/Parser defined variables and functions
extern std::FILE *Stackerin;
extern int Stackerlineno;
extern char* Stackertext;
extern int Stackerleng;
extern int Stackerparse();

StackerCompiler* StackerCompiler::TheInstance = 0;

static Statistic<> NumDefinitions(
        "numdefs","The # of definitions encoutered while compiling Stacker");

StackerCompiler::StackerCompiler()
    : CurFilename("")
    , TheModule(0)
    , TheFunction(0)
    , DefinitionType(0)
    , TheStack(0)
    , TheIndex(0)
    , TheScanf(0)
    , ThePrintf(0)
    , TheExit(0)
    , StrFormat(0)
    , NumFormat(0)
    , ChrFormat(0)
    , InStrFormat(0)
    , InNumFormat(0)
    , InChrFormat(0)
    , Zero(0)
    , One(0)
    , Two(0)
    , Three(0)
    , Four(0)
    , Five(0)
    , no_arguments()
    , echo(false)
    , stack_size(256)
    , stack_type(0)
{
}

StackerCompiler::~StackerCompiler()
{
    // delete TheModule; << don't do this!
    // TheModule is passed to caller of the compile() method .. its their
    // problem.  Likewise for the other allocated objects (which become part
    // of TheModule.
    TheModule = 0;
    DefinitionType = 0;
    TheStack = 0;
    TheIndex = 0;
}

Module*
StackerCompiler::compile(
    const std::string& filename,
    bool should_echo,
    unsigned optLevel,
    size_t the_stack_size
)
{
    // TODO: Provide a global lock to protect the singled-threaded compiler
    // and its global variables. Should be in guard object on the stack so
    // that its destructor causes lock to be released (multiple exits from
    // this function).

    // Assign parameters
    CurFilename = filename;
    echo = should_echo;
    stack_size = the_stack_size;

    /// Default the file to read
    FILE *F = stdin;

    ///
    if (filename != "-")
    {
        F = fopen(filename.c_str(), "r");

        if (F == 0)
        {
            throw ParseException(filename,
                "Could not open file '" + filename + "'");
        }
    }

    Module *Result;
    try
    {
        // Create the module we'll return
        TheModule = new Module( CurFilename );

        // Tell the module about our runtime library
        TheModule->addLibrary("stkr_runtime");

        // Create a type to represent the stack. This is the same as the LLVM
        // Assembly type [ 256 x long ]
        stack_type = ArrayType::get( Type::LongTy, stack_size );

        // Create a global variable for the stack. Note the use of appending
        // linkage linkage so that multiple modules will make the stack larger.
        // Also note that the last argument causes the global to be inserted
        // automatically into the module.
        TheStack = new GlobalVariable(
            /*type=*/ stack_type,
            /*isConstant=*/ false,
            /*Linkage=*/ GlobalValue::LinkOnceLinkage,
            /*initializer=*/ Constant::getNullValue(stack_type),
            /*name=*/ "_stack_",
            /*parent=*/ TheModule
        );

        // Create a global variable for indexing into the stack. Note the use
        // of LinkOnce linkage. Only one copy of _index_ will be retained
        // after linking
        TheIndex = new GlobalVariable(
            /*type=*/Type::LongTy,
            /*isConstant=*/false,
            /*Linkage=*/GlobalValue::LinkOnceLinkage,
            /*initializer=*/ Constant::getNullValue(Type::LongTy),
            /*name=*/"_index_",
            /*parent=*/TheModule
        );

        // Create a function prototype for definitions. No parameters, no
        // result.  This is used below any time a function is created.
        std::vector<const Type*> params; // No parameters
        DefinitionType = FunctionType::get( Type::VoidTy, params, false );

        // Create a function for printf(3)
        params.push_back( PointerType::get( Type::SByteTy ) );
        FunctionType* printf_type =
            FunctionType::get( Type::IntTy, params, true );
        ThePrintf = new Function(
            printf_type, GlobalValue::ExternalLinkage, "printf", TheModule);

        // Create a function for scanf(3)
        TheScanf = new Function(
            printf_type, GlobalValue::ExternalLinkage, "scanf", TheModule);

        // Create a function for exit(3)
        params.clear();
        params.push_back( Type::IntTy );
        FunctionType* exit_type =
            FunctionType::get( Type::VoidTy, params, false );
        TheExit = new Function(
            exit_type, GlobalValue::ExternalLinkage, "exit", TheModule);

        Constant* str_format = ConstantArray::get("%s");
        StrFormat = new GlobalVariable(
            /*type=*/ArrayType::get( Type::SByteTy,  3 ),
            /*isConstant=*/true,
            /*Linkage=*/GlobalValue::LinkOnceLinkage,
            /*initializer=*/str_format,
            /*name=*/"_str_format_",
            /*parent=*/TheModule
        );

        Constant* in_str_format = ConstantArray::get(" %as");
        InStrFormat = new GlobalVariable(
            /*type=*/ArrayType::get( Type::SByteTy,  5 ),
            /*isConstant=*/true,
            /*Linkage=*/GlobalValue::LinkOnceLinkage,
            /*initializer=*/in_str_format,
            /*name=*/"_in_str_format_",
            /*parent=*/TheModule
        );

        Constant* num_format = ConstantArray::get("%d");
        NumFormat = new GlobalVariable(
            /*type=*/ArrayType::get( Type::SByteTy,  3 ),
            /*isConstant=*/true,
            /*Linkage=*/GlobalValue::LinkOnceLinkage,
            /*initializer=*/num_format,
            /*name=*/"_num_format_",
            /*parent=*/TheModule
        );

        Constant* in_num_format = ConstantArray::get(" %d");
        InNumFormat = new GlobalVariable(
            /*type=*/ArrayType::get( Type::SByteTy,  4 ),
            /*isConstant=*/true,
            /*Linkage=*/GlobalValue::LinkOnceLinkage,
            /*initializer=*/in_num_format,
            /*name=*/"_in_num_format_",
            /*parent=*/TheModule
        );

        Constant* chr_format = ConstantArray::get("%c");
        ChrFormat = new GlobalVariable(
            /*type=*/ArrayType::get( Type::SByteTy,  3 ),
            /*isConstant=*/true,
            /*Linkage=*/GlobalValue::LinkOnceLinkage,
            /*initializer=*/chr_format,
            /*name=*/"_chr_format_",
            /*parent=*/TheModule
        );

        Constant* in_chr_format = ConstantArray::get(" %c");
        InChrFormat = new GlobalVariable(
            /*type=*/ArrayType::get( Type::SByteTy,  4 ),
            /*isConstant=*/true,
            /*Linkage=*/GlobalValue::LinkOnceLinkage,
            /*initializer=*/in_chr_format,
            /*name=*/"_in_chr_format_",
            /*parent=*/TheModule
        );

        // Get some constants so we aren't always creating them
        Zero = ConstantInt::get( Type::LongTy, 0 );
        One = ConstantInt::get( Type::LongTy, 1 );
        Two = ConstantInt::get( Type::LongTy, 2 );
        Three = ConstantInt::get( Type::LongTy, 3 );
        Four = ConstantInt::get( Type::LongTy, 4 );
        Five = ConstantInt::get( Type::LongTy, 5 );

        // Reset the current line number
        Stackerlineno = 1;

        // Reset the parser's input to F
        Stackerin = F;          // Set the input file.

        // Let the parse know about this instance
        TheInstance = this;

        // Parse the file. The parser (see StackParser.y) will call back to
        // the StackerCompiler via the "handle*" methods
        Stackerparse();

        // Avoid potential illegal use (TheInstance might be on the stack)
        TheInstance = 0;

        // Set up a pass manager
        PassManager Passes;
        // Add in the passes we want to execute
        Passes.add(new TargetData("stkrc",TheModule));
        // Verify we start with valid
        Passes.add(createVerifierPass());

        if (optLevel > 0) {
            if (optLevel > 1) {
                // Clean up disgusting code
                Passes.add(createCFGSimplificationPass());
                // Remove unused globals
                Passes.add(createGlobalDCEPass());
                // IP Constant Propagation
                Passes.add(createIPConstantPropagationPass());
                // Clean up after IPCP
                Passes.add(createInstructionCombiningPass());
                // Clean up after IPCP
                Passes.add(createCFGSimplificationPass());
                // Inline small definitions (functions)
                Passes.add(createFunctionInliningPass());
                // Simplify cfg by copying code
                Passes.add(createTailDuplicationPass());
                if (optLevel > 2) {
                    // Merge & remove BBs
                    Passes.add(createCFGSimplificationPass());
                    // Compile silly sequences
                    Passes.add(createInstructionCombiningPass());
                    // Reassociate expressions
                    Passes.add(createReassociatePass());
                    // Combine silly seq's
                    Passes.add(createInstructionCombiningPass());
                    // Eliminate tail calls
                    Passes.add(createTailCallEliminationPass());
                    // Merge & remove BBs
                    Passes.add(createCFGSimplificationPass());
                    // Hoist loop invariants
                    Passes.add(createLICMPass());
                    // Clean up after the unroller
                    Passes.add(createInstructionCombiningPass());
                    // Canonicalize indvars
                    Passes.add(createIndVarSimplifyPass());
                    // Unroll small loops
                    Passes.add(createLoopUnrollPass());
                    // Clean up after the unroller
                    Passes.add(createInstructionCombiningPass());
                    // GVN for load instructions
                    Passes.add(createLoadValueNumberingPass());
                    // Remove common subexprs
                    Passes.add(createGCSEPass());
                    // Constant prop with SCCP
                    Passes.add(createSCCPPass());
                }
                if (optLevel > 3) {
                    // Run instcombine again after redundancy elimination
                    Passes.add(createInstructionCombiningPass());
                    // Delete dead stores
                    Passes.add(createDeadStoreEliminationPass());
                    // SSA based 'Aggressive DCE'
                    Passes.add(createAggressiveDCEPass());
                    // Merge & remove BBs
                    Passes.add(createCFGSimplificationPass());
                    // Merge dup global constants
                    Passes.add(createConstantMergePass());
                }
            }

            // Merge & remove BBs
            Passes.add(createCFGSimplificationPass());
            // Memory To Register
            Passes.add(createPromoteMemoryToRegisterPass());
            // Compile silly sequences
            Passes.add(createInstructionCombiningPass());
            // Make sure everything is still good.
            Passes.add(createVerifierPass());
        }

        // Run our queue of passes all at once now, efficiently.
        Passes.run(*TheModule);

    } catch (...) {
        if (F != stdin) fclose(F);      // Make sure to close file descriptor
        throw;                          // if an exception is thrown
    }

    // Close the file
    if (F != stdin) fclose(F);

    // Return the compiled module to the caller
    return TheModule;
}

//===----------------------------------------------------------------------===//
//            Internal Functions, used by handleXXX below.
//            These represent the basic stack operations.
//===----------------------------------------------------------------------===//

Instruction*
StackerCompiler::incr_stack_index( BasicBlock* bb, Value* ival = 0 )
{
    // Load the value from the TheIndex
    LoadInst* loadop = new LoadInst( TheIndex );
    bb->getInstList().push_back( loadop );

    // Increment the loaded index value
    if ( ival == 0 ) ival = One;
    CastInst* caster = new CastInst( ival, Type::LongTy );
    bb->getInstList().push_back( caster );
    BinaryOperator* addop = BinaryOperator::create( Instruction::Add,
            loadop, caster);
    bb->getInstList().push_back( addop );

    // Store the incremented value
    StoreInst* storeop = new StoreInst( addop, TheIndex );
    bb->getInstList().push_back( storeop );
    return storeop;
}

Instruction*
StackerCompiler::decr_stack_index( BasicBlock* bb, Value* ival = 0 )
{
    // Load the value from the TheIndex
    LoadInst* loadop = new LoadInst( TheIndex );
    bb->getInstList().push_back( loadop );

    // Decrement the loaded index value
    if ( ival == 0 ) ival = One;
    CastInst* caster = new CastInst( ival, Type::LongTy );
    bb->getInstList().push_back( caster );
    BinaryOperator* subop = BinaryOperator::create( Instruction::Sub,
            loadop, caster);
    bb->getInstList().push_back( subop );

    // Store the incremented value
    StoreInst* storeop = new StoreInst( subop, TheIndex );
    bb->getInstList().push_back( storeop );

    return storeop;
}

Instruction*
StackerCompiler::get_stack_pointer( BasicBlock* bb, Value* index = 0 )
{
    // Load the value of the Stack Index
    LoadInst* loadop = new LoadInst( TheIndex );
    bb->getInstList().push_back( loadop );

    // Index into the stack to get its address. NOTE the use of two
    // elements in this vector. The first de-references the pointer that
    // "TheStack" represents. The second indexes into the pointed to array.
    // Think of the first index as getting the address of the 0th element
    // of the array.
    std::vector<Value*> indexVec;
    indexVec.push_back( Zero );

    if ( index == 0 )
    {
        indexVec.push_back(loadop);
    }
    else
    {
        CastInst* caster = new CastInst( index, Type::LongTy );
        bb->getInstList().push_back( caster );
        BinaryOperator* subop = BinaryOperator::create(
            Instruction::Sub, loadop, caster );
        bb->getInstList().push_back( subop );
        indexVec.push_back(subop);
    }

    // Get the address of the indexed stack element
    GetElementPtrInst* gep = new GetElementPtrInst( TheStack, indexVec );
    bb->getInstList().push_back( gep );         // Put GEP in Block

    return gep;
}

Instruction*
StackerCompiler::push_value( BasicBlock* bb, Value* val )
{
    // Get location of
    incr_stack_index(bb);

    // Get the stack pointer
    GetElementPtrInst* gep = cast<GetElementPtrInst>(
            get_stack_pointer( bb ) );

    // Cast the value to a long .. hopefully it works
    CastInst* cast_inst = new CastInst( val, Type::LongTy );
    bb->getInstList().push_back( cast_inst );

    // Store the value
    StoreInst* storeop = new StoreInst( cast_inst, gep );
    bb->getInstList().push_back( storeop );

    return storeop;
}

Instruction*
StackerCompiler::push_integer(BasicBlock* bb, int64_t value )
{
    // Just push a constant integer value
    return push_value( bb, ConstantSInt::get( Type::LongTy, value ) );
}

Instruction*
StackerCompiler::pop_integer( BasicBlock*bb )
{
    // Get the stack pointer
    GetElementPtrInst* gep = cast<GetElementPtrInst>(
        get_stack_pointer( bb ));

    // Load the value
    LoadInst* load_inst = new LoadInst( gep );
    bb->getInstList().push_back( load_inst );

    // Decrement the stack index
    decr_stack_index( bb );

    // Return the value
    return load_inst;
}

Instruction*
StackerCompiler::push_string( BasicBlock* bb, const char* value )
{
    // Get length of the string
    size_t len = strlen( value );

    // Create a type for the string constant. Length is +1 for
    // the terminating 0.
    ArrayType* char_array = ArrayType::get( Type::SByteTy, len + 1 );

    // Create an initializer for the value
    Constant* initVal = ConstantArray::get( value );

    // Create an internal linkage global variable to hold the constant.
    GlobalVariable* strconst = new GlobalVariable(
        char_array,
        /*isConstant=*/true,
        GlobalValue::InternalLinkage,
        /*initializer=*/initVal,
        "",
        TheModule
    );

    // Push the casted value
    return push_value( bb, strconst );
}

Instruction*
StackerCompiler::pop_string( BasicBlock* bb )
{
    // Get location of stack pointer
    GetElementPtrInst* gep = cast<GetElementPtrInst>(
        get_stack_pointer( bb ));

    // Load the value from the stack
    LoadInst* loader = new LoadInst( gep );
    bb->getInstList().push_back( loader );

    // Cast the integer to a sbyte*
    CastInst* caster = new CastInst( loader, PointerType::get(Type::SByteTy) );
    bb->getInstList().push_back( caster );

    // Decrement stack index
    decr_stack_index( bb );

    // Return the value
    return caster;
}

Instruction*
StackerCompiler::replace_top( BasicBlock* bb, Value* new_top, Value* index = 0 )
{
    // Get the stack pointer
    GetElementPtrInst* gep = cast<GetElementPtrInst>(
            get_stack_pointer( bb, index ));

    // Store the value there
    StoreInst* store_inst = new StoreInst( new_top, gep );
    bb->getInstList().push_back( store_inst );

    // Return the value
    return store_inst;
}

Instruction*
StackerCompiler::stack_top( BasicBlock* bb, Value* index = 0 )
{
    // Get the stack pointer
    GetElementPtrInst* gep = cast<GetElementPtrInst>(
        get_stack_pointer( bb, index ));

    // Load the value
    LoadInst* load_inst = new LoadInst( gep );
    bb->getInstList().push_back( load_inst );

    // Return the value
    return load_inst;
}

Instruction*
StackerCompiler::stack_top_string( BasicBlock* bb, Value* index = 0 )
{
    // Get location of stack pointer
    GetElementPtrInst* gep = cast<GetElementPtrInst>(
        get_stack_pointer( bb, index ));

    // Load the value from the stack
    LoadInst* loader = new LoadInst( gep );
    bb->getInstList().push_back( loader );

    // Cast the integer to a sbyte*
    CastInst* caster = new CastInst( loader, PointerType::get(Type::SByteTy) );
    bb->getInstList().push_back( caster );

    // Return the value
    return caster;
}

static void
add_block( Function*f, BasicBlock* bb )
{
    if ( ! f->empty() && f->back().getTerminator() == 0 )
    {
        BranchInst* branch = new BranchInst(bb);
        f->back().getInstList().push_back( branch );
    }
    f->getBasicBlockList().push_back( bb );
}


//===----------------------------------------------------------------------===//
//            handleXXX - Handle semantics of parser productions
//===----------------------------------------------------------------------===//

Module*
StackerCompiler::handle_module_start( )
{
    // Return the newly created module
    return TheModule;
}

Module*
StackerCompiler::handle_module_end( Module* mod )
{
    // Return the module.
    return mod;
}

Module*
StackerCompiler::handle_definition_list_start()
{
    return TheModule;
}

Module*
StackerCompiler::handle_definition_list_end( Module* mod, Function* definition )
{
    if ( ! definition->empty() )
    {
        BasicBlock& last_block = definition->back();
        if ( last_block.getTerminator() == 0 )
        {
            last_block.getInstList().push_back( new ReturnInst() );
        }
    }
    // Insert the definition into the module
    mod->getFunctionList().push_back( definition );

    // Bump our (sample) statistic.
    ++NumDefinitions;
    return mod;
}

Function*
StackerCompiler::handle_main_definition( Function* func )
{
    // Set the name of the function defined as the Stacker main
    // This will get called by the "main" that is defined in
    // the runtime library.
    func->setName( "_MAIN_");

    // Turn "_stack_" into an initialized variable since this is the main
    // module. This causes it to not be "external" but defined in this module.
    TheStack->setInitializer( Constant::getNullValue(stack_type) );
    TheStack->setLinkage( GlobalValue::LinkOnceLinkage );

    // Turn "_index_" into an intialized variable for the same reason.
    TheIndex->setInitializer( Constant::getNullValue(Type::LongTy) );
    TheIndex->setLinkage( GlobalValue::LinkOnceLinkage );

    return func;
}

Function*
StackerCompiler::handle_forward( char * name )
{
    // Just create a placeholder function
    Function* the_function = new Function (
        DefinitionType,
        GlobalValue::ExternalLinkage,
        name );
    assert( the_function->isExternal() );

    free( name );
    return the_function;
}

Function*
StackerCompiler::handle_definition( char * name, Function* f )
{
    // Look up the function name in the module to see if it was forward
    // declared.
#if 0
    Function* existing_function = TheModule->getNamedFunction( name );

    // If the function already exists...
    if ( existing_function )
    {
        // Just get rid of the placeholder
        existing_function->dropAllReferences();
        delete existing_function;
    }
#endif

    // Just set the name of the function now that we know what it is.
    f->setName( name );

    free( name );

    return f;
}

Function*
StackerCompiler::handle_word_list_start()
{
    TheFunction = new Function(DefinitionType, GlobalValue::ExternalLinkage);
    return TheFunction;
}

Function*
StackerCompiler::handle_word_list_end( Function* f, BasicBlock* bb )
{
    add_block( f, bb );
    return f;
}

BasicBlock*
StackerCompiler::handle_if( char* ifTrue, char* ifFalse )
{
    // Create a basic block for the preamble
    BasicBlock* bb = new BasicBlock((echo?"if":""));

    // Get the condition value
    LoadInst* cond = cast<LoadInst>( pop_integer(bb) );

    // Compare the condition against 0
    SetCondInst* cond_inst = new SetCondInst( Instruction::SetNE, cond,
        ConstantSInt::get( Type::LongTy, 0) );
    bb->getInstList().push_back( cond_inst );

    // Create an exit block
    BasicBlock* exit_bb = new BasicBlock((echo?"endif":""));

    // Create the true_block
    BasicBlock* true_bb = new BasicBlock((echo?"then":""));

    // Create the false_block
    BasicBlock* false_bb = 0;
    if ( ifFalse ) false_bb = new BasicBlock((echo?"else":""));

    // Create a branch on the SetCond
    BranchInst* br_inst = new BranchInst( true_bb,
        ( ifFalse ? false_bb : exit_bb ), cond_inst );
    bb->getInstList().push_back( br_inst );

    // Fill the true block
    std::vector<Value*> args;
    if ( Function* true_func = TheModule->getNamedFunction(ifTrue) )
    {
        true_bb->getInstList().push_back(
                new CallInst( true_func, args ) );
        true_bb->getInstList().push_back(
                new BranchInst( exit_bb ) );
    }
    else
    {
        ThrowException(std::string("Function '") + ifTrue +
            "' must be declared first.'");
    }

    free( ifTrue );

    // Fill the false block
    if ( false_bb )
    {
        if ( Function* false_func = TheModule->getNamedFunction(ifFalse) )
        {
            false_bb->getInstList().push_back(
                    new CallInst( false_func, args ) );
            false_bb->getInstList().push_back(
                    new BranchInst( exit_bb ) );
        }
        else
        {
            ThrowException(std::string("Function '") + ifFalse +
                    "' must be declared first.'");
        }
        free( ifFalse );
    }

    // Add the blocks to the function
    add_block( TheFunction, bb );
    add_block( TheFunction, true_bb );
    if ( false_bb ) add_block( TheFunction, false_bb );

    return exit_bb;
}

BasicBlock*
StackerCompiler::handle_while( char* todo )
{

    // Create a basic block for the loop test
    BasicBlock* test = new BasicBlock((echo?"while":""));

    // Create an exit block
    BasicBlock* exit = new BasicBlock((echo?"end":""));

    // Create a loop body block
    BasicBlock* body = new BasicBlock((echo?"do":""));

    // Create a root node
    BasicBlock* bb = new BasicBlock((echo?"root":""));
    BranchInst* root_br_inst = new BranchInst( test );
    bb->getInstList().push_back( root_br_inst );

    // Examine the condition value
    LoadInst* cond = cast<LoadInst>( stack_top(test) );

    // Compare the condition against 0
    SetCondInst* cond_inst = new SetCondInst(
        Instruction::SetNE, cond, ConstantSInt::get( Type::LongTy, 0) );
    test->getInstList().push_back( cond_inst );

    // Add the branch instruction
    BranchInst* br_inst = new BranchInst( body, exit, cond_inst );
    test->getInstList().push_back( br_inst );

    // Fill in the body
    std::vector<Value*> args;
    if ( Function* body_func = TheModule->getNamedFunction(todo) )
    {
        body->getInstList().push_back( new CallInst( body_func, args ) );
        body->getInstList().push_back( new BranchInst( test ) );
    }
    else
    {
        ThrowException(std::string("Function '") + todo +
            "' must be declared first.'");
    }

    free( todo );

    // Add the blocks
    add_block( TheFunction, bb );
    add_block( TheFunction, test );
    add_block( TheFunction, body );

    return exit;
}

BasicBlock*
StackerCompiler::handle_identifier( char * name )
{
    Function* func = TheModule->getNamedFunction( name );
    BasicBlock* bb = new BasicBlock((echo?"call":""));
    if ( func )
    {
        CallInst* call_def = new CallInst( func , no_arguments );
        bb->getInstList().push_back( call_def );
    }
    else
    {
        ThrowException(std::string("Definition '") + name +
            "' must be defined before it can be used.");
    }

    free( name );
    return bb;
}

BasicBlock*
StackerCompiler::handle_string( char * value )
{
    // Create a new basic block for the push operation
    BasicBlock* bb = new BasicBlock((echo?"string":""));

    // Push the string onto the stack
    push_string(bb, value);

    // Free the strdup'd string
    free( value );

    return bb;
}

BasicBlock*
StackerCompiler::handle_integer( const int64_t value )
{
    // Create a new basic block for the push operation
    BasicBlock* bb = new BasicBlock((echo?"int":""));

    // Push the integer onto the stack
    push_integer(bb, value );

    return bb;
}

BasicBlock*
StackerCompiler::handle_word( int tkn )
{
    // Create a new basic block to hold the instruction(s)
    BasicBlock* bb = new BasicBlock();

    /* Fill the basic block with the appropriate instructions */
    switch ( tkn )
    {
    case DUMP :  // Dump the stack (debugging aid)
    {
        if (echo) bb->setName("DUMP");
        Function* f = TheModule->getOrInsertFunction(
            "_stacker_dump_stack_", DefinitionType);
        std::vector<Value*> args;
        bb->getInstList().push_back( new CallInst( f, args ) );
        break;
    }

    // Logical Operations
    case TRUETOK :  // -- -1
    {
        if (echo) bb->setName("TRUE");
        push_integer(bb,-1);
        break;
    }
    case FALSETOK : // -- 0
    {
        if (echo) bb->setName("FALSE");
        push_integer(bb,0);
        break;
    }
    case LESS : // w1 w2 -- w2<w1
    {
        if (echo) bb->setName("LESS");
        LoadInst* op1 = cast<LoadInst>(pop_integer(bb));
        LoadInst* op2 = cast<LoadInst>(pop_integer(bb));
        SetCondInst* cond_inst =
            new SetCondInst( Instruction::SetLT, op1, op2 );
        bb->getInstList().push_back( cond_inst );
        push_value( bb, cond_inst );
        break;
    }
    case MORE : // w1 w2 -- w2>w1
    {
        if (echo) bb->setName("MORE");
        LoadInst* op1 = cast<LoadInst>(pop_integer(bb));
        LoadInst* op2 = cast<LoadInst>(pop_integer(bb));
        SetCondInst* cond_inst =
            new SetCondInst( Instruction::SetGT, op1, op2 );
        bb->getInstList().push_back( cond_inst );
        push_value( bb, cond_inst );
        break;
    }
    case LESS_EQUAL : // w1 w2 -- w2<=w1
    {
        if (echo) bb->setName("LE");
        LoadInst* op1 = cast<LoadInst>(pop_integer(bb));
        LoadInst* op2 = cast<LoadInst>(pop_integer(bb));
        SetCondInst* cond_inst =
            new SetCondInst( Instruction::SetLE, op1, op2 );
        bb->getInstList().push_back( cond_inst );
        push_value( bb, cond_inst );
        break;
    }
    case MORE_EQUAL : // w1 w2 -- w2>=w1
    {
        if (echo) bb->setName("GE");
        LoadInst* op1 = cast<LoadInst>(pop_integer(bb));
        LoadInst* op2 = cast<LoadInst>(pop_integer(bb));
        SetCondInst* cond_inst =
            new SetCondInst( Instruction::SetGE, op1, op2 );
        bb->getInstList().push_back( cond_inst );
        push_value( bb, cond_inst );
        break;
    }
    case NOT_EQUAL : // w1 w2 -- w2!=w1
    {
        if (echo) bb->setName("NE");
        LoadInst* op1 = cast<LoadInst>(pop_integer(bb));
        LoadInst* op2 = cast<LoadInst>(pop_integer(bb));
        SetCondInst* cond_inst =
            new SetCondInst( Instruction::SetNE, op1, op2 );
        bb->getInstList().push_back( cond_inst );
        push_value( bb, cond_inst );
        break;
    }
    case EQUAL : // w1 w2 -- w1==w2
    {
        if (echo) bb->setName("EQ");
        LoadInst* op1 = cast<LoadInst>(pop_integer(bb));
        LoadInst* op2 = cast<LoadInst>(pop_integer(bb));
        SetCondInst* cond_inst =
            new SetCondInst( Instruction::SetEQ, op1, op2 );
        bb->getInstList().push_back( cond_inst );
        push_value( bb, cond_inst );
        break;
    }

    // Arithmetic Operations
    case PLUS : // w1 w2 -- w2+w1
    {
        if (echo) bb->setName("ADD");
        LoadInst* op1 = cast<LoadInst>(pop_integer(bb));
        LoadInst* op2 = cast<LoadInst>(pop_integer(bb));
        BinaryOperator* addop =
            BinaryOperator::create( Instruction::Add, op1, op2);
        bb->getInstList().push_back( addop );
        push_value( bb, addop );
        break;
    }
    case MINUS : // w1 w2 -- w2-w1
    {
        if (echo) bb->setName("SUB");
        LoadInst* op1 = cast<LoadInst>(pop_integer(bb));
        LoadInst* op2 = cast<LoadInst>(pop_integer(bb));
        BinaryOperator* subop =
            BinaryOperator::create( Instruction::Sub, op1, op2);
        bb->getInstList().push_back( subop );
        push_value( bb, subop );
        break;
    }
    case INCR :  // w1 -- w1+1
    {
        if (echo) bb->setName("INCR");
        LoadInst* op1 = cast<LoadInst>(pop_integer(bb));
        BinaryOperator* addop =
            BinaryOperator::create( Instruction::Add, op1, One );
        bb->getInstList().push_back( addop );
        push_value( bb, addop );
        break;
    }
    case DECR : // w1 -- w1-1
    {
        if (echo) bb->setName("DECR");
        LoadInst* op1 = cast<LoadInst>(pop_integer(bb));
        BinaryOperator* subop = BinaryOperator::create( Instruction::Sub, op1,
            ConstantSInt::get( Type::LongTy, 1 ) );
        bb->getInstList().push_back( subop );
        push_value( bb, subop );
        break;
    }
    case MULT : // w1 w2 -- w2*w1
    {
        if (echo) bb->setName("MUL");
        LoadInst* op1 = cast<LoadInst>(pop_integer(bb));
        LoadInst* op2 = cast<LoadInst>(pop_integer(bb));
        BinaryOperator* multop =
            BinaryOperator::create( Instruction::Mul, op1, op2);
        bb->getInstList().push_back( multop );
        push_value( bb, multop );
        break;
    }
    case DIV :// w1 w2 -- w2/w1
    {
        if (echo) bb->setName("DIV");
        LoadInst* op1 = cast<LoadInst>(pop_integer(bb));
        LoadInst* op2 = cast<LoadInst>(pop_integer(bb));
        BinaryOperator* divop =
            BinaryOperator::create( Instruction::Div, op1, op2);
        bb->getInstList().push_back( divop );
        push_value( bb, divop );
        break;
    }
    case MODULUS : // w1 w2 -- w2%w1
    {
        if (echo) bb->setName("MOD");
        LoadInst* op1 = cast<LoadInst>(pop_integer(bb));
        LoadInst* op2 = cast<LoadInst>(pop_integer(bb));
        BinaryOperator* divop =
            BinaryOperator::create( Instruction::Rem, op1, op2);
        bb->getInstList().push_back( divop );
        push_value( bb, divop );
        break;
    }
    case STAR_SLASH : // w1 w2 w3 -- (w3*w2)/w1
    {
        if (echo) bb->setName("STAR_SLASH");
        // Get the operands
        LoadInst* op1 = cast<LoadInst>(pop_integer(bb));
        LoadInst* op2 = cast<LoadInst>(pop_integer(bb));
        LoadInst* op3 = cast<LoadInst>(pop_integer(bb));

        // Multiply the first two
        BinaryOperator* multop =
            BinaryOperator::create( Instruction::Mul, op1, op2);
        bb->getInstList().push_back( multop );

        // Divide by the third operand
        BinaryOperator* divop =
            BinaryOperator::create( Instruction::Div, multop, op3);
        bb->getInstList().push_back( divop );

        // Push the result
        push_value( bb, divop );

        break;
    }
    case NEGATE : // w1 -- -w1
    {
        if (echo) bb->setName("NEG");
        LoadInst* op1 = cast<LoadInst>(pop_integer(bb));
        // APPARENTLY, the following doesn't work:
        // BinaryOperator* negop = BinaryOperator::createNeg( op1 );
        // bb->getInstList().push_back( negop );
        // So we'll multiply by -1 (ugh)
        BinaryOperator* multop = BinaryOperator::create( Instruction::Mul, op1,
            ConstantSInt::get( Type::LongTy, -1 ) );
        bb->getInstList().push_back( multop );
        push_value( bb, multop );
        break;
    }
    case ABS : // w1 -- |w1|
    {
        if (echo) bb->setName("ABS");
        // Get the top of stack value
        LoadInst* op1 = cast<LoadInst>(stack_top(bb));

        // Determine if its negative
        SetCondInst* cond_inst =
            new SetCondInst( Instruction::SetLT, op1, Zero );
        bb->getInstList().push_back( cond_inst );

        // Create a block for storing the result
        BasicBlock* exit_bb = new BasicBlock((echo?"exit":""));

        // Create a block for making it a positive value
        BasicBlock* pos_bb = new BasicBlock((echo?"neg":""));

        // Create the branch on the SetCond
        BranchInst* br_inst = new BranchInst( pos_bb, exit_bb, cond_inst );
        bb->getInstList().push_back( br_inst );

        // Fill out the negation block
        LoadInst* pop_op = cast<LoadInst>( pop_integer(pos_bb) );
        BinaryOperator* neg_op = BinaryOperator::createNeg( pop_op );
        pos_bb->getInstList().push_back( neg_op );
        push_value( pos_bb, neg_op );
        pos_bb->getInstList().push_back( new BranchInst( exit_bb ) );

        // Add the new blocks in the correct order
        add_block( TheFunction, bb );
        add_block( TheFunction, pos_bb );
        bb = exit_bb;
        break;
    }
    case MIN : // w1 w2 -- (w2<w1?w2:w1)
    {
        if (echo) bb->setName("MIN");

        // Create the three blocks
        BasicBlock* exit_bb  = new BasicBlock((echo?"exit":""));
        BasicBlock* op1_block = new BasicBlock((echo?"less":""));
        BasicBlock* op2_block = new BasicBlock((echo?"more":""));

        // Get the two operands
        LoadInst* op1 = cast<LoadInst>(pop_integer(bb));
        LoadInst* op2 = cast<LoadInst>(pop_integer(bb));

        // Compare them
        SetCondInst* cond_inst =
            new SetCondInst( Instruction::SetLT, op1, op2);
        bb->getInstList().push_back( cond_inst );

        // Create a branch on the SetCond
        BranchInst* br_inst =
            new BranchInst( op1_block, op2_block, cond_inst );
        bb->getInstList().push_back( br_inst );

        // Create a block for pushing the first one
        push_value(op1_block, op1);
        op1_block->getInstList().push_back( new BranchInst( exit_bb ) );

        // Create a block for pushing the second one
        push_value(op2_block, op2);
        op2_block->getInstList().push_back( new BranchInst( exit_bb ) );

        // Add the blocks
        add_block( TheFunction, bb );
        add_block( TheFunction, op1_block );
        add_block( TheFunction, op2_block );
        bb = exit_bb;
        break;
    }
    case MAX : // w1 w2 -- (w2>w1?w2:w1)
    {
        if (echo) bb->setName("MAX");
        // Get the two operands
        LoadInst* op1 = cast<LoadInst>(pop_integer(bb));
        LoadInst* op2 = cast<LoadInst>(pop_integer(bb));

        // Compare them
        SetCondInst* cond_inst =
            new SetCondInst( Instruction::SetGT, op1, op2);
        bb->getInstList().push_back( cond_inst );

        // Create an exit block
        BasicBlock* exit_bb = new BasicBlock((echo?"exit":""));

        // Create a block for pushing the larger one
        BasicBlock* op1_block = new BasicBlock((echo?"more":""));
        push_value(op1_block, op1);
        op1_block->getInstList().push_back( new BranchInst( exit_bb ) );

        // Create a block for pushing the smaller or equal one
        BasicBlock* op2_block = new BasicBlock((echo?"less":""));
        push_value(op2_block, op2);
        op2_block->getInstList().push_back( new BranchInst( exit_bb ) );

        // Create a banch on the SetCond
        BranchInst* br_inst =
            new BranchInst( op1_block, op2_block, cond_inst );
        bb->getInstList().push_back( br_inst );

        // Add the blocks
        add_block( TheFunction, bb );
        add_block( TheFunction, op1_block );
        add_block( TheFunction, op2_block );

        bb = exit_bb;
        break;
    }

    // Bitwise Operators
    case AND : // w1 w2 -- w2&w1
    {
        if (echo) bb->setName("AND");
        LoadInst* op1 = cast<LoadInst>(pop_integer(bb));
        LoadInst* op2 = cast<LoadInst>(pop_integer(bb));
        BinaryOperator* andop =
            BinaryOperator::create( Instruction::And, op1, op2);
        bb->getInstList().push_back( andop );
        push_value( bb, andop );
        break;
    }
    case OR : // w1 w2 -- w2|w1
    {
        if (echo) bb->setName("OR");
        LoadInst* op1 = cast<LoadInst>(pop_integer(bb));
        LoadInst* op2 = cast<LoadInst>(pop_integer(bb));
        BinaryOperator* orop =
            BinaryOperator::create( Instruction::Or, op1, op2);
        bb->getInstList().push_back( orop );
        push_value( bb, orop );
        break;
    }
    case XOR : // w1 w2 -- w2^w1
    {
        if (echo) bb->setName("XOR");
        LoadInst* op1 = cast<LoadInst>(pop_integer(bb));
        LoadInst* op2 = cast<LoadInst>(pop_integer(bb));
        BinaryOperator* xorop =
            BinaryOperator::create( Instruction::Xor, op1, op2);
        bb->getInstList().push_back( xorop );
        push_value( bb, xorop );
        break;
    }
    case LSHIFT : // w1 w2 -- w1<<w2
    {
        if (echo) bb->setName("SHL");
        LoadInst* op1 = cast<LoadInst>(pop_integer(bb));
        LoadInst* op2 = cast<LoadInst>(pop_integer(bb));
        CastInst* castop = new CastInst( op1, Type::UByteTy );
        bb->getInstList().push_back( castop );
        ShiftInst* shlop = new ShiftInst( Instruction::Shl, op2, castop );
        bb->getInstList().push_back( shlop );
        push_value( bb, shlop );
        break;
    }
    case RSHIFT :  // w1 w2 -- w1>>w2
    {
        if (echo) bb->setName("SHR");
        LoadInst* op1 = cast<LoadInst>(pop_integer(bb));
        LoadInst* op2 = cast<LoadInst>(pop_integer(bb));
        CastInst* castop = new CastInst( op1, Type::UByteTy );
        bb->getInstList().push_back( castop );
        ShiftInst* shrop = new ShiftInst( Instruction::Shr, op2, castop );
        bb->getInstList().push_back( shrop );
        push_value( bb, shrop );
        break;
    }

    // Stack Manipulation Operations
    case DROP:          // w --
    {
        if (echo) bb->setName("DROP");
        decr_stack_index(bb, One);
        break;
    }
    case DROP2: // w1 w2 --
    {
        if (echo) bb->setName("DROP2");
        decr_stack_index( bb, Two );
        break;
    }
    case NIP:   // w1 w2 -- w2
    {
        if (echo) bb->setName("NIP");
        LoadInst* w2 = cast<LoadInst>( stack_top( bb ) );
        decr_stack_index( bb  );
        replace_top( bb, w2 );
        break;
    }
    case NIP2:  // w1 w2 w3 w4 -- w3 w4
    {
        if (echo) bb->setName("NIP2");
        LoadInst* w4 = cast<LoadInst>( stack_top( bb ) );
        LoadInst* w3 = cast<LoadInst>( stack_top( bb, One ) );
        decr_stack_index( bb, Two );
        replace_top( bb, w4 );
        replace_top( bb, w3, One );
        break;
    }
    case DUP:   // w -- w w
    {
        if (echo) bb->setName("DUP");
        LoadInst* w = cast<LoadInst>( stack_top( bb ) );
        push_value( bb, w );
        break;
    }
    case DUP2:  // w1 w2 -- w1 w2 w1 w2
    {
        if (echo) bb->setName("DUP2");
        LoadInst* w2 = cast<LoadInst>( stack_top(bb) );
        LoadInst* w1 = cast<LoadInst>( stack_top(bb, One ) );
        incr_stack_index( bb, Two );
        replace_top( bb, w1, One );
        replace_top( bb, w2 );
        break;
    }
    case SWAP:  // w1 w2 -- w2 w1
    {
        if (echo) bb->setName("SWAP");
        LoadInst* w2 = cast<LoadInst>( stack_top( bb ) );
        LoadInst* w1 = cast<LoadInst>( stack_top( bb, One ) );
        replace_top( bb, w1 );
        replace_top( bb, w2, One );
        break;
    }
    case SWAP2: // w1 w2 w3 w4 -- w3 w4 w1 w2
    {
        if (echo) bb->setName("SWAP2");
        LoadInst* w4 = cast<LoadInst>( stack_top( bb ) );
        LoadInst* w3 = cast<LoadInst>( stack_top( bb, One ) );
        LoadInst* w2 = cast<LoadInst>( stack_top( bb, Two ) );
        LoadInst* w1 = cast<LoadInst>( stack_top( bb, Three ) );
        replace_top( bb, w2 );
        replace_top( bb, w1, One );
        replace_top( bb, w4, Two );
        replace_top( bb, w3, Three );
        break;
    }
    case OVER:  // w1 w2 -- w1 w2 w1
    {
        if (echo) bb->setName("OVER");
        LoadInst* w1 = cast<LoadInst>( stack_top( bb, One ) );
        push_value( bb, w1 );
        break;
    }
    case OVER2: // w1 w2 w3 w4 -- w1 w2 w3 w4 w1 w2
    {
        if (echo) bb->setName("OVER2");
        LoadInst* w2 = cast<LoadInst>( stack_top( bb, Two ) );
        LoadInst* w1 = cast<LoadInst>( stack_top( bb, Three ) );
        incr_stack_index( bb, Two );
        replace_top( bb, w2 );
        replace_top( bb, w1, One );
        break;
    }
    case ROT:   // w1 w2 w3 -- w2 w3 w1
    {
        if (echo) bb->setName("ROT");
        LoadInst* w3 = cast<LoadInst>( stack_top( bb ) );
        LoadInst* w2 = cast<LoadInst>( stack_top( bb, One ) );
        LoadInst* w1 = cast<LoadInst>( stack_top( bb, Two ) );
        replace_top( bb, w1 );
        replace_top( bb, w3, One );
        replace_top( bb, w2, Two );
        break;
    }
    case ROT2:  // w1 w2 w3 w4 w5 w6 -- w3 w4 w5 w6 w1 w2
    {
        if (echo) bb->setName("ROT2");
        LoadInst* w6 = cast<LoadInst>( stack_top( bb ) );
        LoadInst* w5 = cast<LoadInst>( stack_top( bb, One ) );
        LoadInst* w4 = cast<LoadInst>( stack_top( bb, Two ) );
        LoadInst* w3 = cast<LoadInst>( stack_top( bb, Three) );
        LoadInst* w2 = cast<LoadInst>( stack_top( bb, Four ) );
        LoadInst* w1 = cast<LoadInst>( stack_top( bb, Five ) );
        replace_top( bb, w2 );
        replace_top( bb, w1, One );
        replace_top( bb, w6, Two );
        replace_top( bb, w5, Three );
        replace_top( bb, w4, Four );
        replace_top( bb, w3, Five );
        break;
    }
    case RROT:  // w1 w2 w3 -- w3 w1 w2
    {
        if (echo) bb->setName("RROT2");
        LoadInst* w3 = cast<LoadInst>( stack_top( bb ) );
        LoadInst* w2 = cast<LoadInst>( stack_top( bb, One ) );
        LoadInst* w1 = cast<LoadInst>( stack_top( bb, Two ) );
        replace_top( bb, w2 );
        replace_top( bb, w1, One );
        replace_top( bb, w3, Two );
        break;
    }
    case RROT2: // w1 w2 w3 w4 w5 w6 -- w5 w6 w1 w2 w3 w4
    {
        if (echo) bb->setName("RROT2");
        LoadInst* w6 = cast<LoadInst>( stack_top( bb ) );
        LoadInst* w5 = cast<LoadInst>( stack_top( bb, One ) );
        LoadInst* w4 = cast<LoadInst>( stack_top( bb, Two ) );
        LoadInst* w3 = cast<LoadInst>( stack_top( bb, Three) );
        LoadInst* w2 = cast<LoadInst>( stack_top( bb, Four ) );
        LoadInst* w1 = cast<LoadInst>( stack_top( bb, Five ) );
        replace_top( bb, w4 );
        replace_top( bb, w3, One );
        replace_top( bb, w2, Two );
        replace_top( bb, w1, Three );
        replace_top( bb, w6, Four );
        replace_top( bb, w5, Five );
        break;
    }
    case TUCK:  // w1 w2 -- w2 w1 w2
    {
        if (echo) bb->setName("TUCK");
        LoadInst* w2 = cast<LoadInst>( stack_top( bb ) );
        LoadInst* w1 = cast<LoadInst>( stack_top( bb, One ) );
        incr_stack_index( bb );
        replace_top( bb, w2 );
        replace_top( bb, w1, One );
        replace_top( bb, w2, Two );
        break;
    }
    case TUCK2: // w1 w2 w3 w4 -- w3 w4 w1 w2 w3 w4
    {
        if (echo) bb->setName("TUCK2");
        LoadInst* w4 = cast<LoadInst>( stack_top( bb ) );
        LoadInst* w3 = cast<LoadInst>( stack_top( bb, One ) );
        LoadInst* w2 = cast<LoadInst>( stack_top( bb, Two ) );
        LoadInst* w1 = cast<LoadInst>( stack_top( bb, Three) );
        incr_stack_index( bb, Two );
        replace_top( bb, w4 );
        replace_top( bb, w3, One );
        replace_top( bb, w2, Two );
        replace_top( bb, w1, Three );
        replace_top( bb, w4, Four );
        replace_top( bb, w3, Five );
        break;
    }
    case ROLL:  // x0 x1 .. xn n -- x1 .. xn x0
    {
        /// THIS OEPRATOR IS OMITTED PURPOSEFULLY AND IS LEFT TO THE
        /// READER AS AN EXERCISE. THIS IS ONE OF THE MORE COMPLICATED
        /// OPERATORS. IF YOU CAN GET THIS ONE RIGHT, YOU COMPLETELY
        /// UNDERSTAND HOW BOTH LLVM AND STACKER WOR.
        /// HINT: LOOK AT PICK AND SELECT. ROLL IS SIMILAR.
        if (echo) bb->setName("ROLL");
        break;
    }
    case PICK:  // x0 ... Xn n -- x0 ... Xn x0
    {
        if (echo) bb->setName("PICK");
        LoadInst* n = cast<LoadInst>( stack_top( bb ) );
        BinaryOperator* addop =
            BinaryOperator::create( Instruction::Add, n, One );
        bb->getInstList().push_back( addop );
        LoadInst* x0 = cast<LoadInst>( stack_top( bb, addop ) );
        replace_top( bb, x0 );
        break;
    }
    case SELECT:        // m n X0..Xm Xm+1 .. Xn -- Xm
    {
        if (echo) bb->setName("SELECT");
        LoadInst* m = cast<LoadInst>( stack_top(bb) );
        LoadInst* n = cast<LoadInst>( stack_top(bb, One) );
        BinaryOperator* index =
            BinaryOperator::create( Instruction::Add, m, One );
        bb->getInstList().push_back( index );
        LoadInst* Xm = cast<LoadInst>( stack_top(bb, index ) );
        BinaryOperator* n_plus_1 =
            BinaryOperator::create( Instruction::Add, n, One );
        bb->getInstList().push_back( n_plus_1 );
        decr_stack_index( bb, n_plus_1 );
        replace_top( bb, Xm );
        break;
    }
    case MALLOC : // n -- p
    {
        if (echo) bb->setName("MALLOC");
        // Get the number of bytes to mallocate
        LoadInst* op1 = cast<LoadInst>( pop_integer(bb) );

        // Make sure its a UIntTy
        CastInst* caster = new CastInst( op1, Type::UIntTy );
        bb->getInstList().push_back( caster );

        // Allocate the bytes
        MallocInst* mi = new MallocInst( Type::SByteTy, caster );
        bb->getInstList().push_back( mi );

        // Push the pointer
        push_value( bb, mi );
        break;
    }
    case FREE :  // p --
    {
        if (echo) bb->setName("FREE");
        // Pop the value off the stack
        CastInst* ptr = cast<CastInst>( pop_string(bb) );

        // Free the memory
        FreeInst* fi = new FreeInst( ptr );
        bb->getInstList().push_back( fi );

        break;
    }
    case GET : // p w1 -- p w2
    {
        if (echo) bb->setName("GET");
        // Get the character index
        LoadInst* op1 = cast<LoadInst>( stack_top(bb) );
        CastInst* chr_idx = new CastInst( op1, Type::LongTy );
        bb->getInstList().push_back( chr_idx );

        // Get the String pointer
        CastInst* ptr = cast<CastInst>( stack_top_string(bb,One) );

        // Get address of op1'th element of the string
        std::vector<Value*> indexVec;
        indexVec.push_back( chr_idx );
        GetElementPtrInst* gep = new GetElementPtrInst( ptr, indexVec );
        bb->getInstList().push_back( gep );

        // Get the value and push it
        LoadInst* loader = new LoadInst( gep );
        bb->getInstList().push_back( loader );
        CastInst* caster = new CastInst( loader, Type::IntTy );
        bb->getInstList().push_back( caster );

        // Push the result back on stack
        replace_top( bb, caster );

        break;
    }
    case PUT : // p w2 w1  -- p
    {
        if (echo) bb->setName("PUT");

        // Get the value to put
        LoadInst* w1 = cast<LoadInst>( pop_integer(bb) );

        // Get the character index
        LoadInst* w2 = cast<LoadInst>( pop_integer(bb) );
        CastInst* chr_idx = new CastInst( w2, Type::LongTy );
        bb->getInstList().push_back( chr_idx );

        // Get the String pointer
        CastInst* ptr = cast<CastInst>( stack_top_string(bb) );

        // Get address of op2'th element of the string
        std::vector<Value*> indexVec;
        indexVec.push_back( chr_idx );
        GetElementPtrInst* gep = new GetElementPtrInst( ptr, indexVec );
        bb->getInstList().push_back( gep );

        // Cast the value and put it
        CastInst* caster = new CastInst( w1, Type::SByteTy );
        bb->getInstList().push_back( caster );
        StoreInst* storer = new StoreInst( caster, gep );
        bb->getInstList().push_back( storer );

        break;
    }
    case RECURSE :
    {
        if (echo) bb->setName("RECURSE");
        std::vector<Value*> params;
        CallInst* call_inst = new CallInst( TheFunction, params );
        bb->getInstList().push_back( call_inst );
        break;
    }
    case RETURN :
    {
        if (echo) bb->setName("RETURN");
        bb->getInstList().push_back( new ReturnInst() );
        break;
    }
    case EXIT :
    {
        if (echo) bb->setName("EXIT");
        // Get the result value
        LoadInst* op1 = cast<LoadInst>(pop_integer(bb));

        // Cast down to an integer
        CastInst* caster = new CastInst( op1, Type::IntTy );
        bb->getInstList().push_back( caster );

        // Call exit(3)
        std::vector<Value*> params;
        params.push_back(caster);
        CallInst* call_inst = new CallInst( TheExit, params );
        bb->getInstList().push_back( call_inst );
        break;
    }
    case TAB :
    {
        if (echo) bb->setName("TAB");
        // Get the format string for a character
        std::vector<Value*> indexVec;
        indexVec.push_back( Zero );
        indexVec.push_back( Zero );
        GetElementPtrInst* format_gep =
            new GetElementPtrInst( ChrFormat, indexVec );
        bb->getInstList().push_back( format_gep );

        // Get the character to print (a tab)
        ConstantSInt* newline = ConstantSInt::get(Type::IntTy,
            static_cast<int>('\t'));

        // Call printf
        std::vector<Value*> args;
        args.push_back( format_gep );
        args.push_back( newline );
        bb->getInstList().push_back( new CallInst( ThePrintf, args ) );
        break;
    }
    case SPACE :
    {
        if (echo) bb->setName("SPACE");
        // Get the format string for a character
        std::vector<Value*> indexVec;
        indexVec.push_back( Zero );
        indexVec.push_back( Zero );
        GetElementPtrInst* format_gep =
            new GetElementPtrInst( ChrFormat, indexVec );
        bb->getInstList().push_back( format_gep );

        // Get the character to print (a space)
        ConstantSInt* newline = ConstantSInt::get(Type::IntTy,
            static_cast<int>(' '));

        // Call printf
        std::vector<Value*> args;
        args.push_back( format_gep );
        args.push_back( newline );
        bb->getInstList().push_back( new CallInst( ThePrintf, args ) );
        break;
    }
    case CR :
    {
        if (echo) bb->setName("CR");
        // Get the format string for a character
        std::vector<Value*> indexVec;
        indexVec.push_back( Zero );
        indexVec.push_back( Zero );
        GetElementPtrInst* format_gep =
            new GetElementPtrInst( ChrFormat, indexVec );
        bb->getInstList().push_back( format_gep );

        // Get the character to print (a newline)
        ConstantSInt* newline = ConstantSInt::get(Type::IntTy,
            static_cast<int>('\n'));

        // Call printf
        std::vector<Value*> args;
        args.push_back( format_gep );
        args.push_back( newline );
        bb->getInstList().push_back( new CallInst( ThePrintf, args ) );
        break;
    }
    case IN_STR :
    {
        if (echo) bb->setName("IN_STR");
        // Make room for the value result
        incr_stack_index(bb);
        GetElementPtrInst* gep_value =
            cast<GetElementPtrInst>(get_stack_pointer(bb));
        CastInst* caster =
            new CastInst( gep_value, PointerType::get( Type::SByteTy ) );

        // Make room for the count result
        incr_stack_index(bb);
        GetElementPtrInst* gep_count =
            cast<GetElementPtrInst>(get_stack_pointer(bb));

        // Call scanf(3)
        std::vector<Value*> args;
        args.push_back( InStrFormat );
        args.push_back( caster );
        CallInst* scanf = new CallInst( TheScanf, args );
        bb->getInstList().push_back( scanf );

        // Store the result
        bb->getInstList().push_back( new StoreInst( scanf, gep_count ) );
        break;
    }
    case IN_NUM :
    {
        if (echo) bb->setName("IN_NUM");
        // Make room for the value result
        incr_stack_index(bb);
        GetElementPtrInst* gep_value =
            cast<GetElementPtrInst>(get_stack_pointer(bb));

        // Make room for the count result
        incr_stack_index(bb);
        GetElementPtrInst* gep_count =
            cast<GetElementPtrInst>(get_stack_pointer(bb));

        // Call scanf(3)
        std::vector<Value*> args;
        args.push_back( InStrFormat );
        args.push_back( gep_value );
        CallInst* scanf = new CallInst( TheScanf, args );
        bb->getInstList().push_back( scanf );

        // Store the result
        bb->getInstList().push_back( new StoreInst( scanf, gep_count ) );
        break;
    }
    case IN_CHAR :
    {
        if (echo) bb->setName("IN_CHAR");
        // Make room for the value result
        incr_stack_index(bb);
        GetElementPtrInst* gep_value =
            cast<GetElementPtrInst>(get_stack_pointer(bb));

        // Make room for the count result
        incr_stack_index(bb);
        GetElementPtrInst* gep_count =
            cast<GetElementPtrInst>(get_stack_pointer(bb));

        // Call scanf(3)
        std::vector<Value*> args;
        args.push_back( InChrFormat );
        args.push_back( gep_value );
        CallInst* scanf = new CallInst( TheScanf, args );
        bb->getInstList().push_back( scanf );

        // Store the result
        bb->getInstList().push_back( new StoreInst( scanf, gep_count ) );
        break;
    }
    case OUT_STR :
    {
        if (echo) bb->setName("OUT_STR");
        LoadInst* op1 = cast<LoadInst>(stack_top(bb));

        // Get the address of the format string
        std::vector<Value*> indexVec;
        indexVec.push_back( Zero );
        indexVec.push_back( Zero );
        GetElementPtrInst* format_gep =
            new GetElementPtrInst( StrFormat, indexVec );
        bb->getInstList().push_back( format_gep );
        // Build function call arguments
        std::vector<Value*> args;
        args.push_back( format_gep );
        args.push_back( op1 );
        // Call printf
        bb->getInstList().push_back( new CallInst( ThePrintf, args ) );
        break;
    }
    case OUT_NUM :
    {
        if (echo) bb->setName("OUT_NUM");
        // Pop the numeric operand off the stack
        LoadInst* op1 = cast<LoadInst>(stack_top(bb));

        // Get the address of the format string
        std::vector<Value*> indexVec;
        indexVec.push_back( Zero );
        indexVec.push_back( Zero );
        GetElementPtrInst* format_gep =
            new GetElementPtrInst( NumFormat, indexVec );
        bb->getInstList().push_back( format_gep );

        // Build function call arguments
        std::vector<Value*> args;
        args.push_back( format_gep );
        args.push_back( op1 );

        // Call printf
        bb->getInstList().push_back( new CallInst( ThePrintf, args ) );
        break;
    }
    case OUT_CHAR :
    {
        if (echo) bb->setName("OUT_CHAR");
        // Pop the character operand off the stack
        LoadInst* op1 = cast<LoadInst>(stack_top(bb));

        // Get the address of the format string
        std::vector<Value*> indexVec;
        indexVec.push_back( Zero );
        indexVec.push_back( Zero );
        GetElementPtrInst* format_gep =
            new GetElementPtrInst( ChrFormat, indexVec );
        bb->getInstList().push_back( format_gep );

        // Build function call arguments
        std::vector<Value*> args;
        args.push_back( format_gep );
        args.push_back( op1 );
        // Call printf
        bb->getInstList().push_back( new CallInst( ThePrintf, args ) );
        break;
    }
    default :
    {
        ThrowException(std::string("Compiler Error: Unhandled token #"));
    }
    }

    // Return the basic block
    return bb;
}