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