-
Notifications
You must be signed in to change notification settings - Fork 6
/
malc
executable file
·104 lines (89 loc) · 2.17 KB
/
malc
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
#!/bin/bash
set -e
usage() {
cat << EOF
Usage: $0 [-g] [-l] [-v] -c source_file.mal [-o executable_file]
OPTIONS:
-h/-? Show this message
-c FILENAME Mal source file name
-g Enable debug mode (mark functions as external for clearer
stack traces)
-l Keep intermediate LLVM IR filse
-o FILENAME Output executable file name
-v Enable verbose logging
EOF
}
log() {
[ "$verbose" == yes ] && echo "malc: $@" || true
}
keep_llvm=no
compile_mode=release
srcfile=
outfile=
verbose=no
while getopts "c:ghlo:v?" OPTION ; do
case $OPTION in
c)
srcfile="$(readlink -f $OPTARG)"
;;
g)
compile_mode=debug
;;
h)
usage
exit 1
;;
l)
keep_llvm=yes
;;
o)
outfile="$(readlink -f $OPTARG)"
;;
v)
verbose=yes
;;
?)
usage
exit 1
;;
esac
done
if [ -z "$srcfile" ] ; then
usage
exit 1
fi
bindir=$(readlink -f $(dirname $0))
if [ -z "${outfile}" ] ; then
outfile="$(dirname $srcfile)/$(basename $srcfile .mal)"
fi
# user overridable
MAL_TO_LLVM=${MAL_TO_LLVM:-}
log "Source file: $srcfile"
log "Compile mode: $compile_mode"
log "Intermediate LLVM IR file: ${outfile}.ll"
# Compile mal to LLVM IR
log "Compiling Mal program to LLVM IR"
if [ -n "${MAL_IMPL:-}" ] ; then
MAL_IMPL=$(readlink -f ${MAL_IMPL})
log "Using Mal interpreter: ${MAL_IMPL} $bindir/mal-to-llvm.mal"
${MAL_IMPL} $bindir/mal-to-llvm.mal $compile_mode $bindir $srcfile > "${outfile}.ll"
else
log "Using binary compiler: $bindir/mal-to-llvm"
$bindir/mal-to-llvm $compile_mode $bindir $srcfile > "${outfile}.ll"
fi
# Optimize generated LLVM IR
log "Optimizing LLVM IR to: ${outfile}.opt.ll"
opt -S -O3 "${outfile}.ll" -o "${outfile}.opt.ll"
# Compile LLVM IR to object file
log "Compiling LLVM IR to object file: ${outfile}.o"
llc -filetype=obj "${outfile}.opt.ll" -o "${outfile}.o"
# Link
log "Linking executable file: ${outfile}"
clang -no-pie -g "${outfile}.o" -lgc -lreadline -lstdc++ -o "${outfile}"
# Cleanup
log "Cleaning up"
if [ "$keep_llvm" = no ] ; then
rm -f "${outfile}.ll" "${outfile}.opt.ll"
fi
rm -f "${outfile}.o"
log "Done"