• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Constant Folding
2## Overview
3**Constant folding** - optimization which calculate instructions with constant inputs in compile time.
4## Rationality
5
6Reducing the number of instructions.
7
8## Dependence
9 * RPO analyze.
10## Algorithm
11Visit all instructions in PRO order.
12
13If instruction have constant inputs, new constant is calculate and input of user of original instruction is replaced on new constant.
14
15Constant folding is called in Peephole optimization.
16## Pseudocode
17```
18for (auto inst: All insts in RPO order) {
19   if (inputs is constants) {
20      Calculate new value.
21      Putting new constant in inputs of inst users.
22   }
23}
24```
25## Examples
26Before constant folding:
27```
281.i64 Constant 1 -> v3
292.i64 Constant 2 -> v3
30
313.i64 Add v1, v2 -> v4 // is redundant, can calculate in compile time
324.i64 Return v3
33```
34After constant folding:
35```
361.i64 Constant 1
372.i64 Constant 2
385.i64 Constant 3 -> v4
39
403.i64 Add v1, v2
414.i64 Return v5
42```
43
44## Links
45
46Source code:
47[constant_folding.cpp](../optimizer/optimizations/const_folding.cpp)
48[constant_folding.h](../optimizer/optimizations/const_folding.h)
49
50Tests:
51[constant_folding_test.cpp](../tests/const_folding_test.cpp)