coreprof updates, nothing huge
[IRC.git] / Robust / src / IR / Flat / BuildCode.java
1 package IR.Flat;
2 import IR.Tree.Modifiers;
3 import IR.Tree.FlagExpressionNode;
4 import IR.Tree.DNFFlag;
5 import IR.Tree.DNFFlagAtom;
6 import IR.Tree.TagExpressionList;
7 import IR.Tree.OffsetNode;
8 import IR.*;
9
10 import java.util.*;
11 import java.io.*;
12
13 import Util.Relation;
14 import Analysis.TaskStateAnalysis.FlagState;
15 import Analysis.TaskStateAnalysis.FlagComparator;
16 import Analysis.TaskStateAnalysis.OptionalTaskDescriptor;
17 import Analysis.TaskStateAnalysis.Predicate;
18 import Analysis.TaskStateAnalysis.SafetyAnalysis;
19 import Analysis.TaskStateAnalysis.TaskIndex;
20 import Analysis.Locality.LocalityAnalysis;
21 import Analysis.Locality.LocalityBinding;
22 import Analysis.Locality.DiscoverConflicts;
23 import Analysis.Locality.DCWrapper;
24 import Analysis.Locality.DelayComputation;
25 import Analysis.Locality.BranchAnalysis;
26 import Analysis.CallGraph.CallGraph;
27 import Analysis.Disjoint.AllocSite;
28 import Analysis.Disjoint.Effect;
29 import Analysis.Disjoint.ReachGraph;
30 import Analysis.Disjoint.Taint;
31 import Analysis.OoOJava.OoOJavaAnalysis;
32 import Analysis.Prefetch.*;
33 import Analysis.Loops.WriteBarrier;
34 import Analysis.Loops.GlobalFieldType;
35 import Analysis.Locality.TypeAnalysis;
36 import Analysis.MLP.ConflictGraph;
37 import Analysis.MLP.ConflictNode;
38 import Analysis.MLP.MLPAnalysis;
39 import Analysis.MLP.ParentChildConflictsMap;
40 import Analysis.MLP.SESELock;
41 import Analysis.MLP.SESEWaitingQueue;
42 import Analysis.MLP.VariableSourceToken;
43 import Analysis.MLP.VSTWrapper;
44 import Analysis.MLP.CodePlan;
45 import Analysis.MLP.SESEandAgePair;
46 import Analysis.MLP.WaitingElement;
47
48 public class BuildCode {
49   State state;
50   Hashtable temptovar;
51   Hashtable paramstable;
52   Hashtable tempstable;
53   Hashtable fieldorder;
54   Hashtable flagorder;
55   int tag=0;
56   String localsprefix="___locals___";
57   String localsprefixaddr="&"+localsprefix;
58   String localsprefixderef=localsprefix+".";
59   String fcrevert="___fcrevert___";
60   String paramsprefix="___params___";
61   String oidstr="___nextobject___";
62   String nextobjstr="___nextobject___";
63   String localcopystr="___localcopy___";
64   public static boolean GENERATEPRECISEGC=false;
65   public static String PREFIX="";
66   public static String arraytype="ArrayObject";
67   public static int flagcount = 0;
68   Virtual virtualcalls;
69   TypeUtil typeutil;
70   protected int maxtaskparams=0;
71   private int maxcount=0;
72   ClassDescriptor[] cdarray;
73   TypeDescriptor[] arraytable;
74   LocalityAnalysis locality;
75   Hashtable<LocalityBinding, TempDescriptor> reverttable;
76   Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>> backuptable;
77   SafetyAnalysis sa;
78   PrefetchAnalysis pa;
79   MLPAnalysis mlpa;
80   OoOJavaAnalysis oooa;
81   String maxTaskRecSizeStr="__maxTaskRecSize___";
82   String mlperrstr = "if(status != 0) { "+
83     "sprintf(errmsg, \"MLP error at %s:%d\", __FILE__, __LINE__); "+
84     "perror(errmsg); exit(-1); }";
85   boolean nonSESEpass=true;
86   RuntimeConflictResolver rcr = null;
87   WriteBarrier wb;
88   DiscoverConflicts dc;
89   DiscoverConflicts recorddc;
90   DCWrapper delaycomp;
91   CallGraph callgraph;
92
93
94   public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa) {
95     this(st, temptovar, typeutil, null, sa, pa, null, null);
96   }
97
98   public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa, OoOJavaAnalysis oooa) {
99     this(st, temptovar, typeutil, null, sa, pa, mlpa, oooa);
100   }
101
102   public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, PrefetchAnalysis pa, MLPAnalysis mlpa, OoOJavaAnalysis oooa) {
103     this(st, temptovar, typeutil, locality, null, pa, mlpa, oooa);
104   }
105
106   public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa, OoOJavaAnalysis oooa) {
107     this.sa=sa;
108     this.pa=pa;
109     this.mlpa=mlpa;
110     this.oooa=oooa;
111     state=st;
112     callgraph=new CallGraph(state);
113     if (state.SINGLETM)
114       oidstr="___objlocation___";
115     this.temptovar=temptovar;
116     paramstable=new Hashtable();
117     tempstable=new Hashtable();
118     fieldorder=new Hashtable();
119     flagorder=new Hashtable();
120     this.typeutil=typeutil;
121     virtualcalls=new Virtual(state,locality);
122     if (locality!=null) {
123       this.locality=locality;
124       this.reverttable=new Hashtable<LocalityBinding, TempDescriptor>();
125       this.backuptable=new Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>>();
126       this.wb=new WriteBarrier(locality, st);
127     }
128     if (state.SINGLETM&&state.DCOPTS) {
129       TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
130       GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
131       this.dc=new DiscoverConflicts(locality, st, typeanalysis, gft);
132       dc.doAnalysis();
133     }
134     if (state.DELAYCOMP) {
135       //TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
136       TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
137       GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
138       delaycomp=new DCWrapper(locality, st, typeanalysis, gft);
139       dc=delaycomp.getConflicts();
140       recorddc=new DiscoverConflicts(locality, st, typeanalysis, delaycomp.getCannotDelayMap(), true, true, null);
141       recorddc.doAnalysis();
142     }
143   }
144
145   /** The buildCode method outputs C code for all the methods.  The Flat
146    * versions of the methods must already be generated and stored in
147    * the State object. */
148   PrintWriter outsandbox=null;
149
150   public void buildCode() {
151     /* Create output streams to write to */
152     PrintWriter outclassdefs=null;
153     PrintWriter outstructs=null;
154     PrintWriter outrepairstructs=null;
155     PrintWriter outmethodheader=null;
156     PrintWriter outmethod=null;
157     PrintWriter outvirtual=null;
158     PrintWriter outtask=null;
159     PrintWriter outtaskdefs=null;
160     PrintWriter outoptionalarrays=null;
161     PrintWriter optionalheaders=null;
162
163     try {
164       if (state.SANDBOX) {
165         outsandbox=new PrintWriter(new FileOutputStream(PREFIX+"sandboxdefs.c"), true);
166       }
167       outstructs=new PrintWriter(new FileOutputStream(PREFIX+"structdefs.h"), true);
168       outmethodheader=new PrintWriter(new FileOutputStream(PREFIX+"methodheaders.h"), true);
169       outclassdefs=new PrintWriter(new FileOutputStream(PREFIX+"classdefs.h"), true);
170       outmethod=new PrintWriter(new FileOutputStream(PREFIX+"methods.c"), true);
171       outvirtual=new PrintWriter(new FileOutputStream(PREFIX+"virtualtable.h"), true);
172       if (state.TASK) {
173         outtask=new PrintWriter(new FileOutputStream(PREFIX+"task.h"), true);
174         outtaskdefs=new PrintWriter(new FileOutputStream(PREFIX+"taskdefs.c"), true);
175         if (state.OPTIONAL) {
176           outoptionalarrays=new PrintWriter(new FileOutputStream(PREFIX+"optionalarrays.c"), true);
177           optionalheaders=new PrintWriter(new FileOutputStream(PREFIX+"optionalstruct.h"), true);
178         }
179       }
180       if (state.structfile!=null) {
181         outrepairstructs=new PrintWriter(new FileOutputStream(PREFIX+state.structfile+".struct"), true);
182       }
183     } catch (Exception e) {
184       e.printStackTrace();
185       System.exit(-1);
186     }
187
188     /* Build the virtual dispatch tables */
189     buildVirtualTables(outvirtual);
190
191     /* Output includes */
192     outmethodheader.println("#ifndef METHODHEADERS_H");
193     outmethodheader.println("#define METHODHEADERS_H");
194     outmethodheader.println("#include \"structdefs.h\"");
195     if (state.DSM)
196       outmethodheader.println("#include \"dstm.h\"");
197     if (state.SANDBOX) {
198       outmethodheader.println("#include \"sandbox.h\"");
199     }
200     if (state.EVENTMONITOR) {
201       outmethodheader.println("#include \"monitor.h\"");
202     }
203     if (state.SINGLETM) {
204       outmethodheader.println("#include \"tm.h\"");
205       outmethodheader.println("#include \"delaycomp.h\"");
206       outmethodheader.println("#include \"inlinestm.h\"");
207     }
208     if (state.ABORTREADERS) {
209       outmethodheader.println("#include \"abortreaders.h\"");
210       outmethodheader.println("#include <setjmp.h>");
211     }
212     if (state.MLP || state.OOOJAVA) {
213       outmethodheader.println("#include <stdlib.h>");
214       outmethodheader.println("#include <stdio.h>");
215       outmethodheader.println("#include <string.h>");
216       outmethodheader.println("#include \"mlp_runtime.h\"");
217       outmethodheader.println("#include \"psemaphore.h\"");
218       outmethodheader.println("#include \"memPool.h\"");
219
220       // spit out a global to inform all worker threads with
221       // the maximum size is for any task record
222       outmethodheader.println("extern int "+maxTaskRecSizeStr+";");
223     }
224
225     /* Output Structures */
226     outputStructs(outstructs);
227
228     // Output the C class declarations
229     // These could mutually reference each other
230     
231     
232     outclassdefs.println("#ifndef __CLASSDEF_H_");
233     outclassdefs.println("#define __CLASSDEF_H_");
234     outputClassDeclarations(outclassdefs);
235
236     // Output function prototypes and structures for parameters
237     Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
238     while(it.hasNext()) {
239       ClassDescriptor cn=(ClassDescriptor)it.next();
240       generateCallStructs(cn, outclassdefs, outstructs, outmethodheader);
241     }
242     outclassdefs.println("#endif");
243     outclassdefs.close();
244
245     if (state.TASK) {
246       /* Map flags to integers */
247       /* The runtime keeps track of flags using these integers */
248       it=state.getClassSymbolTable().getDescriptorsIterator();
249       while(it.hasNext()) {
250         ClassDescriptor cn=(ClassDescriptor)it.next();
251         mapFlags(cn);
252       }
253       /* Generate Tasks */
254       generateTaskStructs(outstructs, outmethodheader);
255
256       /* Outputs generic task structures if this is a task
257          program */
258       outputTaskTypes(outtask);
259     }
260
261     if( state.MLP || state.OOOJAVA) {      
262       // have to initialize some SESE compiler data before
263       // analyzing normal methods, which must happen before
264       // generating SESE internal code
265       
266       Iterator<FlatSESEEnterNode> seseit;
267       if(state.MLP){
268         seseit=mlpa.getAllSESEs().iterator();
269       }else{
270         seseit=oooa.getAllSESEs().iterator();
271       }
272       
273       //TODO signal the object that will report errors
274       if(state.RCR) {
275         try {
276           rcr = new RuntimeConflictResolver(PREFIX);
277           rcr.setGlobalEffects(oooa.getDisjointAnalysis().getEffectsAnalysis().getAllEffects());
278         } catch (FileNotFoundException e) {
279           System.out.println("Runtime Conflict Resolver could not create output file.");
280         }
281       }
282       
283       while(seseit.hasNext()){
284         FlatSESEEnterNode fsen = seseit.next();
285         initializeSESE( fsen );
286         
287         //this code will culminate all conflicts into one master hashtable. 
288         if(state.RCR && rcr != null) {
289           Analysis.OoOJava.ConflictGraph conflictGraph;
290           Hashtable<Taint, Set<Effect>> conflicts;
291
292           System.out.println("-------");
293           System.out.println(fsen);
294           System.out.println(fsen.getIsCallerSESEplaceholder());
295           System.out.println(fsen.getParent());
296           
297           if (fsen.getParent()!=null) {
298             conflictGraph = oooa.getConflictGraph(fsen.getParent());
299             System.out.println("CG="+conflictGraph);
300             if (conflictGraph!=null)
301               System.out.println("Conflicts="+conflictGraph.getConflictEffectSet(fsen));
302           }
303           
304           if(!fsen.getIsCallerSESEplaceholder() && fsen.getParent()!=null && 
305             (conflictGraph = oooa.getConflictGraph(fsen.getParent())) != null && 
306             (conflicts = conflictGraph.getConflictEffectSet(fsen)) != null) {
307             FlatMethod fm=fsen.getfmEnclosing();
308             ReachGraph rg=oooa.getDisjointAnalysis().getReachGraph(fm.getMethod());
309             if(rcr.cSideDebug)
310               rg.writeGraph("RCR_RG_SESE_DEBUG");
311             
312             rcr.addToTraverseToDoList(fsen, rg, conflicts);
313           }
314         }
315       }
316     }
317
318     /* Build the actual methods */
319     outputMethods(outmethod);
320
321     // Output function prototypes and structures for SESE's and code
322     if( state.MLP || state.OOOJAVA ) {
323
324       // spit out a global to inform all worker threads with
325       // the maximum size is for any task record
326       outmethod.println("int "+maxTaskRecSizeStr+" = 0;");
327
328       // used to differentiate, during code generation, whether we are
329       // passing over SESE body code, or non-SESE code
330       nonSESEpass = false;
331
332       // first generate code for each sese's internals     
333       Iterator<FlatSESEEnterNode> seseit;
334       if(state.MLP){
335         seseit=mlpa.getAllSESEs().iterator();
336       }else{
337         seseit=oooa.getAllSESEs().iterator();
338       }
339       
340       while(seseit.hasNext()) {
341         FlatSESEEnterNode fsen = seseit.next();
342         generateMethodSESE(fsen, null, outstructs, outmethodheader, outmethod);
343       }
344
345       // then write the invokeSESE switch to decouple scheduler
346       // from having to do unique details of sese invocation
347       generateSESEinvocationMethod(outmethodheader, outmethod);
348     }
349
350     if (state.TASK) {
351       /* Output code for tasks */
352       outputTaskCode(outtaskdefs, outmethod);
353       outtaskdefs.close();
354       /* Record maximum number of task parameters */
355       outstructs.println("#define MAXTASKPARAMS "+maxtaskparams);
356     } else if (state.main!=null) {
357       /* Generate main method */
358       outputMainMethod(outmethod);
359     }
360
361     /* Generate information for task with optional parameters */
362     if (state.TASK&&state.OPTIONAL) {
363       generateOptionalArrays(outoptionalarrays, optionalheaders, state.getAnalysisResult(), state.getOptionalTaskDescriptors());
364       outoptionalarrays.close();
365     }
366     
367     /* Output structure definitions for repair tool */
368     if (state.structfile!=null) {
369       buildRepairStructs(outrepairstructs);
370       outrepairstructs.close();
371     }
372     
373     /* Close files */
374     outmethodheader.println("#endif");
375     outmethodheader.close();
376     outmethod.close();
377     outstructs.println("#endif");
378     outstructs.close();
379     if(rcr != null) {
380       rcr.close();
381       System.out.println("Runtime Conflict Resolver Done.");
382     }  
383   }
384   
385
386   /* This code just generates the main C method for java programs.
387    * The main C method packs up the arguments into a string array
388    * and passes it to the java main method. */
389
390   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.getInVarVector();
2142     int incount=0;
2143
2144     for(int i=0; i<inset.size();i++) {
2145       TempDescriptor temp=inset.get(i);
2146       TypeDescriptor type=temp.getType();
2147       if(type.isPtr()) {
2148         incount++;
2149         if (temp.getType().isNull())
2150           outputStructs.println("  void * "+temp.getSafeSymbol()+
2151                                 ";  /* in-or-out-set obj in gl */");
2152         else
2153           outputStructs.println("  struct "+temp.getType().getSafeSymbol()+" * "+
2154                                 temp.getSafeSymbol()+"; /* in-or-out-set obj in gl */");
2155       }
2156     }
2157
2158     for(int i=0; i<objectparams.numPointers(); i++) {
2159       TempDescriptor temp=objectparams.getPointer(i);
2160       if (!inset.contains(temp)) {
2161         if (temp.getType().isNull())
2162           outputStructs.println("  void * "+temp.getSafeSymbol()+
2163                                 ";  /* in-or-out-set obj in gl */");
2164         else
2165           outputStructs.println("  struct "+temp.getType().getSafeSymbol()+" * "+
2166                                 temp.getSafeSymbol()+"; /* in-or-out-set obj in gl */");
2167       }
2168     }
2169     
2170     outputStructs.println("  /* next is primitives for in-set and out-set and dynamic tracking */");
2171
2172     Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
2173     while( itrPrims.hasNext() ) {
2174       TempDescriptor temp = itrPrims.next();
2175       TypeDescriptor type = temp.getType();
2176       if(type.isPrimitive()){
2177           outputStructs.println("  "+temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol()+"; /* in-set or out-set primitive */");
2178       }      
2179     }
2180     
2181     // note that the sese record pointer will be added below, just primitive part of tracking here
2182     Iterator<TempDescriptor> itrDynInVars = fsen.getDynamicInVarSet().iterator();
2183     while( itrDynInVars.hasNext() ) {
2184       TempDescriptor dynInVar = itrDynInVars.next();
2185       outputStructs.println("  INTPTR "+dynInVar+"_srcOffset; /* dynamic tracking primitive */");
2186     }  
2187     
2188     
2189     outputStructs.println("  /* everything after this should be pointers to an SESE record */" );
2190
2191     // other half of info for dynamic tracking, the SESE record pointer
2192     itrDynInVars = fsen.getDynamicInVarSet().iterator();
2193     while( itrDynInVars.hasNext() ) {
2194       TempDescriptor dynInVar = itrDynInVars.next();
2195       String depRecField = dynInVar+"_srcSESE";
2196       outputStructs.println("  SESEcommon* "+depRecField+";");
2197       addingDepRecField( fsen, depRecField );
2198     }  
2199     
2200     // statically known sese sources are record pointers, too
2201     Iterator<SESEandAgePair> itrStaticInVarSrcs = fsen.getStaticInVarSrcs().iterator();
2202     while( itrStaticInVarSrcs.hasNext() ) {
2203       SESEandAgePair srcPair = itrStaticInVarSrcs.next();
2204       outputStructs.println("  "+srcPair.getSESE().getSESErecordName()+"* "+srcPair+";");
2205       addingDepRecField(fsen, srcPair.toString());
2206     }
2207
2208     if (state.RCR) {
2209       outputStructs.println("struct rcrRecord rcrRecords["+incount+"]");
2210     }
2211     
2212     if( fsen.getFirstDepRecField() != null ) {
2213       outputStructs.println("  /* compiler believes first dependent SESE record field above is: "+
2214                             fsen.getFirstDepRecField()+" */" );
2215     }
2216     outputStructs.println("};\n");
2217
2218     
2219     // write method declaration to header file
2220     outputMethHead.print("void ");
2221     outputMethHead.print(fsen.getSESEmethodName()+"(");
2222     outputMethHead.print(fsen.getSESErecordName()+"* "+paramsprefix);
2223     outputMethHead.println(");\n");
2224
2225
2226     generateFlatMethodSESE( fsen.getfmBogus(), 
2227                             fsen.getcdEnclosing(), 
2228                             fsen, 
2229                             fsen.getFlatExit(), 
2230                             outputMethods );
2231   }
2232
2233   private void generateFlatMethodSESE(FlatMethod fm, 
2234                                       ClassDescriptor cn, 
2235                                       FlatSESEEnterNode fsen, 
2236                                       FlatSESEExitNode  seseExit, 
2237                                       PrintWriter output
2238                                       ) {
2239
2240     MethodDescriptor md=fm.getMethod();
2241
2242     output.print("void ");
2243     output.print(fsen.getSESEmethodName()+"(");
2244     output.print(fsen.getSESErecordName()+"* "+paramsprefix);
2245     output.println("){\n");
2246
2247
2248     TempObject objecttemp=(TempObject) tempstable.get(md);
2249
2250     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2251       output.print("   struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
2252       output.print(objecttemp.numPointers()+",");
2253       output.print("&(((SESEcommon*)(___params___))[1])");
2254       for(int j=0; j<objecttemp.numPointers(); j++)
2255         output.print(", NULL");
2256       output.println("};");
2257     }
2258
2259     output.println("   /* regular local primitives */");
2260     for(int i=0; i<objecttemp.numPrimitives(); i++) {
2261       TempDescriptor td=objecttemp.getPrimitive(i);
2262       TypeDescriptor type=td.getType();
2263       if (type.isNull())
2264         output.println("   void * "+td.getSafeSymbol()+";");
2265       else if (type.isClass()||type.isArray())
2266         output.println("   struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
2267       else
2268         output.println("   "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
2269     }
2270
2271
2272     // declare variables for naming static SESE's
2273     output.println("   /* static SESE names */");
2274     Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
2275     while( pItr.hasNext() ) {
2276       SESEandAgePair pair = pItr.next();
2277       output.println("   SESEcommon* "+pair+" = NULL;");
2278     }
2279
2280     // declare variables for tracking dynamic sources
2281     output.println("   /* dynamic variable sources */");
2282     Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
2283     while( dynSrcItr.hasNext() ) {
2284       TempDescriptor dynSrcVar = dynSrcItr.next();
2285       output.println("   SESEcommon*  "+dynSrcVar+"_srcSESE = NULL;");
2286       output.println("   INTPTR       "+dynSrcVar+"_srcOffset = 0x1;");
2287     }    
2288
2289     // declare local temps for in-set primitives, and if it is
2290     // a ready-source variable, get the value from the record
2291     output.println("   /* local temps for in-set primitives */");
2292     Iterator<TempDescriptor> itrInSet = fsen.getInVarSet().iterator();
2293     while( itrInSet.hasNext() ) {
2294       TempDescriptor temp = itrInSet.next();
2295       TypeDescriptor type = temp.getType();
2296       if( !type.isPtr() ) {
2297         if( fsen.getReadyInVarSet().contains( temp ) ) {
2298           output.println("   "+type+" "+temp+" = "+paramsprefix+"->"+temp+";");
2299         } else {
2300           output.println("   "+type+" "+temp+";");
2301         }
2302       }
2303     }    
2304
2305     // declare local temps for out-set primitives if its not already
2306     // in the in-set, and it's value will get written so no problem
2307     output.println("   /* local temp for out-set prim, not already in the in-set */");
2308     Iterator<TempDescriptor> itrOutSet = fsen.getOutVarSet().iterator();
2309     while( itrOutSet.hasNext() ) {
2310       TempDescriptor temp = itrOutSet.next();
2311       TypeDescriptor type = temp.getType();
2312       if( !type.isPtr() && !fsen.getInVarSet().contains( temp ) ) {
2313         output.println("   "+type+" "+temp+";");       
2314       }
2315     }
2316
2317
2318     // initialize thread-local var to a the task's record, which is fused
2319     // with the param list
2320     output.println("   ");
2321     output.println("   /* code of this task's body should use this to access the running task record */");
2322     output.println("   runningSESE = &(___params___->common);");
2323     output.println("   ");
2324     
2325     // setup memory queue
2326     // eom
2327     if(state.OOOJAVA){
2328       output.println("   // set up memory queues ");
2329       output.println("   int numMemoryQueue=0;");
2330       output.println("   int memoryQueueItemID=0;");
2331       Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(fsen);
2332       if (graph != null && graph.hasConflictEdge()) {
2333         output.println("   {");
2334         Set<Analysis.OoOJava.SESELock> lockSet = oooa.getLockMappings(graph);
2335         System.out.println("#lockSet="+lockSet);
2336         if (lockSet.size() > 0) {
2337           output.println("   numMemoryQueue=" + lockSet.size() + ";");
2338           output.println("   runningSESE->numMemoryQueue=numMemoryQueue;");
2339           output.println("   runningSESE->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2340           output.println();
2341         }
2342         output.println("   }");
2343       }
2344     } else {
2345       output.println("   // set up memory queues ");
2346       output.println("   int numMemoryQueue=0;");
2347       output.println("   int memoryQueueItemID=0;");
2348       ConflictGraph graph = null;
2349       graph = mlpa.getConflictGraphResults().get(fsen);
2350       if (graph != null && graph.hasConflictEdge()) {
2351         output.println("   {");
2352         HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
2353             graph);
2354         System.out.println("#lockSet="+lockSet);
2355
2356         if (lockSet.size() > 0) {
2357           output.println("   numMemoryQueue=" + lockSet.size() + "; ");
2358           output.println("   runningSESE->numMemoryQueue=numMemoryQueue;");
2359           output.println("   runningSESE->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2360           output.println();
2361         }
2362         output.println("   }");
2363       }
2364     }
2365
2366
2367     // set up a task's mem pool to recycle the allocation of children tasks
2368     // don't bother if the task never has children (a leaf task)
2369     output.println( "#ifndef OOO_DISABLE_TASKMEMPOOL" );
2370     if( !fsen.getIsLeafSESE() ) {
2371       output.println("   runningSESE->taskRecordMemPool = poolcreate( "+
2372                      maxTaskRecSizeStr+" );");
2373     } else {
2374       // make it clear we purposefully did not initialize this
2375       output.println("   runningSESE->taskRecordMemPool = (MemPool*)0x1;");
2376     }
2377     output.println( "#endif // OOO_DISABLE_TASKMEMPOOL" );
2378
2379
2380     // copy in-set into place, ready vars were already 
2381     // copied when the SESE was issued
2382     Iterator<TempDescriptor> tempItr;
2383
2384     // static vars are from a known SESE
2385     output.println("   // copy variables from static sources");
2386     tempItr = fsen.getStaticInVarSet().iterator();
2387     while( tempItr.hasNext() ) {
2388       TempDescriptor temp = tempItr.next();
2389       VariableSourceToken vst = fsen.getStaticInVarSrc( temp );
2390       SESEandAgePair srcPair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2391       output.println("   "+generateTemp( fsen.getfmBogus(), temp, null )+
2392                      " = "+paramsprefix+"->"+srcPair+"->"+vst.getAddrVar()+";");
2393     }
2394     
2395     output.println("   // decrement references to static sources");
2396     for( Iterator<SESEandAgePair> pairItr = fsen.getStaticInVarSrcs().iterator(); pairItr.hasNext(); ) {
2397       SESEandAgePair srcPair = pairItr.next();
2398       output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
2399       output.println("   {");
2400       output.println("     SESEcommon* src = &("+paramsprefix+"->"+srcPair+"->common);");
2401       output.println("     RELEASE_REFERENCE_TO( src );");
2402       output.println("   }");
2403       output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
2404     }
2405
2406
2407     // dynamic vars come from an SESE and src
2408     output.println("     // copy variables from dynamic sources");
2409     tempItr = fsen.getDynamicInVarSet().iterator();
2410     while( tempItr.hasNext() ) {
2411       TempDescriptor temp = tempItr.next();
2412       TypeDescriptor type = temp.getType();
2413       
2414       // go grab it from the SESE source
2415       output.println("   if( "+paramsprefix+"->"+temp+"_srcSESE != NULL ) {");
2416
2417       String typeStr;
2418       if( type.isNull() ) {
2419         typeStr = "void*";
2420       } else if( type.isClass() || type.isArray() ) {
2421         typeStr = "struct "+type.getSafeSymbol()+"*";
2422       } else {
2423         typeStr = type.getSafeSymbol();
2424       }
2425       
2426       output.println("     "+generateTemp( fsen.getfmBogus(), temp, null )+
2427                      " = *(("+typeStr+"*) ((void*)"+
2428                      paramsprefix+"->"+temp+"_srcSESE + "+
2429                      paramsprefix+"->"+temp+"_srcOffset));");
2430
2431       output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
2432       output.println("     SESEcommon* src = "+paramsprefix+"->"+temp+"_srcSESE;");
2433       output.println("     RELEASE_REFERENCE_TO( src );");
2434       output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
2435
2436       // or if the source was our parent, its already in our record to grab
2437       output.println("   } else {");
2438       output.println("     "+generateTemp( fsen.getfmBogus(), temp, null )+
2439                            " = "+paramsprefix+"->"+temp+";");
2440       output.println("   }");
2441     }
2442
2443     // Check to see if we need to do a GC if this is a
2444     // multi-threaded program...    
2445     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2446         output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2447       //Don't bother if we aren't in recursive methods...The loops case will catch it
2448 //      if (callgraph.getAllMethods(md).contains(md)) {
2449 //        if(this.state.MULTICOREGC) {
2450 //          output.println("if(gcflag) gc("+localsprefixaddr+");");
2451 //        } else {
2452 //        output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2453 //      }
2454 //      }
2455     }    
2456
2457     if( state.COREPROF ) {
2458       output.println("#ifdef CP_EVENTID_TASKEXECUTE");
2459       output.println("   CP_LOGEVENT( CP_EVENTID_TASKEXECUTE, CP_EVENTTYPE_BEGIN );");
2460       output.println("#endif");
2461     }
2462
2463     HashSet<FlatNode> exitset=new HashSet<FlatNode>();
2464     exitset.add(seseExit);    
2465     generateCode(fsen.getNext(0), fm, null, exitset, output, true);
2466     output.println("}\n\n");
2467     
2468   }
2469
2470
2471   // when a new mlp thread is created for an issued SESE, it is started
2472   // by running this method which blocks on a cond variable until
2473   // it is allowed to transition to execute.  Then a case statement
2474   // allows it to invoke the method with the proper SESE body, and after
2475   // exiting the SESE method, executes proper SESE exit code before the
2476   // thread can be destroyed
2477   private void generateSESEinvocationMethod(PrintWriter outmethodheader,
2478                                             PrintWriter outmethod
2479                                             ) {
2480
2481     outmethodheader.println("void* invokeSESEmethod( void* seseRecord );");
2482     outmethod.println(      "void* invokeSESEmethod( void* seseRecord ) {");
2483     outmethod.println(      "  int status;");
2484     outmethod.println(      "  char errmsg[128];");
2485
2486     // generate a case for each SESE class that can be invoked
2487     outmethod.println(      "  switch( *((int*)seseRecord) ) {");
2488     outmethod.println(      "    ");
2489     Iterator<FlatSESEEnterNode> seseit;
2490     if(state.MLP){
2491       seseit=mlpa.getAllSESEs().iterator();
2492     }else{
2493       seseit=oooa.getAllSESEs().iterator();
2494     }
2495     while(seseit.hasNext()){
2496       FlatSESEEnterNode fsen = seseit.next();
2497
2498       outmethod.println(    "    /* "+fsen.getPrettyIdentifier()+" */");
2499       outmethod.println(    "    case "+fsen.getIdentifier()+":");
2500       outmethod.println(    "      "+fsen.getSESEmethodName()+"( seseRecord );");  
2501       
2502       if( (state.MLP && fsen.equals( mlpa.getMainSESE() )) || 
2503           (state.OOOJAVA && fsen.equals( oooa.getMainSESE() ))
2504       ) {
2505         outmethod.println(  "      /* work scheduler works forever, explicitly exit */");
2506         outmethod.println(  "      CP_EXIT();");
2507         outmethod.println(  "      CP_DUMP();");        
2508         outmethod.println(  "      workScheduleExit();");
2509         outmethod.println(  "      exit( 0 );");
2510       }
2511
2512       outmethod.println(    "      break;");
2513       outmethod.println(    "");
2514     }
2515
2516     // default case should never be taken, error out
2517     outmethod.println(      "    default:");
2518     outmethod.println(      "      printf(\"Error: unknown SESE class ID in invoke method.\\n\");");
2519     outmethod.println(      "      exit(-30);");
2520     outmethod.println(      "      break;");
2521     outmethod.println(      "  }");
2522     outmethod.println(      "  return NULL;");
2523     outmethod.println(      "}\n\n");
2524   }
2525
2526
2527   protected void generateCode(FlatNode first,
2528                               FlatMethod fm,
2529                               LocalityBinding lb,
2530                               Set<FlatNode> stopset,
2531                               PrintWriter output, boolean firstpass) {
2532
2533     /* Assign labels to FlatNode's if necessary.*/
2534
2535     Hashtable<FlatNode, Integer> nodetolabel;
2536
2537     if (state.DELAYCOMP&&!firstpass)
2538       nodetolabel=dcassignLabels(first, stopset);      
2539     else
2540       nodetolabel=assignLabels(first, stopset);      
2541     
2542     Set<FlatNode> storeset=null;
2543     HashSet<FlatNode> genset=null;
2544     HashSet<FlatNode> refset=null;
2545     Set<FlatNode> unionset=null;
2546
2547     if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
2548       storeset=delaycomp.livecode(lb);
2549       genset=new HashSet<FlatNode>();
2550       if (state.STMARRAY&&!state.DUALVIEW) {
2551         refset=new HashSet<FlatNode>();
2552         refset.addAll(delaycomp.getDeref(lb));
2553         refset.removeAll(delaycomp.getCannotDelay(lb));
2554         refset.removeAll(delaycomp.getOther(lb));
2555       }
2556       if (firstpass) {
2557         genset.addAll(delaycomp.getCannotDelay(lb));
2558         genset.addAll(delaycomp.getOther(lb));
2559       } else {
2560         genset.addAll(delaycomp.getNotReady(lb));
2561         if (state.STMARRAY&&!state.DUALVIEW) {
2562           genset.removeAll(refset);
2563         }
2564       }
2565       unionset=new HashSet<FlatNode>();
2566       unionset.addAll(storeset);
2567       unionset.addAll(genset);
2568       if (state.STMARRAY&&!state.DUALVIEW)
2569         unionset.addAll(refset);
2570     }
2571     
2572     /* Do the actual code generation */
2573     FlatNode current_node=null;
2574     HashSet tovisit=new HashSet();
2575     HashSet visited=new HashSet();
2576     if (!firstpass)
2577       tovisit.add(first.getNext(0));
2578     else
2579       tovisit.add(first);
2580     while(current_node!=null||!tovisit.isEmpty()) {
2581       if (current_node==null) {
2582         current_node=(FlatNode)tovisit.iterator().next();
2583         tovisit.remove(current_node);
2584       } else if (tovisit.contains(current_node)) {
2585         tovisit.remove(current_node);
2586       }
2587       visited.add(current_node);
2588       if (nodetolabel.containsKey(current_node)) {
2589         output.println("L"+nodetolabel.get(current_node)+":");
2590       }
2591       if (state.INSTRUCTIONFAILURE) {
2592         if (state.THREAD||state.DSM||state.SINGLETM) {
2593           output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
2594         } else
2595           output.println("if ((--instructioncount)==0) injectinstructionfailure();");
2596       }
2597       if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
2598         output.print("   ");
2599         if (!state.DELAYCOMP||firstpass) {
2600           generateFlatNode(fm, lb, current_node, output);
2601         } else {
2602           //store primitive variables in out set
2603           AtomicRecord ar=atomicmethodmap.get((FlatAtomicEnterNode)first);
2604           Set<TempDescriptor> liveout=ar.liveout;
2605           for(Iterator<TempDescriptor> tmpit=liveout.iterator();tmpit.hasNext();) {
2606             TempDescriptor tmp=tmpit.next();
2607             output.println("primitives->"+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2608           }
2609         }
2610         if ((state.MLP || state.OOOJAVA) && stopset!=null) {
2611           assert first.getPrev( 0 ) instanceof FlatSESEEnterNode;
2612           assert current_node       instanceof FlatSESEExitNode;
2613           FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev( 0 );
2614           FlatSESEExitNode  fsxn = (FlatSESEExitNode)  current_node;
2615           assert fsen.getFlatExit().equals( fsxn );
2616           assert fsxn.getFlatEnter().equals( fsen );
2617         }
2618         if (current_node.kind()!=FKind.FlatReturnNode) {
2619           output.println("   return;");
2620         }
2621         current_node=null;
2622       } else if(current_node.numNext()==1) {
2623         FlatNode nextnode;
2624         if ((state.MLP|| state.OOOJAVA) && 
2625             current_node.kind()==FKind.FlatSESEEnterNode && 
2626             !((FlatSESEEnterNode)current_node).getIsCallerSESEplaceholder()
2627            ) {
2628           FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
2629           generateFlatNode(fm, lb, current_node, output);
2630           nextnode=fsen.getFlatExit().getNext(0);
2631         } else if (state.DELAYCOMP) {
2632           boolean specialprimitive=false;
2633           //skip literals...no need to add extra overhead
2634           if (storeset!=null&&storeset.contains(current_node)&&current_node.kind()==FKind.FlatLiteralNode) {
2635             TypeDescriptor typedesc=((FlatLiteralNode)current_node).getType();
2636             if (!typedesc.isClass()&&!typedesc.isArray()) {
2637               specialprimitive=true;
2638             }
2639           }
2640
2641           if (genset==null||genset.contains(current_node)||specialprimitive)
2642             generateFlatNode(fm, lb, current_node, output);
2643           if (state.STMARRAY&&!state.DUALVIEW&&refset!=null&&refset.contains(current_node)) {
2644             //need to acquire lock
2645             handleArrayDeref(fm, lb, current_node, output, firstpass);
2646           }
2647           if (storeset!=null&&storeset.contains(current_node)&&!specialprimitive) {
2648             TempDescriptor wrtmp=current_node.writesTemps()[0];
2649             if (firstpass) {
2650               //need to store value written by previous node
2651               if (wrtmp.getType().isPtr()) {
2652                 //only lock the objects that may actually need locking
2653                 if (recorddc.getNeedTrans(lb, current_node)&&
2654                     (!state.STMARRAY||state.DUALVIEW||!wrtmp.getType().isArray()||
2655                      wrtmp.getType().getSymbol().equals(TypeUtil.ObjectClass))) {
2656                   output.println("STOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2657                 } else {
2658                   output.println("STOREPTRNOLOCK("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2659                 }
2660               } else {
2661                 output.println("STORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");/* "+current_node.nodeid+" */");
2662               }
2663             } else {
2664               //need to read value read by previous node
2665               if (wrtmp.getType().isPtr()) {
2666                 output.println("RESTOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2667               } else {
2668                 output.println("RESTORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+"); /* "+current_node.nodeid+" */");               
2669               }
2670             }
2671           }
2672           nextnode=current_node.getNext(0);
2673         } else {
2674           output.print("   ");
2675           generateFlatNode(fm, lb, current_node, output);
2676           nextnode=current_node.getNext(0);
2677         }
2678         if (visited.contains(nextnode)) {
2679           output.println("goto L"+nodetolabel.get(nextnode)+";");
2680           current_node=null;
2681         } else 
2682           current_node=nextnode;
2683       } else if (current_node.numNext()==2) {
2684         /* Branch */
2685         if (state.DELAYCOMP) {
2686           boolean computeside=false;
2687           if (firstpass) {
2688             //need to record which way it should go
2689             if (genset==null||genset.contains(current_node)) {
2690               if (storeset!=null&&storeset.contains(current_node)) {
2691                 //need to store which way branch goes
2692                 generateStoreFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2693               } else
2694                 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2695             } else {
2696               //which side to execute
2697               computeside=true;
2698             }
2699           } else {
2700             if (genset.contains(current_node)) {
2701               generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);             
2702             } else if (storeset.contains(current_node)) {
2703               //need to do branch
2704               branchanalysis.generateGroupCode(current_node, output, nodetolabel);
2705             } else {
2706               //which side to execute
2707               computeside=true;
2708             }
2709           }
2710           if (computeside) {
2711             Set<FlatNode> leftset=DelayComputation.getNext(current_node, 0, unionset, lb,locality, true);
2712             int branch=0;
2713             if (leftset.size()==0)
2714               branch=1;
2715             if (visited.contains(current_node.getNext(branch))) {
2716               //already visited -- build jump
2717               output.println("goto L"+nodetolabel.get(current_node.getNext(branch))+";");
2718               current_node=null;
2719             } else {
2720               current_node=current_node.getNext(branch);
2721             }
2722           } else {
2723             if (!visited.contains(current_node.getNext(1)))
2724               tovisit.add(current_node.getNext(1));
2725             if (visited.contains(current_node.getNext(0))) {
2726               output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2727               current_node=null;
2728             } else 
2729               current_node=current_node.getNext(0);
2730           }
2731         } else {
2732           output.print("   ");  
2733           generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2734           if (!visited.contains(current_node.getNext(1)))
2735             tovisit.add(current_node.getNext(1));
2736           if (visited.contains(current_node.getNext(0))) {
2737             output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2738             current_node=null;
2739           } else 
2740             current_node=current_node.getNext(0);
2741         }
2742       } else throw new Error();
2743     }
2744   }
2745
2746   protected void handleArrayDeref(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output, boolean firstpass) {
2747     if (fn.kind()==FKind.FlatSetElementNode) {
2748       FlatSetElementNode fsen=(FlatSetElementNode) fn;
2749       String dst=generateTemp(fm, fsen.getDst(), lb);
2750       String src=generateTemp(fm, fsen.getSrc(), lb);
2751       String index=generateTemp(fm, fsen.getIndex(), lb);      
2752       TypeDescriptor elementtype=fsen.getDst().getType().dereference();
2753       String type="";
2754       if (elementtype.isArray()||elementtype.isClass())
2755         type="void *";
2756       else
2757         type=elementtype.getSafeSymbol()+" ";
2758       if (firstpass) {
2759         output.println("STOREARRAY("+dst+","+index+","+type+")");
2760       } else {
2761         output.println("{");
2762         output.println("  struct ArrayObject *array;");
2763         output.println("  int index;");
2764         output.println("  RESTOREARRAY(array,index);");
2765         output.println("  (("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index]="+src+";");
2766         output.println("}");
2767       }
2768     } else if (fn.kind()==FKind.FlatElementNode) {
2769       FlatElementNode fen=(FlatElementNode) fn;
2770       String src=generateTemp(fm, fen.getSrc(), lb);
2771       String index=generateTemp(fm, fen.getIndex(), lb);
2772       TypeDescriptor elementtype=fen.getSrc().getType().dereference();
2773       String dst=generateTemp(fm, fen.getDst(), lb);
2774       String type="";
2775       if (elementtype.isArray()||elementtype.isClass())
2776         type="void *";
2777       else
2778         type=elementtype.getSafeSymbol()+" ";
2779       if (firstpass) {
2780         output.println("STOREARRAY("+src+","+index+","+type+")");
2781       } else {
2782         output.println("{");
2783         output.println("  struct ArrayObject *array;");
2784         output.println("  int index;");
2785         output.println("  RESTOREARRAY(array,index);");
2786         output.println("  "+dst+"=(("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index];");
2787         output.println("}");
2788       }
2789     }
2790   }
2791   /** Special label assignment for delaycomputation */
2792   protected Hashtable<FlatNode, Integer> dcassignLabels(FlatNode first, Set<FlatNode> lastset) {
2793     HashSet tovisit=new HashSet();
2794     HashSet visited=new HashSet();
2795     int labelindex=0;
2796     Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2797
2798     //Label targets of branches
2799     Set<FlatNode> targets=branchanalysis.getTargets();
2800     for(Iterator<FlatNode> it=targets.iterator();it.hasNext();) {
2801       nodetolabel.put(it.next(), new Integer(labelindex++));
2802     }
2803
2804
2805     tovisit.add(first);
2806     /*Assign labels first.  A node needs a label if the previous
2807      * node has two exits or this node is a join point. */
2808
2809     while(!tovisit.isEmpty()) {
2810       FlatNode fn=(FlatNode)tovisit.iterator().next();
2811       tovisit.remove(fn);
2812       visited.add(fn);
2813
2814
2815       if(lastset!=null&&lastset.contains(fn)) {
2816         // if last is not null and matches, don't go 
2817         // any further for assigning labels
2818         continue;
2819       }
2820
2821       for(int i=0; i<fn.numNext(); i++) {
2822         FlatNode nn=fn.getNext(i);
2823
2824         if(i>0) {
2825           //1) Edge >1 of node
2826           nodetolabel.put(nn,new Integer(labelindex++));
2827         }
2828         if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2829           tovisit.add(nn);
2830         } else {
2831           //2) Join point
2832           nodetolabel.put(nn,new Integer(labelindex++));
2833         }
2834       }
2835     }
2836     return nodetolabel;
2837
2838   }
2839
2840   protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first) {
2841     return assignLabels(first, null);
2842   }
2843
2844   protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
2845     HashSet tovisit=new HashSet();
2846     HashSet visited=new HashSet();
2847     int labelindex=0;
2848     Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2849     tovisit.add(first);
2850
2851     /*Assign labels first.  A node needs a label if the previous
2852      * node has two exits or this node is a join point. */
2853
2854     while(!tovisit.isEmpty()) {
2855       FlatNode fn=(FlatNode)tovisit.iterator().next();
2856       tovisit.remove(fn);
2857       visited.add(fn);
2858
2859
2860       if(lastset!=null&&lastset.contains(fn)) {
2861         // if last is not null and matches, don't go 
2862         // any further for assigning labels
2863         continue;
2864       }
2865
2866       for(int i=0; i<fn.numNext(); i++) {
2867         FlatNode nn=fn.getNext(i);
2868
2869         if(i>0) {
2870           //1) Edge >1 of node
2871           nodetolabel.put(nn,new Integer(labelindex++));
2872         }
2873         if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2874           tovisit.add(nn);
2875         } else {
2876           //2) Join point
2877           nodetolabel.put(nn,new Integer(labelindex++));
2878         }
2879       }
2880     }
2881     return nodetolabel;
2882   }
2883
2884
2885   /** Generate text string that corresponds to the TempDescriptor td. */
2886   protected String generateTemp(FlatMethod fm, TempDescriptor td, LocalityBinding lb) {
2887     MethodDescriptor md=fm.getMethod();
2888     TaskDescriptor task=fm.getTask();
2889     TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
2890
2891     if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
2892       return td.getSafeSymbol();
2893     }
2894
2895     if (objecttemps.isLocalPtr(td)) {
2896       return localsprefixderef+td.getSafeSymbol();
2897     }
2898
2899     if (objecttemps.isParamPtr(td)) {
2900       return paramsprefix+"->"+td.getSafeSymbol();
2901     }
2902
2903     throw new Error();
2904   }
2905
2906   protected void generateFlatNode(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output) {
2907
2908     // insert pre-node actions from the code plan
2909     if( state.MLP|| state.OOOJAVA ) {
2910       
2911       CodePlan cp;
2912       if(state.MLP){
2913         cp = mlpa.getCodePlan( fn );
2914       }else{
2915         cp = oooa.getCodePlan(fn);
2916       }
2917
2918       if( cp != null ) {
2919         
2920         FlatSESEEnterNode currentSESE = cp.getCurrentSESE();
2921         
2922         // for each sese and age pair that this parent statement
2923         // must stall on, take that child's stall semaphore, the
2924         // copying of values comes after the statement
2925         Iterator<VariableSourceToken> vstItr = cp.getStallTokens().iterator();
2926         while( vstItr.hasNext() ) {
2927           VariableSourceToken vst = vstItr.next();
2928
2929           SESEandAgePair pair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2930
2931           output.println("   {");
2932           output.println("     "+pair.getSESE().getSESErecordName()+"* child = ("+
2933                          pair.getSESE().getSESErecordName()+"*) "+pair+";");
2934
2935           output.println("     SESEcommon* common = (SESEcommon*) "+pair+";");
2936           if( state.COREPROF ) {
2937             output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
2938             output.println("     CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_BEGIN );");
2939             output.println("#endif");
2940           }
2941           output.println("     pthread_mutex_lock( &(common->lock) );");
2942           output.println("     if( common->doneExecuting == FALSE ) {");
2943           output.println("       stopforgc((struct garbagelist *)&___locals___);");
2944           output.println("       do {");
2945           output.println("         pthread_cond_wait( &(common->doneCond), &(common->lock) );");
2946           output.println("       } while( common->doneExecuting == FALSE );");
2947           output.println("       restartaftergc();");
2948           output.println("    }");
2949           output.println("     pthread_mutex_unlock( &(common->lock) );");
2950
2951           // copy things we might have stalled for                
2952           Iterator<TempDescriptor> tdItr = cp.getCopySet( vst ).iterator();
2953           while( tdItr.hasNext() ) {
2954             TempDescriptor td = tdItr.next();
2955             FlatMethod fmContext;
2956             if( currentSESE.getIsCallerSESEplaceholder() ) {
2957               fmContext = currentSESE.getfmEnclosing();
2958             } else {
2959               fmContext = currentSESE.getfmBogus();
2960             }
2961             output.println("       "+generateTemp( fmContext, td, null )+
2962                            " = child->"+vst.getAddrVar().getSafeSymbol()+";");
2963           }
2964           if( state.COREPROF ) {
2965             output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
2966             output.println("     CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_END );");
2967             output.println("#endif");
2968           }
2969           output.println("   }");
2970         }
2971   
2972         // for each variable with a dynamic source, stall just for that variable
2973         Iterator<TempDescriptor> dynItr = cp.getDynamicStallSet().iterator();
2974         while( dynItr.hasNext() ) {
2975           TempDescriptor dynVar = dynItr.next();
2976
2977           // only stall if the dynamic source is not yourself, denoted by src==NULL
2978           // otherwise the dynamic write nodes will have the local var up-to-date
2979           output.println("   {");
2980           output.println("     if( "+dynVar+"_srcSESE != NULL ) {");
2981           output.println("       SESEcommon* common = (SESEcommon*) "+dynVar+"_srcSESE;");
2982           if( state.COREPROF ) {
2983             output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
2984             output.println("       CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_BEGIN );");
2985             output.println("#endif");
2986           }
2987           output.println("       psem_take( &(common->stallSem) );");
2988
2989           FlatMethod fmContext;
2990           if( currentSESE.getIsCallerSESEplaceholder() ) {
2991             fmContext = currentSESE.getfmEnclosing();
2992           } else {
2993             fmContext = currentSESE.getfmBogus();
2994           }
2995           
2996           TypeDescriptor type=dynVar.getType();
2997           String typeStr;
2998           if( type.isNull() ) {
2999             typeStr = "void*";
3000           } else if( type.isClass() || type.isArray() ) {
3001             typeStr = "struct "+type.getSafeSymbol()+"*";
3002           } else {
3003             typeStr = type.getSafeSymbol();
3004           }
3005       
3006           output.println("       "+generateTemp( fmContext, dynVar, null )+
3007                          " = *(("+typeStr+"*) ((void*)"+
3008                          dynVar+"_srcSESE + "+dynVar+"_srcOffset));");
3009           if( state.COREPROF ) {
3010             output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
3011             output.println("       CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_END );");
3012             output.println("#endif");
3013           }
3014           output.println("     }");
3015           output.println("   }");
3016         }
3017
3018         // for each assignment of a variable to rhs that has a dynamic source,
3019         // copy the dynamic sources
3020         Iterator dynAssignItr = cp.getDynAssigns().entrySet().iterator();
3021         while( dynAssignItr.hasNext() ) {
3022           Map.Entry      me  = (Map.Entry)      dynAssignItr.next();
3023           TempDescriptor lhs = (TempDescriptor) me.getKey();
3024           TempDescriptor rhs = (TempDescriptor) me.getValue();
3025
3026           output.println("   {");
3027           output.println("   SESEcommon* oldSrc = "+lhs+"_srcSESE;");
3028           
3029           output.println("   "+lhs+"_srcSESE   = "+rhs+"_srcSESE;");
3030           output.println("   "+lhs+"_srcOffset = "+rhs+"_srcOffset;");
3031
3032           // no matter what we did above, track reference count of whatever
3033           // this variable pointed to, do release last in case we're just
3034           // copying the same value in because 1->2->1 is safe but ref count
3035           // 1->0->1 has a window where it looks like it should be free'd
3036           output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
3037           output.println("     if( "+rhs+"_srcSESE != NULL ) {");
3038           output.println("       ADD_REFERENCE_TO( "+rhs+"_srcSESE );");
3039           output.println("     }");
3040           output.println("     if( oldSrc != NULL ) {");
3041           output.println("       RELEASE_REFERENCE_TO( oldSrc );");
3042           output.println("     }");
3043           output.println("   }");
3044           output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
3045         }
3046
3047         // for each lhs that is dynamic from a non-dynamic source, set the
3048         // dynamic source vars to the current SESE
3049         dynItr = cp.getDynAssignCurr().iterator();
3050         while( dynItr.hasNext() ) {
3051           TempDescriptor dynVar = dynItr.next();          
3052           assert currentSESE.getDynamicVarSet().contains( dynVar );
3053
3054           // first release a reference to current record
3055           output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
3056           output.println("   if( "+dynVar+"_srcSESE != NULL ) {");
3057           output.println("     RELEASE_REFERENCE_TO( oldSrc );");
3058           output.println("   }");
3059           output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
3060
3061           output.println("   "+dynVar+"_srcSESE = NULL;");
3062         }
3063         
3064         // eom
3065         // handling stall site
3066         if (state.OOOJAVA) {
3067           Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(currentSESE);
3068           if(graph!=null){
3069             Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
3070             Set<Analysis.OoOJava.WaitingElement> waitingElementSet =
3071               graph.getStallSiteWaitingElementSet(fn, seseLockSet);
3072             
3073             if(waitingElementSet.size()>0){
3074               output.println("// stall on parent's stall sites ");
3075               output.println("   {");
3076               output.println("     REntry* rentry;");
3077           
3078               for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
3079                 Analysis.OoOJava.WaitingElement waitingElement = (Analysis.OoOJava.WaitingElement) iterator.next();
3080                 
3081                 if(state.RCR && rcr != null){
3082                   Analysis.OoOJava.ConflictGraph conflictGraph = graph;
3083                   Hashtable<Taint, Set<Effect>> conflicts;
3084                   ReachGraph rg = oooa.getDisjointAnalysis().getReachGraph(currentSESE.getmdEnclosing());
3085                   if(rcr.cSideDebug) {
3086                     rg.writeGraph("RCR_RG_STALLSITE_DEBUG");
3087                   }
3088                   if((conflictGraph != null) && 
3089                       (conflicts = graph.getConflictEffectSet(fn)) != null &&
3090                       (rg != null)){
3091                     rcr.addToTraverseToDoList(fn, waitingElement.getTempDesc(), rg, conflicts);
3092                    }
3093                 }
3094                
3095                 if( waitingElement.getStatus() >= ConflictNode.COARSE ){
3096                   output.println("     rentry=mlpCreateREntry("+ waitingElement.getStatus()+ ", runningSESE);");
3097                 }else{
3098                   output.println("     rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", runningSESE,  (void*)&" +generateTemp(fm,waitingElement.getTempDesc(),lb)+ ");");
3099                 }         
3100                 output.println("     psem_init( &(rentry->parentStallSem) );");
3101                 output.println("     rentry->queue=runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
3102                 output.println("     if(ADDRENTRY(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()
3103                            + "],rentry)==NOTREADY){");
3104                 if( state.COREPROF ) {
3105                   output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3106                   output.println("        CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_BEGIN );");
3107                   output.println("#endif");
3108                 }
3109                 output.println("        psem_take( &(rentry->parentStallSem) );");
3110                 if( state.COREPROF ) {
3111                   output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3112                   output.println("        CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_END );");
3113                   output.println("#endif");
3114                 }
3115                 output.println("     }  ");
3116                 
3117                 if(state.RCR && rcr != null) {
3118                   output.println("   "+rcr.getTraverserInvocation(waitingElement.getTempDesc(), 
3119                       generateTemp(fm, waitingElement.getTempDesc(), null), fn));
3120                 }
3121               }
3122               output.println("   }");
3123             }
3124           }
3125         }else{
3126           ParentChildConflictsMap conflictsMap = mlpa.getConflictsResults().get(fn);
3127           if (conflictsMap != null) {
3128             Set<Long> allocSet = conflictsMap.getAllocationSiteIDSetofStallSite();
3129             if (allocSet.size() > 0) {
3130               FlatNode enclosingFlatNode=null;
3131               if( currentSESE.getIsCallerSESEplaceholder() && currentSESE.getParent()==null){
3132                 enclosingFlatNode=currentSESE.getfmEnclosing();
3133               }else{
3134                 enclosingFlatNode=currentSESE;
3135               }                                         
3136               ConflictGraph graph=mlpa.getConflictGraphResults().get(enclosingFlatNode);
3137               HashSet<SESELock> seseLockSet=mlpa.getConflictGraphLockMap().get(graph);
3138               Set<WaitingElement> waitingElementSet=graph.getStallSiteWaitingElementSet(conflictsMap, seseLockSet);
3139                         
3140               if(waitingElementSet.size()>0){
3141                 output.println("// stall on parent's stall sites ");
3142                 output.println("   {");
3143                 output.println("     REntry* rentry;");
3144                                 
3145                 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
3146                   WaitingElement waitingElement = (WaitingElement) iterator.next();
3147                                         
3148                   if( waitingElement.getStatus() >= ConflictNode.COARSE ){
3149                     // HERE! a parent might conflict with a child
3150                     output.println("     rentry=mlpCreateREntry("+ waitingElement.getStatus()+ ", runningSESE);");
3151                   }else{
3152                     output.println("     rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", runningSESE,  (void*)&___locals___."+ waitingElement.getDynID() + ");");
3153                   }                                     
3154                   output.println("     psem_init( &(rentry->parentStallSem) );");
3155                   output.println("     rentry->queue=runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
3156                   output
3157                     .println("     if(ADDRENTRY(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()
3158                              + "],rentry)==NOTREADY){");
3159                   if( state.COREPROF ) {
3160                     output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3161                     output.println("        CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_BEGIN );");
3162                     output.println("#endif");
3163                   }
3164                   output.println("        psem_take( &(rentry->parentStallSem) );");
3165                   if( state.COREPROF ) {
3166                     output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3167                     output.println("        CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_END );");
3168                     output.println("#endif");
3169                   }
3170                   output.println("     }  ");
3171                 }
3172                 output.println("   }");
3173               }
3174             }
3175           }     
3176         }
3177       }
3178     }
3179
3180     switch(fn.kind()) {
3181     case FKind.FlatAtomicEnterNode:
3182       generateFlatAtomicEnterNode(fm, lb, (FlatAtomicEnterNode) fn, output);
3183       break;
3184
3185     case FKind.FlatAtomicExitNode:
3186       generateFlatAtomicExitNode(fm, lb, (FlatAtomicExitNode) fn, output);
3187       break;
3188
3189     case FKind.FlatInstanceOfNode:
3190       generateFlatInstanceOfNode(fm, lb, (FlatInstanceOfNode)fn, output);
3191       break;
3192
3193     case FKind.FlatSESEEnterNode:
3194       generateFlatSESEEnterNode(fm, lb, (FlatSESEEnterNode)fn, output);
3195       break;
3196
3197     case FKind.FlatSESEExitNode:
3198       generateFlatSESEExitNode(fm, lb, (FlatSESEExitNode)fn, output);
3199       break;
3200       
3201     case FKind.FlatWriteDynamicVarNode:
3202       generateFlatWriteDynamicVarNode(fm, lb, (FlatWriteDynamicVarNode)fn, output);
3203       break;
3204
3205     case FKind.FlatGlobalConvNode:
3206       generateFlatGlobalConvNode(fm, lb, (FlatGlobalConvNode) fn, output);
3207       break;
3208
3209     case FKind.FlatTagDeclaration:
3210       generateFlatTagDeclaration(fm, lb, (FlatTagDeclaration) fn,output);
3211       break;
3212
3213     case FKind.FlatCall:
3214       generateFlatCall(fm, lb, (FlatCall) fn,output);
3215       break;
3216
3217     case FKind.FlatFieldNode:
3218       generateFlatFieldNode(fm, lb, (FlatFieldNode) fn,output);
3219       break;
3220
3221     case FKind.FlatElementNode:
3222       generateFlatElementNode(fm, lb, (FlatElementNode) fn,output);
3223       break;
3224
3225     case FKind.FlatSetElementNode:
3226       generateFlatSetElementNode(fm, lb, (FlatSetElementNode) fn,output);
3227       break;
3228
3229     case FKind.FlatSetFieldNode:
3230       generateFlatSetFieldNode(fm, lb, (FlatSetFieldNode) fn,output);
3231       break;
3232
3233     case FKind.FlatNew:
3234       generateFlatNew(fm, lb, (FlatNew) fn,output);
3235       break;
3236
3237     case FKind.FlatOpNode:
3238       generateFlatOpNode(fm, lb, (FlatOpNode) fn,output);
3239       break;
3240
3241     case FKind.FlatCastNode:
3242       generateFlatCastNode(fm, lb, (FlatCastNode) fn,output);
3243       break;
3244
3245     case FKind.FlatLiteralNode:
3246       generateFlatLiteralNode(fm, lb, (FlatLiteralNode) fn,output);
3247       break;
3248
3249     case FKind.FlatReturnNode:
3250       generateFlatReturnNode(fm, lb, (FlatReturnNode) fn,output);
3251       break;
3252
3253     case FKind.FlatNop:
3254       output.println("/* nop */");
3255       break;
3256
3257     case FKind.FlatGenReachNode:
3258       // this node is just for generating a reach graph
3259       // in disjointness analysis at a particular program point
3260       break;
3261
3262     case FKind.FlatExit:
3263       output.println("/* exit */");
3264       break;
3265
3266     case FKind.FlatBackEdge:
3267       if (state.SINGLETM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
3268         output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
3269       }
3270       if(state.DSM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
3271         output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
3272       }
3273       if (((state.MLP|| state.OOOJAVA||state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
3274           || (this.state.MULTICOREGC)) {
3275         if(state.DSM&&locality.getAtomic(lb).get(fn).intValue()>0) {
3276           output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
3277         } else if(this.state.MULTICOREGC) {
3278           output.println("if (gcflag) gc("+localsprefixaddr+");");
3279         } else {
3280           output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3281         }
3282       } else
3283         output.println("/* nop */");
3284       break;
3285
3286     case FKind.FlatCheckNode:
3287       generateFlatCheckNode(fm, lb, (FlatCheckNode) fn, output);
3288       break;
3289
3290     case FKind.FlatFlagActionNode:
3291       generateFlatFlagActionNode(fm, lb, (FlatFlagActionNode) fn, output);
3292       break;
3293
3294     case FKind.FlatPrefetchNode:
3295       generateFlatPrefetchNode(fm,lb, (FlatPrefetchNode) fn, output);
3296       break;
3297
3298     case FKind.FlatOffsetNode:
3299       generateFlatOffsetNode(fm, lb, (FlatOffsetNode)fn, output);
3300       break;
3301
3302     default:
3303       throw new Error();
3304     }
3305
3306     // insert post-node actions from the code-plan
3307     /*
3308     if( state.MLP) {
3309       CodePlan cp = mlpa.getCodePlan( fn );
3310
3311       if( cp != null ) {     
3312       }
3313     }
3314     */
3315   }
3316
3317   public void generateFlatOffsetNode(FlatMethod fm, LocalityBinding lb, FlatOffsetNode fofn, PrintWriter output) {
3318     output.println("/* FlatOffsetNode */");
3319     FieldDescriptor fd=fofn.getField();
3320     output.println(generateTemp(fm, fofn.getDst(),lb)+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+ fd.getSafeSymbol()+");");
3321     output.println("/* offset */");
3322   }
3323
3324   public void generateFlatPrefetchNode(FlatMethod fm, LocalityBinding lb, FlatPrefetchNode fpn, PrintWriter output) {
3325     if (state.PREFETCH) {
3326       Vector oids = new Vector();
3327       Vector fieldoffset = new Vector();
3328       Vector endoffset = new Vector();
3329       int tuplecount = 0;        //Keeps track of number of prefetch tuples that need to be generated
3330       for(Iterator it = fpn.hspp.iterator(); it.hasNext();) {
3331         PrefetchPair pp = (PrefetchPair) it.next();
3332         Integer statusbase = locality.getNodePreTempInfo(lb,fpn).get(pp.base);
3333         /* Find prefetches that can generate oid */
3334         if(statusbase == LocalityAnalysis.GLOBAL) {
3335           generateTransCode(fm, lb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(lb).get(fpn).intValue()>0, false);
3336           tuplecount++;
3337         } else if (statusbase == LocalityAnalysis.LOCAL) {
3338           generateTransCode(fm,lb,pp,oids,fieldoffset,endoffset,tuplecount,false,true);
3339         } else {
3340           continue;
3341         }
3342       }
3343       if (tuplecount==0)
3344         return;
3345       System.out.println("Adding prefetch "+fpn+ " to method:" +fm);
3346       output.println("{");
3347       output.println("/* prefetch */");
3348       output.println("/* prefetchid_" + fpn.siteid + " */");
3349       output.println("void * prefptr;");
3350       output.println("int tmpindex;");
3351
3352       output.println("if((evalPrefetch["+fpn.siteid+"].operMode) || (evalPrefetch["+fpn.siteid+"].retrycount <= 0)) {");
3353       /*Create C code for oid array */
3354       output.print("   unsigned int oidarray_[] = {");
3355       boolean needcomma=false;
3356       for (Iterator it = oids.iterator(); it.hasNext();) {
3357         if (needcomma)
3358           output.print(", ");
3359         output.print(it.next());
3360         needcomma=true;
3361       }
3362       output.println("};");
3363
3364       /*Create C code for endoffset values */
3365       output.print("   unsigned short endoffsetarry_[] = {");
3366       needcomma=false;
3367       for (Iterator it = endoffset.iterator(); it.hasNext();) {
3368         if (needcomma)
3369           output.print(", ");
3370         output.print(it.next());
3371         needcomma=true;
3372       }
3373       output.println("};");
3374
3375       /*Create C code for Field Offset Values */
3376       output.print("   short fieldarry_[] = {");
3377       needcomma=false;
3378       for (Iterator it = fieldoffset.iterator(); it.hasNext();) {
3379         if (needcomma)
3380           output.print(", ");
3381         output.print(it.next());
3382         needcomma=true;
3383       }
3384       output.println("};");
3385       /* make the prefetch call to Runtime */
3386       output.println("   if(!evalPrefetch["+fpn.siteid+"].operMode) {");
3387       output.println("     evalPrefetch["+fpn.siteid+"].retrycount = RETRYINTERVAL;");
3388       output.println("   }");
3389       output.println("   prefetch("+fpn.siteid+" ,"+tuplecount+", oidarray_, endoffsetarry_, fieldarry_);");
3390       output.println(" } else {");
3391       output.println("   evalPrefetch["+fpn.siteid+"].retrycount--;");
3392       output.println(" }");
3393       output.println("}");
3394     }
3395   }
3396
3397   public void generateTransCode(FlatMethod fm, LocalityBinding lb,PrefetchPair pp, Vector oids, Vector fieldoffset, Vector endoffset, int tuplecount, boolean inside, boolean localbase) {
3398     short offsetcount = 0;
3399     int breakindex=0;
3400     if (inside) {
3401       breakindex=1;
3402     } else if (localbase) {
3403       for(; breakindex<pp.desc.size(); breakindex++) {
3404         Descriptor desc=pp.getDescAt(breakindex);
3405         if (desc instanceof FieldDescriptor) {
3406           FieldDescriptor fd=(FieldDescriptor)desc;
3407           if (fd.isGlobal()) {
3408             break;
3409           }
3410         }
3411       }
3412       breakindex++;
3413     }
3414
3415     if (breakindex>pp.desc.size())     //all local
3416       return;
3417
3418     TypeDescriptor lasttype=pp.base.getType();
3419     String basestr=generateTemp(fm, pp.base, lb);
3420     String teststr="";
3421     boolean maybenull=fm.getMethod().isStatic()||
3422                        !pp.base.equals(fm.getParameter(0));
3423
3424     for(int i=0; i<breakindex; i++) {
3425       String indexcheck="";
3426
3427       Descriptor desc=pp.getDescAt(i);
3428       if (desc instanceof FieldDescriptor) {
3429         FieldDescriptor fd=(FieldDescriptor)desc;
3430         if (maybenull) {
3431           if (!teststr.equals(""))
3432             teststr+="&&";
3433           teststr+="((prefptr="+basestr+")!=NULL)";
3434           basestr="((struct "+lasttype.getSafeSymbol()+" *)prefptr)->"+fd.getSafeSymbol();
3435         } else {
3436           basestr=basestr+"->"+fd.getSafeSymbol();
3437           maybenull=true;
3438         }
3439         lasttype=fd.getType();
3440       } else {
3441         IndexDescriptor id=(IndexDescriptor)desc;
3442         indexcheck="((tmpindex=";
3443         for(int j=0; j<id.tddesc.size(); j++) {
3444           indexcheck+=generateTemp(fm, id.getTempDescAt(j), lb)+"+";
3445         }
3446         indexcheck+=id.offset+")>=0)&(tmpindex<((struct ArrayObject *)prefptr)->___length___)";
3447
3448         if (!teststr.equals(""))
3449           teststr+="&&";
3450         teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck;
3451         basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]";
3452         maybenull=true;
3453         lasttype=lasttype.dereference();
3454       }
3455     }
3456
3457     String oid;
3458     if (teststr.equals("")) {
3459       oid="((unsigned int)"+basestr+")";
3460     } else {
3461       oid="((unsigned int)(("+teststr+")?"+basestr+":NULL))";
3462     }
3463     oids.add(oid);
3464
3465     for(int i = breakindex; i < pp.desc.size(); i++) {
3466       String newfieldoffset;
3467       Object desc = pp.getDescAt(i);
3468       if(desc instanceof FieldDescriptor) {
3469         FieldDescriptor fd=(FieldDescriptor)desc;
3470         newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))");
3471         lasttype=fd.getType();
3472       } else {
3473         newfieldoffset = "";
3474         IndexDescriptor id=(IndexDescriptor)desc;
3475         for(int j = 0; j < id.tddesc.size(); j++) {
3476           newfieldoffset += generateTemp(fm, id.getTempDescAt(j), lb) + "+";
3477         }
3478         newfieldoffset += id.offset.toString();
3479         lasttype=lasttype.dereference();
3480       }
3481       fieldoffset.add(newfieldoffset);
3482     }
3483
3484     int base=(tuplecount>0) ? ((Short)endoffset.get(tuplecount-1)).intValue() : 0;
3485     base+=pp.desc.size()-breakindex;
3486     endoffset.add(new Short((short)base));
3487   }
3488
3489
3490
3491   public void generateFlatGlobalConvNode(FlatMethod fm, LocalityBinding lb, FlatGlobalConvNode fgcn, PrintWriter output) {
3492     if (lb!=fgcn.getLocality())
3493       return;
3494     /* Have to generate flat globalconv */
3495     if (fgcn.getMakePtr()) {
3496       if (state.DSM) {
3497         //DEBUG: output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+",\" "+fm+":"+fgcn+"\");");
3498            output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3499       } else {
3500         if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fgcn)||state.READSET&&dc.getNeedWriteTrans(lb, fgcn)) {
3501           //need to do translation
3502           output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+", (void *)("+localsprefixaddr+"));");
3503         } else if (state.READSET&&dc.getNeedTrans(lb, fgcn)) {
3504           if (state.HYBRID&&delaycomp.getConv(lb).contains(fgcn)) {
3505             output.println("TRANSREADRDFISSION("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3506           } else
3507             output.println("TRANSREADRD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3508         }
3509       }
3510     } else {
3511       /* Need to convert to OID */
3512       if ((dc==null)||dc.getNeedSrcTrans(lb,fgcn)) {
3513         if (fgcn.doConvert()||(delaycomp!=null&&delaycomp.needsFission(lb, fgcn.getAtomicEnter())&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) {
3514           output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc(),lb)+");");
3515         } else {
3516           output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=NULL;");
3517         }
3518       }
3519     }
3520   }
3521
3522   public void generateFlatInstanceOfNode(FlatMethod fm,  LocalityBinding lb, FlatInstanceOfNode fion, PrintWriter output) {
3523     int type;
3524     if (fion.getType().isArray()) {
3525       type=state.getArrayNumber(fion.getType())+state.numClasses();
3526     } else {
3527       type=fion.getType().getClassDesc().getId();
3528     }
3529
3530     if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
3531       output.println(generateTemp(fm, fion.getDst(), lb)+"=1;");
3532     else
3533       output.println(generateTemp(fm, fion.getDst(), lb)+"=instanceof("+generateTemp(fm,fion.getSrc(),lb)+","+type+");");
3534   }
3535
3536   int sandboxcounter=0;
3537   public void generateFlatAtomicEnterNode(FlatMethod fm,  LocalityBinding lb, FlatAtomicEnterNode faen, PrintWriter output) {
3538     /* Check to see if we need to generate code for this atomic */
3539     if (locality==null) {
3540       if (GENERATEPRECISEGC) {
3541         output.println("if (pthread_mutex_trylock(&atomiclock)!=0) {");
3542         output.println("stopforgc((struct garbagelist *) &___locals___);");
3543         output.println("pthread_mutex_lock(&atomiclock);");
3544         output.println("restartaftergc();");
3545         output.println("}");
3546       } else {
3547         output.println("pthread_mutex_lock(&atomiclock);");
3548       }
3549       return;
3550     }
3551
3552     if (locality.getAtomic(lb).get(faen.getPrev(0)).intValue()>0)
3553       return;
3554
3555
3556     if (state.SANDBOX) {
3557       outsandbox.println("int atomiccounter"+sandboxcounter+"=LOW_CHECK_FREQUENCY;");
3558       output.println("counter_reset_pointer=&atomiccounter"+sandboxcounter+";");
3559     }
3560
3561     if (state.DELAYCOMP&&delaycomp.needsFission(lb, faen)) {
3562       AtomicRecord ar=atomicmethodmap.get(faen);
3563       //copy in
3564       for(Iterator<TempDescriptor> tmpit=ar.livein.iterator();tmpit.hasNext();) {
3565         TempDescriptor tmp=tmpit.next();
3566         output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3567       }
3568
3569       //copy outs that depend on path
3570       for(Iterator<TempDescriptor> tmpit=ar.liveoutvirtualread.iterator();tmpit.hasNext();) {
3571         TempDescriptor tmp=tmpit.next();
3572         if (!ar.livein.contains(tmp))
3573           output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3574       }
3575     }
3576
3577     /* Backup the temps. */
3578     for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3579       TempDescriptor tmp=tmpit.next();
3580       output.println(generateTemp(fm, backuptable.get(lb).get(tmp),lb)+"="+generateTemp(fm,tmp,lb)+";");
3581     }
3582
3583     output.println("goto transstart"+faen.getIdentifier()+";");
3584
3585     /******* Print code to retry aborted transaction *******/
3586     output.println("transretry"+faen.getIdentifier()+":");
3587
3588     /* Restore temps */
3589     for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3590       TempDescriptor tmp=tmpit.next();
3591       output.println(generateTemp(fm, tmp,lb)+"="+generateTemp(fm,backuptable.get(lb).get(tmp),lb)+";");
3592     }
3593
3594     if (state.DSM) {
3595       /********* Need to revert local object store ********/
3596       String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3597
3598       output.println("while ("+revertptr+") {");
3599       output.println("struct ___Object___ * tmpptr;");
3600       output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3601       output.println("REVERT_OBJ("+revertptr+");");
3602       output.println(revertptr+"=tmpptr;");
3603       output.println("}");
3604     }
3605     /******* Tell the runtime to start the transaction *******/
3606
3607     output.println("transstart"+faen.getIdentifier()+":");
3608     if (state.SANDBOX) {
3609       output.println("transaction_check_counter=*counter_reset_pointer;");
3610       sandboxcounter++;
3611     }
3612     output.println("transStart();");
3613
3614     if (state.ABORTREADERS||state.SANDBOX) {
3615       if (state.SANDBOX)
3616         output.println("abortenabled=1;");
3617       output.println("if (_setjmp(aborttrans)) {");
3618       output.println("  goto transretry"+faen.getIdentifier()+"; }");
3619     }
3620   }
3621
3622   public void generateFlatAtomicExitNode(FlatMethod fm,  LocalityBinding lb, FlatAtomicExitNode faen, PrintWriter output) {
3623     /* Check to see if we need to generate code for this atomic */
3624     if (locality==null) {
3625       output.println("pthread_mutex_unlock(&atomiclock);");
3626       return;
3627     }
3628     if (locality.getAtomic(lb).get(faen).intValue()>0)
3629       return;
3630     //store the revert list before we lose the transaction object
3631     
3632     if (state.DSM) {
3633       String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3634       output.println(revertptr+"=revertlist;");
3635       output.println("if (transCommit()) {");
3636       output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3637       output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3638       output.println("} else {");
3639       /* Need to commit local object store */
3640       output.println("while ("+revertptr+") {");
3641       output.println("struct ___Object___ * tmpptr;");
3642       output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3643       output.println("COMMIT_OBJ("+revertptr+");");
3644       output.println(revertptr+"=tmpptr;");
3645       output.println("}");
3646       output.println("}");
3647       return;
3648     }
3649
3650     if (!state.DELAYCOMP) {
3651       //Normal STM stuff
3652       output.println("if (transCommit()) {");
3653       /* Transaction aborts if it returns true */
3654       output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3655       output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3656       output.println("}");
3657     } else {
3658       if (delaycomp.optimizeTrans(lb, faen.getAtomicEnter())&&(!state.STMARRAY||state.DUALVIEW))  {
3659         AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3660         output.println("LIGHTWEIGHTCOMMIT("+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+", transretry"+faen.getAtomicEnter().getIdentifier()+");");
3661         //copy out
3662         for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3663           TempDescriptor tmp=tmpit.next();
3664           output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3665         }
3666       } else if (delaycomp.needsFission(lb, faen.getAtomicEnter())) {
3667         AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3668         //do call
3669         output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {");
3670         output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3671         output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3672         output.println("}");
3673         //copy out
3674         output.println("else {");
3675         for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3676           TempDescriptor tmp=tmpit.next();
3677           output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3678         }
3679         output.println("}");
3680       } else {
3681         output.println("if (transCommit(NULL, NULL, NULL, NULL)) {");
3682         output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3683         output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3684         output.println("}");
3685       }
3686     }
3687   }
3688
3689   public void generateFlatSESEEnterNode( FlatMethod fm,  
3690                                          LocalityBinding lb, 
3691                                          FlatSESEEnterNode fsen, 
3692                                          PrintWriter output 
3693                                        ) {
3694     // if MLP flag is off, okay that SESE nodes are in IR graph, 
3695     // just skip over them and code generates exactly the same
3696     if( !(state.MLP || state.OOOJAVA) ) {
3697       return;
3698     }    
3699     // there may be an SESE in an unreachable method, skip over
3700     if( (state.MLP && !mlpa.getAllSESEs().contains( fsen )) ||
3701         (state.OOOJAVA && !oooa.getAllSESEs().contains(fsen))
3702     ) {
3703       return;
3704     }
3705
3706     // also, if we have encountered a placeholder, just skip it
3707     if( fsen.getIsCallerSESEplaceholder() ) {
3708       return;
3709     }
3710
3711     output.println("   {");
3712
3713     if( state.COREPROF ) {
3714       output.println("#ifdef CP_EVENTID_TASKDISPATCH");
3715       output.println("     CP_LOGEVENT( CP_EVENTID_TASKDISPATCH, CP_EVENTTYPE_BEGIN );");
3716       output.println("#endif");
3717     }
3718
3719
3720     // before doing anything, lock your own record and increment the running children
3721     if( (state.MLP     && fsen != mlpa.getMainSESE()) || 
3722         (state.OOOJAVA && fsen != oooa.getMainSESE())
3723     ) {      
3724       output.println("     atomic_inc(&(runningSESE->numRunningChildren));");
3725     }
3726
3727
3728     // allocate the space for this record
3729     output.println( "#ifndef OOO_DISABLE_TASKMEMPOOL" );
3730
3731     output.println( "#ifdef CP_EVENTID_POOLALLOC");
3732     output.println( "     CP_LOGEVENT( CP_EVENTID_POOLALLOC, CP_EVENTTYPE_BEGIN );");
3733     output.println( "#endif");
3734     if( (state.MLP     && fsen != mlpa.getMainSESE()) || 
3735         (state.OOOJAVA && fsen != oooa.getMainSESE())
3736         ) {
3737       output.println("     "+
3738                      fsen.getSESErecordName()+"* seseToIssue = ("+
3739                      fsen.getSESErecordName()+"*) poolalloc( runningSESE->taskRecordMemPool );");
3740     } else {
3741       output.println("     "+
3742                      fsen.getSESErecordName()+"* seseToIssue = ("+
3743                      fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
3744                      fsen.getSESErecordName()+" ) );");
3745     }
3746     output.println( "#ifdef CP_EVENTID_POOLALLOC");
3747     output.println( "     CP_LOGEVENT( CP_EVENTID_POOLALLOC, CP_EVENTTYPE_END );");
3748     output.println( "#endif");
3749
3750     output.println( "#else // OOO_DISABLE_TASKMEMPOOL" );
3751       output.println("     "+
3752                      fsen.getSESErecordName()+"* seseToIssue = ("+
3753                      fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
3754                      fsen.getSESErecordName()+" ) );");
3755     output.println( "#endif // OOO_DISABLE_TASKMEMPOOL" );
3756
3757
3758
3759
3760     // set up the SESE in-set and out-set objects, which look
3761     // like a garbage list
3762     output.println("     struct garbagelist * gl= (struct garbagelist *)&(((SESEcommon*)(seseToIssue))[1]);");
3763     output.println("     gl->size="+calculateSizeOfSESEParamList(fsen)+";");
3764     output.println("     gl->next = NULL;");
3765
3766     // there are pointers to SESE records the newly-issued SESE
3767     // will use to get values it depends on them for--how many
3768     // are there, and what is the offset from the total SESE
3769     // record to the first dependent record pointer?
3770     output.println("     seseToIssue->common.numDependentSESErecords="+
3771                    fsen.getNumDepRecs()+";");
3772     
3773     // we only need this (and it will only compile) when the number of dependent
3774     // SESE records is non-zero
3775     if( fsen.getFirstDepRecField() != null ) {
3776       output.println("     seseToIssue->common.offsetToDepSESErecords=(INTPTR)sizeof("+
3777                      fsen.getSESErecordName()+") - (INTPTR)&((("+
3778                      fsen.getSESErecordName()+"*)0)->"+fsen.getFirstDepRecField()+");"
3779                      );
3780     }
3781     
3782     if (state.RCR) {
3783       output.println("    seseToIssumer->common.offsetToParamRecords=(INTPTR)sizeof("+fsen.getSESErecordName()+") - (INTPTR) & ((("+fsen.getSESErecordName()+"*)0)->rcrRecords);");
3784     }
3785
3786     // fill in common data
3787     output.println("     int localCount=0;");
3788     output.println("     seseToIssue->common.classID = "+fsen.getIdentifier()+";");
3789     output.println("     psem_init( &(seseToIssue->common.stallSem) );");
3790     output.println("     seseToIssue->common.forwardList = createQueue();");
3791     output.println("     seseToIssue->common.unresolvedDependencies = 10000;");
3792     output.println("     pthread_cond_init( &(seseToIssue->common.doneCond), NULL );");
3793     output.println("     seseToIssue->common.doneExecuting = FALSE;");    
3794     output.println("     pthread_cond_init( &(seseToIssue->common.runningChildrenCond), NULL );");
3795     output.println("     seseToIssue->common.numRunningChildren = 0;");
3796     output.println("     seseToIssue->common.parent = runningSESE;");
3797     // start with refCount = 2, one being the count that the child itself
3798     // will decrement when it retires, to say it is done using its own
3799     // record, and the other count is for the parent that will remember
3800     // the static name of this new child below
3801     output.println("     seseToIssue->common.refCount = 2;");
3802
3803     // all READY in-vars should be copied now and be done with it
3804     Iterator<TempDescriptor> tempItr = fsen.getReadyInVarSet().iterator();
3805     while( tempItr.hasNext() ) {
3806       TempDescriptor temp = tempItr.next();
3807
3808       // when we are issuing the main SESE or an SESE with placeholder
3809       // caller SESE as parent, generate temp child child's eclosing method,
3810       // otherwise use the parent's enclosing method as the context
3811       boolean useParentContext = false;
3812
3813       if( (state.MLP && fsen != mlpa.getMainSESE()) || 
3814           (state.OOOJAVA && fsen != oooa.getMainSESE())     
3815       ) {
3816         assert fsen.getParent() != null;
3817         if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3818           useParentContext = true;
3819         }
3820       }
3821
3822       if( useParentContext ) {
3823         output.println("     seseToIssue->"+temp+" = "+
3824                        generateTemp( fsen.getParent().getfmBogus(), temp, null )+";");   
3825       } else {
3826         output.println("     seseToIssue->"+temp+" = "+
3827                        generateTemp( fsen.getfmEnclosing(), temp, null )+";");
3828       }
3829     }
3830     
3831     // before potentially adding this SESE to other forwarding lists,
3832     // create it's lock
3833     output.println("     pthread_mutex_init( &(seseToIssue->common.lock), NULL );");
3834
3835   
3836     if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3837         (state.OOOJAVA && fsen != oooa.getMainSESE())    
3838     ) {
3839       // count up outstanding dependencies, static first, then dynamic
3840       Iterator<SESEandAgePair> staticSrcsItr = fsen.getStaticInVarSrcs().iterator();
3841       while( staticSrcsItr.hasNext() ) {
3842         SESEandAgePair srcPair = staticSrcsItr.next();
3843         output.println("     {");
3844         output.println("       SESEcommon* src = (SESEcommon*)"+srcPair+";");
3845         output.println("       pthread_mutex_lock( &(src->lock) );");
3846         // FORWARD TODO
3847         output.println("       if( !src->doneExecuting ) {");
3848         output.println("         addNewItem( src->forwardList, seseToIssue );");        
3849         output.println("         ++(localCount);");
3850         output.println("       }");
3851         output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
3852         output.println("       ADD_REFERENCE_TO( src );");
3853         output.println("#endif" );
3854         output.println("       pthread_mutex_unlock( &(src->lock) );");
3855         output.println("     }");
3856
3857         // whether or not it is an outstanding dependency, make sure
3858         // to pass the static name to the child's record
3859         output.println("     seseToIssue->"+srcPair+" = "+
3860                        "("+srcPair.getSESE().getSESErecordName()+"*)"+
3861                        srcPair+";");
3862       }
3863       
3864       // dynamic sources might already be accounted for in the static list,
3865       // so only add them to forwarding lists if they're not already there
3866       Iterator<TempDescriptor> dynVarsItr = fsen.getDynamicInVarSet().iterator();
3867       while( dynVarsItr.hasNext() ) {
3868         TempDescriptor dynInVar = dynVarsItr.next();
3869         output.println("     {");
3870         output.println("       SESEcommon* src = (SESEcommon*)"+dynInVar+"_srcSESE;");
3871
3872         // the dynamic source is NULL if it comes from your own space--you can't pass
3873         // the address off to the new child, because you're not done executing and
3874         // might change the variable, so copy it right now
3875         output.println("       if( src != NULL ) {");
3876         output.println("         pthread_mutex_lock( &(src->lock) );");
3877
3878         // FORWARD TODO
3879
3880         output.println("         if( isEmpty( src->forwardList ) ||");
3881         output.println("             seseToIssue != peekItem( src->forwardList ) ) {");
3882         output.println("           if( !src->doneExecuting ) {");
3883         output.println("             addNewItem( src->forwardList, seseToIssue );");
3884         output.println("             ++(localCount);");
3885         output.println("           }");
3886         output.println("         }");
3887         output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
3888         output.println("         ADD_REFERENCE_TO( src );");
3889         output.println("#endif" );
3890         output.println("         pthread_mutex_unlock( &(src->lock) );");       
3891         output.println("         seseToIssue->"+dynInVar+"_srcOffset = "+dynInVar+"_srcOffset;");
3892         output.println("       } else {");
3893
3894         boolean useParentContext = false;
3895         if( (state.MLP && fsen != mlpa.getMainSESE()) || 
3896             (state.OOOJAVA && fsen != oooa.getMainSESE())       
3897         ) {
3898           assert fsen.getParent() != null;
3899           if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3900             useParentContext = true;
3901           }
3902         }       
3903         if( useParentContext ) {
3904           output.println("         seseToIssue->"+dynInVar+" = "+
3905                          generateTemp( fsen.getParent().getfmBogus(), dynInVar, null )+";");
3906         } else {
3907           output.println("         seseToIssue->"+dynInVar+" = "+
3908                          generateTemp( fsen.getfmEnclosing(), dynInVar, null )+";");
3909         }
3910         
3911         output.println("       }");
3912         output.println("     }");
3913         
3914         // even if the value is already copied, make sure your NULL source
3915         // gets passed so child knows it already has the dynamic value
3916         output.println("     seseToIssue->"+dynInVar+"_srcSESE = "+dynInVar+"_srcSESE;");
3917       }
3918
3919       
3920
3921
3922       // maintain pointers for finding dynamic SESE 
3923       // instances from static names      
3924       SESEandAgePair pairNewest = new SESEandAgePair( fsen, 0 );
3925       SESEandAgePair pairOldest = new SESEandAgePair( fsen, fsen.getOldestAgeToTrack() );
3926       if(  fsen.getParent() != null && 
3927            fsen.getParent().getNeededStaticNames().contains( pairNewest ) 
3928         ) {       
3929         output.println("     {");
3930         output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
3931         output.println("       SESEcommon* oldest = "+pairOldest+";");
3932         output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
3933
3934         for( int i = fsen.getOldestAgeToTrack(); i > 0; --i ) {
3935           SESEandAgePair pair1 = new SESEandAgePair( fsen, i   );
3936           SESEandAgePair pair2 = new SESEandAgePair( fsen, i-1 );
3937           output.println("       "+pair1+" = "+pair2+";");
3938         }      
3939         output.println("       "+pairNewest+" = &(seseToIssue->common);");
3940
3941         // no need to add a reference to whatever is the newest record, because
3942         // we initialized seseToIssue->refCount to *2*
3943         // but release a reference to whatever was the oldest BEFORE the shift
3944         output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
3945         output.println("       if( oldest != NULL ) {");
3946         output.println("         RELEASE_REFERENCE_TO( oldest );");
3947         output.println("       }");
3948         output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
3949         output.println("     }");
3950       }
3951
3952       if (state.RCR) {
3953
3954         
3955       }
3956
3957       if(state.RCR) {
3958         //TODO BCD
3959         //clear out the parameter records
3960
3961       }
3962
3963
3964       if( state.COREPROF ) {
3965         output.println("#ifdef CP_EVENTID_PREPAREMEMQ");
3966         output.println("     CP_LOGEVENT( CP_EVENTID_PREPAREMEMQ, CP_EVENTTYPE_BEGIN );");
3967         output.println("#endif");
3968       }
3969
3970
3971       ////////////////
3972       // count up memory conflict dependencies,
3973       // eom
3974       if(state.OOOJAVA){
3975         FlatSESEEnterNode parent = fsen.getParent();
3976         Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(parent);
3977         if (graph != null && graph.hasConflictEdge()) {
3978           Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
3979           output.println();
3980           output.println("     //add memory queue element");
3981           Analysis.OoOJava.SESEWaitingQueue seseWaitingQueue=
3982             graph.getWaitingElementSetBySESEID(fsen.getIdentifier(), seseLockSet);
3983           if(seseWaitingQueue.getWaitingElementSize()>0) {
3984             output.println("     {");
3985             output.println("       REntry* rentry=NULL;");
3986             output.println("       INTPTR* pointer=NULL;");
3987             output.println("       seseToIssue->common.rentryIdx=0;");
3988
3989             Set<Integer> queueIDSet=seseWaitingQueue.getQueueIDSet();
3990             for (Iterator iterator = queueIDSet.iterator(); iterator.hasNext();) {
3991               Integer key = (Integer) iterator.next();
3992               int queueID=key.intValue();
3993               Set<Analysis.OoOJava.WaitingElement> waitingQueueSet =  
3994                 seseWaitingQueue.getWaitingElementSet(queueID);
3995               int enqueueType=seseWaitingQueue.getType(queueID);
3996               if(enqueueType==SESEWaitingQueue.EXCEPTION) {
3997                 output.println("       INITIALIZEBUF(runningSESE->memoryQueueArray[" + queueID+ "]);");
3998               }
3999               for (Iterator iterator2 = waitingQueueSet.iterator(); iterator2.hasNext();) {
4000                 Analysis.OoOJava.WaitingElement waitingElement 
4001                   = (Analysis.OoOJava.WaitingElement) iterator2.next();
4002                 if (waitingElement.getStatus() >= ConflictNode.COARSE) {
4003                   output.println("       rentry=mlpCreateREntry("
4004                                  + waitingElement.getStatus()
4005                                  + ", &(seseToIssue->common));");
4006                 } else {
4007                   TempDescriptor td = waitingElement.getTempDesc();
4008                   // decide whether waiting element is dynamic or static
4009                   if (fsen.getDynamicInVarSet().contains(td)) {
4010                     // dynamic in-var case
4011                     output.println("       pointer=seseToIssue->"
4012                                    + waitingElement.getDynID()
4013                                    + "_srcSESE+seseToIssue->"
4014                                    + waitingElement.getDynID()
4015                                    + "_srcOffset;");
4016                     output.println("       rentry=mlpCreateFineREntry("
4017                                    + waitingElement.getStatus()
4018                                    + ", &(seseToIssue->common),  pointer );");
4019                   } else if (fsen.getStaticInVarSet().contains(td)) {
4020                     // static in-var case
4021                     VariableSourceToken vst = fsen.getStaticInVarSrc(td);
4022                     if (vst != null) {
4023   
4024                       String srcId = "SESE_" + vst.getSESE().getPrettyIdentifier()
4025                         + vst.getSESE().getIdentifier()
4026                         + "_" + vst.getAge();
4027                       output.println("       pointer=(void*)&seseToIssue->"
4028                                      + srcId
4029                                      + "->"
4030                                      + waitingElement
4031                                      .getDynID()
4032                                      + ";");
4033                       output.println("       rentry=mlpCreateFineREntry("
4034                                      + waitingElement.getStatus()
4035                                      + ", &(seseToIssue->common),  pointer );");
4036                     }
4037                   } else {
4038                     output.println("       rentry=mlpCreateFineREntry("
4039                                    + waitingElement.getStatus()
4040                                    + ", &(seseToIssue->common), (void*)&seseToIssue->"
4041                                    + waitingElement.getDynID()
4042                                    + ");");
4043                   }
4044                 }
4045                 output.println("       rentry->queue=runningSESE->memoryQueueArray["
4046                                + waitingElement.getQueueID()
4047                                + "];");
4048                 
4049                 if(enqueueType==SESEWaitingQueue.NORMAL){
4050                   output.println("       seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
4051                   output.println("       if(ADDRENTRY(runningSESE->memoryQueueArray["
4052                                  + waitingElement.getQueueID()
4053                                  + "],rentry)==NOTREADY) {");
4054                   output.println("          localCount++;");
4055                   output.println("       }");
4056                   
4057                   // Trying to execute the dynamic coarse grain conflict strategy...
4058                   if(state.RCR && rcr != null) {
4059                     boolean useParentContext = false;
4060
4061                     if( (state.MLP &&fsen != mlpa.getMainSESE()) || 
4062                         (state.OOOJAVA &&fsen != oooa.getMainSESE())) {
4063                       assert fsen.getParent() != null;
4064                       if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
4065                         useParentContext = true;
4066                       }
4067                     }
4068                     
4069                     for (TempDescriptor invar : fsen.getInVarsForDynamicCoarseConflictResolution()) {                      
4070                       String varString;
4071                       if( useParentContext ) {
4072                         varString = generateTemp( fsen.getParent().getfmBogus(), invar, null );
4073                       } else {
4074                         varString = generateTemp( fsen.getfmEnclosing(),         invar, null );
4075                       }
4076                       output.println("       "+rcr.getTraverserInvocation(invar, varString, fsen));
4077                     }
4078                   }
4079                 }else{
4080                   output.println("       ADDRENTRYTOBUF(runningSESE->memoryQueueArray[" + waitingElement.getQueueID() + "],rentry);");
4081                 }
4082               }
4083               if(enqueueType!=SESEWaitingQueue.NORMAL){
4084                 output.println("       localCount+=RESOLVEBUF(runningSESE->memoryQueueArray["
4085                                + queueID+ "],&seseToIssue->common);");
4086               }       
4087             }
4088             output.println("     }");
4089           }
4090           output.println();
4091         }
4092       } else {
4093         ConflictGraph graph = null;
4094         FlatSESEEnterNode parent = fsen.getParent();
4095         if (parent != null) {
4096           if (parent.isCallerSESEplaceholder) {
4097             graph = mlpa.getConflictGraphResults().get(parent.getfmEnclosing());
4098           } else {
4099             graph = mlpa.getConflictGraphResults().get(parent);
4100           }
4101         }
4102         if (graph != null && graph.hasConflictEdge()) {
4103           HashSet<SESELock> seseLockSet = mlpa.getConflictGraphLockMap()
4104             .get(graph);
4105           output.println();
4106           output.println("     //add memory queue element");
4107           SESEWaitingQueue seseWaitingQueue=graph.getWaitingElementSetBySESEID(fsen.getIdentifier(),
4108                                                                                seseLockSet);
4109           if(seseWaitingQueue.getWaitingElementSize()>0){
4110             output.println("     {");
4111             output.println("     REntry* rentry=NULL;");
4112             output.println("     INTPTR* pointer=NULL;");
4113             output.println("     seseToIssue->common.rentryIdx=0;");
4114
4115             Set<Integer> queueIDSet=seseWaitingQueue.getQueueIDSet();
4116             for (Iterator iterator = queueIDSet.iterator(); iterator
4117                    .hasNext();) {
4118               Integer key = (Integer) iterator.next();
4119               int queueID=key.intValue();
4120               Set<WaitingElement> waitingQueueSet =  seseWaitingQueue.getWaitingElementSet(queueID);
4121               int enqueueType=seseWaitingQueue.getType(queueID);
4122               if(enqueueType==SESEWaitingQueue.EXCEPTION){
4123                 output.println("     INITIALIZEBUF(runningSESE->memoryQueueArray["
4124                                + queueID+ "]);");
4125               }
4126               for (Iterator iterator2 = waitingQueueSet.iterator(); iterator2
4127                      .hasNext();) {
4128                 WaitingElement waitingElement = (WaitingElement) iterator2
4129                   .next();
4130                 if (waitingElement.getStatus() >= ConflictNode.COARSE) {
4131                   output.println("     rentry=mlpCreateREntry("
4132                                  + waitingElement.getStatus()
4133                                  + ", &(seseToIssue->common));");
4134                 } else {
4135                   TempDescriptor td = waitingElement
4136                     .getTempDesc();
4137                   // decide whether waiting element is dynamic or
4138                   // static
4139                   if (fsen.getDynamicInVarSet().contains(td)) {
4140                     // dynamic in-var case
4141                     output.println("     pointer=seseToIssue->"
4142                                    + waitingElement.getDynID()
4143                                    + "_srcSESE+seseToIssue->"
4144                                    + waitingElement.getDynID()
4145                                    + "_srcOffset;");
4146                     output
4147                       .println("     rentry=mlpCreateFineREntry("
4148                                + waitingElement
4149                                .getStatus()
4150                                + ", &(seseToIssue->common),  pointer );");
4151                   } else if (fsen.getStaticInVarSet()
4152                              .contains(td)) {
4153                     // static in-var case
4154                     VariableSourceToken vst = fsen
4155                       .getStaticInVarSrc(td);
4156                     if (vst != null) {
4157   
4158                       String srcId = "SESE_"
4159                         + vst.getSESE()
4160                         .getPrettyIdentifier()
4161                         + vst.getSESE().getIdentifier()
4162                         + "_" + vst.getAge();
4163                       output
4164                         .println("     pointer=(void*)&seseToIssue->"
4165                                  + srcId
4166                                  + "->"
4167                                  + waitingElement
4168                                  .getDynID()
4169                                  + ";");
4170                       output
4171                         .println("     rentry=mlpCreateFineREntry("
4172                                  + waitingElement
4173                                  .getStatus()
4174                                  + ", &(seseToIssue->common),  pointer );");
4175   
4176                     }
4177                   } else {
4178                     output
4179                       .println("     rentry=mlpCreateFineREntry("
4180                                + waitingElement
4181                                .getStatus()
4182                                + ", &(seseToIssue->common),  (void*)&seseToIssue->"
4183                                + waitingElement.getDynID()
4184                                + ");");
4185                   }
4186                 }
4187                 output
4188                   .println("     rentry->queue=runningSESE->memoryQueueArray["
4189                            + waitingElement.getQueueID()
4190                            + "];");
4191                                                         
4192                 if(enqueueType==SESEWaitingQueue.NORMAL){
4193                   output
4194                     .println("     seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
4195                   output
4196                     .println("     if(ADDRENTRY(runningSESE->memoryQueueArray["
4197                              + waitingElement.getQueueID()
4198                              + "],rentry)==NOTREADY){");
4199                   output.println("        ++(localCount);");
4200                   output.println("     } ");
4201                 }else{
4202                   output
4203                     .println("     ADDRENTRYTOBUF(runningSESE->memoryQueueArray["
4204                              + waitingElement.getQueueID()
4205                              + "],rentry);");
4206                 }
4207               }
4208               if(enqueueType!=SESEWaitingQueue.NORMAL){
4209                 output.println("     localCount+=RESOLVEBUF(runningSESE->memoryQueueArray["
4210                                + queueID+ "],&seseToIssue->common);");
4211               }
4212             }
4213             output.println("     }");
4214           }
4215           output.println();
4216         }
4217       }
4218     }
4219
4220     if( state.COREPROF ) {
4221       output.println("#ifdef CP_EVENTID_PREPAREMEMQ");
4222       output.println("     CP_LOGEVENT( CP_EVENTID_PREPAREMEMQ, CP_EVENTTYPE_END );");
4223       output.println("#endif");
4224     }
4225     
4226     // Enqueue Task Record
4227     if (state.RCR) {
4228       output.println("    enqueueTR((void *)seseToIssue);");
4229     }
4230
4231     // if there were no outstanding dependencies, issue here
4232     output.println("     if(  atomic_sub_and_test(10000-localCount,&(seseToIssue->common.unresolvedDependencies) ) ) {");
4233     output.println("       workScheduleSubmit( (void*)seseToIssue );");
4234     output.println("     }");
4235
4236     
4237
4238     if( state.COREPROF ) {
4239       output.println("#ifdef CP_EVENTID_TASKDISPATCH");
4240       output.println("     CP_LOGEVENT( CP_EVENTID_TASKDISPATCH, CP_EVENTTYPE_END );");
4241       output.println("#endif");
4242     }
4243
4244     output.println("   }");
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