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