found a bug, wasn't returning pointer at end of poolcreate--pool allocation doesn...
[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("   CP_LOGEVENT( CP_EVENTID_TASKEXECUTE, CP_EVENTTYPE_BEGIN );");
2414     }
2415
2416     HashSet<FlatNode> exitset=new HashSet<FlatNode>();
2417     exitset.add(seseExit);    
2418     generateCode(fsen.getNext(0), fm, null, exitset, output, true);
2419     output.println("}\n\n");
2420     
2421   }
2422
2423
2424   // when a new mlp thread is created for an issued SESE, it is started
2425   // by running this method which blocks on a cond variable until
2426   // it is allowed to transition to execute.  Then a case statement
2427   // allows it to invoke the method with the proper SESE body, and after
2428   // exiting the SESE method, executes proper SESE exit code before the
2429   // thread can be destroyed
2430   private void generateSESEinvocationMethod(PrintWriter outmethodheader,
2431                                             PrintWriter outmethod
2432                                             ) {
2433
2434     outmethodheader.println("void* invokeSESEmethod( void* seseRecord );");
2435     outmethod.println(      "void* invokeSESEmethod( void* seseRecord ) {");
2436     outmethod.println(      "  int status;");
2437     outmethod.println(      "  char errmsg[128];");
2438
2439     // generate a case for each SESE class that can be invoked
2440     outmethod.println(      "  switch( *((int*)seseRecord) ) {");
2441     outmethod.println(      "    ");
2442     Iterator<FlatSESEEnterNode> seseit;
2443     if(state.MLP){
2444       seseit=mlpa.getAllSESEs().iterator();
2445     }else{
2446       seseit=oooa.getAllSESEs().iterator();
2447     }
2448     while(seseit.hasNext()){
2449       FlatSESEEnterNode fsen = seseit.next();
2450
2451       outmethod.println(    "    /* "+fsen.getPrettyIdentifier()+" */");
2452       outmethod.println(    "    case "+fsen.getIdentifier()+":");
2453       outmethod.println(    "      "+fsen.getSESEmethodName()+"( seseRecord );");  
2454       
2455       if( (state.MLP && fsen.equals( mlpa.getMainSESE() )) || 
2456           (state.OOOJAVA && fsen.equals( oooa.getMainSESE() ))
2457       ) {
2458         outmethod.println(  "      /* work scheduler works forever, explicitly exit */");
2459         outmethod.println(  "      CP_EXIT();");
2460         outmethod.println(  "      CP_DUMP();");        
2461         outmethod.println(  "      workScheduleExit();");
2462         outmethod.println(  "      exit( 0 );");
2463       }
2464
2465       outmethod.println(    "      break;");
2466       outmethod.println(    "");
2467     }
2468
2469     // default case should never be taken, error out
2470     outmethod.println(      "    default:");
2471     outmethod.println(      "      printf(\"Error: unknown SESE class ID in invoke method.\\n\");");
2472     outmethod.println(      "      exit(-30);");
2473     outmethod.println(      "      break;");
2474     outmethod.println(      "  }");
2475     outmethod.println(      "  return NULL;");
2476     outmethod.println(      "}\n\n");
2477   }
2478
2479
2480   protected void generateCode(FlatNode first,
2481                               FlatMethod fm,
2482                               LocalityBinding lb,
2483                               Set<FlatNode> stopset,
2484                               PrintWriter output, boolean firstpass) {
2485
2486     /* Assign labels to FlatNode's if necessary.*/
2487
2488     Hashtable<FlatNode, Integer> nodetolabel;
2489
2490     if (state.DELAYCOMP&&!firstpass)
2491       nodetolabel=dcassignLabels(first, stopset);      
2492     else
2493       nodetolabel=assignLabels(first, stopset);      
2494     
2495     Set<FlatNode> storeset=null;
2496     HashSet<FlatNode> genset=null;
2497     HashSet<FlatNode> refset=null;
2498     Set<FlatNode> unionset=null;
2499
2500     if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
2501       storeset=delaycomp.livecode(lb);
2502       genset=new HashSet<FlatNode>();
2503       if (state.STMARRAY&&!state.DUALVIEW) {
2504         refset=new HashSet<FlatNode>();
2505         refset.addAll(delaycomp.getDeref(lb));
2506         refset.removeAll(delaycomp.getCannotDelay(lb));
2507         refset.removeAll(delaycomp.getOther(lb));
2508       }
2509       if (firstpass) {
2510         genset.addAll(delaycomp.getCannotDelay(lb));
2511         genset.addAll(delaycomp.getOther(lb));
2512       } else {
2513         genset.addAll(delaycomp.getNotReady(lb));
2514         if (state.STMARRAY&&!state.DUALVIEW) {
2515           genset.removeAll(refset);
2516         }
2517       }
2518       unionset=new HashSet<FlatNode>();
2519       unionset.addAll(storeset);
2520       unionset.addAll(genset);
2521       if (state.STMARRAY&&!state.DUALVIEW)
2522         unionset.addAll(refset);
2523     }
2524     
2525     /* Do the actual code generation */
2526     FlatNode current_node=null;
2527     HashSet tovisit=new HashSet();
2528     HashSet visited=new HashSet();
2529     if (!firstpass)
2530       tovisit.add(first.getNext(0));
2531     else
2532       tovisit.add(first);
2533     while(current_node!=null||!tovisit.isEmpty()) {
2534       if (current_node==null) {
2535         current_node=(FlatNode)tovisit.iterator().next();
2536         tovisit.remove(current_node);
2537       } else if (tovisit.contains(current_node)) {
2538         tovisit.remove(current_node);
2539       }
2540       visited.add(current_node);
2541       if (nodetolabel.containsKey(current_node)) {
2542         output.println("L"+nodetolabel.get(current_node)+":");
2543       }
2544       if (state.INSTRUCTIONFAILURE) {
2545         if (state.THREAD||state.DSM||state.SINGLETM) {
2546           output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
2547         } else
2548           output.println("if ((--instructioncount)==0) injectinstructionfailure();");
2549       }
2550       if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
2551         output.print("   ");
2552         if (!state.DELAYCOMP||firstpass) {
2553           generateFlatNode(fm, lb, current_node, output);
2554         } else {
2555           //store primitive variables in out set
2556           AtomicRecord ar=atomicmethodmap.get((FlatAtomicEnterNode)first);
2557           Set<TempDescriptor> liveout=ar.liveout;
2558           for(Iterator<TempDescriptor> tmpit=liveout.iterator();tmpit.hasNext();) {
2559             TempDescriptor tmp=tmpit.next();
2560             output.println("primitives->"+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2561           }
2562         }
2563         if ((state.MLP || state.OOOJAVA) && stopset!=null) {
2564           assert first.getPrev( 0 ) instanceof FlatSESEEnterNode;
2565           assert current_node       instanceof FlatSESEExitNode;
2566           FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev( 0 );
2567           FlatSESEExitNode  fsxn = (FlatSESEExitNode)  current_node;
2568           assert fsen.getFlatExit().equals( fsxn );
2569           assert fsxn.getFlatEnter().equals( fsen );
2570         }
2571         if (current_node.kind()!=FKind.FlatReturnNode) {
2572           output.println("   return;");
2573         }
2574         current_node=null;
2575       } else if(current_node.numNext()==1) {
2576         FlatNode nextnode;
2577         if ((state.MLP|| state.OOOJAVA) && 
2578             current_node.kind()==FKind.FlatSESEEnterNode && 
2579             !((FlatSESEEnterNode)current_node).getIsCallerSESEplaceholder()
2580            ) {
2581           FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
2582           generateFlatNode(fm, lb, current_node, output);
2583           nextnode=fsen.getFlatExit().getNext(0);
2584         } else if (state.DELAYCOMP) {
2585           boolean specialprimitive=false;
2586           //skip literals...no need to add extra overhead
2587           if (storeset!=null&&storeset.contains(current_node)&&current_node.kind()==FKind.FlatLiteralNode) {
2588             TypeDescriptor typedesc=((FlatLiteralNode)current_node).getType();
2589             if (!typedesc.isClass()&&!typedesc.isArray()) {
2590               specialprimitive=true;
2591             }
2592           }
2593
2594           if (genset==null||genset.contains(current_node)||specialprimitive)
2595             generateFlatNode(fm, lb, current_node, output);
2596           if (state.STMARRAY&&!state.DUALVIEW&&refset!=null&&refset.contains(current_node)) {
2597             //need to acquire lock
2598             handleArrayDeref(fm, lb, current_node, output, firstpass);
2599           }
2600           if (storeset!=null&&storeset.contains(current_node)&&!specialprimitive) {
2601             TempDescriptor wrtmp=current_node.writesTemps()[0];
2602             if (firstpass) {
2603               //need to store value written by previous node
2604               if (wrtmp.getType().isPtr()) {
2605                 //only lock the objects that may actually need locking
2606                 if (recorddc.getNeedTrans(lb, current_node)&&
2607                     (!state.STMARRAY||state.DUALVIEW||!wrtmp.getType().isArray()||
2608                      wrtmp.getType().getSymbol().equals(TypeUtil.ObjectClass))) {
2609                   output.println("STOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2610                 } else {
2611                   output.println("STOREPTRNOLOCK("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2612                 }
2613               } else {
2614                 output.println("STORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");/* "+current_node.nodeid+" */");
2615               }
2616             } else {
2617               //need to read value read by previous node
2618               if (wrtmp.getType().isPtr()) {
2619                 output.println("RESTOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2620               } else {
2621                 output.println("RESTORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+"); /* "+current_node.nodeid+" */");               
2622               }
2623             }
2624           }
2625           nextnode=current_node.getNext(0);
2626         } else {
2627           output.print("   ");
2628           generateFlatNode(fm, lb, current_node, output);
2629           nextnode=current_node.getNext(0);
2630         }
2631         if (visited.contains(nextnode)) {
2632           output.println("goto L"+nodetolabel.get(nextnode)+";");
2633           current_node=null;
2634         } else 
2635           current_node=nextnode;
2636       } else if (current_node.numNext()==2) {
2637         /* Branch */
2638         if (state.DELAYCOMP) {
2639           boolean computeside=false;
2640           if (firstpass) {
2641             //need to record which way it should go
2642             if (genset==null||genset.contains(current_node)) {
2643               if (storeset!=null&&storeset.contains(current_node)) {
2644                 //need to store which way branch goes
2645                 generateStoreFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2646               } else
2647                 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2648             } else {
2649               //which side to execute
2650               computeside=true;
2651             }
2652           } else {
2653             if (genset.contains(current_node)) {
2654               generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);             
2655             } else if (storeset.contains(current_node)) {
2656               //need to do branch
2657               branchanalysis.generateGroupCode(current_node, output, nodetolabel);
2658             } else {
2659               //which side to execute
2660               computeside=true;
2661             }
2662           }
2663           if (computeside) {
2664             Set<FlatNode> leftset=DelayComputation.getNext(current_node, 0, unionset, lb,locality, true);
2665             int branch=0;
2666             if (leftset.size()==0)
2667               branch=1;
2668             if (visited.contains(current_node.getNext(branch))) {
2669               //already visited -- build jump
2670               output.println("goto L"+nodetolabel.get(current_node.getNext(branch))+";");
2671               current_node=null;
2672             } else {
2673               current_node=current_node.getNext(branch);
2674             }
2675           } else {
2676             if (!visited.contains(current_node.getNext(1)))
2677               tovisit.add(current_node.getNext(1));
2678             if (visited.contains(current_node.getNext(0))) {
2679               output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2680               current_node=null;
2681             } else 
2682               current_node=current_node.getNext(0);
2683           }
2684         } else {
2685           output.print("   ");  
2686           generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2687           if (!visited.contains(current_node.getNext(1)))
2688             tovisit.add(current_node.getNext(1));
2689           if (visited.contains(current_node.getNext(0))) {
2690             output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2691             current_node=null;
2692           } else 
2693             current_node=current_node.getNext(0);
2694         }
2695       } else throw new Error();
2696     }
2697   }
2698
2699   protected void handleArrayDeref(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output, boolean firstpass) {
2700     if (fn.kind()==FKind.FlatSetElementNode) {
2701       FlatSetElementNode fsen=(FlatSetElementNode) fn;
2702       String dst=generateTemp(fm, fsen.getDst(), lb);
2703       String src=generateTemp(fm, fsen.getSrc(), lb);
2704       String index=generateTemp(fm, fsen.getIndex(), lb);      
2705       TypeDescriptor elementtype=fsen.getDst().getType().dereference();
2706       String type="";
2707       if (elementtype.isArray()||elementtype.isClass())
2708         type="void *";
2709       else
2710         type=elementtype.getSafeSymbol()+" ";
2711       if (firstpass) {
2712         output.println("STOREARRAY("+dst+","+index+","+type+")");
2713       } else {
2714         output.println("{");
2715         output.println("  struct ArrayObject *array;");
2716         output.println("  int index;");
2717         output.println("  RESTOREARRAY(array,index);");
2718         output.println("  (("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index]="+src+";");
2719         output.println("}");
2720       }
2721     } else if (fn.kind()==FKind.FlatElementNode) {
2722       FlatElementNode fen=(FlatElementNode) fn;
2723       String src=generateTemp(fm, fen.getSrc(), lb);
2724       String index=generateTemp(fm, fen.getIndex(), lb);
2725       TypeDescriptor elementtype=fen.getSrc().getType().dereference();
2726       String dst=generateTemp(fm, fen.getDst(), lb);
2727       String type="";
2728       if (elementtype.isArray()||elementtype.isClass())
2729         type="void *";
2730       else
2731         type=elementtype.getSafeSymbol()+" ";
2732       if (firstpass) {
2733         output.println("STOREARRAY("+src+","+index+","+type+")");
2734       } else {
2735         output.println("{");
2736         output.println("  struct ArrayObject *array;");
2737         output.println("  int index;");
2738         output.println("  RESTOREARRAY(array,index);");
2739         output.println("  "+dst+"=(("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index];");
2740         output.println("}");
2741       }
2742     }
2743   }
2744   /** Special label assignment for delaycomputation */
2745   protected Hashtable<FlatNode, Integer> dcassignLabels(FlatNode first, Set<FlatNode> lastset) {
2746     HashSet tovisit=new HashSet();
2747     HashSet visited=new HashSet();
2748     int labelindex=0;
2749     Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2750
2751     //Label targets of branches
2752     Set<FlatNode> targets=branchanalysis.getTargets();
2753     for(Iterator<FlatNode> it=targets.iterator();it.hasNext();) {
2754       nodetolabel.put(it.next(), new Integer(labelindex++));
2755     }
2756
2757
2758     tovisit.add(first);
2759     /*Assign labels first.  A node needs a label if the previous
2760      * node has two exits or this node is a join point. */
2761
2762     while(!tovisit.isEmpty()) {
2763       FlatNode fn=(FlatNode)tovisit.iterator().next();
2764       tovisit.remove(fn);
2765       visited.add(fn);
2766
2767
2768       if(lastset!=null&&lastset.contains(fn)) {
2769         // if last is not null and matches, don't go 
2770         // any further for assigning labels
2771         continue;
2772       }
2773
2774       for(int i=0; i<fn.numNext(); i++) {
2775         FlatNode nn=fn.getNext(i);
2776
2777         if(i>0) {
2778           //1) Edge >1 of node
2779           nodetolabel.put(nn,new Integer(labelindex++));
2780         }
2781         if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2782           tovisit.add(nn);
2783         } else {
2784           //2) Join point
2785           nodetolabel.put(nn,new Integer(labelindex++));
2786         }
2787       }
2788     }
2789     return nodetolabel;
2790
2791   }
2792
2793   protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first) {
2794     return assignLabels(first, null);
2795   }
2796
2797   protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
2798     HashSet tovisit=new HashSet();
2799     HashSet visited=new HashSet();
2800     int labelindex=0;
2801     Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2802     tovisit.add(first);
2803
2804     /*Assign labels first.  A node needs a label if the previous
2805      * node has two exits or this node is a join point. */
2806
2807     while(!tovisit.isEmpty()) {
2808       FlatNode fn=(FlatNode)tovisit.iterator().next();
2809       tovisit.remove(fn);
2810       visited.add(fn);
2811
2812
2813       if(lastset!=null&&lastset.contains(fn)) {
2814         // if last is not null and matches, don't go 
2815         // any further for assigning labels
2816         continue;
2817       }
2818
2819       for(int i=0; i<fn.numNext(); i++) {
2820         FlatNode nn=fn.getNext(i);
2821
2822         if(i>0) {
2823           //1) Edge >1 of node
2824           nodetolabel.put(nn,new Integer(labelindex++));
2825         }
2826         if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2827           tovisit.add(nn);
2828         } else {
2829           //2) Join point
2830           nodetolabel.put(nn,new Integer(labelindex++));
2831         }
2832       }
2833     }
2834     return nodetolabel;
2835   }
2836
2837
2838   /** Generate text string that corresponds to the TempDescriptor td. */
2839   protected String generateTemp(FlatMethod fm, TempDescriptor td, LocalityBinding lb) {
2840     MethodDescriptor md=fm.getMethod();
2841     TaskDescriptor task=fm.getTask();
2842     TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
2843
2844     if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
2845       return td.getSafeSymbol();
2846     }
2847
2848     if (objecttemps.isLocalPtr(td)) {
2849       return localsprefixderef+td.getSafeSymbol();
2850     }
2851
2852     if (objecttemps.isParamPtr(td)) {
2853       return paramsprefix+"->"+td.getSafeSymbol();
2854     }
2855
2856     throw new Error();
2857   }
2858
2859   protected void generateFlatNode(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output) {
2860
2861     // insert pre-node actions from the code plan
2862     if( state.MLP|| state.OOOJAVA ) {
2863       
2864       CodePlan cp;
2865       if(state.MLP){
2866         cp = mlpa.getCodePlan( fn );
2867       }else{
2868         cp = oooa.getCodePlan(fn);
2869       }
2870
2871       if( cp != null ) {
2872         
2873         FlatSESEEnterNode currentSESE = cp.getCurrentSESE();
2874         
2875         // for each sese and age pair that this parent statement
2876         // must stall on, take that child's stall semaphore, the
2877         // copying of values comes after the statement
2878         Iterator<VariableSourceToken> vstItr = cp.getStallTokens().iterator();
2879         while( vstItr.hasNext() ) {
2880           VariableSourceToken vst = vstItr.next();
2881
2882           SESEandAgePair pair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2883
2884           output.println("   {");
2885           output.println("     "+pair.getSESE().getSESErecordName()+"* child = ("+
2886                          pair.getSESE().getSESErecordName()+"*) "+pair+";");
2887
2888           output.println("     SESEcommon* common = (SESEcommon*) "+pair+";");
2889           if( state.COREPROF ) {
2890             //output.println("     CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_BEGIN );");
2891           }
2892           output.println("     pthread_mutex_lock( &(common->lock) );");
2893           output.println("     while( common->doneExecuting == FALSE ) {");
2894           output.println("       pthread_cond_wait( &(common->doneCond), &(common->lock) );");
2895           output.println("     }");
2896           output.println("     pthread_mutex_unlock( &(common->lock) );");
2897
2898           // copy things we might have stalled for                
2899           Iterator<TempDescriptor> tdItr = cp.getCopySet( vst ).iterator();
2900           while( tdItr.hasNext() ) {
2901             TempDescriptor td = tdItr.next();
2902             FlatMethod fmContext;
2903             if( currentSESE.getIsCallerSESEplaceholder() ) {
2904               fmContext = currentSESE.getfmEnclosing();
2905             } else {
2906               fmContext = currentSESE.getfmBogus();
2907             }
2908             output.println("       "+generateTemp( fmContext, td, null )+
2909                            " = child->"+vst.getAddrVar().getSafeSymbol()+";");
2910           }
2911           if( state.COREPROF ) {
2912             //output.println("     CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_END );");
2913           }
2914           output.println("   }");
2915         }
2916   
2917         // for each variable with a dynamic source, stall just for that variable
2918         Iterator<TempDescriptor> dynItr = cp.getDynamicStallSet().iterator();
2919         while( dynItr.hasNext() ) {
2920           TempDescriptor dynVar = dynItr.next();
2921
2922           // only stall if the dynamic source is not yourself, denoted by src==NULL
2923           // otherwise the dynamic write nodes will have the local var up-to-date
2924           output.println("   {");
2925           output.println("     if( "+dynVar+"_srcSESE != NULL ) {");
2926           output.println("       SESEcommon* common = (SESEcommon*) "+dynVar+"_srcSESE;");
2927           if( state.COREPROF ) {
2928             //output.println("       CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_BEGIN );");
2929           }
2930           output.println("       psem_take( &(common->stallSem) );");
2931
2932           FlatMethod fmContext;
2933           if( currentSESE.getIsCallerSESEplaceholder() ) {
2934             fmContext = currentSESE.getfmEnclosing();
2935           } else {
2936             fmContext = currentSESE.getfmBogus();
2937           }
2938           
2939           TypeDescriptor type=dynVar.getType();
2940           String typeStr;
2941           if( type.isNull() ) {
2942             typeStr = "void*";
2943           } else if( type.isClass() || type.isArray() ) {
2944             typeStr = "struct "+type.getSafeSymbol()+"*";
2945           } else {
2946             typeStr = type.getSafeSymbol();
2947           }
2948       
2949           output.println("       "+generateTemp( fmContext, dynVar, null )+
2950                          " = *(("+typeStr+"*) ("+
2951                          dynVar+"_srcSESE + "+dynVar+"_srcOffset));");
2952           if( state.COREPROF ) {
2953             //output.println("       CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_END );");
2954           }
2955           output.println("     }");
2956           output.println("   }");
2957         }
2958
2959         // for each assignment of a variable to rhs that has a dynamic source,
2960         // copy the dynamic sources
2961         Iterator dynAssignItr = cp.getDynAssigns().entrySet().iterator();
2962         while( dynAssignItr.hasNext() ) {
2963           Map.Entry      me  = (Map.Entry)      dynAssignItr.next();
2964           TempDescriptor lhs = (TempDescriptor) me.getKey();
2965           TempDescriptor rhs = (TempDescriptor) me.getValue();
2966
2967           output.println("   {");
2968           output.println("   SESEcommon* oldSrc = "+lhs+"_srcSESE;");
2969           
2970           output.println("   "+lhs+"_srcSESE   = "+rhs+"_srcSESE;");
2971           output.println("   "+lhs+"_srcOffset = "+rhs+"_srcOffset;");
2972
2973           // no matter what we did above, track reference count of whatever
2974           // this variable pointed to, do release last in case we're just
2975           // copying the same value in because 1->2->1 is safe but ref count
2976           // 1->0->1 has a window where it looks like it should be free'd
2977           output.println("     if( "+rhs+"_srcSESE != NULL ) {");
2978           output.println("       ADD_REFERENCE_TO( "+rhs+"_srcSESE );");
2979           output.println("     }");
2980           output.println("     if( oldSrc != NULL ) {");
2981           output.println("       RELEASE_REFERENCE_TO( oldSrc );");
2982           output.println("     }");
2983           output.println("   }");
2984         }
2985
2986         // for each lhs that is dynamic from a non-dynamic source, set the
2987         // dynamic source vars to the current SESE
2988         dynItr = cp.getDynAssignCurr().iterator();
2989         while( dynItr.hasNext() ) {
2990           TempDescriptor dynVar = dynItr.next();          
2991           assert currentSESE.getDynamicVarSet().contains( dynVar );
2992
2993           // first release a reference to current record
2994           output.println("   if( "+dynVar+"_srcSESE != NULL ) {");
2995           output.println("     RELEASE_REFERENCE_TO( oldSrc );");
2996           output.println("   }");
2997
2998           output.println("   "+dynVar+"_srcSESE = NULL;");
2999         }
3000         
3001         // eom
3002         // handling stall site
3003         if (state.OOOJAVA) {
3004           Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(currentSESE);
3005           if(graph!=null){
3006             Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
3007             Set<Analysis.OoOJava.WaitingElement> waitingElementSet =
3008               graph.getStallSiteWaitingElementSet(fn, seseLockSet);
3009             
3010             if(waitingElementSet.size()>0){
3011               output.println("// stall on parent's stall sites ");
3012               output.println("   {");
3013               output.println("     REntry* rentry;");
3014           
3015               for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
3016                 Analysis.OoOJava.WaitingElement waitingElement = (Analysis.OoOJava.WaitingElement) iterator.next();
3017                 
3018                 if(state.RCR && rcr != null){
3019                   Analysis.OoOJava.ConflictGraph conflictGraph = graph;
3020                   Hashtable<Taint, Set<Effect>> conflicts;
3021                   ReachGraph rg = oooa.getDisjointAnalysis().getReachGraph(currentSESE.getmdEnclosing());
3022                   if(rcr.cSideDebug) {
3023                     rg.writeGraph("RCR_RG_STALLSITE_DEBUG");
3024                   }
3025                   if((conflictGraph != null) && 
3026                       (conflicts = graph.getConflictEffectSet(fn)) != null &&
3027                       (rg != null)){
3028                     
3029                     //get effect set
3030                     Hashtable<Taint, Set<Effect>>  effects=oooa.getDisjointAnalysis().getEffectsAnalysis().get(fn);
3031                     rcr.traverseStallSite(fn, waitingElement.getTempDesc(), effects, conflicts, rg);
3032                    }
3033                 }
3034                
3035                 if( waitingElement.getStatus() >= ConflictNode.COARSE ){
3036                   output.println("     rentry=mlpCreateREntry("+ waitingElement.getStatus()+ ", runningSESE);");
3037                 }else{
3038                   output.println("     rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", runningSESE,  (void*)&" +generateTemp(fm,waitingElement.getTempDesc(),lb)+ ");");
3039                 }         
3040                 output.println("     psem_init( &(rentry->parentStallSem) );");
3041                 output.println("     rentry->queue=runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
3042                 output.println("     if(ADDRENTRY(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()
3043                            + "],rentry)==NOTREADY){");
3044                 if( state.COREPROF ) {
3045                   //output.println("        CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_BEGIN );");
3046                 }
3047                 output.println("        psem_take( &(rentry->parentStallSem) );");
3048                 if( state.COREPROF ) {
3049                   //output.println("        CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_END );");
3050                 }
3051                 output.println("     }  ");
3052                 
3053                 if(state.RCR && rcr != null) {
3054                   output.println("   "+rcr.getTraverserInvocation(waitingElement.getTempDesc(), 
3055                       generateTemp(fm, waitingElement.getTempDesc(), null), fn));
3056                 }
3057               }
3058               output.println("   }");
3059             }
3060           }
3061         }else{
3062           ParentChildConflictsMap conflictsMap = mlpa.getConflictsResults().get(fn);
3063           if (conflictsMap != null) {
3064             Set<Long> allocSet = conflictsMap.getAllocationSiteIDSetofStallSite();
3065             if (allocSet.size() > 0) {
3066               FlatNode enclosingFlatNode=null;
3067               if( currentSESE.getIsCallerSESEplaceholder() && currentSESE.getParent()==null){
3068                 enclosingFlatNode=currentSESE.getfmEnclosing();
3069               }else{
3070                 enclosingFlatNode=currentSESE;
3071               }                                         
3072               ConflictGraph graph=mlpa.getConflictGraphResults().get(enclosingFlatNode);
3073               HashSet<SESELock> seseLockSet=mlpa.getConflictGraphLockMap().get(graph);
3074               Set<WaitingElement> waitingElementSet=graph.getStallSiteWaitingElementSet(conflictsMap, seseLockSet);
3075                         
3076               if(waitingElementSet.size()>0){
3077                 output.println("// stall on parent's stall sites ");
3078                 output.println("   {");
3079                 output.println("     REntry* rentry;");
3080                                 
3081                 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
3082                   WaitingElement waitingElement = (WaitingElement) iterator.next();
3083                                         
3084                   if( waitingElement.getStatus() >= ConflictNode.COARSE ){
3085                     // HERE! a parent might conflict with a child
3086                     output.println("     rentry=mlpCreateREntry("+ waitingElement.getStatus()+ ", runningSESE);");
3087                   }else{
3088                     output.println("     rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", runningSESE,  (void*)&___locals___."+ waitingElement.getDynID() + ");");
3089                   }                                     
3090                   output.println("     psem_init( &(rentry->parentStallSem) );");
3091                   output.println("     rentry->queue=runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
3092                   output
3093                     .println("     if(ADDRENTRY(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()
3094                              + "],rentry)==NOTREADY){");
3095                   if( state.COREPROF ) {
3096                     //output.println("        CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_BEGIN );");
3097                   }
3098                   output.println("        psem_take( &(rentry->parentStallSem) );");
3099                   if( state.COREPROF ) {
3100                     //output.println("        CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_END );");
3101                   }
3102                   output.println("     }  ");
3103                 }
3104                 output.println("   }");
3105               }
3106             }
3107           }     
3108         }
3109       }
3110     }
3111
3112     switch(fn.kind()) {
3113     case FKind.FlatAtomicEnterNode:
3114       generateFlatAtomicEnterNode(fm, lb, (FlatAtomicEnterNode) fn, output);
3115       break;
3116
3117     case FKind.FlatAtomicExitNode:
3118       generateFlatAtomicExitNode(fm, lb, (FlatAtomicExitNode) fn, output);
3119       break;
3120
3121     case FKind.FlatInstanceOfNode:
3122       generateFlatInstanceOfNode(fm, lb, (FlatInstanceOfNode)fn, output);
3123       break;
3124
3125     case FKind.FlatSESEEnterNode:
3126       generateFlatSESEEnterNode(fm, lb, (FlatSESEEnterNode)fn, output);
3127       break;
3128
3129     case FKind.FlatSESEExitNode:
3130       generateFlatSESEExitNode(fm, lb, (FlatSESEExitNode)fn, output);
3131       break;
3132       
3133     case FKind.FlatWriteDynamicVarNode:
3134       generateFlatWriteDynamicVarNode(fm, lb, (FlatWriteDynamicVarNode)fn, output);
3135       break;
3136
3137     case FKind.FlatGlobalConvNode:
3138       generateFlatGlobalConvNode(fm, lb, (FlatGlobalConvNode) fn, output);
3139       break;
3140
3141     case FKind.FlatTagDeclaration:
3142       generateFlatTagDeclaration(fm, lb, (FlatTagDeclaration) fn,output);
3143       break;
3144
3145     case FKind.FlatCall:
3146       generateFlatCall(fm, lb, (FlatCall) fn,output);
3147       break;
3148
3149     case FKind.FlatFieldNode:
3150       generateFlatFieldNode(fm, lb, (FlatFieldNode) fn,output);
3151       break;
3152
3153     case FKind.FlatElementNode:
3154       generateFlatElementNode(fm, lb, (FlatElementNode) fn,output);
3155       break;
3156
3157     case FKind.FlatSetElementNode:
3158       generateFlatSetElementNode(fm, lb, (FlatSetElementNode) fn,output);
3159       break;
3160
3161     case FKind.FlatSetFieldNode:
3162       generateFlatSetFieldNode(fm, lb, (FlatSetFieldNode) fn,output);
3163       break;
3164
3165     case FKind.FlatNew:
3166       generateFlatNew(fm, lb, (FlatNew) fn,output);
3167       break;
3168
3169     case FKind.FlatOpNode:
3170       generateFlatOpNode(fm, lb, (FlatOpNode) fn,output);
3171       break;
3172
3173     case FKind.FlatCastNode:
3174       generateFlatCastNode(fm, lb, (FlatCastNode) fn,output);
3175       break;
3176
3177     case FKind.FlatLiteralNode:
3178       generateFlatLiteralNode(fm, lb, (FlatLiteralNode) fn,output);
3179       break;
3180
3181     case FKind.FlatReturnNode:
3182       generateFlatReturnNode(fm, lb, (FlatReturnNode) fn,output);
3183       break;
3184
3185     case FKind.FlatNop:
3186       output.println("/* nop */");
3187       break;
3188
3189     case FKind.FlatExit:
3190       output.println("/* exit */");
3191       break;
3192
3193     case FKind.FlatBackEdge:
3194       if (state.SINGLETM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
3195         output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
3196       }
3197       if(state.DSM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
3198         output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
3199       }
3200       if (((state.MLP|| state.OOOJAVA||state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
3201           || (this.state.MULTICOREGC)) {
3202         if(state.DSM&&locality.getAtomic(lb).get(fn).intValue()>0) {
3203           output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
3204         } else if(this.state.MULTICOREGC) {
3205           output.println("if (gcflag) gc("+localsprefixaddr+");");
3206         } else {
3207           output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3208         }
3209       } else
3210         output.println("/* nop */");
3211       break;
3212
3213     case FKind.FlatCheckNode:
3214       generateFlatCheckNode(fm, lb, (FlatCheckNode) fn, output);
3215       break;
3216
3217     case FKind.FlatFlagActionNode:
3218       generateFlatFlagActionNode(fm, lb, (FlatFlagActionNode) fn, output);
3219       break;
3220
3221     case FKind.FlatPrefetchNode:
3222       generateFlatPrefetchNode(fm,lb, (FlatPrefetchNode) fn, output);
3223       break;
3224
3225     case FKind.FlatOffsetNode:
3226       generateFlatOffsetNode(fm, lb, (FlatOffsetNode)fn, output);
3227       break;
3228
3229     default:
3230       throw new Error();
3231     }
3232
3233     // insert post-node actions from the code-plan
3234     /*
3235     if( state.MLP) {
3236       CodePlan cp = mlpa.getCodePlan( fn );
3237
3238       if( cp != null ) {     
3239       }
3240     }
3241     */
3242   }
3243
3244   public void generateFlatOffsetNode(FlatMethod fm, LocalityBinding lb, FlatOffsetNode fofn, PrintWriter output) {
3245     output.println("/* FlatOffsetNode */");
3246     FieldDescriptor fd=fofn.getField();
3247     output.println(generateTemp(fm, fofn.getDst(),lb)+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+ fd.getSafeSymbol()+");");
3248     output.println("/* offset */");
3249   }
3250
3251   public void generateFlatPrefetchNode(FlatMethod fm, LocalityBinding lb, FlatPrefetchNode fpn, PrintWriter output) {
3252     if (state.PREFETCH) {
3253       Vector oids = new Vector();
3254       Vector fieldoffset = new Vector();
3255       Vector endoffset = new Vector();
3256       int tuplecount = 0;        //Keeps track of number of prefetch tuples that need to be generated
3257       for(Iterator it = fpn.hspp.iterator(); it.hasNext();) {
3258         PrefetchPair pp = (PrefetchPair) it.next();
3259         Integer statusbase = locality.getNodePreTempInfo(lb,fpn).get(pp.base);
3260         /* Find prefetches that can generate oid */
3261         if(statusbase == LocalityAnalysis.GLOBAL) {
3262           generateTransCode(fm, lb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(lb).get(fpn).intValue()>0, false);
3263           tuplecount++;
3264         } else if (statusbase == LocalityAnalysis.LOCAL) {
3265           generateTransCode(fm,lb,pp,oids,fieldoffset,endoffset,tuplecount,false,true);
3266         } else {
3267           continue;
3268         }
3269       }
3270       if (tuplecount==0)
3271         return;
3272       System.out.println("Adding prefetch "+fpn+ " to method:" +fm);
3273       output.println("{");
3274       output.println("/* prefetch */");
3275       output.println("/* prefetchid_" + fpn.siteid + " */");
3276       output.println("void * prefptr;");
3277       output.println("int tmpindex;");
3278
3279       output.println("if((evalPrefetch["+fpn.siteid+"].operMode) || (evalPrefetch["+fpn.siteid+"].retrycount <= 0)) {");
3280       /*Create C code for oid array */
3281       output.print("   unsigned int oidarray_[] = {");
3282       boolean needcomma=false;
3283       for (Iterator it = oids.iterator(); it.hasNext();) {
3284         if (needcomma)
3285           output.print(", ");
3286         output.print(it.next());
3287         needcomma=true;
3288       }
3289       output.println("};");
3290
3291       /*Create C code for endoffset values */
3292       output.print("   unsigned short endoffsetarry_[] = {");
3293       needcomma=false;
3294       for (Iterator it = endoffset.iterator(); it.hasNext();) {
3295         if (needcomma)
3296           output.print(", ");
3297         output.print(it.next());
3298         needcomma=true;
3299       }
3300       output.println("};");
3301
3302       /*Create C code for Field Offset Values */
3303       output.print("   short fieldarry_[] = {");
3304       needcomma=false;
3305       for (Iterator it = fieldoffset.iterator(); it.hasNext();) {
3306         if (needcomma)
3307           output.print(", ");
3308         output.print(it.next());
3309         needcomma=true;
3310       }
3311       output.println("};");
3312       /* make the prefetch call to Runtime */
3313       output.println("   if(!evalPrefetch["+fpn.siteid+"].operMode) {");
3314       output.println("     evalPrefetch["+fpn.siteid+"].retrycount = RETRYINTERVAL;");
3315       output.println("   }");
3316       output.println("   prefetch("+fpn.siteid+" ,"+tuplecount+", oidarray_, endoffsetarry_, fieldarry_);");
3317       output.println(" } else {");
3318       output.println("   evalPrefetch["+fpn.siteid+"].retrycount--;");
3319       output.println(" }");
3320       output.println("}");
3321     }
3322   }
3323
3324   public void generateTransCode(FlatMethod fm, LocalityBinding lb,PrefetchPair pp, Vector oids, Vector fieldoffset, Vector endoffset, int tuplecount, boolean inside, boolean localbase) {
3325     short offsetcount = 0;
3326     int breakindex=0;
3327     if (inside) {
3328       breakindex=1;
3329     } else if (localbase) {
3330       for(; breakindex<pp.desc.size(); breakindex++) {
3331         Descriptor desc=pp.getDescAt(breakindex);
3332         if (desc instanceof FieldDescriptor) {
3333           FieldDescriptor fd=(FieldDescriptor)desc;
3334           if (fd.isGlobal()) {
3335             break;
3336           }
3337         }
3338       }
3339       breakindex++;
3340     }
3341
3342     if (breakindex>pp.desc.size())     //all local
3343       return;
3344
3345     TypeDescriptor lasttype=pp.base.getType();
3346     String basestr=generateTemp(fm, pp.base, lb);
3347     String teststr="";
3348     boolean maybenull=fm.getMethod().isStatic()||
3349                        !pp.base.equals(fm.getParameter(0));
3350
3351     for(int i=0; i<breakindex; i++) {
3352       String indexcheck="";
3353
3354       Descriptor desc=pp.getDescAt(i);
3355       if (desc instanceof FieldDescriptor) {
3356         FieldDescriptor fd=(FieldDescriptor)desc;
3357         if (maybenull) {
3358           if (!teststr.equals(""))
3359             teststr+="&&";
3360           teststr+="((prefptr="+basestr+")!=NULL)";
3361           basestr="((struct "+lasttype.getSafeSymbol()+" *)prefptr)->"+fd.getSafeSymbol();
3362         } else {
3363           basestr=basestr+"->"+fd.getSafeSymbol();
3364           maybenull=true;
3365         }
3366         lasttype=fd.getType();
3367       } else {
3368         IndexDescriptor id=(IndexDescriptor)desc;
3369         indexcheck="((tmpindex=";
3370         for(int j=0; j<id.tddesc.size(); j++) {
3371           indexcheck+=generateTemp(fm, id.getTempDescAt(j), lb)+"+";
3372         }
3373         indexcheck+=id.offset+")>=0)&(tmpindex<((struct ArrayObject *)prefptr)->___length___)";
3374
3375         if (!teststr.equals(""))
3376           teststr+="&&";
3377         teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck;
3378         basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]";
3379         maybenull=true;
3380         lasttype=lasttype.dereference();
3381       }
3382     }
3383
3384     String oid;
3385     if (teststr.equals("")) {
3386       oid="((unsigned int)"+basestr+")";
3387     } else {
3388       oid="((unsigned int)(("+teststr+")?"+basestr+":NULL))";
3389     }
3390     oids.add(oid);
3391
3392     for(int i = breakindex; i < pp.desc.size(); i++) {
3393       String newfieldoffset;
3394       Object desc = pp.getDescAt(i);
3395       if(desc instanceof FieldDescriptor) {
3396         FieldDescriptor fd=(FieldDescriptor)desc;
3397         newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))");
3398         lasttype=fd.getType();
3399       } else {
3400         newfieldoffset = "";
3401         IndexDescriptor id=(IndexDescriptor)desc;
3402         for(int j = 0; j < id.tddesc.size(); j++) {
3403           newfieldoffset += generateTemp(fm, id.getTempDescAt(j), lb) + "+";
3404         }
3405         newfieldoffset += id.offset.toString();
3406         lasttype=lasttype.dereference();
3407       }
3408       fieldoffset.add(newfieldoffset);
3409     }
3410
3411     int base=(tuplecount>0) ? ((Short)endoffset.get(tuplecount-1)).intValue() : 0;
3412     base+=pp.desc.size()-breakindex;
3413     endoffset.add(new Short((short)base));
3414   }
3415
3416
3417
3418   public void generateFlatGlobalConvNode(FlatMethod fm, LocalityBinding lb, FlatGlobalConvNode fgcn, PrintWriter output) {
3419     if (lb!=fgcn.getLocality())
3420       return;
3421     /* Have to generate flat globalconv */
3422     if (fgcn.getMakePtr()) {
3423       if (state.DSM) {
3424         //DEBUG: output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+",\" "+fm+":"+fgcn+"\");");
3425            output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3426       } else {
3427         if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fgcn)||state.READSET&&dc.getNeedWriteTrans(lb, fgcn)) {
3428           //need to do translation
3429           output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+", (void *)("+localsprefixaddr+"));");
3430         } else if (state.READSET&&dc.getNeedTrans(lb, fgcn)) {
3431           if (state.HYBRID&&delaycomp.getConv(lb).contains(fgcn)) {
3432             output.println("TRANSREADRDFISSION("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3433           } else
3434             output.println("TRANSREADRD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3435         }
3436       }
3437     } else {
3438       /* Need to convert to OID */
3439       if ((dc==null)||dc.getNeedSrcTrans(lb,fgcn)) {
3440         if (fgcn.doConvert()||(delaycomp!=null&&delaycomp.needsFission(lb, fgcn.getAtomicEnter())&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) {
3441           output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc(),lb)+");");
3442         } else {
3443           output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=NULL;");
3444         }
3445       }
3446     }
3447   }
3448
3449   public void generateFlatInstanceOfNode(FlatMethod fm,  LocalityBinding lb, FlatInstanceOfNode fion, PrintWriter output) {
3450     int type;
3451     if (fion.getType().isArray()) {
3452       type=state.getArrayNumber(fion.getType())+state.numClasses();
3453     } else {
3454       type=fion.getType().getClassDesc().getId();
3455     }
3456
3457     if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
3458       output.println(generateTemp(fm, fion.getDst(), lb)+"=1;");
3459     else
3460       output.println(generateTemp(fm, fion.getDst(), lb)+"=instanceof("+generateTemp(fm,fion.getSrc(),lb)+","+type+");");
3461   }
3462
3463   int sandboxcounter=0;
3464   public void generateFlatAtomicEnterNode(FlatMethod fm,  LocalityBinding lb, FlatAtomicEnterNode faen, PrintWriter output) {
3465     /* Check to see if we need to generate code for this atomic */
3466     if (locality==null) {
3467       if (GENERATEPRECISEGC) {
3468         output.println("if (pthread_mutex_trylock(&atomiclock)!=0) {");
3469         output.println("stopforgc((struct garbagelist *) &___locals___);");
3470         output.println("pthread_mutex_lock(&atomiclock);");
3471         output.println("restartaftergc();");
3472         output.println("}");
3473       } else {
3474         output.println("pthread_mutex_lock(&atomiclock);");
3475       }
3476       return;
3477     }
3478
3479     if (locality.getAtomic(lb).get(faen.getPrev(0)).intValue()>0)
3480       return;
3481
3482
3483     if (state.SANDBOX) {
3484       outsandbox.println("int atomiccounter"+sandboxcounter+"=LOW_CHECK_FREQUENCY;");
3485       output.println("counter_reset_pointer=&atomiccounter"+sandboxcounter+";");
3486     }
3487
3488     if (state.DELAYCOMP&&delaycomp.needsFission(lb, faen)) {
3489       AtomicRecord ar=atomicmethodmap.get(faen);
3490       //copy in
3491       for(Iterator<TempDescriptor> tmpit=ar.livein.iterator();tmpit.hasNext();) {
3492         TempDescriptor tmp=tmpit.next();
3493         output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3494       }
3495
3496       //copy outs that depend on path
3497       for(Iterator<TempDescriptor> tmpit=ar.liveoutvirtualread.iterator();tmpit.hasNext();) {
3498         TempDescriptor tmp=tmpit.next();
3499         if (!ar.livein.contains(tmp))
3500           output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3501       }
3502     }
3503
3504     /* Backup the temps. */
3505     for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3506       TempDescriptor tmp=tmpit.next();
3507       output.println(generateTemp(fm, backuptable.get(lb).get(tmp),lb)+"="+generateTemp(fm,tmp,lb)+";");
3508     }
3509
3510     output.println("goto transstart"+faen.getIdentifier()+";");
3511
3512     /******* Print code to retry aborted transaction *******/
3513     output.println("transretry"+faen.getIdentifier()+":");
3514
3515     /* Restore temps */
3516     for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3517       TempDescriptor tmp=tmpit.next();
3518       output.println(generateTemp(fm, tmp,lb)+"="+generateTemp(fm,backuptable.get(lb).get(tmp),lb)+";");
3519     }
3520
3521     if (state.DSM) {
3522       /********* Need to revert local object store ********/
3523       String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3524
3525       output.println("while ("+revertptr+") {");
3526       output.println("struct ___Object___ * tmpptr;");
3527       output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3528       output.println("REVERT_OBJ("+revertptr+");");
3529       output.println(revertptr+"=tmpptr;");
3530       output.println("}");
3531     }
3532     /******* Tell the runtime to start the transaction *******/
3533
3534     output.println("transstart"+faen.getIdentifier()+":");
3535     if (state.SANDBOX) {
3536       output.println("transaction_check_counter=*counter_reset_pointer;");
3537       sandboxcounter++;
3538     }
3539     output.println("transStart();");
3540
3541     if (state.ABORTREADERS||state.SANDBOX) {
3542       if (state.SANDBOX)
3543         output.println("abortenabled=1;");
3544       output.println("if (_setjmp(aborttrans)) {");
3545       output.println("  goto transretry"+faen.getIdentifier()+"; }");
3546     }
3547   }
3548
3549   public void generateFlatAtomicExitNode(FlatMethod fm,  LocalityBinding lb, FlatAtomicExitNode faen, PrintWriter output) {
3550     /* Check to see if we need to generate code for this atomic */
3551     if (locality==null) {
3552       output.println("pthread_mutex_unlock(&atomiclock);");
3553       return;
3554     }
3555     if (locality.getAtomic(lb).get(faen).intValue()>0)
3556       return;
3557     //store the revert list before we lose the transaction object
3558     
3559     if (state.DSM) {
3560       String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3561       output.println(revertptr+"=revertlist;");
3562       output.println("if (transCommit()) {");
3563       output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3564       output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3565       output.println("} else {");
3566       /* Need to commit local object store */
3567       output.println("while ("+revertptr+") {");
3568       output.println("struct ___Object___ * tmpptr;");
3569       output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3570       output.println("COMMIT_OBJ("+revertptr+");");
3571       output.println(revertptr+"=tmpptr;");
3572       output.println("}");
3573       output.println("}");
3574       return;
3575     }
3576
3577     if (!state.DELAYCOMP) {
3578       //Normal STM stuff
3579       output.println("if (transCommit()) {");
3580       /* Transaction aborts if it returns true */
3581       output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3582       output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3583       output.println("}");
3584     } else {
3585       if (delaycomp.optimizeTrans(lb, faen.getAtomicEnter())&&(!state.STMARRAY||state.DUALVIEW))  {
3586         AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3587         output.println("LIGHTWEIGHTCOMMIT("+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+", transretry"+faen.getAtomicEnter().getIdentifier()+");");
3588         //copy out
3589         for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3590           TempDescriptor tmp=tmpit.next();
3591           output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3592         }
3593       } else if (delaycomp.needsFission(lb, faen.getAtomicEnter())) {
3594         AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3595         //do call
3596         output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {");
3597         output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3598         output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3599         output.println("}");
3600         //copy out
3601         output.println("else {");
3602         for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3603           TempDescriptor tmp=tmpit.next();
3604           output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3605         }
3606         output.println("}");
3607       } else {
3608         output.println("if (transCommit(NULL, NULL, NULL, NULL)) {");
3609         output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3610         output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3611         output.println("}");
3612       }
3613     }
3614   }
3615
3616   public void generateFlatSESEEnterNode( FlatMethod fm,  
3617                                          LocalityBinding lb, 
3618                                          FlatSESEEnterNode fsen, 
3619                                          PrintWriter output 
3620                                        ) {
3621     // if MLP flag is off, okay that SESE nodes are in IR graph, 
3622     // just skip over them and code generates exactly the same
3623     if( !(state.MLP || state.OOOJAVA) ) {
3624       return;
3625     }    
3626     // there may be an SESE in an unreachable method, skip over
3627     if( (state.MLP && !mlpa.getAllSESEs().contains( fsen )) ||
3628         (state.OOOJAVA && !oooa.getAllSESEs().contains(fsen))
3629     ) {
3630       return;
3631     }
3632
3633     // also, if we have encountered a placeholder, just skip it
3634     if( fsen.getIsCallerSESEplaceholder() ) {
3635       return;
3636     }
3637
3638     output.println("   {");
3639
3640     if( state.COREPROF ) {
3641       output.println("CP_LOGEVENT( CP_EVENTID_TASKDISPATCH, CP_EVENTTYPE_BEGIN );");
3642     }
3643     
3644     // before doing anything, lock your own record and increment the running children
3645     if( (state.MLP     && fsen != mlpa.getMainSESE()) || 
3646         (state.OOOJAVA && fsen != oooa.getMainSESE())
3647     ) {      
3648       output.println("     atomic_inc(&(runningSESE->numRunningChildren));");
3649     }
3650
3651     // allocate the space for this record
3652     output.println( "#ifndef OOO_DISABLE_TASKMEMPOOL" );
3653     if( (state.MLP     && fsen != mlpa.getMainSESE()) || 
3654         (state.OOOJAVA && fsen != oooa.getMainSESE())
3655         ) {
3656       output.println("     "+
3657                      fsen.getSESErecordName()+"* seseToIssue = ("+
3658                      fsen.getSESErecordName()+"*) poolalloc( runningSESE->taskRecordMemPool );");
3659     } else {
3660       output.println("     "+
3661                      fsen.getSESErecordName()+"* seseToIssue = ("+
3662                      fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
3663                      fsen.getSESErecordName()+" ) );");
3664     }
3665     output.println( "#else" );
3666       output.println("     "+
3667                      fsen.getSESErecordName()+"* seseToIssue = ("+
3668                      fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
3669                      fsen.getSESErecordName()+" ) );");
3670     output.println( "#endif" );
3671
3672
3673     // set up the SESE in-set and out-set objects, which look
3674     // like a garbage list
3675     output.println("     struct garbagelist * gl= (struct garbagelist *)&(((SESEcommon*)(seseToIssue))[1]);");
3676     output.println("     gl->size="+calculateSizeOfSESEParamList(fsen)+";");
3677     output.println("     gl->next = NULL;");
3678
3679     // there are pointers to SESE records the newly-issued SESE
3680     // will use to get values it depends on them for--how many
3681     // are there, and what is the offset from the total SESE
3682     // record to the first dependent record pointer?
3683     output.println("     seseToIssue->common.numDependentSESErecords="+
3684                    fsen.getNumDepRecs()+";");
3685     
3686     // we only need this (and it will only compile) when the number of dependent
3687     // SESE records is non-zero
3688     if( fsen.getFirstDepRecField() != null ) {
3689       output.println("     seseToIssue->common.offsetToDepSESErecords=(INTPTR)sizeof("+
3690                      fsen.getSESErecordName()+") - (INTPTR)&((("+
3691                      fsen.getSESErecordName()+"*)0)->"+fsen.getFirstDepRecField()+");"
3692                      );
3693     }
3694     
3695     // fill in common data
3696     output.println("     int localCount=0;");
3697     output.println("     seseToIssue->common.classID = "+fsen.getIdentifier()+";");
3698     output.println("     psem_init( &(seseToIssue->common.stallSem) );");
3699
3700     output.println("     seseToIssue->common.forwardList = createQueue();");
3701     output.println("     seseToIssue->common.unresolvedDependencies = 10000;");
3702     output.println("     pthread_cond_init( &(seseToIssue->common.doneCond), NULL );");
3703     output.println("     seseToIssue->common.doneExecuting = FALSE;");    
3704     output.println("     pthread_cond_init( &(seseToIssue->common.runningChildrenCond), NULL );");
3705     output.println("     seseToIssue->common.numRunningChildren = 0;");
3706     output.println("     seseToIssue->common.parent = runningSESE;");
3707     // start with refCount = 2, one being the count that the child itself
3708     // will decrement when it retires, to say it is done using its own
3709     // record, and the other count is for the parent that will remember
3710     // the static name of this new child below
3711     output.println("     seseToIssue->common.refCount = 2;");
3712
3713     // all READY in-vars should be copied now and be done with it
3714     Iterator<TempDescriptor> tempItr = fsen.getReadyInVarSet().iterator();
3715     while( tempItr.hasNext() ) {
3716       TempDescriptor temp = tempItr.next();
3717
3718       // when we are issuing the main SESE or an SESE with placeholder
3719       // caller SESE as parent, generate temp child child's eclosing method,
3720       // otherwise use the parent's enclosing method as the context
3721       boolean useParentContext = false;
3722
3723       if( (state.MLP && fsen != mlpa.getMainSESE()) || 
3724           (state.OOOJAVA && fsen != oooa.getMainSESE())     
3725       ) {
3726         assert fsen.getParent() != null;
3727         if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3728           useParentContext = true;
3729         }
3730       }
3731
3732       if( useParentContext ) {
3733         output.println("     seseToIssue->"+temp+" = "+
3734                        generateTemp( fsen.getParent().getfmBogus(), temp, null )+";");   
3735       } else {
3736         output.println("     seseToIssue->"+temp+" = "+
3737                        generateTemp( fsen.getfmEnclosing(), temp, null )+";");
3738       }
3739     }
3740     
3741     // before potentially adding this SESE to other forwarding lists,
3742     // create it's lock
3743     output.println("     pthread_mutex_init( &(seseToIssue->common.lock), NULL );");
3744   
3745     if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3746         (state.OOOJAVA && fsen != oooa.getMainSESE())    
3747     ) {
3748       // count up outstanding dependencies, static first, then dynamic
3749       Iterator<SESEandAgePair> staticSrcsItr = fsen.getStaticInVarSrcs().iterator();
3750       while( staticSrcsItr.hasNext() ) {
3751         SESEandAgePair srcPair = staticSrcsItr.next();
3752         output.println("     {");
3753         output.println("       SESEcommon* src = (SESEcommon*)"+srcPair+";");
3754         //eomgc
3755         if(GENERATEPRECISEGC){
3756                 output.println("       stopforgc((struct garbagelist *)&___locals___);");
3757         }
3758         output.println("       pthread_mutex_lock( &(src->lock) );");
3759         if(GENERATEPRECISEGC){
3760                 output.println("       restartaftergc();");
3761         }
3762         output.println("       if( !isEmpty( src->forwardList ) &&");
3763         output.println("           seseToIssue == peekItem( src->forwardList ) ) {");
3764         output.println("         printf( \"This shouldnt already be here\\n\");");
3765         output.println("         exit( -1 );");
3766         output.println("       }");
3767         output.println("       if( !src->doneExecuting ) {");
3768         output.println("         addNewItem( src->forwardList, seseToIssue );");
3769         output.println("         ++(localCount);");
3770         output.println("       }");
3771         output.println("       ADD_REFERENCE_TO( src );");
3772         output.println("       pthread_mutex_unlock( &(src->lock) );");
3773         output.println("     }");
3774
3775         // whether or not it is an outstanding dependency, make sure
3776         // to pass the static name to the child's record
3777         output.println("     seseToIssue->"+srcPair+" = "+
3778                        "("+srcPair.getSESE().getSESErecordName()+"*)"+
3779                        srcPair+";");
3780       }
3781       
3782       // dynamic sources might already be accounted for in the static list,
3783       // so only add them to forwarding lists if they're not already there
3784       Iterator<TempDescriptor> dynVarsItr = fsen.getDynamicInVarSet().iterator();
3785       while( dynVarsItr.hasNext() ) {
3786         TempDescriptor dynInVar = dynVarsItr.next();
3787         output.println("     {");
3788         output.println("       SESEcommon* src = (SESEcommon*)"+dynInVar+"_srcSESE;");
3789
3790         // the dynamic source is NULL if it comes from your own space--you can't pass
3791         // the address off to the new child, because you're not done executing and
3792         // might change the variable, so copy it right now
3793         output.println("       if( src != NULL ) {");
3794         //eomgc
3795         if(GENERATEPRECISEGC){
3796                 output.println("         stopforgc((struct garbagelist *)&___locals___);");
3797         }
3798         output.println("         pthread_mutex_lock( &(src->lock) );");
3799         if(GENERATEPRECISEGC){
3800                 output.println("         restartaftergc();");
3801         }
3802         output.println("         if( isEmpty( src->forwardList ) ||");
3803         output.println("             seseToIssue != peekItem( src->forwardList ) ) {");
3804         output.println("           if( !src->doneExecuting ) {");
3805         output.println("             addNewItem( src->forwardList, seseToIssue );");
3806         output.println("             ++(localCount);");
3807         output.println("           }");
3808         output.println("         }");
3809         output.println("         ADD_REFERENCE_TO( src );");
3810         output.println("         pthread_mutex_unlock( &(src->lock) );");       
3811         output.println("         seseToIssue->"+dynInVar+"_srcOffset = "+dynInVar+"_srcOffset;");
3812         output.println("       } else {");
3813
3814         boolean useParentContext = false;
3815         if( (state.MLP && fsen != mlpa.getMainSESE()) || 
3816             (state.OOOJAVA && fsen != oooa.getMainSESE())       
3817         ) {
3818           assert fsen.getParent() != null;
3819           if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3820             useParentContext = true;
3821           }
3822         }       
3823         if( useParentContext ) {
3824           output.println("         seseToIssue->"+dynInVar+" = "+
3825                          generateTemp( fsen.getParent().getfmBogus(), dynInVar, null )+";");
3826         } else {
3827           output.println("         seseToIssue->"+dynInVar+" = "+
3828                          generateTemp( fsen.getfmEnclosing(), dynInVar, null )+";");
3829         }
3830         
3831         output.println("       }");
3832         output.println("     }");
3833         
3834         // even if the value is already copied, make sure your NULL source
3835         // gets passed so child knows it already has the dynamic value
3836         output.println("     seseToIssue->"+dynInVar+"_srcSESE = "+dynInVar+"_srcSESE;");
3837       }
3838
3839       
3840       // maintain pointers for finding dynamic SESE 
3841       // instances from static names      
3842       SESEandAgePair pairNewest = new SESEandAgePair( fsen, 0 );
3843       SESEandAgePair pairOldest = new SESEandAgePair( fsen, fsen.getOldestAgeToTrack() );
3844       if(  fsen.getParent() != null && 
3845            fsen.getParent().getNeededStaticNames().contains( pairNewest ) 
3846         ) {       
3847
3848         for( int i = fsen.getOldestAgeToTrack(); i > 0; --i ) {
3849           SESEandAgePair pair1 = new SESEandAgePair( fsen, i   );
3850           SESEandAgePair pair2 = new SESEandAgePair( fsen, i-1 );
3851           output.println("     "+pair1+" = "+pair2+";");
3852         }      
3853         output.println("     "+pairNewest+" = &(seseToIssue->common);");
3854       }
3855       // no need to add a reference to whatever is the newest record, because
3856       // we initialized seseToIssue->refCount to *2*
3857       // but release a reference to whatever was the oldest BEFORE the shift
3858       output.println("     if( "+pairOldest+" != NULL ) {");
3859       output.println("       RELEASE_REFERENCE_TO( "+pairOldest+" );");
3860       output.println("     }");
3861
3862       
3863
3864
3865       ////////////////
3866       // count up memory conflict dependencies,
3867       // eom
3868       if(state.OOOJAVA){
3869
3870         //output.println("       seseToIssue->common.numMemoryQueue=0;");
3871         //output.println("       seseToIssue->common.rentryIdx=0;");
3872         //output.println("       seseToIssue->common.unresolvedRentryIdx=0;");
3873         //output.println("       seseToIssue->common.memoryQueueArray=NULL;");
3874
3875         FlatSESEEnterNode parent = fsen.getParent();
3876         Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(parent);
3877         if (graph != null && graph.hasConflictEdge()) {
3878           Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
3879           output.println();
3880           output.println("     //add memory queue element");
3881           Analysis.OoOJava.SESEWaitingQueue seseWaitingQueue=
3882             graph.getWaitingElementSetBySESEID(fsen.getIdentifier(), seseLockSet);
3883           if(seseWaitingQueue.getWaitingElementSize()>0){
3884             output.println("     {");
3885             output.println("       REntry* rentry=NULL;");
3886             output.println("       INTPTR* pointer=NULL;");
3887             output.println("       seseToIssue->common.rentryIdx=0;");
3888             
3889             Set<Integer> queueIDSet=seseWaitingQueue.getQueueIDSet();
3890             for (Iterator iterator = queueIDSet.iterator(); iterator
3891                    .hasNext();) {
3892               Integer key = (Integer) iterator.next();
3893               int queueID=key.intValue();
3894               Set<Analysis.OoOJava.WaitingElement> waitingQueueSet =  
3895                 seseWaitingQueue.getWaitingElementSet(queueID);
3896               int enqueueType=seseWaitingQueue.getType(queueID);
3897               if(enqueueType==SESEWaitingQueue.EXCEPTION){
3898                 output.println("       INITIALIZEBUF(runningSESE->memoryQueueArray["
3899                                + queueID+ "]);");
3900               }
3901               for (Iterator iterator2 = waitingQueueSet.iterator(); iterator2.hasNext();) {
3902                 Analysis.OoOJava.WaitingElement waitingElement 
3903                   = (Analysis.OoOJava.WaitingElement) iterator2.next();
3904                 if (waitingElement.getStatus() >= ConflictNode.COARSE) {
3905                   output.println("       rentry=mlpCreateREntry("
3906                                  + waitingElement.getStatus()
3907                                  + ", &(seseToIssue->common));");
3908                 } else {
3909                   TempDescriptor td = waitingElement.getTempDesc();
3910                   // decide whether waiting element is dynamic or static
3911                   if (fsen.getDynamicInVarSet().contains(td)) {
3912                     // dynamic in-var case
3913                     output.println("       pointer=seseToIssue->"
3914                                    + waitingElement.getDynID()
3915                                    + "_srcSESE+seseToIssue->"
3916                                    + waitingElement.getDynID()
3917                                    + "_srcOffset;");
3918                     output.println("       rentry=mlpCreateFineREntry("
3919                                    + waitingElement.getStatus()
3920                                    + ", &(seseToIssue->common),  pointer );");
3921                   } else if (fsen.getStaticInVarSet().contains(td)) {
3922                     // static in-var case
3923                     VariableSourceToken vst = fsen.getStaticInVarSrc(td);
3924                     if (vst != null) {
3925   
3926                       String srcId = "SESE_"
3927                         + vst.getSESE()
3928                         .getPrettyIdentifier()
3929                         + vst.getSESE().getIdentifier()
3930                         + "_" + vst.getAge();
3931                       output.println("       pointer=(void*)&seseToIssue->"
3932                                      + srcId
3933                                      + "->"
3934                                      + waitingElement
3935                                      .getDynID()
3936                                      + ";");
3937                       output.println("       rentry=mlpCreateFineREntry("
3938                                      + waitingElement.getStatus()
3939                                      + ", &(seseToIssue->common),  pointer );");
3940                     }
3941                   } else {
3942                     output.println("       rentry=mlpCreateFineREntry("
3943                                    + waitingElement.getStatus()
3944                                    + ", &(seseToIssue->common),  (void*)&seseToIssue->"
3945                                    + waitingElement.getDynID()
3946                                    + ");");
3947                   }
3948                 }
3949                 output.println("       rentry->queue=runningSESE->memoryQueueArray["
3950                                + waitingElement.getQueueID()
3951                                + "];");
3952                 
3953                 if(enqueueType==SESEWaitingQueue.NORMAL){
3954                   output.println("       seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
3955                   output.println("       if(ADDRENTRY(runningSESE->memoryQueueArray["
3956                                  + waitingElement.getQueueID()
3957                                  + "],rentry)==NOTREADY){");
3958                   output.println("          ++(localCount);");
3959                   output.println("       }");
3960                   
3961                   // Trying to execute the dynamic coarse grain conflict strategy...
3962                   if(state.RCR && rcr != null) {
3963                     boolean useParentContext = false;
3964
3965                     if( (state.MLP &&fsen != mlpa.getMainSESE()) || 
3966                         (state.OOOJAVA &&fsen != oooa.getMainSESE())) {
3967                       assert fsen.getParent() != null;
3968                       if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3969                         useParentContext = true;
3970                       }
3971                     }
3972                     
3973                     for (TempDescriptor invar : fsen.getInVarsForDynamicCoarseConflictResolution()) {                      
3974                       String varString;
3975                       if( useParentContext ) {
3976                         varString = generateTemp( fsen.getParent().getfmBogus(), invar, null );
3977                       } else {
3978                         varString = generateTemp( fsen.getfmEnclosing(),         invar, null );
3979                       }
3980                       output.println("       "+rcr.getTraverserInvocation(invar, varString, fsen));
3981                     }
3982                   }
3983                 }else{
3984                   output
3985                     .println("       ADDRENTRYTOBUF(runningSESE->memoryQueueArray["
3986                              + waitingElement.getQueueID()
3987                              + "],rentry);");
3988                 }
3989               }
3990               if(enqueueType!=SESEWaitingQueue.NORMAL){
3991                 output.println("       localCount+=RESOLVEBUF(runningSESE->memoryQueueArray["
3992                                + queueID+ "],&seseToIssue->common);");
3993               }       
3994             }
3995             output.println("     }");
3996           }
3997           output.println();
3998         }
3999         
4000       }else{
4001         ConflictGraph graph = null;
4002         FlatSESEEnterNode parent = fsen.getParent();
4003         if (parent != null) {
4004           if (parent.isCallerSESEplaceholder) {
4005             graph = mlpa.getConflictGraphResults().get(parent.getfmEnclosing());
4006           } else {
4007             graph = mlpa.getConflictGraphResults().get(parent);
4008           }
4009         }
4010         if (graph != null && graph.hasConflictEdge()) {
4011           HashSet<SESELock> seseLockSet = mlpa.getConflictGraphLockMap()
4012             .get(graph);
4013           output.println();
4014           output.println("     //add memory queue element");
4015           SESEWaitingQueue seseWaitingQueue=graph.getWaitingElementSetBySESEID(fsen.getIdentifier(),
4016                                                                                seseLockSet);
4017           if(seseWaitingQueue.getWaitingElementSize()>0){
4018             output.println("     {");
4019             output.println("     REntry* rentry=NULL;");
4020             output.println("     INTPTR* pointer=NULL;");
4021             output.println("     seseToIssue->common.rentryIdx=0;");
4022                                         
4023             Set<Integer> queueIDSet=seseWaitingQueue.getQueueIDSet();
4024             for (Iterator iterator = queueIDSet.iterator(); iterator
4025                    .hasNext();) {
4026               Integer key = (Integer) iterator.next();
4027               int queueID=key.intValue();
4028               Set<WaitingElement> waitingQueueSet =  seseWaitingQueue.getWaitingElementSet(queueID);
4029               int enqueueType=seseWaitingQueue.getType(queueID);
4030               if(enqueueType==SESEWaitingQueue.EXCEPTION){
4031                 output.println("     INITIALIZEBUF(runningSESE->memoryQueueArray["
4032                                + queueID+ "]);");
4033               }
4034               for (Iterator iterator2 = waitingQueueSet.iterator(); iterator2
4035                      .hasNext();) {
4036                 WaitingElement waitingElement = (WaitingElement) iterator2
4037                   .next();
4038                 if (waitingElement.getStatus() >= ConflictNode.COARSE) {
4039                   output.println("     rentry=mlpCreateREntry("
4040                                  + waitingElement.getStatus()
4041                                  + ", &(seseToIssue->common));");
4042                 } else {
4043                   TempDescriptor td = waitingElement
4044                     .getTempDesc();
4045                   // decide whether waiting element is dynamic or
4046                   // static
4047                   if (fsen.getDynamicInVarSet().contains(td)) {
4048                     // dynamic in-var case
4049                     output.println("     pointer=seseToIssue->"
4050                                    + waitingElement.getDynID()
4051                                    + "_srcSESE+seseToIssue->"
4052                                    + waitingElement.getDynID()
4053                                    + "_srcOffset;");
4054                     output
4055                       .println("     rentry=mlpCreateFineREntry("
4056                                + waitingElement
4057                                .getStatus()
4058                                + ", &(seseToIssue->common),  pointer );");
4059                   } else if (fsen.getStaticInVarSet()
4060                              .contains(td)) {
4061                     // static in-var case
4062                     VariableSourceToken vst = fsen
4063                       .getStaticInVarSrc(td);
4064                     if (vst != null) {
4065   
4066                       String srcId = "SESE_"
4067                         + vst.getSESE()
4068                         .getPrettyIdentifier()
4069                         + vst.getSESE().getIdentifier()
4070                         + "_" + vst.getAge();
4071                       output
4072                         .println("     pointer=(void*)&seseToIssue->"
4073                                  + srcId
4074                                  + "->"
4075                                  + waitingElement
4076                                  .getDynID()
4077                                  + ";");
4078                       output
4079                         .println("     rentry=mlpCreateFineREntry("
4080                                  + waitingElement
4081                                  .getStatus()
4082                                  + ", &(seseToIssue->common),  pointer );");
4083   
4084                     }
4085                   } else {
4086                     output
4087                       .println("     rentry=mlpCreateFineREntry("
4088                                + waitingElement
4089                                .getStatus()
4090                                + ", &(seseToIssue->common),  (void*)&seseToIssue->"
4091                                + waitingElement.getDynID()
4092                                + ");");
4093                   }
4094                 }
4095                 output
4096                   .println("     rentry->queue=runningSESE->memoryQueueArray["
4097                            + waitingElement.getQueueID()
4098                            + "];");
4099                                                         
4100                 if(enqueueType==SESEWaitingQueue.NORMAL){
4101                   output
4102                     .println("     seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
4103                   output
4104                     .println("     if(ADDRENTRY(runningSESE->memoryQueueArray["
4105                              + waitingElement.getQueueID()
4106                              + "],rentry)==NOTREADY){");
4107                   output.println("        ++(localCount);");
4108                   output.println("     } ");
4109                 }else{
4110                   output
4111                     .println("     ADDRENTRYTOBUF(runningSESE->memoryQueueArray["
4112                              + waitingElement.getQueueID()
4113                              + "],rentry);");
4114                 }
4115               }
4116               if(enqueueType!=SESEWaitingQueue.NORMAL){
4117                 output.println("     localCount+=RESOLVEBUF(runningSESE->memoryQueueArray["
4118                                + queueID+ "],&seseToIssue->common);");
4119               }                         
4120             }
4121             output.println("     }");
4122           }
4123           output.println();
4124         }
4125       }
4126       ////////////////
4127     }
4128     
4129     // release this SESE for siblings to update its dependencies or,
4130     // eventually, for it to mark itself finished
4131     //    output.println("     pthread_mutex_unlock( &(seseToIssue->common.lock) );");
4132     
4133     // if there were no outstanding dependencies, issue here
4134     output.println("     if(  atomic_sub_and_test(10000-localCount,&(seseToIssue->common.unresolvedDependencies) ) ) {");
4135     output.println("       workScheduleSubmit( (void*)seseToIssue );");
4136     output.println("     }");
4137     /*
4138     output.println("     if( seseToIssue->common.unresolvedDependencies == 0 ) {");
4139     output.println("       workScheduleSubmit( (void*)seseToIssue );");
4140     output.println("     }");
4141     */
4142     // release this SESE for siblings to update its dependencies or,
4143     // eventually, for it to mark itself finished
4144 //    output.println("     pthread_mutex_unlock( &(seseToIssue->common.lock) );");
4145
4146     if( state.COREPROF ) {
4147       output.println("CP_LOGEVENT( CP_EVENTID_TASKDISPATCH, CP_EVENTTYPE_END );");
4148     }
4149
4150     output.println("   }");
4151     
4152   }
4153
4154   public void generateFlatSESEExitNode( FlatMethod fm,  
4155                                         LocalityBinding lb, 
4156                                         FlatSESEExitNode fsexn, 
4157                                         PrintWriter output
4158                                       ) {
4159
4160     // if MLP flag is off, okay that SESE nodes are in IR graph, 
4161     // just skip over them and code generates exactly the same 
4162     if( ! (state.MLP || state.OOOJAVA) ) {
4163       return;
4164     }
4165
4166     // get the enter node for this exit that has meta data embedded
4167     FlatSESEEnterNode fsen = fsexn.getFlatEnter();
4168
4169     // there may be an SESE in an unreachable method, skip over
4170     if( (state.MLP && !mlpa.getAllSESEs().contains( fsen ))  ||
4171         (state.OOOJAVA && !oooa.getAllSESEs().contains( fsen ))
4172     ) {
4173       return;
4174     }
4175
4176     // also, if we have encountered a placeholder, just jump it
4177     if( fsen.getIsCallerSESEplaceholder() ) {
4178       return;
4179     }
4180     
4181     if( state.COREPROF ) {
4182       output.println("   CP_LOGEVENT( CP_EVENTID_TASKEXECUTE, CP_EVENTTYPE_END );");
4183     }
4184
4185     output.println("   /* SESE exiting */");
4186
4187     if( state.COREPROF ) {
4188       output.println("   CP_LOGEVENT( CP_EVENTID_TASKRETIRE, CP_EVENTTYPE_BEGIN );");
4189     }
4190     
4191     String com = paramsprefix+"->common";
4192
4193     // this SESE cannot be done until all of its children are done
4194     // so grab your own lock with the condition variable for watching
4195     // that the number of your running children is greater than zero    
4196     if (GENERATEPRECISEGC){
4197         output.println("   stopforgc((struct garbagelist *)&___locals___);");
4198     }
4199     output.println("   pthread_mutex_lock( &("+com+".lock) );");
4200     if (GENERATEPRECISEGC){
4201         output.println("   restartaftergc();");
4202     }
4203     output.println("   while( "+com+".numRunningChildren > 0 ) {");
4204     if (GENERATEPRECISEGC){
4205 //      output.println("   stopforgc((struct garbagelist *)&(((SESEcommon*)(___params___))[1]));");
4206         output.println("   stopforgc((struct garbagelist *)&___locals___);");
4207     }
4208     output.println("     pthread_cond_wait( &("+com+".runningChildrenCond), &("+com+".lock) );");
4209     if (GENERATEPRECISEGC){
4210         output.println("   restartaftergc();");
4211     }
4212     output.println("   }");
4213
4214
4215     // copy out-set from local temps into the sese record
4216     Iterator<TempDescriptor> itr = fsen.getOutVarSet().iterator();
4217     while( itr.hasNext() ) {
4218       TempDescriptor temp = itr.next();
4219
4220       // only have to do this for primitives non-arrays
4221       if( !(
4222             temp.getType().isPrimitive() && !temp.getType().isArray()
4223            )
4224         ) {
4225         continue;
4226       }
4227
4228       // have to determine the context enclosing this sese
4229       boolean useParentContext = false;
4230
4231       if( (state.MLP &&fsen != mlpa.getMainSESE()) || 
4232           (state.OOOJAVA &&fsen != oooa.getMainSESE())
4233       ) {
4234         assert fsen.getParent() != null;
4235         if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
4236           useParentContext = true;
4237         }
4238       }
4239
4240       String from;
4241       if( useParentContext ) {
4242         from = generateTemp( fsen.getParent().getfmBogus(), temp, null );
4243       } else {
4244         from = generateTemp( fsen.getfmEnclosing(),         temp, null );
4245       }
4246
4247       output.println("   "+paramsprefix+
4248                      "->"+temp.getSafeSymbol()+
4249                      " = "+from+";");
4250     }    
4251     
4252     // mark yourself done, your SESE data is now read-only
4253     output.println("   "+com+".doneExecuting = TRUE;");
4254     output.println("   pthread_cond_signal( &("+com+".doneCond) );");
4255     output.println("   pthread_mutex_unlock( &("+com+".lock) );");
4256
4257     // decrement dependency count for all SESE's on your forwarding list
4258     output.println("   while( !isEmpty( "+com+".forwardList ) ) {");
4259     output.println("     SESEcommon* consumer = (SESEcommon*) getItem( "+com+".forwardList );");
4260     
4261    
4262     output.println("     if(consumer->rentryIdx>0){");
4263     output.println("        // resolved null pointer");
4264     output.println("        int idx;");
4265     output.println("        for(idx=0;idx<consumer->rentryIdx;idx++){");
4266     output.println("           resolvePointer(consumer->rentryArray[idx]);");
4267     output.println("        }");
4268     output.println("     }");
4269     
4270     
4271 //    output.println("     pthread_mutex_lock( &(consumer->lock) );");
4272 //  output.println("     --(consumer->unresolvedDependencies);");
4273 //    output.println("     if( consumer->unresolvedDependencies == 0 ) {");
4274     output.println("     if( atomic_sub_and_test(1, &(consumer->unresolvedDependencies)) ){");
4275     output.println("       workScheduleSubmit( (void*)consumer );");
4276     output.println("     }");
4277 //    output.println("     pthread_mutex_unlock( &(consumer->lock) );");
4278     output.println("   }");
4279     
4280     
4281     // eom
4282     // clean up its lock element from waiting queue, and decrement dependency count for next SESE block
4283     if( (state.MLP && fsen != mlpa.getMainSESE()) ||
4284         (state.OOOJAVA && fsen != oooa.getMainSESE())
4285     ) {
4286         
4287                 output.println();
4288                 output.println("   /* check memory dependency*/");
4289                 output.println("  {");                  
4290                 output.println("      int idx;");
4291                 output.println("      for(idx=0;idx<___params___->common.rentryIdx;idx++){");
4292                 output.println("           REntry* re=___params___->common.rentryArray[idx];");
4293                 output.println("           RETIRERENTRY(re->queue,re);");
4294                 output.println("      }");
4295                 output.println("   }");
4296                 
4297     }
4298     
4299     // if parent is stalling on you, let them know you're done
4300     if( (state.MLP && fsexn.getFlatEnter() != mlpa.getMainSESE()) || 
4301         (state.OOOJAVA &&  fsexn.getFlatEnter() != oooa.getMainSESE())    
4302     ) {
4303       output.println("   psem_give( &("+paramsprefix+"->common.stallSem) );");
4304     }
4305
4306     // last of all, decrement your parent's number of running children    
4307     output.println("   if( "+paramsprefix+"->common.parent != NULL ) {");
4308     output.println("     if (atomic_sub_and_test(1, &"+paramsprefix+"->common.parent->numRunningChildren)) {");
4309     if (GENERATEPRECISEGC){
4310         output.println("   stopforgc((struct garbagelist *)&___locals___);");
4311     }
4312     output.println("       pthread_mutex_lock( &("+paramsprefix+"->common.parent->lock) );");
4313     if (GENERATEPRECISEGC){
4314         output.println("   restartaftergc();");
4315     }
4316     output.println("       pthread_cond_signal( &("+paramsprefix+"->common.parent->runningChildrenCond) );");
4317     output.println("       pthread_mutex_unlock( &("+paramsprefix+"->common.parent->lock) );");
4318     output.println("     }");
4319     output.println("   }");
4320
4321     // a task has variables to track static/dynamic instances
4322     // that serve as sources, release the parent's ref of each
4323     // non-null var of these types
4324
4325     output.println("   // releasing static SESEs");
4326     Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
4327     while( pItr.hasNext() ) {
4328       SESEandAgePair pair = pItr.next();
4329       output.println("   if( "+pair+" != NULL ) {");
4330       output.println("     RELEASE_REFERENCE_TO( "+pair+" );");
4331       output.println("   }");
4332     }
4333     output.println("   // releasing dynamic variable sources");
4334     Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
4335     while( dynSrcItr.hasNext() ) {
4336       TempDescriptor dynSrcVar = dynSrcItr.next();
4337       output.println("   if( "+dynSrcVar+"_srcSESE != NULL ) {");
4338       output.println("     RELEASE_REFERENCE_TO( "+dynSrcVar+"_srcSESE );");
4339       output.println("   }");
4340     }    
4341
4342
4343     // destroy this task's mempool if it is not a leaf task
4344     output.println( "#ifndef OOO_DISABLE_TASKMEMPOOL" );
4345     if( !fsen.getIsLeafSESE() ) {
4346       output.println("     pooldestroy( runningSESE->taskRecordMemPool );");
4347     }
4348     output.println( "#endif" );
4349
4350
4351     // if this is not the Main sese (which has no parent) then return
4352     // THIS task's record to the PARENT'S task record pool, and only if
4353     // the reference count is now zero
4354     if( (state.MLP     && fsen != mlpa.getMainSESE()) || 
4355         (state.OOOJAVA && fsen != oooa.getMainSESE())
4356         ) {
4357       output.println("   RELEASE_REFERENCE_TO( runningSESE );");
4358     } else {
4359       // the main task has no parent, just free its record
4360       output.println("   mlpFreeSESErecord( runningSESE );");
4361     }
4362
4363     // as this thread is wrapping up the task, make sure the thread-local var
4364     // for the currently running task record references an invalid task
4365     output.println("   runningSESE = (SESEcommon*) 0x1;");
4366
4367     if( state.COREPROF ) {
4368       output.println("   CP_LOGEVENT( CP_EVENTID_TASKRETIRE, CP_EVENTTYPE_END );");
4369     }
4370   }
4371  
4372   public void generateFlatWriteDynamicVarNode( FlatMethod fm,  
4373                                                LocalityBinding lb, 
4374                                                FlatWriteDynamicVarNode fwdvn,
4375                                                PrintWriter output
4376                                              ) {
4377     if( !(state.MLP || state.OOOJAVA) ) {
4378       // should node should not be in an IR graph if the
4379       // MLP flag is not set
4380       throw new Error("Unexpected presence of FlatWriteDynamicVarNode");
4381     }
4382         
4383     Hashtable<TempDescriptor, VSTWrapper> writeDynamic = fwdvn.getVar2src();
4384
4385     assert writeDynamic != null;
4386
4387     Iterator wdItr = writeDynamic.entrySet().iterator();
4388     while( wdItr.hasNext() ) {
4389       Map.Entry           me     = (Map.Entry)      wdItr.next();
4390       TempDescriptor      refVar = (TempDescriptor) me.getKey();
4391       VSTWrapper          vstW   = (VSTWrapper)     me.getValue();
4392       VariableSourceToken vst    =                  vstW.vst;
4393
4394       output.println("     {");
4395       output.println("       SESEcommon* oldSrc = "+refVar+"_srcSESE;");
4396
4397       if( vst == null ) {
4398         // if there is no given source, this variable is ready so
4399         // mark src pointer NULL to signify that the var is up-to-date
4400         output.println("       "+refVar+"_srcSESE = NULL;");
4401       } else {
4402         // otherwise we track where it will come from
4403         SESEandAgePair instance = new SESEandAgePair( vst.getSESE(), vst.getAge() );
4404         output.println("       "+refVar+"_srcSESE = "+instance+";");    
4405         output.println("       "+refVar+"_srcOffset = (INTPTR) &((("+
4406                        vst.getSESE().getSESErecordName()+"*)0)->"+vst.getAddrVar()+");");
4407       }
4408
4409       // no matter what we did above, track reference count of whatever
4410       // this variable pointed to, do release last in case we're just
4411       // copying the same value in because 1->2->1 is safe but ref count
4412       // 1->0->1 has a window where it looks like it should be free'd
4413       output.println("       if( "+refVar+"_srcSESE != NULL ) {");
4414       output.println("         ADD_REFERENCE_TO( "+refVar+"_srcSESE );");
4415       output.println("       }");
4416       output.println("       if( oldSrc != NULL ) {");
4417       output.println("         RELEASE_REFERENCE_TO( oldSrc );");
4418       output.println("       }");
4419       output.println("     }");
4420     }   
4421   }
4422
4423   
4424   private void generateFlatCheckNode(FlatMethod fm,  LocalityBinding lb, FlatCheckNode fcn, PrintWriter output) {
4425     if (state.CONSCHECK) {
4426       String specname=fcn.getSpec();
4427       String varname="repairstate___";
4428       output.println("{");
4429       output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
4430
4431       TempDescriptor[] temps=fcn.getTemps();
4432       String[] vars=fcn.getVars();
4433       for(int i=0; i<temps.length; i++) {
4434         output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i],lb)+";");
4435       }
4436
4437       output.println("if (doanalysis"+specname+"("+varname+")) {");
4438       output.println("free"+specname+"_state("+varname+");");
4439       output.println("} else {");
4440       output.println("/* Bad invariant */");
4441       output.println("free"+specname+"_state("+varname+");");
4442       output.println("abort_task();");
4443       output.println("}");
4444       output.println("}");
4445     }
4446   }
4447
4448   private void generateFlatCall(FlatMethod fm, LocalityBinding lb, FlatCall fc, PrintWriter output) {
4449
4450     MethodDescriptor md=fc.getMethod();
4451     ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? locality.getBinding(lb, fc) : md);
4452     ClassDescriptor cn=md.getClassDesc();
4453     output.println("{");
4454     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4455       if (lb!=null) {
4456         LocalityBinding fclb=locality.getBinding(lb, fc);
4457         output.print("       struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
4458       } else
4459         output.print("       struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
4460       output.print(objectparams.numPointers());
4461       output.print(", "+localsprefixaddr);
4462       if (md.getThis()!=null) {
4463         output.print(", ");
4464         output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis(),lb));
4465       }
4466       if (fc.getThis()!=null&&md.getThis()==null) {
4467         System.out.println("WARNING!!!!!!!!!!!!");
4468         System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
4469       }
4470
4471
4472       for(int i=0; i<fc.numArgs(); i++) {
4473         Descriptor var=md.getParameter(i);
4474         TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
4475         if (objectparams.isParamPtr(paramtemp)) {
4476           TempDescriptor targ=fc.getArg(i);
4477           output.print(", ");
4478           TypeDescriptor td=md.getParamType(i);
4479           if (td.isTag())
4480             output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()  +" *)"+generateTemp(fm, targ,lb));
4481           else
4482             output.print("(struct "+md.getParamType(i).getSafeSymbol()  +" *)"+generateTemp(fm, targ,lb));
4483         }
4484       }
4485       output.println("};");
4486     }
4487     output.print("       ");
4488
4489
4490     if (fc.getReturnTemp()!=null)
4491       output.print(generateTemp(fm,fc.getReturnTemp(),lb)+"=");
4492
4493     /* Do we need to do virtual dispatch? */
4494     if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
4495       //no
4496       if (lb!=null) {
4497         LocalityBinding fclb=locality.getBinding(lb, fc);
4498         output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
4499       } else {
4500         output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
4501       }
4502     } else {
4503       //yes
4504       output.print("((");
4505       if (md.getReturnType().isClass()||md.getReturnType().isArray())
4506         output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
4507       else
4508         output.print(md.getReturnType().getSafeSymbol()+" ");
4509       output.print("(*)(");
4510
4511       boolean printcomma=false;
4512       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4513         if (lb!=null) {
4514           LocalityBinding fclb=locality.getBinding(lb, fc);
4515           output.print("struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
4516         } else
4517           output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
4518         printcomma=true;
4519       }
4520
4521       for(int i=0; i<objectparams.numPrimitives(); i++) {
4522         TempDescriptor temp=objectparams.getPrimitive(i);
4523         if (printcomma)
4524           output.print(", ");
4525         printcomma=true;
4526         if (temp.getType().isClass()||temp.getType().isArray())
4527           output.print("struct " + temp.getType().getSafeSymbol()+" * ");
4528         else
4529           output.print(temp.getType().getSafeSymbol());
4530       }
4531
4532
4533       if (lb!=null) {
4534         LocalityBinding fclb=locality.getBinding(lb, fc);
4535         output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])");
4536       } else
4537         output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
4538     }
4539
4540     output.print("(");
4541     boolean needcomma=false;
4542     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4543       output.print("&__parameterlist__");
4544       needcomma=true;
4545     }
4546
4547     if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
4548       if (fc.getThis()!=null) {
4549         TypeDescriptor ptd=md.getThis().getType();
4550         if (needcomma)
4551           output.print(",");
4552         if (ptd.isClass()&&!ptd.isArray())
4553           output.print("(struct "+ptd.getSafeSymbol()+" *) ");
4554         output.print(generateTemp(fm,fc.getThis(),lb));
4555         needcomma=true;
4556       }
4557     }
4558
4559     for(int i=0; i<fc.numArgs(); i++) {
4560       Descriptor var=md.getParameter(i);
4561       TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
4562       if (objectparams.isParamPrim(paramtemp)) {
4563         TempDescriptor targ=fc.getArg(i);
4564         if (needcomma)
4565           output.print(", ");
4566
4567         TypeDescriptor ptd=md.getParamType(i);
4568         if (ptd.isClass()&&!ptd.isArray())
4569           output.print("(struct "+ptd.getSafeSymbol()+" *) ");
4570         output.print(generateTemp(fm, targ,lb));
4571         needcomma=true;
4572       }
4573     }
4574     output.println(");");
4575     output.println("   }");
4576   }
4577
4578   private boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
4579     Set subclasses=typeutil.getSubClasses(thiscd);
4580     if (subclasses==null)
4581       return true;
4582     for(Iterator classit=subclasses.iterator(); classit.hasNext();) {
4583       ClassDescriptor cd=(ClassDescriptor)classit.next();
4584       Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol());
4585       for(Iterator matchit=possiblematches.iterator(); matchit.hasNext();) {
4586         MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
4587         if (md.matches(matchmd))
4588           return false;
4589       }
4590     }
4591     return true;
4592   }
4593
4594   private void generateFlatFieldNode(FlatMethod fm, LocalityBinding lb, FlatFieldNode ffn, PrintWriter output) {
4595     if (state.SINGLETM) {
4596       //single machine transactional memory case
4597       String field=ffn.getField().getSafeSymbol();
4598       String src=generateTemp(fm, ffn.getSrc(),lb);
4599       String dst=generateTemp(fm, ffn.getDst(),lb);
4600
4601       output.println(dst+"="+ src +"->"+field+ ";");
4602       if (ffn.getField().getType().isPtr()&&locality.getAtomic(lb).get(ffn).intValue()>0&&
4603           locality.getNodePreTempInfo(lb, ffn).get(ffn.getSrc())!=LocalityAnalysis.SCRATCH) {
4604         if ((dc==null)||(!state.READSET&&dc.getNeedTrans(lb, ffn))||
4605             (state.READSET&&dc.getNeedWriteTrans(lb, ffn))) {
4606           output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));");
4607         } else if (state.READSET&&dc.getNeedTrans(lb, ffn)) {
4608           if (state.HYBRID&&delaycomp.getConv(lb).contains(ffn)) {
4609             output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4610           } else
4611             output.println("TRANSREADRD("+dst+", "+dst+");");
4612         }
4613       }
4614     } else if (state.DSM) {
4615       Integer status=locality.getNodePreTempInfo(lb,ffn).get(ffn.getSrc());
4616       if (status==LocalityAnalysis.GLOBAL) {
4617         String field=ffn.getField().getSafeSymbol();
4618         String src=generateTemp(fm, ffn.getSrc(),lb);
4619         String dst=generateTemp(fm, ffn.getDst(),lb);
4620
4621         if (ffn.getField().getType().isPtr()) {
4622
4623           //TODO: Uncomment this when we have runtime support
4624           //if (ffn.getSrc()==ffn.getDst()) {
4625           //output.println("{");
4626           //output.println("void * temp="+src+";");
4627           //output.println("if (temp&0x1) {");
4628           //output.println("temp=(void *) transRead(trans, (unsigned int) temp);");
4629           //output.println(src+"->"+field+"="+temp+";");
4630           //output.println("}");
4631           //output.println(dst+"=temp;");
4632           //output.println("}");
4633           //} else {
4634           output.println(dst+"="+ src +"->"+field+ ";");
4635           //output.println("if ("+dst+"&0x1) {");
4636           //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
4637       output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
4638           //output.println(src+"->"+field+"="+src+"->"+field+";");
4639           //output.println("}");
4640           //}
4641         } else {
4642           output.println(dst+"="+ src+"->"+field+";");
4643         }
4644       } else if (status==LocalityAnalysis.LOCAL) {
4645         if (ffn.getField().getType().isPtr()&&
4646             ffn.getField().isGlobal()) {
4647           String field=ffn.getField().getSafeSymbol();
4648           String src=generateTemp(fm, ffn.getSrc(),lb);
4649           String dst=generateTemp(fm, ffn.getDst(),lb);
4650           output.println(dst+"="+ src +"->"+field+ ";");
4651           if (locality.getAtomic(lb).get(ffn).intValue()>0)
4652             //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
4653             output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
4654         } else
4655           output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4656       } else if (status==LocalityAnalysis.EITHER) {
4657         //Code is reading from a null pointer
4658         output.println("if ("+generateTemp(fm, ffn.getSrc(),lb)+") {");
4659         output.println("#ifndef RAW");
4660         output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4661         output.println("#endif");
4662         //This should throw a suitable null pointer error
4663         output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4664       } else
4665         throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4666     } else{
4667 // DEBUG        if(!ffn.getDst().getType().isPrimitive()){
4668 // DEBUG                output.println("within((void*)"+generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+");");
4669 // DEBUG        }      
4670       output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4671     }
4672   }
4673
4674
4675   private void generateFlatSetFieldNode(FlatMethod fm, LocalityBinding lb, FlatSetFieldNode fsfn, PrintWriter output) {
4676     if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
4677       throw new Error("Can't set array length");
4678     if (state.SINGLETM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
4679       //Single Machine Transaction Case
4680       boolean srcptr=fsfn.getSrc().getType().isPtr();
4681       String src=generateTemp(fm,fsfn.getSrc(),lb);
4682       String dst=generateTemp(fm,fsfn.getDst(),lb);
4683       output.println("//"+srcptr+" "+fsfn.getSrc().getType().isNull());
4684       if (srcptr&&!fsfn.getSrc().getType().isNull()) {
4685         output.println("{");
4686         if ((dc==null)||dc.getNeedSrcTrans(lb, fsfn)&&
4687             locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) {
4688           output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4689         } else {
4690           output.println("INTPTR srcoid=(INTPTR)"+src+";");
4691         }
4692       }
4693       if (wb.needBarrier(fsfn)&&
4694           locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getDst())!=LocalityAnalysis.SCRATCH) {
4695         if (state.EVENTMONITOR) {
4696           output.println("if ("+dst+"->___objstatus___&DIRTY) EVLOGEVENTOBJ(EV_WRITE,"+dst+"->objuid)");
4697         }
4698         output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;");
4699       }
4700       if (srcptr&!fsfn.getSrc().getType().isNull()) {
4701         output.println("*((unsigned INTPTR *)&("+dst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4702         output.println("}");
4703       } else {
4704         output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4705       }
4706     } else if (state.DSM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
4707       Integer statussrc=locality.getNodePreTempInfo(lb,fsfn).get(fsfn.getSrc());
4708       Integer statusdst=locality.getNodeTempInfo(lb).get(fsfn).get(fsfn.getDst());
4709       boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4710
4711       String src=generateTemp(fm,fsfn.getSrc(),lb);
4712       String dst=generateTemp(fm,fsfn.getDst(),lb);
4713       if (srcglobal) {
4714         output.println("{");
4715         output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4716       }
4717       if (statusdst.equals(LocalityAnalysis.GLOBAL)) {
4718         String glbdst=dst;
4719         //mark it dirty
4720         if (wb.needBarrier(fsfn))
4721           output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;");
4722         if (srcglobal) {
4723           output.println("*((unsigned INTPTR *)&("+glbdst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4724         } else
4725           output.println(glbdst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4726       } else if (statusdst.equals(LocalityAnalysis.LOCAL)) {
4727         /** Check if we need to copy */
4728         output.println("if(!"+dst+"->"+localcopystr+") {");
4729         /* Link object into list */
4730         String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4731         output.println(revertptr+"=revertlist;");
4732         if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4733           output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4734         else
4735           output.println("COPY_OBJ("+dst+");");
4736         output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4737         output.println("revertlist=(struct ___Object___ *)"+dst+";");
4738         output.println("}");
4739         if (srcglobal)
4740           output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4741         else
4742           output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4743       } else if (statusdst.equals(LocalityAnalysis.EITHER)) {
4744         //writing to a null...bad
4745         output.println("if ("+dst+") {");
4746         output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}");
4747         if (srcglobal)
4748           output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4749         else
4750           output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4751       }
4752       if (srcglobal) {
4753         output.println("}");
4754       }
4755     } else {
4756       if (state.FASTCHECK) {
4757         String dst=generateTemp(fm, fsfn.getDst(),lb);
4758         output.println("if(!"+dst+"->"+localcopystr+") {");
4759         /* Link object into list */
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+"="+fcrevert+";");
4765         output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4766         output.println("}");
4767       }
4768       
4769 // DEBUG        if(!fsfn.getField().getType().isPrimitive()){
4770 // DEBUG                output.println("within((void*)"+generateTemp(fm,fsfn.getSrc(),lb)+");");
4771 // DEBUG   }   
4772       output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
4773     }
4774   }
4775
4776   private void generateFlatElementNode(FlatMethod fm, LocalityBinding lb, FlatElementNode fen, PrintWriter output) {
4777     TypeDescriptor elementtype=fen.getSrc().getType().dereference();
4778     String type="";
4779
4780     if (elementtype.isArray()||elementtype.isClass())
4781       type="void *";
4782     else
4783       type=elementtype.getSafeSymbol()+" ";
4784
4785     if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
4786       output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fen.getIndex(),lb)+") >= "+generateTemp(fm,fen.getSrc(),lb) + "->___length___))");
4787       output.println("failedboundschk();");
4788     }
4789     if (state.SINGLETM) {
4790       //Single machine transaction case
4791       String dst=generateTemp(fm, fen.getDst(),lb);
4792       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))) {
4793         output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4794       } else {
4795         output.println("STMGETARRAY("+dst+", "+ generateTemp(fm,fen.getSrc(),lb)+", "+generateTemp(fm, fen.getIndex(),lb)+", "+type+");");
4796       }
4797
4798       if (elementtype.isPtr()&&locality.getAtomic(lb).get(fen).intValue()>0&&
4799           locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())!=LocalityAnalysis.SCRATCH) {
4800         if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fen)||state.READSET&&dc.getNeedWriteTrans(lb, fen)) {
4801           output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));");
4802         } else if (state.READSET&&dc.getNeedTrans(lb, fen)) {
4803           if (state.HYBRID&&delaycomp.getConv(lb).contains(fen)) {
4804             output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4805           } else
4806             output.println("TRANSREADRD("+dst+", "+dst+");");
4807         }
4808       }
4809     } else if (state.DSM) {
4810       Integer status=locality.getNodePreTempInfo(lb,fen).get(fen.getSrc());
4811       if (status==LocalityAnalysis.GLOBAL) {
4812         String dst=generateTemp(fm, fen.getDst(),lb);
4813         if (elementtype.isPtr()) {
4814           output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4815           //DEBUG: output.println("TRANSREAD("+dst+", "+dst+",\""+fm+":"+fen+"\");");
4816           output.println("TRANSREAD("+dst+", "+dst+");");
4817         } else {
4818           output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4819         }
4820       } else if (status==LocalityAnalysis.LOCAL) {
4821         output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4822       } else if (status==LocalityAnalysis.EITHER) {
4823         //Code is reading from a null pointer
4824         output.println("if ("+generateTemp(fm, fen.getSrc(),lb)+") {");
4825         output.println("#ifndef RAW");
4826         output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4827         output.println("#endif");
4828         //This should throw a suitable null pointer error
4829         output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4830       } else
4831         throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4832     } else {
4833 // DEBUG output.println("within((void*)"+generateTemp(fm,fen.getSrc(),lb)+");");
4834         output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4835     }
4836   }
4837
4838   private void generateFlatSetElementNode(FlatMethod fm, LocalityBinding lb, FlatSetElementNode fsen, PrintWriter output) {
4839     //TODO: need dynamic check to make sure this assignment is actually legal
4840     //Because Object[] could actually be something more specific...ie. Integer[]
4841
4842     TypeDescriptor elementtype=fsen.getDst().getType().dereference();
4843     String type="";
4844
4845     if (elementtype.isArray()||elementtype.isClass())
4846       type="void *";
4847     else
4848       type=elementtype.getSafeSymbol()+" ";
4849
4850     if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
4851       output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fsen.getIndex(),lb)+") >= "+generateTemp(fm,fsen.getDst(),lb) + "->___length___))");
4852       output.println("failedboundschk();");
4853     }
4854
4855     if (state.SINGLETM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4856       //Transaction set element case
4857       if (wb.needBarrier(fsen)&&
4858           locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH) {
4859         output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___objstatus___))|=DIRTY;");
4860       }
4861       if (fsen.getSrc().getType().isPtr()&&!fsen.getSrc().getType().isNull()) {
4862         output.println("{");
4863         String src=generateTemp(fm, fsen.getSrc(), lb);
4864         if ((dc==null)||dc.getNeedSrcTrans(lb, fsen)&&
4865             locality.getNodePreTempInfo(lb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) {
4866           output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4867         } else {
4868           output.println("INTPTR srcoid=(INTPTR)"+src+";");
4869         }
4870         if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
4871           output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", srcoid, INTPTR);");
4872         } else {
4873           output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
4874         }
4875         output.println("}");
4876       } else {
4877         if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
4878           output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", "+ generateTemp(fm, fsen.getSrc(), lb) +", "+type+");");
4879         } else {
4880           output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4881         }
4882       }
4883     } else if (state.DSM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4884       Integer statussrc=locality.getNodePreTempInfo(lb,fsen).get(fsen.getSrc());
4885       Integer statusdst=locality.getNodePreTempInfo(lb,fsen).get(fsen.getDst());
4886       boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4887       boolean dstglobal=statusdst==LocalityAnalysis.GLOBAL;
4888       boolean dstlocal=(statusdst==LocalityAnalysis.LOCAL)||(statusdst==LocalityAnalysis.EITHER);
4889       
4890       if (dstglobal) {
4891         if (wb.needBarrier(fsen))
4892           output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___localcopy___))|=DIRTY;");
4893       } else if (dstlocal) {
4894         /** Check if we need to copy */
4895         String dst=generateTemp(fm, fsen.getDst(),lb);
4896         output.println("if(!"+dst+"->"+localcopystr+") {");
4897         /* Link object into list */
4898         String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4899         output.println(revertptr+"=revertlist;");
4900         if ((GENERATEPRECISEGC) || this.state.MULTICOREGC)
4901         output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4902         else
4903           output.println("COPY_OBJ("+dst+");");
4904         output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4905         output.println("revertlist=(struct ___Object___ *)"+dst+";");
4906         output.println("}");
4907       } else {
4908         System.out.println("Node: "+fsen);
4909         System.out.println(lb);
4910         System.out.println("statusdst="+statusdst);
4911         System.out.println(fm.printMethod());
4912         throw new Error("Unknown array type");
4913       }
4914       if (srcglobal) {
4915         output.println("{");
4916         String src=generateTemp(fm, fsen.getSrc(), lb);
4917         output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4918         output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
4919         output.println("}");
4920       } else {
4921         output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4922       }
4923     } else {
4924       if (state.FASTCHECK) {
4925         String dst=generateTemp(fm, fsen.getDst(),lb);
4926         output.println("if(!"+dst+"->"+localcopystr+") {");
4927         /* Link object into list */
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+"="+fcrevert+";");
4933         output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4934         output.println("}");
4935       }
4936 // DEBUG      output.println("within((void*)"+generateTemp(fm,fsen.getDst(),lb)+");");
4937       output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4938     }
4939   }
4940
4941   protected void generateFlatNew(FlatMethod fm, LocalityBinding lb, FlatNew fn, PrintWriter output) {
4942     if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
4943       //Stash pointer in case of GC
4944       String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4945       output.println(revertptr+"=revertlist;");
4946     }
4947     if (state.SINGLETM) {
4948       if (fn.getType().isArray()) {
4949         int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4950         if (locality.getAtomic(lb).get(fn).intValue()>0) {
4951           //inside transaction
4952           output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4953         } else {
4954           //outside transaction
4955           output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4956         }
4957       } else {
4958         if (locality.getAtomic(lb).get(fn).intValue()>0) {
4959           //inside transaction
4960           output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4961         } else {
4962           //outside transaction
4963           output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4964         }
4965       }
4966     } else if (fn.getType().isArray()) {
4967       int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4968       if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4969         output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4970       } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4971           if(this.state.MLP || state.OOOJAVA){
4972             output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray_mlp("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+", oid, "+oooa.getDisjointAnalysis().getAllocationSiteFromFlatNew(fn).getUniqueAllocSiteID()+");");
4973         output.println("    oid += numWorkers;");
4974           }else{
4975     output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");                      
4976           }
4977       } else {
4978         output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4979       }
4980     } else {
4981       if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4982         output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");");
4983       } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4984           if (this.state.MLP || state.OOOJAVA){
4985         output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new_mlp("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+", oid, "+oooa.getDisjointAnalysis().getAllocationSiteFromFlatNew(fn).getUniqueAllocSiteID()+");");
4986         output.println("    oid += numWorkers;");
4987           } else {
4988     output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");                      
4989           }
4990       } else {
4991         output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
4992       }
4993     }
4994     if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
4995       String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4996       String dst=generateTemp(fm,fn.getDst(),lb);
4997       output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
4998       output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4999       output.println("revertlist=(struct ___Object___ *)"+dst+";");
5000     }
5001     if (state.FASTCHECK) {
5002       String dst=generateTemp(fm,fn.getDst(),lb);
5003       output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
5004       output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
5005       output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
5006     }
5007   }
5008
5009   private void generateFlatTagDeclaration(FlatMethod fm, LocalityBinding lb, FlatTagDeclaration fn, PrintWriter output) {
5010     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5011       output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
5012     } else {
5013       output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+state.getTagId(fn.getType())+");");
5014     }
5015   }
5016
5017   private void generateFlatOpNode(FlatMethod fm, LocalityBinding lb, FlatOpNode fon, PrintWriter output) {
5018     if (fon.getRight()!=null) {
5019       if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
5020         if (fon.getLeft().getType().isLong())
5021           output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
5022         else
5023           output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned int)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
5024
5025       } else if (dc!=null) {
5026         output.print(generateTemp(fm, fon.getDest(),lb)+" = (");
5027         if (fon.getLeft().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
5028             output.print("(void *)");
5029         if (dc.getNeedLeftSrcTrans(lb, fon))
5030           output.print("("+generateTemp(fm, fon.getLeft(),lb)+"!=NULL?"+generateTemp(fm, fon.getLeft(),lb)+"->"+oidstr+":NULL)");
5031         else
5032           output.print(generateTemp(fm, fon.getLeft(),lb));
5033         output.print(")"+fon.getOp().toString()+"(");
5034         if (fon.getRight().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
5035             output.print("(void *)");
5036         if (dc.getNeedRightSrcTrans(lb, fon))
5037           output.println("("+generateTemp(fm, fon.getRight(),lb)+"!=NULL?"+generateTemp(fm, fon.getRight(),lb)+"->"+oidstr+":NULL));");
5038         else
5039           output.println(generateTemp(fm,fon.getRight(),lb)+");");
5040       } else
5041         output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+fon.getOp().toString()+generateTemp(fm,fon.getRight(),lb)+";");
5042     } else if (fon.getOp().getOp()==Operation.ASSIGN)
5043       output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
5044     else if (fon.getOp().getOp()==Operation.UNARYPLUS)
5045       output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
5046     else if (fon.getOp().getOp()==Operation.UNARYMINUS)
5047       output.println(generateTemp(fm, fon.getDest(),lb)+" = -"+generateTemp(fm, fon.getLeft(),lb)+";");
5048     else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
5049       output.println(generateTemp(fm, fon.getDest(),lb)+" = !"+generateTemp(fm, fon.getLeft(),lb)+";");
5050     else if (fon.getOp().getOp()==Operation.COMP)
5051       output.println(generateTemp(fm, fon.getDest(),lb)+" = ~"+generateTemp(fm, fon.getLeft(),lb)+";");
5052     else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
5053       output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+"->fses==NULL;");
5054     } else
5055       output.println(generateTemp(fm, fon.getDest(),lb)+fon.getOp().toString()+generateTemp(fm, fon.getLeft(),lb)+";");
5056   }
5057
5058   private void generateFlatCastNode(FlatMethod fm, LocalityBinding lb, FlatCastNode fcn, PrintWriter output) {
5059     /* TODO: Do type check here */
5060     if (fcn.getType().isArray()) {
5061       output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
5062     } else if (fcn.getType().isClass())
5063       output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
5064     else
5065       output.println(generateTemp(fm,fcn.getDst(),lb)+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc(),lb)+";");
5066   }
5067
5068   private void generateFlatLiteralNode(FlatMethod fm, LocalityBinding lb, FlatLiteralNode fln, PrintWriter output) {
5069     if (fln.getValue()==null)
5070       output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
5071     else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
5072       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5073         if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
5074           //Stash pointer in case of GC
5075           String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5076           output.println(revertptr+"=revertlist;");
5077         }
5078         output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
5079         if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
5080           //Stash pointer in case of GC
5081           String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5082           output.println("revertlist="+revertptr+";");
5083         }
5084       } else {
5085         output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
5086       }
5087     } else if (fln.getType().isBoolean()) {
5088       if (((Boolean)fln.getValue()).booleanValue())
5089         output.println(generateTemp(fm, fln.getDst(),lb)+"=1;");
5090       else
5091         output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
5092     } else if (fln.getType().isChar()) {
5093       String st=FlatLiteralNode.escapeString(fln.getValue().toString());
5094       output.println(generateTemp(fm, fln.getDst(),lb)+"='"+st+"';");
5095     } else if (fln.getType().isLong()) {
5096       output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+"LL;");
5097     } else
5098       output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+";");
5099   }
5100
5101   protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) {
5102     if (frn.getReturnTemp()!=null) {
5103       if (frn.getReturnTemp().getType().isPtr())
5104         output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";");
5105       else
5106         output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";");
5107     } else {
5108       output.println("return;");
5109     }
5110   }
5111
5112   protected void generateStoreFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
5113     int left=-1;
5114     int right=-1;
5115     //only record if this group has more than one exit
5116     if (branchanalysis.numJumps(fcb)>1) {
5117       left=branchanalysis.jumpValue(fcb, 0);
5118       right=branchanalysis.jumpValue(fcb, 1);
5119     }
5120     output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") {");
5121     if (right!=-1)
5122       output.println("STOREBRANCH("+right+");");
5123     output.println("goto "+label+";");
5124     output.println("}");
5125     if (left!=-1)
5126       output.println("STOREBRANCH("+left+");");
5127   }
5128
5129   protected void generateFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
5130     output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") goto "+label+";");
5131   }
5132
5133   /** This method generates header information for the method or
5134    * task referenced by the Descriptor des. */
5135   private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) {
5136     generateHeader(fm, lb, des, output, false);
5137   }
5138
5139   private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output, boolean addSESErecord) {
5140     /* Print header */
5141     ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : des);
5142     MethodDescriptor md=null;
5143     TaskDescriptor task=null;
5144     if (des instanceof MethodDescriptor)
5145       md=(MethodDescriptor) des;
5146     else
5147       task=(TaskDescriptor) des;
5148
5149     ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
5150
5151     if (md!=null&&md.getReturnType()!=null) {
5152       if (md.getReturnType().isClass()||md.getReturnType().isArray())
5153         output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
5154       else
5155         output.print(md.getReturnType().getSafeSymbol()+" ");
5156     } else
5157       //catch the constructor case
5158       output.print("void ");
5159     if (md!=null) {
5160       if (state.DSM||state.SINGLETM) {
5161         output.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
5162       } else
5163         output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
5164     } else
5165       output.print(task.getSafeSymbol()+"(");
5166     
5167     boolean printcomma=false;
5168     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5169       if (md!=null) {
5170         if (state.DSM||state.SINGLETM) {
5171           output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
5172         } else
5173           output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
5174       } else
5175         output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
5176       printcomma=true;
5177     }
5178
5179     if (md!=null) {
5180       /* Method */
5181       for(int i=0; i<objectparams.numPrimitives(); i++) {
5182         TempDescriptor temp=objectparams.getPrimitive(i);
5183         if (printcomma)
5184           output.print(", ");
5185         printcomma=true;
5186         if (temp.getType().isClass()||temp.getType().isArray())
5187           output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
5188         else
5189           output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
5190       }
5191       output.println(") {");
5192     } else if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
5193       /* Imprecise Task */
5194       output.println("void * parameterarray[]) {");
5195       /* Unpack variables */
5196       for(int i=0; i<objectparams.numPrimitives(); i++) {
5197         TempDescriptor temp=objectparams.getPrimitive(i);
5198         output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
5199       }
5200       for(int i=0; i<fm.numTags(); i++) {
5201         TempDescriptor temp=fm.getTag(i);
5202         int offset=i+objectparams.numPrimitives();
5203         output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
5204       }
5205
5206       if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
5207         maxtaskparams=objectparams.numPrimitives()+fm.numTags();
5208     } else output.println(") {");
5209   }
5210
5211   public void generateFlatFlagActionNode(FlatMethod fm, LocalityBinding lb, FlatFlagActionNode ffan, PrintWriter output) {
5212     output.println("/* FlatFlagActionNode */");
5213
5214
5215     /* Process tag changes */
5216     Relation tagsettable=new Relation();
5217     Relation tagcleartable=new Relation();
5218
5219     Iterator tagsit=ffan.getTempTagPairs();
5220     while (tagsit.hasNext()) {
5221       TempTagPair ttp=(TempTagPair) tagsit.next();
5222       TempDescriptor objtmp=ttp.getTemp();
5223       TagDescriptor tag=ttp.getTag();
5224       TempDescriptor tagtmp=ttp.getTagTemp();
5225       boolean tagstatus=ffan.getTagChange(ttp);
5226       if (tagstatus) {
5227         tagsettable.put(objtmp, tagtmp);
5228       } else {
5229         tagcleartable.put(objtmp, tagtmp);
5230       }
5231     }
5232
5233
5234     Hashtable flagandtable=new Hashtable();
5235     Hashtable flagortable=new Hashtable();
5236
5237     /* Process flag changes */
5238     Iterator flagsit=ffan.getTempFlagPairs();
5239     while(flagsit.hasNext()) {
5240       TempFlagPair tfp=(TempFlagPair)flagsit.next();
5241       TempDescriptor temp=tfp.getTemp();
5242       Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
5243       FlagDescriptor flag=tfp.getFlag();
5244       if (flag==null) {
5245         //Newly allocate objects that don't set any flags case
5246         if (flagortable.containsKey(temp)) {
5247           throw new Error();
5248         }
5249         int mask=0;
5250         flagortable.put(temp,new Integer(mask));
5251       } else {
5252         int flagid=1<<((Integer)flagtable.get(flag)).intValue();
5253         boolean flagstatus=ffan.getFlagChange(tfp);
5254         if (flagstatus) {
5255           int mask=0;
5256           if (flagortable.containsKey(temp)) {
5257             mask=((Integer)flagortable.get(temp)).intValue();
5258           }
5259           mask|=flagid;
5260           flagortable.put(temp,new Integer(mask));
5261         } else {
5262           int mask=0xFFFFFFFF;
5263           if (flagandtable.containsKey(temp)) {
5264             mask=((Integer)flagandtable.get(temp)).intValue();
5265           }
5266           mask&=(0xFFFFFFFF^flagid);
5267           flagandtable.put(temp,new Integer(mask));
5268         }
5269       }
5270     }
5271
5272
5273     HashSet flagtagset=new HashSet();
5274     flagtagset.addAll(flagortable.keySet());
5275     flagtagset.addAll(flagandtable.keySet());
5276     flagtagset.addAll(tagsettable.keySet());
5277     flagtagset.addAll(tagcleartable.keySet());
5278
5279     Iterator ftit=flagtagset.iterator();
5280     while(ftit.hasNext()) {
5281       TempDescriptor temp=(TempDescriptor)ftit.next();
5282
5283
5284       Set tagtmps=tagcleartable.get(temp);
5285       if (tagtmps!=null) {
5286         Iterator tagit=tagtmps.iterator();
5287         while(tagit.hasNext()) {
5288           TempDescriptor tagtmp=(TempDescriptor)tagit.next();
5289           if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
5290             output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5291           else
5292             output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5293         }
5294       }
5295
5296       tagtmps=tagsettable.get(temp);
5297       if (tagtmps!=null) {
5298         Iterator tagit=tagtmps.iterator();
5299         while(tagit.hasNext()) {
5300           TempDescriptor tagtmp=(TempDescriptor)tagit.next();
5301           if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
5302             output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5303           else
5304             output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp, lb)+", "+generateTemp(fm,tagtmp, lb)+");");
5305         }
5306       }
5307
5308       int ormask=0;
5309       int andmask=0xFFFFFFF;
5310
5311       if (flagortable.containsKey(temp))
5312         ormask=((Integer)flagortable.get(temp)).intValue();
5313       if (flagandtable.containsKey(temp))
5314         andmask=((Integer)flagandtable.get(temp)).intValue();
5315       generateFlagOrAnd(ffan, fm, lb, temp, output, ormask, andmask);
5316       generateObjectDistribute(ffan, fm, lb, temp, output);
5317     }
5318   }
5319
5320   protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp,
5321                                    PrintWriter output, int ormask, int andmask) {
5322     if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
5323       output.println("flagorandinit("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
5324     } else {
5325       output.println("flagorand("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
5326     }
5327   }
5328
5329   protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, PrintWriter output) {
5330     output.println("enqueueObject("+generateTemp(fm, temp, lb)+");");
5331   }
5332
5333   void generateOptionalHeader(PrintWriter headers) {
5334
5335     //GENERATE HEADERS
5336     headers.println("#include \"task.h\"\n\n");
5337     headers.println("#ifndef _OPTIONAL_STRUCT_");
5338     headers.println("#define _OPTIONAL_STRUCT_");
5339
5340     //STRUCT PREDICATEMEMBER
5341     headers.println("struct predicatemember{");
5342     headers.println("int type;");
5343     headers.println("int numdnfterms;");
5344     headers.println("int * flags;");
5345     headers.println("int numtags;");
5346     headers.println("int * tags;\n};\n\n");
5347
5348     //STRUCT OPTIONALTASKDESCRIPTOR
5349     headers.println("struct optionaltaskdescriptor{");
5350     headers.println("struct taskdescriptor * task;");
5351     headers.println("int index;");
5352     headers.println("int numenterflags;");
5353     headers.println("int * enterflags;");
5354     headers.println("int numpredicatemembers;");
5355     headers.println("struct predicatemember ** predicatememberarray;");
5356     headers.println("};\n\n");
5357
5358     //STRUCT TASKFAILURE
5359     headers.println("struct taskfailure {");
5360     headers.println("struct taskdescriptor * task;");
5361     headers.println("int index;");
5362     headers.println("int numoptionaltaskdescriptors;");
5363     headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
5364
5365     //STRUCT FSANALYSISWRAPPER
5366     headers.println("struct fsanalysiswrapper{");
5367     headers.println("int  flags;");
5368     headers.println("int numtags;");
5369     headers.println("int * tags;");
5370     headers.println("int numtaskfailures;");
5371     headers.println("struct taskfailure ** taskfailurearray;");
5372     headers.println("int numoptionaltaskdescriptors;");
5373     headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
5374
5375     //STRUCT CLASSANALYSISWRAPPER
5376     headers.println("struct classanalysiswrapper{");
5377     headers.println("int type;");
5378     headers.println("int numotd;");
5379     headers.println("struct optionaltaskdescriptor ** otdarray;");
5380     headers.println("int numfsanalysiswrappers;");
5381     headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
5382
5383     headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
5384
5385     Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
5386     while(taskit.hasNext()) {
5387       TaskDescriptor td=(TaskDescriptor)taskit.next();
5388       headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
5389     }
5390
5391   }
5392
5393   //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
5394   int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
5395     int predicateindex = 0;
5396     //iterate through the classes concerned by the predicate
5397     Set c_vard = predicate.vardescriptors;
5398     Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
5399     int current_slot=0;
5400
5401     for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext();) {
5402       VarDescriptor vard = (VarDescriptor)vard_it.next();
5403       TypeDescriptor typed = vard.getType();
5404
5405       //generate for flags
5406       HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
5407       output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5408       int numberterms=0;
5409       if (fen_hashset!=null) {
5410         for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext();) {
5411           FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
5412           if (fen!=null) {
5413             DNFFlag dflag=fen.getDNF();
5414             numberterms+=dflag.size();
5415
5416             Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
5417
5418             for(int j=0; j<dflag.size(); j++) {
5419               if (j!=0)
5420                 output.println(",");
5421               Vector term=dflag.get(j);
5422               int andmask=0;
5423               int checkmask=0;
5424               for(int k=0; k<term.size(); k++) {
5425                 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
5426                 FlagDescriptor fd=dfa.getFlag();
5427                 boolean negated=dfa.getNegated();
5428                 int flagid=1<<((Integer)flags.get(fd)).intValue();
5429                 andmask|=flagid;
5430                 if (!negated)
5431                   checkmask|=flagid;
5432               }
5433               output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
5434             }
5435           }
5436         }
5437       }
5438       output.println("};\n");
5439
5440       //generate for tags
5441       TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
5442       output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5443       int numtags = 0;
5444       if (tagel!=null) {
5445         for(int j=0; j<tagel.numTags(); j++) {
5446           if (j!=0)
5447             output.println(",");
5448           TempDescriptor tmp=tagel.getTemp(j);
5449           if (!slotnumber.containsKey(tmp)) {
5450             Integer slotint=new Integer(current_slot++);
5451             slotnumber.put(tmp,slotint);
5452           }
5453           int slot=slotnumber.get(tmp).intValue();
5454           output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
5455         }
5456         numtags = tagel.numTags();
5457       }
5458       output.println("};");
5459
5460       //store the result into a predicatemember struct
5461       output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
5462       output.println("/*type*/"+typed.getClassDesc().getId()+",");
5463       output.println("/* number of dnf terms */"+numberterms+",");
5464       output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5465       output.println("/* number of tag */"+numtags+",");
5466       output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5467       output.println("};\n");
5468       predicateindex++;
5469     }
5470
5471
5472     //generate an array that stores the entire predicate
5473     output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5474     for( int j = 0; j<predicateindex; j++) {
5475       if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5476       else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5477     }
5478     output.println("};\n");
5479     return predicateindex;
5480   }
5481
5482
5483   void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
5484     generateOptionalHeader(headers);
5485     //GENERATE STRUCTS
5486     output.println("#include \"optionalstruct.h\"\n\n");
5487     output.println("#include \"stdlib.h\"\n");
5488
5489     HashSet processedcd = new HashSet();
5490     int maxotd=0;
5491     Enumeration e = safeexecution.keys();
5492     while (e.hasMoreElements()) {
5493       int numotd=0;
5494       //get the class
5495       ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
5496       Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp);       //will be used several times
5497
5498       //Generate the struct of optionals
5499       Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
5500       numotd = c_otd.size();
5501       if(maxotd<numotd) maxotd = numotd;
5502       if( !c_otd.isEmpty() ) {
5503         for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
5504           OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
5505
5506           //generate the int arrays for the predicate
5507           Predicate predicate = otd.predicate;
5508           int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
5509           TreeSet<Integer> fsset=new TreeSet<Integer>();
5510           //iterate through possible FSes corresponding to
5511           //the state when entering
5512
5513           for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext();) {
5514             FlagState fs = (FlagState)fses.next();
5515             int flagid=0;
5516             for(Iterator flags = fs.getFlags(); flags.hasNext();) {
5517               FlagDescriptor flagd = (FlagDescriptor)flags.next();
5518               int id=1<<((Integer)flaginfo.get(flagd)).intValue();
5519               flagid|=id;
5520             }
5521             fsset.add(new Integer(flagid));
5522             //tag information not needed because tag
5523             //changes are not tolerated.
5524           }
5525
5526           output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5527           boolean needcomma=false;
5528           for(Iterator<Integer> it=fsset.iterator(); it.hasNext();) {
5529             if(needcomma)
5530               output.print(", ");
5531             output.println(it.next());
5532           }
5533
5534           output.println("};\n");
5535
5536
5537           //generate optionaltaskdescriptor that actually
5538           //includes exit fses, predicate and the task
5539           //concerned
5540           output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
5541           output.println("&task_"+otd.td.getSafeSymbol()+",");
5542           output.println("/*index*/"+otd.getIndex()+",");
5543           output.println("/*number of enter flags*/"+fsset.size()+",");
5544           output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5545           output.println("/*number of members */"+predicateindex+",");
5546           output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5547           output.println("};\n");
5548         }
5549       } else
5550         continue;
5551       // if there are no optionals, there is no need to build the rest of the struct
5552
5553       output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
5554       c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
5555       if( !c_otd.isEmpty() ) {
5556         boolean needcomma=false;
5557         for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
5558           OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
5559           if(needcomma)
5560             output.println(",");
5561           needcomma=true;
5562           output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5563         }
5564       }
5565       output.println("};\n");
5566
5567       //get all the possible flagstates reachable by an object
5568       Hashtable hashtbtemp = safeexecution.get(cdtemp);
5569       int fscounter = 0;
5570       TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
5571       fsts.addAll(hashtbtemp.keySet());
5572       for(Iterator fsit=fsts.iterator(); fsit.hasNext();) {
5573         FlagState fs = (FlagState)fsit.next();
5574         fscounter++;
5575
5576         //get the set of OptionalTaskDescriptors corresponding
5577         HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
5578         //iterate through the OptionalTaskDescriptors and
5579         //store the pointers to the optionals struct (see on
5580         //top) into an array
5581
5582         output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
5583         for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext();) {
5584           OptionalTaskDescriptor mm = mos.next();
5585           if(!mos.hasNext())
5586             output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
5587           else
5588             output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5589         }
5590
5591         output.println("};\n");
5592
5593         //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
5594
5595         int flagid=0;
5596         for(Iterator flags = fs.getFlags(); flags.hasNext();) {
5597           FlagDescriptor flagd = (FlagDescriptor)flags.next();
5598           int id=1<<((Integer)flaginfo.get(flagd)).intValue();
5599           flagid|=id;
5600         }
5601
5602         //process tag information
5603
5604         int tagcounter = 0;
5605         boolean first = true;
5606         Enumeration tag_enum = fs.getTags();
5607         output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
5608         while(tag_enum.hasMoreElements()) {
5609           tagcounter++;
5610           TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
5611           if(first==true)
5612             first = false;
5613           else
5614             output.println(", ");
5615           output.println("/*tagid*/"+state.getTagId(tagd));
5616         }
5617         output.println("};");
5618
5619         Set<TaskIndex> tiset=sa.getTaskIndex(fs);
5620         for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
5621           TaskIndex ti=itti.next();
5622           if (ti.isRuntime())
5623             continue;
5624
5625           Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
5626
5627           output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
5628           boolean needcomma=false;
5629           for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext();) {
5630             OptionalTaskDescriptor otd=otdit.next();
5631             if(needcomma)
5632               output.print(", ");
5633             needcomma=true;
5634             output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5635           }
5636           output.println("};");
5637
5638           output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
5639           output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
5640           output.print(ti.getIndex()+", ");
5641           output.print(otdset.size()+", ");
5642           output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
5643           output.println("};");
5644         }
5645
5646         tiset=sa.getTaskIndex(fs);
5647         boolean needcomma=false;
5648         int runtimeti=0;
5649         output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
5650         for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
5651           TaskIndex ti=itti.next();
5652           if (ti.isRuntime()) {
5653             runtimeti++;
5654             continue;
5655           }
5656           if (needcomma)
5657             output.print(", ");
5658           needcomma=true;
5659           output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
5660         }
5661         output.println("};\n");
5662
5663         //Store the result in fsanalysiswrapper
5664
5665         output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
5666         output.println("/*flag*/"+flagid+",");
5667         output.println("/* number of tags*/"+tagcounter+",");
5668         output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
5669         output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
5670         output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
5671         output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
5672         output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
5673         output.println("};\n");
5674
5675       }
5676
5677       //Build the array of fsanalysiswrappers
5678       output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
5679       boolean needcomma=false;
5680       for(int i = 0; i<fscounter; i++) {
5681         if (needcomma) output.print(",");
5682         output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
5683         needcomma=true;
5684       }
5685       output.println("};");
5686
5687       //Build the classanalysiswrapper referring to the previous array
5688       output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
5689       output.println("/*type*/"+cdtemp.getId()+",");
5690       output.println("/*numotd*/"+numotd+",");
5691       output.println("otdarray"+cdtemp.getSafeSymbol()+",");
5692       output.println("/* number of fsanalysiswrappers */"+fscounter+",");
5693       output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
5694       processedcd.add(cdtemp);
5695     }
5696
5697     //build an array containing every classes for which code has been build
5698     output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
5699     for(int i=0; i<state.numClasses(); i++) {
5700       ClassDescriptor cn=cdarray[i];
5701       if (i>0)
5702         output.print(", ");
5703       if ((cn != null) && (processedcd.contains(cn)))
5704         output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
5705       else
5706         output.print("NULL");
5707     }
5708     output.println("};");
5709
5710     output.println("#define MAXOTD "+maxotd);
5711     headers.println("#endif");
5712   }
5713
5714   public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
5715     Relation r=new Relation();
5716     for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext();) {
5717       OptionalTaskDescriptor otd=otdit.next();
5718       TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
5719       r.put(ti, otd);
5720     }
5721
5722     LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
5723     for(Iterator it=r.keySet().iterator(); it.hasNext();) {
5724       Set s=r.get(it.next());
5725       for(Iterator it2=s.iterator(); it2.hasNext();) {
5726         OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
5727         l.add(otd);
5728       }
5729     }
5730
5731     return l;
5732   }
5733
5734   protected void outputTransCode(PrintWriter output) {
5735   }
5736   
5737   private int calculateSizeOfSESEParamList(FlatSESEEnterNode fsen){
5738           
5739           Set<TempDescriptor> tdSet=new HashSet<TempDescriptor>();
5740           
5741           for (Iterator iterator = fsen.getInVarSet().iterator(); iterator.hasNext();) {
5742                 TempDescriptor tempDescriptor = (TempDescriptor) iterator.next();
5743                 if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()){
5744                         tdSet.add(tempDescriptor);
5745                 }       
5746           }
5747           
5748           for (Iterator iterator = fsen.getOutVarSet().iterator(); iterator.hasNext();) {
5749                         TempDescriptor tempDescriptor = (TempDescriptor) iterator.next();
5750                         if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()){
5751                                 tdSet.add(tempDescriptor);
5752                         }       
5753           }       
5754                   
5755           return tdSet.size();
5756   }
5757   
5758   private String calculateSizeOfSESEParamSize(FlatSESEEnterNode fsen){
5759     HashMap <String,Integer> map=new HashMap();
5760     HashSet <TempDescriptor> processed=new HashSet<TempDescriptor>();
5761     String rtr="";
5762           
5763     // space for all in and out set primitives
5764     Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
5765     inSetAndOutSet.addAll( fsen.getInVarSet() );
5766     inSetAndOutSet.addAll( fsen.getOutVarSet() );
5767             
5768     Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
5769
5770     Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
5771     while( itr.hasNext() ) {
5772       TempDescriptor temp = itr.next();
5773       TypeDescriptor type = temp.getType();
5774       if( !type.isPtr() ) {
5775         inSetAndOutSetPrims.add( temp );
5776       }
5777     }
5778             
5779     Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
5780     while( itrPrims.hasNext() ) {
5781       TempDescriptor temp = itrPrims.next();
5782       TypeDescriptor type = temp.getType();
5783       if(type.isPrimitive()){
5784         Integer count=map.get(type.getSymbol());
5785         if(count==null){
5786           count=new Integer(1);
5787           map.put(type.getSymbol(), count);
5788         }else{
5789           map.put(type.getSymbol(), new Integer(count.intValue()+1));
5790         }
5791       }      
5792     }
5793           
5794     Set<String> keySet=map.keySet();
5795     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
5796       String key = (String) iterator.next();
5797       rtr+="+sizeof("+key+")*"+map.get(key);
5798     }
5799     return  rtr;
5800   }
5801
5802 }
5803
5804
5805
5806
5807
5808