Bug fixes for gc
[IRC.git] / Robust / src / IR / Flat / BuildCode.java
1 package IR.Flat;
2 import IR.Tree.Modifiers;
3 import IR.Tree.FlagExpressionNode;
4 import IR.Tree.DNFFlag;
5 import IR.Tree.DNFFlagAtom;
6 import IR.Tree.TagExpressionList;
7 import IR.Tree.OffsetNode;
8 import IR.*;
9
10 import java.util.*;
11 import java.io.*;
12
13 import Util.Relation;
14 import Analysis.TaskStateAnalysis.FlagState;
15 import Analysis.TaskStateAnalysis.FlagComparator;
16 import Analysis.TaskStateAnalysis.OptionalTaskDescriptor;
17 import Analysis.TaskStateAnalysis.Predicate;
18 import Analysis.TaskStateAnalysis.SafetyAnalysis;
19 import Analysis.TaskStateAnalysis.TaskIndex;
20 import Analysis.CallGraph.CallGraph;
21 import Analysis.Loops.GlobalFieldType;
22 import Util.CodePrinter;
23
24 public class BuildCode {
25   State state;
26   Hashtable temptovar;
27   Hashtable paramstable;
28   Hashtable tempstable;
29   Hashtable fieldorder;
30   Hashtable flagorder;
31   int tag=0;
32   String localsprefix="___locals___";
33   String localsprefixaddr="&"+localsprefix;
34   String localsprefixderef=localsprefix+".";
35   String fcrevert="___fcrevert___";
36   String paramsprefix="___params___";
37   String nextobjstr="___nextobject___";
38   String localcopystr="___localcopy___";
39   public static boolean GENERATEPRECISEGC=false;
40   public static String PREFIX="";
41   public static String arraytype="ArrayObject";
42   public static int flagcount = 0;
43   Virtual virtualcalls;
44   TypeUtil typeutil;
45   protected int maxtaskparams=0;
46   protected int maxcount=0;
47   ClassDescriptor[] cdarray;
48   ClassDescriptor[] ifarray;
49   TypeDescriptor[] arraytable;
50   SafetyAnalysis sa;
51   CallGraph callgraph;
52   Hashtable<String, ClassDescriptor> printedfieldstbl;
53   int globaldefscount=0;
54   boolean mgcstaticinit = false;
55
56   public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil) {
57     this(st, temptovar, typeutil, null);
58   }
59
60   public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa) {
61     this.sa=sa;
62     state=st;
63     callgraph=new CallGraph(state);
64     this.temptovar=temptovar;
65     paramstable=new Hashtable();
66     tempstable=new Hashtable();
67     fieldorder=new Hashtable();
68     flagorder=new Hashtable();
69     this.typeutil=typeutil;
70     checkMethods2Gen();
71     virtualcalls=new Virtual(state, null);
72     printedfieldstbl = new Hashtable<String, ClassDescriptor>();
73   }
74
75   /** The buildCode method outputs C code for all the methods.  The Flat
76    * versions of the methods must already be generated and stored in
77    * the State object. */
78
79
80   public void buildCode() {
81     /* Create output streams to write to */
82     PrintWriter outclassdefs=null;
83     PrintWriter outstructs=null;
84     PrintWriter outrepairstructs=null;
85     PrintWriter outmethodheader=null;
86     PrintWriter outmethod=null;
87     PrintWriter outvirtual=null;
88     PrintWriter outtask=null;
89     PrintWriter outtaskdefs=null;
90     PrintWriter outoptionalarrays=null;
91     PrintWriter optionalheaders=null;
92     PrintWriter outglobaldefs=null;
93     PrintWriter outglobaldefsprim=null;
94
95     try {
96       buildCodeSetup(); //EXTENSION POINT
97       outstructs=new CodePrinter(new FileOutputStream(PREFIX+"structdefs.h"), true);
98       outmethodheader=new CodePrinter(new FileOutputStream(PREFIX+"methodheaders.h"), true);
99       outclassdefs=new CodePrinter(new FileOutputStream(PREFIX+"classdefs.h"), true);
100       outglobaldefs=new CodePrinter(new FileOutputStream(PREFIX+"globaldefs.h"), true);
101       outglobaldefsprim=new CodePrinter(new FileOutputStream(PREFIX+"globaldefsprim.h"), true);
102       outmethod=new CodePrinter(new FileOutputStream(PREFIX+"methods.c"), true);
103       outvirtual=new CodePrinter(new FileOutputStream(PREFIX+"virtualtable.h"), true);
104       if (state.TASK) {
105         outtask=new CodePrinter(new FileOutputStream(PREFIX+"task.h"), true);
106         outtaskdefs=new CodePrinter(new FileOutputStream(PREFIX+"taskdefs.c"), true);
107         if (state.OPTIONAL) {
108           outoptionalarrays=new CodePrinter(new FileOutputStream(PREFIX+"optionalarrays.c"), true);
109           optionalheaders=new CodePrinter(new FileOutputStream(PREFIX+"optionalstruct.h"), true);
110         }
111       }
112       if (state.structfile!=null) {
113         outrepairstructs=new CodePrinter(new FileOutputStream(PREFIX+state.structfile+".struct"), true);
114       }
115     } catch (Exception e) {
116       e.printStackTrace();
117       System.exit(-1);
118     }
119
120     /* Fix field safe symbols due to shadowing */
121     FieldShadow.handleFieldShadow(state);
122
123     /* Build the virtual dispatch tables */
124     buildVirtualTables(outvirtual);
125
126     /* Tag the methods that are invoked by static blocks */
127     tagMethodInvokedByStaticBlock();
128
129     /* Output includes */
130     outmethodheader.println("#ifndef METHODHEADERS_H");
131     outmethodheader.println("#define METHODHEADERS_H");
132     outmethodheader.println("#include \"structdefs.h\"");
133
134     if (state.EVENTMONITOR) {
135       outmethodheader.println("#include \"monitor.h\"");
136     }
137
138     additionalIncludesMethodsHeader(outmethodheader);
139
140     /* Output Structures */
141     outputStructs(outstructs);
142
143     // Output the C class declarations
144     // These could mutually reference each other
145
146     outglobaldefs.println("#ifndef __GLOBALDEF_H_");
147     outglobaldefs.println("#define __GLOBALDEF_H_");
148     outglobaldefs.println("");
149     outglobaldefs.println("struct global_defs_t {");
150     outglobaldefs.println("  int size;");
151     outglobaldefs.println("  void * next;");
152     outglobaldefsprim.println("#ifndef __GLOBALDEFPRIM_H_");
153     outglobaldefsprim.println("#define __GLOBALDEFPRIM_H_");
154     outglobaldefsprim.println("");
155     outglobaldefsprim.println("struct global_defsprim_t {");
156
157     outclassdefs.println("#ifndef __CLASSDEF_H_");
158     outclassdefs.println("#define __CLASSDEF_H_");
159     outputClassDeclarations(outclassdefs, outglobaldefs, outglobaldefsprim);
160
161     // Output function prototypes and structures for parameters
162     Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
163     while(it.hasNext()) {
164       ClassDescriptor cn=(ClassDescriptor)it.next();
165       generateCallStructs(cn, outclassdefs, outstructs, outmethodheader, outglobaldefs, outglobaldefsprim);
166     }
167     outclassdefs.println("#include \"globaldefs.h\"");
168     outclassdefs.println("#include \"globaldefsprim.h\"");
169     outclassdefs.println("#endif");
170     outclassdefs.close();
171     
172     outglobaldefs.println("};");
173     outglobaldefs.println("");
174     outglobaldefs.println("extern struct global_defs_t * global_defs_p;");
175     outglobaldefs.println("#endif");
176     outglobaldefs.flush();
177     outglobaldefs.close();
178
179     outglobaldefsprim.println("};");
180     outglobaldefsprim.println("");
181     outglobaldefsprim.println("extern struct global_defsprim_t * global_defsprim_p;");
182     outglobaldefsprim.println("#endif");
183     outglobaldefsprim.flush();
184     outglobaldefsprim.close();
185
186     if (state.TASK) {
187       /* Map flags to integers */
188       /* The runtime keeps track of flags using these integers */
189       it=state.getClassSymbolTable().getDescriptorsIterator();
190       while(it.hasNext()) {
191         ClassDescriptor cn=(ClassDescriptor)it.next();
192         mapFlags(cn);
193       }
194       /* Generate Tasks */
195       generateTaskStructs(outstructs, outmethodheader);
196
197       /* Outputs generic task structures if this is a task
198          program */
199       outputTaskTypes(outtask);
200     }
201
202
203     // an opportunity for subclasses to do extra
204     // initialization
205     preCodeGenInitialization();
206
207
208     /* Build the actual methods */
209     outputMethods(outmethod);
210
211
212     // opportunity for subclasses to gen extra code
213     additionalCodeGen(outmethodheader,
214                       outstructs,
215                       outmethod);
216
217
218     if (state.TASK) {
219       /* Output code for tasks */
220       outputTaskCode(outtaskdefs, outmethod);
221       outtaskdefs.close();
222       /* Record maximum number of task parameters */
223       outstructs.println("#define MAXTASKPARAMS "+maxtaskparams);
224     } else if (state.main!=null) {
225       /* Generate main method */
226       outputMainMethod(outmethod);
227     }
228
229     /* Generate information for task with optional parameters */
230     if (state.TASK&&state.OPTIONAL) {
231       generateOptionalArrays(outoptionalarrays, optionalheaders, state.getAnalysisResult(), state.getOptionalTaskDescriptors());
232       outoptionalarrays.close();
233     }
234
235     /* Output structure definitions for repair tool */
236     if (state.structfile!=null) {
237       buildRepairStructs(outrepairstructs);
238       outrepairstructs.close();
239     }
240
241     /* Close files */
242     outmethodheader.println("#endif");
243     outmethodheader.close();
244     outmethod.close();
245     outstructs.println("#endif");
246     outstructs.close();
247
248
249
250     postCodeGenCleanUp();
251   }
252
253   /* This method goes though the call graph and check which methods are really
254    * invoked and should be generated
255    */
256   protected void checkMethods2Gen() {
257     MethodDescriptor md=(state.main==null)?null:typeutil.getMain();
258     
259     if(md != null) {
260       // check the methods to be generated
261       state.setGenAllMethods(false);
262     } else {
263       // generate all methods
264       return;
265     }
266     this.state.addMethod2gen(md);
267     
268     Iterator it_classes = this.state.getClassSymbolTable().getDescriptorsIterator();
269     while(it_classes.hasNext()) {
270       ClassDescriptor cd = (ClassDescriptor)it_classes.next();
271       Iterator it_methods = cd.getMethodTable().getDescriptorsIterator();
272       while(it_methods.hasNext()) {
273         md = (MethodDescriptor)it_methods.next();
274         if(md.isStaticBlock() || md.getModifiers().isNative() || this.callgraph.getCallerSet(md).size() > 0
275             || (cd.getSymbol().equals("Thread") && md.getSymbol().equals("staticStart"))) {
276           this.state.addMethod2gen(md);
277         }
278       }
279     }
280   }
281
282
283   /* This method goes though the call graph and tag those methods that are
284    * invoked inside static blocks
285    */
286   protected void tagMethodInvokedByStaticBlock() {
287     Iterator it_sclasses = this.state.getSClassSymbolTable().getDescriptorsIterator();
288     MethodDescriptor current_md=null;
289     HashSet tovisit=new HashSet();
290     HashSet visited=new HashSet();
291     
292     while(it_sclasses.hasNext()) {
293       ClassDescriptor cd = (ClassDescriptor)it_sclasses.next();
294       MethodDescriptor md = (MethodDescriptor)cd.getMethodTable().get("staticblocks");
295       if(md != null) {
296         tovisit.add(md);
297       }
298     }
299     
300     while(!tovisit.isEmpty()) {
301       current_md=(MethodDescriptor)tovisit.iterator().next();
302       tovisit.remove(current_md);
303       visited.add(current_md);
304       Iterator it_callee = this.callgraph.getCalleeSet(current_md).iterator();
305       while(it_callee.hasNext()) {
306         Descriptor d = (Descriptor)it_callee.next();
307         if(d instanceof MethodDescriptor) {
308           if(!visited.contains(d)) {
309             ((MethodDescriptor)d).setIsInvokedByStatic(true);
310             tovisit.add(d);
311           }
312         }
313       }
314     }
315   }
316
317   /* This code generates code for each static block and static field
318    * initialization.*/
319   protected void outputStaticBlocks(PrintWriter outmethod) {
320     //  execute all the static blocks and all the static field initializations
321     // execute all the static blocks and all the static field initializations
322     SymbolTable sctbl = this.state.getSClassSymbolTable();
323     Iterator it_sclasses = sctbl.getDescriptorsIterator();
324     if(it_sclasses.hasNext()) {
325       while(it_sclasses.hasNext()) {
326         ClassDescriptor t_cd = (ClassDescriptor)it_sclasses.next();
327         MethodDescriptor t_md = (MethodDescriptor)t_cd.getMethodTable().get("staticblocks");
328         if(t_md != null) {
329           outmethod.println("   {");
330           if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
331             outmethod.print("       struct "+t_cd.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"_params __parameterlist__={");
332             outmethod.println("0, NULL};");
333             outmethod.println("     "+t_cd.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"(& __parameterlist__);");
334           } else {
335             outmethod.println("     "+t_cd.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();");
336           }
337           outmethod.println("   }");
338         }
339       }
340     }
341   }
342
343   /* This code generates code to create a Class object for each class for
344    * getClass() method.
345    * */
346   protected void outputClassObjects(PrintWriter outmethod) {
347     // for each class, initialize its Class object
348     SymbolTable ctbl = this.state.getClassSymbolTable();
349     for(Iterator it_classes = ctbl.getDescriptorsIterator();it_classes.hasNext();) {
350       ClassDescriptor t_cd = (ClassDescriptor)it_classes.next();
351       outmethod.println(" {");
352       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
353         outmethod.println("    struct garbagelist dummy={0,NULL};");
354         outmethod.println("    global_defs_p->"+t_cd.getSafeSymbol()+"classobj = allocate_new(&dummy, " + typeutil.getClass(TypeUtil.ObjectClass).getId() + ");");
355       } else 
356         outmethod.println("    global_defs_p->"+t_cd.getSafeSymbol()+"classobj = allocate_new("+typeutil.getClass(TypeUtil.ObjectClass).getId() + ");");
357       outmethod.println(" }");
358     }
359   }
360
361   /* This code just generates the main C method for java programs.
362    * The main C method packs up the arguments into a string array
363    * and passes it to the java main method. */
364
365   protected void outputMainMethod(PrintWriter outmethod) {
366     outmethod.println("int main(int argc, const char *argv[]) {");
367     outmethod.println("  int i;");
368     outmethod.println("  global_defs_p=calloc(1, sizeof(struct global_defs_t));");
369     outmethod.println("  global_defsprim_p=calloc(1, sizeof(struct global_defsprim_t));");
370     if (GENERATEPRECISEGC) {
371       outmethod.println("  global_defs_p->size="+globaldefscount+";");
372       outmethod.println("  for(i=0;i<"+globaldefscount+";i++) {");
373       outmethod.println("    ((struct garbagelist *)global_defs_p)->array[i]=NULL;");
374       outmethod.println("  }");
375     }
376     outputStaticBlocks(outmethod);
377     outputClassObjects(outmethod);
378
379
380     additionalCodeAtTopOfMain(outmethod);
381
382     if (state.THREAD) {
383       outmethod.println("initializethreads();");
384     }
385
386     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
387       outmethod.println("  struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1);");
388     } else {
389       outmethod.println("  struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1);");
390     }
391     outmethod.println("  for(i=1;i<argc;i++) {");
392     outmethod.println("    int length=strlen(argv[i]);");
393
394     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
395       outmethod.println("    struct ___String___ *newstring=NewString(NULL, argv[i], length);");
396     } else {
397       outmethod.println("    struct ___String___ *newstring=NewString(argv[i], length);");
398     }
399     outmethod.println("    ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-1]=newstring;");
400     outmethod.println("  }");
401
402     MethodDescriptor md=typeutil.getMain();
403     ClassDescriptor cd=typeutil.getMainClass();
404
405     outmethod.println("   {");
406     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
407       outmethod.print("       struct "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
408       outmethod.println("1, NULL,"+"stringarray};");
409       outmethod.println("     "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
410     } else {
411       outmethod.println("     "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
412     }
413     outmethod.println("   }");
414
415     if (state.THREAD) {
416       outmethod.println("pthread_mutex_lock(&gclistlock);");
417       outmethod.println("threadcount--;");
418       outmethod.println("pthread_cond_signal(&gccond);");
419       outmethod.println("pthread_mutex_unlock(&gclistlock);");
420     }
421
422     if (state.EVENTMONITOR) {
423       outmethod.println("dumpdata();");
424     }
425
426     if (state.THREAD)
427       outmethod.println("pthread_exit(NULL);");
428
429
430     additionalCodeAtBottomOfMain(outmethod);
431
432     outmethod.println("}");
433   }
434
435   /* This method outputs code for each task. */
436
437   protected void outputTaskCode(PrintWriter outtaskdefs, PrintWriter outmethod) {
438     /* Compile task based program */
439     outtaskdefs.println("#include \"task.h\"");
440     outtaskdefs.println("#include \"methodheaders.h\"");
441     Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
442     while(taskit.hasNext()) {
443       TaskDescriptor td=(TaskDescriptor)taskit.next();
444       FlatMethod fm=state.getMethodFlat(td);
445       generateFlatMethod(fm, outmethod);
446       generateTaskDescriptor(outtaskdefs, fm, td);
447     }
448
449     //Output task descriptors
450     taskit=state.getTaskSymbolTable().getDescriptorsIterator();
451     outtaskdefs.println("struct taskdescriptor * taskarray[]= {");
452     boolean first=true;
453     while(taskit.hasNext()) {
454       TaskDescriptor td=(TaskDescriptor)taskit.next();
455       if (first)
456         first=false;
457       else
458         outtaskdefs.println(",");
459       outtaskdefs.print("&task_"+td.getSafeSymbol());
460     }
461     outtaskdefs.println("};");
462
463     outtaskdefs.println("int numtasks="+state.getTaskSymbolTable().getValueSet().size()+";");
464   }
465
466
467   /* This method outputs most of the methods.c file.  This includes
468    * some standard includes and then an array with the sizes of
469    * objets and array that stores supertype and then the code for
470    * the Java methods.. */
471   protected void outputMethods(PrintWriter outmethod) {
472     outmethod.println("#include \"methodheaders.h\"");
473     outmethod.println("#include \"virtualtable.h\"");
474     outmethod.println("#include \"runtime.h\"");
475
476     // always include: compiler directives will leave out
477     // instrumentation when option is not set
478     outmethod.println("#include \"coreprof/coreprof.h\"");
479
480     if (state.FASTCHECK) {
481       outmethod.println("#include \"localobjects.h\"");
482     }
483     if(state.MULTICORE) {
484       if(state.TASK) {
485         outmethod.println("#include \"task.h\"");
486       }
487       outmethod.println("#include \"multicoreruntime.h\"");
488       outmethod.println("#include \"runtime_arch.h\"");
489     }
490     if (state.THREAD||state.DSM||state.SINGLETM) {
491       outmethod.println("#include <thread.h>");
492     }
493     if(state.MGC) {
494       outmethod.println("#include \"thread.h\"");
495     }
496     if (state.main!=null) {
497       outmethod.println("#include <string.h>");
498     }
499     if (state.CONSCHECK) {
500       outmethod.println("#include \"checkers.h\"");
501     }
502
503
504     additionalIncludesMethodsImplementation(outmethod);
505
506     outmethod.println("struct global_defs_t * global_defs_p;");
507     outmethod.println("struct global_defsprim_t * global_defsprim_p;");
508     //Store the sizes of classes & array elements
509     generateSizeArray(outmethod);
510
511     //Store table of supertypes
512     generateSuperTypeTable(outmethod);
513
514     //Store the layout of classes
515     generateLayoutStructs(outmethod);
516
517
518     additionalCodeAtTopMethodsImplementation(outmethod);
519
520     generateMethods(outmethod);
521   }
522
523   protected void generateMethods(PrintWriter outmethod) {
524     /* Generate code for methods */
525     Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
526     while(classit.hasNext()) {
527       ClassDescriptor cn=(ClassDescriptor)classit.next();
528       Iterator methodit=cn.getMethods();
529       while(methodit.hasNext()) {
530         /* Classify parameters */
531         MethodDescriptor md=(MethodDescriptor)methodit.next();
532     if(!this.state.genAllMethods) {
533       boolean foundmatch = false;
534       Set vec_md = this.state.getMethod2gen().getSet(md.getSymbol());
535       for(Iterator matchit=vec_md.iterator(); matchit.hasNext();) {
536         MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
537         if (md.matches(matchmd)) {
538           foundmatch=true;
539           break;
540         }
541       }
542       if(!foundmatch) {
543         continue;
544       }
545     }
546         FlatMethod fm=state.getMethodFlat(md);
547         if (!md.getModifiers().isNative()) {
548           generateFlatMethod(fm, outmethod);
549         }
550       }
551     }
552   }
553
554   protected void outputStructs(PrintWriter outstructs) {
555     outstructs.println("#ifndef STRUCTDEFS_H");
556     outstructs.println("#define STRUCTDEFS_H");
557     outstructs.println("#include \"classdefs.h\"");
558     outstructs.println("#ifndef INTPTR");
559     outstructs.println("#ifdef BIT64");
560     outstructs.println("#define INTPTR long");
561     outstructs.println("#else");
562     outstructs.println("#define INTPTR int");
563     outstructs.println("#endif");
564     outstructs.println("#endif");
565
566
567     additionalIncludesStructsHeader(outstructs);
568
569
570     /* Output #defines that the runtime uses to determine type
571      * numbers for various objects it needs */
572     outstructs.println("#define MAXCOUNT "+maxcount);
573
574     outstructs.println("#define STRINGARRAYTYPE "+
575                        (state.getArrayNumber(
576                           (new TypeDescriptor(typeutil.getClass(TypeUtil.StringClass))).makeArray(state))+state.numClasses()));
577
578     outstructs.println("#define OBJECTARRAYTYPE "+
579                        (state.getArrayNumber(
580                           (new TypeDescriptor(typeutil.getClass(TypeUtil.ObjectClass))).makeArray(state))+state.numClasses()));
581
582
583     outstructs.println("#define STRINGTYPE "+typeutil.getClass(TypeUtil.StringClass).getId());
584     outstructs.println("#define CHARARRAYTYPE "+
585                        (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.CHAR)).makeArray(state))+state.numClasses()));
586
587     outstructs.println("#define BYTEARRAYTYPE "+
588                        (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state))+state.numClasses()));
589
590     outstructs.println("#define BYTEARRAYARRAYTYPE "+
591                        (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state).makeArray(state))+state.numClasses()));
592
593     outstructs.println("#define NUMCLASSES "+state.numClasses());
594     int totalClassSize = state.numClasses() + state.numArrays() + state.numInterfaces();
595     outstructs.println("#define TOTALNUMCLASSANDARRAY "+ totalClassSize);
596     if (state.TASK) {
597       outstructs.println("#define STARTUPTYPE "+typeutil.getClass(TypeUtil.StartupClass).getId());
598       outstructs.println("#define TAGTYPE "+typeutil.getClass(TypeUtil.TagClass).getId());
599       outstructs.println("#define TAGARRAYTYPE "+
600                          (state.getArrayNumber(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)).makeArray(state))+state.numClasses()));
601     }
602   }
603
604   protected void outputClassDeclarations(PrintWriter outclassdefs, PrintWriter outglobaldefs, PrintWriter outglobaldefsprim) {
605     if (state.THREAD||state.DSM||state.SINGLETM)
606       outclassdefs.println("#include <pthread.h>");
607     outclassdefs.println("#ifndef INTPTR");
608     outclassdefs.println("#ifdef BIT64");
609     outclassdefs.println("#define INTPTR long");
610     outclassdefs.println("#else");
611     outclassdefs.println("#define INTPTR int");
612     outclassdefs.println("#endif");
613     outclassdefs.println("#endif");
614     if(state.OPTIONAL)
615       outclassdefs.println("#include \"optionalstruct.h\"");
616     outclassdefs.println("struct "+arraytype+";");
617     /* Start by declaring all structs */
618     Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
619     while(it.hasNext()) {
620       ClassDescriptor cn=(ClassDescriptor)it.next();
621       outclassdefs.println("struct "+cn.getSafeSymbol()+";");
622
623       if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) {
624         // this class has static fields/blocks, need to add a global flag to
625         // indicate if its static fields have been initialized and/or if its
626         // static blocks have been executed
627         outglobaldefsprim.println("  int "+cn.getSafeSymbol()+"static_block_exe_flag;");
628       }
629       
630       // for each class, create a global object
631       outglobaldefs.println("  struct ___Object___ *"+cn.getSafeSymbol()+"classobj;");
632       globaldefscount++;
633     }
634     outclassdefs.println("");
635     //Print out definition for array type
636     outclassdefs.println("struct "+arraytype+" {");
637     outclassdefs.println("  int type;");
638
639
640     additionalClassObjectFields(outclassdefs);
641
642
643     if (state.EVENTMONITOR) {
644       outclassdefs.println("  int objuid;");
645     }
646     if (state.THREAD) {
647       outclassdefs.println("  pthread_t tid;");
648       outclassdefs.println("  void * lockentry;");
649       outclassdefs.println("  int lockcount;");
650     }
651     if(state.MGC) {
652       outclassdefs.println("  int mutex;");
653       outclassdefs.println("  volatile int notifycount;");
654       outclassdefs.println("  volatile int objlock;");
655       if(state.MULTICOREGC) {
656         outclassdefs.println("  int marked;");
657       }
658     }
659     if (state.TASK) {
660       outclassdefs.println("  int flag;");
661       if(!state.MULTICORE) {
662         outclassdefs.println("  void * flagptr;");
663       } else {
664         outclassdefs.println("  int version;");
665         outclassdefs.println("  int * lock;");  // lock entry for this obj
666         outclassdefs.println("  int mutex;");
667         outclassdefs.println("  int lockcount;");
668         if(state.MULTICOREGC) {
669           outclassdefs.println("  int marked;");
670         }
671       }
672       if(state.OPTIONAL) {
673         outclassdefs.println("  int numfses;");
674         outclassdefs.println("  int * fses;");
675       }
676     }
677
678     printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs, outglobaldefs, outglobaldefsprim);
679     printedfieldstbl.clear();
680     printExtraArrayFields(outclassdefs);
681     if (state.ARRAYPAD) {
682       outclassdefs.println("  int paddingforarray;");
683     }
684
685     outclassdefs.println("  int ___length___;");
686     outclassdefs.println("};\n");
687
688     if(state.MGC) {
689       // TODO add version for normal Java later
690       outclassdefs.println("");
691       //Print out definition for Class type
692       outclassdefs.println("struct Class {");
693       outclassdefs.println("  int type;");
694
695
696       additionalClassObjectFields(outclassdefs);
697
698
699       if (state.EVENTMONITOR) {
700         outclassdefs.println("  int objuid;");
701       }
702       if (state.THREAD) {
703         outclassdefs.println("  pthread_t tid;");
704         outclassdefs.println("  void * lockentry;");
705         outclassdefs.println("  int lockcount;");
706       }
707       if(state.MGC) {
708         outclassdefs.println("  int mutex;");
709         outclassdefs.println("  volatile int notifycount;");
710         outclassdefs.println("  volatile int objlock;");
711         if(state.MULTICOREGC) {
712           outclassdefs.println("  int marked;");
713         }
714       }
715       if (state.TASK) {
716         outclassdefs.println("  int flag;");
717         if(!state.MULTICORE) {
718           outclassdefs.println("  void * flagptr;");
719         } else {
720           outclassdefs.println("  int version;");
721           outclassdefs.println("  int * lock;"); // lock entry for this obj
722           outclassdefs.println("  int mutex;");
723           outclassdefs.println("  int lockcount;");
724           if(state.MULTICOREGC) {
725             outclassdefs.println("  int marked;");
726           }
727         }
728         if(state.OPTIONAL) {
729           outclassdefs.println("  int numfses;");
730           outclassdefs.println("  int * fses;");
731         }
732       }
733       printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs, outglobaldefs, outglobaldefsprim);
734       printedfieldstbl.clear();
735       outclassdefs.println("};\n");
736     }
737
738     outclassdefs.println("");
739     outclassdefs.println("extern int classsize[];");
740     outclassdefs.println("extern int hasflags[];");
741     outclassdefs.println("extern unsigned INTPTR * pointerarray[];");
742     outclassdefs.println("extern int* supertypes[];");
743     outclassdefs.println("");
744   }
745
746   /** Prints out definitions for generic task structures */
747
748   protected void outputTaskTypes(PrintWriter outtask) {
749     outtask.println("#ifndef _TASK_H");
750     outtask.println("#define _TASK_H");
751     outtask.println("struct parameterdescriptor {");
752     outtask.println("int type;");
753     outtask.println("int numberterms;");
754     outtask.println("int *intarray;");
755     outtask.println("void * queue;");
756     outtask.println("int numbertags;");
757     outtask.println("int *tagarray;");
758     outtask.println("};");
759
760     outtask.println("struct taskdescriptor {");
761     outtask.println("void * taskptr;");
762     outtask.println("int numParameters;");
763     outtask.println("  int numTotal;");
764     outtask.println("struct parameterdescriptor **descriptorarray;");
765     outtask.println("char * name;");
766     outtask.println("};");
767     outtask.println("extern struct taskdescriptor * taskarray[];");
768     outtask.println("extern numtasks;");
769     outtask.println("#endif");
770   }
771
772
773   protected void buildRepairStructs(PrintWriter outrepairstructs) {
774     Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
775     while(classit.hasNext()) {
776       ClassDescriptor cn=(ClassDescriptor)classit.next();
777       outrepairstructs.println("structure "+cn.getSymbol()+" {");
778       outrepairstructs.println("  int __type__;");
779       if (state.TASK) {
780         outrepairstructs.println("  int __flag__;");
781         if(!state.MULTICORE) {
782           outrepairstructs.println("  int __flagptr__;");
783         }
784       }
785       printRepairStruct(cn, outrepairstructs);
786       outrepairstructs.println("}\n");
787     }
788
789     for(int i=0; i<state.numArrays(); i++) {
790       TypeDescriptor tdarray=arraytable[i];
791       TypeDescriptor tdelement=tdarray.dereference();
792       outrepairstructs.println("structure "+arraytype+"_"+state.getArrayNumber(tdarray)+" {");
793       outrepairstructs.println("  int __type__;");
794       printRepairStruct(typeutil.getClass(TypeUtil.ObjectClass), outrepairstructs);
795       outrepairstructs.println("  int length;");
796       outrepairstructs.println("}\n");
797     }
798   }
799
800   protected void printRepairStruct(ClassDescriptor cn, PrintWriter output) {
801     ClassDescriptor sp=cn.getSuperDesc();
802     if (sp!=null)
803       printRepairStruct(sp, output);
804
805     Vector fields=(Vector)fieldorder.get(cn);
806
807     for(int i=0; i<fields.size(); i++) {
808       FieldDescriptor fd=(FieldDescriptor)fields.get(i);
809       if (fd.getType().isArray()) {
810         output.println("  "+arraytype+"_"+ state.getArrayNumber(fd.getType()) +" * "+fd.getSymbol()+";");
811       } else if (fd.getType().isClass())
812         output.println("  "+fd.getType().getRepairSymbol()+" * "+fd.getSymbol()+";");
813       else if (fd.getType().isFloat())
814         output.println("  int "+fd.getSymbol()+"; /* really float */");
815       else
816         output.println("  "+fd.getType().getRepairSymbol()+" "+fd.getSymbol()+";");
817     }
818   }
819
820   /** This method outputs TaskDescriptor information */
821   protected void generateTaskDescriptor(PrintWriter output, FlatMethod fm, TaskDescriptor task) {
822     for (int i=0; i<task.numParameters(); i++) {
823       VarDescriptor param_var=task.getParameter(i);
824       TypeDescriptor param_type=task.getParamType(i);
825       FlagExpressionNode param_flag=task.getFlag(param_var);
826       TagExpressionList param_tag=task.getTag(param_var);
827
828       int dnfterms;
829       if (param_flag==null) {
830         output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
831         output.println("0x0, 0x0 };");
832         dnfterms=1;
833       } else {
834         DNFFlag dflag=param_flag.getDNF();
835         dnfterms=dflag.size();
836
837         Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
838         output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
839         for(int j=0; j<dflag.size(); j++) {
840           if (j!=0)
841             output.println(",");
842           Vector term=dflag.get(j);
843           int andmask=0;
844           int checkmask=0;
845           for(int k=0; k<term.size(); k++) {
846             DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
847             FlagDescriptor fd=dfa.getFlag();
848             boolean negated=dfa.getNegated();
849             int flagid=1<<((Integer)flags.get(fd)).intValue();
850             andmask|=flagid;
851             if (!negated)
852               checkmask|=flagid;
853           }
854           output.print("0x"+Integer.toHexString(andmask)+", 0x"+Integer.toHexString(checkmask));
855         }
856         output.println("};");
857       }
858
859       output.println("int parametertag_"+i+"_"+task.getSafeSymbol()+"[]={");
860       if (param_tag!=null)
861         for(int j=0; j<param_tag.numTags(); j++) {
862           if (j!=0)
863             output.println(",");
864           /* for each tag we need */
865           /* which slot it is */
866           /* what type it is */
867           TagVarDescriptor tvd=(TagVarDescriptor)task.getParameterTable().get(param_tag.getName(j));
868           TempDescriptor tmp=param_tag.getTemp(j);
869           int slot=fm.getTagInt(tmp);
870           output.println(slot+", "+state.getTagId(tvd.getTag()));
871         }
872       output.println("};");
873
874       output.println("struct parameterdescriptor parameter_"+i+"_"+task.getSafeSymbol()+"={");
875       output.println("/* type */"+param_type.getClassDesc().getId()+",");
876       output.println("/* number of DNF terms */"+dnfterms+",");
877       output.println("parameterdnf_"+i+"_"+task.getSafeSymbol()+",");
878       output.println("0,");
879       if (param_tag!=null)
880         output.println("/* number of tags */"+param_tag.numTags()+",");
881       else
882         output.println("/* number of tags */ 0,");
883       output.println("parametertag_"+i+"_"+task.getSafeSymbol());
884       output.println("};");
885     }
886
887
888     output.println("struct parameterdescriptor * parameterdescriptors_"+task.getSafeSymbol()+"[] = {");
889     for (int i=0; i<task.numParameters(); i++) {
890       if (i!=0)
891         output.println(",");
892       output.print("&parameter_"+i+"_"+task.getSafeSymbol());
893     }
894     output.println("};");
895
896     output.println("struct taskdescriptor task_"+task.getSafeSymbol()+"={");
897     output.println("&"+task.getSafeSymbol()+",");
898     output.println("/* number of parameters */" +task.numParameters() + ",");
899     int numtotal=task.numParameters()+fm.numTags();
900     output.println("/* number total parameters */" +numtotal + ",");
901     output.println("parameterdescriptors_"+task.getSafeSymbol()+",");
902     output.println("\""+task.getSymbol()+"\"");
903     output.println("};");
904   }
905
906
907   /** The buildVirtualTables method outputs the virtual dispatch
908    * tables for methods. */
909
910   protected void buildVirtualTables(PrintWriter outvirtual) {
911     Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
912     while(classit.hasNext()) {
913       ClassDescriptor cd=(ClassDescriptor)classit.next();
914       if (virtualcalls.getMethodCount(cd)>maxcount)
915         maxcount=virtualcalls.getMethodCount(cd);
916     }
917     MethodDescriptor[][] virtualtable=null;
918     virtualtable=new MethodDescriptor[state.numClasses()+state.numArrays()][maxcount];
919
920     /* Fill in virtual table */
921     classit=state.getClassSymbolTable().getDescriptorsIterator();
922     while(classit.hasNext()) {
923       ClassDescriptor cd=(ClassDescriptor)classit.next();
924       if(cd.isInterface()) {
925         continue;
926       }        
927       fillinRow(cd, virtualtable, cd.getId());
928     }
929
930     ClassDescriptor objectcd=typeutil.getClass(TypeUtil.ObjectClass);
931     Iterator arrayit=state.getArrayIterator();
932     while(arrayit.hasNext()) {
933       TypeDescriptor td=(TypeDescriptor)arrayit.next();
934       int id=state.getArrayNumber(td);
935       fillinRow(objectcd, virtualtable, id+state.numClasses());
936     }
937
938     outvirtual.print("void * virtualtable[]={");
939     boolean needcomma=false;
940     for(int i=0; i<state.numClasses()+state.numArrays(); i++) {
941       for(int j=0; j<maxcount; j++) {
942         if (needcomma)
943           outvirtual.print(", ");
944         if (virtualtable[i][j]!=null) {
945           MethodDescriptor md=virtualtable[i][j];
946           outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
947         } else {
948           outvirtual.print("0");
949         }
950         needcomma=true;
951       }
952       outvirtual.println("");
953     }
954     outvirtual.println("};");
955     outvirtual.close();
956   }
957
958   protected void fillinRow(ClassDescriptor cd, MethodDescriptor[][] virtualtable, int rownum) {
959     /* Get inherited methods */
960     Iterator it_sifs = cd.getSuperInterfaces();
961     while(it_sifs.hasNext()) {
962       ClassDescriptor superif = (ClassDescriptor)it_sifs.next();
963       fillinRow(superif, virtualtable, rownum);
964     }
965     if (cd.getSuperDesc()!=null)
966       fillinRow(cd.getSuperDesc(), virtualtable, rownum);
967     /* Override them with our methods */
968     for(Iterator it=cd.getMethods(); it.hasNext(); ) {
969       MethodDescriptor md=(MethodDescriptor)it.next();
970       if (md.isStatic()||md.getReturnType()==null)
971         continue;
972       boolean foundmatch = false;
973       if(this.state.genAllMethods) {
974         foundmatch = true;
975       } else {
976         Set vec_md = this.state.getMethod2gen().getSet(md.getSymbol());
977         for(Iterator matchit=vec_md.iterator(); matchit.hasNext();) {
978           MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
979           if (md.matches(matchmd)) {
980             foundmatch=true;
981             break;
982           }
983         }
984       }
985       if(!foundmatch) {
986         continue;
987       }
988       int methodnum = virtualcalls.getMethodNumber(md);
989       virtualtable[rownum][methodnum]=md;
990     }
991   }
992
993   /** Generate array that contains the sizes of class objects.  The
994    * object allocation functions in the runtime use this
995    * information. */
996
997   protected void generateSizeArray(PrintWriter outclassdefs) {
998     outclassdefs.print("extern struct prefetchCountStats * evalPrefetch;\n");
999     generateSizeArrayExtensions(outclassdefs);
1000
1001     Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1002     cdarray=new ClassDescriptor[state.numClasses()];
1003     ifarray = new ClassDescriptor[state.numInterfaces()];
1004     cdarray[0] = null;
1005     int interfaceid = 0;
1006     while(it.hasNext()) {
1007       ClassDescriptor cd=(ClassDescriptor)it.next();
1008       if(cd.isInterface()) {
1009         ifarray[cd.getId()] = cd;
1010       } else {
1011         cdarray[cd.getId()] = cd;
1012       }
1013     }
1014
1015     arraytable=new TypeDescriptor[state.numArrays()];
1016
1017     Iterator arrayit=state.getArrayIterator();
1018     while(arrayit.hasNext()) {
1019       TypeDescriptor td=(TypeDescriptor)arrayit.next();
1020       int id=state.getArrayNumber(td);
1021       arraytable[id]=td;
1022     }
1023
1024     /* Print out types */
1025     outclassdefs.println("/* ");
1026     for(int i=0; i<state.numClasses(); i++) {
1027       ClassDescriptor cd=cdarray[i];
1028       if(cd == null) {
1029         outclassdefs.println("NULL " + i);
1030       } else {
1031         outclassdefs.println(cd +"  "+i);
1032       }
1033     }
1034
1035     for(int i=0; i<state.numArrays(); i++) {
1036       TypeDescriptor arraytd=arraytable[i];
1037       outclassdefs.println(arraytd.toPrettyString() +"  "+(i+state.numClasses()));
1038     }
1039     
1040     for(int i=0; i<state.numInterfaces(); i++) {
1041       ClassDescriptor ifcd = ifarray[i];
1042       outclassdefs.println(ifcd +"  "+(i+state.numClasses()+state.numArrays()));
1043     }
1044
1045     outclassdefs.println("*/");
1046
1047
1048     outclassdefs.print("int classsize[]={");
1049
1050     boolean needcomma=false;
1051     for(int i=0; i<state.numClasses(); i++) {
1052       if (needcomma)
1053         outclassdefs.print(", ");
1054       if(i>0) {
1055         outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")");
1056       } else {
1057         outclassdefs.print("0");
1058       }
1059       needcomma=true;
1060     }
1061
1062
1063     for(int i=0; i<state.numArrays(); i++) {
1064       if (needcomma)
1065         outclassdefs.print(", ");
1066       TypeDescriptor tdelement=arraytable[i].dereference();
1067       if (tdelement.isArray()||tdelement.isClass()||tdelement.isNull())
1068         outclassdefs.print("sizeof(void *)");
1069       else
1070         outclassdefs.print("sizeof("+tdelement.getSafeSymbol()+")");
1071       needcomma=true;
1072     }
1073     
1074     for(int i=0; i<state.numInterfaces(); i++) {
1075       if (needcomma)
1076         outclassdefs.print(", ");
1077       outclassdefs.print("sizeof(struct "+ifarray[i].getSafeSymbol()+")");
1078       needcomma=true;
1079     }
1080
1081     outclassdefs.println("};");
1082
1083     ClassDescriptor objectclass=typeutil.getClass(TypeUtil.ObjectClass);
1084     needcomma=false;
1085     outclassdefs.print("int typearray[]={");
1086     for(int i=0; i<state.numClasses(); i++) {
1087       ClassDescriptor cd=cdarray[i];
1088       ClassDescriptor supercd=i>0 ? cd.getSuperDesc() : null;
1089       if(supercd != null && supercd.isInterface()) {
1090         throw new Error("Super class can not be interfaces");
1091       }
1092       if (needcomma)
1093         outclassdefs.print(", ");
1094       if (supercd==null)
1095         outclassdefs.print("-1");
1096       else
1097         outclassdefs.print(supercd.getId());
1098       needcomma=true;
1099     }
1100
1101     for(int i=0; i<state.numArrays(); i++) {
1102       TypeDescriptor arraytd=arraytable[i];
1103       ClassDescriptor arraycd=arraytd.getClassDesc();
1104       if (arraycd==null) {
1105         if (needcomma)
1106           outclassdefs.print(", ");
1107         outclassdefs.print(objectclass.getId());
1108         needcomma=true;
1109         continue;
1110       }
1111       ClassDescriptor cd=arraycd.getSuperDesc();
1112       int type=-1;
1113       while(cd!=null) {
1114         TypeDescriptor supertd=new TypeDescriptor(cd);
1115         supertd.setArrayCount(arraytd.getArrayCount());
1116         type=state.getArrayNumber(supertd);
1117         if (type!=-1) {
1118           type+=state.numClasses();
1119           break;
1120         }
1121         cd=cd.getSuperDesc();
1122       }
1123       if (needcomma)
1124         outclassdefs.print(", ");
1125       outclassdefs.print(type);
1126       needcomma=true;
1127     }
1128     
1129     for(int i=0; i<state.numInterfaces(); i++) {
1130       ClassDescriptor cd=ifarray[i];
1131       ClassDescriptor supercd=cd.getSuperDesc();
1132       if(supercd != null && supercd.isInterface()) {
1133         throw new Error("Super class can not be interfaces");
1134       }
1135       if (needcomma)
1136     outclassdefs.print(", ");
1137       if (supercd==null)
1138     outclassdefs.print("-1");
1139       else
1140     outclassdefs.print(supercd.getId());
1141       needcomma=true;
1142     }
1143
1144     outclassdefs.println("};");
1145
1146     needcomma=false;
1147
1148
1149     outclassdefs.print("int typearray2[]={");
1150     for(int i=0; i<state.numArrays(); i++) {
1151       TypeDescriptor arraytd=arraytable[i];
1152       ClassDescriptor arraycd=arraytd.getClassDesc();
1153       if (arraycd==null) {
1154         if (needcomma)
1155           outclassdefs.print(", ");
1156         outclassdefs.print("-1");
1157         needcomma=true;
1158         continue;
1159       }
1160       ClassDescriptor cd=arraycd.getSuperDesc();
1161       int level=arraytd.getArrayCount()-1;
1162       int type=-1;
1163       for(; level>0; level--) {
1164         TypeDescriptor supertd=new TypeDescriptor(objectclass);
1165         supertd.setArrayCount(level);
1166         type=state.getArrayNumber(supertd);
1167         if (type!=-1) {
1168           type+=state.numClasses();
1169           break;
1170         }
1171       }
1172       if (needcomma)
1173         outclassdefs.print(", ");
1174       outclassdefs.print(type);
1175       needcomma=true;
1176     }
1177
1178     outclassdefs.println("};");
1179   }
1180
1181   /** Constructs params and temp objects for each method or task.
1182    * These objects tell the compiler which temps need to be
1183    * allocated.  */
1184
1185   protected void generateTempStructs(FlatMethod fm) {
1186     MethodDescriptor md=fm.getMethod();
1187     TaskDescriptor task=fm.getTask();
1188     ParamsObject objectparams=md!=null ? new ParamsObject(md,tag++) : new ParamsObject(task, tag++);
1189     if (md!=null)
1190       paramstable.put(md, objectparams);
1191     else
1192       paramstable.put(task, objectparams);
1193
1194     for(int i=0; i<fm.numParameters(); i++) {
1195       TempDescriptor temp=fm.getParameter(i);
1196       TypeDescriptor type=temp.getType();
1197       if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1198         objectparams.addPtr(temp);
1199       else
1200         objectparams.addPrim(temp);
1201     }
1202
1203     for(int i=0; i<fm.numTags(); i++) {
1204       TempDescriptor temp=fm.getTag(i);
1205       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1206         objectparams.addPtr(temp);
1207       else
1208         objectparams.addPrim(temp);
1209     }
1210
1211     TempObject objecttemps=md!=null ? new TempObject(objectparams,md,tag++) : new TempObject(objectparams, task, tag++);
1212     if (md!=null)
1213       tempstable.put(md, objecttemps);
1214     else
1215       tempstable.put(task, objecttemps);
1216
1217     for(Iterator nodeit=fm.getNodeSet().iterator(); nodeit.hasNext(); ) {
1218       FlatNode fn=(FlatNode)nodeit.next();
1219       TempDescriptor[] writes=fn.writesTemps();
1220       for(int i=0; i<writes.length; i++) {
1221         TempDescriptor temp=writes[i];
1222         TypeDescriptor type=temp.getType();
1223         if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1224           objecttemps.addPtr(temp);
1225         else
1226           objecttemps.addPrim(temp);
1227       }
1228     }
1229   }
1230
1231   /** This method outputs the following information about classes
1232    * and arrays:
1233    * (1) For classes, what are the locations of pointers.
1234    * (2) For arrays, does the array contain pointers or primitives.
1235    * (3) For classes, does the class contain flags.
1236    */
1237
1238   protected void generateLayoutStructs(PrintWriter output) {
1239     Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1240     while(it.hasNext()) {
1241       ClassDescriptor cn=(ClassDescriptor)it.next();
1242       output.println("unsigned INTPTR "+cn.getSafeSymbol()+"_pointers[]={");
1243       Iterator allit=cn.getFieldTable().getAllDescriptorsIterator();
1244       int count=0;
1245       while(allit.hasNext()) {
1246         FieldDescriptor fd=(FieldDescriptor)allit.next();
1247     if(fd.isStatic()) {
1248       continue;
1249     }
1250         TypeDescriptor type=fd.getType();
1251         if (type.isPtr())
1252           count++;
1253       }
1254       output.print(count);
1255       allit=cn.getFieldTable().getAllDescriptorsIterator();
1256       while(allit.hasNext()) {
1257         FieldDescriptor fd=(FieldDescriptor)allit.next();
1258     if(fd.isStatic()) {
1259       continue;
1260     }
1261         TypeDescriptor type=fd.getType();
1262         if (type.isPtr()) {
1263           output.println(",");
1264           output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+
1265                        fd.getSafeSymbol()+"))");
1266         }
1267       }
1268       output.println("};");
1269     }
1270     output.println("unsigned INTPTR * pointerarray[]={");
1271     boolean needcomma=false;
1272     for(int i=0; i<state.numClasses(); i++) {
1273       ClassDescriptor cn=cdarray[i];
1274       if (needcomma)
1275         output.println(",");
1276       needcomma=true;
1277       if(cn != null) {
1278         output.print(cn.getSafeSymbol()+"_pointers");
1279       } else {
1280         output.print("NULL");
1281       }
1282     }
1283
1284     for(int i=0; i<state.numArrays(); i++) {
1285       if (needcomma)
1286         output.println(", ");
1287       TypeDescriptor tdelement=arraytable[i].dereference();
1288       if (tdelement.isArray()||tdelement.isClass())
1289         output.print("((unsigned INTPTR *)1)");
1290       else
1291         output.print("0");
1292       needcomma=true;
1293     }
1294
1295     output.println("};");
1296     needcomma=false;
1297     output.println("int hasflags[]={");
1298     for(int i=0; i<state.numClasses(); i++) {
1299       ClassDescriptor cn=cdarray[i];
1300       if (needcomma)
1301         output.println(", ");
1302       needcomma=true;
1303       if ((cn != null) && (cn.hasFlags()))
1304         output.print("1");
1305       else
1306         output.print("0");
1307     }
1308     output.println("};");
1309   }
1310   
1311   private int checkarraysupertype(ClassDescriptor arraycd, TypeDescriptor arraytd) {
1312     int type=-1;
1313     
1314     TypeDescriptor supertd=new TypeDescriptor(arraycd);
1315     supertd.setArrayCount(arraytd.getArrayCount());
1316     type=state.getArrayNumber(supertd);
1317     if (type!=-1) {
1318       return type;
1319     }
1320     
1321     ClassDescriptor cd = arraycd.getSuperDesc();
1322     if(cd != null) {
1323       type = checkarraysupertype(cd, arraytd);
1324       if(type != -1) {
1325         return type;
1326       }
1327     }
1328
1329     Iterator it_sifs = arraycd.getSuperInterfaces();
1330     while(it_sifs.hasNext()) {
1331       ClassDescriptor ifcd = (ClassDescriptor)it_sifs.next();
1332       type = checkarraysupertype(ifcd, arraytd);
1333       if(type != -1) {
1334         return type;
1335       }
1336     }
1337     
1338     return type;
1339   }
1340
1341
1342   /** Print out table to give us supertypes */
1343   protected void generateSuperTypeTable(PrintWriter output) {
1344     ClassDescriptor objectclass=typeutil.getClass(TypeUtil.ObjectClass);
1345     for(int i=0; i<state.numClasses(); i++) {
1346       ClassDescriptor cn=cdarray[i];
1347       if(cn == null) {
1348         continue;
1349       }
1350       output.print("int supertypes" + cn.getSafeSymbol() + "[] = {");
1351       boolean ncomma = false;
1352       int snum = 0;
1353       if((cn != null) && (cn.getSuperDesc() != null)) {
1354         snum++;
1355       }
1356       Iterator it_sifs = cn != null? cn.getSuperInterfaces() : null;
1357       while(it_sifs != null && it_sifs.hasNext()) {
1358         snum++;
1359         it_sifs.next();
1360       }
1361       output.print(snum);
1362       ncomma = true;
1363       if ((cn != null) && (cn.getSuperDesc()!=null)) {
1364         if(ncomma) {
1365           output.print(",");
1366         }
1367         ClassDescriptor cdsuper=cn.getSuperDesc();
1368         output.print(cdsuper.getId());
1369       } 
1370       it_sifs = cn != null? cn.getSuperInterfaces() : null;
1371       while(it_sifs != null && it_sifs.hasNext()) {
1372         if(ncomma) {
1373           output.print(",");
1374         }
1375         output.print(((ClassDescriptor)it_sifs.next()).getId()+state.numClasses()+state.numArrays());
1376       }
1377       
1378       output.println("};");
1379     }
1380     
1381     for(int i=0; i<state.numArrays(); i++) {
1382       TypeDescriptor arraytd=arraytable[i];
1383       ClassDescriptor arraycd=arraytd.getClassDesc();
1384       output.print("int supertypes___arraytype___" + (i+state.numClasses()) + "[] = {");
1385       boolean ncomma = false;
1386       int snum = 0;
1387       if (arraycd==null) {
1388         snum++;
1389         output.print(snum);
1390         output.print(", ");
1391         output.print(objectclass.getId());
1392         output.println("};");
1393         continue;
1394       }
1395       if((arraycd != null) && (arraycd.getSuperDesc() != null)) {
1396         snum++;
1397       }
1398       Iterator it_sifs = arraycd != null? arraycd.getSuperInterfaces() : null;
1399       while(it_sifs != null && it_sifs.hasNext()) {
1400         snum++;
1401         it_sifs.next();
1402       }
1403       output.print(snum);
1404       ncomma = true;
1405       if ((arraycd != null) && (arraycd.getSuperDesc()!=null)) {
1406         ClassDescriptor cd=arraycd.getSuperDesc();
1407         int type=-1;
1408         if(cd!=null) {
1409           type = checkarraysupertype(cd, arraytd);
1410           if(type != -1) {
1411             type += state.numClasses();
1412           }
1413         }
1414         if (ncomma)
1415           output.print(", ");
1416         output.print(type);
1417       } 
1418       it_sifs = arraycd != null? arraycd.getSuperInterfaces() : null;
1419       while(it_sifs != null && it_sifs.hasNext()) {
1420         ClassDescriptor ifcd = (ClassDescriptor)it_sifs.next();
1421         int type = checkarraysupertype(ifcd , arraytd);
1422         if(type != -1) {
1423           type += state.numClasses();
1424         }
1425         if (ncomma)
1426           output.print(", ");
1427         output.print(type);
1428       }
1429       output.println("};");
1430     }
1431     
1432     for(int i=0; i<state.numInterfaces(); i++) {
1433       ClassDescriptor cn=ifarray[i];
1434       if(cn == null) {
1435         continue;
1436       }
1437       output.print("int supertypes" + cn.getSafeSymbol() + "[] = {");
1438       boolean ncomma = false;
1439       int snum = 0;
1440       if((cn != null) && (cn.getSuperDesc() != null)) {
1441         snum++;
1442       }
1443       Iterator it_sifs = cn != null? cn.getSuperInterfaces() : null;
1444       while(it_sifs != null && it_sifs.hasNext()) {
1445         snum++;
1446         it_sifs.next();
1447       }
1448       output.print(snum);
1449       ncomma = true;
1450       if ((cn != null) && (cn.getSuperDesc()!=null)) {
1451         if(ncomma) {
1452           output.print(",");
1453         }
1454         ClassDescriptor cdsuper=cn.getSuperDesc();
1455         output.print(cdsuper.getId());
1456       } 
1457       it_sifs = cn != null? cn.getSuperInterfaces() : null;
1458       while(it_sifs != null && it_sifs.hasNext()) {
1459         if(ncomma) {
1460           output.print(",");
1461         }
1462         output.print(((ClassDescriptor)it_sifs.next()).getId()+state.numClasses()+state.numArrays());
1463       }
1464       
1465       output.println("};");
1466     }
1467     
1468     output.println("int* supertypes[]={");
1469     boolean needcomma=false;
1470     for(int i=0; i<state.numClasses(); i++) {
1471       ClassDescriptor cn=cdarray[i];
1472       if (needcomma)
1473         output.println(",");
1474       needcomma=true;
1475       if(cn != null) {
1476         output.print("supertypes" + cn.getSafeSymbol());
1477       } else {
1478         output.print(0);
1479       }
1480     }
1481     
1482     for(int i=0; i<state.numArrays(); i++) {
1483       if (needcomma)
1484         output.println(",");
1485       needcomma = true;
1486       output.print("supertypes___arraytype___" + (i+state.numClasses()));
1487     }
1488     
1489     for(int i=0; i<state.numInterfaces(); i++) {
1490       ClassDescriptor cn=ifarray[i];
1491       if (needcomma)
1492     output.println(",");
1493       needcomma=true;
1494       output.print("supertypes" + cn.getSafeSymbol());
1495     }
1496     output.println("};");
1497   }
1498
1499   /** Force consistent field ordering between inherited classes. */
1500
1501   protected void printClassStruct(ClassDescriptor cn, PrintWriter classdefout, PrintWriter globaldefout, PrintWriter globaldefprimout) {
1502
1503     ClassDescriptor sp=cn.getSuperDesc();
1504     if (sp!=null)
1505       printClassStruct(sp, classdefout, /*globaldefout*/ null, null);
1506
1507     SymbolTable sitbl = cn.getSuperInterfaceTable();
1508     Iterator it_sifs = sitbl.getDescriptorsIterator();
1509     while(it_sifs.hasNext()) {
1510       ClassDescriptor si = (ClassDescriptor)it_sifs.next();
1511       printClassStruct(si, classdefout, /*globaldefout*/ null, null);
1512     }
1513
1514     if (!fieldorder.containsKey(cn)) {
1515       Vector fields=new Vector();
1516       fieldorder.put(cn,fields);
1517
1518       Vector fieldvec=cn.getFieldVec();
1519       for(int i=0; i<fieldvec.size(); i++) {
1520         FieldDescriptor fd=(FieldDescriptor)fieldvec.get(i);
1521         if((sp != null) && sp.getFieldTable().contains(fd.getSymbol())) {
1522           // a shadow field
1523         } else {
1524           it_sifs = sitbl.getDescriptorsIterator();
1525           boolean hasprinted = false;
1526           while(it_sifs.hasNext()) {
1527             ClassDescriptor si = (ClassDescriptor)it_sifs.next();
1528             if(si.getFieldTable().contains(fd.getSymbol())) {
1529               hasprinted = true;
1530               break;
1531             }
1532           }
1533           if(hasprinted) {
1534             // this field has been defined in the super class
1535           } else {
1536             fields.add(fd);
1537           }
1538         }
1539       }
1540     }
1541     //Vector fields=(Vector)fieldorder.get(cn);
1542
1543     Vector fields = cn.getFieldVec();
1544
1545     for(int i=0; i<fields.size(); i++) {
1546       FieldDescriptor fd=(FieldDescriptor)fields.get(i);
1547       String fstring = fd.getSafeSymbol();
1548       if(printedfieldstbl.containsKey(fstring)) {
1549         printedfieldstbl.put(fstring, cn);
1550         continue;
1551       } else {
1552         printedfieldstbl.put(fstring, cn);
1553       }
1554       if (fd.getType().isClass()
1555           && fd.getType().getClassDesc().isEnum()) {
1556         classdefout.println("  int " + fd.getSafeSymbol() + ";");
1557       } else if (fd.getType().isClass()||fd.getType().isArray()) {
1558         if (fd.isStatic()) {
1559           // TODO add version for normal Java later
1560           // static field
1561           if(globaldefout != null) {
1562             if(fd.isVolatile()) {
1563               globaldefout.println("  volatile struct "+fd.getType().getSafeSymbol()+ " * "+fd.getSafeSymbol()+";");
1564             } else {
1565               globaldefout.println("  struct "+fd.getType().getSafeSymbol()+ " * "+fd.getSafeSymbol()+";");
1566             }
1567             globaldefscount++;
1568           }
1569         } else if (fd.isVolatile()) {
1570           //volatile field
1571           classdefout.println("  volatile struct "+fd.getType().getSafeSymbol()+ " * "+fd.getSafeSymbol()+";");
1572         } else {
1573           classdefout.println("  struct "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1574         }
1575       } else if (fd.isStatic()) {
1576         // TODO add version for normal Java later
1577         // static field
1578         if(globaldefout != null) {
1579           if(fd.isVolatile()) {
1580             globaldefprimout.println("  volatile "+fd.getType().getSafeSymbol()+ " "+fd.getSafeSymbol()+";");
1581           } else {
1582             globaldefprimout.println("  "+fd.getType().getSafeSymbol()+ " "+fd.getSafeSymbol()+";");
1583           }
1584         }
1585       } else if (fd.isVolatile()) {
1586         //volatile field
1587         classdefout.println("  volatile "+fd.getType().getSafeSymbol()+ " "+fd.getSafeSymbol()+";");
1588       } else
1589         classdefout.println("  "+fd.getType().getSafeSymbol()+" "+fd.getSafeSymbol()+";");
1590     }
1591   }
1592
1593
1594   /* Map flags to integers consistently between inherited
1595    * classes. */
1596
1597   protected void mapFlags(ClassDescriptor cn) {
1598     ClassDescriptor sp=cn.getSuperDesc();
1599     if (sp!=null)
1600       mapFlags(sp);
1601     int max=0;
1602     if (!flagorder.containsKey(cn)) {
1603       Hashtable flags=new Hashtable();
1604       flagorder.put(cn,flags);
1605       if (sp!=null) {
1606         Hashtable superflags=(Hashtable)flagorder.get(sp);
1607         Iterator superflagit=superflags.keySet().iterator();
1608         while(superflagit.hasNext()) {
1609           FlagDescriptor fd=(FlagDescriptor)superflagit.next();
1610           Integer number=(Integer)superflags.get(fd);
1611           flags.put(fd, number);
1612           if ((number.intValue()+1)>max)
1613             max=number.intValue()+1;
1614         }
1615       }
1616
1617       Iterator flagit=cn.getFlags();
1618       while(flagit.hasNext()) {
1619         FlagDescriptor fd=(FlagDescriptor)flagit.next();
1620         if (sp==null||!sp.getFlagTable().contains(fd.getSymbol()))
1621           flags.put(fd, new Integer(max++));
1622       }
1623     }
1624   }
1625
1626
1627   /** This function outputs (1) structures that parameters are
1628    * passed in (when PRECISE GC is enabled) and (2) function
1629    * prototypes for the methods */
1630
1631   protected void generateCallStructs(ClassDescriptor cn, PrintWriter classdefout, PrintWriter output, PrintWriter headersout, PrintWriter globaldefout, PrintWriter globaldefprimout) {
1632     /* Output class structure */
1633     classdefout.println("struct "+cn.getSafeSymbol()+" {");
1634     classdefout.println("  int type;");
1635
1636
1637     additionalClassObjectFields(classdefout);
1638
1639
1640     if (state.EVENTMONITOR) {
1641       classdefout.println("  int objuid;");
1642     }
1643     if (state.THREAD) {
1644       classdefout.println("  pthread_t tid;");
1645       classdefout.println("  void * lockentry;");
1646       classdefout.println("  int lockcount;");
1647     }
1648     if (state.MGC) {
1649       classdefout.println("  int mutex;");
1650       classdefout.println("  volatile int notifycount;");
1651       classdefout.println("  volatile int objlock;");
1652       if(state.MULTICOREGC) {
1653         classdefout.println("  int marked;");
1654       }
1655     }
1656     if (state.TASK) {
1657       classdefout.println("  int flag;");
1658       if((!state.MULTICORE) || (cn.getSymbol().equals("TagDescriptor"))) {
1659         classdefout.println("  void * flagptr;");
1660       } else if (state.MULTICORE) {
1661         classdefout.println("  int version;");
1662         classdefout.println("  int * lock;"); // lock entry for this obj
1663         classdefout.println("  int mutex;");
1664         classdefout.println("  int lockcount;");
1665         if(state.MULTICOREGC) {
1666           classdefout.println("  int marked;");
1667         }
1668       }
1669       if (state.OPTIONAL) {
1670         classdefout.println("  int numfses;");
1671         classdefout.println("  int * fses;");
1672       }
1673     }
1674     printClassStruct(cn, classdefout, globaldefout, globaldefprimout);
1675     printedfieldstbl.clear(); // = new Hashtable<String, ClassDescriptor>();
1676     classdefout.println("};\n");
1677     generateCallStructsMethods(cn, output, headersout);
1678   }
1679
1680
1681   protected void generateCallStructsMethods(ClassDescriptor cn, PrintWriter output, PrintWriter headersout) {
1682     for(Iterator methodit=cn.getMethods(); methodit.hasNext(); ) {
1683       MethodDescriptor md=(MethodDescriptor)methodit.next();
1684       boolean foundmatch = false;
1685       if(this.state.genAllMethods) {
1686         foundmatch = true;
1687       } else {
1688         Set vec_md = this.state.getMethod2gen().getSet(md.getSymbol());
1689         for(Iterator matchit=vec_md.iterator(); matchit.hasNext();) {
1690           MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
1691           if (md.matches(matchmd)) {
1692             foundmatch=true;
1693             break;
1694           }
1695         }
1696       }
1697       if(foundmatch) {
1698         generateMethod(cn, md, headersout, output);
1699       }
1700     }
1701   }
1702
1703   protected void generateMethodParam(ClassDescriptor cn, MethodDescriptor md, PrintWriter output) {
1704     /* Output parameter structure */
1705     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1706       if(md.isInvokedByStatic() && !md.isStaticBlock() && !md.getModifiers().isNative()) {
1707         // generate the staticinit version
1708         String mdstring = md.getSafeMethodDescriptor() + "staticinit";
1709         
1710         ParamsObject objectparams=(ParamsObject) paramstable.get(md);
1711         output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_params {");
1712         output.println("  int size;");
1713         output.println("  void * next;");
1714         for(int i=0; i<objectparams.numPointers(); i++) {
1715           TempDescriptor temp=objectparams.getPointer(i);
1716           if(temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
1717             output.println("  int " + temp.getSafeSymbol() + ";");
1718           } else {
1719             output.println("  struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1720           }
1721         }
1722         output.println("};\n");
1723       }
1724       
1725       ParamsObject objectparams=(ParamsObject) paramstable.get(md);
1726       output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1727       output.println("  int size;");
1728       output.println("  void * next;");
1729       for(int i=0; i<objectparams.numPointers(); i++) {
1730         TempDescriptor temp=objectparams.getPointer(i);
1731         if(temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
1732           output.println("  int " + temp.getSafeSymbol() + ";");
1733         } else {
1734           output.println("  struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1735         }
1736       }
1737       output.println("};\n");
1738     }
1739   }
1740
1741   protected void generateMethod(ClassDescriptor cn, MethodDescriptor md, PrintWriter headersout, PrintWriter output) {
1742     FlatMethod fm=state.getMethodFlat(md);
1743     generateTempStructs(fm);
1744
1745     ParamsObject objectparams=(ParamsObject) paramstable.get(md);
1746     TempObject objecttemps=(TempObject) tempstable.get(md);
1747     
1748     boolean printcomma = false;
1749     
1750     generateMethodParam(cn, md, output);
1751     
1752     if(md.isInvokedByStatic() && !md.isStaticBlock() && !md.getModifiers().isNative()) {
1753       // generate the staticinit version
1754       String mdstring = md.getSafeMethodDescriptor() + "staticinit";
1755
1756       /* Output temp structure */
1757       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1758         output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_locals {");
1759         output.println("  int size;");
1760         output.println("  void * next;");
1761         for(int i=0; i<objecttemps.numPointers(); i++) {
1762           TempDescriptor temp=objecttemps.getPointer(i);
1763           if (!temp.getType().isArray() && temp.getType().isNull())
1764             output.println("  void * "+temp.getSafeSymbol()+";");
1765           else
1766             output.println("  struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1767         }
1768         output.println("};\n");
1769       }
1770       
1771       headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+" 1");
1772       /* First the return type */
1773       if (md.getReturnType()!=null) {
1774         if(md.getReturnType().isClass() && md.getReturnType().getClassDesc().isEnum()) {
1775           headersout.println("  int ");
1776         } else if (md.getReturnType().isClass()||md.getReturnType().isArray())
1777           headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1778         else
1779           headersout.print(md.getReturnType().getSafeSymbol()+" ");
1780       } else
1781         //catch the constructor case
1782         headersout.print("void ");
1783
1784       /* Next the method name */
1785       headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"(");
1786       printcomma=false;
1787       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1788         headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_params * "+paramsprefix);
1789         printcomma=true;
1790       }
1791
1792       /*  Output parameter list*/
1793       for(int i=0; i<objectparams.numPrimitives(); i++) {
1794         TempDescriptor temp=objectparams.getPrimitive(i);
1795         if (printcomma)
1796           headersout.print(", ");
1797         printcomma=true;
1798         if(temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
1799           headersout.print("int " + temp.getSafeSymbol());
1800         } else if (temp.getType().isClass()||temp.getType().isArray())
1801           headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1802         else
1803           headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1804       }
1805       headersout.println(");\n");
1806     }
1807
1808     /* Output temp structure */
1809     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1810       output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1811       output.println("  int size;");
1812       output.println("  void * next;");
1813       for(int i=0; i<objecttemps.numPointers(); i++) {
1814         TempDescriptor temp=objecttemps.getPointer(i);
1815         if (!temp.getType().isArray() && temp.getType().isNull())
1816           output.println("  void * "+temp.getSafeSymbol()+";");
1817         else
1818           output.println("  struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1819       }
1820       output.println("};\n");
1821     }
1822
1823     /********* Output method declaration ***********/
1824     headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1825     /* First the return type */
1826     if (md.getReturnType()!=null) {
1827       if(md.getReturnType().isClass() && md.getReturnType().getClassDesc().isEnum()) {
1828         headersout.println("  int ");
1829       } else if (md.getReturnType().isClass()||md.getReturnType().isArray())
1830         headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1831       else
1832         headersout.print(md.getReturnType().getSafeSymbol()+" ");
1833     } else
1834       //catch the constructor case
1835       headersout.print("void ");
1836
1837     /* Next the method name */
1838     headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1839     printcomma=false;
1840     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1841       headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1842       printcomma=true;
1843     }
1844
1845     /*  Output parameter list*/
1846     for(int i=0; i<objectparams.numPrimitives(); i++) {
1847       TempDescriptor temp=objectparams.getPrimitive(i);
1848       if (printcomma)
1849         headersout.print(", ");
1850       printcomma=true;
1851       if(temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
1852         headersout.print("int " + temp.getSafeSymbol());
1853       } else if (temp.getType().isClass()||temp.getType().isArray())
1854         headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1855       else
1856         headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1857     }
1858     headersout.println(");\n");
1859   }
1860
1861
1862   /** This function outputs (1) structures that parameters are
1863    * passed in (when PRECISE GC is enabled) and (2) function
1864    * prototypes for the tasks */
1865
1866   protected void generateTaskStructs(PrintWriter output, PrintWriter headersout) {
1867     /* Cycle through tasks */
1868     Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
1869
1870     while(taskit.hasNext()) {
1871       /* Classify parameters */
1872       TaskDescriptor task=(TaskDescriptor)taskit.next();
1873       FlatMethod fm=state.getMethodFlat(task);
1874       generateTempStructs(fm);
1875
1876       ParamsObject objectparams=(ParamsObject) paramstable.get(task);
1877       TempObject objecttemps=(TempObject) tempstable.get(task);
1878
1879       /* Output parameter structure */
1880       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1881         output.println("struct "+task.getSafeSymbol()+"_params {");
1882         output.println("  int size;");
1883         output.println("  void * next;");
1884         for(int i=0; i<objectparams.numPointers(); i++) {
1885           TempDescriptor temp=objectparams.getPointer(i);
1886           output.println("  struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1887         }
1888
1889         output.println("};\n");
1890         if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
1891           maxtaskparams=objectparams.numPointers()+fm.numTags();
1892         }
1893       }
1894
1895       /* Output temp structure */
1896       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1897         output.println("struct "+task.getSafeSymbol()+"_locals {");
1898         output.println("  int size;");
1899         output.println("  void * next;");
1900         for(int i=0; i<objecttemps.numPointers(); i++) {
1901           TempDescriptor temp=objecttemps.getPointer(i);
1902           if (!temp.getType().isArray() && temp.getType().isNull())
1903             output.println("  void * "+temp.getSafeSymbol()+";");
1904           else if(temp.getType().isTag())
1905             output.println("  struct "+
1906                            (new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1907           else
1908             output.println("  struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1909         }
1910         output.println("};\n");
1911       }
1912
1913       /* Output task declaration */
1914       headersout.print("void " + task.getSafeSymbol()+"(");
1915
1916       boolean printcomma=false;
1917       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1918         headersout.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
1919       } else
1920         headersout.print("void * parameterarray[]");
1921       headersout.println(");\n");
1922     }
1923   }
1924
1925   protected void generateFlatMethod(FlatMethod fm, PrintWriter output) {
1926     if (State.PRINTFLAT)
1927       System.out.println(fm.printMethod());
1928     MethodDescriptor md=fm.getMethod();
1929     TaskDescriptor task=fm.getTask();
1930     ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
1931     ParamsObject objectparams=(ParamsObject)paramstable.get(md!=null ? md : task);
1932     
1933     if((md != null) && md.isInvokedByStatic() && !md.isStaticBlock() && !md.getModifiers().isNative()) {
1934       // generate a special static init version
1935       mgcstaticinit = true;
1936       String mdstring = md.getSafeMethodDescriptor() + "staticinit";
1937       
1938       generateHeader(fm, md!=null ? md : task,output);
1939       TempObject objecttemp=(TempObject) tempstable.get(md!=null ? md : task);
1940       
1941       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1942         output.print("   struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_locals "+localsprefix+"={");
1943         output.print(objecttemp.numPointers()+",");
1944         output.print(paramsprefix);
1945         for(int j=0; j<objecttemp.numPointers(); j++)
1946           output.print(", NULL");
1947         output.println("};");
1948       }
1949
1950       for(int i=0; i<objecttemp.numPrimitives(); i++) {
1951         TempDescriptor td=objecttemp.getPrimitive(i);
1952         TypeDescriptor type=td.getType();
1953         if (type.isNull() && !type.isArray())
1954           output.println("   void * "+td.getSafeSymbol()+";");
1955         else if (type.isClass() && type.getClassDesc().isEnum()) {
1956           output.println("   int " + td.getSafeSymbol() + ";");
1957         } else if (type.isClass()||type.isArray())
1958           output.println("   struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1959         else
1960           output.println("   "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1961       }
1962
1963       additionalCodeAtTopFlatMethodBody(output, fm);
1964
1965       /* Check to see if we need to do a GC if this is a
1966        * multi-threaded program...*/
1967
1968       if (((state.OOOJAVA||state.THREAD)&&GENERATEPRECISEGC)
1969           || this.state.MULTICOREGC) {
1970         //Don't bother if we aren't in recursive methods...The loops case will catch it
1971         if (callgraph.getAllMethods(md).contains(md)) {
1972           if (this.state.MULTICOREGC) {
1973             output.println("if(gcflag) gc("+localsprefixaddr+");");
1974           } else {
1975             output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
1976           }
1977         }
1978       }
1979       
1980       generateCode(fm.getNext(0), fm, null, output);
1981
1982       output.println("}\n\n");
1983       
1984       mgcstaticinit = false;
1985     }
1986     
1987     generateHeader(fm, md!=null ? md : task,output);
1988     TempObject objecttemp=(TempObject) tempstable.get(md!=null ? md : task);
1989
1990     if((md != null) && (md.isStaticBlock())) {
1991       mgcstaticinit = true;
1992     }
1993
1994     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1995       if (md!=null)
1996         output.print("   struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1997       else
1998         output.print("   struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={");
1999       output.print(objecttemp.numPointers()+",");
2000       output.print(paramsprefix);
2001       for(int j=0; j<objecttemp.numPointers(); j++)
2002         output.print(", NULL");
2003       output.println("};");
2004     }
2005
2006     for(int i=0; i<objecttemp.numPrimitives(); i++) {
2007       TempDescriptor td=objecttemp.getPrimitive(i);
2008       TypeDescriptor type=td.getType();
2009       if (type.isNull() && !type.isArray())
2010         output.println("   void * "+td.getSafeSymbol()+";");
2011       else if (type.isClass() && type.getClassDesc().isEnum()) {
2012         output.println("   int " + td.getSafeSymbol() + ";");
2013       } else if (type.isClass()||type.isArray())
2014         output.println("   struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
2015       else
2016         output.println("   "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
2017     }
2018
2019     additionalCodeAtTopFlatMethodBody(output, fm);
2020
2021     /* Check to see if we need to do a GC if this is a
2022      * multi-threaded program...*/
2023
2024     if (((state.OOOJAVA||state.THREAD)&&GENERATEPRECISEGC)
2025         || this.state.MULTICOREGC) {
2026       //Don't bother if we aren't in recursive methods...The loops case will catch it
2027       if (callgraph.getAllMethods(md).contains(md)) {
2028         if (this.state.MULTICOREGC) {
2029           output.println("if(gcflag) gc("+localsprefixaddr+");");
2030         } else {
2031           output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2032         }
2033       }
2034     }
2035
2036     if(fm.getMethod().isStaticBlock()) {
2037       // a static block, check if it has been executed
2038       output.println("  if(global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag != 0) {");
2039       output.println("    return;");
2040       output.println("  }");
2041       output.println("");
2042     }
2043
2044     generateCode(fm.getNext(0), fm, null, output);
2045
2046     output.println("}\n\n");
2047     
2048     mgcstaticinit = false;
2049   }
2050
2051   protected void generateCode(FlatNode first,
2052                               FlatMethod fm,
2053                               Set<FlatNode> stopset,
2054                               PrintWriter output) {
2055
2056     /* Assign labels to FlatNode's if necessary.*/
2057
2058     Hashtable<FlatNode, Integer> nodetolabel;
2059
2060     nodetolabel=assignLabels(first, stopset);
2061
2062     Set<FlatNode> storeset=null;
2063     HashSet<FlatNode> genset=null;
2064     HashSet<FlatNode> refset=null;
2065     Set<FlatNode> unionset=null;
2066
2067     /* Do the actual code generation */
2068     FlatNode current_node=null;
2069     HashSet tovisit=new HashSet();
2070     HashSet visited=new HashSet();
2071     tovisit.add(first);
2072     while(current_node!=null||!tovisit.isEmpty()) {
2073       if (current_node==null) {
2074         current_node=(FlatNode)tovisit.iterator().next();
2075         tovisit.remove(current_node);
2076       } else if (tovisit.contains(current_node)) {
2077         tovisit.remove(current_node);
2078       }
2079       visited.add(current_node);
2080       if (nodetolabel.containsKey(current_node)) {
2081         output.println("L"+nodetolabel.get(current_node)+":");
2082       }
2083       if (state.INSTRUCTIONFAILURE) {
2084         if (state.THREAD) {
2085           output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
2086         } else
2087           output.println("if ((--instructioncount)==0) injectinstructionfailure();");
2088       }
2089       if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
2090         output.print("   ");
2091         generateFlatNode(fm, current_node, output);
2092
2093         if (state.OOOJAVA && stopset!=null) {
2094           assert first.getPrev(0) instanceof FlatSESEEnterNode;
2095           assert current_node       instanceof FlatSESEExitNode;
2096           FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev(0);
2097           FlatSESEExitNode fsxn = (FlatSESEExitNode)  current_node;
2098           assert fsen.getFlatExit().equals(fsxn);
2099           assert fsxn.getFlatEnter().equals(fsen);
2100         }
2101         if (current_node.kind()!=FKind.FlatReturnNode) {
2102           if((fm.getMethod() != null) && (fm.getMethod().isStaticBlock())) {
2103             // a static block, check if it has been executed
2104             output.println("  global_defsprim_p->" + fm.getMethod().getClassDesc().getSafeSymbol()+"static_block_exe_flag = 1;");
2105             output.println("");
2106           }
2107           output.println("   return;");
2108         }
2109         current_node=null;
2110       } else if(current_node.numNext()==1) {
2111         FlatNode nextnode;
2112         if (state.OOOJAVA &&
2113             current_node.kind()==FKind.FlatSESEEnterNode) {
2114           FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
2115           generateFlatNode(fm, current_node, output);
2116           nextnode=fsen.getFlatExit().getNext(0);
2117         } else {
2118           output.print("   ");
2119           generateFlatNode(fm, current_node, output);
2120           nextnode=current_node.getNext(0);
2121         }
2122         if (visited.contains(nextnode)) {
2123           output.println("goto L"+nodetolabel.get(nextnode)+";");
2124           current_node=null;
2125         } else
2126           current_node=nextnode;
2127       } else if (current_node.numNext()==2) {
2128         /* Branch */
2129         output.print("   ");
2130         generateFlatCondBranch(fm, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2131         if (!visited.contains(current_node.getNext(1)))
2132           tovisit.add(current_node.getNext(1));
2133         if (visited.contains(current_node.getNext(0))) {
2134           output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2135           current_node=null;
2136         } else
2137           current_node=current_node.getNext(0);
2138       } else throw new Error();
2139     }
2140   }
2141
2142   protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
2143     HashSet tovisit=new HashSet();
2144     HashSet visited=new HashSet();
2145     int labelindex=0;
2146     Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2147     tovisit.add(first);
2148
2149     /*Assign labels first.  A node needs a label if the previous
2150      * node has two exits or this node is a join point. */
2151
2152     while(!tovisit.isEmpty()) {
2153       FlatNode fn=(FlatNode)tovisit.iterator().next();
2154       tovisit.remove(fn);
2155       visited.add(fn);
2156
2157
2158       if(lastset!=null&&lastset.contains(fn)) {
2159         // if last is not null and matches, don't go
2160         // any further for assigning labels
2161         continue;
2162       }
2163
2164       for(int i=0; i<fn.numNext(); i++) {
2165         FlatNode nn=fn.getNext(i);
2166
2167         if(i>0) {
2168           //1) Edge >1 of node
2169           nodetolabel.put(nn,new Integer(labelindex++));
2170         }
2171         if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2172           tovisit.add(nn);
2173         } else {
2174           //2) Join point
2175           nodetolabel.put(nn,new Integer(labelindex++));
2176         }
2177       }
2178     }
2179     return nodetolabel;
2180   }
2181
2182   /** Generate text string that corresponds to the TempDescriptor td. */
2183   protected String generateTemp(FlatMethod fm, TempDescriptor td) {
2184     MethodDescriptor md=fm.getMethod();
2185     TaskDescriptor task=fm.getTask();
2186     TempObject objecttemps=(TempObject) tempstable.get(md!=null ? md : task);
2187
2188     if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
2189       return td.getSafeSymbol();
2190     }
2191
2192     if (objecttemps.isLocalPtr(td)) {
2193       return localsprefixderef+td.getSafeSymbol();
2194     }
2195
2196     if (objecttemps.isParamPtr(td)) {
2197       return paramsprefix+"->"+td.getSafeSymbol();
2198     }
2199
2200     throw new Error();
2201   }
2202
2203
2204
2205   protected void generateFlatNode(FlatMethod fm, FlatNode fn, PrintWriter output) {
2206     if(state.LINENUM) printSourceLineNumber(fm,fn,output);
2207     additionalCodePreNode(fm, fn, output);
2208
2209     switch(fn.kind()) {
2210     case FKind.FlatAtomicEnterNode:
2211       generateFlatAtomicEnterNode(fm, (FlatAtomicEnterNode) fn, output);
2212       break;
2213
2214     case FKind.FlatAtomicExitNode:
2215       generateFlatAtomicExitNode(fm, (FlatAtomicExitNode) fn, output);
2216       break;
2217
2218     case FKind.FlatInstanceOfNode:
2219       generateFlatInstanceOfNode(fm, (FlatInstanceOfNode)fn, output);
2220       break;
2221
2222     case FKind.FlatSESEEnterNode:
2223       generateFlatSESEEnterNode(fm, (FlatSESEEnterNode)fn, output);
2224       break;
2225
2226     case FKind.FlatSESEExitNode:
2227       generateFlatSESEExitNode(fm, (FlatSESEExitNode)fn, output);
2228       break;
2229
2230     case FKind.FlatWriteDynamicVarNode:
2231       generateFlatWriteDynamicVarNode(fm, (FlatWriteDynamicVarNode)fn, output);
2232       break;
2233
2234     case FKind.FlatGlobalConvNode:
2235       generateFlatGlobalConvNode(fm, (FlatGlobalConvNode) fn, output);
2236       break;
2237
2238     case FKind.FlatTagDeclaration:
2239       generateFlatTagDeclaration(fm, (FlatTagDeclaration) fn,output);
2240       break;
2241
2242     case FKind.FlatCall:
2243       generateFlatCall(fm, (FlatCall) fn,output);
2244       break;
2245
2246     case FKind.FlatFieldNode:
2247       generateFlatFieldNode(fm, (FlatFieldNode) fn,output);
2248       break;
2249
2250     case FKind.FlatElementNode:
2251       generateFlatElementNode(fm, (FlatElementNode) fn,output);
2252       break;
2253
2254     case FKind.FlatSetElementNode:
2255       generateFlatSetElementNode(fm, (FlatSetElementNode) fn,output);
2256       break;
2257
2258     case FKind.FlatSetFieldNode:
2259       generateFlatSetFieldNode(fm, (FlatSetFieldNode) fn,output);
2260       break;
2261
2262     case FKind.FlatNew:
2263       generateFlatNew(fm, (FlatNew) fn,output);
2264       break;
2265
2266     case FKind.FlatOpNode:
2267       generateFlatOpNode(fm, (FlatOpNode) fn,output);
2268       break;
2269
2270     case FKind.FlatCastNode:
2271       generateFlatCastNode(fm, (FlatCastNode) fn,output);
2272       break;
2273
2274     case FKind.FlatLiteralNode:
2275       generateFlatLiteralNode(fm, (FlatLiteralNode) fn,output);
2276       break;
2277
2278     case FKind.FlatReturnNode:
2279       generateFlatReturnNode(fm, (FlatReturnNode) fn,output);
2280       break;
2281
2282     case FKind.FlatNop:
2283       output.println("/* nop */");
2284       break;
2285
2286     case FKind.FlatGenReachNode:
2287       // this node is just for generating a reach graph
2288       // in disjointness analysis at a particular program point
2289       break;
2290
2291     case FKind.FlatExit:
2292       output.println("/* exit */");
2293       break;
2294
2295     case FKind.FlatBackEdge:
2296       generateFlatBackEdge(fm, (FlatBackEdge)fn, output);
2297       break;
2298
2299     case FKind.FlatCheckNode:
2300       generateFlatCheckNode(fm, (FlatCheckNode) fn, output);
2301       break;
2302
2303     case FKind.FlatFlagActionNode:
2304       generateFlatFlagActionNode(fm, (FlatFlagActionNode) fn, output);
2305       break;
2306
2307     case FKind.FlatPrefetchNode:
2308       generateFlatPrefetchNode(fm, (FlatPrefetchNode) fn, output);
2309       break;
2310
2311     case FKind.FlatOffsetNode:
2312       generateFlatOffsetNode(fm, (FlatOffsetNode)fn, output);
2313       break;
2314
2315     default:
2316       throw new Error();
2317     }
2318
2319     additionalCodePostNode(fm, fn, output);
2320   }
2321
2322   public void generateFlatBackEdge(FlatMethod fm, FlatBackEdge fn, PrintWriter output) {
2323     if (((state.OOOJAVA||state.THREAD)&&GENERATEPRECISEGC)
2324         || (this.state.MULTICOREGC)) {
2325       if(this.state.MULTICOREGC) {
2326         output.println("if (gcflag) gc("+localsprefixaddr+");");
2327       } else {
2328         output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2329       }
2330     } else
2331       output.println("/* nop */");
2332   }
2333
2334   public void generateFlatOffsetNode(FlatMethod fm, FlatOffsetNode fofn, PrintWriter output) {
2335     output.println("/* FlatOffsetNode */");
2336     FieldDescriptor fd=fofn.getField();
2337     if(!fd.isStatic()) {
2338     output.println(generateTemp(fm, fofn.getDst())+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+
2339                    fd.getSafeSymbol()+");");
2340     }
2341     output.println("/* offset */");
2342   }
2343
2344   public void generateFlatPrefetchNode(FlatMethod fm, FlatPrefetchNode fpn, PrintWriter output) {
2345   }
2346
2347   public void generateFlatGlobalConvNode(FlatMethod fm, FlatGlobalConvNode fgcn, PrintWriter output) {
2348   }
2349
2350   public void generateFlatInstanceOfNode(FlatMethod fm,  FlatInstanceOfNode fion, PrintWriter output) {
2351     int type;
2352     int otype;
2353     if (fion.getType().isArray()) {
2354       type=state.getArrayNumber(fion.getType())+state.numClasses();
2355     } else if (fion.getType().getClassDesc().isInterface()) {
2356       type=fion.getType().getClassDesc().getId()+state.numClasses()+state.numArrays();
2357     } else {
2358       type=fion.getType().getClassDesc().getId();
2359     }
2360     if (fion.getSrc().getType().isArray()) {
2361       otype=state.getArrayNumber(fion.getSrc().getType())+state.numClasses();
2362     } else if (fion.getSrc().getType().getClassDesc().isInterface()) {
2363       otype=fion.getSrc().getType().getClassDesc().getId()+state.numClasses()+state.numArrays();
2364     } else {
2365       otype=fion.getSrc().getType().getClassDesc().getId();
2366     }
2367
2368     if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
2369       output.println(generateTemp(fm, fion.getDst())+"=(" + generateTemp(fm,fion.getSrc()) + "!= NULL);");
2370     else {
2371       output.println(generateTemp(fm, fion.getDst())+"=instanceof("+generateTemp(fm,fion.getSrc())+","+type+");");
2372     }
2373   }
2374
2375   public void generateFlatAtomicEnterNode(FlatMethod fm, FlatAtomicEnterNode faen, PrintWriter output) {
2376   }
2377
2378   public void generateFlatAtomicExitNode(FlatMethod fm,  FlatAtomicExitNode faen, PrintWriter output) {
2379   }
2380
2381   public void generateFlatSESEEnterNode(FlatMethod fm,
2382                                         FlatSESEEnterNode fsen,
2383                                         PrintWriter output) {
2384     // if OOOJAVA flag is off, okay that SESE nodes are in IR graph,
2385     // just skip over them and code generates exactly the same
2386   }
2387
2388   public void generateFlatSESEExitNode(FlatMethod fm,
2389                                        FlatSESEExitNode fsexn,
2390                                        PrintWriter output) {
2391     // if OOOJAVA flag is off, okay that SESE nodes are in IR graph,
2392     // just skip over them and code generates exactly the same
2393   }
2394
2395   public void generateFlatWriteDynamicVarNode(FlatMethod fm,
2396                                               FlatWriteDynamicVarNode fwdvn,
2397                                               PrintWriter output) {
2398   }
2399
2400
2401   protected void generateFlatCheckNode(FlatMethod fm,  FlatCheckNode fcn, PrintWriter output) {
2402     if (state.CONSCHECK) {
2403       String specname=fcn.getSpec();
2404       String varname="repairstate___";
2405       output.println("{");
2406       output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
2407
2408       TempDescriptor[] temps=fcn.getTemps();
2409       String[] vars=fcn.getVars();
2410       for(int i=0; i<temps.length; i++) {
2411         output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i])+";");
2412       }
2413
2414       output.println("if (doanalysis"+specname+"("+varname+")) {");
2415       output.println("free"+specname+"_state("+varname+");");
2416       output.println("} else {");
2417       output.println("/* Bad invariant */");
2418       output.println("free"+specname+"_state("+varname+");");
2419       output.println("abort_task();");
2420       output.println("}");
2421       output.println("}");
2422     }
2423   }
2424
2425   protected void generateFlatCall(FlatMethod fm, FlatCall fc, PrintWriter output) {
2426     MethodDescriptor md=fc.getMethod();
2427     ParamsObject objectparams=(ParamsObject)paramstable.get(md);
2428     ClassDescriptor cn=md.getClassDesc();
2429     String mdstring = md.getSafeMethodDescriptor();
2430     if(mgcstaticinit && !md.isStaticBlock() && !md.getModifiers().isNative()) {
2431       mdstring += "staticinit";
2432     }
2433
2434     // if the called method is a static block or a static method or a constructor
2435     // need to check if it can be invoked inside some static block
2436     if((md.isStatic() || md.isStaticBlock() || md.isConstructor()) &&
2437        ((fm.getMethod() != null) && ((fm.getMethod().isStaticBlock()) || (fm.getMethod().isInvokedByStatic())))) {
2438       if(!md.isInvokedByStatic()) {
2439         System.err.println("Error: a method that is invoked inside a static block is not tagged!");
2440       }
2441       // is a static block or is invoked in some static block
2442       ClassDescriptor cd = fm.getMethod().getClassDesc();
2443       if(cd == cn) {
2444         // the same class, do nothing
2445       } else if(mgcstaticinit) {
2446         // generate static init check code if it has not done static init in main()
2447         if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) {
2448           // need to check if the class' static fields have been initialized and/or
2449           // its static blocks have been executed
2450           output.println("if(global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag == 0) {");
2451           if(cn.getNumStaticBlocks() != 0) {
2452             MethodDescriptor t_md = (MethodDescriptor)cn.getMethodTable().get("staticblocks");
2453         if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2454           output.print("       struct "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"_params __parameterlist__={");
2455           output.println("0, NULL};");
2456           output.println("     "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"(& __parameterlist__);");
2457         } else {
2458           output.println("  "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();");
2459         }
2460           } else {
2461             output.println("  global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag = 1;");
2462           }
2463           output.println("}");
2464         }
2465       }
2466     }
2467     if((md.getSymbol().equals("MonitorEnter") || md.getSymbol().equals("MonitorExit")) && fc.getThis().getSymbol().equals("classobj")) {
2468       output.println("{");
2469       // call MonitorEnter/MonitorExit on a class obj
2470       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2471         output.print("       struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
2472         output.println("1," + localsprefixaddr + ", global_defs_p->"+ fc.getThis().getType().getClassDesc().getSafeSymbol() +"classobj};");
2473         output.println("     "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
2474       } else {
2475       output.println("       " + cn.getSafeSymbol()+md.getSafeSymbol()+"_"
2476                      + md.getSafeMethodDescriptor() + "((struct ___Object___*)(global_defs_p->"
2477                      + fc.getThis().getType().getClassDesc().getSafeSymbol() +"classobj));");
2478       }
2479       output.println("}");
2480       return;
2481     }
2482     
2483     output.println("{");
2484     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2485       output.print("       struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_params __parameterlist__={");
2486       output.print(objectparams.numPointers());
2487       output.print(", "+localsprefixaddr);
2488       if (md.getThis()!=null) {
2489         output.print(", ");
2490         output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis()));
2491       }
2492       if (fc.getThis()!=null&&md.getThis()==null) {
2493         System.out.println("WARNING!!!!!!!!!!!!");
2494         System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
2495       }
2496
2497
2498       for(int i=0; i<fc.numArgs(); i++) {
2499         Descriptor var=md.getParameter(i);
2500         TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
2501         if (objectparams.isParamPtr(paramtemp)) {
2502           TempDescriptor targ=fc.getArg(i);
2503           output.print(", ");
2504           TypeDescriptor td=md.getParamType(i);
2505           if (td.isTag())
2506             output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()  +" *)"+generateTemp(fm, targ));
2507           else
2508             output.print("(struct "+md.getParamType(i).getSafeSymbol()  +" *)"+generateTemp(fm, targ));
2509         }
2510       }
2511       output.println("};");
2512     }
2513     output.print("       ");
2514
2515
2516     if (fc.getReturnTemp()!=null)
2517       output.print(generateTemp(fm,fc.getReturnTemp())+"=");
2518
2519     /* Do we need to do virtual dispatch? */
2520     if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
2521       //no
2522       output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring);
2523     } else {
2524       //yes
2525       output.print("((");
2526       if (md.getReturnType().isClass() && md.getReturnType().getClassDesc().isEnum()) {
2527         output.print("int ");
2528       } else if (md.getReturnType().isClass()||md.getReturnType().isArray())
2529         output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
2530       else
2531         output.print(md.getReturnType().getSafeSymbol()+" ");
2532       output.print("(*)(");
2533
2534       boolean printcomma=false;
2535       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2536         output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_params * ");
2537         printcomma=true;
2538       }
2539
2540       for(int i=0; i<objectparams.numPrimitives(); i++) {
2541         TempDescriptor temp=objectparams.getPrimitive(i);
2542         if (printcomma)
2543           output.print(", ");
2544         printcomma=true;
2545         if (temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
2546           output.print("int ");
2547         } else if (temp.getType().isClass()||temp.getType().isArray())
2548           output.print("struct " + temp.getType().getSafeSymbol()+" * ");
2549         else
2550           output.print(temp.getType().getSafeSymbol());
2551       }
2552
2553
2554       output.print("))virtualtable["+generateTemp(fm,fc.getThis())+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
2555     }
2556
2557     output.print("(");
2558     boolean needcomma=false;
2559     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2560       output.print("&__parameterlist__");
2561       needcomma=true;
2562     }
2563
2564     if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
2565       if (fc.getThis()!=null) {
2566         TypeDescriptor ptd=null;
2567         if(md.getThis() != null) {
2568           ptd = md.getThis().getType();
2569         } else {
2570           ptd = fc.getThis().getType();
2571         }
2572         if (needcomma)
2573           output.print(",");
2574         if(ptd.isClass() && ptd.getClassDesc().isEnum()) {
2575           // do nothing
2576         } else if (ptd.isClass()&&!ptd.isArray())
2577           output.print("(struct "+ptd.getSafeSymbol()+" *) ");
2578         output.print(generateTemp(fm,fc.getThis()));
2579         needcomma=true;
2580       }
2581     }
2582
2583     for(int i=0; i<fc.numArgs(); i++) {
2584       Descriptor var=md.getParameter(i);
2585       TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
2586       if (objectparams.isParamPrim(paramtemp)) {
2587         TempDescriptor targ=fc.getArg(i);
2588         if (needcomma)
2589           output.print(", ");
2590
2591         TypeDescriptor ptd=md.getParamType(i);
2592         if (ptd.isClass() && ptd.getClassDesc().isEnum()) {
2593           // do nothing
2594         } else if (ptd.isClass()&&!ptd.isArray())
2595           output.print("(struct "+ptd.getSafeSymbol()+" *) ");
2596         output.print(generateTemp(fm, targ));
2597         needcomma=true;
2598       }
2599     }
2600     output.println(");");
2601     output.println("   }");
2602   }
2603
2604   protected boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
2605     if(thiscd.isInterface()) {
2606       // for interfaces, always need virtual dispatch
2607       return false;
2608     } else {
2609     Set subclasses=typeutil.getSubClasses(thiscd);
2610     if (subclasses==null)
2611       return true;
2612     for(Iterator classit=subclasses.iterator(); classit.hasNext(); ) {
2613       ClassDescriptor cd=(ClassDescriptor)classit.next();
2614       Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol());
2615       for(Iterator matchit=possiblematches.iterator(); matchit.hasNext(); ) {
2616         MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
2617         if (md.matches(matchmd))
2618           return false;
2619       }
2620     }
2621     }
2622     return true;
2623   }
2624
2625   protected void generateFlatFieldNode(FlatMethod fm, FlatFieldNode ffn, PrintWriter output) {
2626     
2627     if(ffn.getField().isStatic()) {
2628       // static field
2629       if((fm.getMethod().isStaticBlock()) || (fm.getMethod().isInvokedByStatic())) {
2630         // is a static block or is invoked in some static block
2631         ClassDescriptor cd = fm.getMethod().getClassDesc();
2632         ClassDescriptor cn = ffn.getSrc().getType().getClassDesc();
2633         if(cd == cn) {
2634           // the same class, do nothing
2635         } else if(mgcstaticinit) {
2636       // generate the static init check code if has not done the static init in main()
2637           if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) {
2638             // need to check if the class' static fields have been initialized and/or
2639             // its static blocks have been executed
2640             output.println("if(global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag == 0) {");
2641             if(cn.getNumStaticBlocks() != 0) {
2642               MethodDescriptor t_md = (MethodDescriptor)cn.getMethodTable().get("staticblocks");
2643           if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2644             output.print("       struct "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"_params __parameterlist__={");
2645             output.println("0, NULL};");
2646             output.println("     "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"(& __parameterlist__);");
2647           } else {
2648             output.println("  "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();");
2649           }
2650             } else {
2651               output.println("  global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag = 1;");
2652             }
2653             output.println("}");
2654           }
2655         }
2656       }
2657       // redirect to the global_defs_p structure
2658       if((ffn.getField().isStatic()) || (ffn.getSrc().getType().isClassNameRef())) {
2659         // reference to the static field with Class name
2660         if (ffn.getField().getType().isPtr())
2661           output.println(generateTemp(fm, ffn.getDst())+"=global_defs_p->"+ffn.getField().getSafeSymbol()+";");
2662         else
2663           output.println(generateTemp(fm, ffn.getDst())+"=global_defsprim_p->"+ffn.getField().getSafeSymbol()+";");
2664       } else {
2665         output.println(generateTemp(fm, ffn.getDst())+"=*"+ generateTemp(fm,ffn.getSrc())+"->"+ ffn.getField().getSafeSymbol()+";");
2666       }
2667     } else if (ffn.getField().isEnum()) {
2668       // an Enum value, directly replace the field access as int
2669       output.println(generateTemp(fm, ffn.getDst()) + "=" + ffn.getField().enumValue() + ";");
2670     } else {
2671       output.println(generateTemp(fm, ffn.getDst())+"="+ generateTemp(fm,ffn.getSrc())+"->"+ ffn.getField().getSafeSymbol()+";");
2672     }
2673   }
2674
2675
2676   protected void generateFlatSetFieldNode(FlatMethod fm, FlatSetFieldNode fsfn, PrintWriter output) {
2677     if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
2678       throw new Error("Can't set array length");
2679     if (state.FASTCHECK) {
2680       String dst=generateTemp(fm, fsfn.getDst());
2681       output.println("if(!"+dst+"->"+localcopystr+") {");
2682       /* Link object into list */
2683       if (GENERATEPRECISEGC || this.state.MULTICOREGC)
2684         output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
2685       else
2686         output.println("COPY_OBJ("+dst+");");
2687       output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
2688       output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
2689       output.println("}");
2690     }
2691
2692     if(fsfn.getField().isStatic()) {
2693       // static field
2694       if((fm.getMethod().isStaticBlock()) || (fm.getMethod().isInvokedByStatic())) {
2695         // is a static block or is invoked in some static block
2696         ClassDescriptor cd = fm.getMethod().getClassDesc();
2697         ClassDescriptor cn = fsfn.getDst().getType().getClassDesc();
2698         if(cd == cn) {
2699           // the same class, do nothing
2700         } else if(mgcstaticinit){
2701       // generate static init check code if has not done the static init in main()
2702           if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) {
2703             // need to check if the class' static fields have been initialized and/or
2704             // its static blocks have been executed
2705             output.println("if(global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag == 0) {");
2706             if(cn.getNumStaticBlocks() != 0) {
2707               MethodDescriptor t_md = (MethodDescriptor)cn.getMethodTable().get("staticblocks");
2708           if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2709             output.print("       struct "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"_params __parameterlist__={");
2710             output.println("0, NULL};");
2711             output.println("     "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"(& __parameterlist__);");
2712           } else {
2713             output.println("  "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();");
2714           }
2715             } else {
2716               output.println("  global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag = 1;");
2717             }
2718             output.println("}");
2719           }
2720         }
2721       }
2722       // redirect to the global_defs_p structure
2723       if((fsfn.getDst().getType().isClassNameRef()) || (fsfn.getField().isStatic())) {
2724         // reference to the static field with Class name
2725         if (fsfn.getField().getType().isPtr())
2726           output.println("global_defs_p->" +
2727                          fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc())+";");
2728         else
2729           output.println("global_defsprim_p->" +
2730                          fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc())+";");
2731       } else {
2732         output.println("*"+generateTemp(fm, fsfn.getDst())+"->"+
2733                        fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc())+";");
2734       }
2735     } else {
2736       output.println(generateTemp(fm, fsfn.getDst())+"->"+
2737                      fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc())+";");
2738     }
2739   }
2740
2741
2742   protected void generateFlatElementNode(FlatMethod fm, FlatElementNode fen, PrintWriter output) {
2743     TypeDescriptor elementtype=fen.getSrc().getType().dereference();
2744     String type="";
2745
2746     if (elementtype.isClass() && elementtype.getClassDesc().isEnum()) {
2747       type="int ";
2748     } else if (elementtype.isArray()||elementtype.isClass())
2749       type="void *";
2750     else
2751       type=elementtype.getSafeSymbol()+" ";
2752
2753     if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
2754       output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fen.getIndex())+") >= "+generateTemp(fm,fen.getSrc()) + "->___length___))");
2755       output.println("failedboundschk();");
2756     }
2757     output.println(generateTemp(fm, fen.getDst())+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc())+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex())+"];");
2758   }
2759
2760   protected void generateFlatSetElementNode(FlatMethod fm, FlatSetElementNode fsen, PrintWriter output) {
2761     //TODO: need dynamic check to make sure this assignment is actually legal
2762     //Because Object[] could actually be something more specific...ie. Integer[]
2763
2764     TypeDescriptor elementtype=fsen.getDst().getType().dereference();
2765     String type="";
2766
2767     if (elementtype.isClass() && elementtype.getClassDesc().isEnum()) {
2768       type="int ";
2769     } else if (elementtype.isArray()||elementtype.isClass() || (elementtype.isNull()))
2770       type="void *";
2771     else
2772       type=elementtype.getSafeSymbol()+" ";
2773
2774     if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
2775       output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fsen.getIndex())+") >= "+generateTemp(fm,fsen.getDst()) + "->___length___))");
2776       output.println("failedboundschk();");
2777     }
2778     if (state.FASTCHECK) {
2779       String dst=generateTemp(fm, fsen.getDst());
2780       output.println("if(!"+dst+"->"+localcopystr+") {");
2781       /* Link object into list */
2782       if (GENERATEPRECISEGC || this.state.MULTICOREGC)
2783         output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
2784       else
2785         output.println("COPY_OBJ("+dst+");");
2786       output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
2787       output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
2788       output.println("}");
2789     }
2790     output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst())+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex())+"]="+generateTemp(fm,fsen.getSrc())+";");
2791   }
2792
2793
2794   protected void generateFlatNew(FlatMethod fm, FlatNew fn, PrintWriter output) {
2795     if (fn.getType().isArray()) {
2796       int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
2797       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2798         output.println(generateTemp(fm,fn.getDst())+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize())+");");
2799       } else {
2800         output.println(generateTemp(fm,fn.getDst())+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize())+");");
2801       }
2802     } else {
2803       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2804         output.println(generateTemp(fm,fn.getDst())+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
2805       } else {
2806         output.println(generateTemp(fm,fn.getDst())+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
2807       }
2808     }
2809     if (state.FASTCHECK) {
2810       String dst=generateTemp(fm,fn.getDst());
2811       output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
2812       output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
2813       output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
2814     }
2815   }
2816
2817   protected void generateFlatTagDeclaration(FlatMethod fm, FlatTagDeclaration fn, PrintWriter output) {
2818     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2819       output.println(generateTemp(fm,fn.getDst())+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
2820     } else {
2821       output.println(generateTemp(fm,fn.getDst())+"=allocate_tag("+state.getTagId(fn.getType())+");");
2822     }
2823   }
2824
2825   protected void generateFlatOpNode(FlatMethod fm, FlatOpNode fon, PrintWriter output) {
2826     if (fon.getRight()!=null) {
2827       if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
2828         if (fon.getLeft().getType().isLong())
2829           output.println(generateTemp(fm, fon.getDest())+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft())+")>>"+generateTemp(fm,fon.getRight())+";");
2830         else
2831           output.println(generateTemp(fm, fon.getDest())+" = ((unsigned int)"+generateTemp(fm, fon.getLeft())+")>>"+generateTemp(fm,fon.getRight())+";");
2832
2833       } else
2834         output.println(generateTemp(fm, fon.getDest())+" = "+generateTemp(fm, fon.getLeft())+fon.getOp().toString()+generateTemp(fm,fon.getRight())+";");
2835     } else if (fon.getOp().getOp()==Operation.ASSIGN)
2836       output.println(generateTemp(fm, fon.getDest())+" = "+generateTemp(fm, fon.getLeft())+";");
2837     else if (fon.getOp().getOp()==Operation.UNARYPLUS)
2838       output.println(generateTemp(fm, fon.getDest())+" = "+generateTemp(fm, fon.getLeft())+";");
2839     else if (fon.getOp().getOp()==Operation.UNARYMINUS)
2840       output.println(generateTemp(fm, fon.getDest())+" = -"+generateTemp(fm, fon.getLeft())+";");
2841     else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
2842       output.println(generateTemp(fm, fon.getDest())+" = !"+generateTemp(fm, fon.getLeft())+";");
2843     else if (fon.getOp().getOp()==Operation.COMP)
2844       output.println(generateTemp(fm, fon.getDest())+" = ~"+generateTemp(fm, fon.getLeft())+";");
2845     else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
2846       output.println(generateTemp(fm, fon.getDest())+" = "+generateTemp(fm, fon.getLeft())+"->fses==NULL;");
2847     } else
2848       output.println(generateTemp(fm, fon.getDest())+fon.getOp().toString()+generateTemp(fm, fon.getLeft())+";");
2849   }
2850
2851   protected void generateFlatCastNode(FlatMethod fm, FlatCastNode fcn, PrintWriter output) {
2852     /* TODO: Do type check here */
2853     if (fcn.getType().isArray()) {
2854       output.println(generateTemp(fm,fcn.getDst())+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc())+";");
2855     } else if (fcn.getType().isClass() && fcn.getType().getClassDesc().isEnum()) {
2856       output.println(generateTemp(fm,fcn.getDst())+"=(int)"+generateTemp(fm,fcn.getSrc())+";");
2857     } else if (fcn.getType().isClass())
2858       output.println(generateTemp(fm,fcn.getDst())+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc())+";");
2859     else
2860       output.println(generateTemp(fm,fcn.getDst())+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc())+";");
2861   }
2862
2863   protected void generateFlatLiteralNode(FlatMethod fm, FlatLiteralNode fln, PrintWriter output) {
2864     if (fln.getValue()==null)
2865       output.println(generateTemp(fm, fln.getDst())+"=0;");
2866     else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
2867       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2868         output.println(generateTemp(fm, fln.getDst())+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
2869       } else {
2870         output.println(generateTemp(fm, fln.getDst())+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
2871       }
2872     } else if (fln.getType().isBoolean()) {
2873       if (((Boolean)fln.getValue()).booleanValue())
2874         output.println(generateTemp(fm, fln.getDst())+"=1;");
2875       else
2876         output.println(generateTemp(fm, fln.getDst())+"=0;");
2877     } else if (fln.getType().isChar()) {
2878       String st=FlatLiteralNode.escapeString(fln.getValue().toString());
2879       output.println(generateTemp(fm, fln.getDst())+"='"+st+"';");
2880     } else if (fln.getType().isLong()) {
2881       output.println(generateTemp(fm, fln.getDst())+"="+fln.getValue()+"LL;");
2882     } else
2883       output.println(generateTemp(fm, fln.getDst())+"="+fln.getValue()+";");
2884   }
2885
2886   protected void generateFlatReturnNode(FlatMethod fm, FlatReturnNode frn, PrintWriter output) {
2887     if((fm.getMethod() != null) && (fm.getMethod().isStaticBlock())) {
2888       // a static block, check if it has been executed
2889       output.println("  global_defsprim_p->" + fm.getMethod().getClassDesc().getSafeSymbol()+"static_block_exe_flag = 1;");
2890       output.println("");
2891     }
2892     
2893     if (frn.getReturnTemp()!=null) {
2894       if (frn.getReturnTemp().getType().isPtr())
2895         output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp())+";");
2896       else
2897         output.println("return "+generateTemp(fm, frn.getReturnTemp())+";");
2898     } else {
2899       output.println("return;");
2900     }
2901   }
2902
2903   protected void generateFlatCondBranch(FlatMethod fm, FlatCondBranch fcb, String label, PrintWriter output) {
2904     output.println("if (!"+generateTemp(fm, fcb.getTest())+") goto "+label+";");
2905   }
2906
2907   /** This method generates header information for the method or
2908    * task referenced by the Descriptor des. */
2909   protected void generateHeader(FlatMethod fm, Descriptor des, PrintWriter output) {
2910     generateHeader(fm, des, output, false);
2911   }
2912
2913   protected void generateHeader(FlatMethod fm, Descriptor des, PrintWriter output, boolean addSESErecord) {
2914     /* Print header */
2915     ParamsObject objectparams=(ParamsObject)paramstable.get(des);
2916     MethodDescriptor md=null;
2917     TaskDescriptor task=null;
2918     if (des instanceof MethodDescriptor)
2919       md=(MethodDescriptor) des;
2920     else
2921       task=(TaskDescriptor) des;
2922     String mdstring = md != null ? md.getSafeMethodDescriptor() : null;
2923
2924     ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
2925
2926     if (md!=null&&md.getReturnType()!=null) {
2927       if (md.getReturnType().isClass() && md.getReturnType().getClassDesc().isEnum()) {
2928         output.print("int ");
2929       } else if (md.getReturnType().isClass()||md.getReturnType().isArray())
2930         output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
2931       else
2932         output.print(md.getReturnType().getSafeSymbol()+" ");
2933     } else
2934       //catch the constructor case
2935       output.print("void ");
2936     if (md!=null) {
2937       if(mgcstaticinit && !md.isStaticBlock() && !md.getModifiers().isNative()) {
2938         mdstring += "staticinit";
2939       }
2940       output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"(");
2941     } else
2942       output.print(task.getSafeSymbol()+"(");
2943
2944     boolean printcomma=false;
2945     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2946       if (md!=null) {
2947         output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_params * "+paramsprefix);
2948       } else
2949         output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
2950       printcomma=true;
2951     }
2952
2953     if (md!=null) {
2954       /* Method */
2955       for(int i=0; i<objectparams.numPrimitives(); i++) {
2956         TempDescriptor temp=objectparams.getPrimitive(i);
2957         if (printcomma)
2958           output.print(", ");
2959         printcomma=true;
2960         if(temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
2961           output.print("int " + temp.getSafeSymbol());
2962         } else if (temp.getType().isClass()||temp.getType().isArray())
2963           output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
2964         else
2965           output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
2966       }
2967       output.println(") {");
2968     } else if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
2969       /* Imprecise Task */
2970       output.println("void * parameterarray[]) {");
2971       /* Unpack variables */
2972       for(int i=0; i<objectparams.numPrimitives(); i++) {
2973         TempDescriptor temp=objectparams.getPrimitive(i);
2974         if(temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
2975           output.print("int " + temp.getSafeSymbol() + "=parameterarray["+i+"];");
2976         } else {
2977           output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
2978         }
2979       }
2980       for(int i=0; i<fm.numTags(); i++) {
2981         TempDescriptor temp=fm.getTag(i);
2982         int offset=i+objectparams.numPrimitives();
2983         output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
2984       }
2985
2986       if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
2987         maxtaskparams=objectparams.numPrimitives()+fm.numTags();
2988     } else output.println(") {");
2989   }
2990
2991   public void generateFlatFlagActionNode(FlatMethod fm, FlatFlagActionNode ffan, PrintWriter output) {
2992     output.println("/* FlatFlagActionNode */");
2993
2994
2995     /* Process tag changes */
2996     Relation tagsettable=new Relation();
2997     Relation tagcleartable=new Relation();
2998
2999     Iterator tagsit=ffan.getTempTagPairs();
3000     while (tagsit.hasNext()) {
3001       TempTagPair ttp=(TempTagPair) tagsit.next();
3002       TempDescriptor objtmp=ttp.getTemp();
3003       TagDescriptor tag=ttp.getTag();
3004       TempDescriptor tagtmp=ttp.getTagTemp();
3005       boolean tagstatus=ffan.getTagChange(ttp);
3006       if (tagstatus) {
3007         tagsettable.put(objtmp, tagtmp);
3008       } else {
3009         tagcleartable.put(objtmp, tagtmp);
3010       }
3011     }
3012
3013
3014     Hashtable flagandtable=new Hashtable();
3015     Hashtable flagortable=new Hashtable();
3016
3017     /* Process flag changes */
3018     Iterator flagsit=ffan.getTempFlagPairs();
3019     while(flagsit.hasNext()) {
3020       TempFlagPair tfp=(TempFlagPair)flagsit.next();
3021       TempDescriptor temp=tfp.getTemp();
3022       Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
3023       FlagDescriptor flag=tfp.getFlag();
3024       if (flag==null) {
3025         //Newly allocate objects that don't set any flags case
3026         if (flagortable.containsKey(temp)) {
3027           throw new Error();
3028         }
3029         int mask=0;
3030         flagortable.put(temp,new Integer(mask));
3031       } else {
3032         int flagid=1<<((Integer)flagtable.get(flag)).intValue();
3033         boolean flagstatus=ffan.getFlagChange(tfp);
3034         if (flagstatus) {
3035           int mask=0;
3036           if (flagortable.containsKey(temp)) {
3037             mask=((Integer)flagortable.get(temp)).intValue();
3038           }
3039           mask|=flagid;
3040           flagortable.put(temp,new Integer(mask));
3041         } else {
3042           int mask=0xFFFFFFFF;
3043           if (flagandtable.containsKey(temp)) {
3044             mask=((Integer)flagandtable.get(temp)).intValue();
3045           }
3046           mask&=(0xFFFFFFFF^flagid);
3047           flagandtable.put(temp,new Integer(mask));
3048         }
3049       }
3050     }
3051
3052
3053     HashSet flagtagset=new HashSet();
3054     flagtagset.addAll(flagortable.keySet());
3055     flagtagset.addAll(flagandtable.keySet());
3056     flagtagset.addAll(tagsettable.keySet());
3057     flagtagset.addAll(tagcleartable.keySet());
3058
3059     Iterator ftit=flagtagset.iterator();
3060     while(ftit.hasNext()) {
3061       TempDescriptor temp=(TempDescriptor)ftit.next();
3062
3063
3064       Set tagtmps=tagcleartable.get(temp);
3065       if (tagtmps!=null) {
3066         Iterator tagit=tagtmps.iterator();
3067         while(tagit.hasNext()) {
3068           TempDescriptor tagtmp=(TempDescriptor)tagit.next();
3069           if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
3070             output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp)+", "+generateTemp(fm,tagtmp)+");");
3071           else
3072             output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp)+", "+generateTemp(fm,tagtmp)+");");
3073         }
3074       }
3075
3076       tagtmps=tagsettable.get(temp);
3077       if (tagtmps!=null) {
3078         Iterator tagit=tagtmps.iterator();
3079         while(tagit.hasNext()) {
3080           TempDescriptor tagtmp=(TempDescriptor)tagit.next();
3081           if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
3082             output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp)+", "+generateTemp(fm,tagtmp)+");");
3083           else
3084             output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp)+", "+generateTemp(fm,tagtmp)+");");
3085         }
3086       }
3087
3088       int ormask=0;
3089       int andmask=0xFFFFFFF;
3090
3091       if (flagortable.containsKey(temp))
3092         ormask=((Integer)flagortable.get(temp)).intValue();
3093       if (flagandtable.containsKey(temp))
3094         andmask=((Integer)flagandtable.get(temp)).intValue();
3095       generateFlagOrAnd(ffan, fm, temp, output, ormask, andmask);
3096       generateObjectDistribute(ffan, fm, temp, output);
3097     }
3098   }
3099
3100   protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, TempDescriptor temp,
3101                                    PrintWriter output, int ormask, int andmask) {
3102     if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
3103       output.println("flagorandinit("+generateTemp(fm, temp)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
3104     } else {
3105       output.println("flagorand("+generateTemp(fm, temp)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
3106     }
3107   }
3108
3109   protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, TempDescriptor temp, PrintWriter output) {
3110     output.println("enqueueObject("+generateTemp(fm, temp)+");");
3111   }
3112
3113   void generateOptionalHeader(PrintWriter headers) {
3114
3115     //GENERATE HEADERS
3116     headers.println("#include \"task.h\"\n\n");
3117     headers.println("#ifndef _OPTIONAL_STRUCT_");
3118     headers.println("#define _OPTIONAL_STRUCT_");
3119
3120     //STRUCT PREDICATEMEMBER
3121     headers.println("struct predicatemember{");
3122     headers.println("int type;");
3123     headers.println("int numdnfterms;");
3124     headers.println("int * flags;");
3125     headers.println("int numtags;");
3126     headers.println("int * tags;\n};\n\n");
3127
3128     //STRUCT OPTIONALTASKDESCRIPTOR
3129     headers.println("struct optionaltaskdescriptor{");
3130     headers.println("struct taskdescriptor * task;");
3131     headers.println("int index;");
3132     headers.println("int numenterflags;");
3133     headers.println("int * enterflags;");
3134     headers.println("int numpredicatemembers;");
3135     headers.println("struct predicatemember ** predicatememberarray;");
3136     headers.println("};\n\n");
3137
3138     //STRUCT TASKFAILURE
3139     headers.println("struct taskfailure {");
3140     headers.println("struct taskdescriptor * task;");
3141     headers.println("int index;");
3142     headers.println("int numoptionaltaskdescriptors;");
3143     headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
3144
3145     //STRUCT FSANALYSISWRAPPER
3146     headers.println("struct fsanalysiswrapper{");
3147     headers.println("int  flags;");
3148     headers.println("int numtags;");
3149     headers.println("int * tags;");
3150     headers.println("int numtaskfailures;");
3151     headers.println("struct taskfailure ** taskfailurearray;");
3152     headers.println("int numoptionaltaskdescriptors;");
3153     headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
3154
3155     //STRUCT CLASSANALYSISWRAPPER
3156     headers.println("struct classanalysiswrapper{");
3157     headers.println("int type;");
3158     headers.println("int numotd;");
3159     headers.println("struct optionaltaskdescriptor ** otdarray;");
3160     headers.println("int numfsanalysiswrappers;");
3161     headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
3162
3163     headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
3164
3165     Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
3166     while(taskit.hasNext()) {
3167       TaskDescriptor td=(TaskDescriptor)taskit.next();
3168       headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
3169     }
3170
3171   }
3172
3173   //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
3174   int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
3175     int predicateindex = 0;
3176     //iterate through the classes concerned by the predicate
3177     Set c_vard = predicate.vardescriptors;
3178     Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
3179     int current_slot=0;
3180
3181     for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext(); ) {
3182       VarDescriptor vard = (VarDescriptor)vard_it.next();
3183       TypeDescriptor typed = vard.getType();
3184
3185       //generate for flags
3186       HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
3187       output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
3188       int numberterms=0;
3189       if (fen_hashset!=null) {
3190         for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext(); ) {
3191           FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
3192           if (fen!=null) {
3193             DNFFlag dflag=fen.getDNF();
3194             numberterms+=dflag.size();
3195
3196             Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
3197
3198             for(int j=0; j<dflag.size(); j++) {
3199               if (j!=0)
3200                 output.println(",");
3201               Vector term=dflag.get(j);
3202               int andmask=0;
3203               int checkmask=0;
3204               for(int k=0; k<term.size(); k++) {
3205                 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
3206                 FlagDescriptor fd=dfa.getFlag();
3207                 boolean negated=dfa.getNegated();
3208                 int flagid=1<<((Integer)flags.get(fd)).intValue();
3209                 andmask|=flagid;
3210                 if (!negated)
3211                   checkmask|=flagid;
3212               }
3213               output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
3214             }
3215           }
3216         }
3217       }
3218       output.println("};\n");
3219
3220       //generate for tags
3221       TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
3222       output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
3223       int numtags = 0;
3224       if (tagel!=null) {
3225         for(int j=0; j<tagel.numTags(); j++) {
3226           if (j!=0)
3227             output.println(",");
3228           TempDescriptor tmp=tagel.getTemp(j);
3229           if (!slotnumber.containsKey(tmp)) {
3230             Integer slotint=new Integer(current_slot++);
3231             slotnumber.put(tmp,slotint);
3232           }
3233           int slot=slotnumber.get(tmp).intValue();
3234           output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
3235         }
3236         numtags = tagel.numTags();
3237       }
3238       output.println("};");
3239
3240       //store the result into a predicatemember struct
3241       output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
3242       output.println("/*type*/"+typed.getClassDesc().getId()+",");
3243       output.println("/* number of dnf terms */"+numberterms+",");
3244       output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
3245       output.println("/* number of tag */"+numtags+",");
3246       output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
3247       output.println("};\n");
3248       predicateindex++;
3249     }
3250
3251
3252     //generate an array that stores the entire predicate
3253     output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
3254     for( int j = 0; j<predicateindex; j++) {
3255       if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
3256       else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
3257     }
3258     output.println("};\n");
3259     return predicateindex;
3260   }
3261
3262
3263   void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
3264     generateOptionalHeader(headers);
3265     //GENERATE STRUCTS
3266     output.println("#include \"optionalstruct.h\"\n\n");
3267     output.println("#include \"stdlib.h\"\n");
3268
3269     HashSet processedcd = new HashSet();
3270     int maxotd=0;
3271     Enumeration e = safeexecution.keys();
3272     while (e.hasMoreElements()) {
3273       int numotd=0;
3274       //get the class
3275       ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
3276       Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp);       //will be used several times
3277
3278       //Generate the struct of optionals
3279       Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
3280       numotd = c_otd.size();
3281       if(maxotd<numotd) maxotd = numotd;
3282       if( !c_otd.isEmpty() ) {
3283         for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext(); ) {
3284           OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
3285
3286           //generate the int arrays for the predicate
3287           Predicate predicate = otd.predicate;
3288           int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
3289           TreeSet<Integer> fsset=new TreeSet<Integer>();
3290           //iterate through possible FSes corresponding to
3291           //the state when entering
3292
3293           for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext(); ) {
3294             FlagState fs = (FlagState)fses.next();
3295             int flagid=0;
3296             for(Iterator flags = fs.getFlags(); flags.hasNext(); ) {
3297               FlagDescriptor flagd = (FlagDescriptor)flags.next();
3298               int id=1<<((Integer)flaginfo.get(flagd)).intValue();
3299               flagid|=id;
3300             }
3301             fsset.add(new Integer(flagid));
3302             //tag information not needed because tag
3303             //changes are not tolerated.
3304           }
3305
3306           output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
3307           boolean needcomma=false;
3308           for(Iterator<Integer> it=fsset.iterator(); it.hasNext(); ) {
3309             if(needcomma)
3310               output.print(", ");
3311             output.println(it.next());
3312           }
3313
3314           output.println("};\n");
3315
3316
3317           //generate optionaltaskdescriptor that actually
3318           //includes exit fses, predicate and the task
3319           //concerned
3320           output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
3321           output.println("&task_"+otd.td.getSafeSymbol()+",");
3322           output.println("/*index*/"+otd.getIndex()+",");
3323           output.println("/*number of enter flags*/"+fsset.size()+",");
3324           output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
3325           output.println("/*number of members */"+predicateindex+",");
3326           output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
3327           output.println("};\n");
3328         }
3329       } else
3330         continue;
3331       // if there are no optionals, there is no need to build the rest of the struct
3332
3333       output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
3334       c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
3335       if( !c_otd.isEmpty() ) {
3336         boolean needcomma=false;
3337         for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext(); ) {
3338           OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
3339           if(needcomma)
3340             output.println(",");
3341           needcomma=true;
3342           output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
3343         }
3344       }
3345       output.println("};\n");
3346
3347       //get all the possible flagstates reachable by an object
3348       Hashtable hashtbtemp = safeexecution.get(cdtemp);
3349       int fscounter = 0;
3350       TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
3351       fsts.addAll(hashtbtemp.keySet());
3352       for(Iterator fsit=fsts.iterator(); fsit.hasNext(); ) {
3353         FlagState fs = (FlagState)fsit.next();
3354         fscounter++;
3355
3356         //get the set of OptionalTaskDescriptors corresponding
3357         HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
3358         //iterate through the OptionalTaskDescriptors and
3359         //store the pointers to the optionals struct (see on
3360         //top) into an array
3361
3362         output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
3363         for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext(); ) {
3364           OptionalTaskDescriptor mm = mos.next();
3365           if(!mos.hasNext())
3366             output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
3367           else
3368             output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
3369         }
3370
3371         output.println("};\n");
3372
3373         //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
3374
3375         int flagid=0;
3376         for(Iterator flags = fs.getFlags(); flags.hasNext(); ) {
3377           FlagDescriptor flagd = (FlagDescriptor)flags.next();
3378           int id=1<<((Integer)flaginfo.get(flagd)).intValue();
3379           flagid|=id;
3380         }
3381
3382         //process tag information
3383
3384         int tagcounter = 0;
3385         boolean first = true;
3386         Enumeration tag_enum = fs.getTags();
3387         output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
3388         while(tag_enum.hasMoreElements()) {
3389           tagcounter++;
3390           TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
3391           if(first==true)
3392             first = false;
3393           else
3394             output.println(", ");
3395           output.println("/*tagid*/"+state.getTagId(tagd));
3396         }
3397         output.println("};");
3398
3399         Set<TaskIndex> tiset=sa.getTaskIndex(fs);
3400         for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext(); ) {
3401           TaskIndex ti=itti.next();
3402           if (ti.isRuntime())
3403             continue;
3404
3405           Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
3406
3407           output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
3408           boolean needcomma=false;
3409           for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext(); ) {
3410             OptionalTaskDescriptor otd=otdit.next();
3411             if(needcomma)
3412               output.print(", ");
3413             needcomma=true;
3414             output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
3415           }
3416           output.println("};");
3417
3418           output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
3419           output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
3420           output.print(ti.getIndex()+", ");
3421           output.print(otdset.size()+", ");
3422           output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
3423           output.println("};");
3424         }
3425
3426         tiset=sa.getTaskIndex(fs);
3427         boolean needcomma=false;
3428         int runtimeti=0;
3429         output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
3430         for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext(); ) {
3431           TaskIndex ti=itti.next();
3432           if (ti.isRuntime()) {
3433             runtimeti++;
3434             continue;
3435           }
3436           if (needcomma)
3437             output.print(", ");
3438           needcomma=true;
3439           output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
3440         }
3441         output.println("};\n");
3442
3443         //Store the result in fsanalysiswrapper
3444
3445         output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
3446         output.println("/*flag*/"+flagid+",");
3447         output.println("/* number of tags*/"+tagcounter+",");
3448         output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
3449         output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
3450         output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
3451         output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
3452         output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
3453         output.println("};\n");
3454
3455       }
3456
3457       //Build the array of fsanalysiswrappers
3458       output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
3459       boolean needcomma=false;
3460       for(int i = 0; i<fscounter; i++) {
3461         if (needcomma) output.print(",");
3462         output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
3463         needcomma=true;
3464       }
3465       output.println("};");
3466
3467       //Build the classanalysiswrapper referring to the previous array
3468       output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
3469       output.println("/*type*/"+cdtemp.getId()+",");
3470       output.println("/*numotd*/"+numotd+",");
3471       output.println("otdarray"+cdtemp.getSafeSymbol()+",");
3472       output.println("/* number of fsanalysiswrappers */"+fscounter+",");
3473       output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
3474       processedcd.add(cdtemp);
3475     }
3476
3477     //build an array containing every classes for which code has been build
3478     output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
3479     for(int i=0; i<state.numClasses(); i++) {
3480       ClassDescriptor cn=cdarray[i];
3481       if (i>0)
3482         output.print(", ");
3483       if ((cn != null) && (processedcd.contains(cn)))
3484         output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
3485       else
3486         output.print("NULL");
3487     }
3488     output.println("};");
3489
3490     output.println("#define MAXOTD "+maxotd);
3491     headers.println("#endif");
3492   }
3493
3494   public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
3495     Relation r=new Relation();
3496     for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext(); ) {
3497       OptionalTaskDescriptor otd=otdit.next();
3498       TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
3499       r.put(ti, otd);
3500     }
3501
3502     LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
3503     for(Iterator it=r.keySet().iterator(); it.hasNext(); ) {
3504       Set s=r.get(it.next());
3505       for(Iterator it2=s.iterator(); it2.hasNext(); ) {
3506         OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
3507         l.add(otd);
3508       }
3509     }
3510
3511     return l;
3512   }
3513
3514   // override these methods in a subclass of BuildCode
3515   // to generate code for additional systems
3516   protected void printExtraArrayFields(PrintWriter outclassdefs) {
3517   }
3518   protected void outputTransCode(PrintWriter output) {
3519   }
3520   protected void buildCodeSetup() {
3521   }
3522   protected void generateSizeArrayExtensions(PrintWriter outclassdefs) {
3523   }
3524   protected void additionalIncludesMethodsHeader(PrintWriter outmethodheader) {
3525   }
3526   protected void preCodeGenInitialization() {
3527   }
3528   protected void postCodeGenCleanUp() {
3529   }
3530   protected void additionalCodeGen(PrintWriter outmethodheader,
3531                                    PrintWriter outstructs,
3532                                    PrintWriter outmethod) {
3533   }
3534   protected void additionalCodeAtTopOfMain(PrintWriter outmethod) {
3535   }
3536   protected void additionalCodeAtBottomOfMain(PrintWriter outmethod) {
3537   }
3538   protected void additionalIncludesMethodsImplementation(PrintWriter outmethod) {
3539   }
3540   protected void additionalIncludesStructsHeader(PrintWriter outstructs) {
3541   }
3542   protected void additionalClassObjectFields(PrintWriter outclassdefs) {
3543   }
3544   protected void additionalCodeAtTopMethodsImplementation(PrintWriter outmethod) {
3545   }
3546   protected void additionalCodeAtTopFlatMethodBody(PrintWriter output, FlatMethod fm) {
3547   }
3548   protected void additionalCodePreNode(FlatMethod fm, FlatNode fn, PrintWriter output) {
3549   }
3550   protected void additionalCodePostNode(FlatMethod fm, FlatNode fn, PrintWriter output) {
3551   }
3552   
3553   private void printSourceLineNumber(FlatMethod fm, FlatNode fn, PrintWriter output) {
3554     // we do not print out line number if no one explicitly set the number
3555     if(fn.getNumLine()!=-1){
3556       
3557       int lineNum=fn.getNumLine();
3558
3559       // do not generate the line number if it is same as the previous one
3560       boolean needtoprint;
3561       if(fn.prev.size()==0){
3562         needtoprint=true;
3563       }else{
3564         needtoprint=false;
3565       }
3566
3567       for(int i=0;i<fn.prev.size();i++){
3568         int prevLineNum=((FlatNode)fn.prev.get(i)).getNumLine();
3569         if(prevLineNum!=lineNum){
3570           needtoprint=true;
3571           break;
3572         }
3573       }
3574       if(needtoprint){
3575         output.println("// "+fm.getMethod().getClassDesc().getSourceFileName()+":"+fn.getNumLine());
3576       }
3577     }
3578   }
3579   
3580 }
3581
3582
3583
3584
3585
3586