2e5021e940909a488fec446aa81790f79f63f319
[repair.git] / Repair / RepairCompiler / MCC / IR / DotExpr.java
1 package MCC.IR;
2
3 import java.util.*;
4 import MCC.Compiler;
5
6 public class DotExpr extends Expr {
7
8     Expr left;
9     String field;
10     Expr index;
11
12     static boolean DOMEMCHECKS=false;
13     static boolean DOTYPECHECKS=false;
14     static boolean DONULL=false;
15
16
17     public DotExpr(Expr left, String field, Expr index) {
18         this.left = left;
19         this.field = field;
20         this.index = index;
21     }
22
23     public boolean isInvariant(Set vars) {
24         if (!left.isInvariant(vars))
25             return false;
26         if (intindex!=null)
27             return intindex.isInvariant(vars);
28         else
29             return true;
30     }
31
32     public Set findInvariants(Set vars) {
33         if (isInvariant(vars)) {
34             Set s=new HashSet();
35             s.add(this);
36             return s;
37         } else {
38             Set ls=left.findInvariants(vars);
39             if (intindex!=null) {
40                 ls.addAll(intindex.findInvariants(vars));
41                 Expr indexbound=((ArrayDescriptor)this.fd).getIndexBound();
42                 ls.addAll(indexbound.findInvariants(vars));
43                 if ((!(intindex instanceof IntegerLiteralExpr))||
44                     ((IntegerLiteralExpr) intindex).getValue() != 0) {
45                     FieldDescriptor fd=this.fd;
46                     if (fd instanceof ArrayDescriptor)
47                         fd=((ArrayDescriptor)fd).getField();
48                     Expr basesize = fd.getBaseSizeExpr();
49                     ls.addAll(basesize.findInvariants(vars));
50                 }
51             }
52             return ls;
53         }
54     }
55
56
57     public boolean isSafe() {
58         if (!left.isSafe())
59             return false;
60
61         FieldDescriptor tmpfd=fd;
62
63         if (tmpfd.getPtr()) // Pointers cound be invalid
64             return false;
65
66         if (tmpfd instanceof ArrayDescriptor) {
67             Expr arrayindex=((ArrayDescriptor)tmpfd).getIndexBound();
68             if (index instanceof IntegerLiteralExpr&&arrayindex instanceof IntegerLiteralExpr) {
69                 int indexvalue=((IntegerLiteralExpr)index).getValue();
70                 int arrayindexvalue=((IntegerLiteralExpr)arrayindex).getValue();
71                 if (indexvalue>=0&&indexvalue<arrayindexvalue)
72                     return true;
73             }
74             return false; // Otherwise, arrays could be out of bounds
75         }
76         return true;
77     }
78
79     public Set freeVars() {
80         Set lset=left.freeVars();
81         Set iset=null;
82         if (intindex!=null)
83             iset=intindex.freeVars();
84         if (lset==null)
85             return iset;
86         if (iset!=null)
87             lset.addAll(iset);
88         return lset;
89     }
90
91     /*
92     static int memoryindents = 0;
93
94     public static void generate_memory_endblocks(CodeWriter cr) {
95         while (memoryindents > 0) {
96             memoryindents --;
97             cr.endblock();
98         }
99         memoryindents = 0;
100     }
101     */
102
103     FieldDescriptor fd;
104     TypeDescriptor fieldtype;
105     Expr intindex;
106
107     public String name() {
108         String name=left.name()+"."+field;
109         if (index!=null)
110             name+="["+index.name()+"]";
111         return name;
112     }
113
114     public void findmatch(Descriptor d, Set s) {
115         if (d==fd)
116             s.add(this);
117         left.findmatch(d,s);
118         if (intindex!=null)
119             intindex.findmatch(d,s);
120     }
121
122     public Set useDescriptor(Descriptor d) {
123         HashSet newset=new HashSet();
124         if (d==fd)
125             newset.add(this);
126         newset.addAll(left.useDescriptor(d));
127         if (intindex!=null)
128             newset.addAll(intindex.useDescriptor(d));
129         return newset;
130     }
131
132     public boolean usesDescriptor(Descriptor d) {
133         if (d==fd)
134             return true;
135         return left.usesDescriptor(d)||((intindex!=null)&&intindex.usesDescriptor(d));
136     }
137
138     public boolean equals(Map remap, Expr e) {
139         if (e==null||!(e instanceof DotExpr))
140             return false;
141         DotExpr de=(DotExpr)e;
142         if (!de.field.equals(field))
143             return false;
144         if (index==null) {
145             if (de.index!=null)
146                 return false;
147         } else if (!index.equals(remap,de.index))
148             return false;
149         if (!left.equals(remap,de.left))
150             return false;
151         return true;
152     }
153
154
155     public Set getRequiredDescriptors() {
156         Set v = left.getRequiredDescriptors();
157
158         if (intindex != null) {
159             v.addAll(intindex.getRequiredDescriptors());
160         }
161         return v;
162     }
163
164     public Expr getExpr() {
165         return left;
166     }
167
168     public FieldDescriptor getField() {
169         return fd;
170     }
171
172     public Expr getIndex() {
173         return intindex;
174     }
175
176     public void generate(CodeWriter writer, VarDescriptor dest) {
177         VarDescriptor leftd = VarDescriptor.makeNew("left");
178
179         if (writer.getInvariantValue()!=null&&
180             writer.getInvariantValue().isInvariant(this)) {
181             writer.addDeclaration(getType().getGenerateType().getSafeSymbol().toString(), dest.getSafeSymbol());
182             writer.outputline(dest.getSafeSymbol()+"="+writer.getInvariantValue().getValue(this).getSafeSymbol()+";");
183             writer.outputline("maybe="+writer.getInvariantValue().getMaybe(this).getSafeSymbol()+";");
184             return;
185         }
186
187         writer.output("/* " +  leftd.getSafeSymbol() + " <-- ");
188         left.prettyPrint(writer);
189         writer.outputline("*/");
190
191         left.generate(writer, leftd);
192
193         writer.output("/* " +  leftd.getSafeSymbol() + " = ");
194         left.prettyPrint(writer);
195         writer.outputline("*/");
196
197         StructureTypeDescriptor struct = (StructureTypeDescriptor) left.getType();
198         Expr offsetbits;
199
200         // #ATTN#: getOffsetExpr needs to be called with the fielddescriptor object that is in the vector list
201         // this means that if the field is an arraydescriptor you have to call getOffsetExpr with the array
202         // descriptor not the underlying field descriptor
203
204         /* we calculate the offset in bits */
205
206         offsetbits = struct.getOffsetExpr(fd);
207
208         FieldDescriptor fd=this.fd;
209         if (fd instanceof ArrayDescriptor)
210             fd=((ArrayDescriptor)fd).getField();
211         boolean doboundscheck=true;
212         boolean performedboundscheck=false;
213
214         writer.addDeclaration(getType().getGenerateType().toString(),dest.getSafeSymbol());
215         writer.outputline(dest.getSafeSymbol()+"=0;");
216
217         if (intindex != null) {
218             if (intindex instanceof IntegerLiteralExpr && ((IntegerLiteralExpr) intindex).getValue() == 0) {
219                 /* short circuit for constant 0 */
220             } else {
221                 Expr basesize = fd.getBaseSizeExpr();
222                 if (doboundscheck) {
223                     VarDescriptor indexvd=VarDescriptor.makeNew("index");
224                     indexvd.setType(ReservedTypeDescriptor.INT);
225                     writer.getSymbolTable().add(indexvd);
226
227                     writer.output("/* " + indexvd.getSafeSymbol() + " <-- ");
228
229                     intindex.prettyPrint(writer);
230                     writer.outputline("*/");
231                     intindex.generate(writer, indexvd);
232                     writer.output("/* " + indexvd.getSafeSymbol() + " = ");
233                     intindex.prettyPrint(writer);
234                     writer.outputline("*/");
235                     Expr indexbound=((ArrayDescriptor)this.fd).getIndexBound();
236                     VarDescriptor indexboundvd=VarDescriptor.makeNew("indexbound");
237
238                     indexbound.generate(writer,indexboundvd);
239
240                     writer.outputline("if ("+indexvd.getSafeSymbol()+">=0 &&"+indexvd.getSafeSymbol()+"<"+indexboundvd.getSafeSymbol()+")");
241                     writer.startblock();
242                     VarExpr indexve=new VarExpr(indexvd);
243                     offsetbits = new OpExpr(Opcode.ADD, offsetbits, new OpExpr(Opcode.MULT, basesize, indexve));
244
245                     performedboundscheck=true;
246                 } else
247                     offsetbits = new OpExpr(Opcode.ADD, offsetbits, new OpExpr(Opcode.MULT, basesize, intindex));
248             }
249         }
250
251         final SymbolTable st = writer.getSymbolTable();
252         TypeDescriptor td2 = offsetbits.typecheck(new SemanticAnalyzer() {
253                 public IRErrorReporter getErrorReporter() { throw new IRException("badness"); }
254                 public SymbolTable getSymbolTable() { return st; }
255             });
256
257         if (td2 == null) {
258             throw new IRException();
259         } else if (td2 != ReservedTypeDescriptor.INT) {
260             throw new IRException();
261         }
262
263         boolean dotypecheck = false;
264
265         VarDescriptor ob = VarDescriptor.makeNew("offsetinbits");
266         writer.output("/* " + ob.getSafeSymbol() + " <-- ");
267         offsetbits.prettyPrint(writer);
268         writer.outputline("*/");
269         offsetbits.generate(writer, ob);
270         writer.output("/* " + ob.getSafeSymbol() + " = ");
271         offsetbits.prettyPrint(writer);
272         writer.outputline("*/");
273
274         /* derive offset in bytes */
275         VarDescriptor offset = VarDescriptor.makeNew("offset");
276         writer.addDeclaration("int", offset.getSafeSymbol());
277         writer.outputline(offset.getSafeSymbol() + " = " + ob.getSafeSymbol() + " >> 3;");
278
279         if (fd.getType() instanceof ReservedTypeDescriptor && !fd.getPtr()) {
280             VarDescriptor shift = VarDescriptor.makeNew("shift");
281             writer.addDeclaration("int", shift.getSafeSymbol());
282             writer.outputline(shift.getSafeSymbol() + " = " + ob.getSafeSymbol() +
283                               " - (" + offset.getSafeSymbol() + " << 3);");
284             int mask = bitmask(((IntegerLiteralExpr)fd.getType().getSizeExpr()).getValue());
285
286             /* type var = ((*(int *) (base + offset)) >> shift) & mask */
287             writer.outputline("if ("+leftd.getSafeSymbol()+")");
288             writer.outputline(dest.getSafeSymbol() + " = ((*(int *)" +
289                               "(" + leftd.getSafeSymbol() + " + " + offset.getSafeSymbol() + ")) " +
290                               " >> " + shift.getSafeSymbol() + ") & 0x" + Integer.toHexString(mask) + ";");
291             writer.outputline("else maybe=1;");
292         } else { /* a structure address or a ptr */
293             String ptr = fd.getPtr() ? "*(int *)" : "";
294             /* type var = [*(int *)] (base + offset) */
295             writer.outputline("if ("+leftd.getSafeSymbol()+")");
296             writer.startblock();
297             writer.outputline(dest.getSafeSymbol() +
298                               " = " + ptr + "(" + leftd.getSafeSymbol() + " + " + offset.getSafeSymbol() + ");");
299             if (fd.getPtr()) {
300                 writer.outputline("if ("+dest.getSafeSymbol()+")");
301                 writer.startblock();
302                 VarDescriptor typevar=VarDescriptor.makeNew("typechecks");
303                 if (DOMEMCHECKS&&(!DOTYPECHECKS)) {
304                     writer.addDeclaration("bool", typevar.getSafeSymbol());
305                     writer.outputline(typevar.getSafeSymbol()+"=assertvalidmemory(" + dest.getSafeSymbol() + ", " + this.td.getId() + ");");
306                     dotypecheck = true;
307                 } else if (DOTYPECHECKS) {
308                     writer.addDeclaration("bool", typevar.getSafeSymbol());
309                     writer.outputline(typevar.getSafeSymbol()+"=assertvalidtype(" + dest.getSafeSymbol() + ", " + this.td.getId() + ");");
310                 }
311
312                 if (DOTYPECHECKS||DOMEMCHECKS) {
313                     writer.outputline("if (!"+typevar.getSafeSymbol()+")");
314                     writer.startblock();
315                     writer.outputline(dest.getSafeSymbol()+"=0;");
316                     if (DONULL)
317                         writer.outputline(ptr + "(" + leftd.getSafeSymbol() + " + " + offset.getSafeSymbol() + ")=0;");
318                     writer.endblock();
319                 }
320
321                 writer.endblock();
322             }
323             writer.endblock();
324             writer.outputline("else maybe=1;");
325         }
326         if (performedboundscheck) {
327             writer.endblock();
328             writer.outputline(" else ");
329             writer.startblock();
330             writer.outputline(dest.getSafeSymbol()+"=0;");
331             writer.outputline("maybe=1;");
332             if (!Compiler.REPAIR)
333                 writer.outputline("printf(\"Array Index Out of Bounds\");");
334             writer.endblock();
335         }
336     }
337
338     private int bitmask(int bits) {
339         int mask = 0;
340
341         for (int i = 0; i < bits; i++) {
342             mask <<= 1;
343             mask += 1;
344         }
345
346         return mask;
347     }
348
349     public void prettyPrint(PrettyPrinter pp) {
350         left.prettyPrint(pp);
351         pp.output("." + field);
352         if (index != null) {
353             pp.output("[");
354             index.prettyPrint(pp);
355             pp.output("]");
356         }
357     }
358
359     public boolean isValue(TypeDescriptor td) {
360         FieldDescriptor tmpfd=fd;
361         if (tmpfd instanceof ArrayDescriptor)
362             tmpfd=((ArrayDescriptor)tmpfd).getField();
363         return (tmpfd.getPtr()||(tmpfd.getType() instanceof ReservedTypeDescriptor));
364     }
365
366     public boolean isPtr() {
367         FieldDescriptor tmpfd=fd;
368         if (tmpfd instanceof ArrayDescriptor)
369             tmpfd=((ArrayDescriptor)tmpfd).getField();
370         return tmpfd.getPtr();
371     }
372
373     boolean typechecked=false;
374     public TypeDescriptor typecheck(SemanticAnalyzer sa) {
375         if (typechecked)
376             return this.td;
377         else typechecked=true;
378         TypeDescriptor lefttype = left.typecheck(sa);
379         TypeDescriptor indextype = index == null ? null : index.typecheck(sa);
380
381         {
382             /* finished typechecking...so we can fill the fields in */
383             StructureTypeDescriptor struct = (StructureTypeDescriptor) left.getType();
384             FieldDescriptor fd = struct.getField(field);
385             LabelDescriptor ld = struct.getLabel(field);
386             if (ld != null) { /* label */
387                 assert fd == null;
388                 fieldtype = ld.getType(); // d.s ==> Superblock, while,  d.b ==> Block
389                 fd = ld.getField();
390                 assert fd != null;
391                 assert intindex == null;
392                 intindex = ld.getIndex();
393             } else {
394                 if (fd==null) {
395                     throw new Error("Null fd for: "+field);
396                 }
397                 fieldtype = fd.getType();
398                 intindex=index;
399             }
400             this.fd=fd;
401             if (fieldtype instanceof MissingTypeDescriptor)
402                 throw new Error(fieldtype.getSymbol()+" type undefined!");
403         }
404
405         if ((lefttype == null) || (index != null && indextype == null)) {
406             return null;
407         }
408
409         if (indextype != null) {
410             if (indextype != ReservedTypeDescriptor.INT) {
411                 sa.getErrorReporter().report(null, "Index must be of type 'int' not '" + indextype.getSymbol() + "'");
412                 return null;
413             }
414         }
415
416         if (lefttype instanceof StructureTypeDescriptor) {
417             StructureTypeDescriptor struct = (StructureTypeDescriptor) lefttype;
418             FieldDescriptor fd = struct.getField(field);
419             LabelDescriptor ld = struct.getLabel(field);
420
421             if (fd != null) { /* field */
422                 assert ld == null;
423
424                 if (indextype == null && fd instanceof ArrayDescriptor) {
425                     sa.getErrorReporter().report(null, "Must specify an index what accessing array field '" + struct.getSymbol() + "." + fd.getSymbol() + "'");
426                     return null;
427                 } else if (indextype != null && !(fd instanceof ArrayDescriptor)) {
428                     sa.getErrorReporter().report(null, "Cannot specify an index when accessing non-array field '" + struct.getSymbol() + "." + fd.getSymbol() + "'");
429                     return null;
430                 }
431
432                 this.td = fd.getType();
433             } else if (ld != null) { /* label */
434                 assert fd == null;
435
436                 if (index != null) {
437                     sa.getErrorReporter().report(null, "A label cannot be accessed as an array");
438                     return null;
439                 }
440
441                 this.td = ld.getType();
442             } else {
443                 sa.getErrorReporter().report(null, "No such field or label '" + field + "' in structure '" + struct.getSymbol() + "'");
444                 return null;
445             }
446
447             /* we promote bit, byte and short to integer types */
448             if (this.td == ReservedTypeDescriptor.BIT ||
449                 this.td == ReservedTypeDescriptor.BYTE ||
450                 this.td == ReservedTypeDescriptor.SHORT) {
451                 this.td = ReservedTypeDescriptor.INT;
452             }
453
454             return this.td;
455         } else {
456             sa.getErrorReporter().report(null, "Left hand side of . expression must be a structure type, not '" + lefttype.getSymbol() + "'");
457             return null;
458         }
459     }
460 }