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