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