summaryrefslogtreecommitdiff
path: root/condense/CondenseVisitor.java
blob: 7ba2bebc5eaff3c2e9eeb332612fcad3fae6fb1a (plain)
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
package condense;

import cs132.vapor.ast.*;
import misc.*;

import java.util.*;
import java.util.regex.*;

public class CondenseVisitor extends VInstr.Visitor<RuntimeException>{

    ArrayList<String> vaporm;
    ArrayList<String> mips;

    StackHelper curr;

    public CondenseVisitor(VaporProgram vp, ArrayList<String> vaporm) {
        this.vaporm = vaporm;
        this.mips = new ArrayList<String>();

        // preamble
        this.mips.add(0, ".data");
        this.addMIPS(".text");
        this.addMIPS("jal Main");
        this.addMIPS("li $v0 10");
        this.addMIPS("syscall");

        for (int i = 0; i < vp.functions.length; ++i) {
            this.curr = new StackHelper(vp.functions[i].stack);
            this.addMIPS(vp.functions[i].ident+":");

            // prologue
            this.addMIPS("  sw $fp -8($sp)");
            this.addMIPS("  move $fp $sp");
            this.addMIPS(String.format("  subu $sp $sp %d",
                                       this.curr.getFrameSize()));
            this.addMIPS("  sw $ra -4($fp)");

            TreeSet<Node> f = this.sortFunction(vp.functions[i]);
            MinimalLogger.info(String.format("Starting loop with function:\n %s",
                                             f.toString()));

            for (Node n : f) {
                if (n instanceof VInstr) {
                    ((VInstr) n).accept(this);
                }
                else
                    this.addMIPS(((VCodeLabel) n).ident + ":");
            }

            // epilogue
            this.addMIPS("  lw $ra -4($fp)");
            this.addMIPS("  lw $fp -8($fp)");
            this.addMIPS(String.format("  addu $sp $sp %d",
                                       this.curr.getFrameSize()));
            this.addMIPS("  jr $ra");
        }

        this.addMIPS("_print:");
        this.addMIPS("  li $v0 1   # syscall: print integer");
        this.addMIPS("  syscall");
        this.addMIPS("  la $a0 _newline");
        this.addMIPS("  li $v0 4   # syscall: print string");
        this.addMIPS("  syscall");
        this.addMIPS("  jr $ra");

        this.addMIPS("_error:");
        this.addMIPS("  li $v0 4   # syscall: print string");
        this.addMIPS("  syscall");
        this.addMIPS("  li $v0 10  # syscall: exit");
        this.addMIPS("  syscall");

        this.addMIPS("_heapAlloc:");
        this.addMIPS("  li $v0 9   # syscall: sbrk");
        this.addMIPS("  syscall");
        this.addMIPS("  jr $ra");

        this.addMIPS(".data");
        this.addMIPS(".align 0");
        this.addMIPS("_newline: .asciiz \"\\n\"");
        this.addMIPS("_str0: .asciiz \"null pointer\\n\"");
    }

    public ArrayList<String> getMIPS() {
        return this.mips;
    }

    public void addMIPS(String str) {
        MinimalLogger.info(String.format("Adding string:\n%s",
                                         str));

        this.mips.add(str);
    }

    public TreeSet<Node> sortFunction(VFunction f) {
        TreeSet<Node> sort = new TreeSet<Node>((v1, v2) -> {
                return Integer.compare(v1.sourcePos.line, v2.sourcePos.line);
        });

        for (VInstr s : f.body) {
            sort.add(s);
        }
        for (VCodeLabel l : f.labels) {
            sort.add(l);
        }
        return sort;
    }

    public static boolean isNumeric(String strNum) {
        if (strNum == null) {
            return false;
        }
        try {
            double d = Double.parseDouble(strNum);
        } catch (NumberFormatException nfe) {
            return false;
        }
        return true;
    }

    public void visit(VAssign n) throws RuntimeException {
        MinimalLogger.info(String.format("->%s (%s)",
                                         n.getClass().getSimpleName(),
                                         n.sourcePos.toString()));
        ///////////////////////////////////////////////////////////////
        this.addMIPS(String.format("  move $%s %s",
                                   ((VVarRef.Register) n.dest).ident,
                                   n.source.toString()));
        ///////////////////////////////////////////////////////////////
        MinimalLogger.info(String.format("<-%s (%s)",
                                         n.getClass().getSimpleName(),
                                         n.sourcePos.toString()));
    }

    public void visit(VCall n) throws RuntimeException {
        MinimalLogger.info(String.format("->%s (%s)",
                                         n.getClass().getSimpleName(),
                                         n.sourcePos.toString()));
        ///////////////////////////////////////////////////////////////
        this.addMIPS(String.format("  jal %s",
                                   n.addr.toString().substring(1)));
        ///////////////////////////////////////////////////////////////
        MinimalLogger.info(String.format("<-%s (%s)",
                                         n.getClass().getSimpleName(),
                                         n.sourcePos.toString()));
    }

    public void visit(VBuiltIn n) throws RuntimeException {
        MinimalLogger.info(String.format("->%s (%s)",
                                         n.getClass().getSimpleName(),
                                         n.sourcePos.toString()));
        ///////////////////////////////////////////////////////////////
        // treat the arguments (place all in temp registers)

        String[] ts = new String[] { "$a0", "$t9"};
        for (int i = 0; i < n.args.length; ++i) {
            if (this.isNumeric(n.args[i].toString()))
                this.addMIPS(String.format("  li %s %s",
                                           ts[i],
                                           n.args[i].toString()));
            else
                this.addMIPS(String.format("  move %s %s",
                                           ts[i],
                                           n.args[i].toString()));
        }

        boolean done = false;
        String ret = "";
        String op = ((VBuiltIn.Op) n.op).name;
        if (op.equals("Add"))
            ret += "  add";
        else if (op.equals("Sub"))
            ret += "  sub";
        else if (op.equals("MulS"))
            ret += "  mul";
        else if (op.equals("Eq"))
            ret += "NULL"; // fixme
        else if (op.equals("Lt"))
            ;
        else if (op.equals("LtS"))
            ret += "  slti";
        else if (op.equals("PrintIntS"))
            ret += "  jal _print";
        else if (op.equals("HeapAllocZ")) {
            this.addMIPS("  jal _heapAlloc");
            if (n.dest != null)
                this.addMIPS(String.format("  move $%s $v0",
                                           ((VVarRef.Register) n.dest).ident));
            done = true;
        }
        else if (op.equals("Error"))
            ret += "  la $a0 _str0\n  j _error";

        if (!done) {
            if (n.dest != null)
                ret += String.format(" $%s",
                                     ((VVarRef.Register) n.dest).ident);
            for (int i = 0; i < n.args.length; ++i)
                ret += String.format(" %s",
                                     ts[i]);
            this.addMIPS(ret);
        }

        ///////////////////////////////////////////////////////////////
        MinimalLogger.info(String.format("<-%s (%s)",
                                         n.getClass().getSimpleName(),
                                         n.sourcePos.toString()));
    }

    public void visit(VMemWrite n) throws RuntimeException {
        MinimalLogger.info(String.format("->%s (%s)",
                                         n.getClass().getSimpleName(),
                                         n.sourcePos.toString()));
        ///////////////////////////////////////////////////////////////
        String source = n.source.toString();
        String dest;

        if (n.dest instanceof VMemRef.Stack)
            dest = this.curr.get(((VMemRef.Stack) n.dest));
        else
            dest = String.format("0(%s)",
                                 ((VMemRef.Global) n.dest).base.toString());
        if (source.contains(":")) {
            this.addMIPS(String.format("  la $t9 %s",
                                       source.substring(1)));
            source = "$t9";
        }
        this.addMIPS(String.format("  sw %s %s",
                                   source,
                                   dest));
        ///////////////////////////////////////////////////////////////
        MinimalLogger.info(String.format("<-%s (%s)",
                                         n.getClass().getSimpleName(),
                                         n.sourcePos.toString()));
    }

    public void visit(VMemRead n) throws RuntimeException {
        MinimalLogger.info(String.format("->%s (%s)",
                                         n.getClass().getSimpleName(),
                                         n.sourcePos.toString()));
        ///////////////////////////////////////////////////////////////
        String dest = n.dest.toString();
        String source;

        if (n.source instanceof VMemRef.Stack)
            source = this.curr.get(((VMemRef.Stack) n.source));
        else
            source = ((VMemRef.Global) n.source).base.toString();
        this.addMIPS(String.format("  lw %s %s",
                                   dest,
                                   source));
        ///////////////////////////////////////////////////////////////
        MinimalLogger.info(String.format("<-%s (%s)",
                                         n.getClass().getSimpleName(),
                                         n.sourcePos.toString()));
    }

    public void visit(VBranch n) throws RuntimeException {
        MinimalLogger.info(String.format("->%s (%s)",
                                         n.getClass().getSimpleName(),
                                         n.sourcePos.toString()));
        ///////////////////////////////////////////////////////////////
        String ret = "  ";
        if (n.positive)
            ret += "bnez ";
        else
            ret += "beqz ";

        ret += n.value.toString()
            + " :";

        ret += n.target.ident;

        this.addMIPS(ret);
        ///////////////////////////////////////////////////////////////
        MinimalLogger.info(String.format("<-%s (%s)",
                                         n.getClass().getSimpleName(),
                                         n.sourcePos.toString()));
    }

    public void visit(VGoto n) throws RuntimeException {
        MinimalLogger.info(String.format("->%s (%s)",
                                         n.getClass().getSimpleName(),
                                         n.sourcePos.toString()));
        ///////////////////////////////////////////////////////////////

        ///////////////////////////////////////////////////////////////
        MinimalLogger.info(String.format("<-%s (%s)",
                                         n.getClass().getSimpleName(),
                                         n.sourcePos.toString()));
    }

    public void visit(VReturn n) throws RuntimeException {
        MinimalLogger.info(String.format("->%s (%s)",
                                         n.getClass().getSimpleName(),
                                         n.sourcePos.toString()));
        ///////////////////////////////////////////////////////////////

        ///////////////////////////////////////////////////////////////
        MinimalLogger.info(String.format("<-%s (%s)",
                                         n.getClass().getSimpleName(),
                                         n.sourcePos.toString()));
    }
}