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