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