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