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