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