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