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