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