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