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()+";");
1660 /* Check to see if we need to do a GC if this is a
1661 * multi-threaded program...*/
1663 if (((state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
1664 || this.state.MULTICOREGC) {
1665 //Don't bother if we aren't in recursive methods...The loops case will catch it
1666 if (callgraph.getAllMethods(md).contains(md)) {
1667 if (state.DSM&&lb.isAtomic())
1668 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
1669 else if (this.state.MULTICOREGC) {
1670 output.println("if(gcflag) gc("+localsprefixaddr+");");
1672 output.println("if (needtocollect) checkcollect("+localsprefixaddr+");");
1676 generateCode(fm.getNext(0), fm, lb, null, output, true);
1678 output.println("}\n\n");
1682 protected void initializeSESE( FlatSESEEnterNode fsen ) {
1684 FlatMethod fm = fsen.getfmEnclosing();
1685 MethodDescriptor md = fm.getMethod();
1686 ClassDescriptor cn = md.getClassDesc();
1689 // Creates bogus method descriptor to index into tables
1690 Modifiers modBogus = new Modifiers();
1691 MethodDescriptor mdBogus =
1692 new MethodDescriptor( modBogus,
1693 new TypeDescriptor( TypeDescriptor.VOID ),
1694 "sese_"+fsen.getPrettyIdentifier()+fsen.getIdentifier()
1697 mdBogus.setClassDesc( fsen.getcdEnclosing() );
1698 FlatMethod fmBogus = new FlatMethod( mdBogus, null );
1699 fsen.setfmBogus( fmBogus );
1700 fsen.setmdBogus( mdBogus );
1702 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1703 inSetAndOutSet.addAll( fsen.getInVarSet() );
1704 inSetAndOutSet.addAll( fsen.getOutVarSet() );
1706 // Build paramsobj for bogus method descriptor
1707 ParamsObject objectparams = new ParamsObject( mdBogus, tag++ );
1708 paramstable.put( mdBogus, objectparams );
1710 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1711 while( itr.hasNext() ) {
1712 TempDescriptor temp = itr.next();
1713 TypeDescriptor type = temp.getType();
1714 if( type.isPtr() ) {
1715 objectparams.addPtr( temp );
1717 objectparams.addPrim( temp );
1721 // Build normal temp object for bogus method descriptor
1722 TempObject objecttemps = new TempObject( objectparams, mdBogus, tag++ );
1723 tempstable.put( mdBogus, objecttemps );
1725 for(Iterator nodeit=fsen.getNodeSet().iterator(); nodeit.hasNext();) {
1726 FlatNode fn=(FlatNode)nodeit.next();
1727 TempDescriptor[] writes=fn.writesTemps();
1728 for(int i=0; i<writes.length; i++) {
1729 TempDescriptor temp=writes[i];
1730 TypeDescriptor type=temp.getType();
1731 if (type.isPtr()&&GENERATEPRECISEGC) {
1732 objecttemps.addPtr(temp);
1734 objecttemps.addPrim(temp);
1740 protected void generateMethodSESE(FlatSESEEnterNode fsen,
1742 PrintWriter outputStructs,
1743 PrintWriter outputMethHead,
1744 PrintWriter outputMethods
1747 ParamsObject objectparams = (ParamsObject) paramstable.get( fsen.getmdBogus() );
1749 TempObject objecttemps = (TempObject) tempstable.get( fsen.getmdBogus() );
1751 // generate locals structure
1752 outputStructs.println("struct "+fsen.getcdEnclosing().getSafeSymbol()+fsen.getmdBogus().getSafeSymbol()+"_"+fsen.getmdBogus().getSafeMethodDescriptor()+"_locals {");
1753 outputStructs.println(" INTPTR size;");
1754 outputStructs.println(" void * next;");
1755 for(int i=0; i<objecttemps.numPointers(); i++) {
1756 TempDescriptor temp=objecttemps.getPointer(i);
1757 if (temp.getType().isNull())
1758 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
1760 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1762 outputStructs.println("};\n");
1765 // generate the SESE record structure
1766 outputStructs.println(fsen.getSESErecordName()+" {");
1768 // data common to any SESE, and it must be placed first so
1769 // a module that doesn't know what kind of SESE record this
1770 // is can cast the pointer to a common struct
1771 outputStructs.println(" SESEcommon common;");
1773 // then garbage list stuff
1774 outputStructs.println(" INTPTR size;");
1775 outputStructs.println(" void * next;");
1777 // in-set source tracking
1778 // in-vars that are READY come from parent, don't need anything
1779 // stuff STATIC needs a custom SESE pointer for each age pair
1780 Iterator<SESEandAgePair> itrStaticInVarSrcs = fsen.getStaticInVarSrcs().iterator();
1781 while( itrStaticInVarSrcs.hasNext() ) {
1782 SESEandAgePair srcPair = itrStaticInVarSrcs.next();
1783 outputStructs.println(" "+srcPair.getSESE().getSESErecordName()+"* "+srcPair+";");
1786 // DYNAMIC stuff needs a source SESE ptr and offset
1787 Iterator<TempDescriptor> itrDynInVars = fsen.getDynamicInVarSet().iterator();
1788 while( itrDynInVars.hasNext() ) {
1789 TempDescriptor dynInVar = itrDynInVars.next();
1790 outputStructs.println(" void* "+dynInVar+"_srcSESE;");
1791 outputStructs.println(" int "+dynInVar+"_srcOffset;");
1794 // space for all in and out set primitives
1795 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1796 inSetAndOutSet.addAll( fsen.getInVarSet() );
1797 inSetAndOutSet.addAll( fsen.getOutVarSet() );
1799 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
1801 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1802 while( itr.hasNext() ) {
1803 TempDescriptor temp = itr.next();
1804 TypeDescriptor type = temp.getType();
1805 if( !type.isPtr() ) {
1806 inSetAndOutSetPrims.add( temp );
1810 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
1811 while( itrPrims.hasNext() ) {
1812 TempDescriptor temp = itrPrims.next();
1813 TypeDescriptor type = temp.getType();
1814 outputStructs.println(" "+temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol()+";");
1817 for(int i=0; i<objectparams.numPointers(); i++) {
1818 TempDescriptor temp=objectparams.getPointer(i);
1819 if (temp.getType().isNull())
1820 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
1822 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1825 outputStructs.println("};\n");
1828 // write method declaration to header file
1829 outputMethHead.print("void ");
1830 outputMethHead.print(fsen.getSESEmethodName()+"(");
1831 outputMethHead.print(fsen.getSESErecordName()+"* "+paramsprefix);
1832 outputMethHead.println(");\n");
1835 generateFlatMethodSESE( fsen.getfmBogus(),
1836 fsen.getcdEnclosing(),
1842 private void generateFlatMethodSESE(FlatMethod fm,
1844 FlatSESEEnterNode fsen,
1845 FlatSESEExitNode seseExit,
1849 MethodDescriptor md=fm.getMethod();
1851 output.print("void ");
1852 output.print(fsen.getSESEmethodName()+"(");
1853 output.print(fsen.getSESErecordName()+"* "+paramsprefix);
1854 output.println("){\n");
1856 TempObject objecttemp=(TempObject) tempstable.get(md);
1858 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1859 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1860 output.print(objecttemp.numPointers()+",");
1861 output.print("(void*) &("+paramsprefix+"->size)");
1862 for(int j=0; j<objecttemp.numPointers(); j++)
1863 output.print(", NULL");
1864 output.println("};");
1867 output.println(" /* regular local primitives */");
1868 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1869 TempDescriptor td=objecttemp.getPrimitive(i);
1870 TypeDescriptor type=td.getType();
1872 output.println(" void * "+td.getSafeSymbol()+";");
1873 else if (type.isClass()||type.isArray())
1874 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1876 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1880 // declare variables for naming static SESE's
1881 output.println(" /* static SESE names */");
1882 Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
1883 while( pItr.hasNext() ) {
1884 SESEandAgePair p = pItr.next();
1885 output.println(" void* "+p+";");
1888 // declare variables for tracking dynamic sources
1889 output.println(" /* dynamic variable sources */");
1890 Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
1891 while( dynSrcItr.hasNext() ) {
1892 TempDescriptor dynSrcVar = dynSrcItr.next();
1893 output.println(" void* "+dynSrcVar+"_srcSESE;");
1894 output.println(" int "+dynSrcVar+"_srcOffset;");
1897 // declare local temps for in-set primitives, and if it is
1898 // a ready-source variable, get the value from the record
1899 output.println(" /* local temps for in-set primitives */");
1900 Iterator<TempDescriptor> itrInSet = fsen.getInVarSet().iterator();
1901 while( itrInSet.hasNext() ) {
1902 TempDescriptor temp = itrInSet.next();
1903 TypeDescriptor type = temp.getType();
1904 if( !type.isPtr() ) {
1905 if( fsen.getReadyInVarSet().contains( temp ) ) {
1906 output.println(" "+type+" "+temp+" = "+paramsprefix+"->"+temp+";");
1908 output.println(" "+type+" "+temp+";");
1913 // declare local temps for out-set primitives if its not already
1914 // in the in-set, and it's value will get written so no problem
1915 output.println(" /* local temp for out-set prim, not already in the in-set */");
1916 Iterator<TempDescriptor> itrOutSet = fsen.getOutVarSet().iterator();
1917 while( itrOutSet.hasNext() ) {
1918 TempDescriptor temp = itrOutSet.next();
1919 TypeDescriptor type = temp.getType();
1920 if( !type.isPtr() && !fsen.getInVarSet().contains( temp ) ) {
1921 output.println(" "+type+" "+temp+";");
1925 // copy in-set into place, ready vars were already
1926 // copied when the SESE was issued
1927 Iterator<TempDescriptor> tempItr;
1929 // static vars are from a known SESE
1930 tempItr = fsen.getStaticInVarSet().iterator();
1931 while( tempItr.hasNext() ) {
1932 TempDescriptor temp = tempItr.next();
1933 VariableSourceToken vst = fsen.getStaticInVarSrc( temp );
1934 SESEandAgePair srcPair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
1936 // can't grab something from this source until it is done
1937 output.println(" {");
1938 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+srcPair+";" );
1939 output.println(" pthread_mutex_lock( &(com->lock) );");
1940 output.println(" while( com->doneExecuting == FALSE ) {");
1941 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
1942 output.println(" }");
1943 output.println(" pthread_mutex_unlock( &(com->lock) );");
1945 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
1946 " = "+paramsprefix+"->"+srcPair+"->"+vst.getAddrVar()+";");
1948 output.println(" }");
1951 // dynamic vars come from an SESE and src
1952 tempItr = fsen.getDynamicInVarSet().iterator();
1953 while( tempItr.hasNext() ) {
1954 TempDescriptor temp = tempItr.next();
1955 TypeDescriptor type = temp.getType();
1957 // go grab it from the SESE source
1958 output.println(" if( "+paramsprefix+"->"+temp+"_srcSESE != NULL ) {");
1960 // gotta wait until the source is done
1961 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+temp+"_srcSESE;" );
1962 output.println(" pthread_mutex_lock( &(com->lock) );");
1963 output.println(" while( com->doneExecuting == FALSE ) {");
1964 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
1965 output.println(" }");
1966 output.println(" pthread_mutex_unlock( &(com->lock) );");
1969 if( type.isNull() ) {
1971 } else if( type.isClass() || type.isArray() ) {
1972 typeStr = "struct "+type.getSafeSymbol()+"*";
1974 typeStr = type.getSafeSymbol();
1977 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
1978 " = *(("+typeStr+"*) ("+
1979 paramsprefix+"->"+temp+"_srcSESE + "+
1980 paramsprefix+"->"+temp+"_srcOffset));");
1982 // or if the source was our parent, its in the record to grab
1983 output.println(" } else {");
1984 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
1985 " = "+paramsprefix+"->"+temp+";");
1986 output.println(" }");
1989 // Check to see if we need to do a GC if this is a
1990 // multi-threaded program...
1991 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1992 //Don't bother if we aren't in recursive methods...The loops case will catch it
1993 if (callgraph.getAllMethods(md).contains(md)) {
1994 if(this.state.MULTICOREGC) {
1995 output.println("if(gcflag) gc("+localsprefixaddr+");");
1997 output.println("if (needtocollect) checkcollect("+localsprefixaddr+");");
2002 HashSet<FlatNode> exitset=new HashSet<FlatNode>();
2003 exitset.add(seseExit);
2006 generateCode(fsen.getNext(0), fm, null, exitset, output, true);
2008 output.println("}\n\n");
2012 // when a new mlp thread is created for an issued SESE, it is started
2013 // by running this method which blocks on a cond variable until
2014 // it is allowed to transition to execute. Then a case statement
2015 // allows it to invoke the method with the proper SESE body, and after
2016 // exiting the SESE method, executes proper SESE exit code before the
2017 // thread can be destroyed
2018 private void generateSESEinvocationMethod(PrintWriter outmethodheader,
2019 PrintWriter outmethod
2022 outmethodheader.println("void* invokeSESEmethod( void* seseRecord );");
2023 outmethod.println( "void* invokeSESEmethod( void* seseRecord ) {");
2024 outmethod.println( " int status;");
2025 outmethod.println( " char errmsg[128];");
2027 // generate a case for each SESE class that can be invoked
2028 outmethod.println( " switch( *((int*)seseRecord) ) {");
2029 outmethod.println( " ");
2030 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
2031 FlatSESEEnterNode fsen = seseit.next();
2033 outmethod.println( " /* "+fsen.getPrettyIdentifier()+" */");
2034 outmethod.println( " case "+fsen.getIdentifier()+":");
2035 outmethod.println( " "+fsen.getSESEmethodName()+"( seseRecord );");
2037 if( fsen.equals( mlpa.getMainSESE() ) ) {
2038 outmethod.println( " /* work scheduler works forever, explicitly exit */");
2039 outmethod.println( " exit( 0 );");
2042 outmethod.println( " break;");
2043 outmethod.println( "");
2046 // default case should never be taken, error out
2047 outmethod.println( " default:");
2048 outmethod.println( " printf(\"Error: unknown SESE class ID in invoke method.\\n\");");
2049 outmethod.println( " exit(-30);");
2050 outmethod.println( " break;");
2051 outmethod.println( " }");
2052 outmethod.println( " return NULL;");
2053 outmethod.println( "}\n\n");
2057 protected void generateCode(FlatNode first,
2060 Set<FlatNode> stopset,
2061 PrintWriter output, boolean firstpass) {
2063 /* Assign labels to FlatNode's if necessary.*/
2064 Hashtable<FlatNode, Integer> nodetolabel=assignLabels(first, stopset);
2066 Set<FlatNode> storeset=null;
2067 HashSet<FlatNode> genset=null;
2068 Set<FlatNode> unionset=null;
2070 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
2071 storeset=delaycomp.livecode(lb);
2072 genset=new HashSet<FlatNode>();
2074 genset.addAll(delaycomp.getCannotDelay(lb));
2075 genset.addAll(delaycomp.getOther(lb));
2077 genset.addAll(delaycomp.getNotReady(lb));
2079 unionset=new HashSet<FlatNode>();
2080 unionset.addAll(storeset);
2081 unionset.addAll(genset);
2084 /* Do the actual code generation */
2085 FlatNode current_node=null;
2086 HashSet tovisit=new HashSet();
2087 HashSet visited=new HashSet();
2089 tovisit.add(first.getNext(0));
2092 while(current_node!=null||!tovisit.isEmpty()) {
2093 if (current_node==null) {
2094 current_node=(FlatNode)tovisit.iterator().next();
2095 tovisit.remove(current_node);
2096 } else if (tovisit.contains(current_node)) {
2097 tovisit.remove(current_node);
2099 visited.add(current_node);
2100 if (nodetolabel.containsKey(current_node)) {
2101 output.println("L"+nodetolabel.get(current_node)+":");
2103 if (state.INSTRUCTIONFAILURE) {
2104 if (state.THREAD||state.DSM||state.SINGLETM) {
2105 output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
2107 output.println("if ((--instructioncount)==0) injectinstructionfailure();");
2109 if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
2111 if (!state.DELAYCOMP||firstpass) {
2112 generateFlatNode(fm, lb, current_node, output);
2114 //store primitive variables in out set
2115 AtomicRecord ar=atomicmethodmap.get((FlatAtomicEnterNode)first);
2116 Set<TempDescriptor> liveout=ar.liveout;
2117 for(Iterator<TempDescriptor> tmpit=liveout.iterator();tmpit.hasNext();) {
2118 TempDescriptor tmp=tmpit.next();
2119 output.println("primitives->"+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2122 if (current_node.kind()!=FKind.FlatReturnNode) {
2123 output.println(" return;");
2126 } else if(current_node.numNext()==1) {
2128 if (state.MLP && current_node.kind()==FKind.FlatSESEEnterNode) {
2129 FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
2130 generateFlatNode(fm, lb, current_node, output);
2131 nextnode=fsen.getFlatExit().getNext(0);
2132 } else if (state.DELAYCOMP) {
2133 boolean specialprimitive=false;
2134 //skip literals...no need to add extra overhead
2135 if (storeset!=null&&storeset.contains(current_node)&¤t_node.kind()==FKind.FlatLiteralNode) {
2136 TypeDescriptor typedesc=((FlatLiteralNode)current_node).getType();
2137 if (!typedesc.isClass()&&!typedesc.isArray()) {
2138 specialprimitive=true;
2142 if (genset==null||genset.contains(current_node)||specialprimitive)
2143 generateFlatNode(fm, lb, current_node, output);
2144 if (storeset!=null&&storeset.contains(current_node)&&!specialprimitive) {
2145 TempDescriptor wrtmp=current_node.writesTemps()[0];
2147 //need to store value written by previous node
2148 if (wrtmp.getType().isPtr()) {
2149 //only lock the objects that may actually need locking
2150 if (recorddc.getNeedTrans(lb, current_node)) {
2151 output.println("STOREPTR("+generateTemp(fm, wrtmp,lb)+");");
2153 output.println("STOREPTRNOLOCK("+generateTemp(fm, wrtmp,lb)+");");
2156 output.println("STORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");");
2159 //need to read value read by previous node
2160 if (wrtmp.getType().isPtr()) {
2161 output.println("RESTOREPTR("+generateTemp(fm, wrtmp,lb)+");");
2163 output.println("RESTORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");");
2167 nextnode=current_node.getNext(0);
2170 generateFlatNode(fm, lb, current_node, output);
2171 nextnode=current_node.getNext(0);
2173 if (visited.contains(nextnode)) {
2174 output.println("goto L"+nodetolabel.get(nextnode)+";");
2177 current_node=nextnode;
2178 } else if (current_node.numNext()==2) {
2180 if (state.DELAYCOMP) {
2181 boolean computeside=false;
2183 //need to record which way it should go
2184 if (genset==null||genset.contains(current_node)) {
2185 if (storeset!=null&&storeset.contains(current_node)) {
2186 //need to store which way branch goes
2187 generateStoreFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2189 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2191 //which side to execute
2195 if (genset.contains(current_node)) {
2196 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2197 } else if (storeset.contains(current_node)) {
2199 output.println("RESTOREANDBRANCH(L"+nodetolabel.get(current_node.getNext(1))+");");
2201 //which side to execute
2206 Set<FlatNode> leftset=DelayComputation.getNext(current_node, 0, unionset, lb,locality, true);
2208 if (leftset.size()==0)
2210 if (visited.contains(current_node.getNext(branch))) {
2211 //already visited -- build jump
2212 output.println("goto L"+nodetolabel.get(current_node.getNext(branch))+";");
2215 current_node=current_node.getNext(branch);
2218 if (!visited.contains(current_node.getNext(1)))
2219 tovisit.add(current_node.getNext(1));
2220 if (visited.contains(current_node.getNext(0))) {
2221 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2224 current_node=current_node.getNext(0);
2228 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2229 if (!visited.contains(current_node.getNext(1)))
2230 tovisit.add(current_node.getNext(1));
2231 if (visited.contains(current_node.getNext(0))) {
2232 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2235 current_node=current_node.getNext(0);
2237 } else throw new Error();
2241 /** This method assigns labels to FlatNodes */
2242 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first) {
2243 return assignLabels(first, null);
2246 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
2247 HashSet tovisit=new HashSet();
2248 HashSet visited=new HashSet();
2250 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2253 /*Assign labels first. A node needs a label if the previous
2254 * node has two exits or this node is a join point. */
2256 while(!tovisit.isEmpty()) {
2257 FlatNode fn=(FlatNode)tovisit.iterator().next();
2262 if(lastset!=null&&lastset.contains(fn)) {
2263 // if last is not null and matches, don't go
2264 // any further for assigning labels
2268 for(int i=0; i<fn.numNext(); i++) {
2269 FlatNode nn=fn.getNext(i);
2272 //1) Edge >1 of node
2273 nodetolabel.put(nn,new Integer(labelindex++));
2275 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2279 nodetolabel.put(nn,new Integer(labelindex++));
2287 /** Generate text string that corresponds to the TempDescriptor td. */
2288 protected String generateTemp(FlatMethod fm, TempDescriptor td, LocalityBinding lb) {
2289 MethodDescriptor md=fm.getMethod();
2290 TaskDescriptor task=fm.getTask();
2291 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
2293 if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
2294 //System.out.println("generateTemp returns " + td.getSafeSymbol());
2295 return td.getSafeSymbol();
2298 if (objecttemps.isLocalPtr(td)) {
2299 return localsprefixderef+td.getSafeSymbol();
2302 if (objecttemps.isParamPtr(td)) {
2303 return paramsprefix+"->"+td.getSafeSymbol();
2309 protected void generateFlatNode(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output) {
2311 // insert pre-node actions from the code plan
2314 CodePlan cp = mlpa.getCodePlan( fn );
2317 FlatSESEEnterNode currentSESE = cp.getCurrentSESE();
2319 // for each sese and age pair that this parent statement
2320 // must stall on, take that child's stall semaphore, the
2321 // copying of values comes after the statement
2322 Iterator<VariableSourceToken> vstItr = cp.getStallTokens().iterator();
2323 while( vstItr.hasNext() ) {
2324 VariableSourceToken vst = vstItr.next();
2326 SESEandAgePair p = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2328 output.println(" {");
2329 output.println(" SESEcommon* common = (SESEcommon*) "+p+";");
2331 output.println(" pthread_mutex_lock( &(common->lock) );");
2332 output.println(" while( common->doneExecuting == FALSE ) {");
2333 output.println(" pthread_cond_wait( &(common->doneCond), &(common->lock) );");
2334 output.println(" }");
2335 output.println(" pthread_mutex_unlock( &(common->lock) );");
2337 //output.println(" psem_take( &(common->stallSem) );");
2339 // copy things we might have stalled for
2340 output.println(" "+p.getSESE().getSESErecordName()+"* child = ("+
2341 p.getSESE().getSESErecordName()+"*) "+p+";");
2343 Iterator<TempDescriptor> tdItr = cp.getCopySet( vst ).iterator();
2344 while( tdItr.hasNext() ) {
2345 TempDescriptor td = tdItr.next();
2346 output.println(" "+generateTemp( currentSESE.getfmBogus(), td, null )+
2347 " = child->"+vst.getAddrVar().getSafeSymbol()+";");
2350 output.println(" }");
2353 // for each variable with a dynamic source, stall just for that variable
2354 Iterator<TempDescriptor> dynItr = cp.getDynamicStallSet().iterator();
2355 while( dynItr.hasNext() ) {
2356 TempDescriptor dynVar = dynItr.next();
2358 // only stall if the dynamic source is not yourself, denoted by src==NULL
2359 // otherwise the dynamic write nodes will have the local var up-to-date
2360 output.println(" {");
2361 output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
2362 output.println(" SESEcommon* common = (SESEcommon*) "+dynVar+"_srcSESE;");
2363 output.println(" psem_take( &(common->stallSem) );");
2364 output.println(" "+generateTemp( currentSESE.getfmBogus(), dynVar, null )+
2365 " = *(("+dynVar.getType()+"*) ("+
2366 dynVar+"_srcSESE + "+dynVar+"_srcOffset));");
2367 output.println(" }");
2368 output.println(" }");
2371 // for each assignment of a variable to rhs that has a dynamic source,
2372 // copy the dynamic sources
2373 Iterator dynAssignItr = cp.getDynAssigns().entrySet().iterator();
2374 while( dynAssignItr.hasNext() ) {
2375 Map.Entry me = (Map.Entry) dynAssignItr.next();
2376 TempDescriptor lhs = (TempDescriptor) me.getKey();
2377 TempDescriptor rhs = (TempDescriptor) me.getValue();
2378 output.println(" "+lhs+"_srcSESE = "+rhs+"_srcSESE;");
2379 output.println(" "+lhs+"_srcOffset = "+rhs+"_srcOffset;");
2385 case FKind.FlatAtomicEnterNode:
2386 generateFlatAtomicEnterNode(fm, lb, (FlatAtomicEnterNode) fn, output);
2389 case FKind.FlatAtomicExitNode:
2390 generateFlatAtomicExitNode(fm, lb, (FlatAtomicExitNode) fn, output);
2393 case FKind.FlatInstanceOfNode:
2394 generateFlatInstanceOfNode(fm, lb, (FlatInstanceOfNode)fn, output);
2397 case FKind.FlatSESEEnterNode:
2398 generateFlatSESEEnterNode(fm, lb, (FlatSESEEnterNode)fn, output);
2401 case FKind.FlatSESEExitNode:
2402 generateFlatSESEExitNode(fm, lb, (FlatSESEExitNode)fn, output);
2405 case FKind.FlatWriteDynamicVarNode:
2406 generateFlatWriteDynamicVarNode(fm, lb, (FlatWriteDynamicVarNode)fn, output);
2409 case FKind.FlatGlobalConvNode:
2410 generateFlatGlobalConvNode(fm, lb, (FlatGlobalConvNode) fn, output);
2413 case FKind.FlatTagDeclaration:
2414 generateFlatTagDeclaration(fm, lb, (FlatTagDeclaration) fn,output);
2417 case FKind.FlatCall:
2418 generateFlatCall(fm, lb, (FlatCall) fn,output);
2421 case FKind.FlatFieldNode:
2422 generateFlatFieldNode(fm, lb, (FlatFieldNode) fn,output);
2425 case FKind.FlatElementNode:
2426 generateFlatElementNode(fm, lb, (FlatElementNode) fn,output);
2429 case FKind.FlatSetElementNode:
2430 generateFlatSetElementNode(fm, lb, (FlatSetElementNode) fn,output);
2433 case FKind.FlatSetFieldNode:
2434 generateFlatSetFieldNode(fm, lb, (FlatSetFieldNode) fn,output);
2438 generateFlatNew(fm, lb, (FlatNew) fn,output);
2441 case FKind.FlatOpNode:
2442 generateFlatOpNode(fm, lb, (FlatOpNode) fn,output);
2445 case FKind.FlatCastNode:
2446 generateFlatCastNode(fm, lb, (FlatCastNode) fn,output);
2449 case FKind.FlatLiteralNode:
2450 generateFlatLiteralNode(fm, lb, (FlatLiteralNode) fn,output);
2453 case FKind.FlatReturnNode:
2454 generateFlatReturnNode(fm, lb, (FlatReturnNode) fn,output);
2458 output.println("/* nop */");
2461 case FKind.FlatExit:
2462 output.println("/* exit */");
2465 case FKind.FlatBackEdge:
2466 if (((state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
2467 || (this.state.MULTICOREGC)) {
2468 if(state.DSM&&locality.getAtomic(lb).get(fn).intValue()>0) {
2469 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
2470 } else if(this.state.MULTICOREGC) {
2471 output.println("if (gcflag) gc("+localsprefixaddr+");");
2473 output.println("if (needtocollect) checkcollect("+localsprefixaddr+");");
2475 output.println("/* nop */");
2478 case FKind.FlatCheckNode:
2479 generateFlatCheckNode(fm, lb, (FlatCheckNode) fn, output);
2482 case FKind.FlatFlagActionNode:
2483 generateFlatFlagActionNode(fm, lb, (FlatFlagActionNode) fn, output);
2486 case FKind.FlatPrefetchNode:
2487 generateFlatPrefetchNode(fm,lb, (FlatPrefetchNode) fn, output);
2490 case FKind.FlatOffsetNode:
2491 generateFlatOffsetNode(fm, lb, (FlatOffsetNode)fn, output);
2498 // insert post-node actions from the code-plan
2500 CodePlan cp = mlpa.getCodePlan( fn );
2507 public void generateFlatOffsetNode(FlatMethod fm, LocalityBinding lb, FlatOffsetNode fofn, PrintWriter output) {
2508 output.println("/* FlatOffsetNode */");
2509 FieldDescriptor fd=fofn.getField();
2510 output.println(generateTemp(fm, fofn.getDst(),lb)+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+ fd.getSafeSymbol()+");");
2511 output.println("/* offset */");
2514 public void generateFlatPrefetchNode(FlatMethod fm, LocalityBinding lb, FlatPrefetchNode fpn, PrintWriter output) {
2515 if (state.PREFETCH) {
2516 Vector oids = new Vector();
2517 Vector fieldoffset = new Vector();
2518 Vector endoffset = new Vector();
2519 int tuplecount = 0; //Keeps track of number of prefetch tuples that need to be generated
2520 for(Iterator it = fpn.hspp.iterator(); it.hasNext();) {
2521 PrefetchPair pp = (PrefetchPair) it.next();
2522 Integer statusbase = locality.getNodePreTempInfo(lb,fpn).get(pp.base);
2523 /* Find prefetches that can generate oid */
2524 if(statusbase == LocalityAnalysis.GLOBAL) {
2525 generateTransCode(fm, lb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(lb).get(fpn).intValue()>0, false);
2527 } else if (statusbase == LocalityAnalysis.LOCAL) {
2528 generateTransCode(fm,lb,pp,oids,fieldoffset,endoffset,tuplecount,false,true);
2535 System.out.println("Adding prefetch "+fpn+ " to method:" +fm);
2536 output.println("{");
2537 output.println("/* prefetch */");
2538 output.println("/* prefetchid_" + fpn.siteid + " */");
2539 output.println("void * prefptr;");
2540 output.println("int tmpindex;");
2542 output.println("if((evalPrefetch["+fpn.siteid+"].operMode) || (evalPrefetch["+fpn.siteid+"].retrycount <= 0)) {");
2543 /*Create C code for oid array */
2544 output.print(" unsigned int oidarray_[] = {");
2545 boolean needcomma=false;
2546 for (Iterator it = oids.iterator(); it.hasNext();) {
2549 output.print(it.next());
2552 output.println("};");
2554 /*Create C code for endoffset values */
2555 output.print(" unsigned short endoffsetarry_[] = {");
2557 for (Iterator it = endoffset.iterator(); it.hasNext();) {
2560 output.print(it.next());
2563 output.println("};");
2565 /*Create C code for Field Offset Values */
2566 output.print(" short fieldarry_[] = {");
2568 for (Iterator it = fieldoffset.iterator(); it.hasNext();) {
2571 output.print(it.next());
2574 output.println("};");
2575 /* make the prefetch call to Runtime */
2576 output.println(" if(!evalPrefetch["+fpn.siteid+"].operMode) {");
2577 output.println(" evalPrefetch["+fpn.siteid+"].retrycount = RETRYINTERVAL;");
2578 output.println(" }");
2579 output.println(" prefetch("+fpn.siteid+" ,"+tuplecount+", oidarray_, endoffsetarry_, fieldarry_);");
2580 output.println(" } else {");
2581 output.println(" evalPrefetch["+fpn.siteid+"].retrycount--;");
2582 output.println(" }");
2583 output.println("}");
2587 public void generateTransCode(FlatMethod fm, LocalityBinding lb,PrefetchPair pp, Vector oids, Vector fieldoffset, Vector endoffset, int tuplecount, boolean inside, boolean localbase) {
2588 short offsetcount = 0;
2592 } else if (localbase) {
2593 for(; breakindex<pp.desc.size(); breakindex++) {
2594 Descriptor desc=pp.getDescAt(breakindex);
2595 if (desc instanceof FieldDescriptor) {
2596 FieldDescriptor fd=(FieldDescriptor)desc;
2597 if (fd.isGlobal()) {
2605 if (breakindex>pp.desc.size()) //all local
2608 TypeDescriptor lasttype=pp.base.getType();
2609 String basestr=generateTemp(fm, pp.base, lb);
2611 boolean maybenull=fm.getMethod().isStatic()||
2612 !pp.base.equals(fm.getParameter(0));
2614 for(int i=0; i<breakindex; i++) {
2615 String indexcheck="";
2617 Descriptor desc=pp.getDescAt(i);
2618 if (desc instanceof FieldDescriptor) {
2619 FieldDescriptor fd=(FieldDescriptor)desc;
2621 if (!teststr.equals(""))
2623 teststr+="((prefptr="+basestr+")!=NULL)";
2624 basestr="((struct "+lasttype.getSafeSymbol()+" *)prefptr)->"+fd.getSafeSymbol();
2626 basestr=basestr+"->"+fd.getSafeSymbol();
2629 lasttype=fd.getType();
2631 IndexDescriptor id=(IndexDescriptor)desc;
2632 indexcheck="((tmpindex=";
2633 for(int j=0; j<id.tddesc.size(); j++) {
2634 indexcheck+=generateTemp(fm, id.getTempDescAt(j), lb)+"+";
2636 indexcheck+=id.offset+")>=0)&(tmpindex<((struct ArrayObject *)prefptr)->___length___)";
2638 if (!teststr.equals(""))
2640 teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck;
2641 basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]";
2643 lasttype=lasttype.dereference();
2648 if (teststr.equals("")) {
2649 oid="((unsigned int)"+basestr+")";
2651 oid="((unsigned int)(("+teststr+")?"+basestr+":NULL))";
2655 for(int i = breakindex; i < pp.desc.size(); i++) {
2656 String newfieldoffset;
2657 Object desc = pp.getDescAt(i);
2658 if(desc instanceof FieldDescriptor) {
2659 FieldDescriptor fd=(FieldDescriptor)desc;
2660 newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))");
2661 lasttype=fd.getType();
2663 newfieldoffset = "";
2664 IndexDescriptor id=(IndexDescriptor)desc;
2665 for(int j = 0; j < id.tddesc.size(); j++) {
2666 newfieldoffset += generateTemp(fm, id.getTempDescAt(j), lb) + "+";
2668 newfieldoffset += id.offset.toString();
2669 lasttype=lasttype.dereference();
2671 fieldoffset.add(newfieldoffset);
2674 int base=(tuplecount>0) ? ((Short)endoffset.get(tuplecount-1)).intValue() : 0;
2675 base+=pp.desc.size()-breakindex;
2676 endoffset.add(new Short((short)base));
2681 public void generateFlatGlobalConvNode(FlatMethod fm, LocalityBinding lb, FlatGlobalConvNode fgcn, PrintWriter output) {
2682 if (lb!=fgcn.getLocality())
2684 /* Have to generate flat globalconv */
2685 if (fgcn.getMakePtr()) {
2687 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+");");
2689 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fgcn)||state.READSET&&dc.getNeedWriteTrans(lb, fgcn)) {
2690 //need to do translation
2691 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+", (void *)("+localsprefixaddr+"));");
2692 } else if (state.READSET&&dc.getNeedTrans(lb, fgcn)) {
2693 output.println("TRANSREADRD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
2697 /* Need to convert to OID */
2698 if ((dc==null)||dc.getNeedSrcTrans(lb,fgcn)) {
2699 if (fgcn.doConvert()||(delaycomp!=null&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) {
2700 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc(),lb)+");");
2702 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=NULL;");
2708 public void generateFlatInstanceOfNode(FlatMethod fm, LocalityBinding lb, FlatInstanceOfNode fion, PrintWriter output) {
2710 if (fion.getType().isArray()) {
2711 type=state.getArrayNumber(fion.getType())+state.numClasses();
2713 type=fion.getType().getClassDesc().getId();
2716 if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
2717 output.println(generateTemp(fm, fion.getDst(), lb)+"=1;");
2719 output.println(generateTemp(fm, fion.getDst(), lb)+"=instanceof("+generateTemp(fm,fion.getSrc(),lb)+","+type+");");
2722 public void generateFlatAtomicEnterNode(FlatMethod fm, LocalityBinding lb, FlatAtomicEnterNode faen, PrintWriter output) {
2723 /* Check to see if we need to generate code for this atomic */
2724 if (locality==null) {
2725 output.println("pthread_mutex_lock(&atomiclock);");
2729 if (locality.getAtomic(lb).get(faen.getPrev(0)).intValue()>0)
2733 if (state.DELAYCOMP) {
2734 AtomicRecord ar=atomicmethodmap.get(faen);
2736 for(Iterator<TempDescriptor> tmpit=ar.livein.iterator();tmpit.hasNext();) {
2737 TempDescriptor tmp=tmpit.next();
2738 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2741 //copy outs that depend on path
2742 for(Iterator<TempDescriptor> tmpit=ar.liveoutvirtualread.iterator();tmpit.hasNext();) {
2743 TempDescriptor tmp=tmpit.next();
2744 if (!ar.livein.contains(tmp))
2745 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2749 /* Backup the temps. */
2750 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
2751 TempDescriptor tmp=tmpit.next();
2752 output.println(generateTemp(fm, backuptable.get(lb).get(tmp),lb)+"="+generateTemp(fm,tmp,lb)+";");
2755 output.println("goto transstart"+faen.getIdentifier()+";");
2757 /******* Print code to retry aborted transaction *******/
2758 output.println("transretry"+faen.getIdentifier()+":");
2761 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
2762 TempDescriptor tmp=tmpit.next();
2763 output.println(generateTemp(fm, tmp,lb)+"="+generateTemp(fm,backuptable.get(lb).get(tmp),lb)+";");
2767 /********* Need to revert local object store ********/
2768 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
2770 output.println("while ("+revertptr+") {");
2771 output.println("struct ___Object___ * tmpptr;");
2772 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
2773 output.println("REVERT_OBJ("+revertptr+");");
2774 output.println(revertptr+"=tmpptr;");
2775 output.println("}");
2777 /******* Tell the runtime to start the transaction *******/
2779 output.println("transstart"+faen.getIdentifier()+":");
2780 output.println("transStart();");
2782 if (state.ABORTREADERS) {
2783 output.println("if (_setjmp(aborttrans)) {");
2784 output.println(" goto transretry"+faen.getIdentifier()+"; }");
2788 public void generateFlatAtomicExitNode(FlatMethod fm, LocalityBinding lb, FlatAtomicExitNode faen, PrintWriter output) {
2789 /* Check to see if we need to generate code for this atomic */
2790 if (locality==null) {
2791 output.println("pthread_mutex_unlock(&atomiclock);");
2794 if (locality.getAtomic(lb).get(faen).intValue()>0)
2796 //store the revert list before we lose the transaction object
2797 String revertptr=null;
2799 revertptr=generateTemp(fm, reverttable.get(lb),lb);
2800 output.println(revertptr+"=revertlist;");
2802 if (state.DELAYCOMP) {
2803 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
2806 output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {");
2808 output.println("if (transCommit()) {");
2809 /* Transaction aborts if it returns true */
2810 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
2812 output.println("} else {");
2813 /* Need to commit local object store */
2814 output.println("while ("+revertptr+") {");
2815 output.println("struct ___Object___ * tmpptr;");
2816 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
2817 output.println("COMMIT_OBJ("+revertptr+");");
2818 output.println(revertptr+"=tmpptr;");
2819 output.println("}");
2821 output.println("}");
2822 if (state.DELAYCOMP) {
2824 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
2825 output.println("else {");
2826 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
2827 TempDescriptor tmp=tmpit.next();
2828 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
2830 output.println("}");
2834 public void generateFlatSESEEnterNode( FlatMethod fm,
2836 FlatSESEEnterNode fsen,
2840 // SESE nodes can be parsed for normal compilation, just skip over them
2844 output.println(" {");
2846 // set up the parent
2847 if( fsen == mlpa.getMainSESE() ) {
2848 output.println(" SESEcommon* parentCommon = NULL;");
2849 } else if( fsen.getParent() != null ) {
2850 output.println(" SESEcommon* parentCommon = &("+paramsprefix+"->common);");
2852 //output.println(" SESEcommon* parentCommon = (SESEcommon*) peekItem( seseCallStack );");
2853 output.println(" SESEcommon* parentCommon = seseCaller;");
2856 // before doing anything, lock your own record and increment the running children
2857 if( fsen != mlpa.getMainSESE() ) {
2858 output.println(" pthread_mutex_lock( &(parentCommon->lock) );");
2859 output.println(" ++(parentCommon->numRunningChildren);");
2860 output.println(" pthread_mutex_unlock( &(parentCommon->lock) );");
2863 // just allocate the space for this record
2864 output.println(" "+fsen.getSESErecordName()+"* seseToIssue = ("+
2865 fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
2866 fsen.getSESErecordName()+" ) );");
2868 // and keep the thread-local sese stack up to date
2869 //output.println(" addNewItem( seseCallStack, (void*) seseToIssue);");
2871 // fill in common data
2872 output.println(" seseToIssue->common.classID = "+fsen.getIdentifier()+";");
2873 output.println(" psem_init( &(seseToIssue->common.stallSem) );");
2875 output.println(" seseToIssue->common.forwardList = createQueue();");
2876 output.println(" seseToIssue->common.unresolvedDependencies = 0;");
2877 output.println(" pthread_cond_init( &(seseToIssue->common.doneCond), NULL );");
2878 output.println(" seseToIssue->common.doneExecuting = FALSE;");
2879 output.println(" pthread_cond_init( &(seseToIssue->common.runningChildrenCond), NULL );");
2880 output.println(" seseToIssue->common.numRunningChildren = 0;");
2881 output.println(" seseToIssue->common.parent = parentCommon;");
2883 // all READY in-vars should be copied now and be done with it
2884 Iterator<TempDescriptor> tempItr = fsen.getReadyInVarSet().iterator();
2885 while( tempItr.hasNext() ) {
2886 TempDescriptor temp = tempItr.next();
2887 if( fsen != mlpa.getMainSESE() &&
2888 fsen.getParent() != null ) {
2889 output.println(" seseToIssue->"+temp+" = "+
2890 generateTemp( fsen.getParent().getfmBogus(), temp, null )+";");
2892 output.println(" seseToIssue->"+temp+" = "+
2893 generateTemp( fsen.getfmEnclosing(), temp, null )+";");
2897 // before potentially adding this SESE to other forwarding lists,
2898 // create it's lock and take it immediately
2899 output.println(" pthread_mutex_init( &(seseToIssue->common.lock), NULL );");
2900 output.println(" pthread_mutex_lock( &(seseToIssue->common.lock) );");
2902 if( fsen != mlpa.getMainSESE() ) {
2903 // count up outstanding dependencies, static first, then dynamic
2904 Iterator<SESEandAgePair> staticSrcsItr = fsen.getStaticInVarSrcs().iterator();
2905 while( staticSrcsItr.hasNext() ) {
2906 SESEandAgePair srcPair = staticSrcsItr.next();
2907 output.println(" {");
2908 output.println(" SESEcommon* src = (SESEcommon*)"+srcPair+";");
2909 output.println(" pthread_mutex_lock( &(src->lock) );");
2910 output.println(" if( !isEmpty( src->forwardList ) &&");
2911 output.println(" seseToIssue == peekItem( src->forwardList ) ) {");
2912 output.println(" printf( \"This shouldnt already be here\\n\");");
2913 output.println(" exit( -1 );");
2914 output.println(" }");
2915 output.println(" if( !src->doneExecuting ) {");
2916 output.println(" addNewItem( src->forwardList, seseToIssue );");
2917 output.println(" ++(seseToIssue->common.unresolvedDependencies);");
2918 output.println(" }");
2919 output.println(" pthread_mutex_unlock( &(src->lock) );");
2920 output.println(" }");
2922 // whether or not it is an outstanding dependency, make sure
2923 // to pass the static name to the child's record
2924 output.println(" seseToIssue->"+srcPair+" = "+srcPair+";");
2927 // dynamic sources might already be accounted for in the static list,
2928 // so only add them to forwarding lists if they're not already there
2929 Iterator<TempDescriptor> dynVarsItr = fsen.getDynamicInVarSet().iterator();
2930 while( dynVarsItr.hasNext() ) {
2931 TempDescriptor dynInVar = dynVarsItr.next();
2932 output.println(" {");
2933 output.println(" SESEcommon* src = (SESEcommon*)"+dynInVar+"_srcSESE;");
2935 // the dynamic source is NULL if it comes from your own space--you can't pass
2936 // the address off to the new child, because you're not done executing and
2937 // might change the variable, so copy it right now
2938 output.println(" if( src != NULL ) {");
2939 output.println(" pthread_mutex_lock( &(src->lock) );");
2940 output.println(" if( isEmpty( src->forwardList ) ||");
2941 output.println(" seseToIssue != peekItem( src->forwardList ) ) {");
2942 output.println(" if( !src->doneExecuting ) {");
2943 output.println(" addNewItem( src->forwardList, seseToIssue );");
2944 output.println(" ++(seseToIssue->common.unresolvedDependencies);");
2945 output.println(" }");
2946 output.println(" }");
2947 output.println(" pthread_mutex_unlock( &(src->lock) );");
2948 output.println(" seseToIssue->"+dynInVar+"_srcOffset = "+dynInVar+"_srcOffset;");
2949 output.println(" } else {");
2950 if( fsen.getParent() != null ) {
2951 output.println(" seseToIssue->"+dynInVar+" = "+
2952 generateTemp( fsen.getParent().getfmBogus(), dynInVar, null )+";");
2954 output.println(" seseToIssue->"+dynInVar+" = "+
2955 generateTemp( fsen.getfmEnclosing(), dynInVar, null )+";");
2957 output.println(" }");
2958 output.println(" }");
2960 // even if the value is already copied, make sure your NULL source
2961 // gets passed so child knows it already has the dynamic value
2962 output.println(" seseToIssue->"+dynInVar+"_srcSESE = "+dynInVar+"_srcSESE;");
2965 // maintain pointers for for finding dynamic SESE
2966 // instances from static names
2967 SESEandAgePair p = new SESEandAgePair( fsen, 0 );
2968 if( fsen.getParent() != null &&
2969 fsen.getParent().getNeededStaticNames().contains( p ) ) {
2971 for( int i = fsen.getOldestAgeToTrack(); i > 0; --i ) {
2972 SESEandAgePair p1 = new SESEandAgePair( fsen, i );
2973 SESEandAgePair p2 = new SESEandAgePair( fsen, i-1 );
2974 output.println(" "+p1+" = "+p2+";");
2976 output.println(" "+p+" = seseToIssue;");
2980 // if there were no outstanding dependencies, issue here
2981 output.println(" if( seseToIssue->common.unresolvedDependencies == 0 ) {");
2982 output.println(" workScheduleSubmit( (void*)seseToIssue );");
2983 output.println(" }");
2985 // release this SESE for siblings to update its dependencies or,
2986 // eventually, for it to mark itself finished
2987 output.println(" pthread_mutex_unlock( &(seseToIssue->common.lock) );");
2988 output.println(" }");
2992 public void generateFlatSESEExitNode( FlatMethod fm,
2994 FlatSESEExitNode fsexn,
2998 // SESE nodes can be parsed for normal compilation, just skip over them
3002 output.println(" /* SESE exiting */");
3004 String com = paramsprefix+"->common";
3007 // take yourself off the thread-local sese call stack
3008 output.println(" if( isEmpty( seseCallStack ) ) {");
3009 output.println(" printf( \"Error, sese call stack is empty.\\n\" );");
3010 output.println(" exit( -1 );");
3011 output.println(" }");
3012 output.println(" if( (void*)"+paramsprefix+" != getItem( seseCallStack ) ) {");
3013 output.println(" printf( \"Error, sese call stack mismatch.\\n\" );");
3014 output.println(" exit( -1 );");
3015 output.println(" }");
3018 // this SESE cannot be done until all of its children are done
3019 // so grab your own lock with the condition variable for watching
3020 // that the number of your running children is greater than zero
3021 output.println(" pthread_mutex_lock( &("+com+".lock) );");
3022 output.println(" while( "+com+".numRunningChildren > 0 ) {");
3023 output.println(" pthread_cond_wait( &("+com+".runningChildrenCond), &("+com+".lock) );");
3024 output.println(" }");
3026 // copy out-set from local temps into the sese record
3027 Iterator<TempDescriptor> itr = fsexn.getFlatEnter().getOutVarSet().iterator();
3028 while( itr.hasNext() ) {
3029 TempDescriptor temp = itr.next();
3030 output.println(" "+paramsprefix+
3031 "->"+temp.getSafeSymbol()+
3032 " = "+temp.getSafeSymbol()+";" );
3035 // mark yourself done, your SESE data is now read-only
3036 output.println(" "+com+".doneExecuting = TRUE;");
3037 output.println(" pthread_cond_signal( &("+com+".doneCond) );");
3038 output.println(" pthread_mutex_unlock( &("+com+".lock) );");
3040 // decrement dependency count for all SESE's on your forwarding list
3041 output.println(" while( !isEmpty( "+com+".forwardList ) ) {");
3042 output.println(" SESEcommon* consumer = (SESEcommon*) getItem( "+com+".forwardList );");
3043 output.println(" pthread_mutex_lock( &(consumer->lock) );");
3044 output.println(" --(consumer->unresolvedDependencies);");
3045 output.println(" if( consumer->unresolvedDependencies == 0 ) {");
3046 output.println(" workScheduleSubmit( (void*)consumer );");
3047 output.println(" }");
3048 output.println(" pthread_mutex_unlock( &(consumer->lock) );");
3049 output.println(" }");
3051 // if parent is stalling on you, let them know you're done
3052 if( fsexn.getFlatEnter() != mlpa.getMainSESE() ) {
3053 output.println(" psem_give( &("+paramsprefix+"->common.stallSem) );");
3056 // last of all, decrement your parent's number of running children
3057 output.println(" if( "+paramsprefix+"->common.parent != NULL ) {");
3058 output.println(" pthread_mutex_lock( &("+paramsprefix+"->common.parent->lock) );");
3059 output.println(" --("+paramsprefix+"->common.parent->numRunningChildren);");
3060 output.println(" pthread_cond_signal( &("+paramsprefix+"->common.parent->runningChildrenCond) );");
3061 output.println(" pthread_mutex_unlock( &("+paramsprefix+"->common.parent->lock) );");
3062 output.println(" }");
3065 public void generateFlatWriteDynamicVarNode( FlatMethod fm,
3067 FlatWriteDynamicVarNode fwdvn,
3071 // should node should not be in an IR graph if the
3072 // MLP flag is not set
3073 throw new Error("Unexpected presence of FlatWriteDynamicVarNode");
3076 Hashtable<TempDescriptor, VariableSourceToken> writeDynamic =
3079 assert writeDynamic != null;
3081 Iterator wdItr = writeDynamic.entrySet().iterator();
3082 while( wdItr.hasNext() ) {
3083 Map.Entry me = (Map.Entry) wdItr.next();
3084 TempDescriptor refVar = (TempDescriptor) me.getKey();
3085 VariableSourceToken vst = (VariableSourceToken) me.getValue();
3087 FlatSESEEnterNode current = fwdvn.getEnclosingSESE();
3089 // only do this if the variable in question should be tracked,
3090 // meaning that it was explicitly added to the dynamic var set
3091 if( !current.getDynamicVarSet().contains( vst.getAddrVar() ) ) {
3095 SESEandAgePair instance = new SESEandAgePair( vst.getSESE(), vst.getAge() );
3097 output.println(" {");
3099 if( current.equals( vst.getSESE() ) ) {
3100 // if the src comes from this SESE, it's a method local variable,
3101 // mark src pointer NULL to signify that the var is up-to-date
3102 output.println(" "+vst.getAddrVar()+"_srcSESE = NULL;");
3105 // otherwise we track where it will come from
3106 output.println(" "+vst.getAddrVar()+"_srcSESE = "+instance+";");
3107 output.println(" "+vst.getAddrVar()+"_srcOffset = (int) &((("+
3108 vst.getSESE().getSESErecordName()+"*)0)->"+vst.getAddrVar()+");");
3111 output.println(" }");
3116 private void generateFlatCheckNode(FlatMethod fm, LocalityBinding lb, FlatCheckNode fcn, PrintWriter output) {
3117 if (state.CONSCHECK) {
3118 String specname=fcn.getSpec();
3119 String varname="repairstate___";
3120 output.println("{");
3121 output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
3123 TempDescriptor[] temps=fcn.getTemps();
3124 String[] vars=fcn.getVars();
3125 for(int i=0; i<temps.length; i++) {
3126 output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i],lb)+";");
3129 output.println("if (doanalysis"+specname+"("+varname+")) {");
3130 output.println("free"+specname+"_state("+varname+");");
3131 output.println("} else {");
3132 output.println("/* Bad invariant */");
3133 output.println("free"+specname+"_state("+varname+");");
3134 output.println("abort_task();");
3135 output.println("}");
3136 output.println("}");
3140 private void generateFlatCall(FlatMethod fm, LocalityBinding lb, FlatCall fc, PrintWriter output) {
3143 output.println(" seseCaller = (SESEcommon*)"+paramsprefix+";");
3146 MethodDescriptor md=fc.getMethod();
3147 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? locality.getBinding(lb, fc) : md);
3148 ClassDescriptor cn=md.getClassDesc();
3149 output.println("{");
3150 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3152 LocalityBinding fclb=locality.getBinding(lb, fc);
3153 output.print(" struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
3155 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
3157 output.print(objectparams.numPointers());
3158 output.print(", "+localsprefixaddr);
3159 if (md.getThis()!=null) {
3161 output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis(),lb));
3163 if (fc.getThis()!=null&&md.getThis()==null) {
3164 System.out.println("WARNING!!!!!!!!!!!!");
3165 System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
3169 for(int i=0; i<fc.numArgs(); i++) {
3170 Descriptor var=md.getParameter(i);
3171 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
3172 if (objectparams.isParamPtr(paramtemp)) {
3173 TempDescriptor targ=fc.getArg(i);
3175 TypeDescriptor td=md.getParamType(i);
3177 output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
3179 output.print("(struct "+md.getParamType(i).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
3182 output.println("};");
3187 if (fc.getReturnTemp()!=null)
3188 output.print(generateTemp(fm,fc.getReturnTemp(),lb)+"=");
3190 /* Do we need to do virtual dispatch? */
3191 if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
3194 LocalityBinding fclb=locality.getBinding(lb, fc);
3195 output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
3197 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
3202 if (md.getReturnType().isClass()||md.getReturnType().isArray())
3203 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
3205 output.print(md.getReturnType().getSafeSymbol()+" ");
3206 output.print("(*)(");
3208 boolean printcomma=false;
3209 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3211 LocalityBinding fclb=locality.getBinding(lb, fc);
3212 output.print("struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
3214 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
3218 for(int i=0; i<objectparams.numPrimitives(); i++) {
3219 TempDescriptor temp=objectparams.getPrimitive(i);
3223 if (temp.getType().isClass()||temp.getType().isArray())
3224 output.print("struct " + temp.getType().getSafeSymbol()+" * ");
3226 output.print(temp.getType().getSafeSymbol());
3231 LocalityBinding fclb=locality.getBinding(lb, fc);
3232 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])");
3234 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
3238 boolean needcomma=false;
3239 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3240 output.print("&__parameterlist__");
3244 if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
3245 if (fc.getThis()!=null) {
3246 TypeDescriptor ptd=md.getThis().getType();
3249 if (ptd.isClass()&&!ptd.isArray())
3250 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
3251 output.print(generateTemp(fm,fc.getThis(),lb));
3256 for(int i=0; i<fc.numArgs(); i++) {
3257 Descriptor var=md.getParameter(i);
3258 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
3259 if (objectparams.isParamPrim(paramtemp)) {
3260 TempDescriptor targ=fc.getArg(i);
3264 TypeDescriptor ptd=md.getParamType(i);
3265 if (ptd.isClass()&&!ptd.isArray())
3266 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
3267 output.print(generateTemp(fm, targ,lb));
3271 output.println(");");
3272 output.println(" }");
3275 private boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
3276 Set subclasses=typeutil.getSubClasses(thiscd);
3277 if (subclasses==null)
3279 for(Iterator classit=subclasses.iterator(); classit.hasNext();) {
3280 ClassDescriptor cd=(ClassDescriptor)classit.next();
3281 Set possiblematches=cd.getMethodTable().getSet(md.getSymbol());
3282 for(Iterator matchit=possiblematches.iterator(); matchit.hasNext();) {
3283 MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
3284 if (md.matches(matchmd))
3291 private void generateFlatFieldNode(FlatMethod fm, LocalityBinding lb, FlatFieldNode ffn, PrintWriter output) {
3292 if (state.SINGLETM) {
3293 //single machine transactional memory case
3294 String field=ffn.getField().getSafeSymbol();
3295 String src=generateTemp(fm, ffn.getSrc(),lb);
3296 String dst=generateTemp(fm, ffn.getDst(),lb);
3298 output.println(dst+"="+ src +"->"+field+ ";");
3299 if (ffn.getField().getType().isPtr()&&locality.getAtomic(lb).get(ffn).intValue()>0&&
3300 locality.getNodePreTempInfo(lb, ffn).get(ffn.getSrc())!=LocalityAnalysis.SCRATCH) {
3301 if ((dc==null)||(!state.READSET&&dc.getNeedTrans(lb, ffn))||
3302 (state.READSET&&dc.getNeedWriteTrans(lb, ffn))) {
3303 output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));");
3304 } else if (state.READSET&&dc.getNeedTrans(lb, ffn)) {
3305 output.println("TRANSREADRD("+dst+", "+dst+");");
3308 } else if (state.DSM) {
3309 Integer status=locality.getNodePreTempInfo(lb,ffn).get(ffn.getSrc());
3310 if (status==LocalityAnalysis.GLOBAL) {
3311 String field=ffn.getField().getSafeSymbol();
3312 String src=generateTemp(fm, ffn.getSrc(),lb);
3313 String dst=generateTemp(fm, ffn.getDst(),lb);
3315 if (ffn.getField().getType().isPtr()) {
3317 //TODO: Uncomment this when we have runtime support
3318 //if (ffn.getSrc()==ffn.getDst()) {
3319 //output.println("{");
3320 //output.println("void * temp="+src+";");
3321 //output.println("if (temp&0x1) {");
3322 //output.println("temp=(void *) transRead(trans, (unsigned int) temp);");
3323 //output.println(src+"->"+field+"="+temp+";");
3324 //output.println("}");
3325 //output.println(dst+"=temp;");
3326 //output.println("}");
3328 output.println(dst+"="+ src +"->"+field+ ";");
3329 //output.println("if ("+dst+"&0x1) {");
3330 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
3331 //output.println(src+"->"+field+"="+src+"->"+field+";");
3332 //output.println("}");
3335 output.println(dst+"="+ src+"->"+field+";");
3337 } else if (status==LocalityAnalysis.LOCAL) {
3338 if (ffn.getField().getType().isPtr()&&
3339 ffn.getField().isGlobal()) {
3340 String field=ffn.getField().getSafeSymbol();
3341 String src=generateTemp(fm, ffn.getSrc(),lb);
3342 String dst=generateTemp(fm, ffn.getDst(),lb);
3343 output.println(dst+"="+ src +"->"+field+ ";");
3344 if (locality.getAtomic(lb).get(ffn).intValue()>0)
3345 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
3347 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
3348 } else if (status==LocalityAnalysis.EITHER) {
3349 //Code is reading from a null pointer
3350 output.println("if ("+generateTemp(fm, ffn.getSrc(),lb)+") {");
3351 output.println("#ifndef RAW");
3352 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
3353 output.println("#endif");
3354 //This should throw a suitable null pointer error
3355 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
3357 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
3359 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
3363 private void generateFlatSetFieldNode(FlatMethod fm, LocalityBinding lb, FlatSetFieldNode fsfn, PrintWriter output) {
3364 if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
3365 throw new Error("Can't set array length");
3366 if (state.SINGLETM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
3367 //Single Machine Transaction Case
3368 boolean srcptr=fsfn.getSrc().getType().isPtr();
3369 String src=generateTemp(fm,fsfn.getSrc(),lb);
3370 String dst=generateTemp(fm,fsfn.getDst(),lb);
3371 output.println("//"+srcptr+" "+fsfn.getSrc().getType().isNull());
3372 if (srcptr&&!fsfn.getSrc().getType().isNull()) {
3373 output.println("{");
3374 if ((dc==null)||dc.getNeedSrcTrans(lb, fsfn)&&
3375 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) {
3376 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3378 output.println("INTPTR srcoid=(INTPTR)"+src+";");
3381 if (wb.needBarrier(fsfn)&&
3382 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getDst())!=LocalityAnalysis.SCRATCH) {
3383 output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;");
3385 if (srcptr&!fsfn.getSrc().getType().isNull()) {
3386 output.println("*((unsigned INTPTR *)&("+dst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
3387 output.println("}");
3389 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3391 } else if (state.DSM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
3392 Integer statussrc=locality.getNodePreTempInfo(lb,fsfn).get(fsfn.getSrc());
3393 Integer statusdst=locality.getNodeTempInfo(lb).get(fsfn).get(fsfn.getDst());
3394 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
3396 String src=generateTemp(fm,fsfn.getSrc(),lb);
3397 String dst=generateTemp(fm,fsfn.getDst(),lb);
3399 output.println("{");
3400 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3402 if (statusdst.equals(LocalityAnalysis.GLOBAL)) {
3405 if (wb.needBarrier(fsfn))
3406 output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;");
3408 output.println("*((unsigned INTPTR *)&("+glbdst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
3410 output.println(glbdst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3411 } else if (statusdst.equals(LocalityAnalysis.LOCAL)) {
3412 /** Check if we need to copy */
3413 output.println("if(!"+dst+"->"+localcopystr+") {");
3414 /* Link object into list */
3415 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3416 output.println(revertptr+"=revertlist;");
3417 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
3418 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3420 output.println("COPY_OBJ("+dst+");");
3421 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
3422 output.println("revertlist=(struct ___Object___ *)"+dst+";");
3423 output.println("}");
3425 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
3427 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3428 } else if (statusdst.equals(LocalityAnalysis.EITHER)) {
3429 //writing to a null...bad
3430 output.println("if ("+dst+") {");
3431 output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}");
3433 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
3435 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3438 output.println("}");
3441 if (state.FASTCHECK) {
3442 String dst=generateTemp(fm, fsfn.getDst(),lb);
3443 output.println("if(!"+dst+"->"+localcopystr+") {");
3444 /* Link object into list */
3445 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
3446 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3448 output.println("COPY_OBJ("+dst+");");
3449 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
3450 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
3451 output.println("}");
3453 output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
3457 private void generateFlatElementNode(FlatMethod fm, LocalityBinding lb, FlatElementNode fen, PrintWriter output) {
3458 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
3461 if (elementtype.isArray()||elementtype.isClass())
3464 type=elementtype.getSafeSymbol()+" ";
3466 if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
3467 output.println("if ("+generateTemp(fm, fen.getIndex(),lb)+"< 0 | "+generateTemp(fm, fen.getIndex(),lb)+" >= "+generateTemp(fm,fen.getSrc(),lb) + "->___length___)");
3468 output.println("failedboundschk();");
3470 if (state.SINGLETM) {
3471 //Single machine transaction case
3472 String dst=generateTemp(fm, fen.getDst(),lb);
3473 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3475 if (elementtype.isPtr()&&locality.getAtomic(lb).get(fen).intValue()>0&&
3476 locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())!=LocalityAnalysis.SCRATCH) {
3477 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fen)||state.READSET&&dc.getNeedWriteTrans(lb, fen)) {
3478 output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));");
3479 } else if (state.READSET&&dc.getNeedTrans(lb, fen)) {
3480 output.println("TRANSREADRD("+dst+", "+dst+");");
3483 } else if (state.DSM) {
3484 Integer status=locality.getNodePreTempInfo(lb,fen).get(fen.getSrc());
3485 if (status==LocalityAnalysis.GLOBAL) {
3486 String dst=generateTemp(fm, fen.getDst(),lb);
3488 if (elementtype.isPtr()) {
3489 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3490 output.println("TRANSREAD("+dst+", "+dst+");");
3492 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3494 } else if (status==LocalityAnalysis.LOCAL) {
3495 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3496 } else if (status==LocalityAnalysis.EITHER) {
3497 //Code is reading from a null pointer
3498 output.println("if ("+generateTemp(fm, fen.getSrc(),lb)+") {");
3499 output.println("#ifndef RAW");
3500 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
3501 output.println("#endif");
3502 //This should throw a suitable null pointer error
3503 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3505 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
3507 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3511 private void generateFlatSetElementNode(FlatMethod fm, LocalityBinding lb, FlatSetElementNode fsen, PrintWriter output) {
3512 //TODO: need dynamic check to make sure this assignment is actually legal
3513 //Because Object[] could actually be something more specific...ie. Integer[]
3515 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
3518 if (elementtype.isArray()||elementtype.isClass())
3521 type=elementtype.getSafeSymbol()+" ";
3523 if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
3524 output.println("if ("+generateTemp(fm, fsen.getIndex(),lb)+"< 0 | "+generateTemp(fm, fsen.getIndex(),lb)+" >= "+generateTemp(fm,fsen.getDst(),lb) + "->___length___)");
3525 output.println("failedboundschk();");
3528 if (state.SINGLETM && locality.getAtomic(lb).get(fsen).intValue()>0) {
3529 //Transaction set element case
3530 if (wb.needBarrier(fsen)&&
3531 locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH) {
3532 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___objstatus___))|=DIRTY;");
3534 if (fsen.getSrc().getType().isPtr()&&!fsen.getSrc().getType().isNull()) {
3535 output.println("{");
3536 String src=generateTemp(fm, fsen.getSrc(), lb);
3537 if ((dc==null)||dc.getNeedSrcTrans(lb, fsen)&&
3538 locality.getNodePreTempInfo(lb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) {
3539 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3541 output.println("INTPTR srcoid=(INTPTR)"+src+";");
3543 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
3544 output.println("}");
3546 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
3548 } else if (state.DSM && locality.getAtomic(lb).get(fsen).intValue()>0) {
3549 Integer statussrc=locality.getNodePreTempInfo(lb,fsen).get(fsen.getSrc());
3550 Integer statusdst=locality.getNodePreTempInfo(lb,fsen).get(fsen.getDst());
3551 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
3552 boolean dstglobal=statusdst==LocalityAnalysis.GLOBAL;
3553 boolean dstlocal=statusdst==LocalityAnalysis.LOCAL;
3556 if (wb.needBarrier(fsen))
3557 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___localcopy___))|=DIRTY;");
3558 } else if (dstlocal) {
3559 /** Check if we need to copy */
3560 String dst=generateTemp(fm, fsen.getDst(),lb);
3561 output.println("if(!"+dst+"->"+localcopystr+") {");
3562 /* Link object into list */
3563 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3564 output.println(revertptr+"=revertlist;");
3565 if ((GENERATEPRECISEGC) || this.state.MULTICOREGC)
3566 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3568 output.println("COPY_OBJ("+dst+");");
3569 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
3570 output.println("revertlist=(struct ___Object___ *)"+dst+";");
3571 output.println("}");
3572 } else throw new Error("Unknown array type");
3574 output.println("{");
3575 String src=generateTemp(fm, fsen.getSrc(), lb);
3576 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3577 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
3578 output.println("}");
3580 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
3583 if (state.FASTCHECK) {
3584 String dst=generateTemp(fm, fsen.getDst(),lb);
3585 output.println("if(!"+dst+"->"+localcopystr+") {");
3586 /* Link object into list */
3587 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
3588 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3590 output.println("COPY_OBJ("+dst+");");
3591 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
3592 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
3593 output.println("}");
3595 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
3599 protected void generateFlatNew(FlatMethod fm, LocalityBinding lb, FlatNew fn, PrintWriter output) {
3600 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
3601 //Stash pointer in case of GC
3602 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3603 output.println(revertptr+"=revertlist;");
3605 if (state.SINGLETM) {
3606 if (fn.getType().isArray()) {
3607 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
3608 if (locality.getAtomic(lb).get(fn).intValue()>0) {
3609 //inside transaction
3610 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3612 //outside transaction
3613 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3616 if (locality.getAtomic(lb).get(fn).intValue()>0) {
3617 //inside transaction
3618 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
3620 //outside transaction
3621 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
3624 } else if (fn.getType().isArray()) {
3625 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
3626 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
3627 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3628 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3629 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3631 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3634 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
3635 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");");
3636 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3637 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
3639 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
3642 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
3643 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3644 String dst=generateTemp(fm,fn.getDst(),lb);
3645 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
3646 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
3647 output.println("revertlist=(struct ___Object___ *)"+dst+";");
3649 if (state.FASTCHECK) {
3650 String dst=generateTemp(fm,fn.getDst(),lb);
3651 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
3652 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
3653 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
3657 private void generateFlatTagDeclaration(FlatMethod fm, LocalityBinding lb, FlatTagDeclaration fn, PrintWriter output) {
3658 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3659 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
3661 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+state.getTagId(fn.getType())+");");
3665 private void generateFlatOpNode(FlatMethod fm, LocalityBinding lb, FlatOpNode fon, PrintWriter output) {
3666 if (fon.getRight()!=null) {
3667 if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
3668 if (fon.getLeft().getType().isLong())
3669 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
3671 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned int)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
3673 } else if (dc!=null) {
3674 output.print(generateTemp(fm, fon.getDest(),lb)+" = ");
3675 if (dc.getNeedLeftSrcTrans(lb, fon))
3676 output.print("("+generateTemp(fm, fon.getLeft(),lb)+"!=NULL?"+generateTemp(fm, fon.getLeft(),lb)+"->"+oidstr+":NULL)");
3678 output.print(generateTemp(fm, fon.getLeft(),lb));
3679 output.print(fon.getOp().toString());
3680 if (dc.getNeedRightSrcTrans(lb, fon))
3681 output.println("("+generateTemp(fm, fon.getRight(),lb)+"!=NULL?"+generateTemp(fm, fon.getRight(),lb)+"->"+oidstr+":NULL);");
3683 output.println(generateTemp(fm,fon.getRight(),lb)+";");
3685 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+fon.getOp().toString()+generateTemp(fm,fon.getRight(),lb)+";");
3686 } else if (fon.getOp().getOp()==Operation.ASSIGN)
3687 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
3688 else if (fon.getOp().getOp()==Operation.UNARYPLUS)
3689 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
3690 else if (fon.getOp().getOp()==Operation.UNARYMINUS)
3691 output.println(generateTemp(fm, fon.getDest(),lb)+" = -"+generateTemp(fm, fon.getLeft(),lb)+";");
3692 else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
3693 output.println(generateTemp(fm, fon.getDest(),lb)+" = !"+generateTemp(fm, fon.getLeft(),lb)+";");
3694 else if (fon.getOp().getOp()==Operation.COMP)
3695 output.println(generateTemp(fm, fon.getDest(),lb)+" = ~"+generateTemp(fm, fon.getLeft(),lb)+";");
3696 else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
3697 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+"->fses==NULL;");
3699 output.println(generateTemp(fm, fon.getDest(),lb)+fon.getOp().toString()+generateTemp(fm, fon.getLeft(),lb)+";");
3702 private void generateFlatCastNode(FlatMethod fm, LocalityBinding lb, FlatCastNode fcn, PrintWriter output) {
3703 /* TODO: Do type check here */
3704 if (fcn.getType().isArray()) {
3705 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
3706 } else if (fcn.getType().isClass())
3707 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
3709 output.println(generateTemp(fm,fcn.getDst(),lb)+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc(),lb)+";");
3712 private void generateFlatLiteralNode(FlatMethod fm, LocalityBinding lb, FlatLiteralNode fln, PrintWriter output) {
3713 if (fln.getValue()==null)
3714 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
3715 else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
3716 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3717 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
3718 //Stash pointer in case of GC
3719 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3720 output.println(revertptr+"=revertlist;");
3722 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
3723 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
3724 //Stash pointer in case of GC
3725 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3726 output.println("revertlist="+revertptr+";");
3729 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
3731 } else if (fln.getType().isBoolean()) {
3732 if (((Boolean)fln.getValue()).booleanValue())
3733 output.println(generateTemp(fm, fln.getDst(),lb)+"=1;");
3735 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
3736 } else if (fln.getType().isChar()) {
3737 String st=FlatLiteralNode.escapeString(fln.getValue().toString());
3738 output.println(generateTemp(fm, fln.getDst(),lb)+"='"+st+"';");
3739 } else if (fln.getType().isLong()) {
3740 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+"LL;");
3742 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+";");
3745 protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) {
3746 if (frn.getReturnTemp()!=null) {
3747 if (frn.getReturnTemp().getType().isPtr())
3748 output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";");
3750 output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";");
3752 output.println("return;");
3756 protected void generateStoreFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
3757 output.println("STOREANDBRANCH(!"+generateTemp(fm, fcb.getTest(),lb)+", "+label+");");
3760 protected void generateFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
3761 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") goto "+label+";");
3764 /** This method generates header information for the method or
3765 * task referenced by the Descriptor des. */
3766 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) {
3767 generateHeader(fm, lb, des, output, false);
3770 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output, boolean addSESErecord) {
3772 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : des);
3773 MethodDescriptor md=null;
3774 TaskDescriptor task=null;
3775 if (des instanceof MethodDescriptor)
3776 md=(MethodDescriptor) des;
3778 task=(TaskDescriptor) des;
3780 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
3782 if (md!=null&&md.getReturnType()!=null) {
3783 if (md.getReturnType().isClass()||md.getReturnType().isArray())
3784 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
3786 output.print(md.getReturnType().getSafeSymbol()+" ");
3788 //catch the constructor case
3789 output.print("void ");
3791 if (state.DSM||state.SINGLETM) {
3792 output.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
3794 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
3796 output.print(task.getSafeSymbol()+"(");
3798 boolean printcomma=false;
3799 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3801 if (state.DSM||state.SINGLETM) {
3802 output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
3804 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
3806 output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
3812 for(int i=0; i<objectparams.numPrimitives(); i++) {
3813 TempDescriptor temp=objectparams.getPrimitive(i);
3817 if (temp.getType().isClass()||temp.getType().isArray())
3818 output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
3820 output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
3822 output.println(") {");
3823 } else if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
3824 /* Imprecise Task */
3825 output.println("void * parameterarray[]) {");
3826 /* Unpack variables */
3827 for(int i=0; i<objectparams.numPrimitives(); i++) {
3828 TempDescriptor temp=objectparams.getPrimitive(i);
3829 output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
3831 for(int i=0; i<fm.numTags(); i++) {
3832 TempDescriptor temp=fm.getTag(i);
3833 int offset=i+objectparams.numPrimitives();
3834 output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
3837 if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
3838 maxtaskparams=objectparams.numPrimitives()+fm.numTags();
3839 } else output.println(") {");
3842 public void generateFlatFlagActionNode(FlatMethod fm, LocalityBinding lb, FlatFlagActionNode ffan, PrintWriter output) {
3843 output.println("/* FlatFlagActionNode */");
3846 /* Process tag changes */
3847 Relation tagsettable=new Relation();
3848 Relation tagcleartable=new Relation();
3850 Iterator tagsit=ffan.getTempTagPairs();
3851 while (tagsit.hasNext()) {
3852 TempTagPair ttp=(TempTagPair) tagsit.next();
3853 TempDescriptor objtmp=ttp.getTemp();
3854 TagDescriptor tag=ttp.getTag();
3855 TempDescriptor tagtmp=ttp.getTagTemp();
3856 boolean tagstatus=ffan.getTagChange(ttp);
3858 tagsettable.put(objtmp, tagtmp);
3860 tagcleartable.put(objtmp, tagtmp);
3865 Hashtable flagandtable=new Hashtable();
3866 Hashtable flagortable=new Hashtable();
3868 /* Process flag changes */
3869 Iterator flagsit=ffan.getTempFlagPairs();
3870 while(flagsit.hasNext()) {
3871 TempFlagPair tfp=(TempFlagPair)flagsit.next();
3872 TempDescriptor temp=tfp.getTemp();
3873 Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
3874 FlagDescriptor flag=tfp.getFlag();
3876 //Newly allocate objects that don't set any flags case
3877 if (flagortable.containsKey(temp)) {
3881 flagortable.put(temp,new Integer(mask));
3883 int flagid=1<<((Integer)flagtable.get(flag)).intValue();
3884 boolean flagstatus=ffan.getFlagChange(tfp);
3887 if (flagortable.containsKey(temp)) {
3888 mask=((Integer)flagortable.get(temp)).intValue();
3891 flagortable.put(temp,new Integer(mask));
3893 int mask=0xFFFFFFFF;
3894 if (flagandtable.containsKey(temp)) {
3895 mask=((Integer)flagandtable.get(temp)).intValue();
3897 mask&=(0xFFFFFFFF^flagid);
3898 flagandtable.put(temp,new Integer(mask));
3904 HashSet flagtagset=new HashSet();
3905 flagtagset.addAll(flagortable.keySet());
3906 flagtagset.addAll(flagandtable.keySet());
3907 flagtagset.addAll(tagsettable.keySet());
3908 flagtagset.addAll(tagcleartable.keySet());
3910 Iterator ftit=flagtagset.iterator();
3911 while(ftit.hasNext()) {
3912 TempDescriptor temp=(TempDescriptor)ftit.next();
3915 Set tagtmps=tagcleartable.get(temp);
3916 if (tagtmps!=null) {
3917 Iterator tagit=tagtmps.iterator();
3918 while(tagit.hasNext()) {
3919 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
3920 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
3921 output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
3923 output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
3927 tagtmps=tagsettable.get(temp);
3928 if (tagtmps!=null) {
3929 Iterator tagit=tagtmps.iterator();
3930 while(tagit.hasNext()) {
3931 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
3932 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
3933 output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
3935 output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp, lb)+", "+generateTemp(fm,tagtmp, lb)+");");
3940 int andmask=0xFFFFFFF;
3942 if (flagortable.containsKey(temp))
3943 ormask=((Integer)flagortable.get(temp)).intValue();
3944 if (flagandtable.containsKey(temp))
3945 andmask=((Integer)flagandtable.get(temp)).intValue();
3946 generateFlagOrAnd(ffan, fm, lb, temp, output, ormask, andmask);
3947 generateObjectDistribute(ffan, fm, lb, temp, output);
3951 protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp,
3952 PrintWriter output, int ormask, int andmask) {
3953 if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
3954 output.println("flagorandinit("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
3956 output.println("flagorand("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
3960 protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, PrintWriter output) {
3961 output.println("enqueueObject("+generateTemp(fm, temp, lb)+");");
3964 void generateOptionalHeader(PrintWriter headers) {
3967 headers.println("#include \"task.h\"\n\n");
3968 headers.println("#ifndef _OPTIONAL_STRUCT_");
3969 headers.println("#define _OPTIONAL_STRUCT_");
3971 //STRUCT PREDICATEMEMBER
3972 headers.println("struct predicatemember{");
3973 headers.println("int type;");
3974 headers.println("int numdnfterms;");
3975 headers.println("int * flags;");
3976 headers.println("int numtags;");
3977 headers.println("int * tags;\n};\n\n");
3979 //STRUCT OPTIONALTASKDESCRIPTOR
3980 headers.println("struct optionaltaskdescriptor{");
3981 headers.println("struct taskdescriptor * task;");
3982 headers.println("int index;");
3983 headers.println("int numenterflags;");
3984 headers.println("int * enterflags;");
3985 headers.println("int numpredicatemembers;");
3986 headers.println("struct predicatemember ** predicatememberarray;");
3987 headers.println("};\n\n");
3989 //STRUCT TASKFAILURE
3990 headers.println("struct taskfailure {");
3991 headers.println("struct taskdescriptor * task;");
3992 headers.println("int index;");
3993 headers.println("int numoptionaltaskdescriptors;");
3994 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
3996 //STRUCT FSANALYSISWRAPPER
3997 headers.println("struct fsanalysiswrapper{");
3998 headers.println("int flags;");
3999 headers.println("int numtags;");
4000 headers.println("int * tags;");
4001 headers.println("int numtaskfailures;");
4002 headers.println("struct taskfailure ** taskfailurearray;");
4003 headers.println("int numoptionaltaskdescriptors;");
4004 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
4006 //STRUCT CLASSANALYSISWRAPPER
4007 headers.println("struct classanalysiswrapper{");
4008 headers.println("int type;");
4009 headers.println("int numotd;");
4010 headers.println("struct optionaltaskdescriptor ** otdarray;");
4011 headers.println("int numfsanalysiswrappers;");
4012 headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
4014 headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
4016 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
4017 while(taskit.hasNext()) {
4018 TaskDescriptor td=(TaskDescriptor)taskit.next();
4019 headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
4024 //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
4025 int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
4026 int predicateindex = 0;
4027 //iterate through the classes concerned by the predicate
4028 Set c_vard = predicate.vardescriptors;
4029 Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
4032 for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext();) {
4033 VarDescriptor vard = (VarDescriptor)vard_it.next();
4034 TypeDescriptor typed = vard.getType();
4036 //generate for flags
4037 HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
4038 output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4040 if (fen_hashset!=null) {
4041 for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext();) {
4042 FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
4044 DNFFlag dflag=fen.getDNF();
4045 numberterms+=dflag.size();
4047 Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
4049 for(int j=0; j<dflag.size(); j++) {
4051 output.println(",");
4052 Vector term=dflag.get(j);
4055 for(int k=0; k<term.size(); k++) {
4056 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
4057 FlagDescriptor fd=dfa.getFlag();
4058 boolean negated=dfa.getNegated();
4059 int flagid=1<<((Integer)flags.get(fd)).intValue();
4064 output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
4069 output.println("};\n");
4072 TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
4073 output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4076 for(int j=0; j<tagel.numTags(); j++) {
4078 output.println(",");
4079 TempDescriptor tmp=tagel.getTemp(j);
4080 if (!slotnumber.containsKey(tmp)) {
4081 Integer slotint=new Integer(current_slot++);
4082 slotnumber.put(tmp,slotint);
4084 int slot=slotnumber.get(tmp).intValue();
4085 output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
4087 numtags = tagel.numTags();
4089 output.println("};");
4091 //store the result into a predicatemember struct
4092 output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
4093 output.println("/*type*/"+typed.getClassDesc().getId()+",");
4094 output.println("/* number of dnf terms */"+numberterms+",");
4095 output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4096 output.println("/* number of tag */"+numtags+",");
4097 output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4098 output.println("};\n");
4103 //generate an array that stores the entire predicate
4104 output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4105 for( int j = 0; j<predicateindex; j++) {
4106 if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4107 else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4109 output.println("};\n");
4110 return predicateindex;
4114 void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
4115 generateOptionalHeader(headers);
4117 output.println("#include \"optionalstruct.h\"\n\n");
4118 output.println("#include \"stdlib.h\"\n");
4120 HashSet processedcd = new HashSet();
4122 Enumeration e = safeexecution.keys();
4123 while (e.hasMoreElements()) {
4126 ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
4127 Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp); //will be used several times
4129 //Generate the struct of optionals
4130 Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
4131 numotd = c_otd.size();
4132 if(maxotd<numotd) maxotd = numotd;
4133 if( !c_otd.isEmpty() ) {
4134 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
4135 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
4137 //generate the int arrays for the predicate
4138 Predicate predicate = otd.predicate;
4139 int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
4140 TreeSet<Integer> fsset=new TreeSet<Integer>();
4141 //iterate through possible FSes corresponding to
4142 //the state when entering
4144 for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext();) {
4145 FlagState fs = (FlagState)fses.next();
4147 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
4148 FlagDescriptor flagd = (FlagDescriptor)flags.next();
4149 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
4152 fsset.add(new Integer(flagid));
4153 //tag information not needed because tag
4154 //changes are not tolerated.
4157 output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4158 boolean needcomma=false;
4159 for(Iterator<Integer> it=fsset.iterator(); it.hasNext();) {
4162 output.println(it.next());
4165 output.println("};\n");
4168 //generate optionaltaskdescriptor that actually
4169 //includes exit fses, predicate and the task
4171 output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
4172 output.println("&task_"+otd.td.getSafeSymbol()+",");
4173 output.println("/*index*/"+otd.getIndex()+",");
4174 output.println("/*number of enter flags*/"+fsset.size()+",");
4175 output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4176 output.println("/*number of members */"+predicateindex+",");
4177 output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4178 output.println("};\n");
4182 // if there are no optionals, there is no need to build the rest of the struct
4184 output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
4185 c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
4186 if( !c_otd.isEmpty() ) {
4187 boolean needcomma=false;
4188 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
4189 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
4191 output.println(",");
4193 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4196 output.println("};\n");
4198 //get all the possible flagstates reachable by an object
4199 Hashtable hashtbtemp = safeexecution.get(cdtemp);
4201 TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
4202 fsts.addAll(hashtbtemp.keySet());
4203 for(Iterator fsit=fsts.iterator(); fsit.hasNext();) {
4204 FlagState fs = (FlagState)fsit.next();
4207 //get the set of OptionalTaskDescriptors corresponding
4208 HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
4209 //iterate through the OptionalTaskDescriptors and
4210 //store the pointers to the optionals struct (see on
4211 //top) into an array
4213 output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
4214 for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext();) {
4215 OptionalTaskDescriptor mm = mos.next();
4217 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
4219 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4222 output.println("};\n");
4224 //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
4227 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
4228 FlagDescriptor flagd = (FlagDescriptor)flags.next();
4229 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
4233 //process tag information
4236 boolean first = true;
4237 Enumeration tag_enum = fs.getTags();
4238 output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
4239 while(tag_enum.hasMoreElements()) {
4241 TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
4245 output.println(", ");
4246 output.println("/*tagid*/"+state.getTagId(tagd));
4248 output.println("};");
4250 Set<TaskIndex> tiset=sa.getTaskIndex(fs);
4251 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
4252 TaskIndex ti=itti.next();
4256 Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
4258 output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
4259 boolean needcomma=false;
4260 for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext();) {
4261 OptionalTaskDescriptor otd=otdit.next();
4265 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4267 output.println("};");
4269 output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
4270 output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
4271 output.print(ti.getIndex()+", ");
4272 output.print(otdset.size()+", ");
4273 output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
4274 output.println("};");
4277 tiset=sa.getTaskIndex(fs);
4278 boolean needcomma=false;
4280 output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
4281 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
4282 TaskIndex ti=itti.next();
4283 if (ti.isRuntime()) {
4290 output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
4292 output.println("};\n");
4294 //Store the result in fsanalysiswrapper
4296 output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
4297 output.println("/*flag*/"+flagid+",");
4298 output.println("/* number of tags*/"+tagcounter+",");
4299 output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
4300 output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
4301 output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
4302 output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
4303 output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
4304 output.println("};\n");
4308 //Build the array of fsanalysiswrappers
4309 output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
4310 boolean needcomma=false;
4311 for(int i = 0; i<fscounter; i++) {
4312 if (needcomma) output.print(",");
4313 output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
4316 output.println("};");
4318 //Build the classanalysiswrapper referring to the previous array
4319 output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
4320 output.println("/*type*/"+cdtemp.getId()+",");
4321 output.println("/*numotd*/"+numotd+",");
4322 output.println("otdarray"+cdtemp.getSafeSymbol()+",");
4323 output.println("/* number of fsanalysiswrappers */"+fscounter+",");
4324 output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
4325 processedcd.add(cdtemp);
4328 //build an array containing every classes for which code has been build
4329 output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
4330 for(int i=0; i<state.numClasses(); i++) {
4331 ClassDescriptor cn=cdarray[i];
4334 if (processedcd.contains(cn))
4335 output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
4337 output.print("NULL");
4339 output.println("};");
4341 output.println("#define MAXOTD "+maxotd);
4342 headers.println("#endif");
4345 public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
4346 Relation r=new Relation();
4347 for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext();) {
4348 OptionalTaskDescriptor otd=otdit.next();
4349 TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
4353 LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
4354 for(Iterator it=r.keySet().iterator(); it.hasNext();) {
4355 Set s=r.get(it.next());
4356 for(Iterator it2=s.iterator(); it2.hasNext();) {
4357 OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
4365 protected void outputTransCode(PrintWriter output) {