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