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