blob: fbdc5bd2ecb7e1f8cbf71bcadade31dd422530db [file] [log] [blame]
Brian Gaeke90181482003-11-24 02:52:51 +00001<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
2<html>
3<head>
4 <title>Stacker: An Example Of Using LLVM</title>
5 <link rel="stylesheet" href="llvm.css" type="text/css">
6</head>
7<body>
8<div class="doc_title">Stacker: An Example Of Using LLVM</div>
Brian Gaeke07e89e42003-11-24 17:03:38 +00009<hr>
Brian Gaeke90181482003-11-24 02:52:51 +000010<ol>
11 <li><a href="#abstract">Abstract</a></li>
12 <li><a href="#introduction">Introduction</a></li>
Brian Gaeke07e89e42003-11-24 17:03:38 +000013 <li><a href="#lessons">Lessons I Learned About LLVM</a>
14 <ol>
15 <li><a href="#value">Everything's a Value!</a></li>
16 <li><a href="#terminate">Terminate Those Blocks!</a></li>
17 <li><a href="#blocks">Concrete Blocks</a></li>
18 <li><a href="#push_back">push_back Is Your Friend</a></li>
19 <li><a href="#gep">The Wily GetElementPtrInst</a></li>
20 <li><a href="#linkage">Getting Linkage Types Right</a></li>
21 <li><a href="#constants">Constants Are Easier Than That!</a></li>
22 </ol>
23 </li>
Brian Gaeke90181482003-11-24 02:52:51 +000024 <li><a href="#lexicon">The Stacker Lexicon</a>
25 <ol>
26 <li><a href="#stack">The Stack</a>
27 <li><a href="#punctuation">Punctuation</a>
Chris Lattnere46d6012003-11-25 01:35:06 +000028 <li><a href="#comments">Comments</a>
Brian Gaeke90181482003-11-24 02:52:51 +000029 <li><a href="#literals">Literals</a>
30 <li><a href="#words">Words</a>
Chris Lattnere46d6012003-11-25 01:35:06 +000031 <li><a href="style">Standard Style</a>
Brian Gaeke90181482003-11-24 02:52:51 +000032 <li><a href="#builtins">Built-Ins</a>
33 </ol>
34 </li>
Brian Gaeke07e89e42003-11-24 17:03:38 +000035 <li><a href="#example">Prime: A Complete Example</a></li>
36 <li><a href="#internal">Internal Code Details</a>
37 <ol>
38 <li><a href="#directory">The Directory Structure </a></li>
39 <li><a href="#lexer">The Lexer</a></li>
40 <li><a href="#parser">The Parser</a></li>
41 <li><a href="#compiler">The Compiler</a></li>
42 <li><a href="#runtime">The Runtime</a></li>
43 <li><a href="#driver">Compiler Driver</a></li>
44 <li><a href="#tests">Test Programs</a></li>
Chris Lattnere46d6012003-11-25 01:35:06 +000045 <li><a href="#exercise">Exercise</a></li>
46 <li><a href="#todo">Things Remaining To Be Done</a></li>
Brian Gaeke07e89e42003-11-24 17:03:38 +000047 </ol>
48 </li>
Brian Gaeke90181482003-11-24 02:52:51 +000049</ol>
50<div class="doc_text">
51<p><b>Written by <a href="mailto:rspencer@x10sys.com">Reid Spencer</a> </b></p>
52<p> </p>
53</div>
Brian Gaeke07e89e42003-11-24 17:03:38 +000054<hr>
Brian Gaeke90181482003-11-24 02:52:51 +000055<!-- ======================================================================= -->
56<div class="doc_section"> <a name="abstract">Abstract </a></div>
57<div class="doc_text">
58<p>This document is another way to learn about LLVM. Unlike the
59<a href="LangRef.html">LLVM Reference Manual</a> or
Chris Lattnere46d6012003-11-25 01:35:06 +000060<a href="ProgrammersManual.html">LLVM Programmer's Manual</a>, we learn
61about LLVM through the experience of creating a simple programming language
62named Stacker. Stacker was invented specifically as a demonstration of
Brian Gaeke90181482003-11-24 02:52:51 +000063LLVM. The emphasis in this document is not on describing the
64intricacies of LLVM itself, but on how to use it to build your own
65compiler system.</p>
66</div>
67<!-- ======================================================================= -->
68<div class="doc_section"> <a name="introduction">Introduction</a> </div>
69<div class="doc_text">
70<p>Amongst other things, LLVM is a platform for compiler writers.
71Because of its exceptionally clean and small IR (intermediate
72representation), compiler writing with LLVM is much easier than with
73other system. As proof, the author of Stacker wrote the entire
74compiler (language definition, lexer, parser, code generator, etc.) in
75about <em>four days</em>! That's important to know because it shows
76how quickly you can get a new
77language up when using LLVM. Furthermore, this was the <em >first</em>
78language the author ever created using LLVM. The learning curve is
79included in that four days.</p>
80<p>The language described here, Stacker, is Forth-like. Programs
81are simple collections of word definitions and the only thing definitions
82can do is manipulate a stack or generate I/O. Stacker is not a "real"
83programming language; its very simple. Although it is computationally
84complete, you wouldn't use it for your next big project. However,
85the fact that it is complete, its simple, and it <em>doesn't</em> have
86a C-like syntax make it useful for demonstration purposes. It shows
Chris Lattnere46d6012003-11-25 01:35:06 +000087that LLVM could be applied to a wide variety of languages.</p>
Brian Gaeke90181482003-11-24 02:52:51 +000088<p>The basic notions behind stacker is very simple. There's a stack of
89integers (or character pointers) that the program manipulates. Pretty
90much the only thing the program can do is manipulate the stack and do
91some limited I/O operations. The language provides you with several
92built-in words that manipulate the stack in interesting ways. To get
93your feet wet, here's how you write the traditional "Hello, World"
94program in Stacker:</p>
95<p><code>: hello_world "Hello, World!" &gt;s DROP CR ;<br>
96: MAIN hello_world ;<br></code></p>
97<p>This has two "definitions" (Stacker manipulates words, not
98functions and words have definitions): <code>MAIN</code> and <code>
99hello_world</code>. The <code>MAIN</code> definition is standard, it
100tells Stacker where to start. Here, <code>MAIN</code> is defined to
101simply invoke the word <code>hello_world</code>. The
102<code>hello_world</code> definition tells stacker to push the
103<code>"Hello, World!"</code> string onto the stack, print it out
104(<code>&gt;s</code>), pop it off the stack (<code>DROP</code>), and
105finally print a carriage return (<code>CR</code>). Although
106<code>hello_world</code> uses the stack, its net effect is null. Well
107written Stacker definitions have that characteristic. </p>
108<p>Exercise for the reader: how could you make this a one line program?</p>
109</div>
110<!-- ======================================================================= -->
Brian Gaeke07e89e42003-11-24 17:03:38 +0000111<div class="doc_section"><a name="lessons"></a>Lessons I Learned About LLVM</div>
Brian Gaeke90181482003-11-24 02:52:51 +0000112<div class="doc_text">
Chris Lattnere46d6012003-11-25 01:35:06 +0000113<p>Stacker was written for two purposes: </p>
114<ol>
115 <li>to get the author over the learning curve, and</li>
116 <li>to provide a simple example of how to write a compiler using LLVM.</li>
117</ol>
118<p>During the development of Stacker, many lessons about LLVM were
Brian Gaeke90181482003-11-24 02:52:51 +0000119learned. Those lessons are described in the following subsections.<p>
120</div>
Brian Gaeke07e89e42003-11-24 17:03:38 +0000121<!-- ======================================================================= -->
122<div class="doc_subsection"><a name="value"></a>Everything's a Value!</div>
123<div class="doc_text">
Chris Lattnere46d6012003-11-25 01:35:06 +0000124<p>Although I knew that LLVM uses a Single Static Assignment (SSA) format,
Brian Gaeke07e89e42003-11-24 17:03:38 +0000125it wasn't obvious to me how prevalent this idea was in LLVM until I really
Chris Lattnere46d6012003-11-25 01:35:06 +0000126started using it. Reading the <a href="ProgrammersManual.html">
127Programmer's Manual</a> and <a href="LangRef.html">Language Reference</a>
128I noted that most of the important LLVM IR (Intermediate Representation) C++
Brian Gaeke07e89e42003-11-24 17:03:38 +0000129classes were derived from the Value class. The full power of that simple
130design only became fully understood once I started constructing executable
131expressions for Stacker.</p>
132<p>This really makes your programming go faster. Think about compiling code
Chris Lattnere46d6012003-11-25 01:35:06 +0000133for the following C/C++ expression: <code>(a|b)*((x+1)/(y+1))</code>. Assuming
134the values are on the stack in the order a, b, x, y, this could be
135expressed in stacker as: <code>1 + SWAP 1 + / ROT2 OR *</code>.
136You could write a function using LLVM that computes this expression like this: </p>
Brian Gaeke07e89e42003-11-24 17:03:38 +0000137<pre><code>
138Value*
139expression(BasicBlock*bb, Value* a, Value* b, Value* x, Value* y )
140{
141 Instruction* tail = bb->getTerminator();
142 ConstantSInt* one = ConstantSInt::get( Type::IntTy, 1);
143 BinaryOperator* or1 =
144 new BinaryOperator::create( Instruction::Or, a, b, "", tail );
145 BinaryOperator* add1 =
146 new BinaryOperator::create( Instruction::Add, x, one, "", tail );
147 BinaryOperator* add2 =
148 new BinaryOperator::create( Instruction::Add, y, one, "", tail );
149 BinaryOperator* div1 =
150 new BinaryOperator::create( Instruction::Div, add1, add2, "", tail);
151 BinaryOperator* mult1 =
152 new BinaryOperator::create( Instruction::Mul, or1, div1, "", tail );
153
154 return mult1;
155}
156</code></pre>
157<p>"Okay, big deal," you say. It is a big deal. Here's why. Note that I didn't
158have to tell this function which kinds of Values are being passed in. They could be
Chris Lattnere46d6012003-11-25 01:35:06 +0000159<code>Instruction</code>s, <code>Constant</code>s, <code>GlobalVariable</code>s,
160etc. Furthermore, if you specify Values that are incorrect for this sequence of
161operations, LLVM will either notice right away (at compilation time) or the LLVM
162Verifier will pick up the inconsistency when the compiler runs. In no case will
163you make a type error that gets passed through to the generated program.
164This <em>really</em> helps you write a compiler that always generates correct code!<p>
Brian Gaeke07e89e42003-11-24 17:03:38 +0000165<p>The second point is that we don't have to worry about branching, registers,
166stack variables, saving partial results, etc. The instructions we create
167<em>are</em> the values we use. Note that all that was created in the above
168code is a Constant value and five operators. Each of the instructions <em>is</em>
Chris Lattnere46d6012003-11-25 01:35:06 +0000169the resulting value of that instruction. This saves a lot of time.</p>
Brian Gaeke07e89e42003-11-24 17:03:38 +0000170<p>The lesson is this: <em>SSA form is very powerful: there is no difference
Chris Lattnere46d6012003-11-25 01:35:06 +0000171between a value and the instruction that created it.</em> This is fully
Brian Gaeke07e89e42003-11-24 17:03:38 +0000172enforced by the LLVM IR. Use it to your best advantage.</p>
173</div>
174<!-- ======================================================================= -->
175<div class="doc_subsection"><a name="terminate"></a>Terminate Those Blocks!</div>
176<div class="doc_text">
177<p>I had to learn about terminating blocks the hard way: using the debugger
178to figure out what the LLVM verifier was trying to tell me and begging for
179help on the LLVMdev mailing list. I hope you avoid this experience.</p>
180<p>Emblazon this rule in your mind:</p>
181<ul>
182 <li><em>All</em> <code>BasicBlock</code>s in your compiler <b>must</b> be
183 terminated with a terminating instruction (branch, return, etc.).
184 </li>
185</ul>
186<p>Terminating instructions are a semantic requirement of the LLVM IR. There
187is no facility for implicitly chaining together blocks placed into a function
188in the order they occur. Indeed, in the general case, blocks will not be
189added to the function in the order of execution because of the recursive
190way compilers are written.</p>
191<p>Furthermore, if you don't terminate your blocks, your compiler code will
192compile just fine. You won't find out about the problem until you're running
193the compiler and the module you just created fails on the LLVM Verifier.</p>
194</div>
195<!-- ======================================================================= -->
196<div class="doc_subsection"><a name="blocks"></a>Concrete Blocks</div>
197<div class="doc_text">
198<p>After a little initial fumbling around, I quickly caught on to how blocks
Chris Lattnere46d6012003-11-25 01:35:06 +0000199should be constructed. In general, here's what I learned:
Brian Gaeke07e89e42003-11-24 17:03:38 +0000200<ol>
201 <li><em>Create your blocks early.</em> While writing your compiler, you
202 will encounter several situations where you know apriori that you will
203 need several blocks. For example, if-then-else, switch, while and for
204 statements in C/C++ all need multiple blocks for expression in LVVM.
205 The rule is, create them early.</li>
206 <li><em>Terminate your blocks early.</em> This just reduces the chances
207 that you forget to terminate your blocks which is required (go
208 <a href="#terminate">here</a> for more).
209 <li><em>Use getTerminator() for instruction insertion.</em> I noticed early on
210 that many of the constructors for the Instruction classes take an optional
211 <code>insert_before</code> argument. At first, I thought this was a mistake
212 because clearly the normal mode of inserting instructions would be one at
213 a time <em>after</em> some other instruction, not <em>before</em>. However,
214 if you hold on to your terminating instruction (or use the handy dandy
215 <code>getTerminator()</code> method on a <code>BasicBlock</code>), it can
216 always be used as the <code>insert_before</code> argument to your instruction
217 constructors. This causes the instruction to automatically be inserted in
Chris Lattnere46d6012003-11-25 01:35:06 +0000218 the RightPlace&trade; place, just before the terminating instruction. The
Brian Gaeke07e89e42003-11-24 17:03:38 +0000219 nice thing about this design is that you can pass blocks around and insert
Chris Lattnere46d6012003-11-25 01:35:06 +0000220 new instructions into them without ever knowing what instructions came
Brian Gaeke07e89e42003-11-24 17:03:38 +0000221 before. This makes for some very clean compiler design.</li>
222</ol>
223<p>The foregoing is such an important principal, its worth making an idiom:</p>
Chris Lattnere46d6012003-11-25 01:35:06 +0000224<pre><code>
Brian Gaeke07e89e42003-11-24 17:03:38 +0000225BasicBlock* bb = new BasicBlock();</li>
226bb->getInstList().push_back( new Branch( ... ) );
227new Instruction(..., bb->getTerminator() );
Chris Lattnere46d6012003-11-25 01:35:06 +0000228</code></pre>
Brian Gaeke07e89e42003-11-24 17:03:38 +0000229<p>To make this clear, consider the typical if-then-else statement
230(see StackerCompiler::handle_if() method). We can set this up
231in a single function using LLVM in the following way: </p>
232<pre>
233using namespace llvm;
234BasicBlock*
235MyCompiler::handle_if( BasicBlock* bb, SetCondInst* condition )
236{
237 // Create the blocks to contain code in the structure of if/then/else
238 BasicBlock* then = new BasicBlock();
239 BasicBlock* else = new BasicBlock();
240 BasicBlock* exit = new BasicBlock();
241
242 // Insert the branch instruction for the "if"
243 bb->getInstList().push_back( new BranchInst( then, else, condition ) );
244
245 // Set up the terminating instructions
246 then->getInstList().push_back( new BranchInst( exit ) );
247 else->getInstList().push_back( new BranchInst( exit ) );
248
249 // Fill in the then part .. details excised for brevity
250 this->fill_in( then );
251
252 // Fill in the else part .. details excised for brevity
253 this->fill_in( else );
254
255 // Return a block to the caller that can be filled in with the code
256 // that follows the if/then/else construct.
257 return exit;
258}
259</pre>
260<p>Presumably in the foregoing, the calls to the "fill_in" method would add
261the instructions for the "then" and "else" parts. They would use the third part
262of the idiom almost exclusively (inserting new instructions before the
263terminator). Furthermore, they could even recurse back to <code>handle_if</code>
Chris Lattnere46d6012003-11-25 01:35:06 +0000264should they encounter another if/then/else statement and it will just work.</p>
Brian Gaeke07e89e42003-11-24 17:03:38 +0000265<p>Note how cleanly this all works out. In particular, the push_back methods on
266the <code>BasicBlock</code>'s instruction list. These are lists of type
267<code>Instruction</code> which also happen to be <code>Value</code>s. To create
268the "if" branch we merely instantiate a <code>BranchInst</code> that takes as
269arguments the blocks to branch to and the condition to branch on. The blocks
270act like branch labels! This new <code>BranchInst</code> terminates
271the <code>BasicBlock</code> provided as an argument. To give the caller a way
272to keep inserting after calling <code>handle_if</code> we create an "exit" block
273which is returned to the caller. Note that the "exit" block is used as the
274terminator for both the "then" and the "else" blocks. This gaurantees that no
275matter what else "handle_if" or "fill_in" does, they end up at the "exit" block.
276</p>
277</div>
278<!-- ======================================================================= -->
279<div class="doc_subsection"><a name="push_back"></a>push_back Is Your Friend</div>
280<div class="doc_text">
281<p>
282One of the first things I noticed is the frequent use of the "push_back"
283method on the various lists. This is so common that it is worth mentioning.
284The "push_back" inserts a value into an STL list, vector, array, etc. at the
285end. The method might have also been named "insert_tail" or "append".
286Althought I've used STL quite frequently, my use of push_back wasn't very
287high in other programs. In LLVM, you'll use it all the time.
288</p>
289</div>
290<!-- ======================================================================= -->
291<div class="doc_subsection"><a name="gep"></a>The Wily GetElementPtrInst</div>
292<div class="doc_text">
293<p>
294It took a little getting used to and several rounds of postings to the LLVM
295mail list to wrap my head around this instruction correctly. Even though I had
296read the Language Reference and Programmer's Manual a couple times each, I still
297missed a few <em>very</em> key points:
298</p>
299<ul>
300 <li>GetElementPtrInst gives you back a Value for the last thing indexed</em>
301 <li>All global variables in LLVM are <em>pointers</em>.
302 <li>Pointers must also be dereferenced with the GetElementPtrInst instruction.
303</ul>
304<p>This means that when you look up an element in the global variable (assuming
305its a struct or array), you <em>must</em> deference the pointer first! For many
306things, this leads to the idiom:
307</p>
308<pre><code>
309std::vector<Value*> index_vector;
310index_vector.push_back( ConstantSInt::get( Type::LongTy, 0 );
311// ... push other indices ...
312GetElementPtrInst* gep = new GetElementPtrInst( ptr, index_vector );
313</code></pre>
314<p>For example, suppose we have a global variable whose type is [24 x int]. The
315variable itself represents a <em>pointer</em> to that array. To subscript the
316array, we need two indices, not just one. The first index (0) dereferences the
317pointer. The second index subscripts the array. If you're a "C" programmer, this
318will run against your grain because you'll naturally think of the global array
319variable and the address of its first element as the same. That tripped me up
320for a while until I realized that they really do differ .. by <em>type</em>.
Chris Lattnere46d6012003-11-25 01:35:06 +0000321Remember that LLVM is a strongly typed language itself. Everything
Brian Gaeke07e89e42003-11-24 17:03:38 +0000322has a type. The "type" of the global variable is [24 x int]*. That is, its
323a pointer to an array of 24 ints. When you dereference that global variable with
Chris Lattnere46d6012003-11-25 01:35:06 +0000324a single (0) index, you now have a "[24 x int]" type. Although
Brian Gaeke07e89e42003-11-24 17:03:38 +0000325the pointer value of the dereferenced global and the address of the zero'th element
326in the array will be the same, they differ in their type. The zero'th element has
327type "int" while the pointer value has type "[24 x int]".</p>
328<p>Get this one aspect of LLVM right in your head and you'll save yourself
329a lot of compiler writing headaches down the road.</p>
330</div>
331<!-- ======================================================================= -->
Brian Gaeke90181482003-11-24 02:52:51 +0000332<div class="doc_subsection"><a name="linkage"></a>Getting Linkage Types Right</div>
Brian Gaeke07e89e42003-11-24 17:03:38 +0000333<div class="doc_text">
334<p>Linkage types in LLVM can be a little confusing, especially if your compiler
335writing mind has affixed very hard concepts to particular words like "weak",
336"external", "global", "linkonce", etc. LLVM does <em>not</em> use the precise
337definitions of say ELF or GCC even though they share common terms. To be fair,
338the concepts are related and similar but not precisely the same. This can lead
339you to think you know what a linkage type represents but in fact it is slightly
340different. I recommend you read the
341<a href="LangRef.html#linkage"> Language Reference on this topic</a> very
Chris Lattnere46d6012003-11-25 01:35:06 +0000342carefully. Then, read it again.<p>
Brian Gaeke07e89e42003-11-24 17:03:38 +0000343<p>Here are some handy tips that I discovered along the way:</p>
344<ul>
345 <li>Unitialized 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.</li>
347 <li>Setting an initializer changes a global's linkage type from whatever it was
348 to a normal, defind global (not external). You'll need to call the setLinkage()
349 method to reset it if you specify the initializer after the GlobalValue has been
350 constructed. This is important for LinkOnce and Weak linkage types.</li>
351 <li>Appending linkage can be used to keep track of compilation information at
352 runtime. It could be used, for example, to build a full table of all the C++
353 virtual tables or hold the C++ RTTI data, or whatever. Appending linkage can
354 only be applied to arrays. The arrays are concatenated together at link time.</li>
355</ul>
356</div>
357<!-- ======================================================================= -->
358<div class="doc_subsection"><a name="constants"></a>Constants Are Easier Than That!</div>
359<div class="doc_text">
360<p>
361Constants in LLVM took a little getting used to until I discovered a few utility
362functions in the LLVM IR that make things easier. Here's what I learned: </p>
363<ul>
364 <li>Constants are Values like anything else and can be operands of instructions</li>
365 <li>Integer constants, frequently needed can be created using the static "get"
366 methods of the ConstantInt, ConstantSInt, and ConstantUInt classes. The nice thing
367 about these is that you can "get" any kind of integer quickly.</li>
368 <li>There's a special method on Constant class which allows you to get the null
369 constant for <em>any</em> type. This is really handy for initializing large
370 arrays or structures, etc.</li>
371</ul>
372</div>
Brian Gaeke90181482003-11-24 02:52:51 +0000373<!-- ======================================================================= -->
374<div class="doc_section"> <a name="lexicon">The Stacker Lexicon</a></div>
Chris Lattnere46d6012003-11-25 01:35:06 +0000375<div class="doc_text"><p>This section describes the Stacker language</p></div>
Brian Gaeke90181482003-11-24 02:52:51 +0000376<div class="doc_subsection"><a name="stack"></a>The Stack</div>
377<div class="doc_text">
378<p>Stacker definitions define what they do to the global stack. Before
379proceeding, a few words about the stack are in order. The stack is simply
380a global array of 32-bit integers or pointers. A global index keeps track
Chris Lattnere46d6012003-11-25 01:35:06 +0000381of the location of the top of the stack. All of this is hidden from the
Brian Gaeke90181482003-11-24 02:52:51 +0000382programmer but it needs to be noted because it is the foundation of the
383conceptual programming model for Stacker. When you write a definition,
384you are, essentially, saying how you want that definition to manipulate
385the global stack.</p>
386<p>Manipulating the stack can be quite hazardous. There is no distinction
387given and no checking for the various types of values that can be placed
388on the stack. Automatic coercion between types is performed. In many
389cases this is useful. For example, a boolean value placed on the stack
390can be interpreted as an integer with good results. However, using a
391word that interprets that boolean value as a pointer to a string to
392print out will almost always yield a crash. Stacker simply leaves it
393to the programmer to get it right without any interference or hindering
Chris Lattnere46d6012003-11-25 01:35:06 +0000394on interpretation of the stack values. You've been warned. :) </p>
Brian Gaeke90181482003-11-24 02:52:51 +0000395</div>
396<!-- ======================================================================= -->
397<div class="doc_subsection"> <a name="punctuation"></a>Punctuation</div>
398<div class="doc_text">
399<p>Punctuation in Stacker is very simple. The colon and semi-colon
400characters are used to introduce and terminate a definition
401(respectively). Except for <em>FORWARD</em> declarations, definitions
402are all you can specify in Stacker. Definitions are read left to right.
Chris Lattnere46d6012003-11-25 01:35:06 +0000403Immediately after the colon comes the name of the word being defined.
404The remaining words in the definition specify what the word does. The definition
405is terminated by a semi-colon.</p>
406<p>So, your typical definition will have the form:</p>
407<pre><code>: name ... ;</code></pre>
408<p>The <code>name</code> is up to you but it must start with a letter and contain
409only letters numbers and underscore. Names are case sensitive and must not be
410the same as the name of a built-in word. The <code>...</code> is replaced by
411the stack manipulting words that you wish define <code>name</code> as. <p>
412</div>
413<!-- ======================================================================= -->
414<div class="doc_subsection"><a name="comments"></a>Comments</div>
415<div class="doc_text">
416 <p>Stacker supports two types of comments. A hash mark (#) starts a comment
417 that extends to the end of the line. It is identical to the kind of comments
418 commonly used in shell scripts. A pair of parentheses also surround a comment.
419 In both cases, the content of the comment is ignored by the Stacker compiler. The
420 following does nothing in Stacker.
421 </p>
422<pre><code>
423# This is a comment to end of line
424( This is an enclosed comment )
425</code></pre>
426<p>See the <a href="#example">example</a> program to see how this works in
427a real program.</p>
Brian Gaeke90181482003-11-24 02:52:51 +0000428</div>
429<!-- ======================================================================= -->
430<div class="doc_subsection"><a name="literals"></a>Literals</div>
431<div class="doc_text">
432 <p>There are three kinds of literal values in Stacker. Integer, Strings,
433 and Booleans. In each case, the stack operation is to simply push the
434 value onto the stack. So, for example:<br/>
435 <code> 42 " is the answer." TRUE </code><br/>
436 will push three values onto the stack: the integer 42, the
437 string " is the answer." and the boolean TRUE.</p>
438</div>
439<!-- ======================================================================= -->
440<div class="doc_subsection"><a name="words"></a>Words</div>
441<div class="doc_text">
442<p>Each definition in Stacker is composed of a set of words. Words are
443read and executed in order from left to right. There is very little
444checking in Stacker to make sure you're doing the right thing with
445the stack. It is assumed that the programmer knows how the stack
446transformation he applies will affect the program.</p>
447<p>Words in a definition come in two flavors: built-in and programmer
448defined. Simply mentioning the name of a previously defined or declared
Chris Lattnere46d6012003-11-25 01:35:06 +0000449programmer-defined word causes that word's definition to be invoked. It
Brian Gaeke90181482003-11-24 02:52:51 +0000450is somewhat like a function call in other languages. The built-in
451words have various effects, described below.</p>
452<p>Sometimes you need to call a word before it is defined. For this, you can
Chris Lattnere46d6012003-11-25 01:35:06 +0000453use the <code>FORWARD</code> declaration. It looks like this:</p>
Brian Gaeke90181482003-11-24 02:52:51 +0000454<p><code>FORWARD name ;</code></p>
455<p>This simply states to Stacker that "name" is the name of a definition
456that is defined elsewhere. Generally it means the definition can be found
457"forward" in the file. But, it doesn't have to be in the current compilation
458unit. Anything declared with <code>FORWARD</code> is an external symbol for
459linking.</p>
460</div>
461<!-- ======================================================================= -->
462<div class="doc_subsection"><a name="builtins"></a>Built In Words</div>
463<div class="doc_text">
464<p>The built-in words of the Stacker language are put in several groups
465depending on what they do. The groups are as follows:</p>
466<ol>
467 <li><em>Logical</em>These words provide the logical operations for
468 comparing stack operands.<br/>The words are: &lt; &gt; &lt;= &gt;=
469 = &lt;&gt; true false.</li>
470 <li><em>Bitwise</em>These words perform bitwise computations on
471 their operands. <br/> The words are: &lt;&lt; &gt;&gt; XOR AND NOT</li>
472 <li><em>Arithmetic</em>These words perform arithmetic computations on
473 their operands. <br/> The words are: ABS NEG + - * / MOD */ ++ -- MIN MAX</li>
474 <li><em>Stack</em>These words manipulate the stack directly by moving
475 its elements around.<br/> The words are: DROP DUP SWAP OVER ROT DUP2 DROP2 PICK TUCK</li>
Brian Gaeke07e89e42003-11-24 17:03:38 +0000476 <li><em>Memory</em>These words allocate, free and manipulate memory
Brian Gaeke90181482003-11-24 02:52:51 +0000477 areas outside the stack.<br/>The words are: MALLOC FREE GET PUT</li>
478 <li><em>Control</em>These words alter the normal left to right flow
479 of execution.<br/>The words are: IF ELSE ENDIF WHILE END RETURN EXIT RECURSE</li>
480 <li><em>I/O</em> These words perform output on the standard output
481 and input on the standard input. No other I/O is possible in Stacker.
482 <br/>The words are: SPACE TAB CR &gt;s &gt;d &gt;c &lt;s &lt;d &lt;c.</li>
483</ol>
484<p>While you may be familiar with many of these operations from other
485programming languages, a careful review of their semantics is important
486for correct programming in Stacker. Of most importance is the effect
487that each of these built-in words has on the global stack. The effect is
488not always intuitive. To better describe the effects, we'll borrow from Forth the idiom of
489describing the effect on the stack with:</p>
490<p><code> BEFORE -- AFTER </code></p>
491<p>That is, to the left of the -- is a representation of the stack before
492the operation. To the right of the -- is a representation of the stack
493after the operation. In the table below that describes the operation of
494each of the built in words, we will denote the elements of the stack
495using the following construction:</p>
496<ol>
497 <li><em>b</em> - a boolean truth value</li>
498 <li><em>w</em> - a normal integer valued word.</li>
499 <li><em>s</em> - a pointer to a string value</li>
Chris Lattnere46d6012003-11-25 01:35:06 +0000500 <li><em>p</em> - a pointer to a malloc'd memory block</li>
Brian Gaeke90181482003-11-24 02:52:51 +0000501</ol>
502</div>
503<div class="doc_text">
504<table class="doc_table" >
505<tr class="doc_table"><td colspan="4">Definition Of Operation Of Built In Words</td></tr>
506<tr class="doc_table"><td colspan="4">LOGICAL OPERATIONS</td></tr>
507<tr class="doc_table"><td>Word</td><td>Name</td><td>Operation</td><td>Description</td></tr>
508<tr class="doc_table"><td>&lt;</td>
509 <td>LT</td>
510 <td>w1 w2 -- b</td>
511 <td>Two values (w1 and w2) are popped off the stack and
512 compared. If w1 is less than w2, TRUE is pushed back on
513 the stack, otherwise FALSE is pushed back on the stack.</td>
514</tr>
515<tr><td>&gt;</td>
516 <td>GT</td>
517 <td>w1 w2 -- b</td>
518 <td>Two values (w1 and w2) are popped off the stack and
519 compared. If w1 is greater than w2, TRUE is pushed back on
520 the stack, otherwise FALSE is pushed back on the stack.</td>
521</tr>
522<tr><td>&gt;=</td>
523 <td>GE</td>
524 <td>w1 w2 -- b</td>
525 <td>Two values (w1 and w2) are popped off the stack and
526 compared. If w1 is greater than or equal to w2, TRUE is
527 pushed back on the stack, otherwise FALSE is pushed back
528 on the stack.</td>
529</tr>
530<tr><td>&lt;=</td>
531 <td>LE</td>
532 <td>w1 w2 -- b</td>
533 <td>Two values (w1 and w2) are popped off the stack and
534 compared. If w1 is less than or equal to w2, TRUE is
535 pushed back on the stack, otherwise FALSE is pushed back
536 on the stack.</td>
537</tr>
538<tr><td>=</td>
539 <td>EQ</td>
540 <td>w1 w2 -- b</td>
541 <td>Two values (w1 and w2) are popped off the stack and
542 compared. If w1 is equal to w2, TRUE is
543 pushed back on the stack, otherwise FALSE is pushed back
544 </td>
545</tr>
546<tr><td>&lt;&gt;</td>
547 <td>NE</td>
548 <td>w1 w2 -- b</td>
549 <td>Two values (w1 and w2) are popped off the stack and
550 compared. If w1 is equal to w2, TRUE is
551 pushed back on the stack, otherwise FALSE is pushed back
552 </td>
553</tr>
554<tr><td>FALSE</td>
555 <td>FALSE</td>
556 <td> -- b</td>
557 <td>The boolean value FALSE (0) is pushed onto the stack.</td>
558</tr>
559<tr><td>TRUE</td>
560 <td>TRUE</td>
561 <td> -- b</td>
562 <td>The boolean value TRUE (-1) is pushed onto the stack.</td>
563</tr>
564<tr><td colspan="4">BITWISE OPERATIONS</td></tr>
565<tr><td>Word</td><td>Name</td><td>Operation</td><td>Description</td></tr>
566<tr><td>&lt;&lt;</td>
567 <td>SHL</td>
568 <td>w1 w2 -- w1&lt;&lt;w2</td>
569 <td>Two values (w1 and w2) are popped off the stack. The w2
570 operand is shifted left by the number of bits given by the
571 w1 operand. The result is pushed back to the stack.</td>
572</tr>
573<tr><td>&gt;&gt;</td>
574 <td>SHR</td>
575 <td>w1 w2 -- w1&gt;&gt;w2</td>
576 <td>Two values (w1 and w2) are popped off the stack. The w2
577 operand is shifted right by the number of bits given by the
578 w1 operand. The result is pushed back to the stack.</td>
579</tr>
580<tr><td>OR</td>
581 <td>OR</td>
582 <td>w1 w2 -- w2|w1</td>
583 <td>Two values (w1 and w2) are popped off the stack. The values
584 are bitwise OR'd together and pushed back on the stack. This is
585 not a logical OR. The sequence 1 2 OR yields 3 not 1.</td>
586</tr>
587<tr><td>AND</td>
588 <td>AND</td>
589 <td>w1 w2 -- w2&amp;w1</td>
590 <td>Two values (w1 and w2) are popped off the stack. The values
591 are bitwise AND'd together and pushed back on the stack. This is
592 not a logical AND. The sequence 1 2 AND yields 0 not 1.</td>
593</tr>
594<tr><td>XOR</td>
595 <td>XOR</td>
596 <td>w1 w2 -- w2^w1</td>
597 <td>Two values (w1 and w2) are popped off the stack. The values
598 are bitwise exclusive OR'd together and pushed back on the stack.
599 For example, The sequence 1 3 XOR yields 2.</td>
600</tr>
601<tr><td colspan="4">ARITHMETIC OPERATIONS</td></tr>
602<tr><td>Word</td><td>Name</td><td>Operation</td><td>Description</td></tr>
603<tr><td>ABS</td>
604 <td>ABS</td>
605 <td>w -- |w|</td>
606 <td>One value s popped off the stack; its absolute value is computed
607 and then pushed onto the stack. If w1 is -1 then w2 is 1. If w1 is
608 1 then w2 is also 1.</td>
609</tr>
610<tr><td>NEG</td>
611 <td>NEG</td>
612 <td>w -- -w</td>
613 <td>One value is popped off the stack which is negated and then
614 pushed back onto the stack. If w1 is -1 then w2 is 1. If w1 is
615 1 then w2 is -1.</td>
616</tr>
617<tr><td> + </td>
618 <td>ADD</td>
619 <td>w1 w2 -- w2+w1</td>
620 <td>Two values are popped off the stack. Their sum is pushed back
621 onto the stack</td>
622</tr>
623<tr><td> - </td>
624 <td>SUB</td>
625 <td>w1 w2 -- w2-w1</td>
626 <td>Two values are popped off the stack. Their difference is pushed back
627 onto the stack</td>
628</tr>
629<tr><td> * </td>
630 <td>MUL</td>
631 <td>w1 w2 -- w2*w1</td>
632 <td>Two values are popped off the stack. Their product is pushed back
633 onto the stack</td>
634</tr>
635<tr><td> / </td>
636 <td>DIV</td>
637 <td>w1 w2 -- w2/w1</td>
638 <td>Two values are popped off the stack. Their quotient is pushed back
639 onto the stack</td>
640</tr>
641<tr><td>MOD</td>
642 <td>MOD</td>
643 <td>w1 w2 -- w2%w1</td>
644 <td>Two values are popped off the stack. Their remainder after division
645 of w1 by w2 is pushed back onto the stack</td>
646</tr>
647<tr><td> */ </td>
648 <td>STAR_SLAH</td>
649 <td>w1 w2 w3 -- (w3*w2)/w1</td>
650 <td>Three values are popped off the stack. The product of w1 and w2 is
651 divided by w3. The result is pushed back onto the stack.</td>
652</tr>
653<tr><td> ++ </td>
654 <td>INCR</td>
655 <td>w -- w+1</td>
656 <td>One value is popped off the stack. It is incremented by one and then
657 pushed back onto the stack.</td>
658</tr>
659<tr><td> -- </td>
660 <td>DECR</td>
661 <td>w -- w-1</td>
662 <td>One value is popped off the stack. It is decremented by one and then
663 pushed back onto the stack.</td>
664</tr>
665<tr><td>MIN</td>
666 <td>MIN</td>
667 <td>w1 w2 -- (w2&lt;w1?w2:w1)</td>
668 <td>Two values are popped off the stack. The larger one is pushed back
669 onto the stack.</td>
670</tr>
671<tr><td>MAX</td>
672 <td>MAX</td>
673 <td>w1 w2 -- (w2&gt;w1?w2:w1)</td>
674 <td>Two values are popped off the stack. The larger value is pushed back
675 onto the stack.</td>
676</tr>
677<tr><td colspan="4">STACK MANIPULATION OPERATIONS</td></tr>
678<tr><td>Word</td><td>Name</td><td>Operation</td><td>Description</td></tr>
679<tr><td>DROP</td>
680 <td>DROP</td>
681 <td>w -- </td>
682 <td>One value is popped off the stack.</td>
683</tr>
684<tr><td>DROP2</td>
685 <td>DROP2</td>
686 <td>w1 w2 -- </td>
687 <td>Two values are popped off the stack.</td>
688</tr>
689<tr><td>NIP</td>
690 <td>NIP</td>
691 <td>w1 w2 -- w2</td>
692 <td>The second value on the stack is removed from the stack. That is,
693 a value is popped off the stack and retained. Then a second value is
694 popped and the retained value is pushed.</td>
695</tr>
696<tr><td>NIP2</td>
697 <td>NIP2</td>
698 <td>w1 w2 w3 w4 -- w3 w4</td>
699 <td>The third and fourth values on the stack are removed from it. That is,
700 two values are popped and retained. Then two more values are popped and
701 the two retained values are pushed back on.</td>
702</tr>
703<tr><td>DUP</td>
704 <td>DUP</td>
705 <td>w1 -- w1 w1</td>
706 <td>One value is popped off the stack. That value is then pushed onto
707 the stack twice to duplicate the top stack vaue.</td>
708</tr>
709<tr><td>DUP2</td>
710 <td>DUP2</td>
711 <td>w1 w2 -- w1 w2 w1 w2</td>
712 <td>The top two values on the stack are duplicated. That is, two vaues
713 are popped off the stack. They are alternately pushed back on the
714 stack twice each.</td>
715</tr>
716<tr><td>SWAP</td>
717 <td>SWAP</td>
718 <td>w1 w2 -- w2 w1</td>
719 <td>The top two stack items are reversed in their order. That is, two
720 values are popped off the stack and pushed back onto the stack in
721 the opposite order they were popped.</td>
722</tr>
723<tr><td>SWAP2</td>
724 <td>SWAP2</td>
725 <td>w1 w2 w3 w4 -- w3 w4 w2 w1</td>
726 <td>The top four stack items are swapped in pairs. That is, two values
727 are popped and retained. Then, two more values are popped and retained.
728 The values are pushed back onto the stack in the reverse order but
729 in pairs.</p>
730</tr>
731<tr><td>OVER</td>
732 <td>OVER</td>
733 <td>w1 w2-- w1 w2 w1</td>
734 <td>Two values are popped from the stack. They are pushed back
735 onto the stack in the order w1 w2 w1. This seems to cause the
736 top stack element to be duplicated "over" the next value.</td>
737</tr>
738<tr><td>OVER2</td>
739 <td>OVER2</td>
740 <td>w1 w2 w3 w4 -- w1 w2 w3 w4 w1 w2</td>
741 <td>The third and fourth values on the stack are replicated onto the
742 top of the stack</td>
743</tr>
744<tr><td>ROT</td>
745 <td>ROT</td>
746 <td>w1 w2 w3 -- w2 w3 w1</td>
747 <td>The top three values are rotated. That is, three value are popped
748 off the stack. They are pushed back onto the stack in the order
749 w1 w3 w2.</td>
750</tr>
751<tr><td>ROT2</td>
752 <td>ROT2</td>
753 <td>w1 w2 w3 w4 w5 w6 -- w3 w4 w5 w6 w1 w2</td>
754 <td>Like ROT but the rotation is done using three pairs instead of
755 three singles.</td>
756</tr>
757<tr><td>RROT</td>
758 <td>RROT</td>
759 <td>w1 w2 w3 -- w2 w3 w1</td>
760 <td>Reverse rotation. Like ROT, but it rotates the other way around.
761 Essentially, the third element on the stack is moved to the top
762 of the stack.</td>
763</tr>
764<tr><td>RROT2</td>
765 <td>RROT2</td>
766 <td>w1 w2 w3 w4 w5 w6 -- w3 w4 w5 w6 w1 w2</td>
767 <td>Double reverse rotation. Like RROT but the rotation is done using
768 three pairs instead of three singles. The fifth and sixth stack
769 elements are moved to the first and second positions</td>
770</tr>
771<tr><td>TUCK</td>
772 <td>TUCK</td>
773 <td>w1 w2 -- w2 w1 w2</td>
774 <td>Similar to OVER except that the second operand is being
775 replicated. Essentially, the first operand is being "tucked"
776 in between two instances of the second operand. Logically, two
777 values are popped off the stack. They are placed back on the
778 stack in the order w2 w1 w2.</td>
779</tr>
780<tr><td>TUCK2</td>
781 <td>TUCK2</td>
782 <td>w1 w2 w3 w4 -- w3 w4 w1 w2 w3 w4</td>
783 <td>Like TUCK but a pair of elements is tucked over two pairs.
784 That is, the top two elements of the stack are duplicated and
785 inserted into the stack at the fifth and positions.</td>
786</tr>
787<tr><td>PICK</td>
788 <td>PICK</td>
789 <td>x0 ... Xn n -- x0 ... Xn x0</td>
790 <td>The top of the stack is used as an index into the remainder of
791 the stack. The element at the nth position replaces the index
792 (top of stack). This is useful for cycling through a set of
793 values. Note that indexing is zero based. So, if n=0 then you
794 get the second item on the stack. If n=1 you get the third, etc.
795 Note also that the index is replaced by the n'th value. </td>
796</tr>
797<tr><td>SELECT</td>
798 <td>SELECT</td>
799 <td>m n X0..Xm Xm+1 .. Xn -- Xm</td>
800 <td>This is like PICK but the list is removed and you need to specify
801 both the index and the size of the list. Careful with this one,
802 the wrong value for n can blow away a huge amount of the stack.</td>
803</tr>
804<tr><td>ROLL</td>
805 <td>ROLL</td>
806 <td>x0 x1 .. xn n -- x1 .. xn x0</td>
807 <td><b>Not Implemented</b>. This one has been left as an exercise to
Chris Lattnere46d6012003-11-25 01:35:06 +0000808 the student. See <a href="#exercise">Exercise</a>. ROLL requires
809 a value, "n", to be on the top of the stack. This value specifies how
810 far into the stack to "roll". The n'th value is <em>moved</em> (not
811 copied) from its location and replaces the "n" value on the top of the
812 stack. In this way, all the values between "n" and x0 roll up the stack.
813 The operation of ROLL is a generalized ROT. The "n" value specifies
814 how much to rotate. That is, ROLL with n=1 is the same as ROT and
815 ROLL with n=2 is the same as ROT2.</td>
Brian Gaeke90181482003-11-24 02:52:51 +0000816</tr>
817<tr><td colspan="4">MEMORY OPERATIONS</td></tr>
818<tr><td>Word</td><td>Name</td><td>Operation</td><td>Description</td></tr>
819<tr><td>MALLOC</td>
820 <td>MALLOC</td>
821 <td>w1 -- p</td>
822 <td>One value is popped off the stack. The value is used as the size
823 of a memory block to allocate. The size is in bytes, not words.
824 The memory allocation is completed and the address of the memory
825 block is pushed onto the stack.</td>
826</tr>
827<tr><td>FREE</td>
828 <td>FREE</td>
829 <td>p -- </td>
830 <td>One pointer value is popped off the stack. The value should be
831 the address of a memory block created by the MALLOC operation. The
832 associated memory block is freed. Nothing is pushed back on the
833 stack. Many bugs can be created by attempting to FREE something
834 that isn't a pointer to a MALLOC allocated memory block. Make
835 sure you know what's on the stack. One way to do this is with
836 the following idiom:<br/>
837 <code>64 MALLOC DUP DUP (use ptr) DUP (use ptr) ... FREE</code>
838 <br/>This ensures that an extra copy of the pointer is placed on
839 the stack (for the FREE at the end) and that every use of the
840 pointer is preceded by a DUP to retain the copy for FREE.</td>
841</tr>
842<tr><td>GET</td>
843 <td>GET</td>
844 <td>w1 p -- w2 p</td>
845 <td>An integer index and a pointer to a memory block are popped of
846 the block. The index is used to index one byte from the memory
847 block. That byte value is retained, the pointer is pushed again
848 and the retained value is pushed. Note that the pointer value
849 s essentially retained in its position so this doesn't count
850 as a "use ptr" in the FREE idiom.</td>
851</tr>
852<tr><td>PUT</td>
853 <td>PUT</td>
854 <td>w1 w2 p -- p </td>
855 <td>An integer value is popped of the stack. This is the value to
856 be put into a memory block. Another integer value is popped of
857 the stack. This is the indexed byte in the memory block. A
858 pointer to the memory block is popped off the stack. The
859 first value (w1) is then converted to a byte and written
860 to the element of the memory block(p) at the index given
861 by the second value (w2). The pointer to the memory block is
862 pushed back on the stack so this doesn't count as a "use ptr"
863 in the FREE idiom.</td>
864</tr>
865<tr><td colspan="4">CONTROL FLOW OPERATIONS</td></tr>
866<tr><td>Word</td><td>Name</td><td>Operation</td><td>Description</td></tr>
867<tr><td>RETURN</td>
868 <td>RETURN</td>
869 <td> -- </td>
870 <td>The currently executing definition returns immediately to its caller.
871 Note that there is an implicit <code>RETURN</code> at the end of each
872 definition, logically located at the semi-colon. The sequence
873 <code>RETURN ;</code> is valid but redundant.</td>
874</tr>
875<tr><td>EXIT</td>
876 <td>EXIT</td>
877 <td>w1 -- </td>
878 <td>A return value for the program is popped off the stack. The program is
879 then immediately terminated. This is normally an abnormal exit from the
880 program. For a normal exit (when <code>MAIN</code> finishes), the exit
881 code will always be zero in accordance with UNIX conventions.</td>
882</tr>
883<tr><td>RECURSE</td>
884 <td>RECURSE</td>
885 <td> -- </td>
886 <td>The currently executed definition is called again. This operation is
887 needed since the definition of a word doesn't exist until the semi colon
888 is reacher. Attempting something like:<br/>
889 <code> : recurser recurser ; </code><br/> will yield and error saying that
890 "recurser" is not defined yet. To accomplish the same thing, change this
891 to:<br/>
892 <code> : recurser RECURSE ; </code></td>
893</tr>
894<tr><td>IF (words...) ENDIF</td>
895 <td>IF (words...) ENDIF</td>
896 <td>b -- </td>
897 <td>A boolean value is popped of the stack. If it is non-zero then the "words..."
898 are executed. Otherwise, execution continues immediately following the ENDIF.</td>
899</tr>
900<tr><td>IF (words...) ELSE (words...) ENDIF</td>
901 <td>IF (words...) ELSE (words...) ENDIF</td>
902 <td>b -- </td>
903 <td>A boolean value is popped of the stack. If it is non-zero then the "words..."
904 between IF and ELSE are executed. Otherwise the words between ELSE and ENDIF are
905 executed. In either case, after the (words....) have executed, execution continues
906 immediately following the ENDIF. </td>
907</tr>
908<tr><td>WHILE (words...) END</td>
909 <td>WHILE (words...) END</td>
910 <td>b -- b </td>
911 <td>The boolean value on the top of the stack is examined. If it is non-zero then the
912 "words..." between WHILE and END are executed. Execution then begins again at the WHILE where another
913 boolean is popped off the stack. To prevent this operation from eating up the entire
914 stack, you should push onto the stack (just before the END) a boolean value that indicates
915 whether to terminate. Note that since booleans and integers can be coerced you can
916 use the following "for loop" idiom:<br/>
917 <code>(push count) WHILE (words...) -- END</code><br/>
918 For example:<br/>
919 <code>10 WHILE DUP &gt;d -- END</code><br/>
920 This will print the numbers from 10 down to 1. 10 is pushed on the stack. Since that is
921 non-zero, the while loop is entered. The top of the stack (10) is duplicated and then
922 printed out with &gt;d. The top of the stack is decremented, yielding 9 and control is
923 transfered back to the WHILE keyword. The process starts all over again and repeats until
924 the top of stack is decremented to 0 at which the WHILE test fails and control is
925 transfered to the word after the END.</td>
926</tr>
927<tr><td colspan="4">INPUT &amp; OUTPUT OPERATIONS</td></tr>
928<tr><td>Word</td><td>Name</td><td>Operation</td><td>Description</td></tr>
929<tr><td>SPACE</td>
930 <td>SPACE</td>
931 <td> -- </td>
932 <td>A space character is put out. There is no stack effect.</td>
933</tr>
934<tr><td>TAB</td>
935 <td>TAB</td>
936 <td> -- </td>
937 <td>A tab character is put out. There is no stack effect.</td>
938</tr>
939<tr><td>CR</td>
940 <td>CR</td>
941 <td> -- </td>
942 <td>A carriage return character is put out. There is no stack effect.</td>
943</tr>
944<tr><td>&gt;s</td>
945 <td>OUT_STR</td>
946 <td> -- </td>
947 <td>A string pointer is popped from the stack. It is put out.</td>
948</tr>
949<tr><td>&gt;d</td>
950 <td>OUT_STR</td>
951 <td> -- </td>
952 <td>A value is popped from the stack. It is put out as a decimal integer.</td>
953</tr>
954<tr><td>&gt;c</td>
955 <td>OUT_CHR</td>
956 <td> -- </td>
957 <td>A value is popped from the stack. It is put out as an ASCII character.</td>
958</tr>
959<tr><td>&lt;s</td>
960 <td>IN_STR</td>
961 <td> -- s </td>
962 <td>A string is read from the input via the scanf(3) format string " %as". The
963 resulting string is pushed onto the stack.</td>
964</tr>
965<tr><td>&lt;d</td>
966 <td>IN_STR</td>
967 <td> -- w </td>
968 <td>An integer is read from the input via the scanf(3) format string " %d". The
969 resulting value is pushed onto the stack</td>
970</tr>
971<tr><td>&lt;c</td>
972 <td>IN_CHR</td>
973 <td> -- w </td>
974 <td>A single character is read from the input via the scanf(3) format string
975 " %c". The value is converted to an integer and pushed onto the stack.</td>
976</tr>
977<tr><td>DUMP</td>
978 <td>DUMP</td>
979 <td> -- </td>
980 <td>The stack contents are dumped to standard output. This is useful for
981 debugging your definitions. Put DUMP at the beginning and end of a definition
982 to see instantly the net effect of the definition.</td>
983</tr>
984</table>
985</div>
986<!-- ======================================================================= -->
Brian Gaeke07e89e42003-11-24 17:03:38 +0000987<div class="doc_section"> <a name="example">Prime: A Complete Example</a></div>
Brian Gaeke90181482003-11-24 02:52:51 +0000988<div class="doc_text">
Brian Gaeke07e89e42003-11-24 17:03:38 +0000989<p>The following fully documented program highlights many features of both
990the Stacker language and what is possible with LLVM. The program has two modes
991of operations. If you provide numeric arguments to the program, it checks to see
992if those arguments are prime numbers, prints out the results. Without any
993aruments, the program prints out any prime numbers it finds between 1 and one
994million (there's a log of them!). The source code comments below tell the
995remainder of the story.
Brian Gaeke90181482003-11-24 02:52:51 +0000996</p>
997</div>
998<div class="doc_text">
Brian Gaeke07e89e42003-11-24 17:03:38 +0000999<pre><code>
Brian Gaeke90181482003-11-24 02:52:51 +00001000################################################################################
1001#
1002# Brute force prime number generator
1003#
1004# This program is written in classic Stacker style, that being the style of a
1005# stack. Start at the bottom and read your way up !
1006#
1007# Reid Spencer - Nov 2003
1008################################################################################
1009# Utility definitions
1010################################################################################
1011: print >d CR ;
1012: it_is_a_prime TRUE ;
1013: it_is_not_a_prime FALSE ;
1014: continue_loop TRUE ;
1015: exit_loop FALSE;
1016
1017################################################################################
1018# This definition tryies an actual division of a candidate prime number. It
1019# determines whether the division loop on this candidate should continue or
1020# not.
1021# STACK<:
1022# div - the divisor to try
1023# p - the prime number we are working on
1024# STACK>:
1025# cont - should we continue the loop ?
1026# div - the next divisor to try
1027# p - the prime number we are working on
1028################################################################################
1029: try_dividing
1030 DUP2 ( save div and p )
1031 SWAP ( swap to put divisor second on stack)
1032 MOD 0 = ( get remainder after division and test for 0 )
1033 IF
1034 exit_loop ( remainder = 0, time to exit )
1035 ELSE
1036 continue_loop ( remainder != 0, keep going )
1037 ENDIF
1038;
1039
1040################################################################################
1041# This function tries one divisor by calling try_dividing. But, before doing
1042# that it checks to see if the value is 1. If it is, it does not bother with
1043# the division because prime numbers are allowed to be divided by one. The
1044# top stack value (cont) is set to determine if the loop should continue on
1045# this prime number or not.
1046# STACK<:
1047# cont - should we continue the loop (ignored)?
1048# div - the divisor to try
1049# p - the prime number we are working on
1050# STACK>:
1051# cont - should we continue the loop ?
1052# div - the next divisor to try
1053# p - the prime number we are working on
1054################################################################################
1055: try_one_divisor
1056 DROP ( drop the loop continuation )
1057 DUP ( save the divisor )
1058 1 = IF ( see if divisor is == 1 )
1059 exit_loop ( no point dividing by 1 )
1060 ELSE
1061 try_dividing ( have to keep going )
1062 ENDIF
1063 SWAP ( get divisor on top )
1064 -- ( decrement it )
1065 SWAP ( put loop continuation back on top )
1066;
1067
1068################################################################################
1069# The number on the stack (p) is a candidate prime number that we must test to
1070# determine if it really is a prime number. To do this, we divide it by every
1071# number from one p-1 to 1. The division is handled in the try_one_divisor
1072# definition which returns a loop continuation value (which we also seed with
1073# the value 1). After the loop, we check the divisor. If it decremented all
1074# the way to zero then we found a prime, otherwise we did not find one.
1075# STACK<:
1076# p - the prime number to check
1077# STACK>:
1078# yn - boolean indiating if its a prime or not
1079# p - the prime number checked
1080################################################################################
1081: try_harder
1082 DUP ( duplicate to get divisor value ) )
1083 -- ( first divisor is one less than p )
1084 1 ( continue the loop )
1085 WHILE
1086 try_one_divisor ( see if its prime )
1087 END
1088 DROP ( drop the continuation value )
1089 0 = IF ( test for divisor == 1 )
1090 it_is_a_prime ( we found one )
1091 ELSE
1092 it_is_not_a_prime ( nope, this one is not a prime )
1093 ENDIF
1094;
1095
1096################################################################################
1097# This definition determines if the number on the top of the stack is a prime
1098# or not. It does this by testing if the value is degenerate (<= 3) and
1099# responding with yes, its a prime. Otherwise, it calls try_harder to actually
1100# make some calculations to determine its primeness.
1101# STACK<:
1102# p - the prime number to check
1103# STACK>:
1104# yn - boolean indicating if its a prime or not
1105# p - the prime number checked
1106################################################################################
1107: is_prime
1108 DUP ( save the prime number )
1109 3 >= IF ( see if its <= 3 )
1110 it_is_a_prime ( its <= 3 just indicate its prime )
1111 ELSE
1112 try_harder ( have to do a little more work )
1113 ENDIF
1114;
1115
1116################################################################################
1117# This definition is called when it is time to exit the program, after we have
1118# found a sufficiently large number of primes.
1119# STACK<: ignored
1120# STACK>: exits
1121################################################################################
1122: done
1123 "Finished" >s CR ( say we are finished )
1124 0 EXIT ( exit nicely )
1125;
1126
1127################################################################################
1128# This definition checks to see if the candidate is greater than the limit. If
1129# it is, it terminates the program by calling done. Otherwise, it increments
1130# the value and calls is_prime to determine if the candidate is a prime or not.
1131# If it is a prime, it prints it. Note that the boolean result from is_prime is
1132# gobbled by the following IF which returns the stack to just contining the
1133# prime number just considered.
1134# STACK<:
1135# p - one less than the prime number to consider
1136# STACK>
1137# p+1 - the prime number considered
1138################################################################################
1139: consider_prime
1140 DUP ( save the prime number to consider )
1141 1000000 < IF ( check to see if we are done yet )
1142 done ( we are done, call "done" )
1143 ENDIF
1144 ++ ( increment to next prime number )
1145 is_prime ( see if it is a prime )
1146 IF
1147 print ( it is, print it )
1148 ENDIF
1149;
1150
1151################################################################################
1152# This definition starts at one, prints it out and continues into a loop calling
1153# consider_prime on each iteration. The prime number candidate we are looking at
1154# is incremented by consider_prime.
1155# STACK<: empty
1156# STACK>: empty
1157################################################################################
1158: find_primes
1159 "Prime Numbers: " >s CR ( say hello )
1160 DROP ( get rid of that pesky string )
1161 1 ( stoke the fires )
1162 print ( print the first one, we know its prime )
1163 WHILE ( loop while the prime to consider is non zero )
1164 consider_prime ( consider one prime number )
1165 END
1166;
1167
1168################################################################################
1169#
1170################################################################################
1171: say_yes
1172 >d ( Print the prime number )
1173 " is prime." ( push string to output )
1174 >s ( output it )
1175 CR ( print carriage return )
1176 DROP ( pop string )
1177;
1178
1179: say_no
1180 >d ( Print the prime number )
1181 " is NOT prime." ( push string to put out )
1182 >s ( put out the string )
1183 CR ( print carriage return )
1184 DROP ( pop string )
1185;
1186
1187################################################################################
1188# This definition processes a single command line argument and determines if it
1189# is a prime number or not.
1190# STACK<:
1191# n - number of arguments
1192# arg1 - the prime numbers to examine
1193# STACK>:
1194# n-1 - one less than number of arguments
1195# arg2 - we processed one argument
1196################################################################################
1197: do_one_argument
1198 -- ( decrement loop counter )
1199 SWAP ( get the argument value )
1200 is_prime IF ( determine if its prime )
1201 say_yes ( uhuh )
1202 ELSE
1203 say_no ( nope )
1204 ENDIF
1205 DROP ( done with that argument )
1206;
1207
1208################################################################################
1209# The MAIN program just prints a banner and processes its arguments.
1210# STACK<:
1211# n - number of arguments
1212# ... - the arguments
1213################################################################################
1214: process_arguments
1215 WHILE ( while there are more arguments )
1216 do_one_argument ( process one argument )
1217 END
1218;
1219
1220################################################################################
1221# The MAIN program just prints a banner and processes its arguments.
1222# STACK<: arguments
1223################################################################################
1224: MAIN
1225 NIP ( get rid of the program name )
1226 -- ( reduce number of arguments )
1227 DUP ( save the arg counter )
1228 1 <= IF ( See if we got an argument )
1229 process_arguments ( tell user if they are prime )
1230 ELSE
1231 find_primes ( see how many we can find )
1232 ENDIF
1233 0 ( push return code )
1234;
Brian Gaeke90181482003-11-24 02:52:51 +00001235</code>
Brian Gaeke07e89e42003-11-24 17:03:38 +00001236</pre>
Brian Gaeke90181482003-11-24 02:52:51 +00001237</div>
1238<!-- ======================================================================= -->
Brian Gaeke07e89e42003-11-24 17:03:38 +00001239<div class="doc_section"> <a name="internal">Internals</a></div>
1240<div class="doc_text">
1241 <p><b>This section is under construction.</b>
1242 <p>In the mean time, you can always read the code! It has comments!</p>
1243</div>
1244<!-- ======================================================================= -->
1245<div class="doc_subsection"> <a name="directory">Directory Structure</a></div>
1246<div class="doc_text">
1247<p>The source code, test programs, and sample programs can all be found
1248under the LLVM "projects" directory. You will need to obtain the LLVM sources
1249to find it (either via anonymous CVS or a tarball. See the
1250<a href="GettingStarted.html">Getting Started</a> document).</p>
1251<p>Under the "projects" directory there is a directory named "stacker". That
1252directory contains everything, as follows:</p>
1253<ul>
1254 <li><em>lib</em> - contains most of the source code
1255 <ul>
1256 <li><em>lib/compiler</em> - contains the compiler library
1257 <li><em>lib/runtime</em> - contains the runtime library
1258 </ul></li>
1259 <li><em>test</em> - contains the test programs</li>
1260 <li><em>tools</em> - contains the Stacker compiler main program, stkrc
1261 <ul>
1262 <li><em>lib/stkrc</em> - contains the Stacker compiler main program
1263 </ul</li>
1264 <li><em>sample</em> - contains the sample programs</li>
1265</ul>
1266</div>
1267<!-- ======================================================================= -->
1268<div class="doc_subsection"><a name="lexer"></a>The Lexer</div>
1269<div class="doc_text">
1270<p>See projects/Stacker/lib/compiler/Lexer.l</p>
1271</p></div>
1272<!-- ======================================================================= -->
1273<div class="doc_subsection"><a name="parser"></a>The Parser</div>
1274<div class="doc_text">
1275<p>See projects/Stacker/lib/compiler/StackerParser.y</p>
1276</p></div>
1277<!-- ======================================================================= -->
1278<div class="doc_subsection"><a name="compiler"></a>The Compiler</div>
1279<div class="doc_text">
1280<p>See projects/Stacker/lib/compiler/StackerCompiler.cpp</p>
1281</p></div>
1282<!-- ======================================================================= -->
1283<div class="doc_subsection"><a name="runtime"></a>The Runtime</div>
1284<div class="doc_text">
1285<p>See projects/Stacker/lib/runtime/stacker_rt.c</p>
1286</p></div>
1287<!-- ======================================================================= -->
1288<div class="doc_subsection"><a name="driver"></a>Compiler Driver</div>
1289<div class="doc_text">
1290<p>See projects/Stacker/tools/stkrc/stkrc.cpp</p>
1291</p></div>
1292<!-- ======================================================================= -->
1293<div class="doc_subsection"><a name="tests"></a>Test Programs</div>
1294<div class="doc_text">
1295<p>See projects/Stacker/test/*.st</p>
1296</p></div>
Brian Gaeke90181482003-11-24 02:52:51 +00001297<!-- ======================================================================= -->
Chris Lattnere46d6012003-11-25 01:35:06 +00001298<div class="doc_subsection"> <a name="exercise">Exercise</a></div>
1299<div class="doc_text">
1300<p>As you may have noted from a careful inspection of the Built-In word
1301definitions, the ROLL word is not implemented. This word was left out of
1302Stacker on purpose so that it can be an exercise for the student. The exercise
1303is to implement the ROLL functionality (in your own workspace) and build a test
1304program for it. If you can implement ROLL you understand Stacker and probably
1305a fair amount about LLVM since this is one of the more complicated Stacker
1306operations. The work will almost be completely limited to the
1307<a href="#compiler">compiler</a>.
1308<p>The ROLL word is already recognized by both the lexer and parser but ignored
1309by the compiler. That means you don't have to futz around with figuring out how
1310to get the keyword recognized. It already is. The part of the compiler that
1311you need to implement is the <code>ROLL</code> case in the
1312<code>StackerCompiler::handle_word(int)</code> method.</p> See the implementations
1313of PICk and SELECT in the same method to get some hints about how to complete
1314this exercise.<p>
1315<p>Good luck!</p>
1316</div>
1317<!-- ======================================================================= -->
1318<div class="doc_subsection"> <a name="todo">Things Remaining To Be Done</a></div>
1319<div class="doc_text">
1320<p>The initial implementation of Stacker has several deficiencies. If you're
1321interested, here are some things that could be implemented better:</p>
1322<ol>
1323 <li>Write an LLVM pass to compute the correct stack depth needed by the
1324 program.</li>
1325 <li>Write an LLVM pass to optimize the use of the global stack. The code
1326 emitted currently is somewhat wasteful. It gets cleaned up a lot by existing
1327 passes but more could be done.</li>
1328 <li>Add -O -O1 -O2 and -O3 optimization switches to the compiler driver to
1329 allow LLVM optimization without using "opt"</li>
1330 <li>Make the compiler driver use the LLVM linking facilities (with IPO) before
1331 depending on GCC to do the final link.</li>
1332 <li>Clean up parsing. It doesn't handle errors very well.</li>
1333 <li>Rearrange the StackerCompiler.cpp code to make better use of inserting
1334 instructions before a block's terminating instruction. I didn't figure this
1335 technique out until I was nearly done with LLVM. As it is, its a bad example
1336 of how to insert instructions!</li>
1337 <li>Provide for I/O to arbitrary files instead of just stdin/stdout.</li>
1338 <li>Write additional built-in words.</li>
1339 <li>Write additional sample Stacker programs.</li>
1340 <li>Add your own compiler writing experiences and tips in the <a href="lessons">
1341 Lessons I Learned About LLVM</a> section.</li>
1342</ol>
1343</div>
1344<!-- ======================================================================= -->
Brian Gaeke90181482003-11-24 02:52:51 +00001345<hr>
1346<div class="doc_footer">
1347<address><a href="mailto:rspencer@x10sys.com">Reid Spencer</a></address>
1348<a href="http://llvm.cs.uiuc.edu">The LLVM Compiler Infrastructure</a>
1349<br>Last modified: $Date$ </div>
1350</body>
1351</html>