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