Skip to content
This repository was archived by the owner on Oct 20, 2022. It is now read-only.

Commit 85af104

Browse files
committed
Add optimiser docs
1 parent 1e41436 commit 85af104

File tree

3 files changed

+52
-0
lines changed

3 files changed

+52
-0
lines changed

docs/img/opt-19.png

9.67 KB
Loading

docs/img/opt-21.png

23.6 KB
Loading

docs/optimiser.md

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
# Optimiser
2+
3+
The optimiser uses the syntax tree generated by the parser and prunes redundant
4+
parts of it. This greatly reduces the size of the program to be compiled, while achieving the
5+
same result.
6+
7+
In this compiler, the optimisation runs before the target code generation, so the
8+
generated code is optimised. The implemented optimisations include:
9+
10+
* Replacing constant variables with constants – this is done by checking if a variable
11+
is ever reassigned. If it is not reassigned (i.e. it is a constant), all references to the
12+
variable are replaced with the constant instead.
13+
14+
* Replacing operations on two constants with the result – this is done by checking
15+
arithmetic expressions for having constants as both of the variables. If so, the
16+
operation gets performed during compilation-time.
17+
18+
* Removing unused variables – this is done by checking if a variable is declared but
19+
never used. If this is the case, the declaration is removed.
20+
21+
* Reducing the size of the tree – this is done by reducing the number of sequence
22+
nodes by merging sequence nodes with only one child.
23+
24+
This is done by recursively optimising the syntax tree repeatedly until no more
25+
optimisations are made during a single run. As a result of this amount of heavy optimisation,
26+
all of the sample programs are compiled down to a single print statement.
27+
28+
The optimised version of a previous example can be seen in
29+
Figure 19.
30+
31+
![Figure 19](./img/opt-19.png)
32+
33+
*Figure 19. Optimised Version of Tree in Figure 13 (A1.2. number-addition.ts)*
34+
35+
If the target code generator is given the optimised syntax tree above, the code in
36+
Figure 20 is generated.
37+
38+
```C
39+
#include <stdio.h>
40+
int main() {
41+
printf("%d", 3);
42+
return 0;
43+
}
44+
```
45+
*Figure 20. Code Generated from Figure 19 (A1.2. number-addition.ts)*
46+
47+
Finally, running the Mocha test suite on the optimised compiler reveals that all of the
48+
tests defined in the Test Cases section pass, as seen in Figure 21.
49+
50+
![Figure 21](./img/opt-21.png)
51+
52+
*Figure 21. Final Run of Mocha Test Suite (from Test Cases)*

0 commit comments

Comments
 (0)