llvm.org GIT mirror llvm / 4630e4d
the stacker doc is way out of date. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@54631 91177308-0d34-0410-b5e6-96231b3b80d8 Chris Lattner 11 years ago
3 changed file(s) with 1 addition(s) and 1434 deletion(s). Raw diff Collapse all Expand all
12901290

This directory contains projects that are not strictly part of LLVM but are

12911291 shipped with LLVM. This is also the directory where you should create your own
12921292 LLVM-based projects. See llvm/projects/sample for an example of how
1293 to set up your own project. See llvm/projects/Stacker for a fully
1294 functional example of a compiler front end.

1293 to set up your own project.

12951294
12961295
12971296
+0
-1428
docs/Stacker.html less more
None
1 "http://www.w3.org/TR/html4/strict.dtd">
2
3
4 Stacker: An Example Of Using LLVM
5
6
7
8
9
Stacker: An Example Of Using LLVM
10
11
12
  • Abstract
  • 13
  • Introduction
  • 14
  • Lessons I Learned About LLVM
  • 15
    16
  • Everything's a Value!
  • 17
  • Terminate Those Blocks!
  • 18
  • Concrete Blocks
  • 19
  • push_back Is Your Friend
  • 20
  • The Wily GetElementPtrInst
  • 21
  • Getting Linkage Types Right
  • 22
  • Constants Are Easier Than That!
  • 23
    24
  • The Stacker Lexicon
  • 25
    26
  • The Stack
  • 27
  • Punctuation
  • 28
  • Comments
  • 29
  • Literals
  • 30
  • Words
  • 31
  • Standard Style
  • 32
  • Built-Ins
  • 33
    34
  • Prime: A Complete Example
  • 35
  • Internal Code Details
  • 36
    37
  • The Directory Structure
  • 38
  • The Lexer
  • 39
  • The Parser
  • 40
  • The Compiler
  • 41
  • The Runtime
  • 42
  • Compiler Driver
  • 43
  • Test Programs
  • 44
  • Exercise
  • 45
  • Things Remaining To Be Done
  • 46
    47
    48
    49
    50

    Written by Reid Spencer

    51
    52
    53
    54
    55
    56

    This document is another way to learn about LLVM. Unlike the

    57 LLVM Reference Manual or
    58 LLVM Programmer's Manual, here we learn
    59 about LLVM through the experience of creating a simple programming language
    60 named Stacker. Stacker was invented specifically as a demonstration of
    61 LLVM. The emphasis in this document is not on describing the
    62 intricacies of LLVM itself but on how to use it to build your own
    63 compiler system.

    64
    65
    66
    67
    68

    Amongst other things, LLVM is a platform for compiler writers.

    69 Because of its exceptionally clean and small IR (intermediate
    70 representation), compiler writing with LLVM is much easier than with
    71 other system. As proof, I wrote the entire compiler (language definition,
    72 lexer, parser, code generator, etc.) in about four days!
    73 That's important to know because it shows how quickly you can get a new
    74 language running when using LLVM. Furthermore, this was the first
    75 language the author ever created using LLVM. The learning curve is
    76 included in that four days.

    77

    The language described here, Stacker, is Forth-like. Programs

    78 are simple collections of word definitions, and the only thing definitions
    79 can do is manipulate a stack or generate I/O. Stacker is not a "real"
    80 programming language; it's very simple. Although it is computationally
    81 complete, you wouldn't use it for your next big project. However,
    82 the fact that it is complete, it's simple, and it doesn't have
    83 a C-like syntax make it useful for demonstration purposes. It shows
    84 that LLVM could be applied to a wide variety of languages.

    85

    The basic notions behind stacker is very simple. There's a stack of

    86 integers (or character pointers) that the program manipulates. Pretty
    87 much the only thing the program can do is manipulate the stack and do
    88 some limited I/O operations. The language provides you with several
    89 built-in words that manipulate the stack in interesting ways. To get
    90 your feet wet, here's how you write the traditional "Hello, World"
    91 program in Stacker:

    92

    : hello_world "Hello, World!" >s DROP CR ;

    93 : MAIN hello_world ;

    94

    This has two "definitions" (Stacker manipulates words, not

    95 functions and words have definitions): MAIN and
    96 hello_world. The MAIN definition is standard; it
    97 tells Stacker where to start. Here, MAIN is defined to
    98 simply invoke the word hello_world. The
    99 hello_world definition tells stacker to push the
    100 "Hello, World!" string on to the stack, print it out
    101 (>s), pop it off the stack (DROP), and
    102 finally print a carriage return (CR). Although
    103 hello_world uses the stack, its net effect is null. Well
    104 written Stacker definitions have that characteristic.

    105

    Exercise for the reader: how could you make this a one line program?

    106
    107
    108
    Lessons I Learned About LLVM
    109
    110

    Stacker was written for two purposes:

    111
    112
  • to get the author over the learning curve, and
  • 113
  • to provide a simple example of how to write a compiler using LLVM.
  • 114
    115

    During the development of Stacker, many lessons about LLVM were

    116 learned. Those lessons are described in the following subsections.

    117
    118
    119
    Everything's a Value!
    120
    121

    Although I knew that LLVM uses a Single Static Assignment (SSA) format,

    122 it wasn't obvious to me how prevalent this idea was in LLVM until I really
    123 started using it. Reading the
    124 Programmer's Manual and Language Reference,
    125 I noted that most of the important LLVM IR (Intermediate Representation) C++
    126 classes were derived from the Value class. The full power of that simple
    127 design only became fully understood once I started constructing executable
    128 expressions for Stacker.

    129
    130

    This really makes your programming go faster. Think about compiling code

    131 for the following C/C++ expression: (a|b)*((x+1)/(y+1)). Assuming
    132 the values are on the stack in the order a, b, x, y, this could be
    133 expressed in stacker as: 1 + SWAP 1 + / ROT2 OR *.
    134 You could write a function using LLVM that computes this expression like
    135 this:

    136
    137
    
                      
                    
    138 Value*
    139 expression(BasicBlock* bb, Value* a, Value* b, Value* x, Value* y )
    140 {
    141 ConstantInt* one = ConstantInt::get(Type::IntTy, 1);
    142 BinaryOperator* or1 = BinaryOperator::createOr(a, b, "", bb);
    143 BinaryOperator* add1 = BinaryOperator::createAdd(x, one, "", bb);
    144 BinaryOperator* add2 = BinaryOperator::createAdd(y, one, "", bb);
    145 BinaryOperator* div1 = BinaryOperator::createDiv(add1, add2, "", bb);
    146 BinaryOperator* mult1 = BinaryOperator::createMul(or1, div1, "", bb);
    147 return mult1;
    148 }
    149
    150
    151

    "Okay, big deal," you say? It is a big deal. Here's why. Note that I didn't

    152 have to tell this function which kinds of Values are being passed in. They could be
    153 Instructions, Constants, GlobalVariables, or
    154 any of the other subclasses of Value that LLVM supports.
    155 Furthermore, if you specify Values that are incorrect for this sequence of
    156 operations, LLVM will either notice right away (at compilation time) or the LLVM
    157 Verifier will pick up the inconsistency when the compiler runs. In either case
    158 LLVM prevents you from making a type error that gets passed through to the
    159 generated program. This really helps you write a compiler that
    160 always generates correct code!

    161

    The second point is that we don't have to worry about branching, registers,

    162 stack variables, saving partial results, etc. The instructions we create
    163 are the values we use. Note that all that was created in the above
    164 code is a Constant value and five operators. Each of the instructions is
    165 the resulting value of that instruction. This saves a lot of time.

    166

    The lesson is this: SSA form is very powerful: there is no difference

    167 between a value and the instruction that created it. This is fully
    168 enforced by the LLVM IR. Use it to your best advantage.

    169
    170
    171
    Terminate Those Blocks!
    172
    173

    I had to learn about terminating blocks the hard way: using the debugger

    174 to figure out what the LLVM verifier was trying to tell me and begging for
    175 help on the LLVMdev mailing list. I hope you avoid this experience.

    176

    Emblazon this rule in your mind:

    177
    178
  • All BasicBlocks in your compiler must be
  • 179 terminated with a terminating instruction (branch, return, etc.).
    180
    181
    182

    Terminating instructions are a semantic requirement of the LLVM IR. There

    183 is no facility for implicitly chaining together blocks placed into a function
    184 in the order they occur. Indeed, in the general case, blocks will not be
    185 added to the function in the order of execution because of the recursive
    186 way compilers are written.

    187

    Furthermore, if you don't terminate your blocks, your compiler code will

    188 compile just fine. You won't find out about the problem until you're running
    189 the compiler and the module you just created fails on the LLVM Verifier.

    190
    191
    192
    Concrete Blocks
    193
    194

    After a little initial fumbling around, I quickly caught on to how blocks

    195 should be constructed. In general, here's what I learned:
    196
    197
  • Create your blocks early. While writing your compiler, you
  • 198 will encounter several situations where you know apriori that you will
    199 need several blocks. For example, if-then-else, switch, while, and for
    200 statements in C/C++ all need multiple blocks for expression in LLVM.
    201 The rule is, create them early.
    202
  • Terminate your blocks early. This just reduces the chances
  • 203 that you forget to terminate your blocks which is required (go
    204 here for more).
    205
  • Use getTerminator() for instruction insertion. I noticed early on
  • 206 that many of the constructors for the Instruction classes take an optional
    207 insert_before argument. At first, I thought this was a mistake
    208 because clearly the normal mode of inserting instructions would be one at
    209 a time after some other instruction, not before. However,
    210 if you hold on to your terminating instruction (or use the handy dandy
    211 getTerminator() method on a BasicBlock), it can
    212 always be used as the insert_before argument to your instruction
    213 constructors. This causes the instruction to automatically be inserted in
    214 the RightPlace™ place, just before the terminating instruction. The
    215 nice thing about this design is that you can pass blocks around and insert
    216 new instructions into them without ever knowing what instructions came
    217 before. This makes for some very clean compiler design.
    218
    219

    The foregoing is such an important principal, its worth making an idiom:

    220
    
                      
                    
    221 BasicBlock* bb = BasicBlock::Create();
    222 bb->getInstList().push_back( BranchInst::Create( ... ) );
    223 new Instruction(..., bb->getTerminator() );
    224
    225

    To make this clear, consider the typical if-then-else statement

    226 (see StackerCompiler::handle_if() method). We can set this up
    227 in a single function using LLVM in the following way:

    228
    
                      
                    
    229 using namespace llvm;
    230 BasicBlock*
    231 MyCompiler::handle_if( BasicBlock* bb, ICmpInst* condition )
    232 {
    233 // Create the blocks to contain code in the structure of if/then/else
    234 BasicBlock* then_bb = BasicBlock::Create();
    235 BasicBlock* else_bb = BasicBlock::Create();
    236 BasicBlock* exit_bb = BasicBlock::Create();
    237
    238 // Insert the branch instruction for the "if"
    239 bb->getInstList().push_back( BranchInst::Create( then_bb, else_bb, condition ) );
    240
    241 // Set up the terminating instructions
    242 then->getInstList().push_back( BranchInst::Create( exit_bb ) );
    243 else->getInstList().push_back( BranchInst::Create( exit_bb ) );
    244
    245 // Fill in the then part .. details excised for brevity
    246 this->fill_in( then_bb );
    247
    248 // Fill in the else part .. details excised for brevity
    249 this->fill_in( else_bb );
    250
    251 // Return a block to the caller that can be filled in with the code
    252 // that follows the if/then/else construct.
    253 return exit_bb;
    254 }
    255
    256

    Presumably in the foregoing, the calls to the "fill_in" method would add

    257 the instructions for the "then" and "else" parts. They would use the third part
    258 of the idiom almost exclusively (inserting new instructions before the
    259 terminator). Furthermore, they could even recurse back to handle_if
    260 should they encounter another if/then/else statement, and it will just work.

    261

    Note how cleanly this all works out. In particular, the push_back methods on

    262 the BasicBlock's instruction list. These are lists of type
    263 Instruction (which is also of type Value). To create
    264 the "if" branch we merely instantiate a BranchInst that takes as
    265 arguments the blocks to branch to and the condition to branch on. The
    266 BasicBlock objects act like branch labels! This new
    267 BranchInst terminates the BasicBlock provided
    268 as an argument. To give the caller a way to keep inserting after calling
    269 handle_if, we create an exit_bb block which is
    270 returned
    271 to the caller. Note that the exit_bb block is used as the
    272 terminator for both the then_bb and the else_bb
    273 blocks. This guarantees that no matter what else handle_if
    274 or fill_in does, they end up at the exit_bb block.
    275

    276
    277
    278
    push_back Is Your Friend
    279
    280

    281 One of the first things I noticed is the frequent use of the "push_back"
    282 method on the various lists. This is so common that it is worth mentioning.
    283 The "push_back" inserts a value into an STL list, vector, array, etc. at the
    284 end. The method might have also been named "insert_tail" or "append".
    285 Although I've used STL quite frequently, my use of push_back wasn't very
    286 high in other programs. In LLVM, you'll use it all the time.
    287

    288
    289
    290
    The Wily GetElementPtrInst
    291
    292

    293 It took a little getting used to and several rounds of postings to the LLVM
    294 mailing list to wrap my head around this instruction correctly. Even though I had
    295 read the Language Reference and Programmer's Manual a couple times each, I still
    296 missed a few very key points:
    297

    298
    299
  • GetElementPtrInst gives you back a Value for the last thing indexed.
  • 300
  • All global variables in LLVM are pointers.
  • 301
  • Pointers must also be dereferenced with the GetElementPtrInst
  • 302 instruction.
    303
    304

    This means that when you look up an element in the global variable (assuming

    305 it's a struct or array), you must deference the pointer first! For many
    306 things, this leads to the idiom:
    307

    308
    
                      
                    
    309 std::vector<Value*> index_vector;
    310 index_vector.push_back( ConstantInt::get( Type::LongTy, 0 );
    311 // ... push other indices ...
    312 GetElementPtrInst* gep = GetElementPtrInst::Create( ptr, index_vector );
    313
    314

    For example, suppose we have a global variable whose type is [24 x int]. The

    315 variable itself represents a pointer to that array. To subscript the
    316 array, we need two indices, not just one. The first index (0) dereferences the
    317 pointer. The second index subscripts the array. If you're a "C" programmer, this
    318 will run against your grain because you'll naturally think of the global array
    319 variable and the address of its first element as the same. That tripped me up
    320 for a while until I realized that they really do differ .. by type.
    321 Remember that LLVM is strongly typed. Everything has a type.
    322 The "type" of the global variable is [24 x int]*. That is, it's
    323 a pointer to an array of 24 ints. When you dereference that global variable with
    324 a single (0) index, you now have a "[24 x int]" type. Although
    325 the pointer value of the dereferenced global and the address of the zero'th element
    326 in the array will be the same, they differ in their type. The zero'th element has
    327 type "int" while the pointer value has type "[24 x int]".

    328

    Get this one aspect of LLVM right in your head, and you'll save yourself

    329 a lot of compiler writing headaches down the road.

    330
    331
    332
    Getting Linkage Types Right
    333
    334

    Linkage types in LLVM can be a little confusing, especially if your compiler

    335 writing mind has affixed firm concepts to particular words like "weak",
    336 "external", "global", "linkonce", etc. LLVM does not use the precise
    337 definitions of, say, ELF or GCC, even though they share common terms. To be fair,
    338 the concepts are related and similar but not precisely the same. This can lead
    339 you to think you know what a linkage type represents but in fact it is slightly
    340 different. I recommend you read the
    341 Language Reference on this topic very
    342 carefully. Then, read it again.

    343

    Here are some handy tips that I discovered along the way:

    344
    345
  • Uninitialized means external. That is, the symbol is declared in the current
  • 346 module and can be used by that module, but it is not defined by that module.
    347
  • Setting an initializer changes a global' linkage type. Setting an
  • 348 initializer changes a global's linkage type from whatever it was to a normal,
    349 defined global (not external). You'll need to call the setLinkage() method to
    350 reset it if you specify the initializer after the GlobalValue has been constructed.
    351 This is important for LinkOnce and Weak linkage types.
    352
  • Appending linkage can keep track of things. Appending linkage can
  • 353 be used to keep track of compilation information at runtime. It could be used,
    354 for example, to build a full table of all the C++ virtual tables or hold the
    355 C++ RTTI data, or whatever. Appending linkage can only be applied to arrays.
    356 All arrays with the same name in each module are concatenated together at link
    357 time.
    358
    359
    360
    361
    Constants Are Easier Than That!
    362
    363

    364 Constants in LLVM took a little getting used to until I discovered a few utility
    365 functions in the LLVM IR that make things easier. Here's what I learned:

    366
    367
  • Constants are Values like anything else and can be operands of instructions
  • 368
  • Integer constants, frequently needed, can be created using the static "get"
  • 369 methods of the ConstantInt class. The nice thing about these is that you can
    370 "get" any kind of integer quickly.
    371
  • There's a special method on Constant class which allows you to get the null
  • 372 constant for any type. This is really handy for initializing large
    373 arrays or structures, etc.
    374
    375
    376
    377
    378

    This section describes the Stacker language

    379
    The Stack
    380
    381

    Stacker definitions define what they do to the global stack. Before

    382 proceeding, a few words about the stack are in order. The stack is simply
    383 a global array of 32-bit integers or pointers. A global index keeps track
    384 of the location of the top of the stack. All of this is hidden from the
    385 programmer, but it needs to be noted because it is the foundation of the
    386 conceptual programming model for Stacker. When you write a definition,
    387 you are, essentially, saying how you want that definition to manipulate
    388 the global stack.

    389

    Manipulating the stack can be quite hazardous. There is no distinction

    390 given and no checking for the various types of values that can be placed
    391 on the stack. Automatic coercion between types is performed. In many
    392 cases, this is useful. For example, a boolean value placed on the stack
    393 can be interpreted as an integer with good results. However, using a
    394 word that interprets that boolean value as a pointer to a string to
    395 print out will almost always yield a crash. Stacker simply leaves it
    396 to the programmer to get it right without any interference or hindering
    397 on interpretation of the stack values. You've been warned. :)

    398
    399
    400
    Punctuation
    401
    402

    Punctuation in Stacker is very simple. The colon and semi-colon

    403 characters are used to introduce and terminate a definition
    404 (respectively). Except for FORWARD declarations, definitions
    405 are all you can specify in Stacker. Definitions are read left to right.
    406 Immediately after the colon comes the name of the word being defined.
    407 The remaining words in the definition specify what the word does. The definition
    408 is terminated by a semi-colon.

    409

    So, your typical definition will have the form:

    410
    : name ... ;
    411

    The name is up to you but it must start with a letter and contain

    412 only letters, numbers, and underscore. Names are case sensitive and must not be
    413 the same as the name of a built-in word. The ... is replaced by
    414 the stack manipulating words that you wish to define name as.

    415
    416
    417
    Comments
    418
    419

    Stacker supports two types of comments. A hash mark (#) starts a comment

    420 that extends to the end of the line. It is identical to the kind of comments
    421 commonly used in shell scripts. A pair of parentheses also surround a comment.
    422 In both cases, the content of the comment is ignored by the Stacker compiler. The
    423 following does nothing in Stacker.
    424

    425
    
    
                      
                    
    426 # This is a comment to end of line
    427 ( This is an enclosed comment )
    428
    429

    See the example program to see comments in use in

    430 a real program.

    431
    432
    433
    Literals
    434
    435

    There are three kinds of literal values in Stacker: Integers, Strings,

    436 and Booleans. In each case, the stack operation is to simply push the
    437 value on to the stack. So, for example:
    438 42 " is the answer." TRUE
    439 will push three values on to the stack: the integer 42, the
    440 string " is the answer.", and the boolean TRUE.

    441
    442
    443
    Words
    444
    445

    Each definition in Stacker is composed of a set of words. Words are

    446 read and executed in order from left to right. There is very little
    447 checking in Stacker to make sure you're doing the right thing with
    448 the stack. It is assumed that the programmer knows how the stack
    449 transformation he applies will affect the program.

    450

    Words in a definition come in two flavors: built-in and programmer

    451 defined. Simply mentioning the name of a previously defined or declared
    452 programmer-defined word causes that word's stack actions to be invoked. It
    453 is somewhat like a function call in other languages. The built-in
    454 words have various effects, described below.

    455

    Sometimes you need to call a word before it is defined. For this, you can

    456 use the FORWARD declaration. It looks like this:

    457

    FORWARD name ;

    458

    This simply states to Stacker that "name" is the name of a definition

    459 that is defined elsewhere. Generally it means the definition can be found
    460 "forward" in the file. But, it doesn't have to be in the current compilation
    461 unit. Anything declared with FORWARD is an external symbol for
    462 linking.

    463
    464
    465
    Standard Style
    466
    467

    TODO

    468
    469
    470
    Built In Words
    471
    472

    The built-in words of the Stacker language are put in several groups

    473 depending on what they do. The groups are as follows:

    474
    475
  • Logical: These words provide the logical operations for
  • 476 comparing stack operands.
    The words are: < > <= >=
    477 = <> true false.
    478
  • Bitwise: These words perform bitwise computations on
  • 479 their operands.
    The words are: << >> XOR AND NOT
    480
  • Arithmetic: These words perform arithmetic computations on
  • 481 their operands.
    The words are: ABS NEG + - * / MOD */ ++ -- MIN MAX
    482
  • StackThese words manipulate the stack directly by moving
  • 483 its elements around.
    The words are: DROP DROP2 NIP NIP2 DUP DUP2
    484 SWAP SWAP2 OVER OVER2 ROT ROT2 RROT RROT2 TUCK TUCK2 PICK SELECT ROLL
    485
  • MemoryThese words allocate, free, and manipulate memory
  • 486 areas outside the stack.
    The words are: MALLOC FREE GET PUT
    487
  • Control: These words alter the normal left to right flow
  • 488 of execution.
    The words are: IF ELSE ENDIF WHILE END RETURN EXIT RECURSE
    489
  • I/O: These words perform output on the standard output
  • 490 and input on the standard input. No other I/O is possible in Stacker.
    491
    The words are: SPACE TAB CR >s >d >c <s <d <c.
    492
    493

    While you may be familiar with many of these operations from other

    494 programming languages, a careful review of their semantics is important
    495 for correct programming in Stacker. Of most importance is the effect
    496 that each of these built-in words has on the global stack. The effect is
    497 not always intuitive. To better describe the effects, we'll borrow from Forth the idiom of
    498 describing the effect on the stack with:

    499

    BEFORE -- AFTER

    500

    That is, to the left of the -- is a representation of the stack before

    501 the operation. To the right of the -- is a representation of the stack
    502 after the operation. In the table below that describes the operation of
    503 each of the built in words, we will denote the elements of the stack
    504 using the following construction:

    505
    506
  • b - a boolean truth value
  • 507
  • w - a normal integer valued word.
  • 508
  • s - a pointer to a string value
  • 509
  • p - a pointer to a malloc'd memory block
  • 510
    511
    512
    513
    514
    Definition Of Operation Of Built In Words
    515
    LOGICAL OPERATIONS
    516
    517 Word
    518 Name
    519 Operation
    520 Description
    521
    522
    523 <
    524 LT
    525 w1 w2 -- b
    526 Two values (w1 and w2) are popped off the stack and
    527 compared. If w1 is less than w2, TRUE is pushed back on
    528 the stack, otherwise FALSE is pushed back on the stack.
    529
    530
    >
    531 GT
    532 w1 w2 -- b
    533 Two values (w1 and w2) are popped off the stack and
    534 compared. If w1 is greater than w2, TRUE is pushed back on
    535 the stack, otherwise FALSE is pushed back on the stack.
    536
    537
    >=
    538 GE
    539 w1 w2 -- b
    540 Two values (w1 and w2) are popped off the stack and
    541 compared. If w1 is greater than or equal to w2, TRUE is
    542 pushed back on the stack, otherwise FALSE is pushed back
    543 on the stack.
    544
    545
    <=
    546 LE
    547 w1 w2 -- b
    548 Two values (w1 and w2) are popped off the stack and
    549 compared. If w1 is less than or equal to w2, TRUE is
    550 pushed back on the stack, otherwise FALSE is pushed back
    551 on the stack.
    552
    553
    =
    554 EQ
    555 w1 w2 -- b
    556 Two values (w1 and w2) are popped off the stack and
    557 compared. If w1 is equal to w2, TRUE is
    558 pushed back on the stack, otherwise FALSE is pushed back
    559
    560
    561
    <>
    562 NE
    563 w1 w2 -- b
    564 Two values (w1 and w2) are popped off the stack and
    565 compared. If w1 is equal to w2, TRUE is
    566 pushed back on the stack, otherwise FALSE is pushed back
    567
    568
    569
    FALSE
    570 FALSE
    571 -- b
    572 The boolean value FALSE (0) is pushed on to the stack.
    573
    574
    TRUE
    575 TRUE
    576 -- b
    577 The boolean value TRUE (-1) is pushed on to the stack.
    578
    579
    BITWISE OPERATORS
    580
    581 Word
    582 Name
    583 Operation
    584 Description
    585
    586
    <<
    587 SHL
    588 w1 w2 -- w1<<w2
    589 Two values (w1 and w2) are popped off the stack. The w2
    590 operand is shifted left by the number of bits given by the
    591 w1 operand. The result is pushed back to the stack.
    592
    593
    >>
    594 SHR
    595 w1 w2 -- w1>>w2
    596 Two values (w1 and w2) are popped off the stack. The w2
    597 operand is shifted right by the number of bits given by the
    598 w1 operand. The result is pushed back to the stack.
    599
    600
    OR
    601 OR
    602 w1 w2 -- w2|w1
    603 Two values (w1 and w2) are popped off the stack. The values
    604 are bitwise OR'd together and pushed back on the stack. This is
    605 not a logical OR. The sequence 1 2 OR yields 3 not 1.
    606
    607
    AND
    608 AND
    609 w1 w2 -- w2&w1
    610 Two values (w1 and w2) are popped off the stack. The values
    611 are bitwise AND'd together and pushed back on the stack. This is
    612 not a logical AND. The sequence 1 2 AND yields 0 not 1.
    613
    614
    XOR
    615 XOR
    616 w1 w2 -- w2^w1
    617 Two values (w1 and w2) are popped off the stack. The values
    618 are bitwise exclusive OR'd together and pushed back on the stack.
    619 For example, The sequence 1 3 XOR yields 2.
    620
    621
    ARITHMETIC OPERATORS
    622
    623 Word
    624 Name
    625 Operation
    626 Description
    627
    628
    ABS
    629 ABS
    630 w -- |w|
    631 One value s popped off the stack; its absolute value is computed
    632 and then pushed on to the stack. If w1 is -1 then w2 is 1. If w1 is
    633 1 then w2 is also 1.
    634
    635
    NEG
    636 NEG
    637 w -- -w
    638 One value is popped off the stack which is negated and then
    639 pushed back on to the stack. If w1 is -1 then w2 is 1. If w1 is
    640 1 then w2 is -1.
    641
    642
    +
    643 ADD
    644 w1 w2 -- w2+w1
    645 Two values are popped off the stack. Their sum is pushed back
    646 on to the stack
    647
    648
    -
    649 SUB
    650 w1 w2 -- w2-w1
    651 Two values are popped off the stack. Their difference is pushed back
    652 on to the stack
    653
    654
    *
    655 MUL
    656 w1 w2 -- w2*w1
    657 Two values are popped off the stack. Their product is pushed back
    658 on to the stack
    659
    660
    /
    661 DIV
    662 w1 w2 -- w2/w1
    663 Two values are popped off the stack. Their quotient is pushed back
    664 on to the stack
    665
    666
    MOD
    667 MOD
    668 w1 w2 -- w2%w1
    669 Two values are popped off the stack. Their remainder after division
    670 of w1 by w2 is pushed back on to the stack
    671
    672
    */
    673 STAR_SLAH
    674 w1 w2 w3 -- (w3*w2)/w1
    675 Three values are popped off the stack. The product of w1 and w2 is
    676 divided by w3. The result is pushed back on to the stack.
    677
    678
    ++
    679 INCR
    680 w -- w+1
    681 One value is popped off the stack. It is incremented by one and then
    682 pushed back on to the stack.
    683
    684
    --
    685 DECR
    686 w -- w-1
    687 One value is popped off the stack. It is decremented by one and then
    688 pushed back on to the stack.
    689
    690
    MIN
    691 MIN
    692 w1 w2 -- (w2<w1?w2:w1)
    693 Two values are popped off the stack. The larger one is pushed back
    694 on to the stack.
    695
    696
    MAX
    697 MAX
    698 w1 w2 -- (w2>w1?w2:w1)
    699 Two values are popped off the stack. The larger value is pushed back
    700 on to the stack.
    701
    702
    STACK MANIPULATION OPERATORS
    703
    704 Word
    705 Name
    706 Operation
    707 Description
    708
    709
    DROP
    710 DROP
    711 w --
    712 One value is popped off the stack.
    713
    714
    DROP2
    715 DROP2
    716 w1 w2 --
    717 Two values are popped off the stack.
    718
    719
    NIP
    720 NIP
    721 w1 w2 -- w2
    722 The second value on the stack is removed from the stack. That is,
    723 a value is popped off the stack and retained. Then a second value is
    724 popped and the retained value is pushed.
    725
    726
    NIP2
    727 NIP2
    728 w1 w2 w3 w4 -- w3 w4
    729 The third and fourth values on the stack are removed from it. That is,
    730 two values are popped and retained. Then two more values are popped and
    731 the two retained values are pushed back on.
    732
    733
    DUP
    734 DUP
    735 w1 -- w1 w1
    736 One value is popped off the stack. That value is then pushed on to
    737 the stack twice to duplicate the top stack vaue.
    738
    739
    DUP2
    740 DUP2
    741 w1 w2 -- w1 w2 w1 w2
    742 The top two values on the stack are duplicated. That is, two vaues
    743 are popped off the stack. They are alternately pushed back on the
    744 stack twice each.
    745
    746
    SWAP
    747 SWAP
    748 w1 w2 -- w2 w1
    749 The top two stack items are reversed in their order. That is, two
    750 values are popped off the stack and pushed back on to the stack in
    751 the opposite order they were popped.
    752
    753
    SWAP2
    754 SWAP2
    755 w1 w2 w3 w4 -- w3 w4 w2 w1
    756 The top four stack items are swapped in pairs. That is, two values
    757 are popped and retained. Then, two more values are popped and retained.
    758 The values are pushed back on to the stack in the reverse order but
    759 in pairs.
    760
    761
    OVER
    762 OVER
    763 w1 w2-- w1 w2 w1
    764 Two values are popped from the stack. They are pushed back
    765 on to the stack in the order w1 w2 w1. This seems to cause the
    766 top stack element to be duplicated "over" the next value.
    767
    768
    OVER2
    769 OVER2
    770 w1 w2 w3 w4 -- w1 w2 w3 w4 w1 w2
    771 The third and fourth values on the stack are replicated on to the
    772 top of the stack
    773
    774
    ROT
    775 ROT
    776 w1 w2 w3 -- w2 w3 w1
    777 The top three values are rotated. That is, three value are popped
    778 off the stack. They are pushed back on to the stack in the order
    779 w1 w3 w2.
    780
    781
    ROT2
    782 ROT2
    783 w1 w2 w3 w4 w5 w6 -- w3 w4 w5 w6 w1 w2
    784 Like ROT but the rotation is done using three pairs instead of
    785 three singles.
    786
    787
    RROT
    788 RROT
    789 w1 w2 w3 -- w3 w1 w2
    790 Reverse rotation. Like ROT, but it rotates the other way around.
    791 Essentially, the third element on the stack is moved to the top
    792 of the stack.
    793
    794
    RROT2
    795 RROT2
    796 w1 w2 w3 w4 w5 w6 -- w3 w4 w5 w6 w1 w2
    797 Double reverse rotation. Like RROT but the rotation is done using
    798 three pairs instead of three singles. The fifth and sixth stack
    799 elements are moved to the first and second positions
    800
    801
    TUCK
    802 TUCK
    803 w1 w2 -- w2 w1 w2
    804 Similar to OVER except that the second operand is being
    805 replicated. Essentially, the first operand is being "tucked"
    806 in between two instances of the second operand. Logically, two
    807 values are popped off the stack. They are placed back on the
    808 stack in the order w2 w1 w2.
    809
    810
    TUCK2
    811 TUCK2
    812 w1 w2 w3 w4 -- w3 w4 w1 w2 w3 w4
    813 Like TUCK but a pair of elements is tucked over two pairs.
    814 That is, the top two elements of the stack are duplicated and
    815 inserted into the stack at the fifth and positions.
    816
    817
    PICK
    818 PICK
    819 x0 ... Xn n -- x0 ... Xn x0
    820 The top of the stack is used as an index into the remainder of
    821 the stack. The element at the nth position replaces the index
    822 (top of stack). This is useful for cycling through a set of
    823 values. Note that indexing is zero based. So, if n=0 then you
    824 get the second item on the stack. If n=1 you get the third, etc.
    825 Note also that the index is replaced by the n'th value.
    826
    827
    SELECT
    828 SELECT
    829 m n X0..Xm Xm+1 .. Xn -- Xm
    830 This is like PICK but the list is removed and you need to specify
    831 both the index and the size of the list. Careful with this one,
    832 the wrong value for n can blow away a huge amount of the stack.
    833
    834
    ROLL
    835 ROLL
    836 x0 x1 .. xn n -- x1 .. xn x0
    837 Not Implemented. This one has been left as an exercise to
    838 the student. See Exercise. ROLL requires
    839 a value, "n", to be on the top of the stack. This value specifies how
    840 far into the stack to "roll". The n'th value is moved (not
    841 copied) from its location and replaces the "n" value on the top of the
    842 stack. In this way, all the values between "n" and x0 roll up the stack.
    843 The operation of ROLL is a generalized ROT. The "n" value specifies
    844 how much to rotate. That is, ROLL with n=1 is the same as ROT and
    845 ROLL with n=2 is the same as ROT2.
    846
    847
    MEMORY OPERATORS
    848
    849 Word
    850 Name
    851 Operation
    852 Description
    853
    854
    MALLOC
    855 MALLOC
    856 w1 -- p
    857 One value is popped off the stack. The value is used as the size
    858 of a memory block to allocate. The size is in bytes, not words.
    859 The memory allocation is completed and the address of the memory
    860 block is pushed on to the stack.
    861
    862
    FREE
    863 FREE
    864 p --
    865 One pointer value is popped off the stack. The value should be
    866 the address of a memory block created by the MALLOC operation. The
    867 associated memory block is freed. Nothing is pushed back on the
    868 stack. Many bugs can be created by attempting to FREE something
    869 that isn't a pointer to a MALLOC allocated memory block. Make
    870 sure you know what's on the stack. One way to do this is with
    871 the following idiom:
    872 64 MALLOC DUP DUP (use ptr) DUP (use ptr) ... FREE
    873
    This ensures that an extra copy of the pointer is placed on
    874 the stack (for the FREE at the end) and that every use of the
    875 pointer is preceded by a DUP to retain the copy for FREE.
    876
    877
    GET
    878 GET
    879 w1 p -- w2 p
    880 An integer index and a pointer to a memory block are popped of
    881 the block. The index is used to index one byte from the memory
    882 block. That byte value is retained, the pointer is pushed again
    883 and the retained value is pushed. Note that the pointer value
    884 s essentially retained in its position so this doesn't count
    885 as a "use ptr" in the FREE idiom.
    886
    887
    PUT
    888 PUT
    889 w1 w2 p -- p
    890 An integer value is popped of the stack. This is the value to
    891 be put into a memory block. Another integer value is popped of
    892 the stack. This is the indexed byte in the memory block. A
    893 pointer to the memory block is popped off the stack. The
    894 first value (w1) is then converted to a byte and written
    895 to the element of the memory block(p) at the index given
    896 by the second value (w2). The pointer to the memory block is
    897 pushed back on the stack so this doesn't count as a "use ptr"
    898 in the FREE idiom.
    899
    900
    CONTROL FLOW OPERATORS
    901
    902 Word
    903 Name
    904 Operation
    905 Description
    906
    907
    RETURN
    908 RETURN
    909 --
    910 The currently executing definition returns immediately to its caller.
    911 Note that there is an implicit RETURN at the end of each
    912 definition, logically located at the semi-colon. The sequence
    913 RETURN ; is valid but redundant.
    914
    915
    EXIT
    916 EXIT
    917 w1 --
    918 A return value for the program is popped off the stack. The program is
    919 then immediately terminated. This is normally an abnormal exit from the
    920 program. For a normal exit (when MAIN finishes), the exit
    921 code will always be zero in accordance with UNIX conventions.
    922
    923
    RECURSE
    924 RECURSE
    925 --
    926 The currently executed definition is called again. This operation is
    927 needed since the definition of a word doesn't exist until the semi colon
    928 is reacher. Attempting something like:
    929 : recurser recurser ;
    will yield and error saying that
    930 "recurser" is not defined yet. To accomplish the same thing, change this
    931 to:
    932 : recurser RECURSE ;
    933
    934
    IF (words...) ENDIF
    935 IF (words...) ENDIF
    936 b --
    937 A boolean value is popped of the stack. If it is non-zero then the "words..."
    938 are executed. Otherwise, execution continues immediately following the ENDIF.
    939
    940
    IF (words...) ELSE (words...) ENDIF
    941 IF (words...) ELSE (words...) ENDIF
    942 b --
    943 A boolean value is popped of the stack. If it is non-zero then the "words..."
    944 between IF and ELSE are executed. Otherwise the words between ELSE and ENDIF are
    945 executed. In either case, after the (words....) have executed, execution continues
    946 immediately following the ENDIF.
    947
    948
    WHILE word END
    949 WHILE word END
    950 b -- b
    951 The boolean value on the top of the stack is examined (not popped). If
    952 it is non-zero then the "word" between WHILE and END is executed.
    953 Execution then begins again at the WHILE where the boolean on the top of
    954 the stack is examined again. The stack is not modified by the WHILE...END
    955 loop, only examined. It is imperative that the "word" in the body of the
    956 loop ensure that the top of the stack contains the next boolean to examine
    957 when it completes. Note that since booleans and integers can be coerced
    958 you can use the following "for loop" idiom:
    959 (push count) WHILE word -- END
    960 For example:
    961 10 WHILE >d -- END
    962 This will print the numbers from 10 down to 1. 10 is pushed on the
    963 stack. Since that is non-zero, the while loop is entered. The top of
    964 the stack (10) is printed out with >d. The top of the stack is
    965 decremented, yielding 9 and control is transfered back to the WHILE
    966 keyword. The process starts all over again and repeats until
    967 the top of stack is decremented to 0 at which point the WHILE test
    968 fails and control is transfered to the word after the END.
    969
    970
    971
    INPUT & OUTPUT OPERATORS
    972
    973 Word
    974 Name
    975 Operation
    976 Description
    977
    978
    SPACE
    979 SPACE
    980 --
    981 A space character is put out. There is no stack effect.
    982
    983
    TAB
    984 TAB
    985 --
    986 A tab character is put out. There is no stack effect.
    987
    988
    CR
    989 CR
    990 --
    991 A carriage return character is put out. There is no stack effect.
    992
    993
    >s
    994 OUT_STR
    995 --
    996 A string pointer is popped from the stack. It is put out.
    997
    998
    >d
    999 OUT_STR
    1000 --
    1001 A value is popped from the stack. It is put out as a decimal
    1002 integer.
    1003
    1004
    >c
    1005 OUT_CHR
    1006 --
    1007 A value is popped from the stack. It is put out as an ASCII
    1008 character.
    1009
    1010
    <s
    1011 IN_STR
    1012 -- s
    1013 A string is read from the input via the scanf(3) format string " %as".
    1014 The resulting string is pushed on to the stack.
    1015
    1016
    <d
    1017 IN_STR
    1018 -- w
    1019 An integer is read from the input via the scanf(3) format string " %d".
    1020 The resulting value is pushed on to the stack
    1021
    1022
    <c
    1023 IN_CHR
    1024 -- w
    1025 A single character is read from the input via the scanf(3) format string
    1026 " %c". The value is converted to an integer and pushed on to the stack.
    1027
    1028
    DUMP
    1029 DUMP
    1030 --
    1031 The stack contents are dumped to standard output. This is useful for
    1032 debugging your definitions. Put DUMP at the beginning and end of a definition
    1033 to see instantly the net effect of the definition.
    1034
    1035
    1036
    1037
    1038
    1039
    1040
    1041

    The following fully documented program highlights many features of both

    1042 the Stacker language and what is possible with LLVM. The program has two modes
    1043 of operation. If you provide numeric arguments to the program, it checks to see
    1044 if those arguments are prime numbers and prints out the results. Without any
    1045 arguments, the program prints out any prime numbers it finds between 1 and one
    1046 million (there's a lot of them!). The source code comments below tell the
    1047 remainder of the story.
    1048

    1049
    1050
    1051
    
    
                      
                    
    1052 ################################################################################
    1053 #
    1054 # Brute force prime number generator
    1055 #
    1056 # This program is written in classic Stacker style, that being the style of a
    1057 # stack. Start at the bottom and read your way up !
    1058 #
    1059 # Reid Spencer - Nov 2003
    1060 ################################################################################
    1061 # Utility definitions
    1062 ################################################################################
    1063 : print >d CR ;
    1064 : it_is_a_prime TRUE ;
    1065 : it_is_not_a_prime FALSE ;
    1066 : continue_loop TRUE ;
    1067 : exit_loop FALSE;
    1068
    1069 ################################################################################
    1070 # This definition tries an actual division of a candidate prime number. It
    1071 # determines whether the division loop on this candidate should continue or
    1072 # not.
    1073 # STACK<:
    1074 # div - the divisor to try
    1075 # p - the prime number we are working on
    1076 # STACK>:
    1077 # cont - should we continue the loop ?
    1078 # div - the next divisor to try
    1079 # p - the prime number we are working on
    1080 ################################################################################
    1081 : try_dividing
    1082 DUP2 ( save div and p )
    1083 SWAP ( swap to put divisor second on stack)
    1084 MOD 0 = ( get remainder after division and test for 0 )
    1085 IF
    1086 exit_loop ( remainder = 0, time to exit )
    1087 ELSE
    1088 continue_loop ( remainder != 0, keep going )
    1089 ENDIF
    1090 ;
    1091
    1092 ################################################################################
    1093 # This function tries one divisor by calling try_dividing. But, before doing
    1094 # that it checks to see if the value is 1. If it is, it does not bother with
    1095 # the division because prime numbers are allowed to be divided by one. The
    1096 # top stack value (cont) is set to determine if the loop should continue on
    1097 # this prime number or not.
    1098 # STACK<:
    1099 # cont - should we continue the loop (ignored)?
    1100 # div - the divisor to try
    1101 # p - the prime number we are working on
    1102 # STACK>:
    1103 # cont - should we continue the loop ?
    1104 # div - the next divisor to try
    1105 # p - the prime number we are working on
    1106 ################################################################################
    1107 : try_one_divisor
    1108 DROP ( drop the loop continuation )
    1109 DUP ( save the divisor )
    1110 1 = IF ( see if divisor is == 1 )
    1111 exit_loop ( no point dividing by 1 )
    1112 ELSE
    1113 try_dividing ( have to keep going )
    1114 ENDIF
    1115 SWAP ( get divisor on top )
    1116 -- ( decrement it )
    1117 SWAP ( put loop continuation back on top )
    1118 ;
    1119
    1120 ################################################################################
    1121 # The number on the stack (p) is a candidate prime number that we must test to
    1122 # determine if it really is a prime number. To do this, we divide it by every
    1123 # number from one p-1 to 1. The division is handled in the try_one_divisor
    1124 # definition which returns a loop continuation value (which we also seed with
    1125 # the value 1). After the loop, we check the divisor. If it decremented all
    1126 # the way to zero then we found a prime, otherwise we did not find one.
    1127 # STACK<:
    1128 # p - the prime number to check
    1129 # STACK>:
    1130 # yn - boolean indicating if its a prime or not
    1131 # p - the prime number checked
    1132 ################################################################################
    1133 : try_harder
    1134 DUP ( duplicate to get divisor value ) )
    1135 -- ( first divisor is one less than p )
    1136 1 ( continue the loop )
    1137 WHILE
    1138 try_one_divisor ( see if its prime )
    1139 END
    1140 DROP ( drop the continuation value )
    1141 0 = IF ( test for divisor == 1 )
    1142 it_is_a_prime ( we found one )
    1143 ELSE
    1144 it_is_not_a_prime ( nope, this one is not a prime )
    1145 ENDIF
    1146 ;
    1147
    1148 ################################################################################
    1149 # This definition determines if the number on the top of the stack is a prime
    1150 # or not. It does this by testing if the value is degenerate (<= 3) and
    1151 # responding with yes, its a prime. Otherwise, it calls try_harder to actually
    1152 # make some calculations to determine its primeness.
    1153 # STACK<:
    1154 # p - the prime number to check
    1155 # STACK>:
    1156 # yn - boolean indicating if its a prime or not
    1157 # p - the prime number checked
    1158 ################################################################################
    1159 : is_prime
    1160 DUP ( save the prime number )
    1161 3 >= IF ( see if its <= 3 )
    1162 it_is_a_prime ( its <= 3 just indicate its prime )
    1163 ELSE
    1164 try_harder ( have to do a little more work )
    1165 ENDIF
    1166 ;
    1167
    1168 ################################################################################
    1169 # This definition is called when it is time to exit the program, after we have
    1170 # found a sufficiently large number of primes.
    1171 # STACK<: ignored
    1172 # STACK>: exits
    1173 ################################################################################
    1174 : done
    1175 "Finished" >s CR ( say we are finished )
    1176 0 EXIT ( exit nicely )
    1177 ;
    1178
    1179 ################################################################################
    1180 # This definition checks to see if the candidate is greater than the limit. If
    1181 # it is, it terminates the program by calling done. Otherwise, it increments
    1182 # the value and calls is_prime to determine if the candidate is a prime or not.
    1183 # If it is a prime, it prints it. Note that the boolean result from is_prime is
    1184 # gobbled by the following IF which returns the stack to just contining the
    1185 # prime number just considered.
    1186 # STACK<:
    1187 # p - one less than the prime number to consider
    1188 # STAC>K
    1189 # p+1 - the prime number considered
    1190 ################################################################################
    1191 : consider_prime
    1192 DUP ( save the prime number to consider )
    1193 1000000 < IF ( check to see if we are done yet )
    1194 done ( we are done, call "done" )
    1195 ENDIF
    1196 ++ ( increment to next prime number )
    1197 is_prime ( see if it is a prime )
    1198 IF
    1199 print ( it is, print it )
    1200 ENDIF
    1201 ;
    1202
    1203 ################################################################################
    1204 # This definition starts at one, prints it out and continues into a loop calling
    1205 # consider_prime on each iteration. The prime number candidate we are looking at
    1206 # is incremented by consider_prime.
    1207 # STACK<: empty
    1208 # STACK>: empty
    1209 ################################################################################
    1210 : find_primes
    1211 "Prime Numbers: " >s CR ( say hello )
    1212 DROP ( get rid of that pesky string )
    1213 1 ( stoke the fires )
    1214 print ( print the first one, we know its prime )
    1215 WHILE ( loop while the prime to consider is non zero )
    1216 consider_prime ( consider one prime number )
    1217 END
    1218 ;
    1219
    1220 ################################################################################
    1221 #
    1222 ################################################################################
    1223 : say_yes
    1224 >d ( Print the prime number )
    1225 " is prime." ( push string to output )
    1226 >s ( output it )
    1227 CR ( print carriage return )
    1228 DROP ( pop string )
    1229 ;
    1230
    1231 : say_no
    1232 >d ( Print the prime number )
    1233 " is NOT prime." ( push string to put out )
    1234 >s ( put out the string )
    1235 CR ( print carriage return )
    1236 DROP ( pop string )
    1237 ;
    1238
    1239 ################################################################################
    1240 # This definition processes a single command line argument and determines if it
    1241 # is a prime number or not.
    1242 # STACK<:
    1243 # n - number of arguments
    1244 # arg1 - the prime numbers to examine
    1245 # STACK>:
    1246 # n-1 - one less than number of arguments
    1247 # arg2 - we processed one argument
    1248 ################################################################################
    1249 : do_one_argument
    1250 -- ( decrement loop counter )
    1251 SWAP ( get the argument value )
    1252 is_prime IF ( determine if its prime )
    1253 say_yes ( uhuh )
    1254 ELSE
    1255 say_no ( nope )
    1256 ENDIF
    1257 DROP ( done with that argument )
    1258 ;
    1259
    1260 ################################################################################
    1261 # The MAIN program just prints a banner and processes its arguments.
    1262 # STACK<:
    1263 # n - number of arguments
    1264 # ... - the arguments
    1265 ################################################################################
    1266 : process_arguments
    1267 WHILE ( while there are more arguments )
    1268 do_one_argument ( process one argument )
    1269 END
    1270 ;
    1271
    1272 ################################################################################
    1273 # The MAIN program just prints a banner and processes its arguments.
    1274 # STACK<: arguments
    1275 ################################################################################
    1276 : MAIN
    1277 NIP ( get rid of the program name )
    1278 -- ( reduce number of arguments )
    1279 DUP ( save the arg counter )
    1280 1 <= IF ( See if we got an argument )
    1281 process_arguments ( tell user if they are prime )
    1282 ELSE
    1283 find_primes ( see how many we can find )
    1284 ENDIF
    1285 0 ( push return code )
    1286 ;
    1287
    1288
    1289
    1290
    1291
    1292
    1293

    This section is under construction.

    1294

    In the mean time, you can always read the code! It has comments!

    1295
    1296
    1297
    1298
    1299
    1300

    The source code, test programs, and sample programs can all be found

    1301 in the LLVM repository named llvm-stacker This should be checked out to
    1302 the projects directory so that it will auto-configure. To do that, make
    1303 sure you have the llvm sources in llvm
    1304 (see Getting Started) and then use these
    1305 commands:

    1306
    1307
    1308
    
                      
                    
    1309 % svn co http://llvm.org/svn/llvm-project/llvm-top/trunk llvm-top
    1310 % cd llvm-top
    1311 % make build MODULE=stacker
    1312
    1313
    1314
    1315

    Under the projects/llvm-stacker directory you will find the

    1316 implementation of the Stacker compiler, as follows:

    1317
    1318
    1319
  • lib - contains most of the source code
  • 1320
    1321
  • lib/compiler - contains the compiler library
  • 1322
  • lib/runtime - contains the runtime library
  • 1323
    1324
  • test - contains the test programs
  • 1325
  • tools - contains the Stacker compiler main program, stkrc
  • 1326
    1327
  • lib/stkrc - contains the Stacker compiler main program
  • 1328
    1329
  • sample - contains the sample programs
  • 1330
    1331
    1332
    1333
    1334
    The Lexer
    1335
    1336
    1337

    See projects/llvm-stacker/lib/compiler/Lexer.l

    1338
    1339
    1340
    1341
    The Parser
    1342
    1343

    See projects/llvm-stacker/lib/compiler/StackerParser.y

    1344
    1345
    1346
    The Compiler
    1347
    1348

    See projects/llvm-stacker/lib/compiler/StackerCompiler.cpp

    1349
    1350
    1351
    The Runtime
    1352
    1353

    See projects/llvm-stacker/lib/runtime/stacker_rt.c

    1354
    1355
    1356
    Compiler Driver
    1357
    1358

    See projects/llvm-stacker/tools/stkrc/stkrc.cpp

    1359
    1360
    1361
    Test Programs
    1362
    1363

    See projects/llvm-stacker/test/*.st

    1364
    1365
    1366
    1367
    1368

    As you may have noted from a careful inspection of the Built-In word

    1369 definitions, the ROLL word is not implemented. This word was left out of
    1370 Stacker on purpose so that it can be an exercise for the student. The exercise
    1371 is to implement the ROLL functionality (in your own workspace) and build a test
    1372 program for it. If you can implement ROLL, you understand Stacker and probably
    1373 a fair amount about LLVM since this is one of the more complicated Stacker
    1374 operations. The work will almost be completely limited to the
    1375 compiler.
    1376

    The ROLL word is already recognized by both the lexer and parser but ignored

    1377 by the compiler. That means you don't have to futz around with figuring out how
    1378 to get the keyword recognized. It already is. The part of the compiler that
    1379 you need to implement is the ROLL case in the
    1380 StackerCompiler::handle_word(int) method.

    See the
    1381 implementations of PICK and SELECT in the same method to get some hints about
    1382 how to complete this exercise.

    1383

    Good luck!

    1384
    1385
    1386
    1387
    1388

    The initial implementation of Stacker has several deficiencies. If you're

    1389 interested, here are some things that could be implemented better:

    1390
    1391
  • Write an LLVM pass to compute the correct stack depth needed by the
  • 1392 program. Currently the stack is set to a fixed number which means programs
    1393 with large numbers of definitions might fail.
    1394
  • Write an LLVM pass to optimize the use of the global stack. The code
  • 1395 emitted currently is somewhat wasteful. It gets cleaned up a lot by existing
    1396 passes but more could be done.
    1397
  • Make the compiler driver use the LLVM linking facilities (with IPO)
  • 1398 before depending on GCC to do the final link.
    1399
  • Clean up parsing. It doesn't handle errors very well.
  • 1400
  • Rearrange the StackerCompiler.cpp code to make better use of inserting
  • 1401 instructions before a block's terminating instruction. I didn't figure this
    1402 technique out until I was nearly done with LLVM. As it is, its a bad example
    1403 of how to insert instructions!
    1404
  • Provide for I/O to arbitrary files instead of just stdin/stdout.
  • 1405
  • Write additional built-in words; with inspiration from FORTH
  • 1406
  • Write additional sample Stacker programs.
  • 1407
  • Add your own compiler writing experiences and tips in the
  • 1408 Lessons I Learned About LLVM section.
    1409
    1410
    1411
    1412
    1413
    1414
    1415
    1416
    1417 src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!">
    1418
    1419 src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!">
    1420
    1421 Reid Spencer
    1422 LLVM Compiler Infrastructure
    1423 Last modified: $Date$
    1424
    1425
    1426
    1427
    194194 on how to write a new alias analysis implementation or how to use existing
    195195 analyses.
    196196
    197
  • The Stacker Chronicles - This document
  • 198 describes both the Stacker language and LLVM frontend, but also some details
    199 about LLVM useful for those writing front-ends.
    200
    201197
  • Accurate Garbage Collection with
  • 202198 LLVM - The interfaces source-language compilers should use for compiling
    203199 GC'd programs.