2ece34467b8c1b6f41db3b85f6ff185d1c424198
[repair.git] / Repair / RepairCompiler / MCC / IR / RepairGenerator.java
1 package MCC.IR;
2
3 import java.io.*;
4 import java.util.*;
5 import MCC.State;
6 import MCC.Compiler;
7
8 public class RepairGenerator {
9     State state;
10     PrintWrapper outputrepair = null;
11     PrintWrapper outputaux = null;
12     PrintWrapper outputhead = null;
13     String name="foo";
14     String headername;
15     static VarDescriptor oldmodel=null;
16     static VarDescriptor newmodel=null;
17     static VarDescriptor worklist=null;
18     static VarDescriptor repairtable=null;
19     static VarDescriptor goodflag=null;
20     Rule currentrule=null;
21     Hashtable updatenames;
22     HashSet usedupdates;
23     Termination termination;
24     Set removed;
25     HashSet togenerate;
26     static boolean DEBUG=false;
27     Cost cost;
28     ModelRuleDependence mrd;
29
30     public RepairGenerator(State state, Termination t) {
31         this.state = state;
32         updatenames=new Hashtable();
33         usedupdates=new HashSet();
34         termination=t;
35         removed=t.removedset;
36         togenerate=new HashSet();
37         togenerate.addAll(termination.conjunctions);
38         if (Compiler.REPAIR)
39             togenerate.removeAll(removed);
40         GraphNode.computeclosure(togenerate,removed);
41         cost=new Cost();
42         mrd=ModelRuleDependence.doAnalysis(state);
43         Repair.repairgenerator=this;
44     }
45
46     private void generatetypechecks(boolean flag) {
47         if (flag) {
48             DotExpr.DOTYPECHECKS=true;
49             VarExpr.DOTYPECHECKS=true;
50             DotExpr.DONULL=true;
51             VarExpr.DONULL=true;
52         } else {
53             VarExpr.DOTYPECHECKS=false;
54             DotExpr.DOTYPECHECKS=false;
55             VarExpr.DONULL=true;
56             DotExpr.DONULL=true;
57         }
58     }
59
60
61     private void name_updates() {
62         int count=0;
63         for(Iterator it=termination.updatenodes.iterator();it.hasNext();) {
64             GraphNode gn=(GraphNode) it.next();
65             TermNode tn=(TermNode) gn.getOwner();
66             MultUpdateNode mun=tn.getUpdate();
67             if (togenerate.contains(gn))
68             for (int i=0;i<mun.numUpdates();i++) {
69                 UpdateNode un=mun.getUpdate(i);
70                 String name="update"+String.valueOf(count++);
71                 updatenames.put(un,name);
72             }
73         }
74     }
75
76     public void generate(OutputStream outputrepair, OutputStream outputaux,OutputStream outputhead, String st) {
77         this.outputrepair = new PrintWrapper(new java.io.PrintWriter(outputrepair, true));
78         this.outputaux = new PrintWrapper(new java.io.PrintWriter(outputaux, true));
79         this.outputhead = new PrintWrapper(new java.io.PrintWriter(outputhead, true));
80
81         headername=st;
82         name_updates();
83         generatetypechecks(true);
84         generate_tokentable();
85         RelationDescriptor.prefix = "thisvar->";
86         SetDescriptor.prefix = "thisvar->";
87
88         generate_hashtables();
89         generate_stateobject();
90
91
92         /* Rewrite globals */
93         CodeWriter craux = new StandardCodeWriter(this.outputaux);
94         for (Iterator it=this.state.stGlobals.descriptors();it.hasNext();) {
95             VarDescriptor vd=(VarDescriptor)it.next();
96             craux.outputline("#define "+vd.getSafeSymbol()+" thisvar->"+vd.getSafeSymbol());
97         }
98
99
100         generate_call();
101         generate_start();
102         generate_rules();
103         if (!Compiler.REPAIR||Compiler.GENERATEDEBUGPRINT) {
104             generate_print();
105         }
106         generate_checks();
107         generate_teardown();
108         CodeWriter crhead = new StandardCodeWriter(this.outputhead);
109         craux = new StandardCodeWriter(this.outputaux);
110         craux.emptyBuffer();
111         craux.endblock();
112
113         if (Compiler.GENERATEDEBUGHOOKS) {
114             crhead.outputline("void debughook();");
115             craux.outputline("void debughook() {}");
116         }
117         generatetypechecks(false);
118         generate_computesizes();
119         generatetypechecks(true);
120         generate_recomputesizes();
121         generatetypechecks(false);
122         generate_updates();
123         StructureGenerator sg=new StructureGenerator(state,this);
124         sg.buildall();
125         crhead.outputline("#endif");
126     }
127
128     String ststate="state";
129     String stmodel="model";
130     String strepairtable="repairtable";
131     String stleft="left";
132     String stright="right";
133     String stnew="newvalue";
134
135     private void generate_updates() {
136         int count=0;
137         CodeWriter crhead = new StandardCodeWriter(outputhead);
138         CodeWriter craux = new StandardCodeWriter(outputaux);
139         RelationDescriptor.prefix = "model->";
140         SetDescriptor.prefix = "model->";
141
142         /* Rewrite globals */
143
144         for (Iterator it=this.state.stGlobals.descriptors();it.hasNext();) {
145             VarDescriptor vd=(VarDescriptor)it.next();
146             craux.outputline("#undef "+vd.getSafeSymbol());
147             craux.outputline("#define "+vd.getSafeSymbol()+" "+ststate+"->"+vd.getSafeSymbol());
148         }
149
150         for(Iterator it=termination.updatenodes.iterator();it.hasNext();) {
151             GraphNode gn=(GraphNode) it.next();
152             TermNode tn=(TermNode) gn.getOwner();
153             MultUpdateNode mun=tn.getUpdate();
154             boolean isrelation=(mun.getDescriptor() instanceof RelationDescriptor);
155             if (togenerate.contains(gn))
156             for (int i=0;i<mun.numUpdates();i++) {
157                 UpdateNode un=mun.getUpdate(i);
158                 String methodname=(String)updatenames.get(un);
159
160                 switch(mun.op) {
161                 case MultUpdateNode.ADD:
162                     if (isrelation) {
163                         crhead.outputline("void "+methodname+"(struct "+name+"_state * " +ststate+",struct "+name+" * "+stmodel+", struct RepairHash * "+strepairtable+", int "+stleft+", int "+stright+");");
164                         craux.outputline("void "+methodname+"(struct "+name+"_state * "+ ststate+", struct "+name+" * "+stmodel+", struct RepairHash * "+strepairtable+", int "+stleft+", int "+stright+")");
165                     } else {
166                         crhead.outputline("void "+methodname+"(struct "+name+"_state * "+ ststate+", struct "+name+" * "+stmodel+", struct RepairHash * "+strepairtable+", int "+stleft+");");
167                         craux.outputline("void "+methodname+"(struct "+name+"_state * "+ststate+", struct "+name+" * "+stmodel+", struct RepairHash * "+strepairtable+", int "+stleft+")");
168                     }
169                     craux.startblock();
170                     craux.startBuffer();
171                     craux.addDeclaration("int","maybe");
172                     craux.outputline("maybe=0;");
173                     if (Compiler.GENERATEINSTRUMENT)
174                         craux.outputline("updatecount++;");
175
176                     final SymbolTable st = un.getRule().getSymbolTable();
177                     CodeWriter cr = new StandardCodeWriter(outputaux) {
178                         public SymbolTable getSymbolTable() { return st; }
179                     };
180                     un.generate(cr, false, false, stleft,stright, null,this);
181                     craux.outputline("if (maybe) printf(\"REALLY BAD\");");
182                     craux.emptyBuffer();
183                     craux.endblock();
184                     break;
185                 case MultUpdateNode.REMOVE: {
186                     Rule r=un.getRule();
187                     String methodcall="void "+methodname+"(struct "+name+"_state * "+ststate+", struct "+name+" * "+stmodel+", struct RepairHash * "+strepairtable;
188                     for(int j=0;j<r.numQuantifiers();j++) {
189                         Quantifier q=r.getQuantifier(j);
190                         if (q instanceof SetQuantifier) {
191                             SetQuantifier sq=(SetQuantifier) q;
192                             methodcall+=","+sq.getVar().getType().getGenerateType().getSafeSymbol()+" "+sq.getVar().getSafeSymbol();
193                         } else if (q instanceof RelationQuantifier) {
194                             RelationQuantifier rq=(RelationQuantifier) q;
195
196                             methodcall+=","+rq.x.getType().getGenerateType().getSafeSymbol()+" "+rq.x.getSafeSymbol();
197                             methodcall+=","+rq.y.getType().getGenerateType().getSafeSymbol()+" "+rq.y.getSafeSymbol();
198                         } else if (q instanceof ForQuantifier) {
199                             ForQuantifier fq=(ForQuantifier) q;
200                             methodcall+=",int "+fq.getVar().getSafeSymbol();
201                         }
202                     }
203                     methodcall+=")";
204                     crhead.outputline(methodcall+";");
205                     craux.outputline(methodcall);
206                     craux.startblock();
207                     craux.startBuffer();
208                     craux.addDeclaration("int","maybe");
209                     craux.outputline("maybe=0;");
210                     if (Compiler.GENERATEINSTRUMENT)
211                         craux.outputline("updatecount++;");
212                     final SymbolTable st2 = un.getRule().getSymbolTable();
213                     CodeWriter cr2 = new StandardCodeWriter(outputaux) {
214                         public SymbolTable getSymbolTable() { return st2; }
215                     };
216                     un.generate(cr2, true, false, null,null, null,this);
217                     craux.outputline("if (maybe) printf(\"REALLY BAD\");");
218                     craux.emptyBuffer();
219                     craux.endblock();
220                 }
221                     break;
222                 case MultUpdateNode.MODIFY: {
223                     Rule r=un.getRule();
224                     String methodcall="void "+methodname+"(struct "+name+"_state * "+ststate+", struct "+name+" * "+stmodel+", struct RepairHash * "+strepairtable;
225                     for(int j=0;j<r.numQuantifiers();j++) {
226                         Quantifier q=r.getQuantifier(j);
227                         if (q instanceof SetQuantifier) {
228                             SetQuantifier sq=(SetQuantifier) q;
229                             methodcall+=","+sq.getVar().getType().getGenerateType().getSafeSymbol()+" "+sq.getVar().getSafeSymbol();
230                         } else if (q instanceof RelationQuantifier) {
231                             RelationQuantifier rq=(RelationQuantifier) q;
232
233                             methodcall+=", "+rq.x.getType().getGenerateType().getSafeSymbol()+" "+rq.x.getSafeSymbol();
234                             methodcall+=", "+rq.y.getType().getGenerateType().getSafeSymbol()+" "+rq.y.getSafeSymbol();
235                         } else if (q instanceof ForQuantifier) {
236                             ForQuantifier fq=(ForQuantifier) q;
237                             methodcall+=", int "+fq.getVar().getSafeSymbol();
238                         }
239                     }
240                     methodcall+=", int "+stleft+", int "+stright+", int "+stnew;
241                     methodcall+=")";
242                     crhead.outputline(methodcall+";");
243                     craux.outputline(methodcall);
244                     craux.startblock();
245                     craux.startBuffer();
246                     craux.outputline("int maybe=0;");
247                     if (Compiler.GENERATEINSTRUMENT)
248                         craux.outputline("updatecount++;");
249                     final SymbolTable st2 = un.getRule().getSymbolTable();
250                     CodeWriter cr2 = new StandardCodeWriter(outputaux) {
251                         public SymbolTable getSymbolTable() { return st2; }
252                     };
253                     un.generate(cr2, false, true, stleft, stright, stnew, this);
254                     craux.outputline("if (maybe) printf(\"REALLY BAD\");");
255                     craux.emptyBuffer();
256                     craux.endblock();
257                 }
258                     break;
259
260                 default:
261                     throw new Error("Nonimplement Update");
262                 }
263             }
264         }
265     }
266
267     private void generate_call() {
268         CodeWriter cr = new StandardCodeWriter(outputrepair);
269         VarDescriptor vdstate=VarDescriptor.makeNew("repairstate");
270         cr.addDeclaration("struct "+ name+"_state *", vdstate.getSafeSymbol());
271         cr.outputline(vdstate.getSafeSymbol()+"=allocate"+name+"_state();");
272         Iterator globals=state.stGlobals.descriptors();
273         while (globals.hasNext()) {
274             VarDescriptor vd=(VarDescriptor) globals.next();
275             cr.outputline(vdstate.getSafeSymbol()+"->"+vd.getSafeSymbol()+"=("+vd.getType().getGenerateType().getSafeSymbol()+")"+vd.getSafeSymbol()+";");
276         }
277         /* Insert repair here */
278         cr.outputline("doanalysis("+vdstate.getSafeSymbol()+");");
279         globals=state.stGlobals.descriptors();
280         while (globals.hasNext()) {
281             VarDescriptor vd=(VarDescriptor) globals.next();
282             cr.outputline("*(("+vd.getType().getGenerateType().getSafeSymbol()+"*) &"+vd.getSafeSymbol()+")="+vdstate.getSafeSymbol()+"->"+vd.getSafeSymbol()+";");
283         }
284         cr.outputline("free"+name+"_state("+vdstate.getSafeSymbol()+");");
285     }
286
287     private void generate_tokentable() {
288         CodeWriter cr = new StandardCodeWriter(outputrepair);
289         Iterator tokens = TokenLiteralExpr.tokens.keySet().iterator();
290
291         cr.outputline("");
292         cr.outputline("/* Token values*/");
293         cr.outputline("");
294
295         while (tokens.hasNext()) {
296             Object token = tokens.next();
297             cr.outputline("/* " + token.toString() + " = " + TokenLiteralExpr.tokens.get(token).toString()+"*/");
298         }
299
300         cr.outputline("");
301         cr.outputline("");
302     }
303
304     private void generate_stateobject() {
305         CodeWriter crhead = new StandardCodeWriter(outputhead);
306         CodeWriter craux = new StandardCodeWriter(outputaux);
307         crhead.outputline("struct "+name+"_state {");
308         Iterator globals=state.stGlobals.descriptors();
309         while (globals.hasNext()) {
310             VarDescriptor vd=(VarDescriptor) globals.next();
311             crhead.outputline(vd.getType().getGenerateType().getSafeSymbol()+" "+vd.getSafeSymbol()+";");
312         }
313         crhead.outputline("};");
314         crhead.outputline("struct "+name+"_state * allocate"+name+"_state();");
315         craux.outputline("struct "+name+"_state * allocate"+name+"_state()");
316         craux.startblock();
317         craux.outputline("return (struct "+name+"_state *) malloc(sizeof(struct "+name+"_state));");
318         craux.endblock();
319
320         crhead.outputline("void free"+name+"_state(struct "+name+"_state *);");
321         craux.outputline("void free"+name+"_state(struct "+name+"_state * thisvar)");
322         craux.startblock();
323         craux.outputline("free(thisvar);");
324         craux.endblock();
325
326         crhead.outputline("void "+name+"_statecomputesizes(struct "+name+"_state * ,int *,int **);");
327         crhead.outputline("void "+name+"_staterecomputesizes(struct "+name+"_state *);");
328     }
329
330     private void generate_computesizes() {
331         int max=TypeDescriptor.counter;
332         TypeDescriptor[] tdarray=new TypeDescriptor[max];
333         for(Iterator it=state.stTypes.descriptors();it.hasNext();) {
334             TypeDescriptor ttd=(TypeDescriptor)it.next();
335             tdarray[ttd.getId()]=ttd;
336         }
337         final SymbolTable st = state.stGlobals;
338         CodeWriter cr = new StandardCodeWriter(outputaux) {
339                 public SymbolTable getSymbolTable() { return st; }
340             };
341
342         cr.outputline("void "+name+"_statecomputesizes(struct "+name+"_state * thisvar,int *sizearray,int **numele)");
343         cr.startblock();
344         cr.startBuffer();
345         cr.addDeclaration("int","maybe");
346         cr.outputline("maybe=0;");
347         for(int i=0;i<max;i++) {
348             TypeDescriptor td=tdarray[i];
349             Expr size=td.getSizeExpr();
350             VarDescriptor vd=VarDescriptor.makeNew("size");
351             size.generate(cr,vd);
352             cr.outputline("sizearray["+i+"]="+vd.getSafeSymbol()+";");
353         }
354         for(int i=0;i<max;i++) {
355             TypeDescriptor td=tdarray[i];
356             if (td instanceof StructureTypeDescriptor) {
357                 StructureTypeDescriptor std=(StructureTypeDescriptor) td;
358                 for(int j=0;j<std.fieldlist.size();j++) {
359                     FieldDescriptor fd=(FieldDescriptor)std.fieldlist.get(j);
360                     if (fd instanceof ArrayDescriptor) {
361                         ArrayDescriptor ad=(ArrayDescriptor)fd;
362                         Expr index=ad.getIndexBound();
363                         VarDescriptor vd=VarDescriptor.makeNew("index");
364                         index.generate(cr,vd);
365                         cr.outputline("numele["+i+"]["+j+"]="+vd.getSafeSymbol()+";");
366                     }
367                 }
368             }
369         }
370         cr.outputline("if (maybe) printf(\"BAD ERROR\");");
371         cr.emptyBuffer();
372         cr.endblock();
373     }
374
375     private void generate_recomputesizes() {
376         int max=TypeDescriptor.counter;
377         TypeDescriptor[] tdarray=new TypeDescriptor[max];
378         for(Iterator it=state.stTypes.descriptors();it.hasNext();) {
379             TypeDescriptor ttd=(TypeDescriptor)it.next();
380             tdarray[ttd.getId()]=ttd;
381         }
382         final SymbolTable st = state.stGlobals;
383         CodeWriter cr = new StandardCodeWriter(outputaux) {
384                 public SymbolTable getSymbolTable() { return st; }
385             };
386         cr.outputline("void "+name+"_staterecomputesizes(struct "+name+"_state * thisvar)");
387         cr.startblock();
388         cr.startBuffer();
389         cr.addDeclaration("int","maybe");
390         cr.outputline("maybe=0;");
391         for(int i=0;i<max;i++) {
392             TypeDescriptor td=tdarray[i];
393             Expr size=td.getSizeExpr();
394             VarDescriptor vd=VarDescriptor.makeNew("size");
395             size.generate(cr,vd);
396         }
397         for(int i=0;i<max;i++) {
398             TypeDescriptor td=tdarray[i];
399             if (td instanceof StructureTypeDescriptor) {
400                 StructureTypeDescriptor std=(StructureTypeDescriptor) td;
401                 for(int j=0;j<std.fieldlist.size();j++) {
402                     FieldDescriptor fd=(FieldDescriptor)std.fieldlist.get(j);
403                     if (fd instanceof ArrayDescriptor) {
404                         ArrayDescriptor ad=(ArrayDescriptor)fd;
405                         Expr index=ad.getIndexBound();
406                         VarDescriptor vd=VarDescriptor.makeNew("index");
407                         index.generate(cr,vd);
408                     }
409                 }
410             }
411         }
412         cr.outputline("if (maybe) printf(\"BAD ERROR\");");
413         cr.emptyBuffer();
414         cr.endblock();
415     }
416
417
418     private void generate_hashtables() {
419         CodeWriter craux = new StandardCodeWriter(outputaux);
420         CodeWriter crhead = new StandardCodeWriter(outputhead);
421         crhead.outputline("#ifndef "+name+"_h");
422         crhead.outputline("#define "+name+"_h");
423         crhead.outputline("#include \"SimpleHash.h\"");
424         crhead.outputline("#include \"instrument.h\"");
425         crhead.outputline("#include <stdio.h>");
426         crhead.outputline("#include <stdlib.h>");
427         crhead.outputline("struct "+name+" * allocate"+name+"();");
428         crhead.outputline("void free"+name+"(struct "+name+" *);");
429         crhead.outputline("struct "+name+" {");
430         craux.outputline("#include \""+headername+"\"");
431         craux.outputline("#include \"size.h\"");
432         if (Compiler.TIME) {
433             craux.outputline("#include <sys/time.h>");
434         }
435         if (Compiler.ALLOCATECPLUSPLUS) {
436             for(Iterator it=state.stTypes.descriptors();it.hasNext();) {
437                 TypeDescriptor td=(TypeDescriptor)it.next();
438                 if (td instanceof StructureTypeDescriptor) {
439                     if (((StructureTypeDescriptor)td).size()>0) {
440                         FieldDescriptor fd=((StructureTypeDescriptor)td).get(0);
441                         if (fd.getSymbol().startsWith("_vptr_")) {
442                             String vtable="_ZTV";
443                             vtable+=td.getSymbol().length();
444                             vtable+=td.getSymbol();
445                             craux.outputline("extern void * "+vtable+";");
446                         }
447                     }
448                 }
449             }
450         }
451         craux.outputline("struct "+ name+"* allocate"+name+"()");
452         craux.startblock();
453         craux.outputline("/* creating hashtables */");
454
455         /* build sets */
456         Iterator sets = state.stSets.descriptors();
457         craux.addDeclaration("struct "+name+"*", "thisvar");
458         craux.outputline("thisvar=(struct "+name+"*) malloc(sizeof(struct "+name+"));");
459
460         /* first pass create all the hash tables */
461         while (sets.hasNext()) {
462             SetDescriptor set = (SetDescriptor) sets.next();
463             crhead.outputline("struct SimpleHash* " + set.getJustSafeSymbol() + "_hash;");
464             craux.outputline(set.getSafeSymbol() + "_hash = noargallocateSimpleHash();");
465         }
466
467         /* second pass build relationships between hashtables */
468         sets = state.stSets.descriptors();
469
470         while (sets.hasNext()) {
471             SetDescriptor set = (SetDescriptor) sets.next();
472             Iterator subsets = set.subsets();
473
474             while (subsets.hasNext()) {
475                 SetDescriptor subset = (SetDescriptor) subsets.next();
476                 craux.outputline("SimpleHashaddParent("+subset.getSafeSymbol() +"_hash ,"+ set.getSafeSymbol() + "_hash);");
477             }
478         }
479
480         /* build relations */
481         Iterator relations = state.stRelations.descriptors();
482
483         /* first pass create all the hash tables */
484         while (relations.hasNext()) {
485             RelationDescriptor relation = (RelationDescriptor) relations.next();
486
487             if (relation.testUsage(RelationDescriptor.IMAGE)) {
488                 crhead.outputline("struct SimpleHash* " + relation.getJustSafeSymbol() + "_hash;");
489                 craux.outputline(relation.getSafeSymbol() + "_hash = noargallocateSimpleHash();");
490             }
491
492             if (relation.testUsage(RelationDescriptor.INVIMAGE)) {
493                 crhead.outputline("struct SimpleHash* " + relation.getJustSafeSymbol() + "_hashinv;");
494                 craux.outputline(relation.getSafeSymbol() + "_hashinv = noargallocateSimpleHash();");
495             }
496         }
497
498         craux.endblock();
499         crhead.outputline("};");
500         craux.outputline("void free"+name+"(struct "+ name +"* thisvar)");
501         craux.startblock();
502         craux.outputline("/* deleting hashtables */");
503
504         /* build destructor */
505         sets = state.stSets.descriptors();
506
507         /* first pass create all the hash tables */
508         while (sets.hasNext()) {
509             SetDescriptor set = (SetDescriptor) sets.next();
510             craux.outputline("freeSimpleHash("+set.getSafeSymbol() + "_hash);");
511         }
512
513         /* destroy relations */
514         relations = state.stRelations.descriptors();
515
516         /* first pass create all the hash tables */
517         while (relations.hasNext()) {
518             RelationDescriptor relation = (RelationDescriptor) relations.next();
519
520             if (relation.testUsage(RelationDescriptor.IMAGE)) {
521                 craux.outputline("freeSimpleHash("+relation.getSafeSymbol() + "_hash);");
522             }
523
524             if (relation.testUsage(RelationDescriptor.INVIMAGE)) {
525                 craux.outputline("freeSimpleHash(" + relation.getSafeSymbol() + "_hashinv);");
526             }
527         }
528         craux.outputline("free(thisvar);");
529         craux.endblock();
530     }
531
532     private void generate_start() {
533         CodeWriter crhead = new StandardCodeWriter(outputhead);
534         CodeWriter craux = new StandardCodeWriter(outputaux);
535         oldmodel=VarDescriptor.makeNew("oldmodel");
536         newmodel=VarDescriptor.makeNew("newmodel");
537         worklist=VarDescriptor.makeNew("worklist");
538         goodflag=VarDescriptor.makeNew("goodflag");
539         repairtable=VarDescriptor.makeNew("repairtable");
540
541         if (Compiler.GENERATEINSTRUMENT) {
542             craux.outputline("int updatecount;");
543             craux.outputline("int rebuildcount;");
544             craux.outputline("int abstractcount;");
545         }
546
547         crhead.outputline("void doanalysis(struct "+name+"_state *);");
548         craux.outputline("void doanalysis(struct "+name+"_state * thisvar)");
549         craux.startblock();
550         craux.startBuffer();
551         if (Compiler.TIME) {
552             craux.outputline("struct timeval _begin_time,_end_time;");
553             craux.outputline("gettimeofday(&_begin_time,NULL);");
554         }
555         if (Compiler.GENERATEINSTRUMENT) {
556             craux.outputline("updatecount=0;");
557             craux.outputline("rebuildcount=0;");
558             craux.outputline("abstractcount=0;");
559         }
560         craux.addDeclaration("int","highmark");
561
562         craux.addDeclaration("struct "+name+ " * ",oldmodel.getSafeSymbol());
563         craux.outputline(oldmodel.getSafeSymbol()+"=0;");
564         craux.addDeclaration("struct WorkList * ",worklist.getSafeSymbol());
565         craux.outputline(worklist.getSafeSymbol()+" = allocateWorkList();");
566         craux.addDeclaration("struct RepairHash * ",repairtable.getSafeSymbol());
567         craux.outputline(repairtable.getSafeSymbol()+"=0;");
568         craux.outputline("initializestack(&highmark);");
569         craux.outputline("computesizes(thisvar);");
570         craux.outputline(name+"_staterecomputesizes(thisvar);");
571         craux.outputline("while (1)");
572         craux.startblock();
573         craux.addDeclaration("struct "+name+ " * ",newmodel.getSafeSymbol());
574         craux.outputline(newmodel.getSafeSymbol()+"=allocate"+name+"();");
575         craux.outputline("WorkListreset("+worklist.getSafeSymbol()+");");
576         if (Compiler.GENERATEINSTRUMENT)
577             craux.outputline("rebuildcount++;");
578     }
579
580     private void generate_teardown() {
581         CodeWriter cr = new StandardCodeWriter(outputaux);
582         cr.endblock();
583         if (Compiler.TIME) {
584             cr.outputline("gettimeofday(&_end_time,NULL);");
585             cr.outputline("printf(\"time=%ld uS\\n\",(_end_time.tv_sec-_begin_time.tv_sec)*1000000+_end_time.tv_usec-_begin_time.tv_usec);");
586         }
587
588         if (Compiler.GENERATEINSTRUMENT) {
589             cr.outputline("printf(\"updatecount=%d\\n\",updatecount);");
590             cr.outputline("printf(\"rebuildcount=%d\\n\",rebuildcount);");
591             cr.outputline("printf(\"abstractcount=%d\\n\",abstractcount);");
592         }
593
594     }
595
596     private void generate_print() {
597
598         final SymbolTable st = new SymbolTable();
599
600         CodeWriter cr = new StandardCodeWriter(outputaux) {
601                 public SymbolTable getSymbolTable() { return st; }
602             };
603
604         cr.outputline("/* printing sets!*/");
605         cr.outputline("printf(\"\\n\\nPRINTING SETS AND RELATIONS\\n\");");
606
607         Iterator setiterator = state.stSets.descriptors();
608         while (setiterator.hasNext()) {
609             SetDescriptor sd = (SetDescriptor) setiterator.next();
610             if (sd.getSymbol().equals("int") || sd.getSymbol().equals("token")) {
611                 continue;
612             }
613
614             String setname = sd.getSafeSymbol();
615
616             cr.startblock();
617             cr.outputline("/* printing set " + setname+"*/");
618             cr.outputline("printf(\"\\nPrinting set " + sd.getSymbol() + " - %d elements \\n\", SimpleHashcountset("+setname+"_hash));");
619             cr.addDeclaration("struct SimpleIterator","__setiterator");
620             cr.outputline("SimpleHashiterator("+setname+"_hash,&__setiterator);");
621             cr.outputline("while (hasNext(&__setiterator))");
622             cr.startblock();
623             cr.addDeclaration("int","__setval");
624             cr.outputline("__setval = (int) next(&__setiterator);");
625
626             TypeDescriptor td = sd.getType();
627             if (td instanceof StructureTypeDescriptor) {
628                 StructureTypeDescriptor std = (StructureTypeDescriptor) td;
629                 VarDescriptor vd = new VarDescriptor ("__setval", "__setval", td, false);
630                 std.generate_printout(cr, vd);
631             } else { // Missing type descriptor or reserved type, just print int
632                 cr.outputline("printf(\"<%d> \", __setval);");
633             }
634
635
636             cr.endblock();
637             cr.endblock();
638         }
639
640         cr.outputline("printf(\"\\n\\n------------------- END PRINTING\\n\");");
641     }
642
643     Set ruleset=null;
644     private void generate_rules() {
645         /* first we must sort the rules */
646         RelationDescriptor.prefix = newmodel.getSafeSymbol()+"->";
647         SetDescriptor.prefix = newmodel.getSafeSymbol()+"->";
648         System.out.println("SCC="+(mrd.numSCC()-1));
649         for(int sccindex=0;sccindex<mrd.numSCC();sccindex++) {
650             ruleset=mrd.getSCC(sccindex);
651             boolean needworklist=mrd.hasCycle(sccindex);
652
653             if (!needworklist) {
654                 Iterator iterator_rs = ruleset.iterator();
655                 while (iterator_rs.hasNext()) {
656                     Rule rule = (Rule) iterator_rs.next();
657                     if (rule.getnogenerate())
658                         continue;
659                     {
660                         final SymbolTable st = rule.getSymbolTable();
661                         CodeWriter cr = new StandardCodeWriter(outputaux) {
662                                 public SymbolTable getSymbolTable() { return st; }
663                             };
664                         InvariantValue ivalue=new InvariantValue();
665                         cr.setInvariantValue(ivalue);
666
667                         cr.outputline("/* build " +escape(rule.toString())+"*/");
668                         cr.startblock();
669                         cr.addDeclaration("int","maybe");
670                         cr.outputline("maybe=0;");
671
672                         Expr ruleexpr=rule.getGuardExpr();
673                         HashSet invariantvars=new HashSet();
674                         Set invariants=ruleexpr.findInvariants(invariantvars);
675
676                         if ((ruleexpr instanceof BooleanLiteralExpr)&&
677                             ((BooleanLiteralExpr)ruleexpr).getValue()) {
678                             if (rule.getInclusion() instanceof SetInclusion) {
679                                 invariants.addAll(((SetInclusion)rule.getInclusion()).getExpr().findInvariants(invariantvars));
680                             } else if (rule.getInclusion() instanceof RelationInclusion) {
681                                 invariants.addAll(((RelationInclusion)rule.getInclusion()).getLeftExpr().findInvariants(invariantvars));
682                                 invariants.addAll(((RelationInclusion)rule.getInclusion()).getRightExpr().findInvariants(invariantvars));
683                             }
684                         }
685                         ListIterator quantifiers = rule.quantifiers();
686                         while (quantifiers.hasNext()) {
687                             Quantifier quantifier = (Quantifier) quantifiers.next();
688                             if (quantifier instanceof ForQuantifier) {
689                                 ForQuantifier fq=(ForQuantifier)quantifier;
690                                 invariants.addAll(fq.lower.findInvariants(invariantvars));
691                                 invariants.addAll(fq.upper.findInvariants(invariantvars));
692                             }
693                         }
694
695                         int openparencount=0;
696                         for(Iterator invit=invariants.iterator();invit.hasNext();) {
697                             Expr invexpr=(Expr)invit.next();
698                             VarDescriptor tmpvd=VarDescriptor.makeNew("tmpvar");
699                             VarDescriptor maybevd=VarDescriptor.makeNew("maybevar");
700                             invexpr.generate(cr,tmpvd);
701                             cr.addDeclaration("int ",maybevd.getSafeSymbol());
702                             cr.outputline(maybevd.getSafeSymbol()+"=maybe;");
703                             cr.outputline("maybe=0;");
704                             ivalue.assignPair(invexpr,tmpvd,maybevd);
705                             openparencount++;
706                             cr.startblock();
707                         }
708                         quantifiers = rule.quantifiers();
709                         while (quantifiers.hasNext()) {
710                             Quantifier quantifier = (Quantifier) quantifiers.next();
711                             quantifier.generate_open(cr);
712                         }
713
714                         /* pretty print! */
715                         cr.output("/*");
716                         rule.getGuardExpr().prettyPrint(cr);
717                         cr.outputline("*/");
718
719                         /* now we have to generate the guard test */
720                         VarDescriptor guardval = VarDescriptor.makeNew();
721                         rule.getGuardExpr().generate(cr, guardval);
722                         cr.outputline("if (" + guardval.getSafeSymbol() + ")");
723                         cr.startblock();
724
725                         /* now we have to generate the inclusion code */
726                         currentrule=rule;
727                         rule.getInclusion().generate(cr);
728                         cr.endblock();
729                         while (quantifiers.hasPrevious()) {
730                             Quantifier quantifier = (Quantifier) quantifiers.previous();
731                             cr.endblock();
732                         }
733                         cr.endblock();
734                         while((openparencount--)>0)
735                             cr.endblock();
736                         cr.outputline("");
737                         cr.outputline("");
738                     }
739                 }
740             } else {
741                 CodeWriter cr2 = new StandardCodeWriter(outputaux);
742
743                 for(Iterator initialworklist=ruleset.iterator();initialworklist.hasNext();) {
744                     /** Construct initial worklist set */
745                     Rule rule=(Rule)initialworklist.next();
746                     cr2.outputline("WorkListadd("+worklist.getSafeSymbol()+","+rule.getNum()+",-1,0,0);");
747                 }
748
749                 cr2.outputline("while (WorkListhasMoreElements("+worklist.getSafeSymbol()+"))");
750                 cr2.startblock();
751                 VarDescriptor idvar=VarDescriptor.makeNew("id");
752                 cr2.addDeclaration("int ",idvar.getSafeSymbol());
753                 cr2.outputline(idvar.getSafeSymbol()+"=WorkListgetid("+worklist.getSafeSymbol()+");");
754
755                 String elseladder = "if";
756
757                 Iterator iterator_rules = ruleset.iterator();
758                 while (iterator_rules.hasNext()) {
759
760                     Rule rule = (Rule) iterator_rules.next();
761                     int dispatchid = rule.getNum();
762
763                     {
764                         final SymbolTable st = rule.getSymbolTable();
765                         CodeWriter cr = new StandardCodeWriter(outputaux) {
766                                 public SymbolTable getSymbolTable() { return st; }
767                             };
768
769                         cr.indent();
770                         cr.outputline(elseladder + " ("+idvar.getSafeSymbol()+" == " + dispatchid + ")");
771                         cr.startblock();
772                         cr.addDeclaration("int","maybe");
773                         cr.outputline("maybe=0;");
774                         VarDescriptor typevar=VarDescriptor.makeNew("type");
775                         VarDescriptor leftvar=VarDescriptor.makeNew("left");
776                         VarDescriptor rightvar=VarDescriptor.makeNew("right");
777                         cr.addDeclaration("int",typevar.getSafeSymbol());
778                         cr.outputline(typevar.getSafeSymbol()+"= WorkListgettype("+worklist.getSafeSymbol()+");");
779                         cr.addDeclaration("int",leftvar.getSafeSymbol());
780                         cr.outputline(leftvar.getSafeSymbol()+"= WorkListgetlvalue("+worklist.getSafeSymbol()+");");
781                         cr.addDeclaration("int",rightvar.getSafeSymbol());
782                         cr.outputline(rightvar.getSafeSymbol()+"= WorkListgetrvalue("+worklist.getSafeSymbol()+");");
783                         cr.outputline("/* build " +escape(rule.toString())+"*/");
784
785
786                         for (int j=0;j<rule.numQuantifiers();j++) {
787                             Quantifier quantifier = rule.getQuantifier(j);
788                             quantifier.generate_open(cr, typevar.getSafeSymbol(),j,leftvar.getSafeSymbol(),rightvar.getSafeSymbol());
789                         }
790
791                         /* pretty print! */
792                         cr.output("/*");
793
794                         rule.getGuardExpr().prettyPrint(cr);
795                         cr.outputline("*/");
796
797                         /* now we have to generate the guard test */
798
799                         VarDescriptor guardval = VarDescriptor.makeNew();
800                         rule.getGuardExpr().generate(cr, guardval);
801
802                         cr.outputline("if (" + guardval.getSafeSymbol() + ")");
803                         cr.startblock();
804
805                         /* now we have to generate the inclusion code */
806                         currentrule=rule;
807                         rule.getInclusion().generate(cr);
808                         cr.endblock();
809
810                         for (int j=0;j<rule.numQuantifiers();j++) {
811                             cr.endblock();
812                         }
813
814                         // close startblocks generated by DotExpr memory checks
815                         //DotExpr.generate_memory_endblocks(cr);
816
817                         cr.endblock(); // end else-if WORKLIST ladder
818
819                         elseladder = "else if";
820                     }
821                 }
822                 cr2.outputline("else");
823                 cr2.startblock();
824                 cr2.outputline("printf(\"VERY BAD !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\\n\\n\");");
825                 cr2.outputline("exit(1);");
826                 cr2.endblock();
827                 // end block created for worklist
828                 cr2.outputline("WorkListpop("+worklist.getSafeSymbol()+");");
829                 cr2.endblock();
830             }
831         }
832     }
833
834     public static String escape(String s) {
835         String newstring="";
836         for(int i=0;i<s.length();i++) {
837             char c=s.charAt(i);
838             if (c=='"')
839                 newstring+="\"";
840             else
841                 newstring+=c;
842         }
843         return newstring;
844     }
845
846     private void generate_checks() {
847         /* do constraint checks */
848         Iterator i;
849         if (Compiler.REPAIR)
850             i=termination.constraintdependence.computeOrdering().iterator();
851         else
852             i=state.vConstraints.iterator();
853         for (; i.hasNext();) {
854             Constraint constraint;
855             if (Compiler.REPAIR)
856                 constraint= (Constraint) ((GraphNode)i.next()).getOwner();
857             else
858                 constraint=(Constraint)i.next();
859
860             {
861                 final SymbolTable st = constraint.getSymbolTable();
862                 CodeWriter cr = new StandardCodeWriter(outputaux);
863                 cr.pushSymbolTable(constraint.getSymbolTable());
864
865                 cr.outputline("/* checking " + escape(constraint.toString())+"*/");
866                 cr.startblock();
867
868                 ListIterator quantifiers = constraint.quantifiers();
869
870                 while (quantifiers.hasNext()) {
871                     Quantifier quantifier = (Quantifier) quantifiers.next();
872                     quantifier.generate_open(cr);
873                 }
874
875                 cr.addDeclaration("int","maybe");
876                 cr.outputline("maybe = 0;");
877
878                 /* now we have to generate the guard test */
879
880                 VarDescriptor constraintboolean = VarDescriptor.makeNew("constraintboolean");
881                 constraint.getLogicStatement().generate(cr, constraintboolean);
882
883                 cr.outputline("if (maybe)");
884                 cr.startblock();
885                 cr.outputline("printf(\"maybe fail " +  escape(constraint.toString()) + ". \\n\");");
886                 //cr.outputline("exit(1);");
887                 cr.endblock();
888
889                 cr.outputline("else if (!" + constraintboolean.getSafeSymbol() + ")");
890                 cr.startblock();
891                 if (!Compiler.REPAIR||Compiler.GENERATEDEBUGHOOKS)
892                     cr.outputline("printf(\"fail " + escape(constraint.toString()) + ". \\n\");");
893
894                 if (Compiler.REPAIR) {
895                 /* Do repairs */
896                 /* Build new repair table */
897
898                 cr.outputline("if ("+repairtable.getSafeSymbol()+")");
899                 cr.outputline("freeRepairHash("+repairtable.getSafeSymbol()+");");
900                 cr.outputline(repairtable.getSafeSymbol()+"=noargallocateRepairHash();");
901
902                 if (Compiler.GENERATEDEBUGHOOKS)
903                     cr.outputline("debughook();");
904                 /* Compute cost of each repair */
905                 VarDescriptor mincost=VarDescriptor.makeNew("mincost");
906                 VarDescriptor mincostindex=VarDescriptor.makeNew("mincostindex");
907                 Vector dnfconst=new Vector();
908                 dnfconst.addAll((Set)termination.conjunctionmap.get(constraint));
909
910                 if (dnfconst.size()<=1) {
911                     cr.addDeclaration("int",mincostindex.getSafeSymbol());
912                     cr.outputline(mincostindex.getSafeSymbol()+"=0;");
913                 }
914                 if (dnfconst.size()>1) {
915                     cr.addDeclaration("int",mincostindex.getSafeSymbol());
916                     boolean first=true;
917                     for(int j=0;j<dnfconst.size();j++) {
918                         GraphNode gn=(GraphNode)dnfconst.get(j);
919                         Conjunction conj=((TermNode)gn.getOwner()).getConjunction();
920                         if (removed.contains(gn))
921                             continue;
922
923                         VarDescriptor costvar;
924                         if (first) {
925                             costvar=mincost;
926                         } else
927                             costvar=VarDescriptor.makeNew("cost");
928                         for(int k=0;k<conj.size();k++) {
929                             DNFPredicate dpred=conj.get(k);
930                             Predicate p=dpred.getPredicate();
931                             boolean negate=dpred.isNegated();
932                             VarDescriptor predvalue=VarDescriptor.makeNew("Predicatevalue");
933                             p.generate(cr,predvalue);
934                             if (k==0) {
935                                 cr.addDeclaration("int",costvar.getSafeSymbol());
936                                 cr.outputline(costvar.getSafeSymbol()+"=0;");
937                             }
938                             if (negate)
939                                 cr.outputline("if (maybe||"+predvalue.getSafeSymbol()+")");
940                             else
941                                 cr.outputline("if (maybe||!"+predvalue.getSafeSymbol()+")");
942                             cr.outputline(costvar.getSafeSymbol()+"+="+cost.getCost(dpred)+";");
943                         }
944
945                         if(!first) {
946                             cr.outputline("if ("+costvar.getSafeSymbol()+"<"+mincost.getSafeSymbol()+")");
947                             cr.startblock();
948                             cr.outputline(mincost.getSafeSymbol()+"="+costvar.getSafeSymbol()+";");
949                             cr.outputline(mincostindex.getSafeSymbol()+"="+j+";");
950                             cr.endblock();
951                         } else
952                             cr.outputline(mincostindex.getSafeSymbol()+"="+j+";");
953                         first=false;
954                     }
955                 }
956                 cr.outputline("switch("+mincostindex.getSafeSymbol()+")");
957                 cr.startblock();
958                 for(int j=0;j<dnfconst.size();j++) {
959                     GraphNode gn=(GraphNode)dnfconst.get(j);
960                     Conjunction conj=((TermNode)gn.getOwner()).getConjunction();
961                     if (removed.contains(gn))
962                         continue;
963                     cr.outputline("case "+j+":");
964                     cr.startblock();
965                     for(int k=0;k<conj.size();k++) {
966                         DNFPredicate dpred=conj.get(k);
967                         Predicate p=dpred.getPredicate();
968                         boolean negate=dpred.isNegated();
969                         VarDescriptor predvalue=VarDescriptor.makeNew("Predicatevalue");
970                         p.generate(cr,predvalue);
971                         if (negate)
972                             cr.outputline("if (maybe||"+predvalue.getSafeSymbol()+")");
973                         else
974                             cr.outputline("if (maybe||!"+predvalue.getSafeSymbol()+")");
975                         cr.startblock();
976                         if (Compiler.GENERATEINSTRUMENT)
977                             cr.outputline("abstractcount++;");
978                         if (p instanceof InclusionPredicate)
979                             generateinclusionrepair(conj,dpred, cr);
980                         else if (p instanceof ExprPredicate) {
981                             ExprPredicate ep=(ExprPredicate)p;
982                             if (ep.getType()==ExprPredicate.SIZE)
983                                 generatesizerepair(conj,dpred,cr);
984                             else if (ep.getType()==ExprPredicate.COMPARISON)
985                                 generatecomparisonrepair(conj,dpred,cr);
986                         } else throw new Error("Unrecognized Predicate");
987                         cr.endblock();
988                     }
989                     /* Update model */
990                     cr.endblock();
991                     cr.outputline("break;");
992                 }
993                 cr.endblock();
994
995                 cr.outputline("if ("+oldmodel.getSafeSymbol()+")");
996                 cr.outputline("free"+name+"("+oldmodel.getSafeSymbol()+");");
997                 cr.outputline(oldmodel.getSafeSymbol()+"="+newmodel.getSafeSymbol()+";");
998                 cr.outputline("goto rebuild;");  /* Rebuild model and all */
999                 }
1000                 cr.endblock();
1001
1002                 while (quantifiers.hasPrevious()) {
1003                     Quantifier quantifier = (Quantifier) quantifiers.previous();
1004                     cr.endblock();
1005                 }
1006                 cr.endblock();
1007                 cr.outputline("");
1008                 cr.outputline("");
1009             }
1010         }
1011         CodeWriter cr = new StandardCodeWriter(outputaux);
1012         cr.startblock();
1013         cr.outputline("if ("+repairtable.getSafeSymbol()+")");
1014         cr.outputline("freeRepairHash("+repairtable.getSafeSymbol()+");");
1015         cr.outputline("if ("+oldmodel.getSafeSymbol()+")");
1016         cr.outputline("free"+name+"("+oldmodel.getSafeSymbol()+");");
1017         cr.outputline("free"+name+"("+newmodel.getSafeSymbol()+");");
1018         cr.outputline("freeWorkList("+worklist.getSafeSymbol()+");");
1019         cr.outputline("resettypemap();");
1020         cr.outputline("break;");
1021         cr.endblock();
1022         cr.outputline("rebuild:");
1023         cr.outputline(";");
1024     }
1025
1026     private MultUpdateNode getmultupdatenode(Conjunction conj, DNFPredicate dpred, int repairtype) {
1027         Set nodes=getmultupdatenodeset(conj,dpred,repairtype);
1028         Iterator it=nodes.iterator();
1029         if (it.hasNext())
1030             return (MultUpdateNode)it.next();
1031         else
1032             return null;
1033     }
1034
1035     private Set getmultupdatenodeset(Conjunction conj, DNFPredicate dpred, int repairtype) {
1036         HashSet hs=new HashSet();
1037         GraphNode gn=(GraphNode) termination.conjtonodemap.get(conj);
1038         for(Iterator edgeit=gn.edges();edgeit.hasNext();) {
1039             GraphNode gn2=((GraphNode.Edge) edgeit.next()).getTarget();
1040             TermNode tn2=(TermNode)gn2.getOwner();
1041             if (tn2.getType()==TermNode.ABSTRACT) {
1042                 AbstractRepair ar=tn2.getAbstract();
1043                 if (((repairtype==-1)||(ar.getType()==repairtype))&&
1044                     ar.getPredicate()==dpred) {
1045                     for(Iterator edgeit2=gn2.edges();edgeit2.hasNext();) {
1046                         GraphNode gn3=((GraphNode.Edge) edgeit2.next()).getTarget();
1047                         if (!removed.contains(gn3)) {
1048                             TermNode tn3=(TermNode)gn3.getOwner();
1049                             if (tn3.getType()==TermNode.UPDATE) {
1050                                 hs.add(tn3.getUpdate());
1051                             }
1052                         }
1053                     }
1054                 }
1055             }
1056         }
1057         return hs;
1058     }
1059
1060     private AbstractRepair getabstractrepair(Conjunction conj, DNFPredicate dpred, int repairtype) {
1061         HashSet hs=new HashSet();
1062         MultUpdateNode mun=null;
1063         GraphNode gn=(GraphNode) termination.conjtonodemap.get(conj);
1064         for(Iterator edgeit=gn.edges();(mun==null)&&edgeit.hasNext();) {
1065             GraphNode gn2=((GraphNode.Edge) edgeit.next()).getTarget();
1066             TermNode tn2=(TermNode)gn2.getOwner();
1067             if (tn2.getType()==TermNode.ABSTRACT) {
1068                 AbstractRepair ar=tn2.getAbstract();
1069                 if (((repairtype==-1)||(ar.getType()==repairtype))&&
1070                     ar.getPredicate()==dpred) {
1071                     return ar;
1072                 }
1073             }
1074         }
1075         return null;
1076     }
1077
1078
1079     /** Generates abstract (and concrete) repair for a comparison */
1080
1081     private void generatecomparisonrepair(Conjunction conj, DNFPredicate dpred, CodeWriter cr){
1082         Set updates=getmultupdatenodeset(conj,dpred,AbstractRepair.MODIFYRELATION);
1083         AbstractRepair ar=getabstractrepair(conj,dpred,AbstractRepair.MODIFYRELATION);
1084         MultUpdateNode munmodify=null;
1085         MultUpdateNode munadd=null;
1086         MultUpdateNode munremove=null;
1087         for(Iterator it=updates.iterator();it.hasNext();) {
1088             MultUpdateNode mun=(MultUpdateNode)it.next();
1089             if (mun.getType()==MultUpdateNode.ADD) {
1090                 munadd=mun;
1091             } else if (mun.getType()==MultUpdateNode.REMOVE) {
1092                 munremove=mun;
1093             } else if (mun.getType()==MultUpdateNode.MODIFY) {
1094                 munmodify=mun;
1095             }
1096         }
1097
1098         ExprPredicate ep=(ExprPredicate)dpred.getPredicate();
1099         RelationDescriptor rd=(RelationDescriptor)ep.getDescriptor();
1100         boolean usageimage=rd.testUsage(RelationDescriptor.IMAGE);
1101         boolean usageinvimage=rd.testUsage(RelationDescriptor.INVIMAGE);
1102         boolean inverted=ep.inverted();
1103         boolean negated=dpred.isNegated();
1104         OpExpr expr=(OpExpr)ep.expr;
1105         Opcode opcode=expr.getOpcode();
1106         VarDescriptor leftside=VarDescriptor.makeNew("leftside");
1107         VarDescriptor rightside=VarDescriptor.makeNew("rightside");
1108         VarDescriptor newvalue=VarDescriptor.makeNew("newvalue");
1109         boolean needremoveloop=ar.mayNeedFunctionEnforcement(state)&&ar.needsRemoves(state);
1110
1111         if (needremoveloop&&((munadd==null)||(munremove==null))) {
1112             System.out.println("Warning:  need to have individual remove operations for"+dpred.name());
1113             needremoveloop=false;
1114         }
1115         if (needremoveloop) {
1116             cr.outputline("while (1)");
1117             cr.startblock();
1118         }
1119         if (!inverted) {
1120             ((RelationExpr)expr.getLeftExpr()).getExpr().generate(cr,leftside);
1121             expr.getRightExpr().generate(cr,newvalue);
1122             cr.addDeclaration(rd.getRange().getType().getGenerateType().getSafeSymbol(),rightside.getSafeSymbol());
1123             cr.outputline("SimpleHashget("+rd.getSafeSymbol()+"_hash,"+leftside.getSafeSymbol()+", &"+rightside.getSafeSymbol()+");");
1124         } else {
1125             ((RelationExpr)expr.getLeftExpr()).getExpr().generate(cr,rightside);
1126             expr.getRightExpr().generate(cr,newvalue);
1127             cr.outputline(rd.getDomain().getType().getGenerateType().getSafeSymbol()+" "+leftside.getSafeSymbol()+";");
1128             cr.outputline("SimpleHashget("+rd.getSafeSymbol()+"_hashinv,"+rightside.getSafeSymbol()+", &"+leftside.getSafeSymbol()+");");
1129         }
1130
1131         opcode=Opcode.translateOpcode(negated,opcode);
1132
1133         if (opcode==Opcode.GT) {
1134             cr.outputline(newvalue.getSafeSymbol()+"++;");
1135         } else if (opcode==Opcode.GE) {
1136             /* Equal */
1137         } else if (opcode==Opcode.LT) {
1138             cr.outputline(newvalue.getSafeSymbol()+"--;");
1139         } else if (opcode==Opcode.LE) {
1140             /* Equal */
1141         } else if (opcode==Opcode.EQ) {
1142             /* Equal */
1143         } else if (opcode==Opcode.NE) { /* search for FLAGNE if this is changed*/
1144             cr.outputline(newvalue.getSafeSymbol()+"++;");
1145         } else {
1146             throw new Error("Unrecognized Opcode");
1147         }
1148         /* Do abstract repairs */
1149         if (usageimage) {
1150             cr.outputline("SimpleHashremove("+rd.getSafeSymbol()+"_hash, "+leftside.getSafeSymbol()+","+rightside.getSafeSymbol()+");");
1151         }
1152         if (usageinvimage) {
1153             cr.outputline("SimpleHashremove("+rd.getSafeSymbol()+"_hashinv, "+rightside.getSafeSymbol()+","+leftside.getSafeSymbol()+");");
1154         }
1155
1156         if (needremoveloop) {
1157             if (!inverted) {
1158                 cr.outputline("if (SimpleHashcontainskey("+rd.getSafeSymbol()+"_hash, "+leftside.getSafeSymbol()+"))");
1159                 cr.startblock();
1160             } else {
1161                 cr.outputline("if (SimpleHashcontainskey("+rd.getSafeSymbol()+"_hashinv, "+rightside.getSafeSymbol()+"))");
1162                 cr.startblock();
1163             }
1164             for(int i=0;i<state.vRules.size();i++) {
1165                 Rule r=(Rule)state.vRules.get(i);
1166                 if (r.getInclusion().getTargetDescriptors().contains(rd)) {
1167                     for(int j=0;j<munremove.numUpdates();j++) {
1168                         UpdateNode un=munremove.getUpdate(i);
1169                         if (un.getRule()==r) {
1170                                 /* Update for rule r */
1171                             String name=(String)updatenames.get(un);
1172                             cr.outputline("RepairHashaddrelation("+repairtable.getSafeSymbol()+","+rd.getNum()+","+r.getNum()+","+leftside.getSafeSymbol()+","+rightside.getSafeSymbol()+",(int) &"+name+");");
1173                         }
1174                     }
1175                 }
1176             }
1177             cr.outputline("continue;");
1178             cr.endblock();
1179         }
1180
1181         if (usageimage) {
1182             if (!inverted) {
1183                 cr.outputline("SimpleHashadd("+rd.getSafeSymbol()+"_hash,"+leftside.getSafeSymbol()+","+newvalue.getSafeSymbol()+");");
1184             } else {
1185                 cr.outputline("SimpleHashadd("+rd.getSafeSymbol()+"_hash, "+newvalue.getSafeSymbol()+","+rightside.getSafeSymbol()+");");
1186             }
1187         }
1188         if (usageinvimage) {
1189             if (!inverted) {
1190                 cr.outputline("SimpleHashadd("+rd.getSafeSymbol()+"_hashinv, "+newvalue.getSafeSymbol()+","+leftside.getSafeSymbol()+");");
1191             } else {
1192                 cr.outputline("SimpleHashadd("+rd.getSafeSymbol()+"_hashinv,"+rightside.getSafeSymbol()+","+newvalue.getSafeSymbol()+");");
1193             }
1194         }
1195         /* Do concrete repairs */
1196         if (munmodify!=null&&(!ar.mayNeedFunctionEnforcement(state))||(munadd==null)||(ar.needsRemoves(state)&&(munremove==null))) {
1197             for(int i=0;i<state.vRules.size();i++) {
1198                 Rule r=(Rule)state.vRules.get(i);
1199                 if (r.getInclusion().getTargetDescriptors().contains(rd)) {
1200                     for(int j=0;j<munmodify.numUpdates();j++) {
1201                         UpdateNode un=munmodify.getUpdate(j);
1202                         if (un.getRule()==r) {
1203                             /* Update for rule r */
1204                             String name=(String)updatenames.get(un);
1205                             cr.outputline("RepairHashaddrelation2("+repairtable.getSafeSymbol()+","+rd.getNum()+","+r.getNum()+","+leftside.getSafeSymbol()+","+rightside.getSafeSymbol()+",(int) &"+name+","+newvalue.getSafeSymbol()+");");
1206                         }
1207                     }
1208                 }
1209             }
1210         } else {
1211             /* Start with scheduling removal */
1212             if (ar.needsRemoves(state))
1213                 for(int i=0;i<state.vRules.size();i++) {
1214                     Rule r=(Rule)state.vRules.get(i);
1215                     if (r.getInclusion().getTargetDescriptors().contains(rd)) {
1216                         for(int j=0;j<munremove.numUpdates();j++) {
1217                             UpdateNode un=munremove.getUpdate(i);
1218                             if (un.getRule()==r) {
1219                                 /* Update for rule r */
1220                                 String name=(String)updatenames.get(un);
1221                                 cr.outputline("RepairHashaddrelation("+repairtable.getSafeSymbol()+","+rd.getNum()+","+r.getNum()+","+leftside.getSafeSymbol()+","+rightside.getSafeSymbol()+",(int) &"+name+");");
1222                             }
1223                         }
1224                     }
1225                 }
1226             /* Now do addition */
1227             UpdateNode un=munadd.getUpdate(0);
1228             String name=(String)updatenames.get(un);
1229             if (!inverted) {
1230                 cr.outputline(name+"(thisvar,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+leftside.getSafeSymbol()+","+newvalue.getSafeSymbol()+");");
1231             } else {
1232                 cr.outputline(name+"(thisvar,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+newvalue.getSafeSymbol()+","+rightside.getSafeSymbol()+");");
1233             }
1234         }
1235         if (needremoveloop) {
1236             cr.outputline("break;");
1237             cr.endblock();
1238         }
1239     }
1240
1241     public void generatesizerepair(Conjunction conj, DNFPredicate dpred, CodeWriter cr) {
1242         ExprPredicate ep=(ExprPredicate)dpred.getPredicate();
1243         OpExpr expr=(OpExpr)ep.expr;
1244         Opcode opcode=expr.getOpcode();
1245         opcode=Opcode.translateOpcode(dpred.isNegated(),opcode);
1246
1247         MultUpdateNode munremove;
1248
1249         MultUpdateNode munadd;
1250         if (ep.getDescriptor() instanceof RelationDescriptor) {
1251             munremove=getmultupdatenode(conj,dpred,AbstractRepair.REMOVEFROMRELATION);
1252             munadd=getmultupdatenode(conj,dpred,AbstractRepair.ADDTORELATION);
1253         } else {
1254             munremove=getmultupdatenode(conj,dpred,AbstractRepair.REMOVEFROMSET);
1255             munadd=getmultupdatenode(conj,dpred,AbstractRepair.ADDTOSET);
1256         }
1257         int size=ep.rightSize();
1258         VarDescriptor sizevar=VarDescriptor.makeNew("size");
1259         ((OpExpr)expr).left.generate(cr, sizevar);
1260         VarDescriptor change=VarDescriptor.makeNew("change");
1261         cr.addDeclaration("int",change.getSafeSymbol());
1262         boolean generateadd=false;
1263         boolean generateremove=false;
1264         if (opcode==Opcode.GT) {
1265             cr.outputline(change.getSafeSymbol()+"="+String.valueOf(size+1)+"-"+sizevar.getSafeSymbol()+";");
1266             generateadd=true;
1267             generateremove=false;
1268         } else if (opcode==Opcode.GE) {
1269             cr.outputline(change.getSafeSymbol()+"="+String.valueOf(size)+"-"+sizevar.getSafeSymbol()+";");
1270             generateadd=true;
1271             generateremove=false;
1272         } else if (opcode==Opcode.LT) {
1273             cr.outputline(change.getSafeSymbol()+"="+String.valueOf(size-1)+"-"+sizevar.getSafeSymbol()+";");
1274             generateadd=false;
1275             generateremove=true;
1276         } else if (opcode==Opcode.LE) {
1277             cr.outputline(change.getSafeSymbol()+"="+String.valueOf(size)+"-"+sizevar.getSafeSymbol()+";");
1278             generateadd=false;
1279             generateremove=true;
1280         } else if (opcode==Opcode.EQ) {
1281             cr.outputline(change.getSafeSymbol()+"="+String.valueOf(size)+"-"+sizevar.getSafeSymbol()+";");
1282             if (size==0)
1283                 generateadd=false;
1284             else
1285                 generateadd=true;
1286             generateremove=true;
1287         } else if (opcode==Opcode.NE) {
1288             cr.outputline(change.getSafeSymbol()+"="+String.valueOf(size+1)+"-"+sizevar.getSafeSymbol()+";");
1289             generateadd=true;
1290             generateremove=false;
1291         } else {
1292             throw new Error("Unrecognized Opcode");
1293         }
1294
1295 // In some cases the analysis has determined that generating removes
1296 // is unnecessary
1297         if (generateremove&&munremove==null)
1298             generateremove=false;
1299
1300         Descriptor d=ep.getDescriptor();
1301         if (generateremove) {
1302             cr.outputline("for(;"+change.getSafeSymbol()+"<0;"+change.getSafeSymbol()+"++)");
1303             cr.startblock();
1304             /* Find element to remove */
1305             VarDescriptor leftvar=VarDescriptor.makeNew("leftvar");
1306             VarDescriptor rightvar=VarDescriptor.makeNew("rightvar");
1307             if (d instanceof RelationDescriptor) {
1308                 if (ep.inverted()) {
1309                     ((ImageSetExpr)((SizeofExpr)expr.left).setexpr).generate_leftside(cr,rightvar);
1310                     cr.addDeclaration("int",leftvar.getSafeSymbol());
1311                     cr.outputline("SimpleHashget("+d.getSafeSymbol()+"_hashinv,(int)"+rightvar.getSafeSymbol()+", &"+leftvar.getSafeSymbol()+");");
1312                 } else {
1313                     ((ImageSetExpr)((SizeofExpr)expr.left).setexpr).generate_leftside(cr,leftvar);
1314                     cr.addDeclaration("int",rightvar.getSafeSymbol());
1315                     cr.outputline("SimpleHashget("+d.getSafeSymbol()+"_hash ,(int)"+leftvar.getSafeSymbol()+", &"+rightvar.getSafeSymbol()+");");
1316                 }
1317             } else {
1318                 cr.addDeclaration("int",leftvar.getSafeSymbol());
1319                 cr.outputline(leftvar.getSafeSymbol()+"= SimpleHashfirstkey("+d.getSafeSymbol()+"_hash);");
1320             }
1321             /* Generate abstract remove instruction */
1322             if (d instanceof RelationDescriptor) {
1323                 RelationDescriptor rd=(RelationDescriptor) d;
1324                 boolean usageimage=rd.testUsage(RelationDescriptor.IMAGE);
1325                 boolean usageinvimage=rd.testUsage(RelationDescriptor.INVIMAGE);
1326                 if (usageimage)
1327                     cr.outputline("SimpleHashremove("+rd.getSafeSymbol()+"_hash, (int)" + leftvar.getSafeSymbol() + ", (int)" + rightvar.getSafeSymbol() + ");");
1328                 if (usageinvimage)
1329                     cr.outputline("SimpleHashremove("+rd.getSafeSymbol()+"_hashinv ,(int)" + rightvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
1330             } else {
1331                 cr.outputline("SimpleHashremove("+d.getSafeSymbol()+"_hash, (int)" + leftvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
1332             }
1333             /* Generate concrete remove instruction */
1334             for(int i=0;i<state.vRules.size();i++) {
1335                 Rule r=(Rule)state.vRules.get(i);
1336                 if (r.getInclusion().getTargetDescriptors().contains(d)) {
1337                     for(int j=0;j<munremove.numUpdates();j++) {
1338                         UpdateNode un=munremove.getUpdate(j);
1339                         if (un.getRule()==r) {
1340                                 /* Update for rule rule r */
1341                             String name=(String)updatenames.get(un);
1342                             if (d instanceof RelationDescriptor) {
1343                                 cr.outputline("RepairHashaddrelation("+repairtable.getSafeSymbol()+","+d.getNum()+","+r.getNum()+","+leftvar.getSafeSymbol()+","+rightvar.getSafeSymbol()+",(int) &"+name+");");
1344                             } else {
1345                                 cr.outputline("RepairHashaddset("+repairtable.getSafeSymbol()+","+d.getNum()+","+r.getNum()+","+leftvar.getSafeSymbol()+",(int) &"+name+");");
1346                             }
1347                         }
1348                     }
1349                 }
1350             }
1351             cr.endblock();
1352         }
1353
1354 // In some cases the analysis has determined that generating removes
1355 // is unnecessary
1356         if (generateadd&&munadd==null)
1357             generateadd=false;
1358
1359         if (generateadd) {
1360
1361             cr.outputline("for(;"+change.getSafeSymbol()+">0;"+change.getSafeSymbol()+"--)");
1362             cr.startblock();
1363             VarDescriptor newobject=VarDescriptor.makeNew("newobject");
1364             if (d instanceof RelationDescriptor) {
1365                 VarDescriptor otherside=VarDescriptor.makeNew("otherside");
1366                 ((ImageSetExpr)((SizeofExpr)expr.left).setexpr).generate_leftside(cr,otherside);
1367
1368                 RelationDescriptor rd=(RelationDescriptor)d;
1369                 if (termination.sources.relsetSource(rd,!ep.inverted())) {
1370                     /* Set Source */
1371                     SetDescriptor sd=termination.sources.relgetSourceSet(rd,!ep.inverted());
1372                     VarDescriptor iterator=VarDescriptor.makeNew("iterator");
1373                     cr.addDeclaration(sd.getType().getGenerateType().getSafeSymbol(),newobject.getSafeSymbol());
1374                     cr.addDeclaration("struct SimpleIterator",iterator.getSafeSymbol());
1375                     cr.outputline("for(SimpleHashiterator("+sd.getSafeSymbol()+"_hash , &"+ iterator.getSafeSymbol() +"); hasNext(&"+iterator.getSafeSymbol()+");)");
1376                     cr.startblock();
1377                     if (ep.inverted()) {
1378                         cr.outputline("if (!SimpleHashcontainskeydata("+rd.getSafeSymbol()+"_hashinv,"+iterator.getSafeSymbol()+".key(),"+otherside.getSafeSymbol()+"))");
1379                     } else {
1380                         cr.outputline("if (!SimpleHashcontainskeydata("+rd.getSafeSymbol()+"_hash, "+otherside.getSafeSymbol()+","+iterator.getSafeSymbol()+".key()))");
1381                     }
1382                     cr.outputline(newobject.getSafeSymbol()+"=key(&"+iterator.getSafeSymbol()+");");
1383                     cr.outputline("next(&"+iterator.getSafeSymbol()+");");
1384                     cr.endblock();
1385                 } else if (termination.sources.relallocSource(rd,!ep.inverted())) {
1386                     /* Allocation Source*/
1387                     termination.sources.relgenerateSourceAlloc(cr,newobject,rd,!ep.inverted());
1388                 } else throw new Error("No source for adding to Relation");
1389                 if (ep.inverted()) {
1390                     boolean usageimage=rd.testUsage(RelationDescriptor.IMAGE);
1391                     boolean usageinvimage=rd.testUsage(RelationDescriptor.INVIMAGE);
1392                     if (usageimage)
1393                         cr.outputline("SimpleHashadd("+rd.getSafeSymbol()+"_hash, "+newobject.getSafeSymbol()+","+otherside.getSafeSymbol()+");");
1394                     if (usageinvimage)
1395                         cr.outputline("SimpleHashadd("+rd.getSafeSymbol()+"_hashinv, "+otherside.getSafeSymbol()+","+newobject.getSafeSymbol()+");");
1396
1397                     UpdateNode un=munadd.getUpdate(0);
1398                     String name=(String)updatenames.get(un);
1399                     cr.outputline(name+"(thisvar,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+newobject.getSafeSymbol()+","+otherside.getSafeSymbol()+");");
1400                 } else {
1401                     boolean usageimage=rd.testUsage(RelationDescriptor.IMAGE);
1402                     boolean usageinvimage=rd.testUsage(RelationDescriptor.INVIMAGE);
1403                     if (usageimage)
1404                         cr.outputline("SimpleHashadd("+rd.getSafeSymbol()+"_hash, "+otherside.getSafeSymbol()+","+newobject.getSafeSymbol()+");");
1405                     if (usageinvimage)
1406                         cr.outputline("SimpleHashadd("+rd.getSafeSymbol()+"_hashinv, "+newobject.getSafeSymbol()+","+otherside.getSafeSymbol()+");");
1407                     UpdateNode un=munadd.getUpdate(0);
1408                     String name=(String)updatenames.get(un);
1409                     cr.outputline(name+"(thisvar, "+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+otherside.getSafeSymbol()+","+newobject.getSafeSymbol()+");");
1410                 }
1411             } else {
1412                 SetDescriptor sd=(SetDescriptor)d;
1413                 if (termination.sources.setSource(sd)) {
1414                     /* Set Source */
1415                     /* Set Source */
1416                     SetDescriptor sourcesd=termination.sources.getSourceSet(sd);
1417                     VarDescriptor iterator=VarDescriptor.makeNew("iterator");
1418                     cr.addDeclaration(sourcesd.getType().getGenerateType().getSafeSymbol(), newobject.getSafeSymbol());
1419                     cr.addDeclaration("struct SimpleIterator",iterator.getSafeSymbol());
1420                     cr.outputline("for(SimpleHashiterator("+sourcesd.getSafeSymbol()+"_hash, &"+iterator.getSafeSymbol()+"); hasNext(&"+iterator.getSafeSymbol()+");)");
1421                     cr.startblock();
1422                     cr.outputline("if (!SimpleHashcontainskey("+sd.getSafeSymbol()+"_hash, key(&"+iterator.getSafeSymbol()+")))");
1423                     cr.outputline(newobject.getSafeSymbol()+"=key(&"+iterator.getSafeSymbol()+");");
1424                     cr.outputline("next(&"+iterator.getSafeSymbol()+");");
1425                     cr.endblock();
1426                 } else if (termination.sources.allocSource(sd)) {
1427                     /* Allocation Source*/
1428                     termination.sources.generateSourceAlloc(cr,newobject,sd);
1429                 } else throw new Error("No source for adding to Set");
1430                 cr.outputline("SimpleHashadd("+sd.getSafeSymbol()+"_hash, "+newobject.getSafeSymbol()+","+newobject.getSafeSymbol()+");");
1431                 UpdateNode un=munadd.getUpdate(0);
1432                 String name=(String)updatenames.get(un);
1433                 cr.outputline(name+"(thisvar,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+newobject.getSafeSymbol()+");");
1434             }
1435             cr.endblock();
1436         }
1437     }
1438
1439     public void generateinclusionrepair(Conjunction conj, DNFPredicate dpred, CodeWriter cr){
1440         InclusionPredicate ip=(InclusionPredicate) dpred.getPredicate();
1441         boolean negated=dpred.isNegated();
1442         MultUpdateNode mun=getmultupdatenode(conj,dpred,-1);
1443         VarDescriptor leftvar=VarDescriptor.makeNew("left");
1444         ip.expr.generate(cr, leftvar);
1445
1446         if (negated) {
1447             if (ip.setexpr instanceof ImageSetExpr) {
1448                 ImageSetExpr ise=(ImageSetExpr) ip.setexpr;
1449                 VarDescriptor rightvar=ise.getVar();
1450                 boolean inverse=ise.inverted();
1451                 RelationDescriptor rd=ise.getRelation();
1452                 boolean usageimage=rd.testUsage(RelationDescriptor.IMAGE);
1453                 boolean usageinvimage=rd.testUsage(RelationDescriptor.INVIMAGE);
1454                 if (inverse) {
1455                     if (usageimage)
1456                         cr.outputline("SimpleHashremove("+rd.getSafeSymbol()+"_hash, (int)" + rightvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
1457                     if (usageinvimage)
1458                         cr.outputline("SimpleHashremove("+rd.getSafeSymbol()+"_hashinv, (int)" + leftvar.getSafeSymbol() + ", (int)" + rightvar.getSafeSymbol() + ");");
1459                 } else {
1460                     if (usageimage)
1461                         cr.outputline("SimpleHashremove("+rd.getSafeSymbol()+"_hash ,(int)" + leftvar.getSafeSymbol() + ", (int)" + rightvar.getSafeSymbol() + ");");
1462                     if (usageinvimage)
1463                         cr.outputline("SimpleHashremove("+rd.getSafeSymbol()+"_hashinv, (int)" + rightvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
1464                 }
1465                 for(int i=0;i<state.vRules.size();i++) {
1466                     Rule r=(Rule)state.vRules.get(i);
1467                     if (r.getInclusion().getTargetDescriptors().contains(rd)) {
1468                         for(int j=0;j<mun.numUpdates();j++) {
1469                             UpdateNode un=mun.getUpdate(j);
1470                             if (un.getRule()==r) {
1471                                 /* Update for rule rule r */
1472                                 String name=(String)updatenames.get(un);
1473                                 if (inverse) {
1474                                     cr.outputline("RepairHashaddrelation("+repairtable.getSafeSymbol()+","+rd.getNum()+","+r.getNum()+","+rightvar.getSafeSymbol()+","+leftvar.getSafeSymbol()+",(int) &"+name+");");
1475                                 } else {
1476                                     cr.outputline("RepairHashaddrelation("+repairtable.getSafeSymbol()+","+rd.getNum()+","+r.getNum()+","+leftvar.getSafeSymbol()+","+rightvar.getSafeSymbol()+",(int) &"+name+");");
1477                                 }
1478                             }
1479                         }
1480                     }
1481                 }
1482             } else {
1483                 SetDescriptor sd=ip.setexpr.sd;
1484                 cr.outputline("SimpleHashremove("+sd.getSafeSymbol()+"_hash, (int)" + leftvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
1485
1486                 for(int i=0;i<state.vRules.size();i++) {
1487                     Rule r=(Rule)state.vRules.get(i);
1488                     if (r.getInclusion().getTargetDescriptors().contains(sd)) {
1489                         for(int j=0;j<mun.numUpdates();j++) {
1490                             UpdateNode un=mun.getUpdate(j);
1491                             if (un.getRule()==r) {
1492                                 /* Update for rule rule r */
1493                                 String name=(String)updatenames.get(un);
1494                                 cr.outputline("RepairHashaddset("+repairtable.getSafeSymbol()+","+sd.getNum()+","+r.getNum()+","+leftvar.getSafeSymbol()+",(int) &"+name+");");
1495                             }
1496                         }
1497                     }
1498                 }
1499             }
1500         } else {
1501             /* Generate update */
1502             if (ip.setexpr instanceof ImageSetExpr) {
1503                 ImageSetExpr ise=(ImageSetExpr) ip.setexpr;
1504                 VarDescriptor rightvar=ise.getVar();
1505                 boolean inverse=ise.inverted();
1506                 RelationDescriptor rd=ise.getRelation();
1507                 boolean usageimage=rd.testUsage(RelationDescriptor.IMAGE);
1508                 boolean usageinvimage=rd.testUsage(RelationDescriptor.INVIMAGE);
1509                 if (inverse) {
1510                     if (usageimage)
1511                         cr.outputline("SimpleHashadd("+rd.getSafeSymbol()+"_hash, (int)" + rightvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
1512                     if (usageinvimage)
1513                         cr.outputline("SimpleHashadd("+rd.getSafeSymbol()+"_hashinv, (int)" + leftvar.getSafeSymbol() + ", (int)" + rightvar.getSafeSymbol() + ");");
1514                 } else {
1515                     if (usageimage)
1516                         cr.outputline("SimpleHashadd("+rd.getSafeSymbol()+"_hash, (int)" + leftvar.getSafeSymbol() + ", (int)" + rightvar.getSafeSymbol() + ");");
1517                     if (usageinvimage)
1518                         cr.outputline("SimpleHashadd("+rd.getSafeSymbol()+"_hashinv, (int)" + rightvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
1519                 }
1520                 UpdateNode un=mun.getUpdate(0);
1521                 String name=(String)updatenames.get(un);
1522                 if (inverse) {
1523                     cr.outputline(name+"(thisvar,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+rightvar.getSafeSymbol()+","+leftvar.getSafeSymbol()+");");
1524                 } else {
1525                     cr.outputline(name+"(thisvar,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+leftvar.getSafeSymbol()+","+rightvar.getSafeSymbol()+");");
1526                 }
1527             } else {
1528                 SetDescriptor sd=ip.setexpr.sd;
1529                 cr.outputline("SimpleHashadd("+sd.getSafeSymbol()+"_hash, (int)" + leftvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
1530
1531                 UpdateNode un=mun.getUpdate(0);
1532                 /* Update for rule rule r */
1533                 String name=(String)updatenames.get(un);
1534                 cr.outputline(name+"(thisvar,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+leftvar.getSafeSymbol()+");");
1535             }
1536         }
1537     }
1538
1539     public static Vector getrulelist(Descriptor d) {
1540         Vector dispatchrules = new Vector();
1541         Vector rules = State.currentState.vRules;
1542
1543         for (int i = 0; i < rules.size(); i++) {
1544             Rule rule = (Rule) rules.elementAt(i);
1545             Set requiredsymbols = rule.getRequiredDescriptors();
1546
1547             // #TBD#: in general this is wrong because these descriptors may contain descriptors
1548             // bound in "in?" expressions which need to be dealt with in a topologically sorted
1549             // fashion...
1550
1551             if (rule.getRequiredDescriptors().contains(d)) {
1552                 dispatchrules.addElement(rule);
1553             }
1554         }
1555         return dispatchrules;
1556     }
1557
1558     private boolean need_compensation(Rule r) {
1559         if (!Compiler.REPAIR)
1560             return false;
1561         GraphNode gn=(GraphNode)termination.scopefalsify.get(r);
1562         for(Iterator edgeit=gn.edges();edgeit.hasNext();) {
1563             GraphNode.Edge edge=(GraphNode.Edge)edgeit.next();
1564             GraphNode gn2=edge.getTarget();
1565             if (!removed.contains(gn2)) {
1566                 TermNode tn2=(TermNode)gn2.getOwner();
1567                 if (tn2.getType()==TermNode.CONSEQUENCE)
1568                     return false;
1569             }
1570         }
1571         return true;
1572     }
1573
1574     private UpdateNode find_compensation(Rule r) {
1575         GraphNode gn=(GraphNode)termination.scopefalsify.get(r);
1576         for(Iterator edgeit=gn.edges();edgeit.hasNext();) {
1577             GraphNode.Edge edge=(GraphNode.Edge)edgeit.next();
1578             GraphNode gn2=edge.getTarget();
1579             if (!removed.contains(gn2)) {
1580                 TermNode tn2=(TermNode)gn2.getOwner();
1581                 if (tn2.getType()==TermNode.UPDATE) {
1582                     MultUpdateNode mun=tn2.getUpdate();
1583                     for(int i=0;i<mun.numUpdates();i++) {
1584                         UpdateNode un=mun.getUpdate(i);
1585                         if (un.getRule()==r)
1586                             return un;
1587                     }
1588                 }
1589             }
1590         }
1591         throw new Error("No Compensation Update could be found");
1592     }
1593
1594     public void generate_dispatch(CodeWriter cr, RelationDescriptor rd, String leftvar, String rightvar) {
1595         boolean usageimage=rd.testUsage(RelationDescriptor.IMAGE);
1596         boolean usageinvimage=rd.testUsage(RelationDescriptor.INVIMAGE);
1597
1598         if (!(usageinvimage||usageimage)) /* not used at all*/
1599             return;
1600
1601         cr.outputline("/* RELATION DISPATCH */");
1602         if (Compiler.REPAIR) {
1603             cr.outputline("if ("+oldmodel.getSafeSymbol()+"&&");
1604             if (usageimage)
1605                 cr.outputline("!SimpleHashcontainskeydata("+oldmodel.getSafeSymbol()+"->"+rd.getJustSafeSymbol() + "_hash, "+leftvar+","+rightvar+"))");
1606             else
1607                 cr.outputline("!SimpleHashcontainskeydata("+oldmodel.getSafeSymbol() +"->"+rd.getJustSafeSymbol()+"_hashinv, "+rightvar+","+leftvar+"))");
1608
1609             cr.startblock(); {
1610                 /* Adding new item */
1611                 /* Perform safety checks */
1612                 cr.outputline("if ("+repairtable.getSafeSymbol()+"&&");
1613                 cr.outputline("RepairHashcontainsrelation("+repairtable.getSafeSymbol()+","+rd.getNum()+","+currentrule.getNum()+","+leftvar+","+rightvar+"))");
1614                 cr.startblock(); {
1615                     /* Have update to call into */
1616                     VarDescriptor mdfyptr=VarDescriptor.makeNew("modifyptr");
1617                     VarDescriptor ismdfyptr=VarDescriptor.makeNew("ismodifyptr");
1618                     cr.addDeclaration("int ",ismdfyptr.getSafeSymbol());
1619                     cr.outputline(ismdfyptr.getSafeSymbol()+"=RepairHashismodify("+repairtable.getSafeSymbol()+","+rd.getNum()+","+currentrule.getNum()+","+leftvar+","+rightvar+");");
1620
1621
1622
1623
1624                     String parttype="";
1625                     for(int i=0;i<currentrule.numQuantifiers();i++) {
1626                         if (currentrule.getQuantifier(i) instanceof RelationQuantifier)
1627                             parttype=parttype+", int, int";
1628                         else
1629                             parttype=parttype+", int";
1630                     }
1631
1632                     VarDescriptor tmpptr=VarDescriptor.makeNew("tempupdateptr");
1633
1634                     String methodcall="(thisvar,"+oldmodel.getSafeSymbol()+","+repairtable.getSafeSymbol();
1635                     for(int i=0;i<currentrule.numQuantifiers();i++) {
1636                         Quantifier q=currentrule.getQuantifier(i);
1637                         if (q instanceof SetQuantifier) {
1638                             SetQuantifier sq=(SetQuantifier) q;
1639                             methodcall+=","+sq.getVar().getSafeSymbol();
1640                         } else if (q instanceof RelationQuantifier) {
1641                             RelationQuantifier rq=(RelationQuantifier) q;
1642                             methodcall+=","+rq.x.getSafeSymbol();
1643                             methodcall+=","+rq.y.getSafeSymbol();
1644                         } else if (q instanceof ForQuantifier) {
1645                             ForQuantifier fq=(ForQuantifier) q;
1646                             methodcall+=","+fq.getVar().getSafeSymbol();
1647                         }
1648                     }
1649
1650
1651
1652                     cr.addDeclaration("void *",tmpptr.getSafeSymbol());
1653                     cr.outputline(tmpptr.getSafeSymbol()+"=");
1654                     cr.outputline("(void *) RepairHashgetrelation("+repairtable.getSafeSymbol()+","+rd.getNum()+","+currentrule.getNum()+","+leftvar+","+rightvar+");");
1655                     cr.outputline("if ("+ismdfyptr.getSafeSymbol()+")");
1656                     {
1657                         VarDescriptor funptr=VarDescriptor.makeNew("updateptr");
1658                         String methodcallprefix="("+funptr.getSafeSymbol()+") ";
1659                         cr.startblock();
1660                         cr.addDeclaration("int",mdfyptr.getSafeSymbol());
1661                         cr.outputline(mdfyptr.getSafeSymbol()+"=RepairHashgetrelation2("+repairtable.getSafeSymbol()+","+rd.getNum()+","+currentrule.getNum()+","+leftvar+","+rightvar+");");
1662                         cr.addDeclaration("void (*"+funptr.getSafeSymbol()+") (struct "+name+"_state *, struct "+name+"*, struct RepairHash *"+parttype+",int,int,int);");
1663                         cr.outputline(funptr.getSafeSymbol()+"="+"(void (*) (struct "+name+"_state *, struct "+name+"*, struct RepairHash *"+parttype+",int,int,int)) "+tmpptr.getSafeSymbol()+";");
1664                         cr.outputline(methodcallprefix+methodcall+","+leftvar+", "+rightvar+", "+mdfyptr.getSafeSymbol() +");");
1665                         cr.endblock();
1666                     }
1667                     cr.outputline("else ");
1668                     {
1669                         VarDescriptor funptr=VarDescriptor.makeNew("updateptr");
1670                         String methodcallprefix="("+funptr.getSafeSymbol()+") ";
1671                         cr.startblock();
1672                         cr.addDeclaration("void (*"+funptr.getSafeSymbol()+") (struct "+name+"_state *, struct "+name+"*,struct RepairHash *"+parttype+");");
1673                         cr.outputline(funptr.getSafeSymbol()+"="+"(void (*) (struct "+name+"_state *,struct "+name+"*,struct RepairHash *"+parttype+")) "+tmpptr.getSafeSymbol()+";");
1674                         cr.outputline(methodcallprefix+methodcall+");");
1675                         cr.endblock();
1676                     }
1677                     cr.outputline("free"+name+"("+newmodel.getSafeSymbol()+");");
1678                     cr.outputline("goto rebuild;");
1679                 }
1680                 cr.endblock();
1681
1682                 /* Build standard compensation actions */
1683                 if (need_compensation(currentrule)) {
1684                     UpdateNode un=find_compensation(currentrule);
1685                     String name=(String)updatenames.get(un);
1686                     usedupdates.add(un); /* Mark as used */
1687                     String methodcall=name+"(thisvar,"+oldmodel.getSafeSymbol()+","+repairtable.getSafeSymbol();
1688                     for(int i=0;i<currentrule.numQuantifiers();i++) {
1689                         Quantifier q=currentrule.getQuantifier(i);
1690                         if (q instanceof SetQuantifier) {
1691                             SetQuantifier sq=(SetQuantifier) q;
1692                             methodcall+=","+sq.getVar().getSafeSymbol();
1693                         } else if (q instanceof RelationQuantifier) {
1694                             RelationQuantifier rq=(RelationQuantifier) q;
1695                             methodcall+=","+rq.x.getSafeSymbol();
1696                             methodcall+=","+rq.y.getSafeSymbol();
1697                         } else if (q instanceof ForQuantifier) {
1698                             ForQuantifier fq=(ForQuantifier) q;
1699                             methodcall+=","+fq.getVar().getSafeSymbol();
1700                         }
1701                     }
1702                     methodcall+=");";
1703                     cr.outputline(methodcall);
1704                     cr.outputline("free"+name+"("+newmodel.getSafeSymbol()+");");
1705                     cr.outputline("goto rebuild;");
1706                 }
1707             }
1708             cr.endblock();
1709         }
1710
1711         String addeditem = (VarDescriptor.makeNew("addeditem")).getSafeSymbol();
1712         cr.startblock();
1713         cr.addDeclaration("int" , addeditem);
1714         cr.outputline(addeditem + "=0;");
1715
1716         String ifstring="if (!maybe";
1717         if (rd.getDomain().getType() instanceof StructureTypeDescriptor)  {
1718             ifstring+="&&"+leftvar;
1719         }
1720
1721         if (rd.getRange().getType() instanceof StructureTypeDescriptor)  {
1722             ifstring+="&&"+rightvar;
1723         }
1724
1725         ifstring+=")";
1726
1727         if (rd.testUsage(RelationDescriptor.IMAGE)) {
1728             cr.outputline(ifstring);
1729             cr.outputline(addeditem + " = SimpleHashadd("+rd.getSafeSymbol()+"_hash, (int)" + leftvar + ", (int)" + rightvar+ ");");
1730         }
1731
1732         if (rd.testUsage(RelationDescriptor.INVIMAGE)) {
1733             cr.outputline(ifstring);
1734             cr.outputline(addeditem + " = SimpleHashadd("+rd.getSafeSymbol()+"_hashinv, (int)" + rightvar + ", (int)" + leftvar + ");");
1735         }
1736
1737
1738         Vector dispatchrules = getrulelist(rd);
1739
1740         Set toremove=new HashSet();
1741         for(int i=0;i<dispatchrules.size();i++) {
1742             Rule r=(Rule)dispatchrules.get(i);
1743             if (!ruleset.contains(r))
1744                 toremove.add(r);
1745         }
1746         dispatchrules.removeAll(toremove);
1747         if (dispatchrules.size() == 0) {
1748             cr.outputline("/* nothing to dispatch */");
1749             cr.endblock();
1750             return;
1751         }
1752
1753         cr.outputline("if (" + addeditem + ")");
1754         cr.startblock();
1755
1756         for(int i = 0; i < dispatchrules.size(); i++) {
1757             Rule rule = (Rule) dispatchrules.elementAt(i);
1758             if (rule.getGuardExpr().getRequiredDescriptors().contains(rd)) {
1759                 /* Guard depends on this relation, so we recomput everything */
1760                 cr.outputline("WorkListadd("+worklist.getSafeSymbol()+","+rule.getNum()+",-1,0,0);");
1761             } else {
1762                 for (int j=0;j<rule.numQuantifiers();j++) {
1763                     Quantifier q=rule.getQuantifier(j);
1764                     if (q.getRequiredDescriptors().contains(rd)) {
1765                         /* Generate add */
1766                         cr.outputline("WorkListadd("+worklist.getSafeSymbol()+","+rule.getNum()+","+j+","+leftvar+","+rightvar+");");
1767                     }
1768                 }
1769             }
1770         }
1771         cr.endblock();
1772         cr.endblock();
1773     }
1774
1775
1776     public void generate_dispatch(CodeWriter cr, SetDescriptor sd, String setvar) {
1777         cr.outputline("/* SET DISPATCH */");
1778         if (Compiler.REPAIR) {
1779             cr.outputline("if ("+oldmodel.getSafeSymbol()+"&&");
1780             cr.outputline("!SimpleHashcontainskey("+oldmodel.getSafeSymbol() +"->"+sd.getJustSafeSymbol()+"_hash, "+setvar+"))");
1781             cr.startblock(); {
1782                 /* Adding new item */
1783                 /* See if there is an outstanding update in the repairtable */
1784                 cr.outputline("if ("+repairtable.getSafeSymbol()+"&&");
1785                 cr.outputline("RepairHashcontainsset("+repairtable.getSafeSymbol()+","+sd.getNum()+","+currentrule.getNum()+","+setvar+"))");
1786                 cr.startblock(); {
1787                     /* Have update to call into */
1788                     VarDescriptor funptr=VarDescriptor.makeNew("updateptr");
1789                     String parttype="";
1790                     for(int i=0;i<currentrule.numQuantifiers();i++) {
1791                         if (currentrule.getQuantifier(i) instanceof RelationQuantifier)
1792                             parttype=parttype+", int, int";
1793                         else
1794                             parttype=parttype+", int";
1795                     }
1796                     cr.addDeclaration("void (*"+funptr.getSafeSymbol()+") (struct "+name+"_state *,struct "+name+"*,struct RepairHash *"+parttype+");");
1797                     cr.outputline(funptr.getSafeSymbol()+"=");
1798                     cr.outputline("(void (*) (struct "+name+"_state *,struct "+name+"*,struct RepairHash *"+parttype+")) RepairHashgetset("+repairtable.getSafeSymbol()+","+sd.getNum()+","+currentrule.getNum()+","+setvar+");");
1799                     String methodcall="("+funptr.getSafeSymbol()+") (thisvar,"+oldmodel.getSafeSymbol()+","+
1800                         repairtable.getSafeSymbol();
1801                     for(int i=0;i<currentrule.numQuantifiers();i++) {
1802                         Quantifier q=currentrule.getQuantifier(i);
1803                         if (q instanceof SetQuantifier) {
1804                             SetQuantifier sq=(SetQuantifier) q;
1805                             methodcall+=","+sq.getVar().getSafeSymbol();
1806                         } else if (q instanceof RelationQuantifier) {
1807                             RelationQuantifier rq=(RelationQuantifier) q;
1808                             methodcall+=","+rq.x.getSafeSymbol();
1809                             methodcall+=","+rq.y.getSafeSymbol();
1810                         } else if (q instanceof ForQuantifier) {
1811                             ForQuantifier fq=(ForQuantifier) q;
1812                             methodcall+=","+fq.getVar().getSafeSymbol();
1813                         }
1814                     }
1815                     methodcall+=");";
1816                     cr.outputline(methodcall);
1817                     cr.outputline("free"+name+"("+newmodel.getSafeSymbol()+");");
1818                     cr.outputline("goto rebuild;");
1819                 }
1820                 cr.endblock();
1821                 /* Build standard compensation actions */
1822                 Vector ruleset=new Vector();
1823                 ruleset.add(currentrule);
1824                 if (state.implicitruleinv.containsKey(currentrule))
1825                     ruleset.addAll((Set)state.implicitruleinv.get(currentrule));
1826                 for(int i=0;i<ruleset.size();i++) {
1827                     Rule itrule=(Rule)ruleset.get(i);
1828
1829                     if (need_compensation(itrule)) {
1830                         UpdateNode un=find_compensation(itrule);
1831                         String name=(String)updatenames.get(un);
1832                         usedupdates.add(un); /* Mark as used */
1833
1834                         String methodcall=name+"(thisvar,"+oldmodel.getSafeSymbol()+","+
1835                             repairtable.getSafeSymbol();
1836                         for(int j=0;j<currentrule.numQuantifiers();j++) {
1837                             Quantifier q=currentrule.getQuantifier(j);
1838                             if (q instanceof SetQuantifier) {
1839                                 SetQuantifier sq=(SetQuantifier) q;
1840                                 methodcall+=","+sq.getVar().getSafeSymbol();
1841                             } else if (q instanceof RelationQuantifier) {
1842                                 RelationQuantifier rq=(RelationQuantifier) q;
1843                                 methodcall+=","+rq.x.getSafeSymbol();
1844                                 methodcall+=","+rq.y.getSafeSymbol();
1845                             } else if (q instanceof ForQuantifier) {
1846                                 ForQuantifier fq=(ForQuantifier) q;
1847                                 methodcall+=","+fq.getVar().getSafeSymbol();
1848                             }
1849                         }
1850                         methodcall+=");";
1851                         if (currentrule!=itrule) {
1852                             SetDescriptor sdrule=((SetInclusion)itrule.getInclusion()).getSet();
1853                             cr.outputline("if ("+oldmodel.getSafeSymbol()+"&&");
1854                             cr.outputline("!SimpleHashcontainskey("+ oldmodel.getSafeSymbol() +"->"+sdrule.getJustSafeSymbol() +"_hash,"+setvar+"))");
1855                             cr.startblock();
1856                         }
1857                         cr.outputline(methodcall);
1858                         cr.outputline("free"+name+"("+newmodel.getSafeSymbol()+");");
1859                         cr.outputline("goto rebuild;");
1860                         cr.endblock();
1861                     }
1862                     if (currentrule==itrule)
1863                         cr.endblock();
1864                 }
1865             }
1866         }
1867
1868         cr.startblock();
1869         String addeditem = (VarDescriptor.makeNew("addeditem")).getSafeSymbol();
1870         cr.addDeclaration("int", addeditem);
1871         cr.outputline(addeditem + " = 0;");
1872         if (sd.getType() instanceof StructureTypeDescriptor)  {
1873             cr.outputline("if (!maybe&&"+setvar+")");
1874         } else
1875             cr.outputline("if (!maybe)");
1876         cr.outputline(addeditem + " = SimpleHashadd("+sd.getSafeSymbol()+"_hash, (int)" + setvar +  ", (int)" + setvar + ");");
1877         cr.startblock();
1878         Vector dispatchrules = getrulelist(sd);
1879
1880         Set toremove=new HashSet();
1881         for(int i=0;i<dispatchrules.size();i++) {
1882             Rule r=(Rule)dispatchrules.get(i);
1883             if (!ruleset.contains(r))
1884                 toremove.add(r);
1885         }
1886         dispatchrules.removeAll(toremove);
1887
1888         if (dispatchrules.size() == 0) {
1889             cr.outputline("/* nothing to dispatch */");
1890             cr.endblock();
1891             cr.endblock();
1892             return;
1893         }
1894         /* Add item to worklist if new */
1895         cr.outputline("if ("+addeditem+")");
1896         cr.startblock();
1897         for(int i = 0; i < dispatchrules.size(); i++) {
1898             Rule rule = (Rule) dispatchrules.elementAt(i);
1899             if (SetDescriptor.expand(rule.getGuardExpr().getRequiredDescriptors()).contains(sd)) {
1900                 /* Guard depends on this relation, so we recompute everything */
1901                 cr.outputline("WorkListadd("+worklist.getSafeSymbol()+","+rule.getNum()+",-1,0,0);");
1902             } else {
1903                 for (int j=0;j<rule.numQuantifiers();j++) {
1904                     Quantifier q=rule.getQuantifier(j);
1905                     if (SetDescriptor.expand(q.getRequiredDescriptors()).contains(sd)) {
1906                         /* Generate add */
1907                         cr.outputline("WorkListadd("+worklist.getSafeSymbol()+","+rule.getNum()+","+j+","+setvar+",0);");
1908                     }
1909                 }
1910             }
1911         }
1912         cr.endblock();
1913         cr.endblock();
1914         cr.endblock();
1915     }
1916 }