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