-
Notifications
You must be signed in to change notification settings - Fork 2
/
BrainF**k.html
1717 lines (1302 loc) · 54.7 KB
/
BrainF**k.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
<style>
h1,
h2,
h3,
h4,
h5,
h6,
p,
blockquote {
margin: 0;
padding: 0;
}
body {
font-family: "Helvetica Neue", Helvetica, "Hiragino Sans GB", Arial, sans-serif;
font-size: 13px;
line-height: 18px;
color: #737373;
background-color: white;
margin: 10px 13px 10px 13px;
}
table {
margin: 10px 0 15px 0;
border-collapse: collapse;
}
td,th {
border: 1px solid #ddd;
padding: 3px 10px;
}
th {
padding: 5px 10px;
}
a {
color: #0069d6;
}
a:hover {
color: #0050a3;
text-decoration: none;
}
a img {
border: none;
}
p {
margin-bottom: 9px;
}
h1,
h2,
h3,
h4,
h5,
h6 {
color: #404040;
line-height: 36px;
}
h1 {
margin-bottom: 18px;
font-size: 30px;
}
h2 {
font-size: 24px;
}
h3 {
font-size: 18px;
}
h4 {
font-size: 16px;
}
h5 {
font-size: 14px;
}
h6 {
font-size: 13px;
}
hr {
margin: 0 0 19px;
border: 0;
border-bottom: 1px solid #ccc;
}
blockquote {
padding: 13px 13px 21px 15px;
margin-bottom: 18px;
font-family:georgia,serif;
font-style: italic;
}
blockquote:before {
content:"\201C";
font-size:40px;
margin-left:-10px;
font-family:georgia,serif;
color:#eee;
}
blockquote p {
font-size: 14px;
font-weight: 300;
line-height: 18px;
margin-bottom: 0;
font-style: italic;
}
code, pre {
font-family: Monaco, Andale Mono, Courier New, monospace;
}
code {
background-color: #fee9cc;
color: rgba(0, 0, 0, 0.75);
padding: 1px 3px;
font-size: 12px;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
}
pre {
display: block;
padding: 14px;
margin: 0 0 18px;
line-height: 16px;
font-size: 11px;
border: 1px solid #d9d9d9;
white-space: pre-wrap;
word-wrap: break-word;
}
pre code {
background-color: #fff;
color:#737373;
font-size: 11px;
padding: 0;
}
sup {
font-size: 0.83em;
vertical-align: super;
line-height: 0;
}
* {
-webkit-print-color-adjust: exact;
}
@media screen and (min-width: 914px) {
body {
width: 854px;
margin:10px auto;
}
}
@media print {
body,code,pre code,h1,h2,h3,h4,h5,h6 {
color: black;
}
table, pre {
page-break-inside: avoid;
}
}
</style>
<title>BrainF**k compiler with LLVM</title>
</head>
<body>
<h1>BrainF**k with LLVM</h1>
<h2>Introduction</h2>
<p>Let's write a compiler using LLVM. Since LLVM (Low Level Virtual Memory) manages the generation and the execution of native binary code, we only need to focus on the part that read our program source code and makes all LLVM API calls.</p>
<p><a href="http://esolangs.org/wiki/brainfuck">BrainF**k</a> is a good introduction to compiler programmation because it use much of basic tools of LLVM API, needed to create more complex compiler.</p>
<h2>BrainF**k</h2>
<p>BrainF**k language is very easy: the internal structure is composed of an array of cells and a cursor. The cursor allows to access (read or write) a cell and each cell contains a number (basically from 0, by default, to 255, to be output as ASCII).</p>
<p>You've got 8 operations:</p>
<pre>
'<' and '>' to move the cursor to access another cell (move to left and right)
'+' and '-' to change the value of the current cell, where the cursor stands (to increment and decrement)
',' and '.' to input (ask the user a value to set) and to output (print the value) the current cell
'[' and ']' to do conditional looping depending of the current cell value (enter the loop the current celle value > 0 and exit if it equals to 0)
</pre>
<p>For example, this dummy program:</p>
<pre>
>><+++<++>--[->+<]>.
</pre>
<p>will gives the output: 1</p>
<p>The state of cells and cursor at the end of the execution is:</p>
<pre>
cells : [2][0][1]
cursor: ^
</pre>
<p>Detailled operations:</p>
<pre>
>> : set cursor to 0 + 2 = 2
< : set cursor to 2 - 1 = 1
+++ : add 3 to current cell value ([1] = 3)
< : set cursor to 1 - 1 = 0
++ : add 2 to current cell value ([0] = 2)
> : set cursor to 0 + 1 = 1
-- : subtract 2 to current cell value ([1] = 3 - 2 = 1)
[ : enter the loop since the current cell value > 0 ([1] = 1)
- : subtract 1 to current cell value ([1] = 1 - 1 = 0)
> : set cursor to 1 + 1 = 2
+ : add 2 to current cell value ([2] = 0 + 1 = 1)
< : set cursor to 1 - 1 = 1
] : exit the loop since the current cell value is 0
> : set cursor to 1 + 1 = 2
. : print the current cell value ([2] = 1)
</pre>
<h2>Compiler & LLVM</h2>
<p>The definition of a compiler is a program that transform a format of file to another. For example, XSD allows to transform XML to HTML, Dart compiler to transform Dart script to Javascript, etc. In our case, we want our compiler to transform BrainF**k files to native code, for x86, ARM or else.</p>
<p>For flexibility reasons, we compile (transform) our BF file to an intermediate language (much lower level) and LLVM compiles this to assembler, which once linked, gives native binary. Hopefully, most works are done by LLVM like assembler generation, we only need to compile our input file to this intermediate language, called <em>Intermediate Representation</em>. This kind of compiler is called a <em>front-end</em> for LLVM (generate IR form input file). The compiler which generate assembler from IR is called a <em>back-end</em>.</p>
<p>Intermediate language allows low-level optimisations and is totally <em>platform independent</em>, so this representation program will be exactly the same even if you want to generate binary code to x86, ARM or Sparc architecture. Basically, intermediate language allows memory operation (allocation, reading and writing data from/to memory), arithmetic operation (add, mul, xor, etc.), basic data structure (c-like struct and array) and integration to external c-function (printf, scanf, etc.).</p>
<pre>
|-- Front-end --| |-- Back-end --|
[Source code] -> [Parser] --- LLVM API --> [IR (Intermediate Representation)] -> [Compilation] -> [Native binary] -> [Execution] -> [Output]
|-- LLVM (Low Level Virtual Machine) --|
</pre>
<p>For example, <em>clang</em> (C/C++ compiler based on LLVM) will follow this schema:</p>
<pre>
|- clang -|
[C/C++ code source] -> [Parser] -> [IR] -> [Compilation] -> [Native binary] -> [Execution] -> [Output]
|-- hello.c --| |-- $ clang hello.c -o hello --| |-- $ ./hello --|
</pre>
<p>As LLVM is a "Virtual Machine", it also can execute code without to generate native binary, following this schema:</p>
<pre>
|-- Front-end --|
[Source code] -> [Parser] --- LLVM API --> [IR (Intermediate Representation)] -> [Execution] -> [Output]
|-- LLVM (Low Level Virtual Machine) --|
</pre>
<p>The performance are the same that a native binary, it's just a convenient way to execute native code without to export a binary. You can choose, once the IR generate from your compiler, to execute native code from the Virtual Machine or to export native binary.</p>
<h2>Installation</h2>
<p>Simply, to install the lasted version of LLVM with git:</p>
<pre>
$ git clone http://llvm.org/git/llvm.git
$ cd llvm/
$ ./configure
$ sudo make install
</pre>
<p>More informations on <a href="http://llvm.org/docs/GettingStarted.html#git-mirror">installation wiki</a>.</p>
<h2>BF Parser</h2>
<p>First, we need to get <em>tokens</em> from our BF program. We will ignore (skip) all characters that are not BF commands (note that we use char, not string):</p>
<pre>
bool Parser::isSkipable(char c)
{
return (c != '<' && c != '>' &&
c != '+' && c != '-' &&
c != '.' && c != ',' &&
c != '[' && c != ']');
}
</pre>
<p>The method <code>getToken</code> returns the next valid character (token).</p>
<p>The <code>while</code> loop will stop when <code>c</code> will be equal to zero, and since the last character of <code>_data</code> (at index <code>index</code>) is zero (null-character terminated string), the method will stop when it reaches the end of the string.</p>
<p>Since we want to skip ignored character, the <code>while</code> will loop until a non-ignored character is found (or the end of the string).</p>
<pre>
char Parser::getToken()
{
char c = 0;
while ( (c = _data[_index++]) && isSkipable(c) ) { }
return c;
}
</pre>
<p>Note: the <code>while ( (var = value) ) { }</code> pattern is common, it's a shorter way to do:</p>
<pre>
while (1) {
var = value;
if (var == 0) {
break;
}
}
</pre>
<p>Note the extra parenthesis <code>(var = value)</code>, this not evaluates the assignment (always true) but the value of the variable assigned, <code>var</code> in this case; if <code>var</code> is greater than zero, the <code>while</code> loop continues to loop. A warning (with <code>-Wall</code>) shows up if the extra parenthesis are missing.</p>
<p>Now, we can create our parser class:</p>
<pre>
class Parser
{
protected:
string _data;
int _index;
static bool isSkipable(char c);
char getToken();
public:
Parser(string s) : _data(s), _index(0) { }
};
</pre>
<p>The default constructor will take a string, the program, store it into <code>_data</code> and will parse it.</p>
<p>Note: Be careful to hide (under <code>protected:</code> or <code>private:</code>) all method and variables that shouldn't be accessed outside the class.
The protected <code>getToken()</code> method is a good example, we don't want to access (and modify <code>_index</code>) outside the parser class.</p>
<p>For debugging propose, we will expose protected and private variables and methods, don't forget to hide them after tests.</p>
<p>Usage:</p>
<pre>
class Parser
{
protected:
string _data;
int _index;
static bool isSkipable(char c);
-- char getToken();
public:
Parser(string s) : _data(s), _index(0) { }
++ char getToken();
};
string s = ">>+++ <<3 + >++ < 123 abc .>.>.";
Parser parser(s);
char c = 0;
while ( (c = parser.getToken()) ) {
cout << c << " ";
}
</pre>
<p>This writes out: <code>> > + + + < < + > + + < . > . > .</code> and ignored characters are ignored indeed.</p>
<p>Put back the <code>getToken()</code> method into protected section.</p>
<p>Let's now write the <code>parse()</code> method.
We will use the pattern from the last example but we will create a case for each item:</p>
<pre>
class Parser
{
protected:
string _data;
int _index;
static bool isSkipable(char c);
char getToken();
++ void parse();
public:
Parser(string s) : _data(s), _index(0)
{ parse(); }
};
++ void Parser::parse()
++ {
++ char c = 0;
++ while ( (c = getToken()) ) {
++ switch (c) {
++ case '<':
++ cout << "go to left" << endl; break;
++ case '>':
++ cout << "go to right" << endl; break;
++ case '+':
++ cout << "add one" << endl; break;
++ case '-':
++ cout << "substract one" << endl; break;
++ case '.':
++ cout << "print" << endl; break;
++ case ',':
++ cout << "ask for value" << endl; break;
++ case '[':
++ cout << "start loop" << endl; break;
++ case ']':
++ cout << "end loop" << endl; break;
++ default: break; // Ignored character
++ }
++ }
++ }
</pre>
<p>Now our parser knows how to handle each character, we use it to create a AST (Abstract Structure Tree) where we will create an object for each case.</p>
<p>Let's begin with the "move to" operation and we will call it the "shift" expression. We can create a single shift expression for right and left, the first add one to cursor (+1), the latter remove one (-1) and we need to check that the cursor can't be less than zero.</p>
<p>The class looks like this:</p>
<pre>
class ShiftExpr
{
protected:
int _step;
public:
ShiftExpr(int step) : _step(step) { }
};
</pre>
<p>We will inherit this class from an abstract (virtual) <code>Expr</code> class which contains a public <code>CodeGen()</code> method to generate the LLVM code, we will see the implementation later.</p>
<pre>
class Expr
{
public:
virtual void CodeGen() = 0;
};
</pre>
<p>and we update our <code>ShiftExpr</code> to inherite from <code>Expr</code> publicly to allow polymorphism:</p>
<pre>
class ShiftExpr : public Expr
{
protected:
int _step;
public:
ShiftExpr(int step) : _step(step) { }
void CodeGen();
};
void ShiftExpr::CodeGen()
{
// We will implement this later
}
</pre>
<p>Now, we will use this class into the parse method. This create an shift expr which could generate LLVM bitcode.
Expressions will be stored into a vector (some sort of array).</p>
<pre>
#include <vector>
</pre>
<pre>
class Parser
{
protected:
string data;
int index;
++ vector<Expr *> exprs;
static bool isSkipable(char c);
char getToken();
void parse();
public:
Parser(string s) : data(s), index(0)
{ parse(); }
};
void Parser::parse()
{
char c = 0;
while ( (c = getToken()) ) {
++ Expr *expr = NULL;
switch (c) {
case '<': {
++ expr = new ShiftExpr(-1); // Shift to the left
++ }
break;
case '>': {
++ expr = new ShiftExpr(1); // Shift to the right
++ }
break;
case '+':
cout << "add one" << endl; break;
case '-':
cout << "substract one" << endl; break;
case '.':
cout << "print" << endl; break;
case ',':
cout << "ask for value" << endl; break;
case '[':
cout << "start loop" << endl; break;
case ']':
cout << "end loop" << endl; break;
default: break; // Ignored character
}
++ if (expr) {
++ exprs.push_back(expr);
++ }
}
}
</pre>
<p>And we will create three more expressions: <code>IncrementExpr</code>, <code>InputExpr</code> and <code>OutputExpr</code> like that:</p>
<pre>
class IncrementExpr : public Expr
{
protected:
int _increment;
public:
IncrementExpr(int increment) : _increment(increment) { }
void CodeGen();
};
void IncrementExpr::CodeGen()
{
// We will implement this later
}
</pre>
<pre>
class InputExpr : public Expr
{
public:
InputExpr() { }
void CodeGen();
};
void InputExpr::CodeGen()
{
// We will implement this later
}
</pre>
<pre>
class OutputExpr : public Expr
{
public:
OutputExpr() { }
void CodeGen();
};
void OutputExpr::CodeGen()
{
// We will implement this later
}
</pre>
<p>And, again, update the <code>parse()</code> method:</p>
<pre>
void Parser::parse()
{
char c = 0;
while ( (c = getToken()) ) {
Expr *expr = NULL;
switch (c) {
case '<': {
expr = new ShiftExpr(-1); // Shift to the left
}
break;
case '>': {
expr = new ShiftExpr(1); // Shift to the right
}
break;
case '+': {
++ expr = new IncrementExpr(1); // Increment (add 1)
++ }
break;
case '-': {
++ expr = new IncrementExpr(-1); // Decrement (substract 1)
++ }
break;
case '.': {
++ expr = new OutputExpr(); // Output value
++ }
break;
case ',': {
++ expr = new InputExpr(); // Output value
++ }
break;
case '[':
cout << "start loop" << endl; break;
case ']':
cout << "end loop" << endl; break;
default: break; // Ignored character
}
++ if (expr) {
++ exprs.push_back(expr);
++ }
}
}
</pre>
<p>Now, a little bit more complicated: the loop. A loop starts with <code>[</code> and ends <code>]</code>. The program enters the loop only if the value at the current cursor is greater than zero and the program ends the loop only if the value at the current cursor is equal to zero. We will see later how to create a loop with LLVM IR language but for now, we only need to create a new class <code>LoopExpr</code> which contains all expressions inside the loop.</p>
<p>As a loop can contain other loops, we will use recursive calls of <code>parse()</code> function, so we need to modify this method to allow reccursivity. In place for calling the function with no arguments, we will use the vector which holds parser expressions as argument.</p>
<p>The new version of the prototype is simply:</p>
<pre>
void Parser::parse(vector<Expr *> &exprs);
</pre>
<p>and the implementation doesn't change.</p>
<p>Also, we need to change the calling into the default constructor:</p>
<pre>
Parser(string s) : data(s), index(0)
{ parse(exprs); }
</pre>
<p>Note: Don't confound the initialisation of instance variables, after the <code>:</code> and the calling of a method inside the method body. These cases aren't correct:</p>
<pre>
Parser(string s) : data(s), index(0), parse(exprs) // error
{ }
</pre>
<pre>
Parser(string s)
{
data(s); index(0); // error
parse(exprs);
}
</pre>
<p>If you are not confident with this writing, you could also write this:</p>
<pre>
Parser(string s)
{
data = s; index = 0;
parse(exprs);
}
</pre>
<p>Now, let's write our <code>LoopExpr</code> class, which be initialised with a vector of expressions:</p>
<pre>
class LoopExpr : public Expr
{
protected:
vector<Expr *> _exprs;
public:
LoopExpr(vector<Expr *> &exprs) : _exprs(exprs) { }
void CodeGen();
};
void LoopExpr::CodeGen()
{
// We will implement this later
}
</pre>
<p>We create the vector when the parser will find a start loop character <code>[</code>:</p>
<pre>
void Parser::parse(vector<Expr *> &exprs)
{
char c = 0;
while ( (c = getToken()) ) {
Expr *expr = NULL;
switch ( c ) {
case '<': {
expr = new ShiftExpr(-1); // Shift to the left
}
break;
case '>': {
expr = new ShiftExpr(1); // Shift to the right
}
break;
case '+': {
expr = new IncrementExpr(1); // Increment (add 1)
}
break;
case '-': {
expr = new IncrementExpr(-1); // Decrement (substract 1)
}
break;
case '.': {
expr = new OutputExpr(); // Output value
}
break;
case ',': {
expr = new InputExpr(); // Output value
}
break;
case '[': {
++ vector<Expr *> loopExprs;
++ parse(loopExprs); // Enter into a new function
++ expr = new LoopExpr(loopExprs);
}
break;
case ']': {
++ return ; // Exit the function
}
default: break; // Ignored character
}
if (expr) {
exprs.push_back(expr);
}
}
}
</pre>
<p>Each time the parser will find a <code>[</code> character, it will call the same method <code>parse(vector<Expr *> &exprs)</code> method and when it will found the associated <code>]</code>, it will quit this function.
Let's look at this simple BF example:</p>
<pre>
++[+[-]]
</pre>
<p>At the beginning, we initialising the parser and calling the <code>parse</code>method. Then, the current cell is incrementing by two before entering the loop. The parser finds a start loop character <code>[</code> so it calls the <code>parse</code> method again by passing a empty vector argument.</p>
<p>The parser will continue from the current token, after the <code>[</code> (inside the loop) and will parsing the next <code>+</code>, which increment again the current cell. Then, another <code>[</code> is found, and the parser will one time more calls the <code>parse</code> method with a new brand vector argument. A this time, no <code>LoopExpr</code> is yet created, not until a matching <code>]</code> is found. The trace looks like:</p>
<pre>
parse this: "++[+[-]]" {
// '+' found
// '+' found
// First '[' found here, call 'parse'
parse this: "+[-]]" {
// '+' found
// Another '[' found here, call 'parse'
parse this: "-]]" {
// We are here
}
}
}
</pre>
<p>Next, we decrement the current cell and a matching <code>]</code> is found, it's time to exit the current loop. At this precise time, the <code>parse</code> method exits and the parser goes on by creating an instance of <code>LoopExpr</code> by passing the vector wich contains an instance of <code>IncrementExpr</code>, created from the previous <code>-</code> character. Then, another <code>]</code> is found, create a <code>LoopExpr</code> with previous expression and exit. The trace looks like:</p>
<pre>
parse this: "++[+[-]]" {
// '+' found
// '+' found
// First '[' found here, call 'parse'
parse this: "+[-]]" {
// '+' found
// Another '[' found here, call 'parse'
parse this: "-]]" {
// '-' found
// A ']' found here, create a 'LoopExpr' with '-' and exit
return
}
// A ']' found here, create a 'LoopExpr' with: '+' and the previous 'LoopExpr' (which contains '-')
// and then, exit
return
}
// End of program
}
</pre>
<p>As the <code>parse()</code> method takes a reference to a vector, with can modify it inside the method and getting a up-to-date version when the method exits, needed to create an new <code>LoopExpr</code> instance (we could also return the vector when exiting the method but this latter solution required to create a copy of a vector, which can more expensive that using a reference).</p>
<p>We also need to add a <code>CodeGen()</code> method to Parser, it will be the entry point to generate native code from the vector of expressions:</p>
<pre>
/** Parser.h **/
class Parser
{
protected:
std::string data;
int index;
std::vector<Expr *> _exprs;
static bool isSkipable(char c);
char getToken();
void parse(std::vector<Expr *> &exprs);
public:
Parser(std::string s) : data(s), index(0)
{ parse(_exprs); }
++ void CodeGen(Module *M, IRBuilder<> &B);
void DebugDescription(int level);
};
</pre>
<pre>
/** Parser.cpp **/
++ void Parser::CodeGen(Module *M, IRBuilder<> &B)
++ {
++ }
</pre>
<h2>Refactoring</h2>
<p>Now our whole is about 200 lines of code, it's time for refactoring!
The idea is to separate part into different files like <code>BrainF.cpp</code> with out <code>main</code> function, <code>Parser.cpp</code> for the <code>Parser</code> class, <code>Expr.cpp</code> for <code>*Expr</code> classes and <code>CodeGen.cpp</code> for all <code>*Expr::CodeGen()</code> methods implementation (as we will see, this file could be the biggest file of the program, it's important to separate from <code>*Expr</code> classes definition).
Let's create <code>Brain.cpp</code>, <code>Expr.cpp</code> and <code>CodeGen.cpp</code> but also header files like so:</p>
<pre>
- BrainF.h
- BrainF.cpp
- Parser.h
- Parser.cpp
- Expr.h
- Expr.cpp
- CodeGen.h
- CodeGen.cpp
</pre>
<p>Move <code>Parser</code> class definition to <code>Parser.h</code> and implementation to <code>Parser.cpp</code>. I recommend the header file to looks like</p>
<pre>
#ifndef PARSER_H
#define PARSER_H
#include <vector>
#include "Expr.h"
// Class declaration here
#endif // PARSER_H
</pre>
<p>The define, like <code>PARSER_H</code> (uppercase path, <code>folder/my_file.h</code> could become <code>FOLDER_MY_FILE_H</code>), is used to avoid multiple inclusion [link].</p>
<p><a href="./BF%20(Parser%20only)/">Code source</a></p>
<p>We need to update the <code>Makefile</code> to include all <code>*.cpp</code>files:</p>
<pre>
all: build run
build: Expr.cpp CodeGen.cpp Parser.cpp BrainF.cpp
clang++ Expr.cpp CodeGen.cpp Parser.cpp BrainF.cpp -o BrainF
run: BrainF
./BrainF
</pre>
<h1>LLVM API</h1>
<p>Note: To follow LLVM coding rules for the API:</p>
<ul>
<li>indentation are created with two white-spaces (not a tab)</li>
<li>each line of code should not be more than 85 columns long</li>
<li>variables should be short, begins with an Uppercase letter and ends with the few first letters of the type; for example a Variable can be called "CountV" and a Type "IntTy"</li>
<li>In comments, variables names are written with <code>|</code>, like <code>|varName|</code></li>
</ul>
<p>Examples:</p>
<pre>
llvm::Variable *CountV = ...;
llvm::Type *IntTy = ...;
llvm::BasicBlock *LoopBB = ...;
llvm::IRBuilder<> LoopB(LoopBB);
</pre>
<p>Or with explicit namespace (preferred):</p>
<pre>
namespace llvm;
Variable *CountV = ...;
Type *IntTy = ...;
BasicBlock *LoopBB = ...;
IRBuilder<> LoopB(LoopBB);
</pre>
<h2>Let's started (seriously)</h2>
<p>We now update our <code>XXXExpr::CodeGen</code> method to pass the module and the IR Builder to generate IR code.</p>
<p><code>llvm:Module</code> contains informations about locals and globals variables, functions, etc. We will only use a single module in our parser.</p>
<p><code>llvm::IRBuilder<></code> is a template to add instructions to the current module.</p>
<pre>
void Parser::CodeGen(Module *M, IRBuilder<> &B)
{
// @TODO: Initialise the native code generator (initialise variables, etc.)
// @TODO: Recursively generate code by calling `CodeGen(M, B)`on each expression
}
void ShiftExpr::CodeGen(Module *M, IRBuilder<> &B)
{
// @TODO: Add |_step| to the current index
}
void IncrementExpr::CodeGen(Module *M, IRBuilder<> &B)
{
// @TODO: Add |_step| to the current cell
}
void InputExpr::CodeGen(Module *M, IRBuilder<> &B)
{
// @TODO: Call "scanf" std function
// @TODO: Put the input value to the current cell
}
void OutputExpr::CodeGen(Module *M, IRBuilder<> &B)
{
// @TODO: Call "printf" std function
}
void LoopExpr::CodeGen(Module *M, IRBuilder<> &B)
{
// @TODO: Create a loop
// @TODO: Enter the loop only if the current cell value is greater than zero
// @TODO: Exit the loop if the current cell value is equal to zero
}
</pre>
<p>Into the <code>Parser</code> method, we will first create two <em>global</em> variables (the opposite of local variable) for the index and cells, and initialise them.</p>
<p>The second step is to recursively call <code>CodeGen()</code> on each <code>*Expr</code> from |_expr|, with a simple for loop.</p>
<pre>
void Parser::CodeGen(Module *M, IRBuilder<> &B)
{
// @TODO: Create |index| global variable
// @TODO: Initialise |index| global variable
// @TODO: Create |cells| global variable
// @TODO: Initialise |cells| global variable
// Recursively generate code
for (std::vector<Expr *>::iterator it = _exprs.begin(); it != _exprs.end(); ++it) {
(*it)->CodeGen(M, B);
}
}
</pre>
<p>For the <code>Shift</code> expression, it simple but we need to decompose each part. To change the value of a variable, the computer need 3 steps:</p>
<ul>
<li><p>Load the value at the given address (the pointer of the <code>|index|</code> global variable)</p></li>
<li><p>Create a temporary variable to store the result of the operation: <code>|index| + |step|</code></p></li>
<li><p>Save the temporary variable value at the <code>|index|</code> address</p></li>
</ul>
<pre>
void ShiftExpr::CodeGen(Module *M, IRBuilder<> &B)
{
// @TODO: Get the value of |index| global variable
// @TODO: Create a temporary variable that contains the |index| + |_step| result
// @TODO: Save the "index" global variable
}
</pre>