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