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