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