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