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