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