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