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