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