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