9df8f12226fa897d7f4fa0e0a11f300cadf131e7
[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     Set<FlatNode> unionset=null;
2153
2154     if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
2155       storeset=delaycomp.livecode(lb);
2156       genset=new HashSet<FlatNode>();
2157       if (firstpass) {
2158         genset.addAll(delaycomp.getCannotDelay(lb));
2159         genset.addAll(delaycomp.getOther(lb));
2160       } else {
2161         genset.addAll(delaycomp.getNotReady(lb));
2162       }
2163       unionset=new HashSet<FlatNode>();
2164       unionset.addAll(storeset);
2165       unionset.addAll(genset);
2166     }
2167     
2168     /* Do the actual code generation */
2169     FlatNode current_node=null;
2170     HashSet tovisit=new HashSet();
2171     HashSet visited=new HashSet();
2172     if (!firstpass)
2173       tovisit.add(first.getNext(0));
2174     else
2175       tovisit.add(first);
2176     while(current_node!=null||!tovisit.isEmpty()) {
2177       if (current_node==null) {
2178         current_node=(FlatNode)tovisit.iterator().next();
2179         tovisit.remove(current_node);
2180       } else if (tovisit.contains(current_node)) {
2181         tovisit.remove(current_node);
2182       }
2183       visited.add(current_node);
2184       if (nodetolabel.containsKey(current_node)) {
2185         output.println("L"+nodetolabel.get(current_node)+":");
2186       }
2187       if (state.INSTRUCTIONFAILURE) {
2188         if (state.THREAD||state.DSM||state.SINGLETM) {
2189           output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
2190         } else
2191           output.println("if ((--instructioncount)==0) injectinstructionfailure();");
2192       }
2193       if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
2194         output.print("   ");
2195         if (!state.DELAYCOMP||firstpass) {
2196           generateFlatNode(fm, lb, current_node, output);
2197         } else {
2198           //store primitive variables in out set
2199           AtomicRecord ar=atomicmethodmap.get((FlatAtomicEnterNode)first);
2200           Set<TempDescriptor> liveout=ar.liveout;
2201           for(Iterator<TempDescriptor> tmpit=liveout.iterator();tmpit.hasNext();) {
2202             TempDescriptor tmp=tmpit.next();
2203             output.println("primitives->"+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2204           }
2205         }
2206         if (state.MLP && stopset!=null) {
2207           assert first.getPrev( 0 ) instanceof FlatSESEEnterNode;
2208           assert current_node       instanceof FlatSESEExitNode;
2209           FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev( 0 );
2210           FlatSESEExitNode  fsxn = (FlatSESEExitNode)  current_node;
2211           assert fsen.getFlatExit().equals( fsxn );
2212           assert fsxn.getFlatEnter().equals( fsen );
2213         }
2214         if (current_node.kind()!=FKind.FlatReturnNode) {
2215           output.println("   return;");
2216         }
2217         current_node=null;
2218       } else if(current_node.numNext()==1) {
2219         FlatNode nextnode;
2220         if (state.MLP && 
2221             current_node.kind()==FKind.FlatSESEEnterNode && 
2222             !((FlatSESEEnterNode)current_node).getIsCallerSESEplaceholder()
2223            ) {
2224           FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
2225           generateFlatNode(fm, lb, current_node, output);
2226           nextnode=fsen.getFlatExit().getNext(0);
2227         } else if (state.DELAYCOMP) {
2228           boolean specialprimitive=false;
2229           //skip literals...no need to add extra overhead
2230           if (storeset!=null&&storeset.contains(current_node)&&current_node.kind()==FKind.FlatLiteralNode) {
2231             TypeDescriptor typedesc=((FlatLiteralNode)current_node).getType();
2232             if (!typedesc.isClass()&&!typedesc.isArray()) {
2233               specialprimitive=true;
2234             }
2235           }
2236
2237           if (genset==null||genset.contains(current_node)||specialprimitive)
2238             generateFlatNode(fm, lb, current_node, output);
2239           if (storeset!=null&&storeset.contains(current_node)&&!specialprimitive) {
2240             TempDescriptor wrtmp=current_node.writesTemps()[0];
2241             if (firstpass) {
2242               //need to store value written by previous node
2243               if (wrtmp.getType().isPtr()) {
2244                 //only lock the objects that may actually need locking
2245                 if (recorddc.getNeedTrans(lb, current_node)) {
2246                   output.println("STOREPTR("+generateTemp(fm, wrtmp,lb)+");");
2247                 } else {
2248                   output.println("STOREPTRNOLOCK("+generateTemp(fm, wrtmp,lb)+");");
2249                 }
2250               } else {
2251                 output.println("STORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");");
2252               }
2253             } else {
2254               //need to read value read by previous node
2255               if (wrtmp.getType().isPtr()) {
2256                 output.println("RESTOREPTR("+generateTemp(fm, wrtmp,lb)+");");
2257               } else {
2258                 output.println("RESTORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");");             
2259               }
2260             }
2261           }
2262           nextnode=current_node.getNext(0);
2263         } else {
2264           output.print("   ");
2265           generateFlatNode(fm, lb, current_node, output);
2266           nextnode=current_node.getNext(0);
2267         }
2268         if (visited.contains(nextnode)) {
2269           output.println("goto L"+nodetolabel.get(nextnode)+";");
2270           current_node=null;
2271         } else 
2272           current_node=nextnode;
2273       } else if (current_node.numNext()==2) {
2274         /* Branch */
2275         if (state.DELAYCOMP) {
2276           boolean computeside=false;
2277           if (firstpass) {
2278             //need to record which way it should go
2279             if (genset==null||genset.contains(current_node)) {
2280               if (storeset!=null&&storeset.contains(current_node)) {
2281                 //need to store which way branch goes
2282                 generateStoreFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2283               } else
2284                 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2285             } else {
2286               //which side to execute
2287               computeside=true;
2288             }
2289           } else {
2290             if (genset.contains(current_node)) {
2291               generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);             
2292             } else if (storeset.contains(current_node)) {
2293               //need to do branch
2294               output.println("RESTOREANDBRANCH(L"+nodetolabel.get(current_node.getNext(1))+");");
2295             } else {
2296               //which side to execute
2297               computeside=true;
2298             }
2299           }
2300           if (computeside) {
2301             Set<FlatNode> leftset=DelayComputation.getNext(current_node, 0, unionset, lb,locality, true);
2302             int branch=0;
2303             if (leftset.size()==0)
2304               branch=1;
2305             if (visited.contains(current_node.getNext(branch))) {
2306               //already visited -- build jump
2307               output.println("goto L"+nodetolabel.get(current_node.getNext(branch))+";");
2308               current_node=null;
2309             } else {
2310               current_node=current_node.getNext(branch);
2311             }
2312           } else {
2313             if (!visited.contains(current_node.getNext(1)))
2314               tovisit.add(current_node.getNext(1));
2315             if (visited.contains(current_node.getNext(0))) {
2316               output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2317               current_node=null;
2318             } else 
2319               current_node=current_node.getNext(0);
2320           }
2321         } else {
2322           output.print("   ");  
2323           generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2324           if (!visited.contains(current_node.getNext(1)))
2325             tovisit.add(current_node.getNext(1));
2326           if (visited.contains(current_node.getNext(0))) {
2327             output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2328             current_node=null;
2329           } else 
2330             current_node=current_node.getNext(0);
2331         }
2332       } else throw new Error();
2333     }
2334   }
2335
2336   /** This method assigns labels to FlatNodes */
2337   protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first) {
2338     return assignLabels(first, null);
2339   }
2340
2341   protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
2342     HashSet tovisit=new HashSet();
2343     HashSet visited=new HashSet();
2344     int labelindex=0;
2345     Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2346     tovisit.add(first);
2347
2348     /*Assign labels first.  A node needs a label if the previous
2349      * node has two exits or this node is a join point. */
2350
2351     while(!tovisit.isEmpty()) {
2352       FlatNode fn=(FlatNode)tovisit.iterator().next();
2353       tovisit.remove(fn);
2354       visited.add(fn);
2355
2356
2357       if(lastset!=null&&lastset.contains(fn)) {
2358         // if last is not null and matches, don't go 
2359         // any further for assigning labels
2360         continue;
2361       }
2362
2363       for(int i=0; i<fn.numNext(); i++) {
2364         FlatNode nn=fn.getNext(i);
2365
2366         if(i>0) {
2367           //1) Edge >1 of node
2368           nodetolabel.put(nn,new Integer(labelindex++));
2369         }
2370         if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2371           tovisit.add(nn);
2372         } else {
2373           //2) Join point
2374           nodetolabel.put(nn,new Integer(labelindex++));
2375         }
2376       }
2377     }
2378     return nodetolabel;
2379   }
2380
2381
2382   /** Generate text string that corresponds to the TempDescriptor td. */
2383   protected String generateTemp(FlatMethod fm, TempDescriptor td, LocalityBinding lb) {
2384     MethodDescriptor md=fm.getMethod();
2385     TaskDescriptor task=fm.getTask();
2386     TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
2387
2388     if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
2389       //System.out.println("generateTemp returns " + td.getSafeSymbol());
2390       return td.getSafeSymbol();
2391     }
2392
2393     if (objecttemps.isLocalPtr(td)) {
2394       return localsprefixderef+td.getSafeSymbol();
2395     }
2396
2397     if (objecttemps.isParamPtr(td)) {
2398       return paramsprefix+"->"+td.getSafeSymbol();
2399     }
2400
2401     throw new Error();
2402   }
2403
2404   protected void generateFlatNode(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output) {
2405
2406     // insert pre-node actions from the code plan
2407     if( state.MLP ) {
2408       
2409       CodePlan cp = mlpa.getCodePlan( fn );
2410       if( cp != null ) {                
2411         
2412         FlatSESEEnterNode currentSESE = cp.getCurrentSESE();
2413         
2414         // for each sese and age pair that this parent statement
2415         // must stall on, take that child's stall semaphore, the
2416         // copying of values comes after the statement
2417         Iterator<VariableSourceToken> vstItr = cp.getStallTokens().iterator();
2418         while( vstItr.hasNext() ) {
2419           VariableSourceToken vst = vstItr.next();
2420
2421           SESEandAgePair p = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2422
2423           output.println("   {");
2424           output.println("     SESEcommon* common = (SESEcommon*) "+p+";");
2425
2426           output.println("     pthread_mutex_lock( &(common->lock) );");
2427           output.println("     while( common->doneExecuting == FALSE ) {");
2428           output.println("       pthread_cond_wait( &(common->doneCond), &(common->lock) );");
2429           output.println("     }");
2430           output.println("     pthread_mutex_unlock( &(common->lock) );");
2431                   
2432           //output.println("     psem_take( &(common->stallSem) );");
2433
2434           // copy things we might have stalled for        
2435           output.println("     "+p.getSESE().getSESErecordName()+"* child = ("+
2436                                  p.getSESE().getSESErecordName()+"*) "+p+";");
2437           
2438           Iterator<TempDescriptor> tdItr = cp.getCopySet( vst ).iterator();
2439           while( tdItr.hasNext() ) {
2440             TempDescriptor td = tdItr.next();
2441             FlatMethod fmContext;
2442             if( currentSESE.getIsCallerSESEplaceholder() ) {
2443               fmContext = currentSESE.getfmEnclosing();
2444             } else {
2445               fmContext = currentSESE.getfmBogus();
2446             }
2447             output.println("       "+generateTemp( fmContext, td, null )+
2448                            " = child->"+vst.getAddrVar().getSafeSymbol()+";");
2449           }
2450
2451           output.println("   }");
2452         }
2453         
2454         // for each variable with a dynamic source, stall just for that variable
2455         Iterator<TempDescriptor> dynItr = cp.getDynamicStallSet().iterator();
2456         while( dynItr.hasNext() ) {
2457           TempDescriptor dynVar = dynItr.next();
2458
2459           // only stall if the dynamic source is not yourself, denoted by src==NULL
2460           // otherwise the dynamic write nodes will have the local var up-to-date
2461           output.println("   {");
2462           output.println("     if( "+dynVar+"_srcSESE != NULL ) {");
2463           output.println("       SESEcommon* common = (SESEcommon*) "+dynVar+"_srcSESE;");
2464           output.println("       psem_take( &(common->stallSem) );");
2465
2466           FlatMethod fmContext;
2467           if( currentSESE.getIsCallerSESEplaceholder() ) {
2468             fmContext = currentSESE.getfmEnclosing();
2469           } else {
2470             fmContext = currentSESE.getfmBogus();
2471           }
2472           output.println("       "+generateTemp( fmContext, dynVar, null )+
2473                          " = *(("+dynVar.getType()+"*) ("+
2474                          dynVar+"_srcSESE + "+dynVar+"_srcOffset));");
2475           
2476           output.println("     }");
2477           output.println("   }");
2478         }
2479
2480         // for each assignment of a variable to rhs that has a dynamic source,
2481         // copy the dynamic sources
2482         Iterator dynAssignItr = cp.getDynAssigns().entrySet().iterator();
2483         while( dynAssignItr.hasNext() ) {
2484           Map.Entry      me  = (Map.Entry)      dynAssignItr.next();
2485           TempDescriptor lhs = (TempDescriptor) me.getKey();
2486           TempDescriptor rhs = (TempDescriptor) me.getValue();
2487           output.println("   "+lhs+"_srcSESE   = "+rhs+"_srcSESE;");
2488           output.println("   "+lhs+"_srcOffset = "+rhs+"_srcOffset;");
2489         }
2490
2491         // for each lhs that is dynamic from a non-dynamic source, set the
2492         // dynamic source vars to the current SESE
2493         dynItr = cp.getDynAssignCurr().iterator();
2494         while( dynItr.hasNext() ) {
2495           TempDescriptor dynVar = dynItr.next();
2496           output.println("   "+dynVar+"_srcSESE = NULL;");
2497         }
2498       }     
2499     }
2500
2501     switch(fn.kind()) {
2502     case FKind.FlatAtomicEnterNode:
2503       generateFlatAtomicEnterNode(fm, lb, (FlatAtomicEnterNode) fn, output);
2504       break;
2505
2506     case FKind.FlatAtomicExitNode:
2507       generateFlatAtomicExitNode(fm, lb, (FlatAtomicExitNode) fn, output);
2508       break;
2509
2510     case FKind.FlatInstanceOfNode:
2511       generateFlatInstanceOfNode(fm, lb, (FlatInstanceOfNode)fn, output);
2512       break;
2513
2514     case FKind.FlatSESEEnterNode:
2515       generateFlatSESEEnterNode(fm, lb, (FlatSESEEnterNode)fn, output);
2516       break;
2517
2518     case FKind.FlatSESEExitNode:
2519       generateFlatSESEExitNode(fm, lb, (FlatSESEExitNode)fn, output);
2520       break;
2521       
2522     case FKind.FlatWriteDynamicVarNode:
2523       generateFlatWriteDynamicVarNode(fm, lb, (FlatWriteDynamicVarNode)fn, output);
2524       break;
2525
2526     case FKind.FlatGlobalConvNode:
2527       generateFlatGlobalConvNode(fm, lb, (FlatGlobalConvNode) fn, output);
2528       break;
2529
2530     case FKind.FlatTagDeclaration:
2531       generateFlatTagDeclaration(fm, lb, (FlatTagDeclaration) fn,output);
2532       break;
2533
2534     case FKind.FlatCall:
2535       generateFlatCall(fm, lb, (FlatCall) fn,output);
2536       break;
2537
2538     case FKind.FlatFieldNode:
2539       generateFlatFieldNode(fm, lb, (FlatFieldNode) fn,output);
2540       break;
2541
2542     case FKind.FlatElementNode:
2543       generateFlatElementNode(fm, lb, (FlatElementNode) fn,output);
2544       break;
2545
2546     case FKind.FlatSetElementNode:
2547       generateFlatSetElementNode(fm, lb, (FlatSetElementNode) fn,output);
2548       break;
2549
2550     case FKind.FlatSetFieldNode:
2551       generateFlatSetFieldNode(fm, lb, (FlatSetFieldNode) fn,output);
2552       break;
2553
2554     case FKind.FlatNew:
2555       generateFlatNew(fm, lb, (FlatNew) fn,output);
2556       break;
2557
2558     case FKind.FlatOpNode:
2559       generateFlatOpNode(fm, lb, (FlatOpNode) fn,output);
2560       break;
2561
2562     case FKind.FlatCastNode:
2563       generateFlatCastNode(fm, lb, (FlatCastNode) fn,output);
2564       break;
2565
2566     case FKind.FlatLiteralNode:
2567       generateFlatLiteralNode(fm, lb, (FlatLiteralNode) fn,output);
2568       break;
2569
2570     case FKind.FlatReturnNode:
2571       generateFlatReturnNode(fm, lb, (FlatReturnNode) fn,output);
2572       break;
2573
2574     case FKind.FlatNop:
2575       output.println("/* nop */");
2576       break;
2577
2578     case FKind.FlatExit:
2579       output.println("/* exit */");
2580       break;
2581
2582     case FKind.FlatBackEdge:
2583       if (state.SINGLETM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
2584         output.println("if ((--transaction_check_counter)<=0) checkObjects();");
2585       }
2586       if (((state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
2587           || (this.state.MULTICOREGC)) {
2588         if(state.DSM&&locality.getAtomic(lb).get(fn).intValue()>0) {
2589           output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
2590         } else if(this.state.MULTICOREGC) {
2591           output.println("if (gcflag) gc("+localsprefixaddr+");");
2592         } else
2593           output.println("if (needtocollect) checkcollect("+localsprefixaddr+");");
2594       } else
2595         output.println("/* nop */");
2596       break;
2597
2598     case FKind.FlatCheckNode:
2599       generateFlatCheckNode(fm, lb, (FlatCheckNode) fn, output);
2600       break;
2601
2602     case FKind.FlatFlagActionNode:
2603       generateFlatFlagActionNode(fm, lb, (FlatFlagActionNode) fn, output);
2604       break;
2605
2606     case FKind.FlatPrefetchNode:
2607       generateFlatPrefetchNode(fm,lb, (FlatPrefetchNode) fn, output);
2608       break;
2609
2610     case FKind.FlatOffsetNode:
2611       generateFlatOffsetNode(fm, lb, (FlatOffsetNode)fn, output);
2612       break;
2613
2614     default:
2615       throw new Error();
2616     }
2617
2618     // insert post-node actions from the code-plan    
2619     if( state.MLP ) {
2620       CodePlan cp = mlpa.getCodePlan( fn );
2621
2622       if( cp != null ) {     
2623       }
2624     }    
2625   }
2626
2627   public void generateFlatOffsetNode(FlatMethod fm, LocalityBinding lb, FlatOffsetNode fofn, PrintWriter output) {
2628     output.println("/* FlatOffsetNode */");
2629     FieldDescriptor fd=fofn.getField();
2630     output.println(generateTemp(fm, fofn.getDst(),lb)+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+ fd.getSafeSymbol()+");");
2631     output.println("/* offset */");
2632   }
2633
2634   public void generateFlatPrefetchNode(FlatMethod fm, LocalityBinding lb, FlatPrefetchNode fpn, PrintWriter output) {
2635     if (state.PREFETCH) {
2636       Vector oids = new Vector();
2637       Vector fieldoffset = new Vector();
2638       Vector endoffset = new Vector();
2639       int tuplecount = 0;        //Keeps track of number of prefetch tuples that need to be generated
2640       for(Iterator it = fpn.hspp.iterator(); it.hasNext();) {
2641         PrefetchPair pp = (PrefetchPair) it.next();
2642         Integer statusbase = locality.getNodePreTempInfo(lb,fpn).get(pp.base);
2643         /* Find prefetches that can generate oid */
2644         if(statusbase == LocalityAnalysis.GLOBAL) {
2645           generateTransCode(fm, lb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(lb).get(fpn).intValue()>0, false);
2646           tuplecount++;
2647         } else if (statusbase == LocalityAnalysis.LOCAL) {
2648           generateTransCode(fm,lb,pp,oids,fieldoffset,endoffset,tuplecount,false,true);
2649         } else {
2650           continue;
2651         }
2652       }
2653       if (tuplecount==0)
2654         return;
2655       System.out.println("Adding prefetch "+fpn+ " to method:" +fm);
2656       output.println("{");
2657       output.println("/* prefetch */");
2658       output.println("/* prefetchid_" + fpn.siteid + " */");
2659       output.println("void * prefptr;");
2660       output.println("int tmpindex;");
2661
2662       output.println("if((evalPrefetch["+fpn.siteid+"].operMode) || (evalPrefetch["+fpn.siteid+"].retrycount <= 0)) {");
2663       /*Create C code for oid array */
2664       output.print("   unsigned int oidarray_[] = {");
2665       boolean needcomma=false;
2666       for (Iterator it = oids.iterator(); it.hasNext();) {
2667         if (needcomma)
2668           output.print(", ");
2669         output.print(it.next());
2670         needcomma=true;
2671       }
2672       output.println("};");
2673
2674       /*Create C code for endoffset values */
2675       output.print("   unsigned short endoffsetarry_[] = {");
2676       needcomma=false;
2677       for (Iterator it = endoffset.iterator(); it.hasNext();) {
2678         if (needcomma)
2679           output.print(", ");
2680         output.print(it.next());
2681         needcomma=true;
2682       }
2683       output.println("};");
2684
2685       /*Create C code for Field Offset Values */
2686       output.print("   short fieldarry_[] = {");
2687       needcomma=false;
2688       for (Iterator it = fieldoffset.iterator(); it.hasNext();) {
2689         if (needcomma)
2690           output.print(", ");
2691         output.print(it.next());
2692         needcomma=true;
2693       }
2694       output.println("};");
2695       /* make the prefetch call to Runtime */
2696       output.println("   if(!evalPrefetch["+fpn.siteid+"].operMode) {");
2697       output.println("     evalPrefetch["+fpn.siteid+"].retrycount = RETRYINTERVAL;");
2698       output.println("   }");
2699       output.println("   prefetch("+fpn.siteid+" ,"+tuplecount+", oidarray_, endoffsetarry_, fieldarry_);");
2700       output.println(" } else {");
2701       output.println("   evalPrefetch["+fpn.siteid+"].retrycount--;");
2702       output.println(" }");
2703       output.println("}");
2704     }
2705   }
2706
2707   public void generateTransCode(FlatMethod fm, LocalityBinding lb,PrefetchPair pp, Vector oids, Vector fieldoffset, Vector endoffset, int tuplecount, boolean inside, boolean localbase) {
2708     short offsetcount = 0;
2709     int breakindex=0;
2710     if (inside) {
2711       breakindex=1;
2712     } else if (localbase) {
2713       for(; breakindex<pp.desc.size(); breakindex++) {
2714         Descriptor desc=pp.getDescAt(breakindex);
2715         if (desc instanceof FieldDescriptor) {
2716           FieldDescriptor fd=(FieldDescriptor)desc;
2717           if (fd.isGlobal()) {
2718             break;
2719           }
2720         }
2721       }
2722       breakindex++;
2723     }
2724
2725     if (breakindex>pp.desc.size())     //all local
2726       return;
2727
2728     TypeDescriptor lasttype=pp.base.getType();
2729     String basestr=generateTemp(fm, pp.base, lb);
2730     String teststr="";
2731     boolean maybenull=fm.getMethod().isStatic()||
2732                        !pp.base.equals(fm.getParameter(0));
2733
2734     for(int i=0; i<breakindex; i++) {
2735       String indexcheck="";
2736
2737       Descriptor desc=pp.getDescAt(i);
2738       if (desc instanceof FieldDescriptor) {
2739         FieldDescriptor fd=(FieldDescriptor)desc;
2740         if (maybenull) {
2741           if (!teststr.equals(""))
2742             teststr+="&&";
2743           teststr+="((prefptr="+basestr+")!=NULL)";
2744           basestr="((struct "+lasttype.getSafeSymbol()+" *)prefptr)->"+fd.getSafeSymbol();
2745         } else {
2746           basestr=basestr+"->"+fd.getSafeSymbol();
2747           maybenull=true;
2748         }
2749         lasttype=fd.getType();
2750       } else {
2751         IndexDescriptor id=(IndexDescriptor)desc;
2752         indexcheck="((tmpindex=";
2753         for(int j=0; j<id.tddesc.size(); j++) {
2754           indexcheck+=generateTemp(fm, id.getTempDescAt(j), lb)+"+";
2755         }
2756         indexcheck+=id.offset+")>=0)&(tmpindex<((struct ArrayObject *)prefptr)->___length___)";
2757
2758         if (!teststr.equals(""))
2759           teststr+="&&";
2760         teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck;
2761         basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]";
2762         maybenull=true;
2763         lasttype=lasttype.dereference();
2764       }
2765     }
2766
2767     String oid;
2768     if (teststr.equals("")) {
2769       oid="((unsigned int)"+basestr+")";
2770     } else {
2771       oid="((unsigned int)(("+teststr+")?"+basestr+":NULL))";
2772     }
2773     oids.add(oid);
2774
2775     for(int i = breakindex; i < pp.desc.size(); i++) {
2776       String newfieldoffset;
2777       Object desc = pp.getDescAt(i);
2778       if(desc instanceof FieldDescriptor) {
2779         FieldDescriptor fd=(FieldDescriptor)desc;
2780         newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))");
2781         lasttype=fd.getType();
2782       } else {
2783         newfieldoffset = "";
2784         IndexDescriptor id=(IndexDescriptor)desc;
2785         for(int j = 0; j < id.tddesc.size(); j++) {
2786           newfieldoffset += generateTemp(fm, id.getTempDescAt(j), lb) + "+";
2787         }
2788         newfieldoffset += id.offset.toString();
2789         lasttype=lasttype.dereference();
2790       }
2791       fieldoffset.add(newfieldoffset);
2792     }
2793
2794     int base=(tuplecount>0) ? ((Short)endoffset.get(tuplecount-1)).intValue() : 0;
2795     base+=pp.desc.size()-breakindex;
2796     endoffset.add(new Short((short)base));
2797   }
2798
2799
2800
2801   public void generateFlatGlobalConvNode(FlatMethod fm, LocalityBinding lb, FlatGlobalConvNode fgcn, PrintWriter output) {
2802     if (lb!=fgcn.getLocality())
2803       return;
2804     /* Have to generate flat globalconv */
2805     if (fgcn.getMakePtr()) {
2806       if (state.DSM) {
2807         output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+");");
2808       } else {
2809         if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fgcn)||state.READSET&&dc.getNeedWriteTrans(lb, fgcn)) {
2810           //need to do translation
2811           output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+", (void *)("+localsprefixaddr+"));");
2812         } else if (state.READSET&&dc.getNeedTrans(lb, fgcn)) {
2813           output.println("TRANSREADRD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
2814         }
2815       }
2816     } else {
2817       /* Need to convert to OID */
2818       if ((dc==null)||dc.getNeedSrcTrans(lb,fgcn)) {
2819         if (fgcn.doConvert()||(delaycomp!=null&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) {
2820           output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc(),lb)+");");
2821         } else {
2822           output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=NULL;");
2823         }
2824       }
2825     }
2826   }
2827
2828   public void generateFlatInstanceOfNode(FlatMethod fm,  LocalityBinding lb, FlatInstanceOfNode fion, PrintWriter output) {
2829     int type;
2830     if (fion.getType().isArray()) {
2831       type=state.getArrayNumber(fion.getType())+state.numClasses();
2832     } else {
2833       type=fion.getType().getClassDesc().getId();
2834     }
2835
2836     if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
2837       output.println(generateTemp(fm, fion.getDst(), lb)+"=1;");
2838     else
2839       output.println(generateTemp(fm, fion.getDst(), lb)+"=instanceof("+generateTemp(fm,fion.getSrc(),lb)+","+type+");");
2840   }
2841
2842   int sandboxcounter=0;
2843   public void generateFlatAtomicEnterNode(FlatMethod fm,  LocalityBinding lb, FlatAtomicEnterNode faen, PrintWriter output) {
2844     /* Check to see if we need to generate code for this atomic */
2845     if (locality==null) {
2846       output.println("pthread_mutex_lock(&atomiclock);");
2847       return;
2848     }
2849
2850     if (locality.getAtomic(lb).get(faen.getPrev(0)).intValue()>0)
2851       return;
2852
2853
2854     if (state.SANDBOX) {
2855       outsandbox.println("int atomiccounter"+sandboxcounter+"=LOW_CHECK_FREQUENCY;");
2856       output.println("counter_reset_pointer=&atomiccounter"+sandboxcounter+";");
2857     }
2858
2859     if (state.DELAYCOMP) {
2860       AtomicRecord ar=atomicmethodmap.get(faen);
2861       //copy in
2862       for(Iterator<TempDescriptor> tmpit=ar.livein.iterator();tmpit.hasNext();) {
2863         TempDescriptor tmp=tmpit.next();
2864         output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2865       }
2866
2867       //copy outs that depend on path
2868       for(Iterator<TempDescriptor> tmpit=ar.liveoutvirtualread.iterator();tmpit.hasNext();) {
2869         TempDescriptor tmp=tmpit.next();
2870         if (!ar.livein.contains(tmp))
2871           output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2872       }
2873     }
2874
2875     /* Backup the temps. */
2876     for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
2877       TempDescriptor tmp=tmpit.next();
2878       output.println(generateTemp(fm, backuptable.get(lb).get(tmp),lb)+"="+generateTemp(fm,tmp,lb)+";");
2879     }
2880
2881     output.println("goto transstart"+faen.getIdentifier()+";");
2882
2883     /******* Print code to retry aborted transaction *******/
2884     output.println("transretry"+faen.getIdentifier()+":");
2885
2886     /* Restore temps */
2887     for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
2888       TempDescriptor tmp=tmpit.next();
2889       output.println(generateTemp(fm, tmp,lb)+"="+generateTemp(fm,backuptable.get(lb).get(tmp),lb)+";");
2890     }
2891
2892     if (state.DSM) {
2893       /********* Need to revert local object store ********/
2894       String revertptr=generateTemp(fm, reverttable.get(lb),lb);
2895
2896       output.println("while ("+revertptr+") {");
2897       output.println("struct ___Object___ * tmpptr;");
2898       output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
2899       output.println("REVERT_OBJ("+revertptr+");");
2900       output.println(revertptr+"=tmpptr;");
2901       output.println("}");
2902     }
2903     /******* Tell the runtime to start the transaction *******/
2904
2905     output.println("transstart"+faen.getIdentifier()+":");
2906     if (state.SANDBOX) {
2907       output.println("transaction_check_counter=*counter_reset_pointer;");
2908       sandboxcounter++;
2909     }
2910     output.println("transStart();");
2911
2912     if (state.ABORTREADERS||state.SANDBOX) {
2913       if (state.SANDBOX)
2914         output.println("abortenabled=1;");
2915       output.println("if (_setjmp(aborttrans)) {");
2916       output.println("  goto transretry"+faen.getIdentifier()+"; }");
2917     }
2918   }
2919
2920   public void generateFlatAtomicExitNode(FlatMethod fm,  LocalityBinding lb, FlatAtomicExitNode faen, PrintWriter output) {
2921     /* Check to see if we need to generate code for this atomic */
2922     if (locality==null) {
2923       output.println("pthread_mutex_unlock(&atomiclock);");
2924       return;
2925     }
2926     if (locality.getAtomic(lb).get(faen).intValue()>0)
2927       return;
2928     //store the revert list before we lose the transaction object
2929     String revertptr=null;
2930     if (state.DSM) {
2931       revertptr=generateTemp(fm, reverttable.get(lb),lb);
2932       output.println(revertptr+"=revertlist;");
2933     }
2934     if (state.DELAYCOMP) {
2935       AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
2936
2937       //do call
2938       output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {");
2939     } else
2940       output.println("if (transCommit()) {");
2941     /* Transaction aborts if it returns true */
2942     output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
2943     if (state.DSM) {
2944       output.println("} else {");
2945       /* Need to commit local object store */
2946       output.println("while ("+revertptr+") {");
2947       output.println("struct ___Object___ * tmpptr;");
2948       output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
2949       output.println("COMMIT_OBJ("+revertptr+");");
2950       output.println(revertptr+"=tmpptr;");
2951       output.println("}");
2952     }
2953     output.println("}");
2954     if (state.DELAYCOMP) {
2955       //copy out
2956       AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
2957       output.println("else {");
2958       for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
2959         TempDescriptor tmp=tmpit.next();
2960         output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
2961       }
2962       output.println("}");
2963     }
2964   }
2965
2966   public void generateFlatSESEEnterNode( FlatMethod fm,  
2967                                          LocalityBinding lb, 
2968                                          FlatSESEEnterNode fsen, 
2969                                          PrintWriter output 
2970                                        ) {
2971
2972     // if MLP flag is off, okay that SESE nodes are in IR graph, 
2973     // just skip over them and code generates exactly the same
2974     if( !state.MLP ) {
2975       return;
2976     }    
2977
2978     // there may be an SESE in an unreachable method, skip over
2979     if( !mlpa.getAllSESEs().contains( fsen ) ) {
2980       return;
2981     }
2982
2983     // also, if we have encountered a placeholder, just skip it
2984     if( fsen.getIsCallerSESEplaceholder() ) {
2985       return;
2986     }
2987
2988     output.println("   {");
2989
2990     // set up the parent
2991     if( fsen == mlpa.getMainSESE() ) {
2992       output.println("     SESEcommon* parentCommon = NULL;");
2993     } else {
2994       if( fsen.getParent() == null ) {
2995         System.out.println( "in "+fm+", "+fsen+" has null parent" );
2996       }
2997       assert fsen.getParent() != null;
2998       if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
2999         output.println("     SESEcommon* parentCommon = &("+paramsprefix+"->common);");
3000       } else {
3001         //output.println("     SESEcommon* parentCommon = (SESEcommon*) peekItem( seseCallStack );");
3002         output.println("     SESEcommon* parentCommon = seseCaller;");
3003       }
3004     }
3005
3006     // before doing anything, lock your own record and increment the running children
3007     if( fsen != mlpa.getMainSESE() ) {      
3008       output.println("     pthread_mutex_lock( &(parentCommon->lock) );");
3009       output.println("     ++(parentCommon->numRunningChildren);");
3010       output.println("     pthread_mutex_unlock( &(parentCommon->lock) );");      
3011     }
3012
3013     // just allocate the space for this record
3014     output.println("     "+fsen.getSESErecordName()+"* seseToIssue = ("+
3015                            fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
3016                            fsen.getSESErecordName()+" ) );");
3017
3018     // and keep the thread-local sese stack up to date
3019     //output.println("     addNewItem( seseCallStack, (void*) seseToIssue);");
3020
3021     // fill in common data
3022     output.println("     seseToIssue->common.classID = "+fsen.getIdentifier()+";");
3023     output.println("     psem_init( &(seseToIssue->common.stallSem) );");
3024
3025     output.println("     seseToIssue->common.forwardList = createQueue();");
3026     output.println("     seseToIssue->common.unresolvedDependencies = 0;");
3027     output.println("     pthread_cond_init( &(seseToIssue->common.doneCond), NULL );");
3028     output.println("     seseToIssue->common.doneExecuting = FALSE;");    
3029     output.println("     pthread_cond_init( &(seseToIssue->common.runningChildrenCond), NULL );");
3030     output.println("     seseToIssue->common.numRunningChildren = 0;");
3031     output.println("     seseToIssue->common.parent = parentCommon;");
3032
3033     // all READY in-vars should be copied now and be done with it
3034     Iterator<TempDescriptor> tempItr = fsen.getReadyInVarSet().iterator();
3035     while( tempItr.hasNext() ) {
3036       TempDescriptor temp = tempItr.next();
3037
3038       // when we are issuing the main SESE or an SESE with placeholder
3039       // caller SESE as parent, generate temp child child's eclosing method,
3040       // otherwise use the parent's enclosing method as the context
3041       boolean useParentContext = false;
3042
3043       if( fsen != mlpa.getMainSESE() ) {
3044         assert fsen.getParent() != null;
3045         if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3046           useParentContext = true;
3047         }
3048       }
3049
3050       if( useParentContext ) {
3051         output.println("     seseToIssue->"+temp+" = "+
3052                        generateTemp( fsen.getParent().getfmBogus(), temp, null )+";");   
3053       } else {
3054         output.println("     seseToIssue->"+temp+" = "+
3055                        generateTemp( fsen.getfmEnclosing(), temp, null )+";");
3056       }
3057     }
3058
3059     // before potentially adding this SESE to other forwarding lists,
3060     //  create it's lock and take it immediately
3061     output.println("     pthread_mutex_init( &(seseToIssue->common.lock), NULL );");
3062     output.println("     pthread_mutex_lock( &(seseToIssue->common.lock) );");
3063
3064     if( fsen != mlpa.getMainSESE() ) {
3065       // count up outstanding dependencies, static first, then dynamic
3066       Iterator<SESEandAgePair> staticSrcsItr = fsen.getStaticInVarSrcs().iterator();
3067       while( staticSrcsItr.hasNext() ) {
3068         SESEandAgePair srcPair = staticSrcsItr.next();
3069         output.println("     {");
3070         output.println("       SESEcommon* src = (SESEcommon*)"+srcPair+";");
3071         output.println("       pthread_mutex_lock( &(src->lock) );");
3072         output.println("       if( !isEmpty( src->forwardList ) &&");
3073         output.println("           seseToIssue == peekItem( src->forwardList ) ) {");
3074         output.println("         printf( \"This shouldnt already be here\\n\");");
3075         output.println("         exit( -1 );");
3076         output.println("       }");
3077         output.println("       if( !src->doneExecuting ) {");
3078         output.println("         addNewItem( src->forwardList, seseToIssue );");
3079         output.println("         ++(seseToIssue->common.unresolvedDependencies);");
3080         output.println("       }");
3081         output.println("       pthread_mutex_unlock( &(src->lock) );");
3082         output.println("     }");
3083
3084         // whether or not it is an outstanding dependency, make sure
3085         // to pass the static name to the child's record
3086         output.println("     seseToIssue->"+srcPair+" = "+srcPair+";");
3087       }
3088
3089       // dynamic sources might already be accounted for in the static list,
3090       // so only add them to forwarding lists if they're not already there
3091       Iterator<TempDescriptor> dynVarsItr = fsen.getDynamicInVarSet().iterator();
3092       while( dynVarsItr.hasNext() ) {
3093         TempDescriptor dynInVar = dynVarsItr.next();
3094         output.println("     {");
3095         output.println("       SESEcommon* src = (SESEcommon*)"+dynInVar+"_srcSESE;");
3096
3097         // the dynamic source is NULL if it comes from your own space--you can't pass
3098         // the address off to the new child, because you're not done executing and
3099         // might change the variable, so copy it right now
3100         output.println("       if( src != NULL ) {");
3101         output.println("         pthread_mutex_lock( &(src->lock) );");
3102         output.println("         if( isEmpty( src->forwardList ) ||");
3103         output.println("             seseToIssue != peekItem( src->forwardList ) ) {");
3104         output.println("           if( !src->doneExecuting ) {");
3105         output.println("             addNewItem( src->forwardList, seseToIssue );");
3106         output.println("             ++(seseToIssue->common.unresolvedDependencies);");
3107         output.println("           }");
3108         output.println("         }");
3109         output.println("         pthread_mutex_unlock( &(src->lock) );");       
3110         output.println("         seseToIssue->"+dynInVar+"_srcOffset = "+dynInVar+"_srcOffset;");
3111         output.println("       } else {");
3112
3113         boolean useParentContext = false;
3114         if( fsen != mlpa.getMainSESE() ) {
3115           assert fsen.getParent() != null;
3116           if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3117             useParentContext = true;
3118           }
3119         }       
3120         if( useParentContext ) {
3121           output.println("         seseToIssue->"+dynInVar+" = "+
3122                          generateTemp( fsen.getParent().getfmBogus(), dynInVar, null )+";");
3123         } else {
3124           output.println("         seseToIssue->"+dynInVar+" = "+
3125                          generateTemp( fsen.getfmEnclosing(), dynInVar, null )+";");
3126         }
3127         
3128         output.println("       }");
3129         output.println("     }");
3130         
3131         // even if the value is already copied, make sure your NULL source
3132         // gets passed so child knows it already has the dynamic value
3133         output.println("     seseToIssue->"+dynInVar+"_srcSESE = "+dynInVar+"_srcSESE;");
3134       }
3135       
3136       // maintain pointers for for finding dynamic SESE 
3137       // instances from static names      
3138       SESEandAgePair p = new SESEandAgePair( fsen, 0 );
3139       if(  fsen.getParent() != null && 
3140            //!fsen.getParent().getIsCallerSESEplaceholder() &&
3141            fsen.getParent().getNeededStaticNames().contains( p ) 
3142         ) {       
3143
3144         for( int i = fsen.getOldestAgeToTrack(); i > 0; --i ) {
3145           SESEandAgePair p1 = new SESEandAgePair( fsen, i   );
3146           SESEandAgePair p2 = new SESEandAgePair( fsen, i-1 );
3147           output.println("     "+p1+" = "+p2+";");
3148         }      
3149         output.println("     "+p+" = seseToIssue;");
3150       }
3151     }
3152
3153     // if there were no outstanding dependencies, issue here
3154     output.println("     if( seseToIssue->common.unresolvedDependencies == 0 ) {");
3155     output.println("       workScheduleSubmit( (void*)seseToIssue );");
3156     output.println("     }");
3157
3158     // release this SESE for siblings to update its dependencies or,
3159     // eventually, for it to mark itself finished
3160     output.println("     pthread_mutex_unlock( &(seseToIssue->common.lock) );");
3161     output.println("   }");
3162
3163   }
3164
3165   public void generateFlatSESEExitNode( FlatMethod fm,  
3166                                         LocalityBinding lb, 
3167                                         FlatSESEExitNode fsexn, 
3168                                         PrintWriter output
3169                                       ) {
3170
3171     // if MLP flag is off, okay that SESE nodes are in IR graph, 
3172     // just skip over them and code generates exactly the same 
3173     if( !state.MLP ) {
3174       return;
3175     }
3176
3177     // get the enter node for this exit that has meta data embedded
3178     FlatSESEEnterNode fsen = fsexn.getFlatEnter();
3179
3180     // there may be an SESE in an unreachable method, skip over
3181     if( !mlpa.getAllSESEs().contains( fsen ) ) {
3182       return;
3183     }
3184
3185     // also, if we have encountered a placeholder, just jump it
3186     if( fsen.getIsCallerSESEplaceholder() ) {
3187       return;
3188     }
3189
3190     output.println("   /* SESE exiting */");
3191
3192     String com = paramsprefix+"->common";
3193
3194     // this SESE cannot be done until all of its children are done
3195     // so grab your own lock with the condition variable for watching
3196     // that the number of your running children is greater than zero    
3197     output.println("   pthread_mutex_lock( &("+com+".lock) );");
3198     output.println("   while( "+com+".numRunningChildren > 0 ) {");
3199     output.println("     pthread_cond_wait( &("+com+".runningChildrenCond), &("+com+".lock) );");
3200     output.println("   }");
3201
3202     // copy out-set from local temps into the sese record
3203     Iterator<TempDescriptor> itr = fsen.getOutVarSet().iterator();
3204     while( itr.hasNext() ) {
3205       TempDescriptor temp = itr.next();
3206
3207       // only have to do this for primitives
3208       if( !temp.getType().isPrimitive() ) {
3209         continue;
3210       }
3211
3212       // have to determine the context enclosing this sese
3213       boolean useParentContext = false;
3214
3215       if( fsen != mlpa.getMainSESE() ) {
3216         assert fsen.getParent() != null;
3217         if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3218           useParentContext = true;
3219         }
3220       }
3221
3222       String from;
3223       if( useParentContext ) {
3224         from = generateTemp( fsen.getParent().getfmBogus(), temp, null );
3225       } else {
3226         from = generateTemp( fsen.getfmEnclosing(),         temp, null );
3227       }
3228
3229       output.println("   "+paramsprefix+
3230                      "->"+temp.getSafeSymbol()+
3231                      " = "+from+";");
3232     }    
3233     
3234     // mark yourself done, your SESE data is now read-only
3235     output.println("   "+com+".doneExecuting = TRUE;");
3236     output.println("   pthread_cond_signal( &("+com+".doneCond) );");
3237     output.println("   pthread_mutex_unlock( &("+com+".lock) );");
3238
3239     // decrement dependency count for all SESE's on your forwarding list
3240     output.println("   while( !isEmpty( "+com+".forwardList ) ) {");
3241     output.println("     SESEcommon* consumer = (SESEcommon*) getItem( "+com+".forwardList );");
3242     output.println("     pthread_mutex_lock( &(consumer->lock) );");
3243     output.println("     --(consumer->unresolvedDependencies);");
3244     output.println("     if( consumer->unresolvedDependencies == 0 ) {");
3245     output.println("       workScheduleSubmit( (void*)consumer );");
3246     output.println("     }");
3247     output.println("     pthread_mutex_unlock( &(consumer->lock) );");
3248     output.println("   }");
3249     
3250     // if parent is stalling on you, let them know you're done
3251     if( fsexn.getFlatEnter() != mlpa.getMainSESE() ) {
3252       output.println("   psem_give( &("+paramsprefix+"->common.stallSem) );");
3253     }
3254
3255     // last of all, decrement your parent's number of running children    
3256     output.println("   if( "+paramsprefix+"->common.parent != NULL ) {");
3257     output.println("     pthread_mutex_lock( &("+paramsprefix+"->common.parent->lock) );");
3258     output.println("     --("+paramsprefix+"->common.parent->numRunningChildren);");
3259     output.println("     pthread_cond_signal( &("+paramsprefix+"->common.parent->runningChildrenCond) );");
3260     output.println("     pthread_mutex_unlock( &("+paramsprefix+"->common.parent->lock) );");
3261     output.println("   }");    
3262
3263     // this is a thread-only variable that can be handled when critical sese-to-sese
3264     // data has been taken care of--set sese pointer to remember self over method
3265     // calls to a non-zero, invalid address
3266     output.println("   seseCaller = (SESEcommon*) 0x1;");    
3267   }
3268
3269   public void generateFlatWriteDynamicVarNode( FlatMethod fm,  
3270                                                LocalityBinding lb, 
3271                                                FlatWriteDynamicVarNode fwdvn,
3272                                                PrintWriter output
3273                                              ) {
3274     if( !state.MLP ) {
3275       // should node should not be in an IR graph if the
3276       // MLP flag is not set
3277       throw new Error("Unexpected presence of FlatWriteDynamicVarNode");
3278     }
3279         
3280     Hashtable<TempDescriptor, VariableSourceToken> writeDynamic = 
3281       fwdvn.getVar2src();
3282
3283     assert writeDynamic != null;
3284
3285     Iterator wdItr = writeDynamic.entrySet().iterator();
3286     while( wdItr.hasNext() ) {
3287       Map.Entry           me     = (Map.Entry)           wdItr.next();
3288       TempDescriptor      refVar = (TempDescriptor)      me.getKey();
3289       VariableSourceToken vst    = (VariableSourceToken) me.getValue();
3290       
3291       FlatSESEEnterNode current = fwdvn.getEnclosingSESE();
3292
3293       // only do this if the variable in question should be tracked,
3294       // meaning that it was explicitly added to the dynamic var set
3295       if( !current.getDynamicVarSet().contains( vst.getAddrVar() ) ) {
3296         continue;
3297       }
3298
3299       SESEandAgePair instance = new SESEandAgePair( vst.getSESE(), vst.getAge() );      
3300
3301       output.println("   {");
3302
3303       if( current.equals( vst.getSESE() ) ) {
3304         // if the src comes from this SESE, it's a method local variable,
3305         // mark src pointer NULL to signify that the var is up-to-date
3306         output.println("     "+vst.getAddrVar()+"_srcSESE = NULL;");
3307
3308       } else {
3309         // otherwise we track where it will come from
3310         output.println("     "+vst.getAddrVar()+"_srcSESE = "+instance+";");    
3311         output.println("     "+vst.getAddrVar()+"_srcOffset = (int) &((("+
3312                        vst.getSESE().getSESErecordName()+"*)0)->"+vst.getAddrVar()+");");
3313       }
3314
3315       output.println("   }");
3316     }   
3317   }
3318
3319   
3320   private void generateFlatCheckNode(FlatMethod fm,  LocalityBinding lb, FlatCheckNode fcn, PrintWriter output) {
3321     if (state.CONSCHECK) {
3322       String specname=fcn.getSpec();
3323       String varname="repairstate___";
3324       output.println("{");
3325       output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
3326
3327       TempDescriptor[] temps=fcn.getTemps();
3328       String[] vars=fcn.getVars();
3329       for(int i=0; i<temps.length; i++) {
3330         output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i],lb)+";");
3331       }
3332
3333       output.println("if (doanalysis"+specname+"("+varname+")) {");
3334       output.println("free"+specname+"_state("+varname+");");
3335       output.println("} else {");
3336       output.println("/* Bad invariant */");
3337       output.println("free"+specname+"_state("+varname+");");
3338       output.println("abort_task();");
3339       output.println("}");
3340       output.println("}");
3341     }
3342   }
3343
3344   private void generateFlatCall(FlatMethod fm, LocalityBinding lb, FlatCall fc, PrintWriter output) {
3345
3346     if( state.MLP && !nonSESEpass ) {
3347       output.println("     seseCaller = (SESEcommon*)"+paramsprefix+";");
3348     }
3349
3350     MethodDescriptor md=fc.getMethod();
3351     ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? locality.getBinding(lb, fc) : md);
3352     ClassDescriptor cn=md.getClassDesc();
3353     output.println("{");
3354     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3355       if (lb!=null) {
3356         LocalityBinding fclb=locality.getBinding(lb, fc);
3357         output.print("       struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
3358       } else
3359         output.print("       struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
3360
3361       output.print(objectparams.numPointers());
3362       output.print(", "+localsprefixaddr);
3363       if (md.getThis()!=null) {
3364         output.print(", ");
3365         output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis(),lb));
3366       }
3367       if (fc.getThis()!=null&&md.getThis()==null) {
3368         System.out.println("WARNING!!!!!!!!!!!!");
3369         System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
3370       }
3371
3372
3373       for(int i=0; i<fc.numArgs(); i++) {
3374         Descriptor var=md.getParameter(i);
3375         TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
3376         if (objectparams.isParamPtr(paramtemp)) {
3377           TempDescriptor targ=fc.getArg(i);
3378           output.print(", ");
3379           TypeDescriptor td=md.getParamType(i);
3380           if (td.isTag())
3381             output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()  +" *)"+generateTemp(fm, targ,lb));
3382           else
3383             output.print("(struct "+md.getParamType(i).getSafeSymbol()  +" *)"+generateTemp(fm, targ,lb));
3384         }
3385       }
3386       output.println("};");
3387     }
3388     output.print("       ");
3389
3390
3391     if (fc.getReturnTemp()!=null)
3392       output.print(generateTemp(fm,fc.getReturnTemp(),lb)+"=");
3393
3394     /* Do we need to do virtual dispatch? */
3395     if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
3396       //no
3397       if (lb!=null) {
3398         LocalityBinding fclb=locality.getBinding(lb, fc);
3399         output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
3400       } else {
3401         output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
3402       }
3403     } else {
3404       //yes
3405       output.print("((");
3406       if (md.getReturnType().isClass()||md.getReturnType().isArray())
3407         output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
3408       else
3409         output.print(md.getReturnType().getSafeSymbol()+" ");
3410       output.print("(*)(");
3411
3412       boolean printcomma=false;
3413       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3414         if (lb!=null) {
3415           LocalityBinding fclb=locality.getBinding(lb, fc);
3416           output.print("struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
3417         } else
3418           output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
3419         printcomma=true;
3420       }
3421
3422       for(int i=0; i<objectparams.numPrimitives(); i++) {
3423         TempDescriptor temp=objectparams.getPrimitive(i);
3424         if (printcomma)
3425           output.print(", ");
3426         printcomma=true;
3427         if (temp.getType().isClass()||temp.getType().isArray())
3428           output.print("struct " + temp.getType().getSafeSymbol()+" * ");
3429         else
3430           output.print(temp.getType().getSafeSymbol());
3431       }
3432
3433
3434       if (lb!=null) {
3435         LocalityBinding fclb=locality.getBinding(lb, fc);
3436         output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])");
3437       } else
3438         output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
3439     }
3440
3441     output.print("(");
3442     boolean needcomma=false;
3443     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3444       output.print("&__parameterlist__");
3445       needcomma=true;
3446     }
3447
3448     if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
3449       if (fc.getThis()!=null) {
3450         TypeDescriptor ptd=md.getThis().getType();
3451         if (needcomma)
3452           output.print(",");
3453         if (ptd.isClass()&&!ptd.isArray())
3454           output.print("(struct "+ptd.getSafeSymbol()+" *) ");
3455         output.print(generateTemp(fm,fc.getThis(),lb));
3456         needcomma=true;
3457       }
3458     }
3459
3460     for(int i=0; i<fc.numArgs(); i++) {
3461       Descriptor var=md.getParameter(i);
3462       TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
3463       if (objectparams.isParamPrim(paramtemp)) {
3464         TempDescriptor targ=fc.getArg(i);
3465         if (needcomma)
3466           output.print(", ");
3467
3468         TypeDescriptor ptd=md.getParamType(i);
3469         if (ptd.isClass()&&!ptd.isArray())
3470           output.print("(struct "+ptd.getSafeSymbol()+" *) ");
3471         output.print(generateTemp(fm, targ,lb));
3472         needcomma=true;
3473       }
3474     }
3475     output.println(");");
3476     output.println("   }");
3477   }
3478
3479   private boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
3480     Set subclasses=typeutil.getSubClasses(thiscd);
3481     if (subclasses==null)
3482       return true;
3483     for(Iterator classit=subclasses.iterator(); classit.hasNext();) {
3484       ClassDescriptor cd=(ClassDescriptor)classit.next();
3485       Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol());
3486       for(Iterator matchit=possiblematches.iterator(); matchit.hasNext();) {
3487         MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
3488         if (md.matches(matchmd))
3489           return false;
3490       }
3491     }
3492     return true;
3493   }
3494
3495   private void generateFlatFieldNode(FlatMethod fm, LocalityBinding lb, FlatFieldNode ffn, PrintWriter output) {
3496     if (state.SINGLETM) {
3497       //single machine transactional memory case
3498       String field=ffn.getField().getSafeSymbol();
3499       String src=generateTemp(fm, ffn.getSrc(),lb);
3500       String dst=generateTemp(fm, ffn.getDst(),lb);
3501
3502       output.println(dst+"="+ src +"->"+field+ ";");
3503       if (ffn.getField().getType().isPtr()&&locality.getAtomic(lb).get(ffn).intValue()>0&&
3504           locality.getNodePreTempInfo(lb, ffn).get(ffn.getSrc())!=LocalityAnalysis.SCRATCH) {
3505         if ((dc==null)||(!state.READSET&&dc.getNeedTrans(lb, ffn))||
3506             (state.READSET&&dc.getNeedWriteTrans(lb, ffn))) {
3507           output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));");
3508         } else if (state.READSET&&dc.getNeedTrans(lb, ffn)) {
3509           output.println("TRANSREADRD("+dst+", "+dst+");");
3510         }
3511       }
3512     } else if (state.DSM) {
3513       Integer status=locality.getNodePreTempInfo(lb,ffn).get(ffn.getSrc());
3514       if (status==LocalityAnalysis.GLOBAL) {
3515         String field=ffn.getField().getSafeSymbol();
3516         String src=generateTemp(fm, ffn.getSrc(),lb);
3517         String dst=generateTemp(fm, ffn.getDst(),lb);
3518
3519         if (ffn.getField().getType().isPtr()) {
3520
3521           //TODO: Uncomment this when we have runtime support
3522           //if (ffn.getSrc()==ffn.getDst()) {
3523           //output.println("{");
3524           //output.println("void * temp="+src+";");
3525           //output.println("if (temp&0x1) {");
3526           //output.println("temp=(void *) transRead(trans, (unsigned int) temp);");
3527           //output.println(src+"->"+field+"="+temp+";");
3528           //output.println("}");
3529           //output.println(dst+"=temp;");
3530           //output.println("}");
3531           //} else {
3532           output.println(dst+"="+ src +"->"+field+ ";");
3533           //output.println("if ("+dst+"&0x1) {");
3534           output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
3535           //output.println(src+"->"+field+"="+src+"->"+field+";");
3536           //output.println("}");
3537           //}
3538         } else {
3539           output.println(dst+"="+ src+"->"+field+";");
3540         }
3541       } else if (status==LocalityAnalysis.LOCAL) {
3542         if (ffn.getField().getType().isPtr()&&
3543             ffn.getField().isGlobal()) {
3544           String field=ffn.getField().getSafeSymbol();
3545           String src=generateTemp(fm, ffn.getSrc(),lb);
3546           String dst=generateTemp(fm, ffn.getDst(),lb);
3547           output.println(dst+"="+ src +"->"+field+ ";");
3548           if (locality.getAtomic(lb).get(ffn).intValue()>0)
3549             output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
3550         } else
3551           output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
3552       } else if (status==LocalityAnalysis.EITHER) {
3553         //Code is reading from a null pointer
3554         output.println("if ("+generateTemp(fm, ffn.getSrc(),lb)+") {");
3555         output.println("#ifndef RAW");
3556         output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
3557         output.println("#endif");
3558         //This should throw a suitable null pointer error
3559         output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
3560       } else
3561         throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
3562     } else
3563       output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
3564   }
3565
3566
3567   private void generateFlatSetFieldNode(FlatMethod fm, LocalityBinding lb, FlatSetFieldNode fsfn, PrintWriter output) {
3568     if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
3569       throw new Error("Can't set array length");
3570     if (state.SINGLETM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
3571       //Single Machine Transaction Case
3572       boolean srcptr=fsfn.getSrc().getType().isPtr();
3573       String src=generateTemp(fm,fsfn.getSrc(),lb);
3574       String dst=generateTemp(fm,fsfn.getDst(),lb);
3575       output.println("//"+srcptr+" "+fsfn.getSrc().getType().isNull());
3576       if (srcptr&&!fsfn.getSrc().getType().isNull()) {
3577         output.println("{");
3578         if ((dc==null)||dc.getNeedSrcTrans(lb, fsfn)&&
3579             locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) {
3580           output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3581         } else {
3582           output.println("INTPTR srcoid=(INTPTR)"+src+";");
3583         }
3584       }
3585       if (wb.needBarrier(fsfn)&&
3586           locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getDst())!=LocalityAnalysis.SCRATCH) {
3587         output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;");
3588       }
3589       if (srcptr&!fsfn.getSrc().getType().isNull()) {
3590         output.println("*((unsigned INTPTR *)&("+dst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
3591         output.println("}");
3592       } else {
3593         output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3594       }
3595     } else if (state.DSM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
3596       Integer statussrc=locality.getNodePreTempInfo(lb,fsfn).get(fsfn.getSrc());
3597       Integer statusdst=locality.getNodeTempInfo(lb).get(fsfn).get(fsfn.getDst());
3598       boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
3599
3600       String src=generateTemp(fm,fsfn.getSrc(),lb);
3601       String dst=generateTemp(fm,fsfn.getDst(),lb);
3602       if (srcglobal) {
3603         output.println("{");
3604         output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3605       }
3606       if (statusdst.equals(LocalityAnalysis.GLOBAL)) {
3607         String glbdst=dst;
3608         //mark it dirty
3609         if (wb.needBarrier(fsfn))
3610           output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;");
3611         if (srcglobal) {
3612           output.println("*((unsigned INTPTR *)&("+glbdst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
3613         } else
3614           output.println(glbdst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3615       } else if (statusdst.equals(LocalityAnalysis.LOCAL)) {
3616         /** Check if we need to copy */
3617         output.println("if(!"+dst+"->"+localcopystr+") {");
3618         /* Link object into list */
3619         String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3620         output.println(revertptr+"=revertlist;");
3621         if (GENERATEPRECISEGC || this.state.MULTICOREGC)
3622           output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3623         else
3624           output.println("COPY_OBJ("+dst+");");
3625         output.println(dst+"->"+nextobjstr+"="+revertptr+";");
3626         output.println("revertlist=(struct ___Object___ *)"+dst+";");
3627         output.println("}");
3628         if (srcglobal)
3629           output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
3630         else
3631           output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3632       } else if (statusdst.equals(LocalityAnalysis.EITHER)) {
3633         //writing to a null...bad
3634         output.println("if ("+dst+") {");
3635         output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}");
3636         if (srcglobal)
3637           output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
3638         else
3639           output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3640       }
3641       if (srcglobal) {
3642         output.println("}");
3643       }
3644     } else {
3645       if (state.FASTCHECK) {
3646         String dst=generateTemp(fm, fsfn.getDst(),lb);
3647         output.println("if(!"+dst+"->"+localcopystr+") {");
3648         /* Link object into list */
3649         if (GENERATEPRECISEGC || this.state.MULTICOREGC)
3650           output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3651         else
3652           output.println("COPY_OBJ("+dst+");");
3653         output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
3654         output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
3655         output.println("}");
3656       }
3657       output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
3658     }
3659   }
3660
3661   private void generateFlatElementNode(FlatMethod fm, LocalityBinding lb, FlatElementNode fen, PrintWriter output) {
3662     TypeDescriptor elementtype=fen.getSrc().getType().dereference();
3663     String type="";
3664
3665     if (elementtype.isArray()||elementtype.isClass())
3666       type="void *";
3667     else
3668       type=elementtype.getSafeSymbol()+" ";
3669
3670     if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
3671       output.println("if ("+generateTemp(fm, fen.getIndex(),lb)+"< 0 | "+generateTemp(fm, fen.getIndex(),lb)+" >= "+generateTemp(fm,fen.getSrc(),lb) + "->___length___)");
3672       output.println("failedboundschk();");
3673     }
3674     if (state.SINGLETM) {
3675       //Single machine transaction case
3676       String dst=generateTemp(fm, fen.getDst(),lb);
3677       output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3678
3679       if (elementtype.isPtr()&&locality.getAtomic(lb).get(fen).intValue()>0&&
3680           locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())!=LocalityAnalysis.SCRATCH) {
3681         if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fen)||state.READSET&&dc.getNeedWriteTrans(lb, fen)) {
3682           output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));");
3683         } else if (state.READSET&&dc.getNeedTrans(lb, fen)) {
3684           output.println("TRANSREADRD("+dst+", "+dst+");");
3685         }
3686       }
3687     } else if (state.DSM) {
3688       Integer status=locality.getNodePreTempInfo(lb,fen).get(fen.getSrc());
3689       if (status==LocalityAnalysis.GLOBAL) {
3690         String dst=generateTemp(fm, fen.getDst(),lb);
3691
3692         if (elementtype.isPtr()) {
3693           output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3694           output.println("TRANSREAD("+dst+", "+dst+");");
3695         } else {
3696           output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3697         }
3698       } else if (status==LocalityAnalysis.LOCAL) {
3699         output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3700       } else if (status==LocalityAnalysis.EITHER) {
3701         //Code is reading from a null pointer
3702         output.println("if ("+generateTemp(fm, fen.getSrc(),lb)+") {");
3703         output.println("#ifndef RAW");
3704         output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
3705         output.println("#endif");
3706         //This should throw a suitable null pointer error
3707         output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3708       } else
3709         throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
3710     } else {
3711       output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3712     }
3713   }
3714
3715   private void generateFlatSetElementNode(FlatMethod fm, LocalityBinding lb, FlatSetElementNode fsen, PrintWriter output) {
3716     //TODO: need dynamic check to make sure this assignment is actually legal
3717     //Because Object[] could actually be something more specific...ie. Integer[]
3718
3719     TypeDescriptor elementtype=fsen.getDst().getType().dereference();
3720     String type="";
3721
3722     if (elementtype.isArray()||elementtype.isClass())
3723       type="void *";
3724     else
3725       type=elementtype.getSafeSymbol()+" ";
3726
3727     if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
3728       output.println("if ("+generateTemp(fm, fsen.getIndex(),lb)+"< 0 | "+generateTemp(fm, fsen.getIndex(),lb)+" >= "+generateTemp(fm,fsen.getDst(),lb) + "->___length___)");
3729       output.println("failedboundschk();");
3730     }
3731
3732     if (state.SINGLETM && locality.getAtomic(lb).get(fsen).intValue()>0) {
3733       //Transaction set element case
3734       if (wb.needBarrier(fsen)&&
3735           locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH) {
3736         output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___objstatus___))|=DIRTY;");
3737       }
3738       if (fsen.getSrc().getType().isPtr()&&!fsen.getSrc().getType().isNull()) {
3739         output.println("{");
3740         String src=generateTemp(fm, fsen.getSrc(), lb);
3741         if ((dc==null)||dc.getNeedSrcTrans(lb, fsen)&&
3742             locality.getNodePreTempInfo(lb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) {
3743           output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3744         } else {
3745           output.println("INTPTR srcoid=(INTPTR)"+src+";");
3746         }
3747         output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
3748         output.println("}");
3749       } else {
3750         output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
3751       }
3752     } else if (state.DSM && locality.getAtomic(lb).get(fsen).intValue()>0) {
3753       Integer statussrc=locality.getNodePreTempInfo(lb,fsen).get(fsen.getSrc());
3754       Integer statusdst=locality.getNodePreTempInfo(lb,fsen).get(fsen.getDst());
3755       boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
3756       boolean dstglobal=statusdst==LocalityAnalysis.GLOBAL;
3757       boolean dstlocal=statusdst==LocalityAnalysis.LOCAL;
3758
3759       if (dstglobal) {
3760         if (wb.needBarrier(fsen))
3761           output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___localcopy___))|=DIRTY;");
3762       } else if (dstlocal) {
3763         /** Check if we need to copy */
3764         String dst=generateTemp(fm, fsen.getDst(),lb);
3765         output.println("if(!"+dst+"->"+localcopystr+") {");
3766         /* Link object into list */
3767         String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3768         output.println(revertptr+"=revertlist;");
3769         if ((GENERATEPRECISEGC) || this.state.MULTICOREGC)
3770         output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3771         else
3772           output.println("COPY_OBJ("+dst+");");
3773         output.println(dst+"->"+nextobjstr+"="+revertptr+";");
3774         output.println("revertlist=(struct ___Object___ *)"+dst+";");
3775         output.println("}");
3776       } else throw new Error("Unknown array type");
3777       if (srcglobal) {
3778         output.println("{");
3779         String src=generateTemp(fm, fsen.getSrc(), lb);
3780         output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3781         output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
3782         output.println("}");
3783       } else {
3784         output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
3785       }
3786     } else {
3787       if (state.FASTCHECK) {
3788         String dst=generateTemp(fm, fsen.getDst(),lb);
3789         output.println("if(!"+dst+"->"+localcopystr+") {");
3790         /* Link object into list */
3791         if (GENERATEPRECISEGC || this.state.MULTICOREGC)
3792           output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3793         else
3794           output.println("COPY_OBJ("+dst+");");
3795         output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
3796         output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
3797         output.println("}");
3798       }
3799       output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
3800     }
3801   }
3802
3803   protected void generateFlatNew(FlatMethod fm, LocalityBinding lb, FlatNew fn, PrintWriter output) {
3804     if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
3805       //Stash pointer in case of GC
3806       String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3807       output.println(revertptr+"=revertlist;");
3808     }
3809     if (state.SINGLETM) {
3810       if (fn.getType().isArray()) {
3811         int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
3812         if (locality.getAtomic(lb).get(fn).intValue()>0) {
3813           //inside transaction
3814           output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3815         } else {
3816           //outside transaction
3817           output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3818         }
3819       } else {
3820         if (locality.getAtomic(lb).get(fn).intValue()>0) {
3821           //inside transaction
3822           output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
3823         } else {
3824           //outside transaction
3825           output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
3826         }
3827       }
3828     } else if (fn.getType().isArray()) {
3829       int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
3830       if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
3831         output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3832       } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3833         output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3834       } else {
3835         output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3836       }
3837     } else {
3838       if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
3839         output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");");
3840       } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3841         output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
3842       } else {
3843         output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
3844       }
3845     }
3846     if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
3847       String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3848       String dst=generateTemp(fm,fn.getDst(),lb);
3849       output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
3850       output.println(dst+"->"+nextobjstr+"="+revertptr+";");
3851       output.println("revertlist=(struct ___Object___ *)"+dst+";");
3852     }
3853     if (state.FASTCHECK) {
3854       String dst=generateTemp(fm,fn.getDst(),lb);
3855       output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
3856       output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
3857       output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
3858     }
3859   }
3860
3861   private void generateFlatTagDeclaration(FlatMethod fm, LocalityBinding lb, FlatTagDeclaration fn, PrintWriter output) {
3862     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3863       output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
3864     } else {
3865       output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+state.getTagId(fn.getType())+");");
3866     }
3867   }
3868
3869   private void generateFlatOpNode(FlatMethod fm, LocalityBinding lb, FlatOpNode fon, PrintWriter output) {
3870     if (fon.getRight()!=null) {
3871       if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
3872         if (fon.getLeft().getType().isLong())
3873           output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
3874         else
3875           output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned int)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
3876
3877       } else if (dc!=null) {
3878         output.print(generateTemp(fm, fon.getDest(),lb)+" = ");
3879         if (dc.getNeedLeftSrcTrans(lb, fon))
3880           output.print("("+generateTemp(fm, fon.getLeft(),lb)+"!=NULL?"+generateTemp(fm, fon.getLeft(),lb)+"->"+oidstr+":NULL)");
3881         else
3882           output.print(generateTemp(fm, fon.getLeft(),lb));
3883         output.print(fon.getOp().toString());
3884         if (dc.getNeedRightSrcTrans(lb, fon))
3885           output.println("("+generateTemp(fm, fon.getRight(),lb)+"!=NULL?"+generateTemp(fm, fon.getRight(),lb)+"->"+oidstr+":NULL);");
3886         else
3887           output.println(generateTemp(fm,fon.getRight(),lb)+";");
3888       } else
3889         output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+fon.getOp().toString()+generateTemp(fm,fon.getRight(),lb)+";");
3890     } else if (fon.getOp().getOp()==Operation.ASSIGN)
3891       output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
3892     else if (fon.getOp().getOp()==Operation.UNARYPLUS)
3893       output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
3894     else if (fon.getOp().getOp()==Operation.UNARYMINUS)
3895       output.println(generateTemp(fm, fon.getDest(),lb)+" = -"+generateTemp(fm, fon.getLeft(),lb)+";");
3896     else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
3897       output.println(generateTemp(fm, fon.getDest(),lb)+" = !"+generateTemp(fm, fon.getLeft(),lb)+";");
3898     else if (fon.getOp().getOp()==Operation.COMP)
3899       output.println(generateTemp(fm, fon.getDest(),lb)+" = ~"+generateTemp(fm, fon.getLeft(),lb)+";");
3900     else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
3901       output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+"->fses==NULL;");
3902     } else
3903       output.println(generateTemp(fm, fon.getDest(),lb)+fon.getOp().toString()+generateTemp(fm, fon.getLeft(),lb)+";");
3904   }
3905
3906   private void generateFlatCastNode(FlatMethod fm, LocalityBinding lb, FlatCastNode fcn, PrintWriter output) {
3907     /* TODO: Do type check here */
3908     if (fcn.getType().isArray()) {
3909       output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
3910     } else if (fcn.getType().isClass())
3911       output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
3912     else
3913       output.println(generateTemp(fm,fcn.getDst(),lb)+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc(),lb)+";");
3914   }
3915
3916   private void generateFlatLiteralNode(FlatMethod fm, LocalityBinding lb, FlatLiteralNode fln, PrintWriter output) {
3917     if (fln.getValue()==null)
3918       output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
3919     else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
3920       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3921         if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
3922           //Stash pointer in case of GC
3923           String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3924           output.println(revertptr+"=revertlist;");
3925         }
3926         output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
3927         if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
3928           //Stash pointer in case of GC
3929           String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3930           output.println("revertlist="+revertptr+";");
3931         }
3932       } else {
3933         output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
3934       }
3935     } else if (fln.getType().isBoolean()) {
3936       if (((Boolean)fln.getValue()).booleanValue())
3937         output.println(generateTemp(fm, fln.getDst(),lb)+"=1;");
3938       else
3939         output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
3940     } else if (fln.getType().isChar()) {
3941       String st=FlatLiteralNode.escapeString(fln.getValue().toString());
3942       output.println(generateTemp(fm, fln.getDst(),lb)+"='"+st+"';");
3943     } else if (fln.getType().isLong()) {
3944       output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+"LL;");
3945     } else
3946       output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+";");
3947   }
3948
3949   protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) {
3950     if (frn.getReturnTemp()!=null) {
3951       if (frn.getReturnTemp().getType().isPtr())
3952         output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";");
3953       else
3954         output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";");
3955     } else {
3956       output.println("return;");
3957     }
3958   }
3959
3960   protected void generateStoreFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
3961     output.println("STOREANDBRANCH(!"+generateTemp(fm, fcb.getTest(),lb)+", "+label+");");
3962   }
3963
3964   protected void generateFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
3965     output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") goto "+label+";");
3966   }
3967
3968   /** This method generates header information for the method or
3969    * task referenced by the Descriptor des. */
3970   private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) {
3971     generateHeader(fm, lb, des, output, false);
3972   }
3973
3974   private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output, boolean addSESErecord) {
3975     /* Print header */
3976     ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : des);
3977     MethodDescriptor md=null;
3978     TaskDescriptor task=null;
3979     if (des instanceof MethodDescriptor)
3980       md=(MethodDescriptor) des;
3981     else
3982       task=(TaskDescriptor) des;
3983
3984     ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
3985
3986     if (md!=null&&md.getReturnType()!=null) {
3987       if (md.getReturnType().isClass()||md.getReturnType().isArray())
3988         output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
3989       else
3990         output.print(md.getReturnType().getSafeSymbol()+" ");
3991     } else
3992       //catch the constructor case
3993       output.print("void ");
3994     if (md!=null) {
3995       if (state.DSM||state.SINGLETM) {
3996         output.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
3997       } else
3998         output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
3999     } else
4000       output.print(task.getSafeSymbol()+"(");
4001     
4002     boolean printcomma=false;
4003     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4004       if (md!=null) {
4005         if (state.DSM||state.SINGLETM) {
4006           output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
4007         } else
4008           output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
4009       } else
4010         output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
4011       printcomma=true;
4012     }
4013
4014     if (md!=null) {
4015       /* Method */
4016       for(int i=0; i<objectparams.numPrimitives(); i++) {
4017         TempDescriptor temp=objectparams.getPrimitive(i);
4018         if (printcomma)
4019           output.print(", ");
4020         printcomma=true;
4021         if (temp.getType().isClass()||temp.getType().isArray())
4022           output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
4023         else
4024           output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
4025       }
4026       output.println(") {");
4027     } else if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
4028       /* Imprecise Task */
4029       output.println("void * parameterarray[]) {");
4030       /* Unpack variables */
4031       for(int i=0; i<objectparams.numPrimitives(); i++) {
4032         TempDescriptor temp=objectparams.getPrimitive(i);
4033         output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
4034       }
4035       for(int i=0; i<fm.numTags(); i++) {
4036         TempDescriptor temp=fm.getTag(i);
4037         int offset=i+objectparams.numPrimitives();
4038         output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
4039       }
4040
4041       if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
4042         maxtaskparams=objectparams.numPrimitives()+fm.numTags();
4043     } else output.println(") {");
4044   }
4045
4046   public void generateFlatFlagActionNode(FlatMethod fm, LocalityBinding lb, FlatFlagActionNode ffan, PrintWriter output) {
4047     output.println("/* FlatFlagActionNode */");
4048
4049
4050     /* Process tag changes */
4051     Relation tagsettable=new Relation();
4052     Relation tagcleartable=new Relation();
4053
4054     Iterator tagsit=ffan.getTempTagPairs();
4055     while (tagsit.hasNext()) {
4056       TempTagPair ttp=(TempTagPair) tagsit.next();
4057       TempDescriptor objtmp=ttp.getTemp();
4058       TagDescriptor tag=ttp.getTag();
4059       TempDescriptor tagtmp=ttp.getTagTemp();
4060       boolean tagstatus=ffan.getTagChange(ttp);
4061       if (tagstatus) {
4062         tagsettable.put(objtmp, tagtmp);
4063       } else {
4064         tagcleartable.put(objtmp, tagtmp);
4065       }
4066     }
4067
4068
4069     Hashtable flagandtable=new Hashtable();
4070     Hashtable flagortable=new Hashtable();
4071
4072     /* Process flag changes */
4073     Iterator flagsit=ffan.getTempFlagPairs();
4074     while(flagsit.hasNext()) {
4075       TempFlagPair tfp=(TempFlagPair)flagsit.next();
4076       TempDescriptor temp=tfp.getTemp();
4077       Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
4078       FlagDescriptor flag=tfp.getFlag();
4079       if (flag==null) {
4080         //Newly allocate objects that don't set any flags case
4081         if (flagortable.containsKey(temp)) {
4082           throw new Error();
4083         }
4084         int mask=0;
4085         flagortable.put(temp,new Integer(mask));
4086       } else {
4087         int flagid=1<<((Integer)flagtable.get(flag)).intValue();
4088         boolean flagstatus=ffan.getFlagChange(tfp);
4089         if (flagstatus) {
4090           int mask=0;
4091           if (flagortable.containsKey(temp)) {
4092             mask=((Integer)flagortable.get(temp)).intValue();
4093           }
4094           mask|=flagid;
4095           flagortable.put(temp,new Integer(mask));
4096         } else {
4097           int mask=0xFFFFFFFF;
4098           if (flagandtable.containsKey(temp)) {
4099             mask=((Integer)flagandtable.get(temp)).intValue();
4100           }
4101           mask&=(0xFFFFFFFF^flagid);
4102           flagandtable.put(temp,new Integer(mask));
4103         }
4104       }
4105     }
4106
4107
4108     HashSet flagtagset=new HashSet();
4109     flagtagset.addAll(flagortable.keySet());
4110     flagtagset.addAll(flagandtable.keySet());
4111     flagtagset.addAll(tagsettable.keySet());
4112     flagtagset.addAll(tagcleartable.keySet());
4113
4114     Iterator ftit=flagtagset.iterator();
4115     while(ftit.hasNext()) {
4116       TempDescriptor temp=(TempDescriptor)ftit.next();
4117
4118
4119       Set tagtmps=tagcleartable.get(temp);
4120       if (tagtmps!=null) {
4121         Iterator tagit=tagtmps.iterator();
4122         while(tagit.hasNext()) {
4123           TempDescriptor tagtmp=(TempDescriptor)tagit.next();
4124           if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
4125             output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4126           else
4127             output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4128         }
4129       }
4130
4131       tagtmps=tagsettable.get(temp);
4132       if (tagtmps!=null) {
4133         Iterator tagit=tagtmps.iterator();
4134         while(tagit.hasNext()) {
4135           TempDescriptor tagtmp=(TempDescriptor)tagit.next();
4136           if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
4137             output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4138           else
4139             output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp, lb)+", "+generateTemp(fm,tagtmp, lb)+");");
4140         }
4141       }
4142
4143       int ormask=0;
4144       int andmask=0xFFFFFFF;
4145
4146       if (flagortable.containsKey(temp))
4147         ormask=((Integer)flagortable.get(temp)).intValue();
4148       if (flagandtable.containsKey(temp))
4149         andmask=((Integer)flagandtable.get(temp)).intValue();
4150       generateFlagOrAnd(ffan, fm, lb, temp, output, ormask, andmask);
4151       generateObjectDistribute(ffan, fm, lb, temp, output);
4152     }
4153   }
4154
4155   protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp,
4156                                    PrintWriter output, int ormask, int andmask) {
4157     if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
4158       output.println("flagorandinit("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
4159     } else {
4160       output.println("flagorand("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
4161     }
4162   }
4163
4164   protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, PrintWriter output) {
4165     output.println("enqueueObject("+generateTemp(fm, temp, lb)+");");
4166   }
4167
4168   void generateOptionalHeader(PrintWriter headers) {
4169
4170     //GENERATE HEADERS
4171     headers.println("#include \"task.h\"\n\n");
4172     headers.println("#ifndef _OPTIONAL_STRUCT_");
4173     headers.println("#define _OPTIONAL_STRUCT_");
4174
4175     //STRUCT PREDICATEMEMBER
4176     headers.println("struct predicatemember{");
4177     headers.println("int type;");
4178     headers.println("int numdnfterms;");
4179     headers.println("int * flags;");
4180     headers.println("int numtags;");
4181     headers.println("int * tags;\n};\n\n");
4182
4183     //STRUCT OPTIONALTASKDESCRIPTOR
4184     headers.println("struct optionaltaskdescriptor{");
4185     headers.println("struct taskdescriptor * task;");
4186     headers.println("int index;");
4187     headers.println("int numenterflags;");
4188     headers.println("int * enterflags;");
4189     headers.println("int numpredicatemembers;");
4190     headers.println("struct predicatemember ** predicatememberarray;");
4191     headers.println("};\n\n");
4192
4193     //STRUCT TASKFAILURE
4194     headers.println("struct taskfailure {");
4195     headers.println("struct taskdescriptor * task;");
4196     headers.println("int index;");
4197     headers.println("int numoptionaltaskdescriptors;");
4198     headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
4199
4200     //STRUCT FSANALYSISWRAPPER
4201     headers.println("struct fsanalysiswrapper{");
4202     headers.println("int  flags;");
4203     headers.println("int numtags;");
4204     headers.println("int * tags;");
4205     headers.println("int numtaskfailures;");
4206     headers.println("struct taskfailure ** taskfailurearray;");
4207     headers.println("int numoptionaltaskdescriptors;");
4208     headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
4209
4210     //STRUCT CLASSANALYSISWRAPPER
4211     headers.println("struct classanalysiswrapper{");
4212     headers.println("int type;");
4213     headers.println("int numotd;");
4214     headers.println("struct optionaltaskdescriptor ** otdarray;");
4215     headers.println("int numfsanalysiswrappers;");
4216     headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
4217
4218     headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
4219
4220     Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
4221     while(taskit.hasNext()) {
4222       TaskDescriptor td=(TaskDescriptor)taskit.next();
4223       headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
4224     }
4225
4226   }
4227
4228   //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
4229   int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
4230     int predicateindex = 0;
4231     //iterate through the classes concerned by the predicate
4232     Set c_vard = predicate.vardescriptors;
4233     Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
4234     int current_slot=0;
4235
4236     for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext();) {
4237       VarDescriptor vard = (VarDescriptor)vard_it.next();
4238       TypeDescriptor typed = vard.getType();
4239
4240       //generate for flags
4241       HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
4242       output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4243       int numberterms=0;
4244       if (fen_hashset!=null) {
4245         for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext();) {
4246           FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
4247           if (fen!=null) {
4248             DNFFlag dflag=fen.getDNF();
4249             numberterms+=dflag.size();
4250
4251             Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
4252
4253             for(int j=0; j<dflag.size(); j++) {
4254               if (j!=0)
4255                 output.println(",");
4256               Vector term=dflag.get(j);
4257               int andmask=0;
4258               int checkmask=0;
4259               for(int k=0; k<term.size(); k++) {
4260                 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
4261                 FlagDescriptor fd=dfa.getFlag();
4262                 boolean negated=dfa.getNegated();
4263                 int flagid=1<<((Integer)flags.get(fd)).intValue();
4264                 andmask|=flagid;
4265                 if (!negated)
4266                   checkmask|=flagid;
4267               }
4268               output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
4269             }
4270           }
4271         }
4272       }
4273       output.println("};\n");
4274
4275       //generate for tags
4276       TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
4277       output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4278       int numtags = 0;
4279       if (tagel!=null) {
4280         for(int j=0; j<tagel.numTags(); j++) {
4281           if (j!=0)
4282             output.println(",");
4283           TempDescriptor tmp=tagel.getTemp(j);
4284           if (!slotnumber.containsKey(tmp)) {
4285             Integer slotint=new Integer(current_slot++);
4286             slotnumber.put(tmp,slotint);
4287           }
4288           int slot=slotnumber.get(tmp).intValue();
4289           output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
4290         }
4291         numtags = tagel.numTags();
4292       }
4293       output.println("};");
4294
4295       //store the result into a predicatemember struct
4296       output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
4297       output.println("/*type*/"+typed.getClassDesc().getId()+",");
4298       output.println("/* number of dnf terms */"+numberterms+",");
4299       output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4300       output.println("/* number of tag */"+numtags+",");
4301       output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4302       output.println("};\n");
4303       predicateindex++;
4304     }
4305
4306
4307     //generate an array that stores the entire predicate
4308     output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4309     for( int j = 0; j<predicateindex; j++) {
4310       if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4311       else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4312     }
4313     output.println("};\n");
4314     return predicateindex;
4315   }
4316
4317
4318   void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
4319     generateOptionalHeader(headers);
4320     //GENERATE STRUCTS
4321     output.println("#include \"optionalstruct.h\"\n\n");
4322     output.println("#include \"stdlib.h\"\n");
4323
4324     HashSet processedcd = new HashSet();
4325     int maxotd=0;
4326     Enumeration e = safeexecution.keys();
4327     while (e.hasMoreElements()) {
4328       int numotd=0;
4329       //get the class
4330       ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
4331       Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp);       //will be used several times
4332
4333       //Generate the struct of optionals
4334       Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
4335       numotd = c_otd.size();
4336       if(maxotd<numotd) maxotd = numotd;
4337       if( !c_otd.isEmpty() ) {
4338         for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
4339           OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
4340
4341           //generate the int arrays for the predicate
4342           Predicate predicate = otd.predicate;
4343           int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
4344           TreeSet<Integer> fsset=new TreeSet<Integer>();
4345           //iterate through possible FSes corresponding to
4346           //the state when entering
4347
4348           for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext();) {
4349             FlagState fs = (FlagState)fses.next();
4350             int flagid=0;
4351             for(Iterator flags = fs.getFlags(); flags.hasNext();) {
4352               FlagDescriptor flagd = (FlagDescriptor)flags.next();
4353               int id=1<<((Integer)flaginfo.get(flagd)).intValue();
4354               flagid|=id;
4355             }
4356             fsset.add(new Integer(flagid));
4357             //tag information not needed because tag
4358             //changes are not tolerated.
4359           }
4360
4361           output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4362           boolean needcomma=false;
4363           for(Iterator<Integer> it=fsset.iterator(); it.hasNext();) {
4364             if(needcomma)
4365               output.print(", ");
4366             output.println(it.next());
4367           }
4368
4369           output.println("};\n");
4370
4371
4372           //generate optionaltaskdescriptor that actually
4373           //includes exit fses, predicate and the task
4374           //concerned
4375           output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
4376           output.println("&task_"+otd.td.getSafeSymbol()+",");
4377           output.println("/*index*/"+otd.getIndex()+",");
4378           output.println("/*number of enter flags*/"+fsset.size()+",");
4379           output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4380           output.println("/*number of members */"+predicateindex+",");
4381           output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4382           output.println("};\n");
4383         }
4384       } else
4385         continue;
4386       // if there are no optionals, there is no need to build the rest of the struct
4387
4388       output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
4389       c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
4390       if( !c_otd.isEmpty() ) {
4391         boolean needcomma=false;
4392         for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
4393           OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
4394           if(needcomma)
4395             output.println(",");
4396           needcomma=true;
4397           output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4398         }
4399       }
4400       output.println("};\n");
4401
4402       //get all the possible flagstates reachable by an object
4403       Hashtable hashtbtemp = safeexecution.get(cdtemp);
4404       int fscounter = 0;
4405       TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
4406       fsts.addAll(hashtbtemp.keySet());
4407       for(Iterator fsit=fsts.iterator(); fsit.hasNext();) {
4408         FlagState fs = (FlagState)fsit.next();
4409         fscounter++;
4410
4411         //get the set of OptionalTaskDescriptors corresponding
4412         HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
4413         //iterate through the OptionalTaskDescriptors and
4414         //store the pointers to the optionals struct (see on
4415         //top) into an array
4416
4417         output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
4418         for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext();) {
4419           OptionalTaskDescriptor mm = mos.next();
4420           if(!mos.hasNext())
4421             output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
4422           else
4423             output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4424         }
4425
4426         output.println("};\n");
4427
4428         //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
4429
4430         int flagid=0;
4431         for(Iterator flags = fs.getFlags(); flags.hasNext();) {
4432           FlagDescriptor flagd = (FlagDescriptor)flags.next();
4433           int id=1<<((Integer)flaginfo.get(flagd)).intValue();
4434           flagid|=id;
4435         }
4436
4437         //process tag information
4438
4439         int tagcounter = 0;
4440         boolean first = true;
4441         Enumeration tag_enum = fs.getTags();
4442         output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
4443         while(tag_enum.hasMoreElements()) {
4444           tagcounter++;
4445           TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
4446           if(first==true)
4447             first = false;
4448           else
4449             output.println(", ");
4450           output.println("/*tagid*/"+state.getTagId(tagd));
4451         }
4452         output.println("};");
4453
4454         Set<TaskIndex> tiset=sa.getTaskIndex(fs);
4455         for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
4456           TaskIndex ti=itti.next();
4457           if (ti.isRuntime())
4458             continue;
4459
4460           Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
4461
4462           output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
4463           boolean needcomma=false;
4464           for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext();) {
4465             OptionalTaskDescriptor otd=otdit.next();
4466             if(needcomma)
4467               output.print(", ");
4468             needcomma=true;
4469             output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4470           }
4471           output.println("};");
4472
4473           output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
4474           output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
4475           output.print(ti.getIndex()+", ");
4476           output.print(otdset.size()+", ");
4477           output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
4478           output.println("};");
4479         }
4480
4481         tiset=sa.getTaskIndex(fs);
4482         boolean needcomma=false;
4483         int runtimeti=0;
4484         output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
4485         for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
4486           TaskIndex ti=itti.next();
4487           if (ti.isRuntime()) {
4488             runtimeti++;
4489             continue;
4490           }
4491           if (needcomma)
4492             output.print(", ");
4493           needcomma=true;
4494           output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
4495         }
4496         output.println("};\n");
4497
4498         //Store the result in fsanalysiswrapper
4499
4500         output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
4501         output.println("/*flag*/"+flagid+",");
4502         output.println("/* number of tags*/"+tagcounter+",");
4503         output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
4504         output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
4505         output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
4506         output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
4507         output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
4508         output.println("};\n");
4509
4510       }
4511
4512       //Build the array of fsanalysiswrappers
4513       output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
4514       boolean needcomma=false;
4515       for(int i = 0; i<fscounter; i++) {
4516         if (needcomma) output.print(",");
4517         output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
4518         needcomma=true;
4519       }
4520       output.println("};");
4521
4522       //Build the classanalysiswrapper referring to the previous array
4523       output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
4524       output.println("/*type*/"+cdtemp.getId()+",");
4525       output.println("/*numotd*/"+numotd+",");
4526       output.println("otdarray"+cdtemp.getSafeSymbol()+",");
4527       output.println("/* number of fsanalysiswrappers */"+fscounter+",");
4528       output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
4529       processedcd.add(cdtemp);
4530     }
4531
4532     //build an array containing every classes for which code has been build
4533     output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
4534     for(int i=0; i<state.numClasses(); i++) {
4535       ClassDescriptor cn=cdarray[i];
4536       if (i>0)
4537         output.print(", ");
4538       if ((cn != null) && (processedcd.contains(cn)))
4539         output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
4540       else
4541         output.print("NULL");
4542     }
4543     output.println("};");
4544
4545     output.println("#define MAXOTD "+maxotd);
4546     headers.println("#endif");
4547   }
4548
4549   public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
4550     Relation r=new Relation();
4551     for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext();) {
4552       OptionalTaskDescriptor otd=otdit.next();
4553       TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
4554       r.put(ti, otd);
4555     }
4556
4557     LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
4558     for(Iterator it=r.keySet().iterator(); it.hasNext();) {
4559       Set s=r.get(it.next());
4560       for(Iterator it2=s.iterator(); it2.hasNext();) {
4561         OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
4562         l.add(otd);
4563       }
4564     }
4565
4566     return l;
4567   }
4568
4569   protected void outputTransCode(PrintWriter output) {
4570   }
4571 }
4572
4573
4574
4575
4576
4577