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