fdf15bc246652fc9876ecec3858638ce8c695b11
[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           globaldefscount++;
1585         }
1586       } else if (fd.isVolatile()) {
1587         //volatile field
1588         classdefout.println("  volatile "+fd.getType().getSafeSymbol()+ " "+fd.getSafeSymbol()+";");
1589       } else
1590         classdefout.println("  "+fd.getType().getSafeSymbol()+" "+fd.getSafeSymbol()+";");
1591     }
1592   }
1593
1594
1595   /* Map flags to integers consistently between inherited
1596    * classes. */
1597
1598   protected void mapFlags(ClassDescriptor cn) {
1599     ClassDescriptor sp=cn.getSuperDesc();
1600     if (sp!=null)
1601       mapFlags(sp);
1602     int max=0;
1603     if (!flagorder.containsKey(cn)) {
1604       Hashtable flags=new Hashtable();
1605       flagorder.put(cn,flags);
1606       if (sp!=null) {
1607         Hashtable superflags=(Hashtable)flagorder.get(sp);
1608         Iterator superflagit=superflags.keySet().iterator();
1609         while(superflagit.hasNext()) {
1610           FlagDescriptor fd=(FlagDescriptor)superflagit.next();
1611           Integer number=(Integer)superflags.get(fd);
1612           flags.put(fd, number);
1613           if ((number.intValue()+1)>max)
1614             max=number.intValue()+1;
1615         }
1616       }
1617
1618       Iterator flagit=cn.getFlags();
1619       while(flagit.hasNext()) {
1620         FlagDescriptor fd=(FlagDescriptor)flagit.next();
1621         if (sp==null||!sp.getFlagTable().contains(fd.getSymbol()))
1622           flags.put(fd, new Integer(max++));
1623       }
1624     }
1625   }
1626
1627
1628   /** This function outputs (1) structures that parameters are
1629    * passed in (when PRECISE GC is enabled) and (2) function
1630    * prototypes for the methods */
1631
1632   protected void generateCallStructs(ClassDescriptor cn, PrintWriter classdefout, PrintWriter output, PrintWriter headersout, PrintWriter globaldefout, PrintWriter globaldefprimout) {
1633     /* Output class structure */
1634     classdefout.println("struct "+cn.getSafeSymbol()+" {");
1635     classdefout.println("  int type;");
1636
1637
1638     additionalClassObjectFields(classdefout);
1639
1640
1641     if (state.EVENTMONITOR) {
1642       classdefout.println("  int objuid;");
1643     }
1644     if (state.THREAD) {
1645       classdefout.println("  pthread_t tid;");
1646       classdefout.println("  void * lockentry;");
1647       classdefout.println("  int lockcount;");
1648     }
1649     if (state.MGC) {
1650       classdefout.println("  int mutex;");
1651       classdefout.println("  volatile int notifycount;");
1652       classdefout.println("  volatile int objlock;");
1653       if(state.MULTICOREGC) {
1654         classdefout.println("  int marked;");
1655       }
1656     }
1657     if (state.TASK) {
1658       classdefout.println("  int flag;");
1659       if((!state.MULTICORE) || (cn.getSymbol().equals("TagDescriptor"))) {
1660         classdefout.println("  void * flagptr;");
1661       } else if (state.MULTICORE) {
1662         classdefout.println("  int version;");
1663         classdefout.println("  int * lock;"); // lock entry for this obj
1664         classdefout.println("  int mutex;");
1665         classdefout.println("  int lockcount;");
1666         if(state.MULTICOREGC) {
1667           classdefout.println("  int marked;");
1668         }
1669       }
1670       if (state.OPTIONAL) {
1671         classdefout.println("  int numfses;");
1672         classdefout.println("  int * fses;");
1673       }
1674     }
1675     printClassStruct(cn, classdefout, globaldefout, globaldefprimout);
1676     printedfieldstbl.clear(); // = new Hashtable<String, ClassDescriptor>();
1677     classdefout.println("};\n");
1678     generateCallStructsMethods(cn, output, headersout);
1679   }
1680
1681
1682   protected void generateCallStructsMethods(ClassDescriptor cn, PrintWriter output, PrintWriter headersout) {
1683     for(Iterator methodit=cn.getMethods(); methodit.hasNext(); ) {
1684       MethodDescriptor md=(MethodDescriptor)methodit.next();
1685       boolean foundmatch = false;
1686       if(this.state.genAllMethods) {
1687         foundmatch = true;
1688       } else {
1689         Set vec_md = this.state.getMethod2gen().getSet(md.getSymbol());
1690         for(Iterator matchit=vec_md.iterator(); matchit.hasNext();) {
1691           MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
1692           if (md.matches(matchmd)) {
1693             foundmatch=true;
1694             break;
1695           }
1696         }
1697       }
1698       if(foundmatch) {
1699         generateMethod(cn, md, headersout, output);
1700       }
1701     }
1702   }
1703
1704   protected void generateMethodParam(ClassDescriptor cn, MethodDescriptor md, PrintWriter output) {
1705     /* Output parameter structure */
1706     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1707       if(md.isInvokedByStatic() && !md.isStaticBlock() && !md.getModifiers().isNative()) {
1708         // generate the staticinit version
1709         String mdstring = md.getSafeMethodDescriptor() + "staticinit";
1710         
1711         ParamsObject objectparams=(ParamsObject) paramstable.get(md);
1712         output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_params {");
1713         output.println("  int size;");
1714         output.println("  void * next;");
1715         for(int i=0; i<objectparams.numPointers(); i++) {
1716           TempDescriptor temp=objectparams.getPointer(i);
1717           if(temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
1718             output.println("  int " + temp.getSafeSymbol() + ";");
1719           } else {
1720             output.println("  struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1721           }
1722         }
1723         output.println("};\n");
1724       }
1725       
1726       ParamsObject objectparams=(ParamsObject) paramstable.get(md);
1727       output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1728       output.println("  int size;");
1729       output.println("  void * next;");
1730       for(int i=0; i<objectparams.numPointers(); i++) {
1731         TempDescriptor temp=objectparams.getPointer(i);
1732         if(temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
1733           output.println("  int " + temp.getSafeSymbol() + ";");
1734         } else {
1735           output.println("  struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1736         }
1737       }
1738       output.println("};\n");
1739     }
1740   }
1741
1742   protected void generateMethod(ClassDescriptor cn, MethodDescriptor md, PrintWriter headersout, PrintWriter output) {
1743     FlatMethod fm=state.getMethodFlat(md);
1744     generateTempStructs(fm);
1745
1746     ParamsObject objectparams=(ParamsObject) paramstable.get(md);
1747     TempObject objecttemps=(TempObject) tempstable.get(md);
1748     
1749     boolean printcomma = false;
1750     
1751     generateMethodParam(cn, md, output);
1752     
1753     if(md.isInvokedByStatic() && !md.isStaticBlock() && !md.getModifiers().isNative()) {
1754       // generate the staticinit version
1755       String mdstring = md.getSafeMethodDescriptor() + "staticinit";
1756
1757       /* Output temp structure */
1758       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1759         output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_locals {");
1760         output.println("  int size;");
1761         output.println("  void * next;");
1762         for(int i=0; i<objecttemps.numPointers(); i++) {
1763           TempDescriptor temp=objecttemps.getPointer(i);
1764           if (!temp.getType().isArray() && temp.getType().isNull())
1765             output.println("  void * "+temp.getSafeSymbol()+";");
1766           else
1767             output.println("  struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1768         }
1769         output.println("};\n");
1770       }
1771       
1772       headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+" 1");
1773       /* First the return type */
1774       if (md.getReturnType()!=null) {
1775         if(md.getReturnType().isClass() && md.getReturnType().getClassDesc().isEnum()) {
1776           headersout.println("  int ");
1777         } else if (md.getReturnType().isClass()||md.getReturnType().isArray())
1778           headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1779         else
1780           headersout.print(md.getReturnType().getSafeSymbol()+" ");
1781       } else
1782         //catch the constructor case
1783         headersout.print("void ");
1784
1785       /* Next the method name */
1786       headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"(");
1787       printcomma=false;
1788       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1789         headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_params * "+paramsprefix);
1790         printcomma=true;
1791       }
1792
1793       /*  Output parameter list*/
1794       for(int i=0; i<objectparams.numPrimitives(); i++) {
1795         TempDescriptor temp=objectparams.getPrimitive(i);
1796         if (printcomma)
1797           headersout.print(", ");
1798         printcomma=true;
1799         if(temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
1800           headersout.print("int " + temp.getSafeSymbol());
1801         } else if (temp.getType().isClass()||temp.getType().isArray())
1802           headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1803         else
1804           headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1805       }
1806       headersout.println(");\n");
1807     }
1808
1809     /* Output temp structure */
1810     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1811       output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1812       output.println("  int size;");
1813       output.println("  void * next;");
1814       for(int i=0; i<objecttemps.numPointers(); i++) {
1815         TempDescriptor temp=objecttemps.getPointer(i);
1816         if (!temp.getType().isArray() && temp.getType().isNull())
1817           output.println("  void * "+temp.getSafeSymbol()+";");
1818         else
1819           output.println("  struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1820       }
1821       output.println("};\n");
1822     }
1823
1824     /********* Output method declaration ***********/
1825     headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1826     /* First the return type */
1827     if (md.getReturnType()!=null) {
1828       if(md.getReturnType().isClass() && md.getReturnType().getClassDesc().isEnum()) {
1829         headersout.println("  int ");
1830       } else if (md.getReturnType().isClass()||md.getReturnType().isArray())
1831         headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1832       else
1833         headersout.print(md.getReturnType().getSafeSymbol()+" ");
1834     } else
1835       //catch the constructor case
1836       headersout.print("void ");
1837
1838     /* Next the method name */
1839     headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1840     printcomma=false;
1841     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1842       headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1843       printcomma=true;
1844     }
1845
1846     /*  Output parameter list*/
1847     for(int i=0; i<objectparams.numPrimitives(); i++) {
1848       TempDescriptor temp=objectparams.getPrimitive(i);
1849       if (printcomma)
1850         headersout.print(", ");
1851       printcomma=true;
1852       if(temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
1853         headersout.print("int " + temp.getSafeSymbol());
1854       } else if (temp.getType().isClass()||temp.getType().isArray())
1855         headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1856       else
1857         headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1858     }
1859     headersout.println(");\n");
1860   }
1861
1862
1863   /** This function outputs (1) structures that parameters are
1864    * passed in (when PRECISE GC is enabled) and (2) function
1865    * prototypes for the tasks */
1866
1867   protected void generateTaskStructs(PrintWriter output, PrintWriter headersout) {
1868     /* Cycle through tasks */
1869     Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
1870
1871     while(taskit.hasNext()) {
1872       /* Classify parameters */
1873       TaskDescriptor task=(TaskDescriptor)taskit.next();
1874       FlatMethod fm=state.getMethodFlat(task);
1875       generateTempStructs(fm);
1876
1877       ParamsObject objectparams=(ParamsObject) paramstable.get(task);
1878       TempObject objecttemps=(TempObject) tempstable.get(task);
1879
1880       /* Output parameter structure */
1881       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1882         output.println("struct "+task.getSafeSymbol()+"_params {");
1883         output.println("  int size;");
1884         output.println("  void * next;");
1885         for(int i=0; i<objectparams.numPointers(); i++) {
1886           TempDescriptor temp=objectparams.getPointer(i);
1887           output.println("  struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1888         }
1889
1890         output.println("};\n");
1891         if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
1892           maxtaskparams=objectparams.numPointers()+fm.numTags();
1893         }
1894       }
1895
1896       /* Output temp structure */
1897       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1898         output.println("struct "+task.getSafeSymbol()+"_locals {");
1899         output.println("  int size;");
1900         output.println("  void * next;");
1901         for(int i=0; i<objecttemps.numPointers(); i++) {
1902           TempDescriptor temp=objecttemps.getPointer(i);
1903           if (!temp.getType().isArray() && temp.getType().isNull())
1904             output.println("  void * "+temp.getSafeSymbol()+";");
1905           else if(temp.getType().isTag())
1906             output.println("  struct "+
1907                            (new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1908           else
1909             output.println("  struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1910         }
1911         output.println("};\n");
1912       }
1913
1914       /* Output task declaration */
1915       headersout.print("void " + task.getSafeSymbol()+"(");
1916
1917       boolean printcomma=false;
1918       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1919         headersout.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
1920       } else
1921         headersout.print("void * parameterarray[]");
1922       headersout.println(");\n");
1923     }
1924   }
1925
1926   protected void generateFlatMethod(FlatMethod fm, PrintWriter output) {
1927     if (State.PRINTFLAT)
1928       System.out.println(fm.printMethod());
1929     MethodDescriptor md=fm.getMethod();
1930     TaskDescriptor task=fm.getTask();
1931     ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
1932     ParamsObject objectparams=(ParamsObject)paramstable.get(md!=null ? md : task);
1933     
1934     if((md != null) && md.isInvokedByStatic() && !md.isStaticBlock() && !md.getModifiers().isNative()) {
1935       // generate a special static init version
1936       mgcstaticinit = true;
1937       String mdstring = md.getSafeMethodDescriptor() + "staticinit";
1938       
1939       generateHeader(fm, md!=null ? md : task,output);
1940       TempObject objecttemp=(TempObject) tempstable.get(md!=null ? md : task);
1941       
1942       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1943         output.print("   struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_locals "+localsprefix+"={");
1944         output.print(objecttemp.numPointers()+",");
1945         output.print(paramsprefix);
1946         for(int j=0; j<objecttemp.numPointers(); j++)
1947           output.print(", NULL");
1948         output.println("};");
1949       }
1950
1951       for(int i=0; i<objecttemp.numPrimitives(); i++) {
1952         TempDescriptor td=objecttemp.getPrimitive(i);
1953         TypeDescriptor type=td.getType();
1954         if (type.isNull() && !type.isArray())
1955           output.println("   void * "+td.getSafeSymbol()+";");
1956         else if (type.isClass() && type.getClassDesc().isEnum()) {
1957           output.println("   int " + td.getSafeSymbol() + ";");
1958         } else if (type.isClass()||type.isArray())
1959           output.println("   struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1960         else
1961           output.println("   "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1962       }
1963
1964       additionalCodeAtTopFlatMethodBody(output, fm);
1965
1966       /* Check to see if we need to do a GC if this is a
1967        * multi-threaded program...*/
1968
1969       if (((state.OOOJAVA||state.THREAD)&&GENERATEPRECISEGC)
1970           || this.state.MULTICOREGC) {
1971         //Don't bother if we aren't in recursive methods...The loops case will catch it
1972         if (callgraph.getAllMethods(md).contains(md)) {
1973           if (this.state.MULTICOREGC) {
1974             output.println("if(gcflag) gc("+localsprefixaddr+");");
1975           } else {
1976             output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
1977           }
1978         }
1979       }
1980       
1981       generateCode(fm.getNext(0), fm, null, output);
1982
1983       output.println("}\n\n");
1984       
1985       mgcstaticinit = false;
1986     }
1987     
1988     generateHeader(fm, md!=null ? md : task,output);
1989     TempObject objecttemp=(TempObject) tempstable.get(md!=null ? md : task);
1990
1991     if((md != null) && (md.isStaticBlock())) {
1992       mgcstaticinit = true;
1993     }
1994
1995     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1996       if (md!=null)
1997         output.print("   struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1998       else
1999         output.print("   struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={");
2000       output.print(objecttemp.numPointers()+",");
2001       output.print(paramsprefix);
2002       for(int j=0; j<objecttemp.numPointers(); j++)
2003         output.print(", NULL");
2004       output.println("};");
2005     }
2006
2007     for(int i=0; i<objecttemp.numPrimitives(); i++) {
2008       TempDescriptor td=objecttemp.getPrimitive(i);
2009       TypeDescriptor type=td.getType();
2010       if (type.isNull() && !type.isArray())
2011         output.println("   void * "+td.getSafeSymbol()+";");
2012       else if (type.isClass() && type.getClassDesc().isEnum()) {
2013         output.println("   int " + td.getSafeSymbol() + ";");
2014       } else if (type.isClass()||type.isArray())
2015         output.println("   struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
2016       else
2017         output.println("   "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
2018     }
2019
2020     additionalCodeAtTopFlatMethodBody(output, fm);
2021
2022     /* Check to see if we need to do a GC if this is a
2023      * multi-threaded program...*/
2024
2025     if (((state.OOOJAVA||state.THREAD)&&GENERATEPRECISEGC)
2026         || this.state.MULTICOREGC) {
2027       //Don't bother if we aren't in recursive methods...The loops case will catch it
2028       if (callgraph.getAllMethods(md).contains(md)) {
2029         if (this.state.MULTICOREGC) {
2030           output.println("if(gcflag) gc("+localsprefixaddr+");");
2031         } else {
2032           output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2033         }
2034       }
2035     }
2036
2037     if(fm.getMethod().isStaticBlock()) {
2038       // a static block, check if it has been executed
2039       output.println("  if(global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag != 0) {");
2040       output.println("    return;");
2041       output.println("  }");
2042       output.println("");
2043     }
2044
2045     generateCode(fm.getNext(0), fm, null, output);
2046
2047     output.println("}\n\n");
2048     
2049     mgcstaticinit = false;
2050   }
2051
2052   protected void generateCode(FlatNode first,
2053                               FlatMethod fm,
2054                               Set<FlatNode> stopset,
2055                               PrintWriter output) {
2056
2057     /* Assign labels to FlatNode's if necessary.*/
2058
2059     Hashtable<FlatNode, Integer> nodetolabel;
2060
2061     nodetolabel=assignLabels(first, stopset);
2062
2063     Set<FlatNode> storeset=null;
2064     HashSet<FlatNode> genset=null;
2065     HashSet<FlatNode> refset=null;
2066     Set<FlatNode> unionset=null;
2067
2068     /* Do the actual code generation */
2069     FlatNode current_node=null;
2070     HashSet tovisit=new HashSet();
2071     HashSet visited=new HashSet();
2072     tovisit.add(first);
2073     while(current_node!=null||!tovisit.isEmpty()) {
2074       if (current_node==null) {
2075         current_node=(FlatNode)tovisit.iterator().next();
2076         tovisit.remove(current_node);
2077       } else if (tovisit.contains(current_node)) {
2078         tovisit.remove(current_node);
2079       }
2080       visited.add(current_node);
2081       if (nodetolabel.containsKey(current_node)) {
2082         output.println("L"+nodetolabel.get(current_node)+":");
2083       }
2084       if (state.INSTRUCTIONFAILURE) {
2085         if (state.THREAD) {
2086           output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
2087         } else
2088           output.println("if ((--instructioncount)==0) injectinstructionfailure();");
2089       }
2090       if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
2091         output.print("   ");
2092         generateFlatNode(fm, current_node, output);
2093
2094         if (state.OOOJAVA && stopset!=null) {
2095           assert first.getPrev(0) instanceof FlatSESEEnterNode;
2096           assert current_node       instanceof FlatSESEExitNode;
2097           FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev(0);
2098           FlatSESEExitNode fsxn = (FlatSESEExitNode)  current_node;
2099           assert fsen.getFlatExit().equals(fsxn);
2100           assert fsxn.getFlatEnter().equals(fsen);
2101         }
2102         if (current_node.kind()!=FKind.FlatReturnNode) {
2103           if((fm.getMethod() != null) && (fm.getMethod().isStaticBlock())) {
2104             // a static block, check if it has been executed
2105             output.println("  global_defsprim_p->" + fm.getMethod().getClassDesc().getSafeSymbol()+"static_block_exe_flag = 1;");
2106             output.println("");
2107           }
2108           output.println("   return;");
2109         }
2110         current_node=null;
2111       } else if(current_node.numNext()==1) {
2112         FlatNode nextnode;
2113         if (state.OOOJAVA &&
2114             current_node.kind()==FKind.FlatSESEEnterNode) {
2115           FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
2116           generateFlatNode(fm, current_node, output);
2117           nextnode=fsen.getFlatExit().getNext(0);
2118         } else {
2119           output.print("   ");
2120           generateFlatNode(fm, current_node, output);
2121           nextnode=current_node.getNext(0);
2122         }
2123         if (visited.contains(nextnode)) {
2124           output.println("goto L"+nodetolabel.get(nextnode)+";");
2125           current_node=null;
2126         } else
2127           current_node=nextnode;
2128       } else if (current_node.numNext()==2) {
2129         /* Branch */
2130         output.print("   ");
2131         generateFlatCondBranch(fm, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2132         if (!visited.contains(current_node.getNext(1)))
2133           tovisit.add(current_node.getNext(1));
2134         if (visited.contains(current_node.getNext(0))) {
2135           output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2136           current_node=null;
2137         } else
2138           current_node=current_node.getNext(0);
2139       } else throw new Error();
2140     }
2141   }
2142
2143   protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
2144     HashSet tovisit=new HashSet();
2145     HashSet visited=new HashSet();
2146     int labelindex=0;
2147     Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2148     tovisit.add(first);
2149
2150     /*Assign labels first.  A node needs a label if the previous
2151      * node has two exits or this node is a join point. */
2152
2153     while(!tovisit.isEmpty()) {
2154       FlatNode fn=(FlatNode)tovisit.iterator().next();
2155       tovisit.remove(fn);
2156       visited.add(fn);
2157
2158
2159       if(lastset!=null&&lastset.contains(fn)) {
2160         // if last is not null and matches, don't go
2161         // any further for assigning labels
2162         continue;
2163       }
2164
2165       for(int i=0; i<fn.numNext(); i++) {
2166         FlatNode nn=fn.getNext(i);
2167
2168         if(i>0) {
2169           //1) Edge >1 of node
2170           nodetolabel.put(nn,new Integer(labelindex++));
2171         }
2172         if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2173           tovisit.add(nn);
2174         } else {
2175           //2) Join point
2176           nodetolabel.put(nn,new Integer(labelindex++));
2177         }
2178       }
2179     }
2180     return nodetolabel;
2181   }
2182
2183   /** Generate text string that corresponds to the TempDescriptor td. */
2184   protected String generateTemp(FlatMethod fm, TempDescriptor td) {
2185     MethodDescriptor md=fm.getMethod();
2186     TaskDescriptor task=fm.getTask();
2187     TempObject objecttemps=(TempObject) tempstable.get(md!=null ? md : task);
2188
2189     if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
2190       return td.getSafeSymbol();
2191     }
2192
2193     if (objecttemps.isLocalPtr(td)) {
2194       return localsprefixderef+td.getSafeSymbol();
2195     }
2196
2197     if (objecttemps.isParamPtr(td)) {
2198       return paramsprefix+"->"+td.getSafeSymbol();
2199     }
2200
2201     throw new Error();
2202   }
2203
2204
2205
2206   protected void generateFlatNode(FlatMethod fm, FlatNode fn, PrintWriter output) {
2207     if(state.LINENUM) printSourceLineNumber(fm,fn,output);
2208     additionalCodePreNode(fm, fn, output);
2209
2210     switch(fn.kind()) {
2211     case FKind.FlatAtomicEnterNode:
2212       generateFlatAtomicEnterNode(fm, (FlatAtomicEnterNode) fn, output);
2213       break;
2214
2215     case FKind.FlatAtomicExitNode:
2216       generateFlatAtomicExitNode(fm, (FlatAtomicExitNode) fn, output);
2217       break;
2218
2219     case FKind.FlatInstanceOfNode:
2220       generateFlatInstanceOfNode(fm, (FlatInstanceOfNode)fn, output);
2221       break;
2222
2223     case FKind.FlatSESEEnterNode:
2224       generateFlatSESEEnterNode(fm, (FlatSESEEnterNode)fn, output);
2225       break;
2226
2227     case FKind.FlatSESEExitNode:
2228       generateFlatSESEExitNode(fm, (FlatSESEExitNode)fn, output);
2229       break;
2230
2231     case FKind.FlatWriteDynamicVarNode:
2232       generateFlatWriteDynamicVarNode(fm, (FlatWriteDynamicVarNode)fn, output);
2233       break;
2234
2235     case FKind.FlatGlobalConvNode:
2236       generateFlatGlobalConvNode(fm, (FlatGlobalConvNode) fn, output);
2237       break;
2238
2239     case FKind.FlatTagDeclaration:
2240       generateFlatTagDeclaration(fm, (FlatTagDeclaration) fn,output);
2241       break;
2242
2243     case FKind.FlatCall:
2244       generateFlatCall(fm, (FlatCall) fn,output);
2245       break;
2246
2247     case FKind.FlatFieldNode:
2248       generateFlatFieldNode(fm, (FlatFieldNode) fn,output);
2249       break;
2250
2251     case FKind.FlatElementNode:
2252       generateFlatElementNode(fm, (FlatElementNode) fn,output);
2253       break;
2254
2255     case FKind.FlatSetElementNode:
2256       generateFlatSetElementNode(fm, (FlatSetElementNode) fn,output);
2257       break;
2258
2259     case FKind.FlatSetFieldNode:
2260       generateFlatSetFieldNode(fm, (FlatSetFieldNode) fn,output);
2261       break;
2262
2263     case FKind.FlatNew:
2264       generateFlatNew(fm, (FlatNew) fn,output);
2265       break;
2266
2267     case FKind.FlatOpNode:
2268       generateFlatOpNode(fm, (FlatOpNode) fn,output);
2269       break;
2270
2271     case FKind.FlatCastNode:
2272       generateFlatCastNode(fm, (FlatCastNode) fn,output);
2273       break;
2274
2275     case FKind.FlatLiteralNode:
2276       generateFlatLiteralNode(fm, (FlatLiteralNode) fn,output);
2277       break;
2278
2279     case FKind.FlatReturnNode:
2280       generateFlatReturnNode(fm, (FlatReturnNode) fn,output);
2281       break;
2282
2283     case FKind.FlatNop:
2284       output.println("/* nop */");
2285       break;
2286
2287     case FKind.FlatGenReachNode:
2288       // this node is just for generating a reach graph
2289       // in disjointness analysis at a particular program point
2290       break;
2291
2292     case FKind.FlatExit:
2293       output.println("/* exit */");
2294       break;
2295
2296     case FKind.FlatBackEdge:
2297       generateFlatBackEdge(fm, (FlatBackEdge)fn, output);
2298       break;
2299
2300     case FKind.FlatCheckNode:
2301       generateFlatCheckNode(fm, (FlatCheckNode) fn, output);
2302       break;
2303
2304     case FKind.FlatFlagActionNode:
2305       generateFlatFlagActionNode(fm, (FlatFlagActionNode) fn, output);
2306       break;
2307
2308     case FKind.FlatPrefetchNode:
2309       generateFlatPrefetchNode(fm, (FlatPrefetchNode) fn, output);
2310       break;
2311
2312     case FKind.FlatOffsetNode:
2313       generateFlatOffsetNode(fm, (FlatOffsetNode)fn, output);
2314       break;
2315
2316     default:
2317       throw new Error();
2318     }
2319
2320     additionalCodePostNode(fm, fn, output);
2321   }
2322
2323   public void generateFlatBackEdge(FlatMethod fm, FlatBackEdge fn, PrintWriter output) {
2324     if (((state.OOOJAVA||state.THREAD)&&GENERATEPRECISEGC)
2325         || (this.state.MULTICOREGC)) {
2326       if(this.state.MULTICOREGC) {
2327         output.println("if (gcflag) gc("+localsprefixaddr+");");
2328       } else {
2329         output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2330       }
2331     } else
2332       output.println("/* nop */");
2333   }
2334
2335   public void generateFlatOffsetNode(FlatMethod fm, FlatOffsetNode fofn, PrintWriter output) {
2336     output.println("/* FlatOffsetNode */");
2337     FieldDescriptor fd=fofn.getField();
2338     if(!fd.isStatic()) {
2339     output.println(generateTemp(fm, fofn.getDst())+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+
2340                    fd.getSafeSymbol()+");");
2341     }
2342     output.println("/* offset */");
2343   }
2344
2345   public void generateFlatPrefetchNode(FlatMethod fm, FlatPrefetchNode fpn, PrintWriter output) {
2346   }
2347
2348   public void generateFlatGlobalConvNode(FlatMethod fm, FlatGlobalConvNode fgcn, PrintWriter output) {
2349   }
2350
2351   public void generateFlatInstanceOfNode(FlatMethod fm,  FlatInstanceOfNode fion, PrintWriter output) {
2352     int type;
2353     int otype;
2354     if (fion.getType().isArray()) {
2355       type=state.getArrayNumber(fion.getType())+state.numClasses();
2356     } else if (fion.getType().getClassDesc().isInterface()) {
2357       type=fion.getType().getClassDesc().getId()+state.numClasses()+state.numArrays();
2358     } else {
2359       type=fion.getType().getClassDesc().getId();
2360     }
2361     if (fion.getSrc().getType().isArray()) {
2362       otype=state.getArrayNumber(fion.getSrc().getType())+state.numClasses();
2363     } else if (fion.getSrc().getType().getClassDesc().isInterface()) {
2364       otype=fion.getSrc().getType().getClassDesc().getId()+state.numClasses()+state.numArrays();
2365     } else {
2366       otype=fion.getSrc().getType().getClassDesc().getId();
2367     }
2368
2369     if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
2370       output.println(generateTemp(fm, fion.getDst())+"=(" + generateTemp(fm,fion.getSrc()) + "!= NULL);");
2371     else {
2372       output.println(generateTemp(fm, fion.getDst())+"=instanceof("+generateTemp(fm,fion.getSrc())+","+type+");");
2373     }
2374   }
2375
2376   public void generateFlatAtomicEnterNode(FlatMethod fm, FlatAtomicEnterNode faen, PrintWriter output) {
2377   }
2378
2379   public void generateFlatAtomicExitNode(FlatMethod fm,  FlatAtomicExitNode faen, PrintWriter output) {
2380   }
2381
2382   public void generateFlatSESEEnterNode(FlatMethod fm,
2383                                         FlatSESEEnterNode fsen,
2384                                         PrintWriter output) {
2385     // if OOOJAVA flag is off, okay that SESE nodes are in IR graph,
2386     // just skip over them and code generates exactly the same
2387   }
2388
2389   public void generateFlatSESEExitNode(FlatMethod fm,
2390                                        FlatSESEExitNode fsexn,
2391                                        PrintWriter output) {
2392     // if OOOJAVA flag is off, okay that SESE nodes are in IR graph,
2393     // just skip over them and code generates exactly the same
2394   }
2395
2396   public void generateFlatWriteDynamicVarNode(FlatMethod fm,
2397                                               FlatWriteDynamicVarNode fwdvn,
2398                                               PrintWriter output) {
2399   }
2400
2401
2402   protected void generateFlatCheckNode(FlatMethod fm,  FlatCheckNode fcn, PrintWriter output) {
2403     if (state.CONSCHECK) {
2404       String specname=fcn.getSpec();
2405       String varname="repairstate___";
2406       output.println("{");
2407       output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
2408
2409       TempDescriptor[] temps=fcn.getTemps();
2410       String[] vars=fcn.getVars();
2411       for(int i=0; i<temps.length; i++) {
2412         output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i])+";");
2413       }
2414
2415       output.println("if (doanalysis"+specname+"("+varname+")) {");
2416       output.println("free"+specname+"_state("+varname+");");
2417       output.println("} else {");
2418       output.println("/* Bad invariant */");
2419       output.println("free"+specname+"_state("+varname+");");
2420       output.println("abort_task();");
2421       output.println("}");
2422       output.println("}");
2423     }
2424   }
2425
2426   protected void generateFlatCall(FlatMethod fm, FlatCall fc, PrintWriter output) {
2427     MethodDescriptor md=fc.getMethod();
2428     ParamsObject objectparams=(ParamsObject)paramstable.get(md);
2429     ClassDescriptor cn=md.getClassDesc();
2430     String mdstring = md.getSafeMethodDescriptor();
2431     if(mgcstaticinit && !md.isStaticBlock() && !md.getModifiers().isNative()) {
2432       mdstring += "staticinit";
2433     }
2434
2435     // if the called method is a static block or a static method or a constructor
2436     // need to check if it can be invoked inside some static block
2437     if((md.isStatic() || md.isStaticBlock() || md.isConstructor()) &&
2438        ((fm.getMethod() != null) && ((fm.getMethod().isStaticBlock()) || (fm.getMethod().isInvokedByStatic())))) {
2439       if(!md.isInvokedByStatic()) {
2440         System.err.println("Error: a method that is invoked inside a static block is not tagged!");
2441       }
2442       // is a static block or is invoked in some static block
2443       ClassDescriptor cd = fm.getMethod().getClassDesc();
2444       if(cd == cn) {
2445         // the same class, do nothing
2446       } else if(mgcstaticinit) {
2447         // generate static init check code if it has not done static init in main()
2448         if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) {
2449           // need to check if the class' static fields have been initialized and/or
2450           // its static blocks have been executed
2451           output.println("if(global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag == 0) {");
2452           if(cn.getNumStaticBlocks() != 0) {
2453             MethodDescriptor t_md = (MethodDescriptor)cn.getMethodTable().get("staticblocks");
2454         if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2455           output.print("       struct "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"_params __parameterlist__={");
2456           output.println("0, NULL};");
2457           output.println("     "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"(& __parameterlist__);");
2458         } else {
2459           output.println("  "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();");
2460         }
2461           } else {
2462             output.println("  global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag = 1;");
2463           }
2464           output.println("}");
2465         }
2466       }
2467     }
2468     if((md.getSymbol().equals("MonitorEnter") || md.getSymbol().equals("MonitorExit")) && fc.getThis().getSymbol().equals("classobj")) {
2469       output.println("{");
2470       // call MonitorEnter/MonitorExit on a class obj
2471       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2472         output.print("       struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
2473         output.println("1," + localsprefixaddr + ", global_defs_p->"+ fc.getThis().getType().getClassDesc().getSafeSymbol() +"classobj};");
2474         output.println("     "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
2475       } else {
2476       output.println("       " + cn.getSafeSymbol()+md.getSafeSymbol()+"_"
2477                      + md.getSafeMethodDescriptor() + "((struct ___Object___*)(global_defs_p->"
2478                      + fc.getThis().getType().getClassDesc().getSafeSymbol() +"classobj));");
2479       }
2480       output.println("}");
2481       return;
2482     }
2483     
2484     output.println("{");
2485     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2486       output.print("       struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_params __parameterlist__={");
2487       output.print(objectparams.numPointers());
2488       output.print(", "+localsprefixaddr);
2489       if (md.getThis()!=null) {
2490         output.print(", ");
2491         output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis()));
2492       }
2493       if (fc.getThis()!=null&&md.getThis()==null) {
2494         System.out.println("WARNING!!!!!!!!!!!!");
2495         System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
2496       }
2497
2498
2499       for(int i=0; i<fc.numArgs(); i++) {
2500         Descriptor var=md.getParameter(i);
2501         TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
2502         if (objectparams.isParamPtr(paramtemp)) {
2503           TempDescriptor targ=fc.getArg(i);
2504           output.print(", ");
2505           TypeDescriptor td=md.getParamType(i);
2506           if (td.isTag())
2507             output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()  +" *)"+generateTemp(fm, targ));
2508           else
2509             output.print("(struct "+md.getParamType(i).getSafeSymbol()  +" *)"+generateTemp(fm, targ));
2510         }
2511       }
2512       output.println("};");
2513     }
2514     output.print("       ");
2515
2516
2517     if (fc.getReturnTemp()!=null)
2518       output.print(generateTemp(fm,fc.getReturnTemp())+"=");
2519
2520     /* Do we need to do virtual dispatch? */
2521     if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
2522       //no
2523       output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring);
2524     } else {
2525       //yes
2526       output.print("((");
2527       if (md.getReturnType().isClass() && md.getReturnType().getClassDesc().isEnum()) {
2528         output.print("int ");
2529       } else if (md.getReturnType().isClass()||md.getReturnType().isArray())
2530         output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
2531       else
2532         output.print(md.getReturnType().getSafeSymbol()+" ");
2533       output.print("(*)(");
2534
2535       boolean printcomma=false;
2536       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2537         output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_params * ");
2538         printcomma=true;
2539       }
2540
2541       for(int i=0; i<objectparams.numPrimitives(); i++) {
2542         TempDescriptor temp=objectparams.getPrimitive(i);
2543         if (printcomma)
2544           output.print(", ");
2545         printcomma=true;
2546         if (temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
2547           output.print("int ");
2548         } else if (temp.getType().isClass()||temp.getType().isArray())
2549           output.print("struct " + temp.getType().getSafeSymbol()+" * ");
2550         else
2551           output.print(temp.getType().getSafeSymbol());
2552       }
2553
2554
2555       output.print("))virtualtable["+generateTemp(fm,fc.getThis())+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
2556     }
2557
2558     output.print("(");
2559     boolean needcomma=false;
2560     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2561       output.print("&__parameterlist__");
2562       needcomma=true;
2563     }
2564
2565     if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
2566       if (fc.getThis()!=null) {
2567         TypeDescriptor ptd=null;
2568         if(md.getThis() != null) {
2569           ptd = md.getThis().getType();
2570         } else {
2571           ptd = fc.getThis().getType();
2572         }
2573         if (needcomma)
2574           output.print(",");
2575         if(ptd.isClass() && ptd.getClassDesc().isEnum()) {
2576           // do nothing
2577         } else if (ptd.isClass()&&!ptd.isArray())
2578           output.print("(struct "+ptd.getSafeSymbol()+" *) ");
2579         output.print(generateTemp(fm,fc.getThis()));
2580         needcomma=true;
2581       }
2582     }
2583
2584     for(int i=0; i<fc.numArgs(); i++) {
2585       Descriptor var=md.getParameter(i);
2586       TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
2587       if (objectparams.isParamPrim(paramtemp)) {
2588         TempDescriptor targ=fc.getArg(i);
2589         if (needcomma)
2590           output.print(", ");
2591
2592         TypeDescriptor ptd=md.getParamType(i);
2593         if (ptd.isClass() && ptd.getClassDesc().isEnum()) {
2594           // do nothing
2595         } else if (ptd.isClass()&&!ptd.isArray())
2596           output.print("(struct "+ptd.getSafeSymbol()+" *) ");
2597         output.print(generateTemp(fm, targ));
2598         needcomma=true;
2599       }
2600     }
2601     output.println(");");
2602     output.println("   }");
2603   }
2604
2605   protected boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
2606     if(thiscd.isInterface()) {
2607       // for interfaces, always need virtual dispatch
2608       return false;
2609     } else {
2610     Set subclasses=typeutil.getSubClasses(thiscd);
2611     if (subclasses==null)
2612       return true;
2613     for(Iterator classit=subclasses.iterator(); classit.hasNext(); ) {
2614       ClassDescriptor cd=(ClassDescriptor)classit.next();
2615       Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol());
2616       for(Iterator matchit=possiblematches.iterator(); matchit.hasNext(); ) {
2617         MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
2618         if (md.matches(matchmd))
2619           return false;
2620       }
2621     }
2622     }
2623     return true;
2624   }
2625
2626   protected void generateFlatFieldNode(FlatMethod fm, FlatFieldNode ffn, PrintWriter output) {
2627     
2628     if(ffn.getField().isStatic()) {
2629       // static field
2630       if((fm.getMethod().isStaticBlock()) || (fm.getMethod().isInvokedByStatic())) {
2631         // is a static block or is invoked in some static block
2632         ClassDescriptor cd = fm.getMethod().getClassDesc();
2633         ClassDescriptor cn = ffn.getSrc().getType().getClassDesc();
2634         if(cd == cn) {
2635           // the same class, do nothing
2636         } else if(mgcstaticinit) {
2637       // generate the static init check code if has not done the static init in main()
2638           if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) {
2639             // need to check if the class' static fields have been initialized and/or
2640             // its static blocks have been executed
2641             output.println("if(global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag == 0) {");
2642             if(cn.getNumStaticBlocks() != 0) {
2643               MethodDescriptor t_md = (MethodDescriptor)cn.getMethodTable().get("staticblocks");
2644           if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2645             output.print("       struct "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"_params __parameterlist__={");
2646             output.println("0, NULL};");
2647             output.println("     "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"(& __parameterlist__);");
2648           } else {
2649             output.println("  "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();");
2650           }
2651             } else {
2652               output.println("  global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag = 1;");
2653             }
2654             output.println("}");
2655           }
2656         }
2657       }
2658       // redirect to the global_defs_p structure
2659       if((ffn.getField().isStatic()) || (ffn.getSrc().getType().isClassNameRef())) {
2660         // reference to the static field with Class name
2661         if (ffn.getField().getType().isPtr())
2662           output.println(generateTemp(fm, ffn.getDst())+"=global_defs_p->"+ffn.getField().getSafeSymbol()+";");
2663         else
2664           output.println(generateTemp(fm, ffn.getDst())+"=global_defsprim_p->"+ffn.getField().getSafeSymbol()+";");
2665       } else {
2666         output.println(generateTemp(fm, ffn.getDst())+"=*"+ generateTemp(fm,ffn.getSrc())+"->"+ ffn.getField().getSafeSymbol()+";");
2667       }
2668     } else if (ffn.getField().isEnum()) {
2669       // an Enum value, directly replace the field access as int
2670       output.println(generateTemp(fm, ffn.getDst()) + "=" + ffn.getField().enumValue() + ";");
2671     } else {
2672       output.println(generateTemp(fm, ffn.getDst())+"="+ generateTemp(fm,ffn.getSrc())+"->"+ ffn.getField().getSafeSymbol()+";");
2673     }
2674   }
2675
2676
2677   protected void generateFlatSetFieldNode(FlatMethod fm, FlatSetFieldNode fsfn, PrintWriter output) {
2678     if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
2679       throw new Error("Can't set array length");
2680     if (state.FASTCHECK) {
2681       String dst=generateTemp(fm, fsfn.getDst());
2682       output.println("if(!"+dst+"->"+localcopystr+") {");
2683       /* Link object into list */
2684       if (GENERATEPRECISEGC || this.state.MULTICOREGC)
2685         output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
2686       else
2687         output.println("COPY_OBJ("+dst+");");
2688       output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
2689       output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
2690       output.println("}");
2691     }
2692
2693     if(fsfn.getField().isStatic()) {
2694       // static field
2695       if((fm.getMethod().isStaticBlock()) || (fm.getMethod().isInvokedByStatic())) {
2696         // is a static block or is invoked in some static block
2697         ClassDescriptor cd = fm.getMethod().getClassDesc();
2698         ClassDescriptor cn = fsfn.getDst().getType().getClassDesc();
2699         if(cd == cn) {
2700           // the same class, do nothing
2701         } else if(mgcstaticinit){
2702       // generate static init check code if has not done the static init in main()
2703           if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) {
2704             // need to check if the class' static fields have been initialized and/or
2705             // its static blocks have been executed
2706             output.println("if(global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag == 0) {");
2707             if(cn.getNumStaticBlocks() != 0) {
2708               MethodDescriptor t_md = (MethodDescriptor)cn.getMethodTable().get("staticblocks");
2709           if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2710             output.print("       struct "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"_params __parameterlist__={");
2711             output.println("0, NULL};");
2712             output.println("     "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"(& __parameterlist__);");
2713           } else {
2714             output.println("  "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();");
2715           }
2716             } else {
2717               output.println("  global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag = 1;");
2718             }
2719             output.println("}");
2720           }
2721         }
2722       }
2723       // redirect to the global_defs_p structure
2724       if((fsfn.getDst().getType().isClassNameRef()) || (fsfn.getField().isStatic())) {
2725         // reference to the static field with Class name
2726         if (fsfn.getField().getType().isPtr())
2727           output.println("global_defs_p->" +
2728                          fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc())+";");
2729         else
2730           output.println("global_defsprim_p->" +
2731                          fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc())+";");
2732       } else {
2733         output.println("*"+generateTemp(fm, fsfn.getDst())+"->"+
2734                        fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc())+";");
2735       }
2736     } else {
2737       output.println(generateTemp(fm, fsfn.getDst())+"->"+
2738                      fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc())+";");
2739     }
2740   }
2741
2742
2743   protected void generateFlatElementNode(FlatMethod fm, FlatElementNode fen, PrintWriter output) {
2744     TypeDescriptor elementtype=fen.getSrc().getType().dereference();
2745     String type="";
2746
2747     if (elementtype.isClass() && elementtype.getClassDesc().isEnum()) {
2748       type="int ";
2749     } else if (elementtype.isArray()||elementtype.isClass())
2750       type="void *";
2751     else
2752       type=elementtype.getSafeSymbol()+" ";
2753
2754     if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
2755       output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fen.getIndex())+") >= "+generateTemp(fm,fen.getSrc()) + "->___length___))");
2756       output.println("failedboundschk();");
2757     }
2758     output.println(generateTemp(fm, fen.getDst())+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc())+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex())+"];");
2759   }
2760
2761   protected void generateFlatSetElementNode(FlatMethod fm, FlatSetElementNode fsen, PrintWriter output) {
2762     //TODO: need dynamic check to make sure this assignment is actually legal
2763     //Because Object[] could actually be something more specific...ie. Integer[]
2764
2765     TypeDescriptor elementtype=fsen.getDst().getType().dereference();
2766     String type="";
2767
2768     if (elementtype.isClass() && elementtype.getClassDesc().isEnum()) {
2769       type="int ";
2770     } else if (elementtype.isArray()||elementtype.isClass() || (elementtype.isNull()))
2771       type="void *";
2772     else
2773       type=elementtype.getSafeSymbol()+" ";
2774
2775     if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
2776       output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fsen.getIndex())+") >= "+generateTemp(fm,fsen.getDst()) + "->___length___))");
2777       output.println("failedboundschk();");
2778     }
2779     if (state.FASTCHECK) {
2780       String dst=generateTemp(fm, fsen.getDst());
2781       output.println("if(!"+dst+"->"+localcopystr+") {");
2782       /* Link object into list */
2783       if (GENERATEPRECISEGC || this.state.MULTICOREGC)
2784         output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
2785       else
2786         output.println("COPY_OBJ("+dst+");");
2787       output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
2788       output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
2789       output.println("}");
2790     }
2791     output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst())+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex())+"]="+generateTemp(fm,fsen.getSrc())+";");
2792   }
2793
2794
2795   protected void generateFlatNew(FlatMethod fm, FlatNew fn, PrintWriter output) {
2796     if (fn.getType().isArray()) {
2797       int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
2798       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2799         output.println(generateTemp(fm,fn.getDst())+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize())+");");
2800       } else {
2801         output.println(generateTemp(fm,fn.getDst())+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize())+");");
2802       }
2803     } else {
2804       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2805         output.println(generateTemp(fm,fn.getDst())+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
2806       } else {
2807         output.println(generateTemp(fm,fn.getDst())+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
2808       }
2809     }
2810     if (state.FASTCHECK) {
2811       String dst=generateTemp(fm,fn.getDst());
2812       output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
2813       output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
2814       output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
2815     }
2816   }
2817
2818   protected void generateFlatTagDeclaration(FlatMethod fm, FlatTagDeclaration fn, PrintWriter output) {
2819     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2820       output.println(generateTemp(fm,fn.getDst())+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
2821     } else {
2822       output.println(generateTemp(fm,fn.getDst())+"=allocate_tag("+state.getTagId(fn.getType())+");");
2823     }
2824   }
2825
2826   protected void generateFlatOpNode(FlatMethod fm, FlatOpNode fon, PrintWriter output) {
2827     if (fon.getRight()!=null) {
2828       if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
2829         if (fon.getLeft().getType().isLong())
2830           output.println(generateTemp(fm, fon.getDest())+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft())+")>>"+generateTemp(fm,fon.getRight())+";");
2831         else
2832           output.println(generateTemp(fm, fon.getDest())+" = ((unsigned int)"+generateTemp(fm, fon.getLeft())+")>>"+generateTemp(fm,fon.getRight())+";");
2833
2834       } else
2835         output.println(generateTemp(fm, fon.getDest())+" = "+generateTemp(fm, fon.getLeft())+fon.getOp().toString()+generateTemp(fm,fon.getRight())+";");
2836     } else if (fon.getOp().getOp()==Operation.ASSIGN)
2837       output.println(generateTemp(fm, fon.getDest())+" = "+generateTemp(fm, fon.getLeft())+";");
2838     else if (fon.getOp().getOp()==Operation.UNARYPLUS)
2839       output.println(generateTemp(fm, fon.getDest())+" = "+generateTemp(fm, fon.getLeft())+";");
2840     else if (fon.getOp().getOp()==Operation.UNARYMINUS)
2841       output.println(generateTemp(fm, fon.getDest())+" = -"+generateTemp(fm, fon.getLeft())+";");
2842     else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
2843       output.println(generateTemp(fm, fon.getDest())+" = !"+generateTemp(fm, fon.getLeft())+";");
2844     else if (fon.getOp().getOp()==Operation.COMP)
2845       output.println(generateTemp(fm, fon.getDest())+" = ~"+generateTemp(fm, fon.getLeft())+";");
2846     else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
2847       output.println(generateTemp(fm, fon.getDest())+" = "+generateTemp(fm, fon.getLeft())+"->fses==NULL;");
2848     } else
2849       output.println(generateTemp(fm, fon.getDest())+fon.getOp().toString()+generateTemp(fm, fon.getLeft())+";");
2850   }
2851
2852   protected void generateFlatCastNode(FlatMethod fm, FlatCastNode fcn, PrintWriter output) {
2853     /* TODO: Do type check here */
2854     if (fcn.getType().isArray()) {
2855       output.println(generateTemp(fm,fcn.getDst())+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc())+";");
2856     } else if (fcn.getType().isClass() && fcn.getType().getClassDesc().isEnum()) {
2857       output.println(generateTemp(fm,fcn.getDst())+"=(int)"+generateTemp(fm,fcn.getSrc())+";");
2858     } else if (fcn.getType().isClass())
2859       output.println(generateTemp(fm,fcn.getDst())+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc())+";");
2860     else
2861       output.println(generateTemp(fm,fcn.getDst())+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc())+";");
2862   }
2863
2864   protected void generateFlatLiteralNode(FlatMethod fm, FlatLiteralNode fln, PrintWriter output) {
2865     if (fln.getValue()==null)
2866       output.println(generateTemp(fm, fln.getDst())+"=0;");
2867     else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
2868       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2869         output.println(generateTemp(fm, fln.getDst())+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
2870       } else {
2871         output.println(generateTemp(fm, fln.getDst())+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
2872       }
2873     } else if (fln.getType().isBoolean()) {
2874       if (((Boolean)fln.getValue()).booleanValue())
2875         output.println(generateTemp(fm, fln.getDst())+"=1;");
2876       else
2877         output.println(generateTemp(fm, fln.getDst())+"=0;");
2878     } else if (fln.getType().isChar()) {
2879       String st=FlatLiteralNode.escapeString(fln.getValue().toString());
2880       output.println(generateTemp(fm, fln.getDst())+"='"+st+"';");
2881     } else if (fln.getType().isLong()) {
2882       output.println(generateTemp(fm, fln.getDst())+"="+fln.getValue()+"LL;");
2883     } else
2884       output.println(generateTemp(fm, fln.getDst())+"="+fln.getValue()+";");
2885   }
2886
2887   protected void generateFlatReturnNode(FlatMethod fm, FlatReturnNode frn, PrintWriter output) {
2888     if((fm.getMethod() != null) && (fm.getMethod().isStaticBlock())) {
2889       // a static block, check if it has been executed
2890       output.println("  global_defsprim_p->" + fm.getMethod().getClassDesc().getSafeSymbol()+"static_block_exe_flag = 1;");
2891       output.println("");
2892     }
2893     
2894     if (frn.getReturnTemp()!=null) {
2895       if (frn.getReturnTemp().getType().isPtr())
2896         output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp())+";");
2897       else
2898         output.println("return "+generateTemp(fm, frn.getReturnTemp())+";");
2899     } else {
2900       output.println("return;");
2901     }
2902   }
2903
2904   protected void generateFlatCondBranch(FlatMethod fm, FlatCondBranch fcb, String label, PrintWriter output) {
2905     output.println("if (!"+generateTemp(fm, fcb.getTest())+") goto "+label+";");
2906   }
2907
2908   /** This method generates header information for the method or
2909    * task referenced by the Descriptor des. */
2910   protected void generateHeader(FlatMethod fm, Descriptor des, PrintWriter output) {
2911     generateHeader(fm, des, output, false);
2912   }
2913
2914   protected void generateHeader(FlatMethod fm, Descriptor des, PrintWriter output, boolean addSESErecord) {
2915     /* Print header */
2916     ParamsObject objectparams=(ParamsObject)paramstable.get(des);
2917     MethodDescriptor md=null;
2918     TaskDescriptor task=null;
2919     if (des instanceof MethodDescriptor)
2920       md=(MethodDescriptor) des;
2921     else
2922       task=(TaskDescriptor) des;
2923     String mdstring = md != null ? md.getSafeMethodDescriptor() : null;
2924
2925     ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
2926
2927     if (md!=null&&md.getReturnType()!=null) {
2928       if (md.getReturnType().isClass() && md.getReturnType().getClassDesc().isEnum()) {
2929         output.print("int ");
2930       } else if (md.getReturnType().isClass()||md.getReturnType().isArray())
2931         output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
2932       else
2933         output.print(md.getReturnType().getSafeSymbol()+" ");
2934     } else
2935       //catch the constructor case
2936       output.print("void ");
2937     if (md!=null) {
2938       if(mgcstaticinit && !md.isStaticBlock() && !md.getModifiers().isNative()) {
2939         mdstring += "staticinit";
2940       }
2941       output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"(");
2942     } else
2943       output.print(task.getSafeSymbol()+"(");
2944
2945     boolean printcomma=false;
2946     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2947       if (md!=null) {
2948         output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_params * "+paramsprefix);
2949       } else
2950         output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
2951       printcomma=true;
2952     }
2953
2954     if (md!=null) {
2955       /* Method */
2956       for(int i=0; i<objectparams.numPrimitives(); i++) {
2957         TempDescriptor temp=objectparams.getPrimitive(i);
2958         if (printcomma)
2959           output.print(", ");
2960         printcomma=true;
2961         if(temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
2962           output.print("int " + temp.getSafeSymbol());
2963         } else if (temp.getType().isClass()||temp.getType().isArray())
2964           output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
2965         else
2966           output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
2967       }
2968       output.println(") {");
2969     } else if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
2970       /* Imprecise Task */
2971       output.println("void * parameterarray[]) {");
2972       /* Unpack variables */
2973       for(int i=0; i<objectparams.numPrimitives(); i++) {
2974         TempDescriptor temp=objectparams.getPrimitive(i);
2975         if(temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
2976           output.print("int " + temp.getSafeSymbol() + "=parameterarray["+i+"];");
2977         } else {
2978           output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
2979         }
2980       }
2981       for(int i=0; i<fm.numTags(); i++) {
2982         TempDescriptor temp=fm.getTag(i);
2983         int offset=i+objectparams.numPrimitives();
2984         output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
2985       }
2986
2987       if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
2988         maxtaskparams=objectparams.numPrimitives()+fm.numTags();
2989     } else output.println(") {");
2990   }
2991
2992   public void generateFlatFlagActionNode(FlatMethod fm, FlatFlagActionNode ffan, PrintWriter output) {
2993     output.println("/* FlatFlagActionNode */");
2994
2995
2996     /* Process tag changes */
2997     Relation tagsettable=new Relation();
2998     Relation tagcleartable=new Relation();
2999
3000     Iterator tagsit=ffan.getTempTagPairs();
3001     while (tagsit.hasNext()) {
3002       TempTagPair ttp=(TempTagPair) tagsit.next();
3003       TempDescriptor objtmp=ttp.getTemp();
3004       TagDescriptor tag=ttp.getTag();
3005       TempDescriptor tagtmp=ttp.getTagTemp();
3006       boolean tagstatus=ffan.getTagChange(ttp);
3007       if (tagstatus) {
3008         tagsettable.put(objtmp, tagtmp);
3009       } else {
3010         tagcleartable.put(objtmp, tagtmp);
3011       }
3012     }
3013
3014
3015     Hashtable flagandtable=new Hashtable();
3016     Hashtable flagortable=new Hashtable();
3017
3018     /* Process flag changes */
3019     Iterator flagsit=ffan.getTempFlagPairs();
3020     while(flagsit.hasNext()) {
3021       TempFlagPair tfp=(TempFlagPair)flagsit.next();
3022       TempDescriptor temp=tfp.getTemp();
3023       Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
3024       FlagDescriptor flag=tfp.getFlag();
3025       if (flag==null) {
3026         //Newly allocate objects that don't set any flags case
3027         if (flagortable.containsKey(temp)) {
3028           throw new Error();
3029         }
3030         int mask=0;
3031         flagortable.put(temp,new Integer(mask));
3032       } else {
3033         int flagid=1<<((Integer)flagtable.get(flag)).intValue();
3034         boolean flagstatus=ffan.getFlagChange(tfp);
3035         if (flagstatus) {
3036           int mask=0;
3037           if (flagortable.containsKey(temp)) {
3038             mask=((Integer)flagortable.get(temp)).intValue();
3039           }
3040           mask|=flagid;
3041           flagortable.put(temp,new Integer(mask));
3042         } else {
3043           int mask=0xFFFFFFFF;
3044           if (flagandtable.containsKey(temp)) {
3045             mask=((Integer)flagandtable.get(temp)).intValue();
3046           }
3047           mask&=(0xFFFFFFFF^flagid);
3048           flagandtable.put(temp,new Integer(mask));
3049         }
3050       }
3051     }
3052
3053
3054     HashSet flagtagset=new HashSet();
3055     flagtagset.addAll(flagortable.keySet());
3056     flagtagset.addAll(flagandtable.keySet());
3057     flagtagset.addAll(tagsettable.keySet());
3058     flagtagset.addAll(tagcleartable.keySet());
3059
3060     Iterator ftit=flagtagset.iterator();
3061     while(ftit.hasNext()) {
3062       TempDescriptor temp=(TempDescriptor)ftit.next();
3063
3064
3065       Set tagtmps=tagcleartable.get(temp);
3066       if (tagtmps!=null) {
3067         Iterator tagit=tagtmps.iterator();
3068         while(tagit.hasNext()) {
3069           TempDescriptor tagtmp=(TempDescriptor)tagit.next();
3070           if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
3071             output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp)+", "+generateTemp(fm,tagtmp)+");");
3072           else
3073             output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp)+", "+generateTemp(fm,tagtmp)+");");
3074         }
3075       }
3076
3077       tagtmps=tagsettable.get(temp);
3078       if (tagtmps!=null) {
3079         Iterator tagit=tagtmps.iterator();
3080         while(tagit.hasNext()) {
3081           TempDescriptor tagtmp=(TempDescriptor)tagit.next();
3082           if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
3083             output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp)+", "+generateTemp(fm,tagtmp)+");");
3084           else
3085             output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp)+", "+generateTemp(fm,tagtmp)+");");
3086         }
3087       }
3088
3089       int ormask=0;
3090       int andmask=0xFFFFFFF;
3091
3092       if (flagortable.containsKey(temp))
3093         ormask=((Integer)flagortable.get(temp)).intValue();
3094       if (flagandtable.containsKey(temp))
3095         andmask=((Integer)flagandtable.get(temp)).intValue();
3096       generateFlagOrAnd(ffan, fm, temp, output, ormask, andmask);
3097       generateObjectDistribute(ffan, fm, temp, output);
3098     }
3099   }
3100
3101   protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, TempDescriptor temp,
3102                                    PrintWriter output, int ormask, int andmask) {
3103     if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
3104       output.println("flagorandinit("+generateTemp(fm, temp)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
3105     } else {
3106       output.println("flagorand("+generateTemp(fm, temp)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
3107     }
3108   }
3109
3110   protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, TempDescriptor temp, PrintWriter output) {
3111     output.println("enqueueObject("+generateTemp(fm, temp)+");");
3112   }
3113
3114   void generateOptionalHeader(PrintWriter headers) {
3115
3116     //GENERATE HEADERS
3117     headers.println("#include \"task.h\"\n\n");
3118     headers.println("#ifndef _OPTIONAL_STRUCT_");
3119     headers.println("#define _OPTIONAL_STRUCT_");
3120
3121     //STRUCT PREDICATEMEMBER
3122     headers.println("struct predicatemember{");
3123     headers.println("int type;");
3124     headers.println("int numdnfterms;");
3125     headers.println("int * flags;");
3126     headers.println("int numtags;");
3127     headers.println("int * tags;\n};\n\n");
3128
3129     //STRUCT OPTIONALTASKDESCRIPTOR
3130     headers.println("struct optionaltaskdescriptor{");
3131     headers.println("struct taskdescriptor * task;");
3132     headers.println("int index;");
3133     headers.println("int numenterflags;");
3134     headers.println("int * enterflags;");
3135     headers.println("int numpredicatemembers;");
3136     headers.println("struct predicatemember ** predicatememberarray;");
3137     headers.println("};\n\n");
3138
3139     //STRUCT TASKFAILURE
3140     headers.println("struct taskfailure {");
3141     headers.println("struct taskdescriptor * task;");
3142     headers.println("int index;");
3143     headers.println("int numoptionaltaskdescriptors;");
3144     headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
3145
3146     //STRUCT FSANALYSISWRAPPER
3147     headers.println("struct fsanalysiswrapper{");
3148     headers.println("int  flags;");
3149     headers.println("int numtags;");
3150     headers.println("int * tags;");
3151     headers.println("int numtaskfailures;");
3152     headers.println("struct taskfailure ** taskfailurearray;");
3153     headers.println("int numoptionaltaskdescriptors;");
3154     headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
3155
3156     //STRUCT CLASSANALYSISWRAPPER
3157     headers.println("struct classanalysiswrapper{");
3158     headers.println("int type;");
3159     headers.println("int numotd;");
3160     headers.println("struct optionaltaskdescriptor ** otdarray;");
3161     headers.println("int numfsanalysiswrappers;");
3162     headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
3163
3164     headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
3165
3166     Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
3167     while(taskit.hasNext()) {
3168       TaskDescriptor td=(TaskDescriptor)taskit.next();
3169       headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
3170     }
3171
3172   }
3173
3174   //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
3175   int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
3176     int predicateindex = 0;
3177     //iterate through the classes concerned by the predicate
3178     Set c_vard = predicate.vardescriptors;
3179     Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
3180     int current_slot=0;
3181
3182     for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext(); ) {
3183       VarDescriptor vard = (VarDescriptor)vard_it.next();
3184       TypeDescriptor typed = vard.getType();
3185
3186       //generate for flags
3187       HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
3188       output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
3189       int numberterms=0;
3190       if (fen_hashset!=null) {
3191         for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext(); ) {
3192           FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
3193           if (fen!=null) {
3194             DNFFlag dflag=fen.getDNF();
3195             numberterms+=dflag.size();
3196
3197             Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
3198
3199             for(int j=0; j<dflag.size(); j++) {
3200               if (j!=0)
3201                 output.println(",");
3202               Vector term=dflag.get(j);
3203               int andmask=0;
3204               int checkmask=0;
3205               for(int k=0; k<term.size(); k++) {
3206                 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
3207                 FlagDescriptor fd=dfa.getFlag();
3208                 boolean negated=dfa.getNegated();
3209                 int flagid=1<<((Integer)flags.get(fd)).intValue();
3210                 andmask|=flagid;
3211                 if (!negated)
3212                   checkmask|=flagid;
3213               }
3214               output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
3215             }
3216           }
3217         }
3218       }
3219       output.println("};\n");
3220
3221       //generate for tags
3222       TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
3223       output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
3224       int numtags = 0;
3225       if (tagel!=null) {
3226         for(int j=0; j<tagel.numTags(); j++) {
3227           if (j!=0)
3228             output.println(",");
3229           TempDescriptor tmp=tagel.getTemp(j);
3230           if (!slotnumber.containsKey(tmp)) {
3231             Integer slotint=new Integer(current_slot++);
3232             slotnumber.put(tmp,slotint);
3233           }
3234           int slot=slotnumber.get(tmp).intValue();
3235           output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
3236         }
3237         numtags = tagel.numTags();
3238       }
3239       output.println("};");
3240
3241       //store the result into a predicatemember struct
3242       output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
3243       output.println("/*type*/"+typed.getClassDesc().getId()+",");
3244       output.println("/* number of dnf terms */"+numberterms+",");
3245       output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
3246       output.println("/* number of tag */"+numtags+",");
3247       output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
3248       output.println("};\n");
3249       predicateindex++;
3250     }
3251
3252
3253     //generate an array that stores the entire predicate
3254     output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
3255     for( int j = 0; j<predicateindex; j++) {
3256       if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
3257       else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
3258     }
3259     output.println("};\n");
3260     return predicateindex;
3261   }
3262
3263
3264   void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
3265     generateOptionalHeader(headers);
3266     //GENERATE STRUCTS
3267     output.println("#include \"optionalstruct.h\"\n\n");
3268     output.println("#include \"stdlib.h\"\n");
3269
3270     HashSet processedcd = new HashSet();
3271     int maxotd=0;
3272     Enumeration e = safeexecution.keys();
3273     while (e.hasMoreElements()) {
3274       int numotd=0;
3275       //get the class
3276       ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
3277       Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp);       //will be used several times
3278
3279       //Generate the struct of optionals
3280       Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
3281       numotd = c_otd.size();
3282       if(maxotd<numotd) maxotd = numotd;
3283       if( !c_otd.isEmpty() ) {
3284         for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext(); ) {
3285           OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
3286
3287           //generate the int arrays for the predicate
3288           Predicate predicate = otd.predicate;
3289           int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
3290           TreeSet<Integer> fsset=new TreeSet<Integer>();
3291           //iterate through possible FSes corresponding to
3292           //the state when entering
3293
3294           for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext(); ) {
3295             FlagState fs = (FlagState)fses.next();
3296             int flagid=0;
3297             for(Iterator flags = fs.getFlags(); flags.hasNext(); ) {
3298               FlagDescriptor flagd = (FlagDescriptor)flags.next();
3299               int id=1<<((Integer)flaginfo.get(flagd)).intValue();
3300               flagid|=id;
3301             }
3302             fsset.add(new Integer(flagid));
3303             //tag information not needed because tag
3304             //changes are not tolerated.
3305           }
3306
3307           output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
3308           boolean needcomma=false;
3309           for(Iterator<Integer> it=fsset.iterator(); it.hasNext(); ) {
3310             if(needcomma)
3311               output.print(", ");
3312             output.println(it.next());
3313           }
3314
3315           output.println("};\n");
3316
3317
3318           //generate optionaltaskdescriptor that actually
3319           //includes exit fses, predicate and the task
3320           //concerned
3321           output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
3322           output.println("&task_"+otd.td.getSafeSymbol()+",");
3323           output.println("/*index*/"+otd.getIndex()+",");
3324           output.println("/*number of enter flags*/"+fsset.size()+",");
3325           output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
3326           output.println("/*number of members */"+predicateindex+",");
3327           output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
3328           output.println("};\n");
3329         }
3330       } else
3331         continue;
3332       // if there are no optionals, there is no need to build the rest of the struct
3333
3334       output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
3335       c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
3336       if( !c_otd.isEmpty() ) {
3337         boolean needcomma=false;
3338         for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext(); ) {
3339           OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
3340           if(needcomma)
3341             output.println(",");
3342           needcomma=true;
3343           output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
3344         }
3345       }
3346       output.println("};\n");
3347
3348       //get all the possible flagstates reachable by an object
3349       Hashtable hashtbtemp = safeexecution.get(cdtemp);
3350       int fscounter = 0;
3351       TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
3352       fsts.addAll(hashtbtemp.keySet());
3353       for(Iterator fsit=fsts.iterator(); fsit.hasNext(); ) {
3354         FlagState fs = (FlagState)fsit.next();
3355         fscounter++;
3356
3357         //get the set of OptionalTaskDescriptors corresponding
3358         HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
3359         //iterate through the OptionalTaskDescriptors and
3360         //store the pointers to the optionals struct (see on
3361         //top) into an array
3362
3363         output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
3364         for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext(); ) {
3365           OptionalTaskDescriptor mm = mos.next();
3366           if(!mos.hasNext())
3367             output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
3368           else
3369             output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
3370         }
3371
3372         output.println("};\n");
3373
3374         //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
3375
3376         int flagid=0;
3377         for(Iterator flags = fs.getFlags(); flags.hasNext(); ) {
3378           FlagDescriptor flagd = (FlagDescriptor)flags.next();
3379           int id=1<<((Integer)flaginfo.get(flagd)).intValue();
3380           flagid|=id;
3381         }
3382
3383         //process tag information
3384
3385         int tagcounter = 0;
3386         boolean first = true;
3387         Enumeration tag_enum = fs.getTags();
3388         output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
3389         while(tag_enum.hasMoreElements()) {
3390           tagcounter++;
3391           TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
3392           if(first==true)
3393             first = false;
3394           else
3395             output.println(", ");
3396           output.println("/*tagid*/"+state.getTagId(tagd));
3397         }
3398         output.println("};");
3399
3400         Set<TaskIndex> tiset=sa.getTaskIndex(fs);
3401         for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext(); ) {
3402           TaskIndex ti=itti.next();
3403           if (ti.isRuntime())
3404             continue;
3405
3406           Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
3407
3408           output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
3409           boolean needcomma=false;
3410           for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext(); ) {
3411             OptionalTaskDescriptor otd=otdit.next();
3412             if(needcomma)
3413               output.print(", ");
3414             needcomma=true;
3415             output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
3416           }
3417           output.println("};");
3418
3419           output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
3420           output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
3421           output.print(ti.getIndex()+", ");
3422           output.print(otdset.size()+", ");
3423           output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
3424           output.println("};");
3425         }
3426
3427         tiset=sa.getTaskIndex(fs);
3428         boolean needcomma=false;
3429         int runtimeti=0;
3430         output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
3431         for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext(); ) {
3432           TaskIndex ti=itti.next();
3433           if (ti.isRuntime()) {
3434             runtimeti++;
3435             continue;
3436           }
3437           if (needcomma)
3438             output.print(", ");
3439           needcomma=true;
3440           output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
3441         }
3442         output.println("};\n");
3443
3444         //Store the result in fsanalysiswrapper
3445
3446         output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
3447         output.println("/*flag*/"+flagid+",");
3448         output.println("/* number of tags*/"+tagcounter+",");
3449         output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
3450         output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
3451         output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
3452         output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
3453         output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
3454         output.println("};\n");
3455
3456       }
3457
3458       //Build the array of fsanalysiswrappers
3459       output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
3460       boolean needcomma=false;
3461       for(int i = 0; i<fscounter; i++) {
3462         if (needcomma) output.print(",");
3463         output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
3464         needcomma=true;
3465       }
3466       output.println("};");
3467
3468       //Build the classanalysiswrapper referring to the previous array
3469       output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
3470       output.println("/*type*/"+cdtemp.getId()+",");
3471       output.println("/*numotd*/"+numotd+",");
3472       output.println("otdarray"+cdtemp.getSafeSymbol()+",");
3473       output.println("/* number of fsanalysiswrappers */"+fscounter+",");
3474       output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
3475       processedcd.add(cdtemp);
3476     }
3477
3478     //build an array containing every classes for which code has been build
3479     output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
3480     for(int i=0; i<state.numClasses(); i++) {
3481       ClassDescriptor cn=cdarray[i];
3482       if (i>0)
3483         output.print(", ");
3484       if ((cn != null) && (processedcd.contains(cn)))
3485         output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
3486       else
3487         output.print("NULL");
3488     }
3489     output.println("};");
3490
3491     output.println("#define MAXOTD "+maxotd);
3492     headers.println("#endif");
3493   }
3494
3495   public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
3496     Relation r=new Relation();
3497     for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext(); ) {
3498       OptionalTaskDescriptor otd=otdit.next();
3499       TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
3500       r.put(ti, otd);
3501     }
3502
3503     LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
3504     for(Iterator it=r.keySet().iterator(); it.hasNext(); ) {
3505       Set s=r.get(it.next());
3506       for(Iterator it2=s.iterator(); it2.hasNext(); ) {
3507         OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
3508         l.add(otd);
3509       }
3510     }
3511
3512     return l;
3513   }
3514
3515   // override these methods in a subclass of BuildCode
3516   // to generate code for additional systems
3517   protected void printExtraArrayFields(PrintWriter outclassdefs) {
3518   }
3519   protected void outputTransCode(PrintWriter output) {
3520   }
3521   protected void buildCodeSetup() {
3522   }
3523   protected void generateSizeArrayExtensions(PrintWriter outclassdefs) {
3524   }
3525   protected void additionalIncludesMethodsHeader(PrintWriter outmethodheader) {
3526   }
3527   protected void preCodeGenInitialization() {
3528   }
3529   protected void postCodeGenCleanUp() {
3530   }
3531   protected void additionalCodeGen(PrintWriter outmethodheader,
3532                                    PrintWriter outstructs,
3533                                    PrintWriter outmethod) {
3534   }
3535   protected void additionalCodeAtTopOfMain(PrintWriter outmethod) {
3536   }
3537   protected void additionalCodeAtBottomOfMain(PrintWriter outmethod) {
3538   }
3539   protected void additionalIncludesMethodsImplementation(PrintWriter outmethod) {
3540   }
3541   protected void additionalIncludesStructsHeader(PrintWriter outstructs) {
3542   }
3543   protected void additionalClassObjectFields(PrintWriter outclassdefs) {
3544   }
3545   protected void additionalCodeAtTopMethodsImplementation(PrintWriter outmethod) {
3546   }
3547   protected void additionalCodeAtTopFlatMethodBody(PrintWriter output, FlatMethod fm) {
3548   }
3549   protected void additionalCodePreNode(FlatMethod fm, FlatNode fn, PrintWriter output) {
3550   }
3551   protected void additionalCodePostNode(FlatMethod fm, FlatNode fn, PrintWriter output) {
3552   }
3553   
3554   private void printSourceLineNumber(FlatMethod fm, FlatNode fn, PrintWriter output) {
3555     // we do not print out line number if no one explicitly set the number
3556     if(fn.getNumLine()!=-1){
3557       
3558       int lineNum=fn.getNumLine();
3559
3560       // do not generate the line number if it is same as the previous one
3561       boolean needtoprint;
3562       if(fn.prev.size()==0){
3563         needtoprint=true;
3564       }else{
3565         needtoprint=false;
3566       }
3567
3568       for(int i=0;i<fn.prev.size();i++){
3569         int prevLineNum=((FlatNode)fn.prev.get(i)).getNumLine();
3570         if(prevLineNum!=lineNum){
3571           needtoprint=true;
3572           break;
3573         }
3574       }
3575       if(needtoprint){
3576         output.println("// "+fm.getMethod().getClassDesc().getSourceFileName()+":"+fn.getNumLine());
3577       }
3578     }
3579   }
3580   
3581 }
3582
3583
3584
3585
3586
3587