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;
13 import Analysis.TaskStateAnalysis.FlagState;
14 import Analysis.TaskStateAnalysis.FlagComparator;
15 import Analysis.TaskStateAnalysis.OptionalTaskDescriptor;
16 import Analysis.TaskStateAnalysis.Predicate;
17 import Analysis.TaskStateAnalysis.SafetyAnalysis;
18 import Analysis.TaskStateAnalysis.TaskIndex;
19 import Analysis.Locality.LocalityAnalysis;
20 import Analysis.Locality.LocalityBinding;
21 import Analysis.Locality.DiscoverConflicts;
22 import Analysis.Locality.DelayComputation;
23 import Analysis.CallGraph.CallGraph;
24 import Analysis.Prefetch.*;
25 import Analysis.Loops.WriteBarrier;
26 import Analysis.Loops.GlobalFieldType;
27 import Analysis.Locality.TypeAnalysis;
28 import Analysis.MLP.MLPAnalysis;
29 import Analysis.MLP.VariableSourceToken;
30 import Analysis.MLP.CodePlan;
31 import Analysis.MLP.SESEandAgePair;
33 public class BuildCode {
36 Hashtable paramstable;
41 String localsprefix="___locals___";
42 String localsprefixaddr="&"+localsprefix;
43 String localsprefixderef=localsprefix+".";
44 String fcrevert="___fcrevert___";
45 String paramsprefix="___params___";
46 String oidstr="___nextobject___";
47 String nextobjstr="___nextobject___";
48 String localcopystr="___localcopy___";
49 public static boolean GENERATEPRECISEGC=false;
50 public static String PREFIX="";
51 public static String arraytype="ArrayObject";
52 public static int flagcount = 0;
55 protected int maxtaskparams=0;
56 private int maxcount=0;
57 ClassDescriptor[] cdarray;
58 TypeDescriptor[] arraytable;
59 LocalityAnalysis locality;
60 Hashtable<LocalityBinding, TempDescriptor> reverttable;
61 Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>> backuptable;
65 String mlperrstr = "if(status != 0) { "+
66 "sprintf(errmsg, \"MLP error at %s:%d\", __FILE__, __LINE__); "+
67 "perror(errmsg); exit(-1); }";
68 boolean nonSESEpass=true;
71 DiscoverConflicts recorddc;
72 DelayComputation delaycomp;
75 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa) {
76 this(st, temptovar, typeutil, null, sa, pa, null);
79 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa) {
80 this(st, temptovar, typeutil, null, sa, pa, mlpa);
83 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, PrefetchAnalysis pa, MLPAnalysis mlpa) {
84 this(st, temptovar, typeutil, locality, null, pa, mlpa);
87 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa) {
92 callgraph=new CallGraph(state);
94 oidstr="___objlocation___";
95 this.temptovar=temptovar;
96 paramstable=new Hashtable();
97 tempstable=new Hashtable();
98 fieldorder=new Hashtable();
99 flagorder=new Hashtable();
100 this.typeutil=typeutil;
101 virtualcalls=new Virtual(state,locality);
102 if (locality!=null) {
103 this.locality=locality;
104 this.reverttable=new Hashtable<LocalityBinding, TempDescriptor>();
105 this.backuptable=new Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>>();
106 this.wb=new WriteBarrier(locality, st);
108 if (state.SINGLETM&&state.DCOPTS) {
109 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
110 this.dc=new DiscoverConflicts(locality, st, typeanalysis, null);
113 if (state.DELAYCOMP) {
114 //TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
115 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
116 GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
117 delaycomp=new DelayComputation(locality, st, typeanalysis, gft);
118 delaycomp.doAnalysis();
119 dc=delaycomp.getConflicts();
120 recorddc=new DiscoverConflicts(locality, st, typeanalysis, delaycomp.getCannotDelayMap(), true, true, null);
121 recorddc.doAnalysis();
125 /** The buildCode method outputs C code for all the methods. The Flat
126 * versions of the methods must already be generated and stored in
127 * the State object. */
129 public void buildCode() {
130 /* Create output streams to write to */
131 PrintWriter outclassdefs=null;
132 PrintWriter outstructs=null;
133 PrintWriter outrepairstructs=null;
134 PrintWriter outmethodheader=null;
135 PrintWriter outmethod=null;
136 PrintWriter outvirtual=null;
137 PrintWriter outtask=null;
138 PrintWriter outtaskdefs=null;
139 PrintWriter outoptionalarrays=null;
140 PrintWriter optionalheaders=null;
143 outstructs=new PrintWriter(new FileOutputStream(PREFIX+"structdefs.h"), true);
144 outmethodheader=new PrintWriter(new FileOutputStream(PREFIX+"methodheaders.h"), true);
145 outclassdefs=new PrintWriter(new FileOutputStream(PREFIX+"classdefs.h"), true);
146 outmethod=new PrintWriter(new FileOutputStream(PREFIX+"methods.c"), true);
147 outvirtual=new PrintWriter(new FileOutputStream(PREFIX+"virtualtable.h"), true);
149 outtask=new PrintWriter(new FileOutputStream(PREFIX+"task.h"), true);
150 outtaskdefs=new PrintWriter(new FileOutputStream(PREFIX+"taskdefs.c"), true);
151 if (state.OPTIONAL) {
152 outoptionalarrays=new PrintWriter(new FileOutputStream(PREFIX+"optionalarrays.c"), true);
153 optionalheaders=new PrintWriter(new FileOutputStream(PREFIX+"optionalstruct.h"), true);
156 if (state.structfile!=null) {
157 outrepairstructs=new PrintWriter(new FileOutputStream(PREFIX+state.structfile+".struct"), true);
159 } catch (Exception e) {
164 /* Build the virtual dispatch tables */
165 buildVirtualTables(outvirtual);
167 /* Output includes */
168 outmethodheader.println("#ifndef METHODHEADERS_H");
169 outmethodheader.println("#define METHODHEADERS_H");
170 outmethodheader.println("#include \"structdefs.h\"");
172 outmethodheader.println("#include \"dstm.h\"");
173 if (state.SINGLETM) {
174 outmethodheader.println("#include \"tm.h\"");
175 outmethodheader.println("#include \"delaycomp.h\"");
177 if (state.ABORTREADERS) {
178 outmethodheader.println("#include \"abortreaders.h\"");
179 outmethodheader.println("#include <setjmp.h>");
182 outmethodheader.println("#include <stdlib.h>");
183 outmethodheader.println("#include <stdio.h>");
184 outmethodheader.println("#include <string.h>");
185 outmethodheader.println("#include \"mlp_runtime.h\"");
186 outmethodheader.println("#include \"psemaphore.h\"");
189 /* Output Structures */
190 outputStructs(outstructs);
192 // Output the C class declarations
193 // These could mutually reference each other
194 outputClassDeclarations(outclassdefs);
196 // Output function prototypes and structures for parameters
197 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
198 while(it.hasNext()) {
199 ClassDescriptor cn=(ClassDescriptor)it.next();
200 generateCallStructs(cn, outclassdefs, outstructs, outmethodheader);
202 outclassdefs.close();
205 /* Map flags to integers */
206 /* The runtime keeps track of flags using these integers */
207 it=state.getClassSymbolTable().getDescriptorsIterator();
208 while(it.hasNext()) {
209 ClassDescriptor cn=(ClassDescriptor)it.next();
213 generateTaskStructs(outstructs, outmethodheader);
215 /* Outputs generic task structures if this is a task
217 outputTaskTypes(outtask);
221 // have to initialize some SESE compiler data before
222 // analyzing normal methods, which must happen before
223 // generating SESE internal code
224 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
225 FlatSESEEnterNode fsen = seseit.next();
226 initializeSESE( fsen );
230 /* Build the actual methods */
231 outputMethods(outmethod);
233 // Output function prototypes and structures for SESE's and code
237 // first generate code for each sese's internals
238 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
239 FlatSESEEnterNode fsen = seseit.next();
240 generateMethodSESE(fsen, null, outstructs, outmethodheader, outmethod);
243 // then write the invokeSESE switch to decouple scheduler
244 // from having to do unique details of sese invocation
245 generateSESEinvocationMethod(outmethodheader, outmethod);
249 /* Output code for tasks */
250 outputTaskCode(outtaskdefs, outmethod);
252 /* Record maximum number of task parameters */
253 outstructs.println("#define MAXTASKPARAMS "+maxtaskparams);
254 } else if (state.main!=null) {
255 /* Generate main method */
256 outputMainMethod(outmethod);
259 /* Generate information for task with optional parameters */
260 if (state.TASK&&state.OPTIONAL) {
261 generateOptionalArrays(outoptionalarrays, optionalheaders, state.getAnalysisResult(), state.getOptionalTaskDescriptors());
262 outoptionalarrays.close();
265 /* Output structure definitions for repair tool */
266 if (state.structfile!=null) {
267 buildRepairStructs(outrepairstructs);
268 outrepairstructs.close();
272 outmethodheader.println("#endif");
273 outmethodheader.close();
275 outstructs.println("#endif");
280 /* This code just generates the main C method for java programs.
281 * The main C method packs up the arguments into a string array
282 * and passes it to the java main method. */
284 private void outputMainMethod(PrintWriter outmethod) {
285 outmethod.println("int main(int argc, const char *argv[]) {");
286 outmethod.println(" int i;");
289 //outmethod.println(" pthread_once( &mlpOnceObj, mlpInitOncePerThread );");
290 outmethod.println(" workScheduleInit( "+state.MLP_NUMCORES+", invokeSESEmethod );");
294 outmethod.println("#ifdef TRANSSTATS \n");
295 outmethod.println("handle();\n");
296 outmethod.println("#endif\n");
298 if (state.THREAD||state.DSM||state.SINGLETM) {
299 outmethod.println("initializethreads();");
302 outmethod.println("if (dstmStartup(argv[1])) {");
303 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
304 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-2);");
306 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-2);");
309 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
310 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1);");
312 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1);");
316 outmethod.println(" for(i=2;i<argc;i++) {");
318 outmethod.println(" for(i=1;i<argc;i++) {");
319 outmethod.println(" int length=strlen(argv[i]);");
320 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
321 outmethod.println(" struct ___String___ *newstring=NewString(NULL, argv[i], length);");
323 outmethod.println(" struct ___String___ *newstring=NewString(argv[i], length);");
326 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-2]=newstring;");
328 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-1]=newstring;");
329 outmethod.println(" }");
331 MethodDescriptor md=typeutil.getMain();
332 ClassDescriptor cd=typeutil.getMainClass();
334 outmethod.println(" {");
335 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
336 if (state.DSM||state.SINGLETM) {
337 outmethod.print(" struct "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
339 outmethod.print(" struct "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
340 outmethod.println("1, NULL,"+"stringarray};");
341 if (state.DSM||state.SINGLETM)
342 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
344 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
346 if (state.DSM||state.SINGLETM)
347 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
349 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
351 outmethod.println(" }");
354 outmethod.println("}");
357 if (state.THREAD||state.DSM||state.SINGLETM) {
358 outmethod.println("pthread_mutex_lock(&gclistlock);");
359 outmethod.println("threadcount--;");
360 outmethod.println("pthread_cond_signal(&gccond);");
361 outmethod.println("pthread_mutex_unlock(&gclistlock);");
364 if (state.DSM||state.SINGLETM) {
365 outmethod.println("#ifdef TRANSSTATS \n");
366 outmethod.println("printf(\"****** Transaction Stats ******\\n\");");
367 outmethod.println("printf(\"numTransCommit= %d\\n\", numTransCommit);");
368 outmethod.println("printf(\"numTransAbort= %d\\n\", numTransAbort);");
369 outmethod.println("printf(\"nSoftAbort= %d\\n\", nSoftAbort);");
371 outmethod.println("printf(\"nchashSearch= %d\\n\", nchashSearch);");
372 outmethod.println("printf(\"nmhashSearch= %d\\n\", nmhashSearch);");
373 outmethod.println("printf(\"nprehashSearch= %d\\n\", nprehashSearch);");
374 outmethod.println("printf(\"nRemoteReadSend= %d\\n\", nRemoteSend);");
375 outmethod.println("printf(\"bytesSent= %d\\n\", bytesSent);");
376 outmethod.println("printf(\"bytesRecv= %d\\n\", bytesRecv);");
377 } else if (state.SINGLETM) {
378 outmethod.println("printf(\"nSoftAbortAbort= %d\\n\", nSoftAbortAbort);");
379 outmethod.println("printf(\"nSoftAbortCommit= %d\\n\", nSoftAbortCommit);");
380 outmethod.println("#ifdef STMSTATS\n");
381 outmethod.println("for(i=0; i<TOTALNUMCLASSANDARRAY; i++) {\n");
382 outmethod.println(" printf(\"typesCausingAbort[%2d] numaccess= %5d numabort= %3d\\n\", i, typesCausingAbort[i].numaccess, typesCausingAbort[i].numabort);\n");
383 outmethod.println("}\n");
384 outmethod.println("#endif\n");
385 outmethod.println("fflush(stdout);");
387 outmethod.println("#endif\n");
390 if (state.THREAD||state.SINGLETM)
391 outmethod.println("pthread_exit(NULL);");
394 outmethod.println(" workScheduleBegin();");
397 outmethod.println("}");
400 /* This method outputs code for each task. */
402 private void outputTaskCode(PrintWriter outtaskdefs, PrintWriter outmethod) {
403 /* Compile task based program */
404 outtaskdefs.println("#include \"task.h\"");
405 outtaskdefs.println("#include \"methodheaders.h\"");
406 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
407 while(taskit.hasNext()) {
408 TaskDescriptor td=(TaskDescriptor)taskit.next();
409 FlatMethod fm=state.getMethodFlat(td);
410 generateFlatMethod(fm, null, outmethod);
411 generateTaskDescriptor(outtaskdefs, fm, td);
414 //Output task descriptors
415 taskit=state.getTaskSymbolTable().getDescriptorsIterator();
416 outtaskdefs.println("struct taskdescriptor * taskarray[]= {");
418 while(taskit.hasNext()) {
419 TaskDescriptor td=(TaskDescriptor)taskit.next();
423 outtaskdefs.println(",");
424 outtaskdefs.print("&task_"+td.getSafeSymbol());
426 outtaskdefs.println("};");
428 outtaskdefs.println("int numtasks="+state.getTaskSymbolTable().getValueSet().size()+";");
431 /* This method outputs most of the methods.c file. This includes
432 * some standard includes and then an array with the sizes of
433 * objets and array that stores supertype and then the code for
434 * the Java methods.. */
436 protected void outputMethods(PrintWriter outmethod) {
437 outmethod.println("#include \"methodheaders.h\"");
438 outmethod.println("#include \"virtualtable.h\"");
439 outmethod.println("#include \"runtime.h\"");
441 outmethod.println("#include \"addPrefetchEnhance.h\"");
442 outmethod.println("#include \"localobjects.h\"");
444 if (state.FASTCHECK) {
445 outmethod.println("#include \"localobjects.h\"");
447 if(state.MULTICORE) {
448 outmethod.println("#include \"task.h\"");
449 outmethod.println("#include \"multicoreruntime.h\"");
450 outmethod.println("#include \"runtime_arch.h\"");
452 if (state.THREAD||state.DSM||state.SINGLETM)
453 outmethod.println("#include <thread.h>");
454 if (state.main!=null) {
455 outmethod.println("#include <string.h>");
457 if (state.CONSCHECK) {
458 outmethod.println("#include \"checkers.h\"");
461 outmethod.println("#include <stdlib.h>");
462 outmethod.println("#include <stdio.h>");
463 outmethod.println("#include \"mlp_runtime.h\"");
464 outmethod.println("#include \"psemaphore.h\"");
468 //Store the sizes of classes & array elements
469 generateSizeArray(outmethod);
471 //Store table of supertypes
472 generateSuperTypeTable(outmethod);
474 //Store the layout of classes
475 generateLayoutStructs(outmethod);
477 /* Generate code for methods */
478 if (state.DSM||state.SINGLETM) {
479 for(Iterator<LocalityBinding> lbit=locality.getLocalityBindings().iterator(); lbit.hasNext();) {
480 LocalityBinding lb=lbit.next();
481 MethodDescriptor md=lb.getMethod();
482 FlatMethod fm=state.getMethodFlat(md);
484 if (!md.getModifiers().isNative()) {
485 generateFlatMethod(fm, lb, outmethod);
489 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
490 while(classit.hasNext()) {
491 ClassDescriptor cn=(ClassDescriptor)classit.next();
492 Iterator methodit=cn.getMethods();
493 while(methodit.hasNext()) {
494 /* Classify parameters */
495 MethodDescriptor md=(MethodDescriptor)methodit.next();
496 FlatMethod fm=state.getMethodFlat(md);
497 if (!md.getModifiers().isNative()) {
498 generateFlatMethod(fm, null, outmethod);
505 protected void outputStructs(PrintWriter outstructs) {
506 outstructs.println("#ifndef STRUCTDEFS_H");
507 outstructs.println("#define STRUCTDEFS_H");
508 outstructs.println("#include \"classdefs.h\"");
509 outstructs.println("#ifndef INTPTR");
510 outstructs.println("#ifdef BIT64");
511 outstructs.println("#define INTPTR long");
512 outstructs.println("#else");
513 outstructs.println("#define INTPTR int");
514 outstructs.println("#endif");
515 outstructs.println("#endif");
517 outstructs.println("#include \"mlp_runtime.h\"");
518 outstructs.println("#include \"psemaphore.h\"");
521 /* Output #defines that the runtime uses to determine type
522 * numbers for various objects it needs */
523 outstructs.println("#define MAXCOUNT "+maxcount);
524 if (state.DSM||state.SINGLETM) {
525 LocalityBinding lb=new LocalityBinding(typeutil.getRun(), false);
527 lb.setGlobalThis(LocalityAnalysis.GLOBAL);
528 else if (state.SINGLETM)
529 lb.setGlobalThis(LocalityAnalysis.NORMAL);
530 outstructs.println("#define RUNMETHOD "+virtualcalls.getLocalityNumber(lb));
533 outstructs.println("#define STRINGARRAYTYPE "+
534 (state.getArrayNumber(
535 (new TypeDescriptor(typeutil.getClass(TypeUtil.StringClass))).makeArray(state))+state.numClasses()));
537 outstructs.println("#define OBJECTARRAYTYPE "+
538 (state.getArrayNumber(
539 (new TypeDescriptor(typeutil.getClass(TypeUtil.ObjectClass))).makeArray(state))+state.numClasses()));
542 outstructs.println("#define STRINGTYPE "+typeutil.getClass(TypeUtil.StringClass).getId());
543 outstructs.println("#define CHARARRAYTYPE "+
544 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.CHAR)).makeArray(state))+state.numClasses()));
546 outstructs.println("#define BYTEARRAYTYPE "+
547 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state))+state.numClasses()));
549 outstructs.println("#define BYTEARRAYARRAYTYPE "+
550 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state).makeArray(state))+state.numClasses()));
552 outstructs.println("#define NUMCLASSES "+state.numClasses());
553 int totalClassSize = state.numClasses() + state.numArrays();
554 outstructs.println("#define TOTALNUMCLASSANDARRAY "+ totalClassSize);
556 outstructs.println("#define STARTUPTYPE "+typeutil.getClass(TypeUtil.StartupClass).getId());
557 outstructs.println("#define TAGTYPE "+typeutil.getClass(TypeUtil.TagClass).getId());
558 outstructs.println("#define TAGARRAYTYPE "+
559 (state.getArrayNumber(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)).makeArray(state))+state.numClasses()));
563 protected void outputClassDeclarations(PrintWriter outclassdefs) {
564 if (state.THREAD||state.DSM||state.SINGLETM)
565 outclassdefs.println("#include <pthread.h>");
566 outclassdefs.println("#ifndef INTPTR");
567 outclassdefs.println("#ifdef BIT64");
568 outclassdefs.println("#define INTPTR long");
569 outclassdefs.println("#else");
570 outclassdefs.println("#define INTPTR int");
571 outclassdefs.println("#endif");
572 outclassdefs.println("#endif");
574 outclassdefs.println("#include \"optionalstruct.h\"");
575 outclassdefs.println("struct "+arraytype+";");
576 /* Start by declaring all structs */
577 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
578 while(it.hasNext()) {
579 ClassDescriptor cn=(ClassDescriptor)it.next();
580 outclassdefs.println("struct "+cn.getSafeSymbol()+";");
582 outclassdefs.println("");
583 //Print out definition for array type
584 outclassdefs.println("struct "+arraytype+" {");
585 outclassdefs.println(" int type;");
587 outclassdefs.println(" pthread_t tid;");
588 outclassdefs.println(" void * lockentry;");
589 outclassdefs.println(" int lockcount;");
592 outclassdefs.println(" int flag;");
593 if(!state.MULTICORE) {
594 outclassdefs.println(" void * flagptr;");
596 outclassdefs.println(" int version;");
597 outclassdefs.println(" int * lock;"); // lock entry for this obj
598 outclassdefs.println(" int mutex;");
599 outclassdefs.println(" int lockcount;");
600 if(state.MULTICOREGC) {
601 outclassdefs.println(" int marked;");
605 outclassdefs.println(" int numfses;");
606 outclassdefs.println(" int * fses;");
609 printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs);
612 outclassdefs.println(" int paddingforarray;");
614 outclassdefs.println(" int ___length___;");
615 outclassdefs.println("};\n");
616 outclassdefs.println("extern int classsize[];");
617 outclassdefs.println("extern int hasflags[];");
618 outclassdefs.println("extern unsigned INTPTR * pointerarray[];");
619 outclassdefs.println("extern int supertypes[];");
622 /** Prints out definitions for generic task structures */
624 private void outputTaskTypes(PrintWriter outtask) {
625 outtask.println("#ifndef _TASK_H");
626 outtask.println("#define _TASK_H");
627 outtask.println("struct parameterdescriptor {");
628 outtask.println("int type;");
629 outtask.println("int numberterms;");
630 outtask.println("int *intarray;");
631 outtask.println("void * queue;");
632 outtask.println("int numbertags;");
633 outtask.println("int *tagarray;");
634 outtask.println("};");
636 outtask.println("struct taskdescriptor {");
637 outtask.println("void * taskptr;");
638 outtask.println("int numParameters;");
639 outtask.println(" int numTotal;");
640 outtask.println("struct parameterdescriptor **descriptorarray;");
641 outtask.println("char * name;");
642 outtask.println("};");
643 outtask.println("extern struct taskdescriptor * taskarray[];");
644 outtask.println("extern numtasks;");
645 outtask.println("#endif");
649 private void buildRepairStructs(PrintWriter outrepairstructs) {
650 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
651 while(classit.hasNext()) {
652 ClassDescriptor cn=(ClassDescriptor)classit.next();
653 outrepairstructs.println("structure "+cn.getSymbol()+" {");
654 outrepairstructs.println(" int __type__;");
656 outrepairstructs.println(" int __flag__;");
657 if(!state.MULTICORE) {
658 outrepairstructs.println(" int __flagptr__;");
661 printRepairStruct(cn, outrepairstructs);
662 outrepairstructs.println("}\n");
665 for(int i=0; i<state.numArrays(); i++) {
666 TypeDescriptor tdarray=arraytable[i];
667 TypeDescriptor tdelement=tdarray.dereference();
668 outrepairstructs.println("structure "+arraytype+"_"+state.getArrayNumber(tdarray)+" {");
669 outrepairstructs.println(" int __type__;");
670 printRepairStruct(typeutil.getClass(TypeUtil.ObjectClass), outrepairstructs);
671 outrepairstructs.println(" int length;");
673 // Need to add support to repair tool for this
674 if (tdelement.isClass()||tdelement.isArray())
675 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" * elem[this.length];");
677 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" elem[this.length];");
679 outrepairstructs.println("}\n");
683 private void printRepairStruct(ClassDescriptor cn, PrintWriter output) {
684 ClassDescriptor sp=cn.getSuperDesc();
686 printRepairStruct(sp, output);
688 Vector fields=(Vector)fieldorder.get(cn);
690 for(int i=0; i<fields.size(); i++) {
691 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
692 if (fd.getType().isArray()) {
693 output.println(" "+arraytype+"_"+ state.getArrayNumber(fd.getType()) +" * "+fd.getSymbol()+";");
694 } else if (fd.getType().isClass())
695 output.println(" "+fd.getType().getRepairSymbol()+" * "+fd.getSymbol()+";");
696 else if (fd.getType().isFloat())
697 output.println(" int "+fd.getSymbol()+"; /* really float */");
699 output.println(" "+fd.getType().getRepairSymbol()+" "+fd.getSymbol()+";");
703 /** This method outputs TaskDescriptor information */
704 private void generateTaskDescriptor(PrintWriter output, FlatMethod fm, TaskDescriptor task) {
705 for (int i=0; i<task.numParameters(); i++) {
706 VarDescriptor param_var=task.getParameter(i);
707 TypeDescriptor param_type=task.getParamType(i);
708 FlagExpressionNode param_flag=task.getFlag(param_var);
709 TagExpressionList param_tag=task.getTag(param_var);
712 if (param_flag==null) {
713 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
714 output.println("0x0, 0x0 };");
717 DNFFlag dflag=param_flag.getDNF();
718 dnfterms=dflag.size();
720 Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
721 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
722 for(int j=0; j<dflag.size(); j++) {
725 Vector term=dflag.get(j);
728 for(int k=0; k<term.size(); k++) {
729 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
730 FlagDescriptor fd=dfa.getFlag();
731 boolean negated=dfa.getNegated();
732 int flagid=1<<((Integer)flags.get(fd)).intValue();
737 output.print("0x"+Integer.toHexString(andmask)+", 0x"+Integer.toHexString(checkmask));
739 output.println("};");
742 output.println("int parametertag_"+i+"_"+task.getSafeSymbol()+"[]={");
743 //BUG...added next line to fix, test with any task program
745 for(int j=0; j<param_tag.numTags(); j++) {
748 /* for each tag we need */
749 /* which slot it is */
750 /* what type it is */
751 TagVarDescriptor tvd=(TagVarDescriptor)task.getParameterTable().get(param_tag.getName(j));
752 TempDescriptor tmp=param_tag.getTemp(j);
753 int slot=fm.getTagInt(tmp);
754 output.println(slot+", "+state.getTagId(tvd.getTag()));
756 output.println("};");
758 output.println("struct parameterdescriptor parameter_"+i+"_"+task.getSafeSymbol()+"={");
759 output.println("/* type */"+param_type.getClassDesc().getId()+",");
760 output.println("/* number of DNF terms */"+dnfterms+",");
761 output.println("parameterdnf_"+i+"_"+task.getSafeSymbol()+",");
762 output.println("0,");
763 //BUG, added next line to fix and else statement...test
764 //with any task program
766 output.println("/* number of tags */"+param_tag.numTags()+",");
768 output.println("/* number of tags */ 0,");
769 output.println("parametertag_"+i+"_"+task.getSafeSymbol());
770 output.println("};");
774 output.println("struct parameterdescriptor * parameterdescriptors_"+task.getSafeSymbol()+"[] = {");
775 for (int i=0; i<task.numParameters(); i++) {
778 output.print("¶meter_"+i+"_"+task.getSafeSymbol());
780 output.println("};");
782 output.println("struct taskdescriptor task_"+task.getSafeSymbol()+"={");
783 output.println("&"+task.getSafeSymbol()+",");
784 output.println("/* number of parameters */" +task.numParameters() + ",");
785 int numtotal=task.numParameters()+fm.numTags();
786 output.println("/* number total parameters */" +numtotal + ",");
787 output.println("parameterdescriptors_"+task.getSafeSymbol()+",");
788 output.println("\""+task.getSymbol()+"\"");
789 output.println("};");
793 /** The buildVirtualTables method outputs the virtual dispatch
794 * tables for methods. */
796 protected void buildVirtualTables(PrintWriter outvirtual) {
797 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
798 while(classit.hasNext()) {
799 ClassDescriptor cd=(ClassDescriptor)classit.next();
800 if (virtualcalls.getMethodCount(cd)>maxcount)
801 maxcount=virtualcalls.getMethodCount(cd);
803 MethodDescriptor[][] virtualtable=null;
804 LocalityBinding[][] lbvirtualtable=null;
805 if (state.DSM||state.SINGLETM)
806 lbvirtualtable=new LocalityBinding[state.numClasses()+state.numArrays()][maxcount];
808 virtualtable=new MethodDescriptor[state.numClasses()+state.numArrays()][maxcount];
810 /* Fill in virtual table */
811 classit=state.getClassSymbolTable().getDescriptorsIterator();
812 while(classit.hasNext()) {
813 ClassDescriptor cd=(ClassDescriptor)classit.next();
814 if (state.DSM||state.SINGLETM)
815 fillinRow(cd, lbvirtualtable, cd.getId());
817 fillinRow(cd, virtualtable, cd.getId());
820 ClassDescriptor objectcd=typeutil.getClass(TypeUtil.ObjectClass);
821 Iterator arrayit=state.getArrayIterator();
822 while(arrayit.hasNext()) {
823 TypeDescriptor td=(TypeDescriptor)arrayit.next();
824 int id=state.getArrayNumber(td);
825 if (state.DSM||state.SINGLETM)
826 fillinRow(objectcd, lbvirtualtable, id+state.numClasses());
828 fillinRow(objectcd, virtualtable, id+state.numClasses());
831 outvirtual.print("void * virtualtable[]={");
832 boolean needcomma=false;
833 for(int i=0; i<state.numClasses()+state.numArrays(); i++) {
834 for(int j=0; j<maxcount; j++) {
836 outvirtual.print(", ");
837 if ((state.DSM||state.SINGLETM)&&lbvirtualtable[i][j]!=null) {
838 LocalityBinding lb=lbvirtualtable[i][j];
839 MethodDescriptor md=lb.getMethod();
840 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
841 } else if (!(state.DSM||state.SINGLETM)&&virtualtable[i][j]!=null) {
842 MethodDescriptor md=virtualtable[i][j];
843 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
845 outvirtual.print("0");
849 outvirtual.println("");
851 outvirtual.println("};");
855 private void fillinRow(ClassDescriptor cd, MethodDescriptor[][] virtualtable, int rownum) {
856 /* Get inherited methods */
857 if (cd.getSuperDesc()!=null)
858 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
859 /* Override them with our methods */
860 for(Iterator it=cd.getMethods(); it.hasNext();) {
861 MethodDescriptor md=(MethodDescriptor)it.next();
862 if (md.isStatic()||md.getReturnType()==null)
864 int methodnum=virtualcalls.getMethodNumber(md);
865 virtualtable[rownum][methodnum]=md;
869 private void fillinRow(ClassDescriptor cd, LocalityBinding[][] virtualtable, int rownum) {
870 /* Get inherited methods */
871 if (cd.getSuperDesc()!=null)
872 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
873 /* Override them with our methods */
874 if (locality.getClassBindings(cd)!=null)
875 for(Iterator<LocalityBinding> lbit=locality.getClassBindings(cd).iterator(); lbit.hasNext();) {
876 LocalityBinding lb=lbit.next();
877 MethodDescriptor md=lb.getMethod();
878 //Is the method static or a constructor
879 if (md.isStatic()||md.getReturnType()==null)
881 int methodnum=virtualcalls.getLocalityNumber(lb);
882 virtualtable[rownum][methodnum]=lb;
886 /** Generate array that contains the sizes of class objects. The
887 * object allocation functions in the runtime use this
890 private void generateSizeArray(PrintWriter outclassdefs) {
891 outclassdefs.print("extern struct prefetchCountStats * evalPrefetch;\n");
892 outclassdefs.print("#ifdef TRANSSTATS \n");
893 outclassdefs.print("extern int numTransAbort;\n");
894 outclassdefs.print("extern int numTransCommit;\n");
895 outclassdefs.print("extern int nSoftAbort;\n");
897 outclassdefs.print("extern int nchashSearch;\n");
898 outclassdefs.print("extern int nmhashSearch;\n");
899 outclassdefs.print("extern int nprehashSearch;\n");
900 outclassdefs.print("extern int nRemoteSend;\n");
901 outclassdefs.print("extern int bytesSent;\n");
902 outclassdefs.print("extern int bytesRecv;\n");
903 outclassdefs.print("extern void handle();\n");
904 } else if (state.SINGLETM) {
905 outclassdefs.println("extern int nSoftAbortAbort;");
906 outclassdefs.println("extern int nSoftAbortCommit;");
907 outclassdefs.println("#ifdef STMSTATS\n");
908 outclassdefs.println("extern objtypestat_t typesCausingAbort[];");
909 outclassdefs.println("#endif\n");
911 outclassdefs.print("#endif\n");
912 outclassdefs.print("int numprefetchsites = " + pa.prefetchsiteid + ";\n");
914 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
915 cdarray=new ClassDescriptor[state.numClasses()];
916 while(it.hasNext()) {
917 ClassDescriptor cd=(ClassDescriptor)it.next();
918 cdarray[cd.getId()]=cd;
921 arraytable=new TypeDescriptor[state.numArrays()];
923 Iterator arrayit=state.getArrayIterator();
924 while(arrayit.hasNext()) {
925 TypeDescriptor td=(TypeDescriptor)arrayit.next();
926 int id=state.getArrayNumber(td);
932 /* Print out types */
933 outclassdefs.println("/* ");
934 for(int i=0; i<state.numClasses(); i++) {
935 ClassDescriptor cd=cdarray[i];
936 outclassdefs.println(cd +" "+i);
939 for(int i=0; i<state.numArrays(); i++) {
940 TypeDescriptor arraytd=arraytable[i];
941 outclassdefs.println(arraytd.toPrettyString() +" "+(i+state.numClasses()));
944 outclassdefs.println("*/");
947 outclassdefs.print("int classsize[]={");
949 boolean needcomma=false;
950 for(int i=0; i<state.numClasses(); i++) {
952 outclassdefs.print(", ");
953 outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")");
958 for(int i=0; i<state.numArrays(); i++) {
960 outclassdefs.print(", ");
961 TypeDescriptor tdelement=arraytable[i].dereference();
962 if (tdelement.isArray()||tdelement.isClass())
963 outclassdefs.print("sizeof(void *)");
965 outclassdefs.print("sizeof("+tdelement.getSafeSymbol()+")");
969 outclassdefs.println("};");
971 ClassDescriptor objectclass=typeutil.getClass(TypeUtil.ObjectClass);
973 outclassdefs.print("int typearray[]={");
974 for(int i=0; i<state.numClasses(); i++) {
975 ClassDescriptor cd=cdarray[i];
976 ClassDescriptor supercd=cd.getSuperDesc();
978 outclassdefs.print(", ");
980 outclassdefs.print("-1");
982 outclassdefs.print(supercd.getId());
986 for(int i=0; i<state.numArrays(); i++) {
987 TypeDescriptor arraytd=arraytable[i];
988 ClassDescriptor arraycd=arraytd.getClassDesc();
991 outclassdefs.print(", ");
992 outclassdefs.print(objectclass.getId());
996 ClassDescriptor cd=arraycd.getSuperDesc();
999 TypeDescriptor supertd=new TypeDescriptor(cd);
1000 supertd.setArrayCount(arraytd.getArrayCount());
1001 type=state.getArrayNumber(supertd);
1003 type+=state.numClasses();
1006 cd=cd.getSuperDesc();
1009 outclassdefs.print(", ");
1010 outclassdefs.print(type);
1014 outclassdefs.println("};");
1019 outclassdefs.print("int typearray2[]={");
1020 for(int i=0; i<state.numArrays(); i++) {
1021 TypeDescriptor arraytd=arraytable[i];
1022 ClassDescriptor arraycd=arraytd.getClassDesc();
1023 if (arraycd==null) {
1025 outclassdefs.print(", ");
1026 outclassdefs.print("-1");
1030 ClassDescriptor cd=arraycd.getSuperDesc();
1031 int level=arraytd.getArrayCount()-1;
1033 for(; level>0; level--) {
1034 TypeDescriptor supertd=new TypeDescriptor(objectclass);
1035 supertd.setArrayCount(level);
1036 type=state.getArrayNumber(supertd);
1038 type+=state.numClasses();
1043 outclassdefs.print(", ");
1044 outclassdefs.print(type);
1048 outclassdefs.println("};");
1051 /** Constructs params and temp objects for each method or task.
1052 * These objects tell the compiler which temps need to be
1055 protected void generateTempStructs(FlatMethod fm, LocalityBinding lb) {
1056 MethodDescriptor md=fm.getMethod();
1057 TaskDescriptor task=fm.getTask();
1058 Set<TempDescriptor> saveset=lb!=null ? locality.getTempSet(lb) : null;
1059 ParamsObject objectparams=md!=null ? new ParamsObject(md,tag++) : new ParamsObject(task, tag++);
1061 paramstable.put(lb, objectparams);
1062 backuptable.put(lb, new Hashtable<TempDescriptor, TempDescriptor>());
1063 } else if (md!=null)
1064 paramstable.put(md, objectparams);
1066 paramstable.put(task, objectparams);
1068 for(int i=0; i<fm.numParameters(); i++) {
1069 TempDescriptor temp=fm.getParameter(i);
1070 TypeDescriptor type=temp.getType();
1071 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1072 objectparams.addPtr(temp);
1074 objectparams.addPrim(temp);
1075 if(lb!=null&&saveset.contains(temp)) {
1076 backuptable.get(lb).put(temp, temp.createNew());
1080 for(int i=0; i<fm.numTags(); i++) {
1081 TempDescriptor temp=fm.getTag(i);
1082 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1083 objectparams.addPtr(temp);
1085 objectparams.addPrim(temp);
1088 TempObject objecttemps=md!=null ? new TempObject(objectparams,md,tag++) : new TempObject(objectparams, task, tag++);
1090 tempstable.put(lb, objecttemps);
1092 tempstable.put(md, objecttemps);
1094 tempstable.put(task, objecttemps);
1096 for(Iterator nodeit=fm.getNodeSet().iterator(); nodeit.hasNext();) {
1097 FlatNode fn=(FlatNode)nodeit.next();
1098 TempDescriptor[] writes=fn.writesTemps();
1099 for(int i=0; i<writes.length; i++) {
1100 TempDescriptor temp=writes[i];
1101 TypeDescriptor type=temp.getType();
1102 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1103 objecttemps.addPtr(temp);
1105 objecttemps.addPrim(temp);
1106 if(lb!=null&&saveset.contains(temp)&&
1107 !backuptable.get(lb).containsKey(temp))
1108 backuptable.get(lb).put(temp, temp.createNew());
1112 /* Create backup temps */
1114 for(Iterator<TempDescriptor> tmpit=backuptable.get(lb).values().iterator(); tmpit.hasNext();) {
1115 TempDescriptor tmp=tmpit.next();
1116 TypeDescriptor type=tmp.getType();
1117 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1118 objecttemps.addPtr(tmp);
1120 objecttemps.addPrim(tmp);
1122 /* Create temp to hold revert table */
1123 if (state.DSM&&(lb.getHasAtomic()||lb.isAtomic())) {
1124 TempDescriptor reverttmp=new TempDescriptor("revertlist", typeutil.getClass(TypeUtil.ObjectClass));
1125 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1126 objecttemps.addPtr(reverttmp);
1128 objecttemps.addPrim(reverttmp);
1129 reverttable.put(lb, reverttmp);
1134 /** This method outputs the following information about classes
1136 * (1) For classes, what are the locations of pointers.
1137 * (2) For arrays, does the array contain pointers or primitives.
1138 * (3) For classes, does the class contain flags.
1141 private void generateLayoutStructs(PrintWriter output) {
1142 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1143 while(it.hasNext()) {
1144 ClassDescriptor cn=(ClassDescriptor)it.next();
1145 output.println("unsigned INTPTR "+cn.getSafeSymbol()+"_pointers[]={");
1146 Iterator allit=cn.getFieldTable().getAllDescriptorsIterator();
1148 while(allit.hasNext()) {
1149 FieldDescriptor fd=(FieldDescriptor)allit.next();
1150 TypeDescriptor type=fd.getType();
1151 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1156 output.print(count);
1157 allit=cn.getFieldTable().getAllDescriptorsIterator();
1158 while(allit.hasNext()) {
1159 FieldDescriptor fd=(FieldDescriptor)allit.next();
1160 TypeDescriptor type=fd.getType();
1161 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1164 output.println(",");
1165 output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+fd.getSafeSymbol()+"))");
1168 output.println("};");
1170 output.println("unsigned INTPTR * pointerarray[]={");
1171 boolean needcomma=false;
1172 for(int i=0; i<state.numClasses(); i++) {
1173 ClassDescriptor cn=cdarray[i];
1175 output.println(",");
1177 output.print(cn.getSafeSymbol()+"_pointers");
1180 for(int i=0; i<state.numArrays(); i++) {
1182 output.println(", ");
1183 TypeDescriptor tdelement=arraytable[i].dereference();
1184 if (tdelement.isArray()||tdelement.isClass())
1185 output.print("((unsigned INTPTR *)1)");
1191 output.println("};");
1193 output.println("int hasflags[]={");
1194 for(int i=0; i<state.numClasses(); i++) {
1195 ClassDescriptor cn=cdarray[i];
1197 output.println(", ");
1204 output.println("};");
1207 /** Print out table to give us supertypes */
1208 private void generateSuperTypeTable(PrintWriter output) {
1209 output.println("int supertypes[]={");
1210 boolean needcomma=false;
1211 for(int i=0; i<state.numClasses(); i++) {
1212 ClassDescriptor cn=cdarray[i];
1214 output.println(",");
1216 if (cn.getSuperDesc()!=null) {
1217 ClassDescriptor cdsuper=cn.getSuperDesc();
1218 output.print(cdsuper.getId());
1222 output.println("};");
1225 /** Force consistent field ordering between inherited classes. */
1227 private void printClassStruct(ClassDescriptor cn, PrintWriter classdefout) {
1229 ClassDescriptor sp=cn.getSuperDesc();
1231 printClassStruct(sp, classdefout);
1233 if (!fieldorder.containsKey(cn)) {
1234 Vector fields=new Vector();
1235 fieldorder.put(cn,fields);
1236 Vector fieldvec=cn.getFieldVec();
1237 for(int i=0;i<fieldvec.size();i++) {
1238 FieldDescriptor fd=(FieldDescriptor)fieldvec.get(i);
1239 if ((sp==null||!sp.getFieldTable().contains(fd.getSymbol())))
1243 Vector fields=(Vector)fieldorder.get(cn);
1245 for(int i=0; i<fields.size(); i++) {
1246 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
1247 if (fd.getType().isClass()||fd.getType().isArray())
1248 classdefout.println(" struct "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1250 classdefout.println(" "+fd.getType().getSafeSymbol()+" "+fd.getSafeSymbol()+";");
1255 /* Map flags to integers consistently between inherited
1258 protected void mapFlags(ClassDescriptor cn) {
1259 ClassDescriptor sp=cn.getSuperDesc();
1263 if (!flagorder.containsKey(cn)) {
1264 Hashtable flags=new Hashtable();
1265 flagorder.put(cn,flags);
1267 Hashtable superflags=(Hashtable)flagorder.get(sp);
1268 Iterator superflagit=superflags.keySet().iterator();
1269 while(superflagit.hasNext()) {
1270 FlagDescriptor fd=(FlagDescriptor)superflagit.next();
1271 Integer number=(Integer)superflags.get(fd);
1272 flags.put(fd, number);
1273 if ((number.intValue()+1)>max)
1274 max=number.intValue()+1;
1278 Iterator flagit=cn.getFlags();
1279 while(flagit.hasNext()) {
1280 FlagDescriptor fd=(FlagDescriptor)flagit.next();
1281 if (sp==null||!sp.getFlagTable().contains(fd.getSymbol()))
1282 flags.put(fd, new Integer(max++));
1288 /** This function outputs (1) structures that parameters are
1289 * passed in (when PRECISE GC is enabled) and (2) function
1290 * prototypes for the methods */
1292 protected void generateCallStructs(ClassDescriptor cn, PrintWriter classdefout, PrintWriter output, PrintWriter headersout) {
1293 /* Output class structure */
1294 classdefout.println("struct "+cn.getSafeSymbol()+" {");
1295 classdefout.println(" int type;");
1297 classdefout.println(" pthread_t tid;");
1298 classdefout.println(" void * lockentry;");
1299 classdefout.println(" int lockcount;");
1303 classdefout.println(" int flag;");
1304 if((!state.MULTICORE) || (cn.getSymbol().equals("TagDescriptor"))) {
1305 classdefout.println(" void * flagptr;");
1306 } else if (state.MULTICORE) {
1307 classdefout.println(" int version;");
1308 classdefout.println(" int * lock;"); // lock entry for this obj
1309 classdefout.println(" int mutex;");
1310 classdefout.println(" int lockcount;");
1311 if(state.MULTICOREGC) {
1312 classdefout.println(" int marked;");
1315 if (state.OPTIONAL) {
1316 classdefout.println(" int numfses;");
1317 classdefout.println(" int * fses;");
1320 printClassStruct(cn, classdefout);
1321 classdefout.println("};\n");
1323 if (state.DSM||state.SINGLETM) {
1324 /* Cycle through LocalityBindings */
1325 HashSet<MethodDescriptor> nativemethods=new HashSet<MethodDescriptor>();
1326 Set<LocalityBinding> lbset=locality.getClassBindings(cn);
1328 for(Iterator<LocalityBinding> lbit=lbset.iterator(); lbit.hasNext();) {
1329 LocalityBinding lb=lbit.next();
1330 MethodDescriptor md=lb.getMethod();
1331 if (md.getModifiers().isNative()) {
1332 //make sure we only print a native method once
1333 if (nativemethods.contains(md)) {
1334 FlatMethod fm=state.getMethodFlat(md);
1335 generateTempStructs(fm, lb);
1338 nativemethods.add(md);
1340 generateMethod(cn, md, lb, headersout, output);
1343 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1344 MethodDescriptor md=(MethodDescriptor)methodit.next();
1345 if (md.getModifiers().isNative()&&!nativemethods.contains(md)) {
1346 //Need to build param structure for library code
1347 FlatMethod fm=state.getMethodFlat(md);
1348 generateTempStructs(fm, null);
1349 generateMethodParam(cn, md, null, output);
1354 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1355 MethodDescriptor md=(MethodDescriptor)methodit.next();
1356 generateMethod(cn, md, null, headersout, output);
1360 private void generateMethodParam(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter output) {
1361 /* Output parameter structure */
1362 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1363 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1364 if ((state.DSM||state.SINGLETM)&&lb!=null)
1365 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1367 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1368 output.println(" INTPTR size;");
1369 output.println(" void * next;");
1370 for(int i=0; i<objectparams.numPointers(); i++) {
1371 TempDescriptor temp=objectparams.getPointer(i);
1372 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1374 output.println("};\n");
1378 private void generateMethod(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter headersout, PrintWriter output) {
1379 FlatMethod fm=state.getMethodFlat(md);
1380 generateTempStructs(fm, lb);
1382 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1383 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md);
1385 generateMethodParam(cn, md, lb, output);
1387 /* Output temp structure */
1388 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1389 if (state.DSM||state.SINGLETM)
1390 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1392 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1393 output.println(" INTPTR size;");
1394 output.println(" void * next;");
1395 for(int i=0; i<objecttemps.numPointers(); i++) {
1396 TempDescriptor temp=objecttemps.getPointer(i);
1397 if (temp.getType().isNull())
1398 output.println(" void * "+temp.getSafeSymbol()+";");
1400 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1402 output.println("};\n");
1405 /********* Output method declaration ***********/
1406 if (state.DSM||state.SINGLETM) {
1407 headersout.println("#define D"+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1409 headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1411 /* First the return type */
1412 if (md.getReturnType()!=null) {
1413 if (md.getReturnType().isClass()||md.getReturnType().isArray())
1414 headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1416 headersout.print(md.getReturnType().getSafeSymbol()+" ");
1418 //catch the constructor case
1419 headersout.print("void ");
1421 /* Next the method name */
1422 if (state.DSM||state.SINGLETM) {
1423 headersout.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1425 headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1427 boolean printcomma=false;
1428 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1429 if (state.DSM||state.SINGLETM) {
1430 headersout.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1432 headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1436 /* Output parameter list*/
1437 for(int i=0; i<objectparams.numPrimitives(); i++) {
1438 TempDescriptor temp=objectparams.getPrimitive(i);
1440 headersout.print(", ");
1442 if (temp.getType().isClass()||temp.getType().isArray())
1443 headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1445 headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1447 headersout.println(");\n");
1451 /** This function outputs (1) structures that parameters are
1452 * passed in (when PRECISE GC is enabled) and (2) function
1453 * prototypes for the tasks */
1455 private void generateTaskStructs(PrintWriter output, PrintWriter headersout) {
1456 /* Cycle through tasks */
1457 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
1459 while(taskit.hasNext()) {
1460 /* Classify parameters */
1461 TaskDescriptor task=(TaskDescriptor)taskit.next();
1462 FlatMethod fm=state.getMethodFlat(task);
1463 generateTempStructs(fm, null);
1465 ParamsObject objectparams=(ParamsObject) paramstable.get(task);
1466 TempObject objecttemps=(TempObject) tempstable.get(task);
1468 /* Output parameter structure */
1469 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1470 output.println("struct "+task.getSafeSymbol()+"_params {");
1472 output.println(" INTPTR size;");
1473 output.println(" void * next;");
1474 for(int i=0; i<objectparams.numPointers(); i++) {
1475 TempDescriptor temp=objectparams.getPointer(i);
1476 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1479 output.println("};\n");
1480 if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
1481 maxtaskparams=objectparams.numPointers()+fm.numTags();
1485 /* Output temp structure */
1486 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1487 output.println("struct "+task.getSafeSymbol()+"_locals {");
1488 output.println(" INTPTR size;");
1489 output.println(" void * next;");
1490 for(int i=0; i<objecttemps.numPointers(); i++) {
1491 TempDescriptor temp=objecttemps.getPointer(i);
1492 if (temp.getType().isNull())
1493 output.println(" void * "+temp.getSafeSymbol()+";");
1494 else if(temp.getType().isTag())
1495 output.println(" struct "+
1496 (new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1498 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1500 output.println("};\n");
1503 /* Output task declaration */
1504 headersout.print("void " + task.getSafeSymbol()+"(");
1506 boolean printcomma=false;
1507 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1508 headersout.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
1510 headersout.print("void * parameterarray[]");
1511 headersout.println(");\n");
1515 /***** Generate code for FlatMethod fm. *****/
1517 Hashtable<FlatAtomicEnterNode, AtomicRecord> atomicmethodmap;
1518 static int atomicmethodcount=0;
1520 private void generateFlatMethod(FlatMethod fm, LocalityBinding lb, PrintWriter output) {
1521 if (State.PRINTFLAT)
1522 System.out.println(fm.printMethod());
1523 MethodDescriptor md=fm.getMethod();
1524 TaskDescriptor task=fm.getTask();
1525 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
1526 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : md!=null ? md : task);
1528 HashSet<AtomicRecord> arset=null;
1530 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1532 if (atomicmethodmap==null)
1533 atomicmethodmap=new Hashtable<FlatAtomicEnterNode, AtomicRecord>();
1535 //fix these so we get right strings for local variables
1536 localsprefixaddr=localsprefix;
1537 localsprefixderef=localsprefix+"->";
1538 arset=new HashSet<AtomicRecord>();
1540 //Generate commit methods here
1541 for(Iterator<FlatNode> fnit=fm.getNodeSet().iterator();fnit.hasNext();) {
1542 FlatNode fn=fnit.next();
1543 if (fn.kind()==FKind.FlatAtomicEnterNode&&
1544 locality.getAtomic(lb).get(fn.getPrev(0)).intValue()==0) {
1545 //We have an atomic enter
1546 FlatAtomicEnterNode faen=(FlatAtomicEnterNode) fn;
1547 Set<FlatNode> exitset=faen.getExits();
1549 String methodname=md.getSymbol()+(atomicmethodcount++);
1550 AtomicRecord ar=new AtomicRecord();
1554 atomicmethodmap.put(faen, ar);
1556 //build data structure declaration
1557 output.println("struct atomicprimitives_"+methodname+" {");
1559 Set<FlatNode> recordset=delaycomp.livecode(lb);
1560 Set<TempDescriptor> liveinto=delaycomp.liveinto(lb, faen, recordset);
1561 Set<TempDescriptor> liveout=delaycomp.liveout(lb, faen);
1562 Set<TempDescriptor> liveoutvirtualread=delaycomp.liveoutvirtualread(lb, faen);
1564 ar.reallivein=new HashSet(liveinto);
1566 ar.liveoutvirtualread=liveoutvirtualread;
1568 for(Iterator<TempDescriptor> it=liveinto.iterator(); it.hasNext();) {
1569 TempDescriptor tmp=it.next();
1570 //remove the pointers
1571 if (tmp.getType().isPtr()) {
1574 //let's print it here
1575 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1578 for(Iterator<TempDescriptor> it=liveout.iterator(); it.hasNext();) {
1579 TempDescriptor tmp=it.next();
1580 //remove the pointers
1581 if (tmp.getType().isPtr()) {
1583 } else if (!liveinto.contains(tmp)) {
1584 //let's print it here
1585 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1588 output.println("};");
1590 //print out method name
1591 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) {");
1592 //build code for commit method
1594 //first define local primitives
1595 Set<TempDescriptor> alltemps=delaycomp.alltemps(lb, faen, recordset);
1596 for(Iterator<TempDescriptor> tmpit=alltemps.iterator();tmpit.hasNext();) {
1597 TempDescriptor tmp=tmpit.next();
1598 if (!tmp.getType().isPtr()) {
1599 if (liveinto.contains(tmp)||liveoutvirtualread.contains(tmp)) {
1600 //read from live into set
1601 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+"=primitives->"+tmp.getSafeSymbol()+";");
1604 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1608 //turn off write barrier generation
1610 state.SINGLETM=false;
1611 generateCode(faen, fm, lb, exitset, output, false);
1612 state.SINGLETM=true;
1613 //turn on write barrier generation
1615 output.println("}\n\n");
1619 //redefine these back to normal
1621 localsprefixaddr="&"+localsprefix;
1622 localsprefixderef=localsprefix+".";
1624 generateHeader(fm, lb, md!=null ? md : task,output);
1625 TempObject objecttemp=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
1627 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1628 for(Iterator<AtomicRecord> arit=arset.iterator();arit.hasNext();) {
1629 AtomicRecord ar=arit.next();
1630 output.println("struct atomicprimitives_"+ar.name+" primitives_"+ar.name+";");
1634 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1635 if (md!=null&&(state.DSM||state.SINGLETM))
1636 output.print(" struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1637 else if (md!=null&&!(state.DSM||state.SINGLETM))
1638 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1640 output.print(" struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={");
1642 output.print(objecttemp.numPointers()+",");
1643 output.print(paramsprefix);
1644 for(int j=0; j<objecttemp.numPointers(); j++)
1645 output.print(", NULL");
1646 output.println("};");
1649 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1650 TempDescriptor td=objecttemp.getPrimitive(i);
1651 TypeDescriptor type=td.getType();
1653 output.println(" void * "+td.getSafeSymbol()+";");
1654 else if (type.isClass()||type.isArray())
1655 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1657 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1662 if( fm.getNext(0) instanceof FlatSESEEnterNode ) {
1663 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
1664 if( callerSESEplaceholder != mlpa.getMainSESE() ) {
1665 // declare variables for naming static SESE's
1666 output.println(" /* static SESE names */");
1667 Iterator<SESEandAgePair> pItr = callerSESEplaceholder.getNeededStaticNames().iterator();
1668 while( pItr.hasNext() ) {
1669 SESEandAgePair p = pItr.next();
1670 output.println(" void* "+p+";");
1673 // declare variables for tracking dynamic sources
1674 output.println(" /* dynamic variable sources */");
1675 Iterator<TempDescriptor> dynSrcItr = callerSESEplaceholder.getDynamicVarSet().iterator();
1676 while( dynSrcItr.hasNext() ) {
1677 TempDescriptor dynSrcVar = dynSrcItr.next();
1678 output.println(" void* "+dynSrcVar+"_srcSESE;");
1679 output.println(" int "+dynSrcVar+"_srcOffset;");
1686 /* Check to see if we need to do a GC if this is a
1687 * multi-threaded program...*/
1689 if (((state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
1690 || this.state.MULTICOREGC) {
1691 //Don't bother if we aren't in recursive methods...The loops case will catch it
1692 if (callgraph.getAllMethods(md).contains(md)) {
1693 if (state.DSM&&lb.isAtomic())
1694 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
1695 else if (this.state.MULTICOREGC) {
1696 output.println("if(gcflag) gc("+localsprefixaddr+");");
1698 output.println("if (needtocollect) checkcollect("+localsprefixaddr+");");
1702 generateCode(fm.getNext(0), fm, lb, null, output, true);
1704 output.println("}\n\n");
1708 protected void initializeSESE( FlatSESEEnterNode fsen ) {
1710 FlatMethod fm = fsen.getfmEnclosing();
1711 MethodDescriptor md = fm.getMethod();
1712 ClassDescriptor cn = md.getClassDesc();
1715 // Creates bogus method descriptor to index into tables
1716 Modifiers modBogus = new Modifiers();
1717 MethodDescriptor mdBogus =
1718 new MethodDescriptor( modBogus,
1719 new TypeDescriptor( TypeDescriptor.VOID ),
1720 "sese_"+fsen.getPrettyIdentifier()+fsen.getIdentifier()
1723 mdBogus.setClassDesc( fsen.getcdEnclosing() );
1724 FlatMethod fmBogus = new FlatMethod( mdBogus, null );
1725 fsen.setfmBogus( fmBogus );
1726 fsen.setmdBogus( mdBogus );
1728 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1729 inSetAndOutSet.addAll( fsen.getInVarSet() );
1730 inSetAndOutSet.addAll( fsen.getOutVarSet() );
1732 // Build paramsobj for bogus method descriptor
1733 ParamsObject objectparams = new ParamsObject( mdBogus, tag++ );
1734 paramstable.put( mdBogus, objectparams );
1736 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1737 while( itr.hasNext() ) {
1738 TempDescriptor temp = itr.next();
1739 TypeDescriptor type = temp.getType();
1740 if( type.isPtr() ) {
1741 objectparams.addPtr( temp );
1743 objectparams.addPrim( temp );
1747 // Build normal temp object for bogus method descriptor
1748 TempObject objecttemps = new TempObject( objectparams, mdBogus, tag++ );
1749 tempstable.put( mdBogus, objecttemps );
1751 for(Iterator nodeit=fsen.getNodeSet().iterator(); nodeit.hasNext();) {
1752 FlatNode fn=(FlatNode)nodeit.next();
1753 TempDescriptor[] writes=fn.writesTemps();
1754 for(int i=0; i<writes.length; i++) {
1755 TempDescriptor temp=writes[i];
1756 TypeDescriptor type=temp.getType();
1757 if (type.isPtr()&&GENERATEPRECISEGC) {
1758 objecttemps.addPtr(temp);
1760 objecttemps.addPrim(temp);
1766 protected void generateMethodSESE(FlatSESEEnterNode fsen,
1768 PrintWriter outputStructs,
1769 PrintWriter outputMethHead,
1770 PrintWriter outputMethods
1773 ParamsObject objectparams = (ParamsObject) paramstable.get( fsen.getmdBogus() );
1775 TempObject objecttemps = (TempObject) tempstable.get( fsen.getmdBogus() );
1777 // generate locals structure
1778 outputStructs.println("struct "+fsen.getcdEnclosing().getSafeSymbol()+fsen.getmdBogus().getSafeSymbol()+"_"+fsen.getmdBogus().getSafeMethodDescriptor()+"_locals {");
1779 outputStructs.println(" INTPTR size;");
1780 outputStructs.println(" void * next;");
1781 for(int i=0; i<objecttemps.numPointers(); i++) {
1782 TempDescriptor temp=objecttemps.getPointer(i);
1783 if (temp.getType().isNull())
1784 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
1786 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1788 outputStructs.println("};\n");
1791 // generate the SESE record structure
1792 outputStructs.println(fsen.getSESErecordName()+" {");
1794 // data common to any SESE, and it must be placed first so
1795 // a module that doesn't know what kind of SESE record this
1796 // is can cast the pointer to a common struct
1797 outputStructs.println(" SESEcommon common;");
1799 // then garbage list stuff
1800 outputStructs.println(" INTPTR size;");
1801 outputStructs.println(" void * next;");
1803 // in-set source tracking
1804 // in-vars that are READY come from parent, don't need anything
1805 // stuff STATIC needs a custom SESE pointer for each age pair
1806 Iterator<SESEandAgePair> itrStaticInVarSrcs = fsen.getStaticInVarSrcs().iterator();
1807 while( itrStaticInVarSrcs.hasNext() ) {
1808 SESEandAgePair srcPair = itrStaticInVarSrcs.next();
1809 outputStructs.println(" "+srcPair.getSESE().getSESErecordName()+"* "+srcPair+";");
1812 // DYNAMIC stuff needs a source SESE ptr and offset
1813 Iterator<TempDescriptor> itrDynInVars = fsen.getDynamicInVarSet().iterator();
1814 while( itrDynInVars.hasNext() ) {
1815 TempDescriptor dynInVar = itrDynInVars.next();
1816 outputStructs.println(" void* "+dynInVar+"_srcSESE;");
1817 outputStructs.println(" int "+dynInVar+"_srcOffset;");
1820 // space for all in and out set primitives
1821 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1822 inSetAndOutSet.addAll( fsen.getInVarSet() );
1823 inSetAndOutSet.addAll( fsen.getOutVarSet() );
1825 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
1827 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1828 while( itr.hasNext() ) {
1829 TempDescriptor temp = itr.next();
1830 TypeDescriptor type = temp.getType();
1831 if( !type.isPtr() ) {
1832 inSetAndOutSetPrims.add( temp );
1836 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
1837 while( itrPrims.hasNext() ) {
1838 TempDescriptor temp = itrPrims.next();
1839 TypeDescriptor type = temp.getType();
1840 outputStructs.println(" "+temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol()+";");
1843 for(int i=0; i<objectparams.numPointers(); i++) {
1844 TempDescriptor temp=objectparams.getPointer(i);
1845 if (temp.getType().isNull())
1846 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
1848 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1851 outputStructs.println("};\n");
1854 // write method declaration to header file
1855 outputMethHead.print("void ");
1856 outputMethHead.print(fsen.getSESEmethodName()+"(");
1857 outputMethHead.print(fsen.getSESErecordName()+"* "+paramsprefix);
1858 outputMethHead.println(");\n");
1861 generateFlatMethodSESE( fsen.getfmBogus(),
1862 fsen.getcdEnclosing(),
1868 private void generateFlatMethodSESE(FlatMethod fm,
1870 FlatSESEEnterNode fsen,
1871 FlatSESEExitNode seseExit,
1875 MethodDescriptor md=fm.getMethod();
1877 output.print("void ");
1878 output.print(fsen.getSESEmethodName()+"(");
1879 output.print(fsen.getSESErecordName()+"* "+paramsprefix);
1880 output.println("){\n");
1882 TempObject objecttemp=(TempObject) tempstable.get(md);
1884 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1885 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1886 output.print(objecttemp.numPointers()+",");
1887 output.print("(void*) &("+paramsprefix+"->size)");
1888 for(int j=0; j<objecttemp.numPointers(); j++)
1889 output.print(", NULL");
1890 output.println("};");
1893 output.println(" /* regular local primitives */");
1894 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1895 TempDescriptor td=objecttemp.getPrimitive(i);
1896 TypeDescriptor type=td.getType();
1898 output.println(" void * "+td.getSafeSymbol()+";");
1899 else if (type.isClass()||type.isArray())
1900 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1902 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1906 // declare variables for naming static SESE's
1907 output.println(" /* static SESE names */");
1908 Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
1909 while( pItr.hasNext() ) {
1910 SESEandAgePair p = pItr.next();
1911 output.println(" void* "+p+";");
1914 // declare variables for tracking dynamic sources
1915 output.println(" /* dynamic variable sources */");
1916 Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
1917 while( dynSrcItr.hasNext() ) {
1918 TempDescriptor dynSrcVar = dynSrcItr.next();
1919 output.println(" void* "+dynSrcVar+"_srcSESE;");
1920 output.println(" int "+dynSrcVar+"_srcOffset;");
1923 // declare local temps for in-set primitives, and if it is
1924 // a ready-source variable, get the value from the record
1925 output.println(" /* local temps for in-set primitives */");
1926 Iterator<TempDescriptor> itrInSet = fsen.getInVarSet().iterator();
1927 while( itrInSet.hasNext() ) {
1928 TempDescriptor temp = itrInSet.next();
1929 TypeDescriptor type = temp.getType();
1930 if( !type.isPtr() ) {
1931 if( fsen.getReadyInVarSet().contains( temp ) ) {
1932 output.println(" "+type+" "+temp+" = "+paramsprefix+"->"+temp+";");
1934 output.println(" "+type+" "+temp+";");
1939 // declare local temps for out-set primitives if its not already
1940 // in the in-set, and it's value will get written so no problem
1941 output.println(" /* local temp for out-set prim, not already in the in-set */");
1942 Iterator<TempDescriptor> itrOutSet = fsen.getOutVarSet().iterator();
1943 while( itrOutSet.hasNext() ) {
1944 TempDescriptor temp = itrOutSet.next();
1945 TypeDescriptor type = temp.getType();
1946 if( !type.isPtr() && !fsen.getInVarSet().contains( temp ) ) {
1947 output.println(" "+type+" "+temp+";");
1951 // copy in-set into place, ready vars were already
1952 // copied when the SESE was issued
1953 Iterator<TempDescriptor> tempItr;
1955 // static vars are from a known SESE
1956 tempItr = fsen.getStaticInVarSet().iterator();
1957 while( tempItr.hasNext() ) {
1958 TempDescriptor temp = tempItr.next();
1959 VariableSourceToken vst = fsen.getStaticInVarSrc( temp );
1960 SESEandAgePair srcPair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
1962 // can't grab something from this source until it is done
1963 output.println(" {");
1964 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+srcPair+";" );
1965 output.println(" pthread_mutex_lock( &(com->lock) );");
1966 output.println(" while( com->doneExecuting == FALSE ) {");
1967 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
1968 output.println(" }");
1969 output.println(" pthread_mutex_unlock( &(com->lock) );");
1971 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
1972 " = "+paramsprefix+"->"+srcPair+"->"+vst.getAddrVar()+";");
1974 output.println(" }");
1977 // dynamic vars come from an SESE and src
1978 tempItr = fsen.getDynamicInVarSet().iterator();
1979 while( tempItr.hasNext() ) {
1980 TempDescriptor temp = tempItr.next();
1981 TypeDescriptor type = temp.getType();
1983 // go grab it from the SESE source
1984 output.println(" if( "+paramsprefix+"->"+temp+"_srcSESE != NULL ) {");
1986 // gotta wait until the source is done
1987 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+temp+"_srcSESE;" );
1988 output.println(" pthread_mutex_lock( &(com->lock) );");
1989 output.println(" while( com->doneExecuting == FALSE ) {");
1990 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
1991 output.println(" }");
1992 output.println(" pthread_mutex_unlock( &(com->lock) );");
1995 if( type.isNull() ) {
1997 } else if( type.isClass() || type.isArray() ) {
1998 typeStr = "struct "+type.getSafeSymbol()+"*";
2000 typeStr = type.getSafeSymbol();
2003 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2004 " = *(("+typeStr+"*) ("+
2005 paramsprefix+"->"+temp+"_srcSESE + "+
2006 paramsprefix+"->"+temp+"_srcOffset));");
2008 // or if the source was our parent, its in the record to grab
2009 output.println(" } else {");
2010 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2011 " = "+paramsprefix+"->"+temp+";");
2012 output.println(" }");
2015 // Check to see if we need to do a GC if this is a
2016 // multi-threaded program...
2017 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2018 //Don't bother if we aren't in recursive methods...The loops case will catch it
2019 if (callgraph.getAllMethods(md).contains(md)) {
2020 if(this.state.MULTICOREGC) {
2021 output.println("if(gcflag) gc("+localsprefixaddr+");");
2023 output.println("if (needtocollect) checkcollect("+localsprefixaddr+");");
2028 // initialize thread-local var to a non-zero, invalid address
2029 output.println(" seseCaller = (SESEcommon*) 0x2;");
2031 HashSet<FlatNode> exitset=new HashSet<FlatNode>();
2032 exitset.add(seseExit);
2034 generateCode(fsen.getNext(0), fm, null, exitset, output, true);
2036 output.println("}\n\n");
2040 // when a new mlp thread is created for an issued SESE, it is started
2041 // by running this method which blocks on a cond variable until
2042 // it is allowed to transition to execute. Then a case statement
2043 // allows it to invoke the method with the proper SESE body, and after
2044 // exiting the SESE method, executes proper SESE exit code before the
2045 // thread can be destroyed
2046 private void generateSESEinvocationMethod(PrintWriter outmethodheader,
2047 PrintWriter outmethod
2050 outmethodheader.println("void* invokeSESEmethod( void* seseRecord );");
2051 outmethod.println( "void* invokeSESEmethod( void* seseRecord ) {");
2052 outmethod.println( " int status;");
2053 outmethod.println( " char errmsg[128];");
2055 // generate a case for each SESE class that can be invoked
2056 outmethod.println( " switch( *((int*)seseRecord) ) {");
2057 outmethod.println( " ");
2058 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
2059 FlatSESEEnterNode fsen = seseit.next();
2061 outmethod.println( " /* "+fsen.getPrettyIdentifier()+" */");
2062 outmethod.println( " case "+fsen.getIdentifier()+":");
2063 outmethod.println( " "+fsen.getSESEmethodName()+"( seseRecord );");
2065 if( fsen.equals( mlpa.getMainSESE() ) ) {
2066 outmethod.println( " /* work scheduler works forever, explicitly exit */");
2067 outmethod.println( " exit( 0 );");
2070 outmethod.println( " break;");
2071 outmethod.println( "");
2074 // default case should never be taken, error out
2075 outmethod.println( " default:");
2076 outmethod.println( " printf(\"Error: unknown SESE class ID in invoke method.\\n\");");
2077 outmethod.println( " exit(-30);");
2078 outmethod.println( " break;");
2079 outmethod.println( " }");
2080 outmethod.println( " return NULL;");
2081 outmethod.println( "}\n\n");
2085 protected void generateCode(FlatNode first,
2088 Set<FlatNode> stopset,
2089 PrintWriter output, boolean firstpass) {
2091 /* Assign labels to FlatNode's if necessary.*/
2092 Hashtable<FlatNode, Integer> nodetolabel=assignLabels(first, stopset);
2094 Set<FlatNode> storeset=null;
2095 HashSet<FlatNode> genset=null;
2096 Set<FlatNode> unionset=null;
2098 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
2099 storeset=delaycomp.livecode(lb);
2100 genset=new HashSet<FlatNode>();
2102 genset.addAll(delaycomp.getCannotDelay(lb));
2103 genset.addAll(delaycomp.getOther(lb));
2105 genset.addAll(delaycomp.getNotReady(lb));
2107 unionset=new HashSet<FlatNode>();
2108 unionset.addAll(storeset);
2109 unionset.addAll(genset);
2112 /* Do the actual code generation */
2113 FlatNode current_node=null;
2114 HashSet tovisit=new HashSet();
2115 HashSet visited=new HashSet();
2117 tovisit.add(first.getNext(0));
2120 while(current_node!=null||!tovisit.isEmpty()) {
2121 if (current_node==null) {
2122 current_node=(FlatNode)tovisit.iterator().next();
2123 tovisit.remove(current_node);
2124 } else if (tovisit.contains(current_node)) {
2125 tovisit.remove(current_node);
2127 visited.add(current_node);
2128 if (nodetolabel.containsKey(current_node)) {
2129 output.println("L"+nodetolabel.get(current_node)+":");
2131 if (state.INSTRUCTIONFAILURE) {
2132 if (state.THREAD||state.DSM||state.SINGLETM) {
2133 output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
2135 output.println("if ((--instructioncount)==0) injectinstructionfailure();");
2137 if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
2139 if (!state.DELAYCOMP||firstpass) {
2140 generateFlatNode(fm, lb, current_node, output);
2142 //store primitive variables in out set
2143 AtomicRecord ar=atomicmethodmap.get((FlatAtomicEnterNode)first);
2144 Set<TempDescriptor> liveout=ar.liveout;
2145 for(Iterator<TempDescriptor> tmpit=liveout.iterator();tmpit.hasNext();) {
2146 TempDescriptor tmp=tmpit.next();
2147 output.println("primitives->"+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2150 if (state.MLP && stopset!=null) {
2151 assert first.getPrev( 0 ) instanceof FlatSESEEnterNode;
2152 assert current_node instanceof FlatSESEExitNode;
2153 FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev( 0 );
2154 FlatSESEExitNode fsxn = (FlatSESEExitNode) current_node;
2155 assert fsen.getFlatExit().equals( fsxn );
2156 assert fsxn.getFlatEnter().equals( fsen );
2158 if (current_node.kind()!=FKind.FlatReturnNode) {
2159 output.println(" return;");
2162 } else if(current_node.numNext()==1) {
2165 current_node.kind()==FKind.FlatSESEEnterNode &&
2166 !((FlatSESEEnterNode)current_node).getIsCallerSESEplaceholder()
2168 FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
2169 generateFlatNode(fm, lb, current_node, output);
2170 nextnode=fsen.getFlatExit().getNext(0);
2171 } else if (state.DELAYCOMP) {
2172 boolean specialprimitive=false;
2173 //skip literals...no need to add extra overhead
2174 if (storeset!=null&&storeset.contains(current_node)&¤t_node.kind()==FKind.FlatLiteralNode) {
2175 TypeDescriptor typedesc=((FlatLiteralNode)current_node).getType();
2176 if (!typedesc.isClass()&&!typedesc.isArray()) {
2177 specialprimitive=true;
2181 if (genset==null||genset.contains(current_node)||specialprimitive)
2182 generateFlatNode(fm, lb, current_node, output);
2183 if (storeset!=null&&storeset.contains(current_node)&&!specialprimitive) {
2184 TempDescriptor wrtmp=current_node.writesTemps()[0];
2186 //need to store value written by previous node
2187 if (wrtmp.getType().isPtr()) {
2188 //only lock the objects that may actually need locking
2189 if (recorddc.getNeedTrans(lb, current_node)) {
2190 output.println("STOREPTR("+generateTemp(fm, wrtmp,lb)+");");
2192 output.println("STOREPTRNOLOCK("+generateTemp(fm, wrtmp,lb)+");");
2195 output.println("STORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");");
2198 //need to read value read by previous node
2199 if (wrtmp.getType().isPtr()) {
2200 output.println("RESTOREPTR("+generateTemp(fm, wrtmp,lb)+");");
2202 output.println("RESTORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");");
2206 nextnode=current_node.getNext(0);
2209 generateFlatNode(fm, lb, current_node, output);
2210 nextnode=current_node.getNext(0);
2212 if (visited.contains(nextnode)) {
2213 output.println("goto L"+nodetolabel.get(nextnode)+";");
2216 current_node=nextnode;
2217 } else if (current_node.numNext()==2) {
2219 if (state.DELAYCOMP) {
2220 boolean computeside=false;
2222 //need to record which way it should go
2223 if (genset==null||genset.contains(current_node)) {
2224 if (storeset!=null&&storeset.contains(current_node)) {
2225 //need to store which way branch goes
2226 generateStoreFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2228 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2230 //which side to execute
2234 if (genset.contains(current_node)) {
2235 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2236 } else if (storeset.contains(current_node)) {
2238 output.println("RESTOREANDBRANCH(L"+nodetolabel.get(current_node.getNext(1))+");");
2240 //which side to execute
2245 Set<FlatNode> leftset=DelayComputation.getNext(current_node, 0, unionset, lb,locality, true);
2247 if (leftset.size()==0)
2249 if (visited.contains(current_node.getNext(branch))) {
2250 //already visited -- build jump
2251 output.println("goto L"+nodetolabel.get(current_node.getNext(branch))+";");
2254 current_node=current_node.getNext(branch);
2257 if (!visited.contains(current_node.getNext(1)))
2258 tovisit.add(current_node.getNext(1));
2259 if (visited.contains(current_node.getNext(0))) {
2260 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2263 current_node=current_node.getNext(0);
2267 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2268 if (!visited.contains(current_node.getNext(1)))
2269 tovisit.add(current_node.getNext(1));
2270 if (visited.contains(current_node.getNext(0))) {
2271 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2274 current_node=current_node.getNext(0);
2276 } else throw new Error();
2280 /** This method assigns labels to FlatNodes */
2281 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first) {
2282 return assignLabels(first, null);
2285 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
2286 HashSet tovisit=new HashSet();
2287 HashSet visited=new HashSet();
2289 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2292 /*Assign labels first. A node needs a label if the previous
2293 * node has two exits or this node is a join point. */
2295 while(!tovisit.isEmpty()) {
2296 FlatNode fn=(FlatNode)tovisit.iterator().next();
2301 if(lastset!=null&&lastset.contains(fn)) {
2302 // if last is not null and matches, don't go
2303 // any further for assigning labels
2307 for(int i=0; i<fn.numNext(); i++) {
2308 FlatNode nn=fn.getNext(i);
2311 //1) Edge >1 of node
2312 nodetolabel.put(nn,new Integer(labelindex++));
2314 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2318 nodetolabel.put(nn,new Integer(labelindex++));
2326 /** Generate text string that corresponds to the TempDescriptor td. */
2327 protected String generateTemp(FlatMethod fm, TempDescriptor td, LocalityBinding lb) {
2328 MethodDescriptor md=fm.getMethod();
2329 TaskDescriptor task=fm.getTask();
2330 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
2332 if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
2333 //System.out.println("generateTemp returns " + td.getSafeSymbol());
2334 return td.getSafeSymbol();
2337 if (objecttemps.isLocalPtr(td)) {
2338 return localsprefixderef+td.getSafeSymbol();
2341 if (objecttemps.isParamPtr(td)) {
2342 return paramsprefix+"->"+td.getSafeSymbol();
2348 protected void generateFlatNode(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output) {
2350 // insert pre-node actions from the code plan
2353 CodePlan cp = mlpa.getCodePlan( fn );
2356 FlatSESEEnterNode currentSESE = cp.getCurrentSESE();
2358 // for each sese and age pair that this parent statement
2359 // must stall on, take that child's stall semaphore, the
2360 // copying of values comes after the statement
2361 Iterator<VariableSourceToken> vstItr = cp.getStallTokens().iterator();
2362 while( vstItr.hasNext() ) {
2363 VariableSourceToken vst = vstItr.next();
2365 SESEandAgePair p = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2367 output.println(" {");
2368 output.println(" SESEcommon* common = (SESEcommon*) "+p+";");
2370 output.println(" pthread_mutex_lock( &(common->lock) );");
2371 output.println(" while( common->doneExecuting == FALSE ) {");
2372 output.println(" pthread_cond_wait( &(common->doneCond), &(common->lock) );");
2373 output.println(" }");
2374 output.println(" pthread_mutex_unlock( &(common->lock) );");
2376 //output.println(" psem_take( &(common->stallSem) );");
2378 // copy things we might have stalled for
2379 output.println(" "+p.getSESE().getSESErecordName()+"* child = ("+
2380 p.getSESE().getSESErecordName()+"*) "+p+";");
2382 Iterator<TempDescriptor> tdItr = cp.getCopySet( vst ).iterator();
2383 while( tdItr.hasNext() ) {
2384 TempDescriptor td = tdItr.next();
2385 FlatMethod fmContext;
2386 if( currentSESE.getIsCallerSESEplaceholder() ) {
2387 fmContext = currentSESE.getfmEnclosing();
2389 fmContext = currentSESE.getfmBogus();
2391 output.println(" "+generateTemp( fmContext, td, null )+
2392 " = child->"+vst.getAddrVar().getSafeSymbol()+";");
2395 output.println(" }");
2398 // for each variable with a dynamic source, stall just for that variable
2399 Iterator<TempDescriptor> dynItr = cp.getDynamicStallSet().iterator();
2400 while( dynItr.hasNext() ) {
2401 TempDescriptor dynVar = dynItr.next();
2403 // only stall if the dynamic source is not yourself, denoted by src==NULL
2404 // otherwise the dynamic write nodes will have the local var up-to-date
2405 output.println(" {");
2406 output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
2407 output.println(" SESEcommon* common = (SESEcommon*) "+dynVar+"_srcSESE;");
2408 output.println(" psem_take( &(common->stallSem) );");
2410 FlatMethod fmContext;
2411 if( currentSESE.getIsCallerSESEplaceholder() ) {
2412 fmContext = currentSESE.getfmEnclosing();
2414 fmContext = currentSESE.getfmBogus();
2416 output.println(" "+generateTemp( fmContext, dynVar, null )+
2417 " = *(("+dynVar.getType()+"*) ("+
2418 dynVar+"_srcSESE + "+dynVar+"_srcOffset));");
2420 output.println(" }");
2421 output.println(" }");
2424 // for each assignment of a variable to rhs that has a dynamic source,
2425 // copy the dynamic sources
2426 Iterator dynAssignItr = cp.getDynAssigns().entrySet().iterator();
2427 while( dynAssignItr.hasNext() ) {
2428 Map.Entry me = (Map.Entry) dynAssignItr.next();
2429 TempDescriptor lhs = (TempDescriptor) me.getKey();
2430 TempDescriptor rhs = (TempDescriptor) me.getValue();
2431 output.println(" "+lhs+"_srcSESE = "+rhs+"_srcSESE;");
2432 output.println(" "+lhs+"_srcOffset = "+rhs+"_srcOffset;");
2438 case FKind.FlatAtomicEnterNode:
2439 generateFlatAtomicEnterNode(fm, lb, (FlatAtomicEnterNode) fn, output);
2442 case FKind.FlatAtomicExitNode:
2443 generateFlatAtomicExitNode(fm, lb, (FlatAtomicExitNode) fn, output);
2446 case FKind.FlatInstanceOfNode:
2447 generateFlatInstanceOfNode(fm, lb, (FlatInstanceOfNode)fn, output);
2450 case FKind.FlatSESEEnterNode:
2451 generateFlatSESEEnterNode(fm, lb, (FlatSESEEnterNode)fn, output);
2454 case FKind.FlatSESEExitNode:
2455 generateFlatSESEExitNode(fm, lb, (FlatSESEExitNode)fn, output);
2458 case FKind.FlatWriteDynamicVarNode:
2459 generateFlatWriteDynamicVarNode(fm, lb, (FlatWriteDynamicVarNode)fn, output);
2462 case FKind.FlatGlobalConvNode:
2463 generateFlatGlobalConvNode(fm, lb, (FlatGlobalConvNode) fn, output);
2466 case FKind.FlatTagDeclaration:
2467 generateFlatTagDeclaration(fm, lb, (FlatTagDeclaration) fn,output);
2470 case FKind.FlatCall:
2471 generateFlatCall(fm, lb, (FlatCall) fn,output);
2474 case FKind.FlatFieldNode:
2475 generateFlatFieldNode(fm, lb, (FlatFieldNode) fn,output);
2478 case FKind.FlatElementNode:
2479 generateFlatElementNode(fm, lb, (FlatElementNode) fn,output);
2482 case FKind.FlatSetElementNode:
2483 generateFlatSetElementNode(fm, lb, (FlatSetElementNode) fn,output);
2486 case FKind.FlatSetFieldNode:
2487 generateFlatSetFieldNode(fm, lb, (FlatSetFieldNode) fn,output);
2491 generateFlatNew(fm, lb, (FlatNew) fn,output);
2494 case FKind.FlatOpNode:
2495 generateFlatOpNode(fm, lb, (FlatOpNode) fn,output);
2498 case FKind.FlatCastNode:
2499 generateFlatCastNode(fm, lb, (FlatCastNode) fn,output);
2502 case FKind.FlatLiteralNode:
2503 generateFlatLiteralNode(fm, lb, (FlatLiteralNode) fn,output);
2506 case FKind.FlatReturnNode:
2507 generateFlatReturnNode(fm, lb, (FlatReturnNode) fn,output);
2511 output.println("/* nop */");
2514 case FKind.FlatExit:
2515 output.println("/* exit */");
2518 case FKind.FlatBackEdge:
2519 if (((state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
2520 || (this.state.MULTICOREGC)) {
2521 if(state.DSM&&locality.getAtomic(lb).get(fn).intValue()>0) {
2522 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
2523 } else if(this.state.MULTICOREGC) {
2524 output.println("if (gcflag) gc("+localsprefixaddr+");");
2526 output.println("if (needtocollect) checkcollect("+localsprefixaddr+");");
2528 output.println("/* nop */");
2531 case FKind.FlatCheckNode:
2532 generateFlatCheckNode(fm, lb, (FlatCheckNode) fn, output);
2535 case FKind.FlatFlagActionNode:
2536 generateFlatFlagActionNode(fm, lb, (FlatFlagActionNode) fn, output);
2539 case FKind.FlatPrefetchNode:
2540 generateFlatPrefetchNode(fm,lb, (FlatPrefetchNode) fn, output);
2543 case FKind.FlatOffsetNode:
2544 generateFlatOffsetNode(fm, lb, (FlatOffsetNode)fn, output);
2551 // insert post-node actions from the code-plan
2553 CodePlan cp = mlpa.getCodePlan( fn );
2560 public void generateFlatOffsetNode(FlatMethod fm, LocalityBinding lb, FlatOffsetNode fofn, PrintWriter output) {
2561 output.println("/* FlatOffsetNode */");
2562 FieldDescriptor fd=fofn.getField();
2563 output.println(generateTemp(fm, fofn.getDst(),lb)+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+ fd.getSafeSymbol()+");");
2564 output.println("/* offset */");
2567 public void generateFlatPrefetchNode(FlatMethod fm, LocalityBinding lb, FlatPrefetchNode fpn, PrintWriter output) {
2568 if (state.PREFETCH) {
2569 Vector oids = new Vector();
2570 Vector fieldoffset = new Vector();
2571 Vector endoffset = new Vector();
2572 int tuplecount = 0; //Keeps track of number of prefetch tuples that need to be generated
2573 for(Iterator it = fpn.hspp.iterator(); it.hasNext();) {
2574 PrefetchPair pp = (PrefetchPair) it.next();
2575 Integer statusbase = locality.getNodePreTempInfo(lb,fpn).get(pp.base);
2576 /* Find prefetches that can generate oid */
2577 if(statusbase == LocalityAnalysis.GLOBAL) {
2578 generateTransCode(fm, lb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(lb).get(fpn).intValue()>0, false);
2580 } else if (statusbase == LocalityAnalysis.LOCAL) {
2581 generateTransCode(fm,lb,pp,oids,fieldoffset,endoffset,tuplecount,false,true);
2588 System.out.println("Adding prefetch "+fpn+ " to method:" +fm);
2589 output.println("{");
2590 output.println("/* prefetch */");
2591 output.println("/* prefetchid_" + fpn.siteid + " */");
2592 output.println("void * prefptr;");
2593 output.println("int tmpindex;");
2595 output.println("if((evalPrefetch["+fpn.siteid+"].operMode) || (evalPrefetch["+fpn.siteid+"].retrycount <= 0)) {");
2596 /*Create C code for oid array */
2597 output.print(" unsigned int oidarray_[] = {");
2598 boolean needcomma=false;
2599 for (Iterator it = oids.iterator(); it.hasNext();) {
2602 output.print(it.next());
2605 output.println("};");
2607 /*Create C code for endoffset values */
2608 output.print(" unsigned short endoffsetarry_[] = {");
2610 for (Iterator it = endoffset.iterator(); it.hasNext();) {
2613 output.print(it.next());
2616 output.println("};");
2618 /*Create C code for Field Offset Values */
2619 output.print(" short fieldarry_[] = {");
2621 for (Iterator it = fieldoffset.iterator(); it.hasNext();) {
2624 output.print(it.next());
2627 output.println("};");
2628 /* make the prefetch call to Runtime */
2629 output.println(" if(!evalPrefetch["+fpn.siteid+"].operMode) {");
2630 output.println(" evalPrefetch["+fpn.siteid+"].retrycount = RETRYINTERVAL;");
2631 output.println(" }");
2632 output.println(" prefetch("+fpn.siteid+" ,"+tuplecount+", oidarray_, endoffsetarry_, fieldarry_);");
2633 output.println(" } else {");
2634 output.println(" evalPrefetch["+fpn.siteid+"].retrycount--;");
2635 output.println(" }");
2636 output.println("}");
2640 public void generateTransCode(FlatMethod fm, LocalityBinding lb,PrefetchPair pp, Vector oids, Vector fieldoffset, Vector endoffset, int tuplecount, boolean inside, boolean localbase) {
2641 short offsetcount = 0;
2645 } else if (localbase) {
2646 for(; breakindex<pp.desc.size(); breakindex++) {
2647 Descriptor desc=pp.getDescAt(breakindex);
2648 if (desc instanceof FieldDescriptor) {
2649 FieldDescriptor fd=(FieldDescriptor)desc;
2650 if (fd.isGlobal()) {
2658 if (breakindex>pp.desc.size()) //all local
2661 TypeDescriptor lasttype=pp.base.getType();
2662 String basestr=generateTemp(fm, pp.base, lb);
2664 boolean maybenull=fm.getMethod().isStatic()||
2665 !pp.base.equals(fm.getParameter(0));
2667 for(int i=0; i<breakindex; i++) {
2668 String indexcheck="";
2670 Descriptor desc=pp.getDescAt(i);
2671 if (desc instanceof FieldDescriptor) {
2672 FieldDescriptor fd=(FieldDescriptor)desc;
2674 if (!teststr.equals(""))
2676 teststr+="((prefptr="+basestr+")!=NULL)";
2677 basestr="((struct "+lasttype.getSafeSymbol()+" *)prefptr)->"+fd.getSafeSymbol();
2679 basestr=basestr+"->"+fd.getSafeSymbol();
2682 lasttype=fd.getType();
2684 IndexDescriptor id=(IndexDescriptor)desc;
2685 indexcheck="((tmpindex=";
2686 for(int j=0; j<id.tddesc.size(); j++) {
2687 indexcheck+=generateTemp(fm, id.getTempDescAt(j), lb)+"+";
2689 indexcheck+=id.offset+")>=0)&(tmpindex<((struct ArrayObject *)prefptr)->___length___)";
2691 if (!teststr.equals(""))
2693 teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck;
2694 basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]";
2696 lasttype=lasttype.dereference();
2701 if (teststr.equals("")) {
2702 oid="((unsigned int)"+basestr+")";
2704 oid="((unsigned int)(("+teststr+")?"+basestr+":NULL))";
2708 for(int i = breakindex; i < pp.desc.size(); i++) {
2709 String newfieldoffset;
2710 Object desc = pp.getDescAt(i);
2711 if(desc instanceof FieldDescriptor) {
2712 FieldDescriptor fd=(FieldDescriptor)desc;
2713 newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))");
2714 lasttype=fd.getType();
2716 newfieldoffset = "";
2717 IndexDescriptor id=(IndexDescriptor)desc;
2718 for(int j = 0; j < id.tddesc.size(); j++) {
2719 newfieldoffset += generateTemp(fm, id.getTempDescAt(j), lb) + "+";
2721 newfieldoffset += id.offset.toString();
2722 lasttype=lasttype.dereference();
2724 fieldoffset.add(newfieldoffset);
2727 int base=(tuplecount>0) ? ((Short)endoffset.get(tuplecount-1)).intValue() : 0;
2728 base+=pp.desc.size()-breakindex;
2729 endoffset.add(new Short((short)base));
2734 public void generateFlatGlobalConvNode(FlatMethod fm, LocalityBinding lb, FlatGlobalConvNode fgcn, PrintWriter output) {
2735 if (lb!=fgcn.getLocality())
2737 /* Have to generate flat globalconv */
2738 if (fgcn.getMakePtr()) {
2740 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+");");
2742 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fgcn)||state.READSET&&dc.getNeedWriteTrans(lb, fgcn)) {
2743 //need to do translation
2744 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+", (void *)("+localsprefixaddr+"));");
2745 } else if (state.READSET&&dc.getNeedTrans(lb, fgcn)) {
2746 output.println("TRANSREADRD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
2750 /* Need to convert to OID */
2751 if ((dc==null)||dc.getNeedSrcTrans(lb,fgcn)) {
2752 if (fgcn.doConvert()||(delaycomp!=null&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) {
2753 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc(),lb)+");");
2755 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=NULL;");
2761 public void generateFlatInstanceOfNode(FlatMethod fm, LocalityBinding lb, FlatInstanceOfNode fion, PrintWriter output) {
2763 if (fion.getType().isArray()) {
2764 type=state.getArrayNumber(fion.getType())+state.numClasses();
2766 type=fion.getType().getClassDesc().getId();
2769 if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
2770 output.println(generateTemp(fm, fion.getDst(), lb)+"=1;");
2772 output.println(generateTemp(fm, fion.getDst(), lb)+"=instanceof("+generateTemp(fm,fion.getSrc(),lb)+","+type+");");
2775 public void generateFlatAtomicEnterNode(FlatMethod fm, LocalityBinding lb, FlatAtomicEnterNode faen, PrintWriter output) {
2776 /* Check to see if we need to generate code for this atomic */
2777 if (locality==null) {
2778 output.println("pthread_mutex_lock(&atomiclock);");
2782 if (locality.getAtomic(lb).get(faen.getPrev(0)).intValue()>0)
2786 if (state.DELAYCOMP) {
2787 AtomicRecord ar=atomicmethodmap.get(faen);
2789 for(Iterator<TempDescriptor> tmpit=ar.livein.iterator();tmpit.hasNext();) {
2790 TempDescriptor tmp=tmpit.next();
2791 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2794 //copy outs that depend on path
2795 for(Iterator<TempDescriptor> tmpit=ar.liveoutvirtualread.iterator();tmpit.hasNext();) {
2796 TempDescriptor tmp=tmpit.next();
2797 if (!ar.livein.contains(tmp))
2798 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2802 /* Backup the temps. */
2803 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
2804 TempDescriptor tmp=tmpit.next();
2805 output.println(generateTemp(fm, backuptable.get(lb).get(tmp),lb)+"="+generateTemp(fm,tmp,lb)+";");
2808 output.println("goto transstart"+faen.getIdentifier()+";");
2810 /******* Print code to retry aborted transaction *******/
2811 output.println("transretry"+faen.getIdentifier()+":");
2814 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
2815 TempDescriptor tmp=tmpit.next();
2816 output.println(generateTemp(fm, tmp,lb)+"="+generateTemp(fm,backuptable.get(lb).get(tmp),lb)+";");
2820 /********* Need to revert local object store ********/
2821 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
2823 output.println("while ("+revertptr+") {");
2824 output.println("struct ___Object___ * tmpptr;");
2825 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
2826 output.println("REVERT_OBJ("+revertptr+");");
2827 output.println(revertptr+"=tmpptr;");
2828 output.println("}");
2830 /******* Tell the runtime to start the transaction *******/
2832 output.println("transstart"+faen.getIdentifier()+":");
2833 output.println("transStart();");
2835 if (state.ABORTREADERS) {
2836 output.println("if (_setjmp(aborttrans)) {");
2837 output.println(" goto transretry"+faen.getIdentifier()+"; }");
2841 public void generateFlatAtomicExitNode(FlatMethod fm, LocalityBinding lb, FlatAtomicExitNode faen, PrintWriter output) {
2842 /* Check to see if we need to generate code for this atomic */
2843 if (locality==null) {
2844 output.println("pthread_mutex_unlock(&atomiclock);");
2847 if (locality.getAtomic(lb).get(faen).intValue()>0)
2849 //store the revert list before we lose the transaction object
2850 String revertptr=null;
2852 revertptr=generateTemp(fm, reverttable.get(lb),lb);
2853 output.println(revertptr+"=revertlist;");
2855 if (state.DELAYCOMP) {
2856 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
2859 output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {");
2861 output.println("if (transCommit()) {");
2862 /* Transaction aborts if it returns true */
2863 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
2865 output.println("} else {");
2866 /* Need to commit local object store */
2867 output.println("while ("+revertptr+") {");
2868 output.println("struct ___Object___ * tmpptr;");
2869 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
2870 output.println("COMMIT_OBJ("+revertptr+");");
2871 output.println(revertptr+"=tmpptr;");
2872 output.println("}");
2874 output.println("}");
2875 if (state.DELAYCOMP) {
2877 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
2878 output.println("else {");
2879 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
2880 TempDescriptor tmp=tmpit.next();
2881 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
2883 output.println("}");
2887 public void generateFlatSESEEnterNode( FlatMethod fm,
2889 FlatSESEEnterNode fsen,
2893 // SESE nodes can be parsed for normal compilation, just skip over them
2897 // also, if we have encountered a placeholder, just skip it
2898 if( fsen.getIsCallerSESEplaceholder() ) {
2902 output.println(" {");
2904 // set up the parent
2905 if( fsen == mlpa.getMainSESE() ) {
2906 output.println(" SESEcommon* parentCommon = NULL;");
2908 if( fsen.getParent() == null ) {
2909 System.out.println( "in "+fm+", "+fsen+" has null parent" );
2911 assert fsen.getParent() != null;
2912 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
2913 output.println(" SESEcommon* parentCommon = &("+paramsprefix+"->common);");
2915 //output.println(" SESEcommon* parentCommon = (SESEcommon*) peekItem( seseCallStack );");
2916 output.println(" SESEcommon* parentCommon = seseCaller;");
2920 // before doing anything, lock your own record and increment the running children
2921 if( fsen != mlpa.getMainSESE() ) {
2922 output.println(" pthread_mutex_lock( &(parentCommon->lock) );");
2923 output.println(" ++(parentCommon->numRunningChildren);");
2924 output.println(" pthread_mutex_unlock( &(parentCommon->lock) );");
2927 // just allocate the space for this record
2928 output.println(" "+fsen.getSESErecordName()+"* seseToIssue = ("+
2929 fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
2930 fsen.getSESErecordName()+" ) );");
2932 // and keep the thread-local sese stack up to date
2933 //output.println(" addNewItem( seseCallStack, (void*) seseToIssue);");
2935 // fill in common data
2936 output.println(" seseToIssue->common.classID = "+fsen.getIdentifier()+";");
2937 output.println(" psem_init( &(seseToIssue->common.stallSem) );");
2939 output.println(" seseToIssue->common.forwardList = createQueue();");
2940 output.println(" seseToIssue->common.unresolvedDependencies = 0;");
2941 output.println(" pthread_cond_init( &(seseToIssue->common.doneCond), NULL );");
2942 output.println(" seseToIssue->common.doneExecuting = FALSE;");
2943 output.println(" pthread_cond_init( &(seseToIssue->common.runningChildrenCond), NULL );");
2944 output.println(" seseToIssue->common.numRunningChildren = 0;");
2945 output.println(" seseToIssue->common.parent = parentCommon;");
2947 // all READY in-vars should be copied now and be done with it
2948 Iterator<TempDescriptor> tempItr = fsen.getReadyInVarSet().iterator();
2949 while( tempItr.hasNext() ) {
2950 TempDescriptor temp = tempItr.next();
2952 // when we are issuing the main SESE or an SESE with placeholder
2953 // caller SESE as parent, generate temp child child's eclosing method,
2954 // otherwise use the parent's enclosing method as the context
2955 boolean useParentContext = false;
2957 if( fsen != mlpa.getMainSESE() ) {
2958 assert fsen.getParent() != null;
2959 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
2960 useParentContext = true;
2964 if( useParentContext ) {
2965 output.println(" seseToIssue->"+temp+" = "+
2966 generateTemp( fsen.getParent().getfmBogus(), temp, null )+";");
2968 output.println(" seseToIssue->"+temp+" = "+
2969 generateTemp( fsen.getfmEnclosing(), temp, null )+";");
2973 // before potentially adding this SESE to other forwarding lists,
2974 // create it's lock and take it immediately
2975 output.println(" pthread_mutex_init( &(seseToIssue->common.lock), NULL );");
2976 output.println(" pthread_mutex_lock( &(seseToIssue->common.lock) );");
2978 if( fsen != mlpa.getMainSESE() ) {
2979 // count up outstanding dependencies, static first, then dynamic
2980 Iterator<SESEandAgePair> staticSrcsItr = fsen.getStaticInVarSrcs().iterator();
2981 while( staticSrcsItr.hasNext() ) {
2982 SESEandAgePair srcPair = staticSrcsItr.next();
2983 output.println(" {");
2984 output.println(" SESEcommon* src = (SESEcommon*)"+srcPair+";");
2985 output.println(" pthread_mutex_lock( &(src->lock) );");
2986 output.println(" if( !isEmpty( src->forwardList ) &&");
2987 output.println(" seseToIssue == peekItem( src->forwardList ) ) {");
2988 output.println(" printf( \"This shouldnt already be here\\n\");");
2989 output.println(" exit( -1 );");
2990 output.println(" }");
2991 output.println(" if( !src->doneExecuting ) {");
2992 output.println(" addNewItem( src->forwardList, seseToIssue );");
2993 output.println(" ++(seseToIssue->common.unresolvedDependencies);");
2994 output.println(" }");
2995 output.println(" pthread_mutex_unlock( &(src->lock) );");
2996 output.println(" }");
2998 // whether or not it is an outstanding dependency, make sure
2999 // to pass the static name to the child's record
3000 output.println(" seseToIssue->"+srcPair+" = "+srcPair+";");
3003 // dynamic sources might already be accounted for in the static list,
3004 // so only add them to forwarding lists if they're not already there
3005 Iterator<TempDescriptor> dynVarsItr = fsen.getDynamicInVarSet().iterator();
3006 while( dynVarsItr.hasNext() ) {
3007 TempDescriptor dynInVar = dynVarsItr.next();
3008 output.println(" {");
3009 output.println(" SESEcommon* src = (SESEcommon*)"+dynInVar+"_srcSESE;");
3011 // the dynamic source is NULL if it comes from your own space--you can't pass
3012 // the address off to the new child, because you're not done executing and
3013 // might change the variable, so copy it right now
3014 output.println(" if( src != NULL ) {");
3015 output.println(" pthread_mutex_lock( &(src->lock) );");
3016 output.println(" if( isEmpty( src->forwardList ) ||");
3017 output.println(" seseToIssue != peekItem( src->forwardList ) ) {");
3018 output.println(" if( !src->doneExecuting ) {");
3019 output.println(" addNewItem( src->forwardList, seseToIssue );");
3020 output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3021 output.println(" }");
3022 output.println(" }");
3023 output.println(" pthread_mutex_unlock( &(src->lock) );");
3024 output.println(" seseToIssue->"+dynInVar+"_srcOffset = "+dynInVar+"_srcOffset;");
3025 output.println(" } else {");
3027 boolean useParentContext = false;
3028 if( fsen != mlpa.getMainSESE() ) {
3029 assert fsen.getParent() != null;
3030 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3031 useParentContext = true;
3034 if( useParentContext ) {
3035 output.println(" seseToIssue->"+dynInVar+" = "+
3036 generateTemp( fsen.getParent().getfmBogus(), dynInVar, null )+";");
3038 output.println(" seseToIssue->"+dynInVar+" = "+
3039 generateTemp( fsen.getfmEnclosing(), dynInVar, null )+";");
3042 output.println(" }");
3043 output.println(" }");
3045 // even if the value is already copied, make sure your NULL source
3046 // gets passed so child knows it already has the dynamic value
3047 output.println(" seseToIssue->"+dynInVar+"_srcSESE = "+dynInVar+"_srcSESE;");
3050 // maintain pointers for for finding dynamic SESE
3051 // instances from static names
3052 SESEandAgePair p = new SESEandAgePair( fsen, 0 );
3053 if( fsen.getParent() != null &&
3054 //!fsen.getParent().getIsCallerSESEplaceholder() &&
3055 fsen.getParent().getNeededStaticNames().contains( p )
3058 for( int i = fsen.getOldestAgeToTrack(); i > 0; --i ) {
3059 SESEandAgePair p1 = new SESEandAgePair( fsen, i );
3060 SESEandAgePair p2 = new SESEandAgePair( fsen, i-1 );
3061 output.println(" "+p1+" = "+p2+";");
3063 output.println(" "+p+" = seseToIssue;");
3067 // if there were no outstanding dependencies, issue here
3068 output.println(" if( seseToIssue->common.unresolvedDependencies == 0 ) {");
3069 output.println(" workScheduleSubmit( (void*)seseToIssue );");
3070 output.println(" }");
3072 // release this SESE for siblings to update its dependencies or,
3073 // eventually, for it to mark itself finished
3074 output.println(" pthread_mutex_unlock( &(seseToIssue->common.lock) );");
3075 output.println(" }");
3079 public void generateFlatSESEExitNode( FlatMethod fm,
3081 FlatSESEExitNode fsexn,
3085 // SESE nodes can be parsed for normal compilation, just skip over them
3089 // also, if we have encountered a placeholder, just jump it
3090 if( fsexn.getFlatEnter().getIsCallerSESEplaceholder() ) {
3094 output.println(" /* SESE exiting */");
3096 String com = paramsprefix+"->common";
3099 // take yourself off the thread-local sese call stack
3100 output.println(" if( isEmpty( seseCallStack ) ) {");
3101 output.println(" printf( \"Error, sese call stack is empty.\\n\" );");
3102 output.println(" exit( -1 );");
3103 output.println(" }");
3104 output.println(" if( (void*)"+paramsprefix+" != getItem( seseCallStack ) ) {");
3105 output.println(" printf( \"Error, sese call stack mismatch.\\n\" );");
3106 output.println(" exit( -1 );");
3107 output.println(" }");
3110 // this SESE cannot be done until all of its children are done
3111 // so grab your own lock with the condition variable for watching
3112 // that the number of your running children is greater than zero
3113 output.println(" pthread_mutex_lock( &("+com+".lock) );");
3114 output.println(" while( "+com+".numRunningChildren > 0 ) {");
3115 output.println(" pthread_cond_wait( &("+com+".runningChildrenCond), &("+com+".lock) );");
3116 output.println(" }");
3118 // copy out-set from local temps into the sese record
3119 Iterator<TempDescriptor> itr = fsexn.getFlatEnter().getOutVarSet().iterator();
3120 while( itr.hasNext() ) {
3121 TempDescriptor temp = itr.next();
3122 output.println(" "+paramsprefix+
3123 "->"+temp.getSafeSymbol()+
3124 " = "+temp.getSafeSymbol()+";" );
3127 // mark yourself done, your SESE data is now read-only
3128 output.println(" "+com+".doneExecuting = TRUE;");
3129 output.println(" pthread_cond_signal( &("+com+".doneCond) );");
3130 output.println(" pthread_mutex_unlock( &("+com+".lock) );");
3132 // decrement dependency count for all SESE's on your forwarding list
3133 output.println(" while( !isEmpty( "+com+".forwardList ) ) {");
3134 output.println(" SESEcommon* consumer = (SESEcommon*) getItem( "+com+".forwardList );");
3135 output.println(" pthread_mutex_lock( &(consumer->lock) );");
3136 output.println(" --(consumer->unresolvedDependencies);");
3137 output.println(" if( consumer->unresolvedDependencies == 0 ) {");
3138 output.println(" workScheduleSubmit( (void*)consumer );");
3139 output.println(" }");
3140 output.println(" pthread_mutex_unlock( &(consumer->lock) );");
3141 output.println(" }");
3143 // if parent is stalling on you, let them know you're done
3144 if( fsexn.getFlatEnter() != mlpa.getMainSESE() ) {
3145 output.println(" psem_give( &("+paramsprefix+"->common.stallSem) );");
3148 // last of all, decrement your parent's number of running children
3149 output.println(" if( "+paramsprefix+"->common.parent != NULL ) {");
3150 output.println(" pthread_mutex_lock( &("+paramsprefix+"->common.parent->lock) );");
3151 output.println(" --("+paramsprefix+"->common.parent->numRunningChildren);");
3152 output.println(" pthread_cond_signal( &("+paramsprefix+"->common.parent->runningChildrenCond) );");
3153 output.println(" pthread_mutex_unlock( &("+paramsprefix+"->common.parent->lock) );");
3154 output.println(" }");
3156 // this is a thread-only variable that can be handled when critical sese-to-sese
3157 // data has been taken care of--set sese pointer to remember self over method
3158 // calls to a non-zero, invalid address
3159 output.println(" seseCaller = (SESEcommon*) 0x1;");
3162 public void generateFlatWriteDynamicVarNode( FlatMethod fm,
3164 FlatWriteDynamicVarNode fwdvn,
3168 // should node should not be in an IR graph if the
3169 // MLP flag is not set
3170 throw new Error("Unexpected presence of FlatWriteDynamicVarNode");
3173 Hashtable<TempDescriptor, VariableSourceToken> writeDynamic =
3176 assert writeDynamic != null;
3178 Iterator wdItr = writeDynamic.entrySet().iterator();
3179 while( wdItr.hasNext() ) {
3180 Map.Entry me = (Map.Entry) wdItr.next();
3181 TempDescriptor refVar = (TempDescriptor) me.getKey();
3182 VariableSourceToken vst = (VariableSourceToken) me.getValue();
3184 FlatSESEEnterNode current = fwdvn.getEnclosingSESE();
3186 // only do this if the variable in question should be tracked,
3187 // meaning that it was explicitly added to the dynamic var set
3188 if( !current.getDynamicVarSet().contains( vst.getAddrVar() ) ) {
3192 SESEandAgePair instance = new SESEandAgePair( vst.getSESE(), vst.getAge() );
3194 output.println(" {");
3196 if( current.equals( vst.getSESE() ) ) {
3197 // if the src comes from this SESE, it's a method local variable,
3198 // mark src pointer NULL to signify that the var is up-to-date
3199 output.println(" "+vst.getAddrVar()+"_srcSESE = NULL;");
3202 // otherwise we track where it will come from
3203 output.println(" "+vst.getAddrVar()+"_srcSESE = "+instance+";");
3204 output.println(" "+vst.getAddrVar()+"_srcOffset = (int) &((("+
3205 vst.getSESE().getSESErecordName()+"*)0)->"+vst.getAddrVar()+");");
3208 output.println(" }");
3213 private void generateFlatCheckNode(FlatMethod fm, LocalityBinding lb, FlatCheckNode fcn, PrintWriter output) {
3214 if (state.CONSCHECK) {
3215 String specname=fcn.getSpec();
3216 String varname="repairstate___";
3217 output.println("{");
3218 output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
3220 TempDescriptor[] temps=fcn.getTemps();
3221 String[] vars=fcn.getVars();
3222 for(int i=0; i<temps.length; i++) {
3223 output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i],lb)+";");
3226 output.println("if (doanalysis"+specname+"("+varname+")) {");
3227 output.println("free"+specname+"_state("+varname+");");
3228 output.println("} else {");
3229 output.println("/* Bad invariant */");
3230 output.println("free"+specname+"_state("+varname+");");
3231 output.println("abort_task();");
3232 output.println("}");
3233 output.println("}");
3237 private void generateFlatCall(FlatMethod fm, LocalityBinding lb, FlatCall fc, PrintWriter output) {
3239 if( state.MLP && !nonSESEpass ) {
3240 output.println(" seseCaller = (SESEcommon*)"+paramsprefix+";");
3243 MethodDescriptor md=fc.getMethod();
3244 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? locality.getBinding(lb, fc) : md);
3245 ClassDescriptor cn=md.getClassDesc();
3246 output.println("{");
3247 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3249 LocalityBinding fclb=locality.getBinding(lb, fc);
3250 output.print(" struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
3252 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
3254 output.print(objectparams.numPointers());
3255 output.print(", "+localsprefixaddr);
3256 if (md.getThis()!=null) {
3258 output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis(),lb));
3260 if (fc.getThis()!=null&&md.getThis()==null) {
3261 System.out.println("WARNING!!!!!!!!!!!!");
3262 System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
3266 for(int i=0; i<fc.numArgs(); i++) {
3267 Descriptor var=md.getParameter(i);
3268 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
3269 if (objectparams.isParamPtr(paramtemp)) {
3270 TempDescriptor targ=fc.getArg(i);
3272 TypeDescriptor td=md.getParamType(i);
3274 output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
3276 output.print("(struct "+md.getParamType(i).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
3279 output.println("};");
3284 if (fc.getReturnTemp()!=null)
3285 output.print(generateTemp(fm,fc.getReturnTemp(),lb)+"=");
3287 /* Do we need to do virtual dispatch? */
3288 if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
3291 LocalityBinding fclb=locality.getBinding(lb, fc);
3292 output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
3294 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
3299 if (md.getReturnType().isClass()||md.getReturnType().isArray())
3300 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
3302 output.print(md.getReturnType().getSafeSymbol()+" ");
3303 output.print("(*)(");
3305 boolean printcomma=false;
3306 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3308 LocalityBinding fclb=locality.getBinding(lb, fc);
3309 output.print("struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
3311 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
3315 for(int i=0; i<objectparams.numPrimitives(); i++) {
3316 TempDescriptor temp=objectparams.getPrimitive(i);
3320 if (temp.getType().isClass()||temp.getType().isArray())
3321 output.print("struct " + temp.getType().getSafeSymbol()+" * ");
3323 output.print(temp.getType().getSafeSymbol());
3328 LocalityBinding fclb=locality.getBinding(lb, fc);
3329 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])");
3331 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
3335 boolean needcomma=false;
3336 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3337 output.print("&__parameterlist__");
3341 if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
3342 if (fc.getThis()!=null) {
3343 TypeDescriptor ptd=md.getThis().getType();
3346 if (ptd.isClass()&&!ptd.isArray())
3347 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
3348 output.print(generateTemp(fm,fc.getThis(),lb));
3353 for(int i=0; i<fc.numArgs(); i++) {
3354 Descriptor var=md.getParameter(i);
3355 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
3356 if (objectparams.isParamPrim(paramtemp)) {
3357 TempDescriptor targ=fc.getArg(i);
3361 TypeDescriptor ptd=md.getParamType(i);
3362 if (ptd.isClass()&&!ptd.isArray())
3363 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
3364 output.print(generateTemp(fm, targ,lb));
3368 output.println(");");
3369 output.println(" }");
3372 private boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
3373 Set subclasses=typeutil.getSubClasses(thiscd);
3374 if (subclasses==null)
3376 for(Iterator classit=subclasses.iterator(); classit.hasNext();) {
3377 ClassDescriptor cd=(ClassDescriptor)classit.next();
3378 Set possiblematches=cd.getMethodTable().getSet(md.getSymbol());
3379 for(Iterator matchit=possiblematches.iterator(); matchit.hasNext();) {
3380 MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
3381 if (md.matches(matchmd))
3388 private void generateFlatFieldNode(FlatMethod fm, LocalityBinding lb, FlatFieldNode ffn, PrintWriter output) {
3389 if (state.SINGLETM) {
3390 //single machine transactional memory case
3391 String field=ffn.getField().getSafeSymbol();
3392 String src=generateTemp(fm, ffn.getSrc(),lb);
3393 String dst=generateTemp(fm, ffn.getDst(),lb);
3395 output.println(dst+"="+ src +"->"+field+ ";");
3396 if (ffn.getField().getType().isPtr()&&locality.getAtomic(lb).get(ffn).intValue()>0&&
3397 locality.getNodePreTempInfo(lb, ffn).get(ffn.getSrc())!=LocalityAnalysis.SCRATCH) {
3398 if ((dc==null)||(!state.READSET&&dc.getNeedTrans(lb, ffn))||
3399 (state.READSET&&dc.getNeedWriteTrans(lb, ffn))) {
3400 output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));");
3401 } else if (state.READSET&&dc.getNeedTrans(lb, ffn)) {
3402 output.println("TRANSREADRD("+dst+", "+dst+");");
3405 } else if (state.DSM) {
3406 Integer status=locality.getNodePreTempInfo(lb,ffn).get(ffn.getSrc());
3407 if (status==LocalityAnalysis.GLOBAL) {
3408 String field=ffn.getField().getSafeSymbol();
3409 String src=generateTemp(fm, ffn.getSrc(),lb);
3410 String dst=generateTemp(fm, ffn.getDst(),lb);
3412 if (ffn.getField().getType().isPtr()) {
3414 //TODO: Uncomment this when we have runtime support
3415 //if (ffn.getSrc()==ffn.getDst()) {
3416 //output.println("{");
3417 //output.println("void * temp="+src+";");
3418 //output.println("if (temp&0x1) {");
3419 //output.println("temp=(void *) transRead(trans, (unsigned int) temp);");
3420 //output.println(src+"->"+field+"="+temp+";");
3421 //output.println("}");
3422 //output.println(dst+"=temp;");
3423 //output.println("}");
3425 output.println(dst+"="+ src +"->"+field+ ";");
3426 //output.println("if ("+dst+"&0x1) {");
3427 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
3428 //output.println(src+"->"+field+"="+src+"->"+field+";");
3429 //output.println("}");
3432 output.println(dst+"="+ src+"->"+field+";");
3434 } else if (status==LocalityAnalysis.LOCAL) {
3435 if (ffn.getField().getType().isPtr()&&
3436 ffn.getField().isGlobal()) {
3437 String field=ffn.getField().getSafeSymbol();
3438 String src=generateTemp(fm, ffn.getSrc(),lb);
3439 String dst=generateTemp(fm, ffn.getDst(),lb);
3440 output.println(dst+"="+ src +"->"+field+ ";");
3441 if (locality.getAtomic(lb).get(ffn).intValue()>0)
3442 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
3444 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
3445 } else if (status==LocalityAnalysis.EITHER) {
3446 //Code is reading from a null pointer
3447 output.println("if ("+generateTemp(fm, ffn.getSrc(),lb)+") {");
3448 output.println("#ifndef RAW");
3449 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
3450 output.println("#endif");
3451 //This should throw a suitable null pointer error
3452 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
3454 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
3456 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
3460 private void generateFlatSetFieldNode(FlatMethod fm, LocalityBinding lb, FlatSetFieldNode fsfn, PrintWriter output) {
3461 if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
3462 throw new Error("Can't set array length");
3463 if (state.SINGLETM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
3464 //Single Machine Transaction Case
3465 boolean srcptr=fsfn.getSrc().getType().isPtr();
3466 String src=generateTemp(fm,fsfn.getSrc(),lb);
3467 String dst=generateTemp(fm,fsfn.getDst(),lb);
3468 output.println("//"+srcptr+" "+fsfn.getSrc().getType().isNull());
3469 if (srcptr&&!fsfn.getSrc().getType().isNull()) {
3470 output.println("{");
3471 if ((dc==null)||dc.getNeedSrcTrans(lb, fsfn)&&
3472 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) {
3473 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3475 output.println("INTPTR srcoid=(INTPTR)"+src+";");
3478 if (wb.needBarrier(fsfn)&&
3479 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getDst())!=LocalityAnalysis.SCRATCH) {
3480 output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;");
3482 if (srcptr&!fsfn.getSrc().getType().isNull()) {
3483 output.println("*((unsigned INTPTR *)&("+dst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
3484 output.println("}");
3486 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3488 } else if (state.DSM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
3489 Integer statussrc=locality.getNodePreTempInfo(lb,fsfn).get(fsfn.getSrc());
3490 Integer statusdst=locality.getNodeTempInfo(lb).get(fsfn).get(fsfn.getDst());
3491 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
3493 String src=generateTemp(fm,fsfn.getSrc(),lb);
3494 String dst=generateTemp(fm,fsfn.getDst(),lb);
3496 output.println("{");
3497 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3499 if (statusdst.equals(LocalityAnalysis.GLOBAL)) {
3502 if (wb.needBarrier(fsfn))
3503 output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;");
3505 output.println("*((unsigned INTPTR *)&("+glbdst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
3507 output.println(glbdst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3508 } else if (statusdst.equals(LocalityAnalysis.LOCAL)) {
3509 /** Check if we need to copy */
3510 output.println("if(!"+dst+"->"+localcopystr+") {");
3511 /* Link object into list */
3512 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3513 output.println(revertptr+"=revertlist;");
3514 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
3515 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3517 output.println("COPY_OBJ("+dst+");");
3518 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
3519 output.println("revertlist=(struct ___Object___ *)"+dst+";");
3520 output.println("}");
3522 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
3524 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3525 } else if (statusdst.equals(LocalityAnalysis.EITHER)) {
3526 //writing to a null...bad
3527 output.println("if ("+dst+") {");
3528 output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}");
3530 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
3532 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3535 output.println("}");
3538 if (state.FASTCHECK) {
3539 String dst=generateTemp(fm, fsfn.getDst(),lb);
3540 output.println("if(!"+dst+"->"+localcopystr+") {");
3541 /* Link object into list */
3542 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
3543 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3545 output.println("COPY_OBJ("+dst+");");
3546 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
3547 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
3548 output.println("}");
3550 output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
3554 private void generateFlatElementNode(FlatMethod fm, LocalityBinding lb, FlatElementNode fen, PrintWriter output) {
3555 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
3558 if (elementtype.isArray()||elementtype.isClass())
3561 type=elementtype.getSafeSymbol()+" ";
3563 if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
3564 output.println("if ("+generateTemp(fm, fen.getIndex(),lb)+"< 0 | "+generateTemp(fm, fen.getIndex(),lb)+" >= "+generateTemp(fm,fen.getSrc(),lb) + "->___length___)");
3565 output.println("failedboundschk();");
3567 if (state.SINGLETM) {
3568 //Single machine transaction case
3569 String dst=generateTemp(fm, fen.getDst(),lb);
3570 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3572 if (elementtype.isPtr()&&locality.getAtomic(lb).get(fen).intValue()>0&&
3573 locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())!=LocalityAnalysis.SCRATCH) {
3574 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fen)||state.READSET&&dc.getNeedWriteTrans(lb, fen)) {
3575 output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));");
3576 } else if (state.READSET&&dc.getNeedTrans(lb, fen)) {
3577 output.println("TRANSREADRD("+dst+", "+dst+");");
3580 } else if (state.DSM) {
3581 Integer status=locality.getNodePreTempInfo(lb,fen).get(fen.getSrc());
3582 if (status==LocalityAnalysis.GLOBAL) {
3583 String dst=generateTemp(fm, fen.getDst(),lb);
3585 if (elementtype.isPtr()) {
3586 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3587 output.println("TRANSREAD("+dst+", "+dst+");");
3589 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3591 } else if (status==LocalityAnalysis.LOCAL) {
3592 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3593 } else if (status==LocalityAnalysis.EITHER) {
3594 //Code is reading from a null pointer
3595 output.println("if ("+generateTemp(fm, fen.getSrc(),lb)+") {");
3596 output.println("#ifndef RAW");
3597 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
3598 output.println("#endif");
3599 //This should throw a suitable null pointer error
3600 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3602 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
3604 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3608 private void generateFlatSetElementNode(FlatMethod fm, LocalityBinding lb, FlatSetElementNode fsen, PrintWriter output) {
3609 //TODO: need dynamic check to make sure this assignment is actually legal
3610 //Because Object[] could actually be something more specific...ie. Integer[]
3612 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
3615 if (elementtype.isArray()||elementtype.isClass())
3618 type=elementtype.getSafeSymbol()+" ";
3620 if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
3621 output.println("if ("+generateTemp(fm, fsen.getIndex(),lb)+"< 0 | "+generateTemp(fm, fsen.getIndex(),lb)+" >= "+generateTemp(fm,fsen.getDst(),lb) + "->___length___)");
3622 output.println("failedboundschk();");
3625 if (state.SINGLETM && locality.getAtomic(lb).get(fsen).intValue()>0) {
3626 //Transaction set element case
3627 if (wb.needBarrier(fsen)&&
3628 locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH) {
3629 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___objstatus___))|=DIRTY;");
3631 if (fsen.getSrc().getType().isPtr()&&!fsen.getSrc().getType().isNull()) {
3632 output.println("{");
3633 String src=generateTemp(fm, fsen.getSrc(), lb);
3634 if ((dc==null)||dc.getNeedSrcTrans(lb, fsen)&&
3635 locality.getNodePreTempInfo(lb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) {
3636 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3638 output.println("INTPTR srcoid=(INTPTR)"+src+";");
3640 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
3641 output.println("}");
3643 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
3645 } else if (state.DSM && locality.getAtomic(lb).get(fsen).intValue()>0) {
3646 Integer statussrc=locality.getNodePreTempInfo(lb,fsen).get(fsen.getSrc());
3647 Integer statusdst=locality.getNodePreTempInfo(lb,fsen).get(fsen.getDst());
3648 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
3649 boolean dstglobal=statusdst==LocalityAnalysis.GLOBAL;
3650 boolean dstlocal=statusdst==LocalityAnalysis.LOCAL;
3653 if (wb.needBarrier(fsen))
3654 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___localcopy___))|=DIRTY;");
3655 } else if (dstlocal) {
3656 /** Check if we need to copy */
3657 String dst=generateTemp(fm, fsen.getDst(),lb);
3658 output.println("if(!"+dst+"->"+localcopystr+") {");
3659 /* Link object into list */
3660 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3661 output.println(revertptr+"=revertlist;");
3662 if ((GENERATEPRECISEGC) || this.state.MULTICOREGC)
3663 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3665 output.println("COPY_OBJ("+dst+");");
3666 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
3667 output.println("revertlist=(struct ___Object___ *)"+dst+";");
3668 output.println("}");
3669 } else throw new Error("Unknown array type");
3671 output.println("{");
3672 String src=generateTemp(fm, fsen.getSrc(), lb);
3673 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3674 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
3675 output.println("}");
3677 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
3680 if (state.FASTCHECK) {
3681 String dst=generateTemp(fm, fsen.getDst(),lb);
3682 output.println("if(!"+dst+"->"+localcopystr+") {");
3683 /* Link object into list */
3684 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
3685 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3687 output.println("COPY_OBJ("+dst+");");
3688 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
3689 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
3690 output.println("}");
3692 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
3696 protected void generateFlatNew(FlatMethod fm, LocalityBinding lb, FlatNew fn, PrintWriter output) {
3697 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
3698 //Stash pointer in case of GC
3699 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3700 output.println(revertptr+"=revertlist;");
3702 if (state.SINGLETM) {
3703 if (fn.getType().isArray()) {
3704 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
3705 if (locality.getAtomic(lb).get(fn).intValue()>0) {
3706 //inside transaction
3707 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3709 //outside transaction
3710 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3713 if (locality.getAtomic(lb).get(fn).intValue()>0) {
3714 //inside transaction
3715 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
3717 //outside transaction
3718 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
3721 } else if (fn.getType().isArray()) {
3722 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
3723 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
3724 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3725 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3726 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3728 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3731 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
3732 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");");
3733 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3734 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
3736 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
3739 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
3740 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3741 String dst=generateTemp(fm,fn.getDst(),lb);
3742 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
3743 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
3744 output.println("revertlist=(struct ___Object___ *)"+dst+";");
3746 if (state.FASTCHECK) {
3747 String dst=generateTemp(fm,fn.getDst(),lb);
3748 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
3749 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
3750 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
3754 private void generateFlatTagDeclaration(FlatMethod fm, LocalityBinding lb, FlatTagDeclaration fn, PrintWriter output) {
3755 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3756 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
3758 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+state.getTagId(fn.getType())+");");
3762 private void generateFlatOpNode(FlatMethod fm, LocalityBinding lb, FlatOpNode fon, PrintWriter output) {
3763 if (fon.getRight()!=null) {
3764 if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
3765 if (fon.getLeft().getType().isLong())
3766 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
3768 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned int)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
3770 } else if (dc!=null) {
3771 output.print(generateTemp(fm, fon.getDest(),lb)+" = ");
3772 if (dc.getNeedLeftSrcTrans(lb, fon))
3773 output.print("("+generateTemp(fm, fon.getLeft(),lb)+"!=NULL?"+generateTemp(fm, fon.getLeft(),lb)+"->"+oidstr+":NULL)");
3775 output.print(generateTemp(fm, fon.getLeft(),lb));
3776 output.print(fon.getOp().toString());
3777 if (dc.getNeedRightSrcTrans(lb, fon))
3778 output.println("("+generateTemp(fm, fon.getRight(),lb)+"!=NULL?"+generateTemp(fm, fon.getRight(),lb)+"->"+oidstr+":NULL);");
3780 output.println(generateTemp(fm,fon.getRight(),lb)+";");
3782 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+fon.getOp().toString()+generateTemp(fm,fon.getRight(),lb)+";");
3783 } else if (fon.getOp().getOp()==Operation.ASSIGN)
3784 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
3785 else if (fon.getOp().getOp()==Operation.UNARYPLUS)
3786 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
3787 else if (fon.getOp().getOp()==Operation.UNARYMINUS)
3788 output.println(generateTemp(fm, fon.getDest(),lb)+" = -"+generateTemp(fm, fon.getLeft(),lb)+";");
3789 else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
3790 output.println(generateTemp(fm, fon.getDest(),lb)+" = !"+generateTemp(fm, fon.getLeft(),lb)+";");
3791 else if (fon.getOp().getOp()==Operation.COMP)
3792 output.println(generateTemp(fm, fon.getDest(),lb)+" = ~"+generateTemp(fm, fon.getLeft(),lb)+";");
3793 else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
3794 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+"->fses==NULL;");
3796 output.println(generateTemp(fm, fon.getDest(),lb)+fon.getOp().toString()+generateTemp(fm, fon.getLeft(),lb)+";");
3799 private void generateFlatCastNode(FlatMethod fm, LocalityBinding lb, FlatCastNode fcn, PrintWriter output) {
3800 /* TODO: Do type check here */
3801 if (fcn.getType().isArray()) {
3802 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
3803 } else if (fcn.getType().isClass())
3804 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
3806 output.println(generateTemp(fm,fcn.getDst(),lb)+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc(),lb)+";");
3809 private void generateFlatLiteralNode(FlatMethod fm, LocalityBinding lb, FlatLiteralNode fln, PrintWriter output) {
3810 if (fln.getValue()==null)
3811 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
3812 else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
3813 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3814 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
3815 //Stash pointer in case of GC
3816 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3817 output.println(revertptr+"=revertlist;");
3819 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
3820 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
3821 //Stash pointer in case of GC
3822 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3823 output.println("revertlist="+revertptr+";");
3826 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
3828 } else if (fln.getType().isBoolean()) {
3829 if (((Boolean)fln.getValue()).booleanValue())
3830 output.println(generateTemp(fm, fln.getDst(),lb)+"=1;");
3832 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
3833 } else if (fln.getType().isChar()) {
3834 String st=FlatLiteralNode.escapeString(fln.getValue().toString());
3835 output.println(generateTemp(fm, fln.getDst(),lb)+"='"+st+"';");
3836 } else if (fln.getType().isLong()) {
3837 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+"LL;");
3839 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+";");
3842 protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) {
3843 if (frn.getReturnTemp()!=null) {
3844 if (frn.getReturnTemp().getType().isPtr())
3845 output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";");
3847 output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";");
3849 output.println("return;");
3853 protected void generateStoreFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
3854 output.println("STOREANDBRANCH(!"+generateTemp(fm, fcb.getTest(),lb)+", "+label+");");
3857 protected void generateFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
3858 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") goto "+label+";");
3861 /** This method generates header information for the method or
3862 * task referenced by the Descriptor des. */
3863 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) {
3864 generateHeader(fm, lb, des, output, false);
3867 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output, boolean addSESErecord) {
3869 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : des);
3870 MethodDescriptor md=null;
3871 TaskDescriptor task=null;
3872 if (des instanceof MethodDescriptor)
3873 md=(MethodDescriptor) des;
3875 task=(TaskDescriptor) des;
3877 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
3879 if (md!=null&&md.getReturnType()!=null) {
3880 if (md.getReturnType().isClass()||md.getReturnType().isArray())
3881 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
3883 output.print(md.getReturnType().getSafeSymbol()+" ");
3885 //catch the constructor case
3886 output.print("void ");
3888 if (state.DSM||state.SINGLETM) {
3889 output.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
3891 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
3893 output.print(task.getSafeSymbol()+"(");
3895 boolean printcomma=false;
3896 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3898 if (state.DSM||state.SINGLETM) {
3899 output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
3901 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
3903 output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
3909 for(int i=0; i<objectparams.numPrimitives(); i++) {
3910 TempDescriptor temp=objectparams.getPrimitive(i);
3914 if (temp.getType().isClass()||temp.getType().isArray())
3915 output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
3917 output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
3919 output.println(") {");
3920 } else if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
3921 /* Imprecise Task */
3922 output.println("void * parameterarray[]) {");
3923 /* Unpack variables */
3924 for(int i=0; i<objectparams.numPrimitives(); i++) {
3925 TempDescriptor temp=objectparams.getPrimitive(i);
3926 output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
3928 for(int i=0; i<fm.numTags(); i++) {
3929 TempDescriptor temp=fm.getTag(i);
3930 int offset=i+objectparams.numPrimitives();
3931 output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
3934 if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
3935 maxtaskparams=objectparams.numPrimitives()+fm.numTags();
3936 } else output.println(") {");
3939 public void generateFlatFlagActionNode(FlatMethod fm, LocalityBinding lb, FlatFlagActionNode ffan, PrintWriter output) {
3940 output.println("/* FlatFlagActionNode */");
3943 /* Process tag changes */
3944 Relation tagsettable=new Relation();
3945 Relation tagcleartable=new Relation();
3947 Iterator tagsit=ffan.getTempTagPairs();
3948 while (tagsit.hasNext()) {
3949 TempTagPair ttp=(TempTagPair) tagsit.next();
3950 TempDescriptor objtmp=ttp.getTemp();
3951 TagDescriptor tag=ttp.getTag();
3952 TempDescriptor tagtmp=ttp.getTagTemp();
3953 boolean tagstatus=ffan.getTagChange(ttp);
3955 tagsettable.put(objtmp, tagtmp);
3957 tagcleartable.put(objtmp, tagtmp);
3962 Hashtable flagandtable=new Hashtable();
3963 Hashtable flagortable=new Hashtable();
3965 /* Process flag changes */
3966 Iterator flagsit=ffan.getTempFlagPairs();
3967 while(flagsit.hasNext()) {
3968 TempFlagPair tfp=(TempFlagPair)flagsit.next();
3969 TempDescriptor temp=tfp.getTemp();
3970 Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
3971 FlagDescriptor flag=tfp.getFlag();
3973 //Newly allocate objects that don't set any flags case
3974 if (flagortable.containsKey(temp)) {
3978 flagortable.put(temp,new Integer(mask));
3980 int flagid=1<<((Integer)flagtable.get(flag)).intValue();
3981 boolean flagstatus=ffan.getFlagChange(tfp);
3984 if (flagortable.containsKey(temp)) {
3985 mask=((Integer)flagortable.get(temp)).intValue();
3988 flagortable.put(temp,new Integer(mask));
3990 int mask=0xFFFFFFFF;
3991 if (flagandtable.containsKey(temp)) {
3992 mask=((Integer)flagandtable.get(temp)).intValue();
3994 mask&=(0xFFFFFFFF^flagid);
3995 flagandtable.put(temp,new Integer(mask));
4001 HashSet flagtagset=new HashSet();
4002 flagtagset.addAll(flagortable.keySet());
4003 flagtagset.addAll(flagandtable.keySet());
4004 flagtagset.addAll(tagsettable.keySet());
4005 flagtagset.addAll(tagcleartable.keySet());
4007 Iterator ftit=flagtagset.iterator();
4008 while(ftit.hasNext()) {
4009 TempDescriptor temp=(TempDescriptor)ftit.next();
4012 Set tagtmps=tagcleartable.get(temp);
4013 if (tagtmps!=null) {
4014 Iterator tagit=tagtmps.iterator();
4015 while(tagit.hasNext()) {
4016 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
4017 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
4018 output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4020 output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4024 tagtmps=tagsettable.get(temp);
4025 if (tagtmps!=null) {
4026 Iterator tagit=tagtmps.iterator();
4027 while(tagit.hasNext()) {
4028 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
4029 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
4030 output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4032 output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp, lb)+", "+generateTemp(fm,tagtmp, lb)+");");
4037 int andmask=0xFFFFFFF;
4039 if (flagortable.containsKey(temp))
4040 ormask=((Integer)flagortable.get(temp)).intValue();
4041 if (flagandtable.containsKey(temp))
4042 andmask=((Integer)flagandtable.get(temp)).intValue();
4043 generateFlagOrAnd(ffan, fm, lb, temp, output, ormask, andmask);
4044 generateObjectDistribute(ffan, fm, lb, temp, output);
4048 protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp,
4049 PrintWriter output, int ormask, int andmask) {
4050 if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
4051 output.println("flagorandinit("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
4053 output.println("flagorand("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
4057 protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, PrintWriter output) {
4058 output.println("enqueueObject("+generateTemp(fm, temp, lb)+");");
4061 void generateOptionalHeader(PrintWriter headers) {
4064 headers.println("#include \"task.h\"\n\n");
4065 headers.println("#ifndef _OPTIONAL_STRUCT_");
4066 headers.println("#define _OPTIONAL_STRUCT_");
4068 //STRUCT PREDICATEMEMBER
4069 headers.println("struct predicatemember{");
4070 headers.println("int type;");
4071 headers.println("int numdnfterms;");
4072 headers.println("int * flags;");
4073 headers.println("int numtags;");
4074 headers.println("int * tags;\n};\n\n");
4076 //STRUCT OPTIONALTASKDESCRIPTOR
4077 headers.println("struct optionaltaskdescriptor{");
4078 headers.println("struct taskdescriptor * task;");
4079 headers.println("int index;");
4080 headers.println("int numenterflags;");
4081 headers.println("int * enterflags;");
4082 headers.println("int numpredicatemembers;");
4083 headers.println("struct predicatemember ** predicatememberarray;");
4084 headers.println("};\n\n");
4086 //STRUCT TASKFAILURE
4087 headers.println("struct taskfailure {");
4088 headers.println("struct taskdescriptor * task;");
4089 headers.println("int index;");
4090 headers.println("int numoptionaltaskdescriptors;");
4091 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
4093 //STRUCT FSANALYSISWRAPPER
4094 headers.println("struct fsanalysiswrapper{");
4095 headers.println("int flags;");
4096 headers.println("int numtags;");
4097 headers.println("int * tags;");
4098 headers.println("int numtaskfailures;");
4099 headers.println("struct taskfailure ** taskfailurearray;");
4100 headers.println("int numoptionaltaskdescriptors;");
4101 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
4103 //STRUCT CLASSANALYSISWRAPPER
4104 headers.println("struct classanalysiswrapper{");
4105 headers.println("int type;");
4106 headers.println("int numotd;");
4107 headers.println("struct optionaltaskdescriptor ** otdarray;");
4108 headers.println("int numfsanalysiswrappers;");
4109 headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
4111 headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
4113 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
4114 while(taskit.hasNext()) {
4115 TaskDescriptor td=(TaskDescriptor)taskit.next();
4116 headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
4121 //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
4122 int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
4123 int predicateindex = 0;
4124 //iterate through the classes concerned by the predicate
4125 Set c_vard = predicate.vardescriptors;
4126 Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
4129 for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext();) {
4130 VarDescriptor vard = (VarDescriptor)vard_it.next();
4131 TypeDescriptor typed = vard.getType();
4133 //generate for flags
4134 HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
4135 output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4137 if (fen_hashset!=null) {
4138 for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext();) {
4139 FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
4141 DNFFlag dflag=fen.getDNF();
4142 numberterms+=dflag.size();
4144 Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
4146 for(int j=0; j<dflag.size(); j++) {
4148 output.println(",");
4149 Vector term=dflag.get(j);
4152 for(int k=0; k<term.size(); k++) {
4153 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
4154 FlagDescriptor fd=dfa.getFlag();
4155 boolean negated=dfa.getNegated();
4156 int flagid=1<<((Integer)flags.get(fd)).intValue();
4161 output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
4166 output.println("};\n");
4169 TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
4170 output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4173 for(int j=0; j<tagel.numTags(); j++) {
4175 output.println(",");
4176 TempDescriptor tmp=tagel.getTemp(j);
4177 if (!slotnumber.containsKey(tmp)) {
4178 Integer slotint=new Integer(current_slot++);
4179 slotnumber.put(tmp,slotint);
4181 int slot=slotnumber.get(tmp).intValue();
4182 output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
4184 numtags = tagel.numTags();
4186 output.println("};");
4188 //store the result into a predicatemember struct
4189 output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
4190 output.println("/*type*/"+typed.getClassDesc().getId()+",");
4191 output.println("/* number of dnf terms */"+numberterms+",");
4192 output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4193 output.println("/* number of tag */"+numtags+",");
4194 output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4195 output.println("};\n");
4200 //generate an array that stores the entire predicate
4201 output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4202 for( int j = 0; j<predicateindex; j++) {
4203 if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4204 else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4206 output.println("};\n");
4207 return predicateindex;
4211 void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
4212 generateOptionalHeader(headers);
4214 output.println("#include \"optionalstruct.h\"\n\n");
4215 output.println("#include \"stdlib.h\"\n");
4217 HashSet processedcd = new HashSet();
4219 Enumeration e = safeexecution.keys();
4220 while (e.hasMoreElements()) {
4223 ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
4224 Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp); //will be used several times
4226 //Generate the struct of optionals
4227 Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
4228 numotd = c_otd.size();
4229 if(maxotd<numotd) maxotd = numotd;
4230 if( !c_otd.isEmpty() ) {
4231 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
4232 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
4234 //generate the int arrays for the predicate
4235 Predicate predicate = otd.predicate;
4236 int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
4237 TreeSet<Integer> fsset=new TreeSet<Integer>();
4238 //iterate through possible FSes corresponding to
4239 //the state when entering
4241 for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext();) {
4242 FlagState fs = (FlagState)fses.next();
4244 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
4245 FlagDescriptor flagd = (FlagDescriptor)flags.next();
4246 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
4249 fsset.add(new Integer(flagid));
4250 //tag information not needed because tag
4251 //changes are not tolerated.
4254 output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4255 boolean needcomma=false;
4256 for(Iterator<Integer> it=fsset.iterator(); it.hasNext();) {
4259 output.println(it.next());
4262 output.println("};\n");
4265 //generate optionaltaskdescriptor that actually
4266 //includes exit fses, predicate and the task
4268 output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
4269 output.println("&task_"+otd.td.getSafeSymbol()+",");
4270 output.println("/*index*/"+otd.getIndex()+",");
4271 output.println("/*number of enter flags*/"+fsset.size()+",");
4272 output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4273 output.println("/*number of members */"+predicateindex+",");
4274 output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4275 output.println("};\n");
4279 // if there are no optionals, there is no need to build the rest of the struct
4281 output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
4282 c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
4283 if( !c_otd.isEmpty() ) {
4284 boolean needcomma=false;
4285 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
4286 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
4288 output.println(",");
4290 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4293 output.println("};\n");
4295 //get all the possible flagstates reachable by an object
4296 Hashtable hashtbtemp = safeexecution.get(cdtemp);
4298 TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
4299 fsts.addAll(hashtbtemp.keySet());
4300 for(Iterator fsit=fsts.iterator(); fsit.hasNext();) {
4301 FlagState fs = (FlagState)fsit.next();
4304 //get the set of OptionalTaskDescriptors corresponding
4305 HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
4306 //iterate through the OptionalTaskDescriptors and
4307 //store the pointers to the optionals struct (see on
4308 //top) into an array
4310 output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
4311 for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext();) {
4312 OptionalTaskDescriptor mm = mos.next();
4314 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
4316 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4319 output.println("};\n");
4321 //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
4324 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
4325 FlagDescriptor flagd = (FlagDescriptor)flags.next();
4326 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
4330 //process tag information
4333 boolean first = true;
4334 Enumeration tag_enum = fs.getTags();
4335 output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
4336 while(tag_enum.hasMoreElements()) {
4338 TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
4342 output.println(", ");
4343 output.println("/*tagid*/"+state.getTagId(tagd));
4345 output.println("};");
4347 Set<TaskIndex> tiset=sa.getTaskIndex(fs);
4348 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
4349 TaskIndex ti=itti.next();
4353 Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
4355 output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
4356 boolean needcomma=false;
4357 for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext();) {
4358 OptionalTaskDescriptor otd=otdit.next();
4362 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4364 output.println("};");
4366 output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
4367 output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
4368 output.print(ti.getIndex()+", ");
4369 output.print(otdset.size()+", ");
4370 output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
4371 output.println("};");
4374 tiset=sa.getTaskIndex(fs);
4375 boolean needcomma=false;
4377 output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
4378 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
4379 TaskIndex ti=itti.next();
4380 if (ti.isRuntime()) {
4387 output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
4389 output.println("};\n");
4391 //Store the result in fsanalysiswrapper
4393 output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
4394 output.println("/*flag*/"+flagid+",");
4395 output.println("/* number of tags*/"+tagcounter+",");
4396 output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
4397 output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
4398 output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
4399 output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
4400 output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
4401 output.println("};\n");
4405 //Build the array of fsanalysiswrappers
4406 output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
4407 boolean needcomma=false;
4408 for(int i = 0; i<fscounter; i++) {
4409 if (needcomma) output.print(",");
4410 output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
4413 output.println("};");
4415 //Build the classanalysiswrapper referring to the previous array
4416 output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
4417 output.println("/*type*/"+cdtemp.getId()+",");
4418 output.println("/*numotd*/"+numotd+",");
4419 output.println("otdarray"+cdtemp.getSafeSymbol()+",");
4420 output.println("/* number of fsanalysiswrappers */"+fscounter+",");
4421 output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
4422 processedcd.add(cdtemp);
4425 //build an array containing every classes for which code has been build
4426 output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
4427 for(int i=0; i<state.numClasses(); i++) {
4428 ClassDescriptor cn=cdarray[i];
4431 if (processedcd.contains(cn))
4432 output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
4434 output.print("NULL");
4436 output.println("};");
4438 output.println("#define MAXOTD "+maxotd);
4439 headers.println("#endif");
4442 public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
4443 Relation r=new Relation();
4444 for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext();) {
4445 OptionalTaskDescriptor otd=otdit.next();
4446 TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
4450 LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
4451 for(Iterator it=r.keySet().iterator(); it.hasNext();) {
4452 Set s=r.get(it.next());
4453 for(Iterator it2=s.iterator(); it2.hasNext();) {
4454 OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
4462 protected void outputTransCode(PrintWriter output) {