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. */
128 PrintWriter outsandbox=null;
130 public void buildCode() {
131 /* Create output streams to write to */
132 PrintWriter outclassdefs=null;
133 PrintWriter outstructs=null;
134 PrintWriter outrepairstructs=null;
135 PrintWriter outmethodheader=null;
136 PrintWriter outmethod=null;
137 PrintWriter outvirtual=null;
138 PrintWriter outtask=null;
139 PrintWriter outtaskdefs=null;
140 PrintWriter outoptionalarrays=null;
141 PrintWriter optionalheaders=null;
145 outsandbox=new PrintWriter(new FileOutputStream(PREFIX+"sandboxdefs.c"), true);
147 outstructs=new PrintWriter(new FileOutputStream(PREFIX+"structdefs.h"), true);
148 outmethodheader=new PrintWriter(new FileOutputStream(PREFIX+"methodheaders.h"), true);
149 outclassdefs=new PrintWriter(new FileOutputStream(PREFIX+"classdefs.h"), true);
150 outmethod=new PrintWriter(new FileOutputStream(PREFIX+"methods.c"), true);
151 outvirtual=new PrintWriter(new FileOutputStream(PREFIX+"virtualtable.h"), true);
153 outtask=new PrintWriter(new FileOutputStream(PREFIX+"task.h"), true);
154 outtaskdefs=new PrintWriter(new FileOutputStream(PREFIX+"taskdefs.c"), true);
155 if (state.OPTIONAL) {
156 outoptionalarrays=new PrintWriter(new FileOutputStream(PREFIX+"optionalarrays.c"), true);
157 optionalheaders=new PrintWriter(new FileOutputStream(PREFIX+"optionalstruct.h"), true);
160 if (state.structfile!=null) {
161 outrepairstructs=new PrintWriter(new FileOutputStream(PREFIX+state.structfile+".struct"), true);
163 } catch (Exception e) {
168 /* Build the virtual dispatch tables */
169 buildVirtualTables(outvirtual);
171 /* Output includes */
172 outmethodheader.println("#ifndef METHODHEADERS_H");
173 outmethodheader.println("#define METHODHEADERS_H");
174 outmethodheader.println("#include \"structdefs.h\"");
176 outmethodheader.println("#include \"dstm.h\"");
178 outmethodheader.println("#include \"sandbox.h\"");
180 if (state.SINGLETM) {
181 outmethodheader.println("#include \"tm.h\"");
182 outmethodheader.println("#include \"delaycomp.h\"");
184 if (state.ABORTREADERS) {
185 outmethodheader.println("#include \"abortreaders.h\"");
186 outmethodheader.println("#include <setjmp.h>");
189 outmethodheader.println("#include <stdlib.h>");
190 outmethodheader.println("#include <stdio.h>");
191 outmethodheader.println("#include <string.h>");
192 outmethodheader.println("#include \"mlp_runtime.h\"");
193 outmethodheader.println("#include \"psemaphore.h\"");
196 /* Output Structures */
197 outputStructs(outstructs);
199 // Output the C class declarations
200 // These could mutually reference each other
201 outputClassDeclarations(outclassdefs);
203 // Output function prototypes and structures for parameters
204 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
205 while(it.hasNext()) {
206 ClassDescriptor cn=(ClassDescriptor)it.next();
207 generateCallStructs(cn, outclassdefs, outstructs, outmethodheader);
209 outclassdefs.close();
212 /* Map flags to integers */
213 /* The runtime keeps track of flags using these integers */
214 it=state.getClassSymbolTable().getDescriptorsIterator();
215 while(it.hasNext()) {
216 ClassDescriptor cn=(ClassDescriptor)it.next();
220 generateTaskStructs(outstructs, outmethodheader);
222 /* Outputs generic task structures if this is a task
224 outputTaskTypes(outtask);
228 // have to initialize some SESE compiler data before
229 // analyzing normal methods, which must happen before
230 // generating SESE internal code
231 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
232 FlatSESEEnterNode fsen = seseit.next();
233 initializeSESE( fsen );
237 /* Build the actual methods */
238 outputMethods(outmethod);
240 // Output function prototypes and structures for SESE's and code
243 // used to differentiate, during code generation, whether we are
244 // passing over SESE body code, or non-SESE code
247 // first generate code for each sese's internals
248 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
249 FlatSESEEnterNode fsen = seseit.next();
250 generateMethodSESE(fsen, null, outstructs, outmethodheader, outmethod);
253 // then write the invokeSESE switch to decouple scheduler
254 // from having to do unique details of sese invocation
255 generateSESEinvocationMethod(outmethodheader, outmethod);
259 /* Output code for tasks */
260 outputTaskCode(outtaskdefs, outmethod);
262 /* Record maximum number of task parameters */
263 outstructs.println("#define MAXTASKPARAMS "+maxtaskparams);
264 } else if (state.main!=null) {
265 /* Generate main method */
266 outputMainMethod(outmethod);
269 /* Generate information for task with optional parameters */
270 if (state.TASK&&state.OPTIONAL) {
271 generateOptionalArrays(outoptionalarrays, optionalheaders, state.getAnalysisResult(), state.getOptionalTaskDescriptors());
272 outoptionalarrays.close();
275 /* Output structure definitions for repair tool */
276 if (state.structfile!=null) {
277 buildRepairStructs(outrepairstructs);
278 outrepairstructs.close();
282 outmethodheader.println("#endif");
283 outmethodheader.close();
285 outstructs.println("#endif");
290 /* This code just generates the main C method for java programs.
291 * The main C method packs up the arguments into a string array
292 * and passes it to the java main method. */
294 private void outputMainMethod(PrintWriter outmethod) {
295 outmethod.println("int main(int argc, const char *argv[]) {");
296 outmethod.println(" int i;");
299 //outmethod.println(" pthread_once( &mlpOnceObj, mlpInitOncePerThread );");
300 outmethod.println(" workScheduleInit( "+state.MLP_NUMCORES+", invokeSESEmethod );");
304 outmethod.println("#ifdef TRANSSTATS \n");
305 outmethod.println("handle();\n");
306 outmethod.println("#endif\n");
308 if (state.THREAD||state.DSM||state.SINGLETM) {
309 outmethod.println("initializethreads();");
312 outmethod.println("if (dstmStartup(argv[1])) {");
313 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
314 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-2);");
316 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-2);");
319 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
320 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1);");
322 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1);");
326 outmethod.println(" for(i=2;i<argc;i++) {");
328 outmethod.println(" for(i=1;i<argc;i++) {");
329 outmethod.println(" int length=strlen(argv[i]);");
330 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
331 outmethod.println(" struct ___String___ *newstring=NewString(NULL, argv[i], length);");
333 outmethod.println(" struct ___String___ *newstring=NewString(argv[i], length);");
336 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-2]=newstring;");
338 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-1]=newstring;");
339 outmethod.println(" }");
341 MethodDescriptor md=typeutil.getMain();
342 ClassDescriptor cd=typeutil.getMainClass();
344 outmethod.println(" {");
345 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
346 if (state.DSM||state.SINGLETM) {
347 outmethod.print(" struct "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
349 outmethod.print(" struct "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
350 outmethod.println("1, NULL,"+"stringarray};");
351 if (state.DSM||state.SINGLETM)
352 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
354 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
356 if (state.DSM||state.SINGLETM)
357 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
359 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
361 outmethod.println(" }");
364 outmethod.println("}");
367 if (state.THREAD||state.DSM||state.SINGLETM) {
368 outmethod.println("pthread_mutex_lock(&gclistlock);");
369 outmethod.println("threadcount--;");
370 outmethod.println("pthread_cond_signal(&gccond);");
371 outmethod.println("pthread_mutex_unlock(&gclistlock);");
374 if (state.DSM||state.SINGLETM) {
375 outmethod.println("#ifdef TRANSSTATS \n");
376 outmethod.println("printf(\"****** Transaction Stats ******\\n\");");
377 outmethod.println("printf(\"numTransCommit= %d\\n\", numTransCommit);");
378 outmethod.println("printf(\"numTransAbort= %d\\n\", numTransAbort);");
379 outmethod.println("printf(\"nSoftAbort= %d\\n\", nSoftAbort);");
381 outmethod.println("printf(\"nchashSearch= %d\\n\", nchashSearch);");
382 outmethod.println("printf(\"nmhashSearch= %d\\n\", nmhashSearch);");
383 outmethod.println("printf(\"nprehashSearch= %d\\n\", nprehashSearch);");
384 outmethod.println("printf(\"nRemoteReadSend= %d\\n\", nRemoteSend);");
385 outmethod.println("printf(\"getResponse= %d\\n\", getResponse);");
386 outmethod.println("printf(\"bytesSent= %d\\n\", bytesSent);");
387 outmethod.println("printf(\"bytesRecv= %d\\n\", bytesRecv);");
388 } else if (state.SINGLETM) {
389 outmethod.println("printf(\"nSoftAbortAbort= %d\\n\", nSoftAbortAbort);");
390 outmethod.println("printf(\"nSoftAbortCommit= %d\\n\", nSoftAbortCommit);");
391 outmethod.println("#ifdef STMSTATS\n");
392 outmethod.println("for(i=0; i<TOTALNUMCLASSANDARRAY; i++) {\n");
393 outmethod.println(" printf(\"typesCausingAbort[%2d] numaccess= %5d numabort= %3d\\n\", i, typesCausingAbort[i].numaccess, typesCausingAbort[i].numabort);\n");
394 outmethod.println("}\n");
395 outmethod.println("#endif\n");
396 outmethod.println("fflush(stdout);");
398 outmethod.println("#endif\n");
401 if (state.THREAD||state.SINGLETM)
402 outmethod.println("pthread_exit(NULL);");
405 outmethod.println(" workScheduleBegin();");
408 outmethod.println("}");
411 /* This method outputs code for each task. */
413 private void outputTaskCode(PrintWriter outtaskdefs, PrintWriter outmethod) {
414 /* Compile task based program */
415 outtaskdefs.println("#include \"task.h\"");
416 outtaskdefs.println("#include \"methodheaders.h\"");
417 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
418 while(taskit.hasNext()) {
419 TaskDescriptor td=(TaskDescriptor)taskit.next();
420 FlatMethod fm=state.getMethodFlat(td);
421 generateFlatMethod(fm, null, outmethod);
422 generateTaskDescriptor(outtaskdefs, fm, td);
425 //Output task descriptors
426 taskit=state.getTaskSymbolTable().getDescriptorsIterator();
427 outtaskdefs.println("struct taskdescriptor * taskarray[]= {");
429 while(taskit.hasNext()) {
430 TaskDescriptor td=(TaskDescriptor)taskit.next();
434 outtaskdefs.println(",");
435 outtaskdefs.print("&task_"+td.getSafeSymbol());
437 outtaskdefs.println("};");
439 outtaskdefs.println("int numtasks="+state.getTaskSymbolTable().getValueSet().size()+";");
442 /* This method outputs most of the methods.c file. This includes
443 * some standard includes and then an array with the sizes of
444 * objets and array that stores supertype and then the code for
445 * the Java methods.. */
447 protected void outputMethods(PrintWriter outmethod) {
448 outmethod.println("#include \"methodheaders.h\"");
449 outmethod.println("#include \"virtualtable.h\"");
450 outmethod.println("#include \"runtime.h\"");
452 outmethod.println("#include \"sandboxdefs.c\"");
455 outmethod.println("#include \"addPrefetchEnhance.h\"");
456 outmethod.println("#include \"localobjects.h\"");
458 if (state.FASTCHECK) {
459 outmethod.println("#include \"localobjects.h\"");
461 if(state.MULTICORE) {
462 outmethod.println("#include \"task.h\"");
463 outmethod.println("#include \"multicoreruntime.h\"");
464 outmethod.println("#include \"runtime_arch.h\"");
466 if (state.THREAD||state.DSM||state.SINGLETM)
467 outmethod.println("#include <thread.h>");
468 if (state.main!=null) {
469 outmethod.println("#include <string.h>");
471 if (state.CONSCHECK) {
472 outmethod.println("#include \"checkers.h\"");
475 outmethod.println("#include <stdlib.h>");
476 outmethod.println("#include <stdio.h>");
477 outmethod.println("#include \"mlp_runtime.h\"");
478 outmethod.println("#include \"psemaphore.h\"");
482 //Store the sizes of classes & array elements
483 generateSizeArray(outmethod);
485 //Store table of supertypes
486 generateSuperTypeTable(outmethod);
488 //Store the layout of classes
489 generateLayoutStructs(outmethod);
491 /* Generate code for methods */
492 if (state.DSM||state.SINGLETM) {
493 for(Iterator<LocalityBinding> lbit=locality.getLocalityBindings().iterator(); lbit.hasNext();) {
494 LocalityBinding lb=lbit.next();
495 MethodDescriptor md=lb.getMethod();
496 FlatMethod fm=state.getMethodFlat(md);
498 if (!md.getModifiers().isNative()) {
499 generateFlatMethod(fm, lb, outmethod);
503 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
504 while(classit.hasNext()) {
505 ClassDescriptor cn=(ClassDescriptor)classit.next();
506 Iterator methodit=cn.getMethods();
507 while(methodit.hasNext()) {
508 /* Classify parameters */
509 MethodDescriptor md=(MethodDescriptor)methodit.next();
510 FlatMethod fm=state.getMethodFlat(md);
511 if (!md.getModifiers().isNative()) {
512 generateFlatMethod(fm, null, outmethod);
519 protected void outputStructs(PrintWriter outstructs) {
520 outstructs.println("#ifndef STRUCTDEFS_H");
521 outstructs.println("#define STRUCTDEFS_H");
522 outstructs.println("#include \"classdefs.h\"");
523 outstructs.println("#ifndef INTPTR");
524 outstructs.println("#ifdef BIT64");
525 outstructs.println("#define INTPTR long");
526 outstructs.println("#else");
527 outstructs.println("#define INTPTR int");
528 outstructs.println("#endif");
529 outstructs.println("#endif");
531 outstructs.println("#include \"mlp_runtime.h\"");
532 outstructs.println("#include \"psemaphore.h\"");
535 /* Output #defines that the runtime uses to determine type
536 * numbers for various objects it needs */
537 outstructs.println("#define MAXCOUNT "+maxcount);
538 if (state.DSM||state.SINGLETM) {
539 LocalityBinding lbrun=new LocalityBinding(typeutil.getRun(), false);
541 lbrun.setGlobalThis(LocalityAnalysis.GLOBAL);
543 else if (state.SINGLETM) {
544 lbrun.setGlobalThis(LocalityAnalysis.NORMAL);
546 outstructs.println("#define RUNMETHOD "+virtualcalls.getLocalityNumber(lbrun));
550 LocalityBinding lbexecute = new LocalityBinding(typeutil.getExecute(), false);
552 lbexecute.setGlobalThis(LocalityAnalysis.GLOBAL);
553 else if( state.SINGLETM)
554 lbexecute.setGlobalThis(LocalityAnalysis.NORMAL);
555 outstructs.println("#define EXECUTEMETHOD " + virtualcalls.getLocalityNumber(lbexecute));
558 outstructs.println("#define STRINGARRAYTYPE "+
559 (state.getArrayNumber(
560 (new TypeDescriptor(typeutil.getClass(TypeUtil.StringClass))).makeArray(state))+state.numClasses()));
562 outstructs.println("#define OBJECTARRAYTYPE "+
563 (state.getArrayNumber(
564 (new TypeDescriptor(typeutil.getClass(TypeUtil.ObjectClass))).makeArray(state))+state.numClasses()));
567 outstructs.println("#define STRINGTYPE "+typeutil.getClass(TypeUtil.StringClass).getId());
568 outstructs.println("#define CHARARRAYTYPE "+
569 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.CHAR)).makeArray(state))+state.numClasses()));
571 outstructs.println("#define BYTEARRAYTYPE "+
572 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state))+state.numClasses()));
574 outstructs.println("#define BYTEARRAYARRAYTYPE "+
575 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state).makeArray(state))+state.numClasses()));
577 outstructs.println("#define NUMCLASSES "+state.numClasses());
578 int totalClassSize = state.numClasses() + state.numArrays();
579 outstructs.println("#define TOTALNUMCLASSANDARRAY "+ totalClassSize);
581 outstructs.println("#define STARTUPTYPE "+typeutil.getClass(TypeUtil.StartupClass).getId());
582 outstructs.println("#define TAGTYPE "+typeutil.getClass(TypeUtil.TagClass).getId());
583 outstructs.println("#define TAGARRAYTYPE "+
584 (state.getArrayNumber(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)).makeArray(state))+state.numClasses()));
588 protected void outputClassDeclarations(PrintWriter outclassdefs) {
589 if (state.THREAD||state.DSM||state.SINGLETM)
590 outclassdefs.println("#include <pthread.h>");
591 outclassdefs.println("#ifndef INTPTR");
592 outclassdefs.println("#ifdef BIT64");
593 outclassdefs.println("#define INTPTR long");
594 outclassdefs.println("#else");
595 outclassdefs.println("#define INTPTR int");
596 outclassdefs.println("#endif");
597 outclassdefs.println("#endif");
599 outclassdefs.println("#include \"optionalstruct.h\"");
600 outclassdefs.println("struct "+arraytype+";");
601 /* Start by declaring all structs */
602 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
603 while(it.hasNext()) {
604 ClassDescriptor cn=(ClassDescriptor)it.next();
605 outclassdefs.println("struct "+cn.getSafeSymbol()+";");
607 outclassdefs.println("");
608 //Print out definition for array type
609 outclassdefs.println("struct "+arraytype+" {");
610 outclassdefs.println(" int type;");
612 outclassdefs.println(" pthread_t tid;");
613 outclassdefs.println(" void * lockentry;");
614 outclassdefs.println(" int lockcount;");
617 outclassdefs.println(" int flag;");
618 if(!state.MULTICORE) {
619 outclassdefs.println(" void * flagptr;");
621 outclassdefs.println(" int version;");
622 outclassdefs.println(" int * lock;"); // lock entry for this obj
623 outclassdefs.println(" int mutex;");
624 outclassdefs.println(" int lockcount;");
625 if(state.MULTICOREGC) {
626 outclassdefs.println(" int marked;");
630 outclassdefs.println(" int numfses;");
631 outclassdefs.println(" int * fses;");
634 printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs);
637 outclassdefs.println(" int paddingforarray;");
639 outclassdefs.println(" int ___length___;");
640 outclassdefs.println("};\n");
641 outclassdefs.println("extern int classsize[];");
642 outclassdefs.println("extern int hasflags[];");
643 outclassdefs.println("extern unsigned INTPTR * pointerarray[];");
644 outclassdefs.println("extern int supertypes[];");
647 /** Prints out definitions for generic task structures */
649 private void outputTaskTypes(PrintWriter outtask) {
650 outtask.println("#ifndef _TASK_H");
651 outtask.println("#define _TASK_H");
652 outtask.println("struct parameterdescriptor {");
653 outtask.println("int type;");
654 outtask.println("int numberterms;");
655 outtask.println("int *intarray;");
656 outtask.println("void * queue;");
657 outtask.println("int numbertags;");
658 outtask.println("int *tagarray;");
659 outtask.println("};");
661 outtask.println("struct taskdescriptor {");
662 outtask.println("void * taskptr;");
663 outtask.println("int numParameters;");
664 outtask.println(" int numTotal;");
665 outtask.println("struct parameterdescriptor **descriptorarray;");
666 outtask.println("char * name;");
667 outtask.println("};");
668 outtask.println("extern struct taskdescriptor * taskarray[];");
669 outtask.println("extern numtasks;");
670 outtask.println("#endif");
674 private void buildRepairStructs(PrintWriter outrepairstructs) {
675 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
676 while(classit.hasNext()) {
677 ClassDescriptor cn=(ClassDescriptor)classit.next();
678 outrepairstructs.println("structure "+cn.getSymbol()+" {");
679 outrepairstructs.println(" int __type__;");
681 outrepairstructs.println(" int __flag__;");
682 if(!state.MULTICORE) {
683 outrepairstructs.println(" int __flagptr__;");
686 printRepairStruct(cn, outrepairstructs);
687 outrepairstructs.println("}\n");
690 for(int i=0; i<state.numArrays(); i++) {
691 TypeDescriptor tdarray=arraytable[i];
692 TypeDescriptor tdelement=tdarray.dereference();
693 outrepairstructs.println("structure "+arraytype+"_"+state.getArrayNumber(tdarray)+" {");
694 outrepairstructs.println(" int __type__;");
695 printRepairStruct(typeutil.getClass(TypeUtil.ObjectClass), outrepairstructs);
696 outrepairstructs.println(" int length;");
698 // Need to add support to repair tool for this
699 if (tdelement.isClass()||tdelement.isArray())
700 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" * elem[this.length];");
702 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" elem[this.length];");
704 outrepairstructs.println("}\n");
708 private void printRepairStruct(ClassDescriptor cn, PrintWriter output) {
709 ClassDescriptor sp=cn.getSuperDesc();
711 printRepairStruct(sp, output);
713 Vector fields=(Vector)fieldorder.get(cn);
715 for(int i=0; i<fields.size(); i++) {
716 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
717 if (fd.getType().isArray()) {
718 output.println(" "+arraytype+"_"+ state.getArrayNumber(fd.getType()) +" * "+fd.getSymbol()+";");
719 } else if (fd.getType().isClass())
720 output.println(" "+fd.getType().getRepairSymbol()+" * "+fd.getSymbol()+";");
721 else if (fd.getType().isFloat())
722 output.println(" int "+fd.getSymbol()+"; /* really float */");
724 output.println(" "+fd.getType().getRepairSymbol()+" "+fd.getSymbol()+";");
728 /** This method outputs TaskDescriptor information */
729 private void generateTaskDescriptor(PrintWriter output, FlatMethod fm, TaskDescriptor task) {
730 for (int i=0; i<task.numParameters(); i++) {
731 VarDescriptor param_var=task.getParameter(i);
732 TypeDescriptor param_type=task.getParamType(i);
733 FlagExpressionNode param_flag=task.getFlag(param_var);
734 TagExpressionList param_tag=task.getTag(param_var);
737 if (param_flag==null) {
738 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
739 output.println("0x0, 0x0 };");
742 DNFFlag dflag=param_flag.getDNF();
743 dnfterms=dflag.size();
745 Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
746 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
747 for(int j=0; j<dflag.size(); j++) {
750 Vector term=dflag.get(j);
753 for(int k=0; k<term.size(); k++) {
754 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
755 FlagDescriptor fd=dfa.getFlag();
756 boolean negated=dfa.getNegated();
757 int flagid=1<<((Integer)flags.get(fd)).intValue();
762 output.print("0x"+Integer.toHexString(andmask)+", 0x"+Integer.toHexString(checkmask));
764 output.println("};");
767 output.println("int parametertag_"+i+"_"+task.getSafeSymbol()+"[]={");
768 //BUG...added next line to fix, test with any task program
770 for(int j=0; j<param_tag.numTags(); j++) {
773 /* for each tag we need */
774 /* which slot it is */
775 /* what type it is */
776 TagVarDescriptor tvd=(TagVarDescriptor)task.getParameterTable().get(param_tag.getName(j));
777 TempDescriptor tmp=param_tag.getTemp(j);
778 int slot=fm.getTagInt(tmp);
779 output.println(slot+", "+state.getTagId(tvd.getTag()));
781 output.println("};");
783 output.println("struct parameterdescriptor parameter_"+i+"_"+task.getSafeSymbol()+"={");
784 output.println("/* type */"+param_type.getClassDesc().getId()+",");
785 output.println("/* number of DNF terms */"+dnfterms+",");
786 output.println("parameterdnf_"+i+"_"+task.getSafeSymbol()+",");
787 output.println("0,");
788 //BUG, added next line to fix and else statement...test
789 //with any task program
791 output.println("/* number of tags */"+param_tag.numTags()+",");
793 output.println("/* number of tags */ 0,");
794 output.println("parametertag_"+i+"_"+task.getSafeSymbol());
795 output.println("};");
799 output.println("struct parameterdescriptor * parameterdescriptors_"+task.getSafeSymbol()+"[] = {");
800 for (int i=0; i<task.numParameters(); i++) {
803 output.print("¶meter_"+i+"_"+task.getSafeSymbol());
805 output.println("};");
807 output.println("struct taskdescriptor task_"+task.getSafeSymbol()+"={");
808 output.println("&"+task.getSafeSymbol()+",");
809 output.println("/* number of parameters */" +task.numParameters() + ",");
810 int numtotal=task.numParameters()+fm.numTags();
811 output.println("/* number total parameters */" +numtotal + ",");
812 output.println("parameterdescriptors_"+task.getSafeSymbol()+",");
813 output.println("\""+task.getSymbol()+"\"");
814 output.println("};");
818 /** The buildVirtualTables method outputs the virtual dispatch
819 * tables for methods. */
821 protected void buildVirtualTables(PrintWriter outvirtual) {
822 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
823 while(classit.hasNext()) {
824 ClassDescriptor cd=(ClassDescriptor)classit.next();
825 if (virtualcalls.getMethodCount(cd)>maxcount)
826 maxcount=virtualcalls.getMethodCount(cd);
828 MethodDescriptor[][] virtualtable=null;
829 LocalityBinding[][] lbvirtualtable=null;
830 if (state.DSM||state.SINGLETM)
831 lbvirtualtable=new LocalityBinding[state.numClasses()+state.numArrays()][maxcount];
833 virtualtable=new MethodDescriptor[state.numClasses()+state.numArrays()][maxcount];
835 /* Fill in virtual table */
836 classit=state.getClassSymbolTable().getDescriptorsIterator();
837 while(classit.hasNext()) {
838 ClassDescriptor cd=(ClassDescriptor)classit.next();
839 if (state.DSM||state.SINGLETM)
840 fillinRow(cd, lbvirtualtable, cd.getId());
842 fillinRow(cd, virtualtable, cd.getId());
845 ClassDescriptor objectcd=typeutil.getClass(TypeUtil.ObjectClass);
846 Iterator arrayit=state.getArrayIterator();
847 while(arrayit.hasNext()) {
848 TypeDescriptor td=(TypeDescriptor)arrayit.next();
849 int id=state.getArrayNumber(td);
850 if (state.DSM||state.SINGLETM)
851 fillinRow(objectcd, lbvirtualtable, id+state.numClasses());
853 fillinRow(objectcd, virtualtable, id+state.numClasses());
856 outvirtual.print("void * virtualtable[]={");
857 boolean needcomma=false;
858 for(int i=0; i<state.numClasses()+state.numArrays(); i++) {
859 for(int j=0; j<maxcount; j++) {
861 outvirtual.print(", ");
862 if ((state.DSM||state.SINGLETM)&&lbvirtualtable[i][j]!=null) {
863 LocalityBinding lb=lbvirtualtable[i][j];
864 MethodDescriptor md=lb.getMethod();
865 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
866 } else if (!(state.DSM||state.SINGLETM)&&virtualtable[i][j]!=null) {
867 MethodDescriptor md=virtualtable[i][j];
868 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
870 outvirtual.print("0");
874 outvirtual.println("");
876 outvirtual.println("};");
880 private void fillinRow(ClassDescriptor cd, MethodDescriptor[][] virtualtable, int rownum) {
881 /* Get inherited methods */
882 if (cd.getSuperDesc()!=null)
883 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
884 /* Override them with our methods */
885 for(Iterator it=cd.getMethods(); it.hasNext();) {
886 MethodDescriptor md=(MethodDescriptor)it.next();
887 if (md.isStatic()||md.getReturnType()==null)
889 int methodnum=virtualcalls.getMethodNumber(md);
890 virtualtable[rownum][methodnum]=md;
894 private void fillinRow(ClassDescriptor cd, LocalityBinding[][] virtualtable, int rownum) {
895 /* Get inherited methods */
896 if (cd.getSuperDesc()!=null)
897 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
898 /* Override them with our methods */
899 if (locality.getClassBindings(cd)!=null)
900 for(Iterator<LocalityBinding> lbit=locality.getClassBindings(cd).iterator(); lbit.hasNext();) {
901 LocalityBinding lb=lbit.next();
902 MethodDescriptor md=lb.getMethod();
903 //Is the method static or a constructor
904 if (md.isStatic()||md.getReturnType()==null)
906 int methodnum=virtualcalls.getLocalityNumber(lb);
907 virtualtable[rownum][methodnum]=lb;
911 /** Generate array that contains the sizes of class objects. The
912 * object allocation functions in the runtime use this
915 private void generateSizeArray(PrintWriter outclassdefs) {
916 outclassdefs.print("extern struct prefetchCountStats * evalPrefetch;\n");
917 outclassdefs.print("#ifdef TRANSSTATS \n");
918 outclassdefs.print("extern int numTransAbort;\n");
919 outclassdefs.print("extern int numTransCommit;\n");
920 outclassdefs.print("extern int nSoftAbort;\n");
922 outclassdefs.print("extern int nchashSearch;\n");
923 outclassdefs.print("extern int nmhashSearch;\n");
924 outclassdefs.print("extern int nprehashSearch;\n");
925 outclassdefs.print("extern int nRemoteSend;\n");
926 outclassdefs.print("extern int getResponse;\n");
927 outclassdefs.print("extern int bytesSent;\n");
928 outclassdefs.print("extern int bytesRecv;\n");
929 outclassdefs.print("extern void handle();\n");
930 } else if (state.SINGLETM) {
931 outclassdefs.println("extern int nSoftAbortAbort;");
932 outclassdefs.println("extern int nSoftAbortCommit;");
933 outclassdefs.println("#ifdef STMSTATS\n");
934 outclassdefs.println("extern objtypestat_t typesCausingAbort[];");
935 outclassdefs.println("#endif\n");
937 outclassdefs.print("#endif\n");
938 outclassdefs.print("int numprefetchsites = " + pa.prefetchsiteid + ";\n");
940 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
941 cdarray=new ClassDescriptor[state.numClasses()];
943 while(it.hasNext()) {
944 ClassDescriptor cd=(ClassDescriptor)it.next();
945 cdarray[cd.getId()]=cd;
948 arraytable=new TypeDescriptor[state.numArrays()];
950 Iterator arrayit=state.getArrayIterator();
951 while(arrayit.hasNext()) {
952 TypeDescriptor td=(TypeDescriptor)arrayit.next();
953 int id=state.getArrayNumber(td);
959 /* Print out types */
960 outclassdefs.println("/* ");
961 for(int i=0; i<state.numClasses(); i++) {
962 ClassDescriptor cd=cdarray[i];
964 outclassdefs.println("NULL " + i);
966 outclassdefs.println(cd +" "+i);
970 for(int i=0; i<state.numArrays(); i++) {
971 TypeDescriptor arraytd=arraytable[i];
972 outclassdefs.println(arraytd.toPrettyString() +" "+(i+state.numClasses()));
975 outclassdefs.println("*/");
978 outclassdefs.print("int classsize[]={");
980 boolean needcomma=false;
981 for(int i=0; i<state.numClasses(); i++) {
983 outclassdefs.print(", ");
985 outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")");
987 outclassdefs.print("0");
993 for(int i=0; i<state.numArrays(); i++) {
995 outclassdefs.print(", ");
996 TypeDescriptor tdelement=arraytable[i].dereference();
997 if (tdelement.isArray()||tdelement.isClass())
998 outclassdefs.print("sizeof(void *)");
1000 outclassdefs.print("sizeof("+tdelement.getSafeSymbol()+")");
1004 outclassdefs.println("};");
1006 ClassDescriptor objectclass=typeutil.getClass(TypeUtil.ObjectClass);
1008 outclassdefs.print("int typearray[]={");
1009 for(int i=0; i<state.numClasses(); i++) {
1010 ClassDescriptor cd=cdarray[i];
1011 ClassDescriptor supercd=i>0?cd.getSuperDesc():null;
1013 outclassdefs.print(", ");
1015 outclassdefs.print("-1");
1017 outclassdefs.print(supercd.getId());
1021 for(int i=0; i<state.numArrays(); i++) {
1022 TypeDescriptor arraytd=arraytable[i];
1023 ClassDescriptor arraycd=arraytd.getClassDesc();
1024 if (arraycd==null) {
1026 outclassdefs.print(", ");
1027 outclassdefs.print(objectclass.getId());
1031 ClassDescriptor cd=arraycd.getSuperDesc();
1034 TypeDescriptor supertd=new TypeDescriptor(cd);
1035 supertd.setArrayCount(arraytd.getArrayCount());
1036 type=state.getArrayNumber(supertd);
1038 type+=state.numClasses();
1041 cd=cd.getSuperDesc();
1044 outclassdefs.print(", ");
1045 outclassdefs.print(type);
1049 outclassdefs.println("};");
1054 outclassdefs.print("int typearray2[]={");
1055 for(int i=0; i<state.numArrays(); i++) {
1056 TypeDescriptor arraytd=arraytable[i];
1057 ClassDescriptor arraycd=arraytd.getClassDesc();
1058 if (arraycd==null) {
1060 outclassdefs.print(", ");
1061 outclassdefs.print("-1");
1065 ClassDescriptor cd=arraycd.getSuperDesc();
1066 int level=arraytd.getArrayCount()-1;
1068 for(; level>0; level--) {
1069 TypeDescriptor supertd=new TypeDescriptor(objectclass);
1070 supertd.setArrayCount(level);
1071 type=state.getArrayNumber(supertd);
1073 type+=state.numClasses();
1078 outclassdefs.print(", ");
1079 outclassdefs.print(type);
1083 outclassdefs.println("};");
1086 /** Constructs params and temp objects for each method or task.
1087 * These objects tell the compiler which temps need to be
1090 protected void generateTempStructs(FlatMethod fm, LocalityBinding lb) {
1091 MethodDescriptor md=fm.getMethod();
1092 TaskDescriptor task=fm.getTask();
1093 Set<TempDescriptor> saveset=lb!=null ? locality.getTempSet(lb) : null;
1094 ParamsObject objectparams=md!=null ? new ParamsObject(md,tag++) : new ParamsObject(task, tag++);
1096 paramstable.put(lb, objectparams);
1097 backuptable.put(lb, new Hashtable<TempDescriptor, TempDescriptor>());
1098 } else if (md!=null)
1099 paramstable.put(md, objectparams);
1101 paramstable.put(task, objectparams);
1103 for(int i=0; i<fm.numParameters(); i++) {
1104 TempDescriptor temp=fm.getParameter(i);
1105 TypeDescriptor type=temp.getType();
1106 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1107 objectparams.addPtr(temp);
1109 objectparams.addPrim(temp);
1110 if(lb!=null&&saveset.contains(temp)) {
1111 backuptable.get(lb).put(temp, temp.createNew());
1115 for(int i=0; i<fm.numTags(); i++) {
1116 TempDescriptor temp=fm.getTag(i);
1117 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1118 objectparams.addPtr(temp);
1120 objectparams.addPrim(temp);
1123 TempObject objecttemps=md!=null ? new TempObject(objectparams,md,tag++) : new TempObject(objectparams, task, tag++);
1125 tempstable.put(lb, objecttemps);
1127 tempstable.put(md, objecttemps);
1129 tempstable.put(task, objecttemps);
1131 for(Iterator nodeit=fm.getNodeSet().iterator(); nodeit.hasNext();) {
1132 FlatNode fn=(FlatNode)nodeit.next();
1133 TempDescriptor[] writes=fn.writesTemps();
1134 for(int i=0; i<writes.length; i++) {
1135 TempDescriptor temp=writes[i];
1136 TypeDescriptor type=temp.getType();
1137 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1138 objecttemps.addPtr(temp);
1140 objecttemps.addPrim(temp);
1141 if(lb!=null&&saveset.contains(temp)&&
1142 !backuptable.get(lb).containsKey(temp))
1143 backuptable.get(lb).put(temp, temp.createNew());
1147 /* Create backup temps */
1149 for(Iterator<TempDescriptor> tmpit=backuptable.get(lb).values().iterator(); tmpit.hasNext();) {
1150 TempDescriptor tmp=tmpit.next();
1151 TypeDescriptor type=tmp.getType();
1152 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1153 objecttemps.addPtr(tmp);
1155 objecttemps.addPrim(tmp);
1157 /* Create temp to hold revert table */
1158 if (state.DSM&&(lb.getHasAtomic()||lb.isAtomic())) {
1159 TempDescriptor reverttmp=new TempDescriptor("revertlist", typeutil.getClass(TypeUtil.ObjectClass));
1160 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1161 objecttemps.addPtr(reverttmp);
1163 objecttemps.addPrim(reverttmp);
1164 reverttable.put(lb, reverttmp);
1169 /** This method outputs the following information about classes
1171 * (1) For classes, what are the locations of pointers.
1172 * (2) For arrays, does the array contain pointers or primitives.
1173 * (3) For classes, does the class contain flags.
1176 private void generateLayoutStructs(PrintWriter output) {
1177 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1178 while(it.hasNext()) {
1179 ClassDescriptor cn=(ClassDescriptor)it.next();
1180 output.println("unsigned INTPTR "+cn.getSafeSymbol()+"_pointers[]={");
1181 Iterator allit=cn.getFieldTable().getAllDescriptorsIterator();
1183 while(allit.hasNext()) {
1184 FieldDescriptor fd=(FieldDescriptor)allit.next();
1185 TypeDescriptor type=fd.getType();
1186 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1191 output.print(count);
1192 allit=cn.getFieldTable().getAllDescriptorsIterator();
1193 while(allit.hasNext()) {
1194 FieldDescriptor fd=(FieldDescriptor)allit.next();
1195 TypeDescriptor type=fd.getType();
1196 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1199 output.println(",");
1200 output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+fd.getSafeSymbol()+"))");
1203 output.println("};");
1205 output.println("unsigned INTPTR * pointerarray[]={");
1206 boolean needcomma=false;
1207 for(int i=0; i<state.numClasses(); i++) {
1208 ClassDescriptor cn=cdarray[i];
1210 output.println(",");
1213 output.print(cn.getSafeSymbol()+"_pointers");
1215 output.print("NULL");
1219 for(int i=0; i<state.numArrays(); i++) {
1221 output.println(", ");
1222 TypeDescriptor tdelement=arraytable[i].dereference();
1223 if (tdelement.isArray()||tdelement.isClass())
1224 output.print("((unsigned INTPTR *)1)");
1230 output.println("};");
1232 output.println("int hasflags[]={");
1233 for(int i=0; i<state.numClasses(); i++) {
1234 ClassDescriptor cn=cdarray[i];
1236 output.println(", ");
1238 if ((cn != null) && (cn.hasFlags()))
1243 output.println("};");
1246 /** Print out table to give us supertypes */
1247 private void generateSuperTypeTable(PrintWriter output) {
1248 output.println("int supertypes[]={");
1249 boolean needcomma=false;
1250 for(int i=0; i<state.numClasses(); i++) {
1251 ClassDescriptor cn=cdarray[i];
1253 output.println(",");
1255 if ((cn != null) && (cn.getSuperDesc()!=null)) {
1256 ClassDescriptor cdsuper=cn.getSuperDesc();
1257 output.print(cdsuper.getId());
1261 output.println("};");
1264 /** Force consistent field ordering between inherited classes. */
1266 private void printClassStruct(ClassDescriptor cn, PrintWriter classdefout) {
1268 ClassDescriptor sp=cn.getSuperDesc();
1270 printClassStruct(sp, classdefout);
1272 if (!fieldorder.containsKey(cn)) {
1273 Vector fields=new Vector();
1274 fieldorder.put(cn,fields);
1275 Vector fieldvec=cn.getFieldVec();
1276 for(int i=0;i<fieldvec.size();i++) {
1277 FieldDescriptor fd=(FieldDescriptor)fieldvec.get(i);
1278 if ((sp==null||!sp.getFieldTable().contains(fd.getSymbol())))
1282 Vector fields=(Vector)fieldorder.get(cn);
1284 for(int i=0; i<fields.size(); i++) {
1285 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
1286 if (fd.getType().isClass()||fd.getType().isArray())
1287 classdefout.println(" struct "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1289 classdefout.println(" "+fd.getType().getSafeSymbol()+" "+fd.getSafeSymbol()+";");
1294 /* Map flags to integers consistently between inherited
1297 protected void mapFlags(ClassDescriptor cn) {
1298 ClassDescriptor sp=cn.getSuperDesc();
1302 if (!flagorder.containsKey(cn)) {
1303 Hashtable flags=new Hashtable();
1304 flagorder.put(cn,flags);
1306 Hashtable superflags=(Hashtable)flagorder.get(sp);
1307 Iterator superflagit=superflags.keySet().iterator();
1308 while(superflagit.hasNext()) {
1309 FlagDescriptor fd=(FlagDescriptor)superflagit.next();
1310 Integer number=(Integer)superflags.get(fd);
1311 flags.put(fd, number);
1312 if ((number.intValue()+1)>max)
1313 max=number.intValue()+1;
1317 Iterator flagit=cn.getFlags();
1318 while(flagit.hasNext()) {
1319 FlagDescriptor fd=(FlagDescriptor)flagit.next();
1320 if (sp==null||!sp.getFlagTable().contains(fd.getSymbol()))
1321 flags.put(fd, new Integer(max++));
1327 /** This function outputs (1) structures that parameters are
1328 * passed in (when PRECISE GC is enabled) and (2) function
1329 * prototypes for the methods */
1331 protected void generateCallStructs(ClassDescriptor cn, PrintWriter classdefout, PrintWriter output, PrintWriter headersout) {
1332 /* Output class structure */
1333 classdefout.println("struct "+cn.getSafeSymbol()+" {");
1334 classdefout.println(" int type;");
1336 classdefout.println(" pthread_t tid;");
1337 classdefout.println(" void * lockentry;");
1338 classdefout.println(" int lockcount;");
1342 classdefout.println(" int flag;");
1343 if((!state.MULTICORE) || (cn.getSymbol().equals("TagDescriptor"))) {
1344 classdefout.println(" void * flagptr;");
1345 } else if (state.MULTICORE) {
1346 classdefout.println(" int version;");
1347 classdefout.println(" int * lock;"); // lock entry for this obj
1348 classdefout.println(" int mutex;");
1349 classdefout.println(" int lockcount;");
1350 if(state.MULTICOREGC) {
1351 classdefout.println(" int marked;");
1354 if (state.OPTIONAL) {
1355 classdefout.println(" int numfses;");
1356 classdefout.println(" int * fses;");
1359 printClassStruct(cn, classdefout);
1360 classdefout.println("};\n");
1362 if (state.DSM||state.SINGLETM) {
1363 /* Cycle through LocalityBindings */
1364 HashSet<MethodDescriptor> nativemethods=new HashSet<MethodDescriptor>();
1365 Set<LocalityBinding> lbset=locality.getClassBindings(cn);
1367 for(Iterator<LocalityBinding> lbit=lbset.iterator(); lbit.hasNext();) {
1368 LocalityBinding lb=lbit.next();
1369 MethodDescriptor md=lb.getMethod();
1370 if (md.getModifiers().isNative()) {
1371 //make sure we only print a native method once
1372 if (nativemethods.contains(md)) {
1373 FlatMethod fm=state.getMethodFlat(md);
1374 generateTempStructs(fm, lb);
1377 nativemethods.add(md);
1379 generateMethod(cn, md, lb, headersout, output);
1382 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1383 MethodDescriptor md=(MethodDescriptor)methodit.next();
1384 if (md.getModifiers().isNative()&&!nativemethods.contains(md)) {
1385 //Need to build param structure for library code
1386 FlatMethod fm=state.getMethodFlat(md);
1387 generateTempStructs(fm, null);
1388 generateMethodParam(cn, md, null, output);
1393 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1394 MethodDescriptor md=(MethodDescriptor)methodit.next();
1395 generateMethod(cn, md, null, headersout, output);
1399 private void generateMethodParam(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter output) {
1400 /* Output parameter structure */
1401 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1402 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1403 if ((state.DSM||state.SINGLETM)&&lb!=null)
1404 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1406 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1407 output.println(" INTPTR size;");
1408 output.println(" void * next;");
1409 for(int i=0; i<objectparams.numPointers(); i++) {
1410 TempDescriptor temp=objectparams.getPointer(i);
1411 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1413 output.println("};\n");
1417 private void generateMethod(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter headersout, PrintWriter output) {
1418 FlatMethod fm=state.getMethodFlat(md);
1419 generateTempStructs(fm, lb);
1421 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1422 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md);
1424 generateMethodParam(cn, md, lb, output);
1426 /* Output temp structure */
1427 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1428 if (state.DSM||state.SINGLETM)
1429 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1431 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1432 output.println(" INTPTR size;");
1433 output.println(" void * next;");
1434 for(int i=0; i<objecttemps.numPointers(); i++) {
1435 TempDescriptor temp=objecttemps.getPointer(i);
1436 if (temp.getType().isNull())
1437 output.println(" void * "+temp.getSafeSymbol()+";");
1439 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1441 output.println("};\n");
1444 /********* Output method declaration ***********/
1445 if (state.DSM||state.SINGLETM) {
1446 headersout.println("#define D"+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1448 headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1450 /* First the return type */
1451 if (md.getReturnType()!=null) {
1452 if (md.getReturnType().isClass()||md.getReturnType().isArray())
1453 headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1455 headersout.print(md.getReturnType().getSafeSymbol()+" ");
1457 //catch the constructor case
1458 headersout.print("void ");
1460 /* Next the method name */
1461 if (state.DSM||state.SINGLETM) {
1462 headersout.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1464 headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1466 boolean printcomma=false;
1467 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1468 if (state.DSM||state.SINGLETM) {
1469 headersout.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1471 headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1475 /* Output parameter list*/
1476 for(int i=0; i<objectparams.numPrimitives(); i++) {
1477 TempDescriptor temp=objectparams.getPrimitive(i);
1479 headersout.print(", ");
1481 if (temp.getType().isClass()||temp.getType().isArray())
1482 headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1484 headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1486 headersout.println(");\n");
1490 /** This function outputs (1) structures that parameters are
1491 * passed in (when PRECISE GC is enabled) and (2) function
1492 * prototypes for the tasks */
1494 private void generateTaskStructs(PrintWriter output, PrintWriter headersout) {
1495 /* Cycle through tasks */
1496 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
1498 while(taskit.hasNext()) {
1499 /* Classify parameters */
1500 TaskDescriptor task=(TaskDescriptor)taskit.next();
1501 FlatMethod fm=state.getMethodFlat(task);
1502 generateTempStructs(fm, null);
1504 ParamsObject objectparams=(ParamsObject) paramstable.get(task);
1505 TempObject objecttemps=(TempObject) tempstable.get(task);
1507 /* Output parameter structure */
1508 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1509 output.println("struct "+task.getSafeSymbol()+"_params {");
1511 output.println(" INTPTR size;");
1512 output.println(" void * next;");
1513 for(int i=0; i<objectparams.numPointers(); i++) {
1514 TempDescriptor temp=objectparams.getPointer(i);
1515 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1518 output.println("};\n");
1519 if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
1520 maxtaskparams=objectparams.numPointers()+fm.numTags();
1524 /* Output temp structure */
1525 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1526 output.println("struct "+task.getSafeSymbol()+"_locals {");
1527 output.println(" INTPTR size;");
1528 output.println(" void * next;");
1529 for(int i=0; i<objecttemps.numPointers(); i++) {
1530 TempDescriptor temp=objecttemps.getPointer(i);
1531 if (temp.getType().isNull())
1532 output.println(" void * "+temp.getSafeSymbol()+";");
1533 else if(temp.getType().isTag())
1534 output.println(" struct "+
1535 (new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1537 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1539 output.println("};\n");
1542 /* Output task declaration */
1543 headersout.print("void " + task.getSafeSymbol()+"(");
1545 boolean printcomma=false;
1546 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1547 headersout.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
1549 headersout.print("void * parameterarray[]");
1550 headersout.println(");\n");
1554 /***** Generate code for FlatMethod fm. *****/
1556 Hashtable<FlatAtomicEnterNode, AtomicRecord> atomicmethodmap;
1557 static int atomicmethodcount=0;
1559 private void generateFlatMethod(FlatMethod fm, LocalityBinding lb, PrintWriter output) {
1560 if (State.PRINTFLAT)
1561 System.out.println(fm.printMethod());
1562 MethodDescriptor md=fm.getMethod();
1563 TaskDescriptor task=fm.getTask();
1564 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
1565 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : md!=null ? md : task);
1567 HashSet<AtomicRecord> arset=null;
1569 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1571 if (atomicmethodmap==null)
1572 atomicmethodmap=new Hashtable<FlatAtomicEnterNode, AtomicRecord>();
1574 //fix these so we get right strings for local variables
1575 localsprefixaddr=localsprefix;
1576 localsprefixderef=localsprefix+"->";
1577 arset=new HashSet<AtomicRecord>();
1579 //Generate commit methods here
1580 for(Iterator<FlatNode> fnit=fm.getNodeSet().iterator();fnit.hasNext();) {
1581 FlatNode fn=fnit.next();
1582 if (fn.kind()==FKind.FlatAtomicEnterNode&&
1583 locality.getAtomic(lb).get(fn.getPrev(0)).intValue()==0) {
1584 //We have an atomic enter
1585 FlatAtomicEnterNode faen=(FlatAtomicEnterNode) fn;
1586 Set<FlatNode> exitset=faen.getExits();
1588 String methodname=md.getSymbol()+(atomicmethodcount++);
1589 AtomicRecord ar=new AtomicRecord();
1593 atomicmethodmap.put(faen, ar);
1595 //build data structure declaration
1596 output.println("struct atomicprimitives_"+methodname+" {");
1598 Set<FlatNode> recordset=delaycomp.livecode(lb);
1599 Set<TempDescriptor> liveinto=delaycomp.liveinto(lb, faen, recordset);
1600 Set<TempDescriptor> liveout=delaycomp.liveout(lb, faen);
1601 Set<TempDescriptor> liveoutvirtualread=delaycomp.liveoutvirtualread(lb, faen);
1603 ar.reallivein=new HashSet(liveinto);
1605 ar.liveoutvirtualread=liveoutvirtualread;
1607 for(Iterator<TempDescriptor> it=liveinto.iterator(); it.hasNext();) {
1608 TempDescriptor tmp=it.next();
1609 //remove the pointers
1610 if (tmp.getType().isPtr()) {
1613 //let's print it here
1614 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1617 for(Iterator<TempDescriptor> it=liveout.iterator(); it.hasNext();) {
1618 TempDescriptor tmp=it.next();
1619 //remove the pointers
1620 if (tmp.getType().isPtr()) {
1622 } else if (!liveinto.contains(tmp)) {
1623 //let's print it here
1624 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1627 output.println("};");
1629 //print out method name
1630 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) {");
1631 //build code for commit method
1633 //first define local primitives
1634 Set<TempDescriptor> alltemps=delaycomp.alltemps(lb, faen, recordset);
1635 for(Iterator<TempDescriptor> tmpit=alltemps.iterator();tmpit.hasNext();) {
1636 TempDescriptor tmp=tmpit.next();
1637 if (!tmp.getType().isPtr()) {
1638 if (liveinto.contains(tmp)||liveoutvirtualread.contains(tmp)) {
1639 //read from live into set
1640 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+"=primitives->"+tmp.getSafeSymbol()+";");
1643 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1647 //turn off write barrier generation
1649 state.SINGLETM=false;
1650 generateCode(faen, fm, lb, exitset, output, false);
1651 state.SINGLETM=true;
1652 //turn on write barrier generation
1654 output.println("}\n\n");
1658 //redefine these back to normal
1660 localsprefixaddr="&"+localsprefix;
1661 localsprefixderef=localsprefix+".";
1663 generateHeader(fm, lb, md!=null ? md : task,output);
1664 TempObject objecttemp=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
1666 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1667 for(Iterator<AtomicRecord> arit=arset.iterator();arit.hasNext();) {
1668 AtomicRecord ar=arit.next();
1669 output.println("struct atomicprimitives_"+ar.name+" primitives_"+ar.name+";");
1673 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1674 if (md!=null&&(state.DSM||state.SINGLETM))
1675 output.print(" struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1676 else if (md!=null&&!(state.DSM||state.SINGLETM))
1677 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1679 output.print(" struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={");
1681 output.print(objecttemp.numPointers()+",");
1682 output.print(paramsprefix);
1683 for(int j=0; j<objecttemp.numPointers(); j++)
1684 output.print(", NULL");
1685 output.println("};");
1688 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1689 TempDescriptor td=objecttemp.getPrimitive(i);
1690 TypeDescriptor type=td.getType();
1692 output.println(" void * "+td.getSafeSymbol()+";");
1693 else if (type.isClass()||type.isArray())
1694 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1696 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1701 if( fm.getNext(0) instanceof FlatSESEEnterNode ) {
1702 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
1703 if( callerSESEplaceholder != mlpa.getMainSESE() ) {
1704 // declare variables for naming static SESE's
1705 output.println(" /* static SESE names */");
1706 Iterator<SESEandAgePair> pItr = callerSESEplaceholder.getNeededStaticNames().iterator();
1707 while( pItr.hasNext() ) {
1708 SESEandAgePair p = pItr.next();
1709 output.println(" void* "+p+";");
1712 // declare variables for tracking dynamic sources
1713 output.println(" /* dynamic variable sources */");
1714 Iterator<TempDescriptor> dynSrcItr = callerSESEplaceholder.getDynamicVarSet().iterator();
1715 while( dynSrcItr.hasNext() ) {
1716 TempDescriptor dynSrcVar = dynSrcItr.next();
1717 output.println(" void* "+dynSrcVar+"_srcSESE;");
1718 output.println(" int "+dynSrcVar+"_srcOffset;");
1725 /* Check to see if we need to do a GC if this is a
1726 * multi-threaded program...*/
1728 if (((state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
1729 || this.state.MULTICOREGC) {
1730 //Don't bother if we aren't in recursive methods...The loops case will catch it
1731 if (callgraph.getAllMethods(md).contains(md)) {
1732 if (state.DSM&&lb.isAtomic())
1733 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
1734 else if (this.state.MULTICOREGC) {
1735 output.println("if(gcflag) gc("+localsprefixaddr+");");
1737 output.println("if (needtocollect) checkcollect("+localsprefixaddr+");");
1741 generateCode(fm.getNext(0), fm, lb, null, output, true);
1743 output.println("}\n\n");
1747 protected void initializeSESE( FlatSESEEnterNode fsen ) {
1749 FlatMethod fm = fsen.getfmEnclosing();
1750 MethodDescriptor md = fm.getMethod();
1751 ClassDescriptor cn = md.getClassDesc();
1754 // Creates bogus method descriptor to index into tables
1755 Modifiers modBogus = new Modifiers();
1756 MethodDescriptor mdBogus =
1757 new MethodDescriptor( modBogus,
1758 new TypeDescriptor( TypeDescriptor.VOID ),
1759 "sese_"+fsen.getPrettyIdentifier()+fsen.getIdentifier()
1762 mdBogus.setClassDesc( fsen.getcdEnclosing() );
1763 FlatMethod fmBogus = new FlatMethod( mdBogus, null );
1764 fsen.setfmBogus( fmBogus );
1765 fsen.setmdBogus( mdBogus );
1767 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1768 inSetAndOutSet.addAll( fsen.getInVarSet() );
1769 inSetAndOutSet.addAll( fsen.getOutVarSet() );
1771 // Build paramsobj for bogus method descriptor
1772 ParamsObject objectparams = new ParamsObject( mdBogus, tag++ );
1773 paramstable.put( mdBogus, objectparams );
1775 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1776 while( itr.hasNext() ) {
1777 TempDescriptor temp = itr.next();
1778 TypeDescriptor type = temp.getType();
1779 if( type.isPtr() ) {
1780 objectparams.addPtr( temp );
1782 objectparams.addPrim( temp );
1786 // Build normal temp object for bogus method descriptor
1787 TempObject objecttemps = new TempObject( objectparams, mdBogus, tag++ );
1788 tempstable.put( mdBogus, objecttemps );
1790 for( Iterator nodeit = fsen.getNodeSet().iterator(); nodeit.hasNext(); ) {
1791 FlatNode fn = (FlatNode)nodeit.next();
1792 TempDescriptor[] writes = fn.writesTemps();
1794 for( int i = 0; i < writes.length; i++ ) {
1795 TempDescriptor temp = writes[i];
1796 TypeDescriptor type = temp.getType();
1798 if( type.isPtr() ) {
1799 objecttemps.addPtr( temp );
1801 objecttemps.addPrim( temp );
1807 protected void generateMethodSESE(FlatSESEEnterNode fsen,
1809 PrintWriter outputStructs,
1810 PrintWriter outputMethHead,
1811 PrintWriter outputMethods
1814 ParamsObject objectparams = (ParamsObject) paramstable.get( fsen.getmdBogus() );
1815 TempObject objecttemps = (TempObject) tempstable .get( fsen.getmdBogus() );
1817 // generate locals structure
1818 outputStructs.println("struct "+
1819 fsen.getcdEnclosing().getSafeSymbol()+
1820 fsen.getmdBogus().getSafeSymbol()+"_"+
1821 fsen.getmdBogus().getSafeMethodDescriptor()+
1823 outputStructs.println(" INTPTR size;");
1824 outputStructs.println(" void * next;");
1825 for(int i=0; i<objecttemps.numPointers(); i++) {
1826 TempDescriptor temp=objecttemps.getPointer(i);
1828 if( fsen.getPrettyIdentifier().equals( "calc" ) ) {
1829 System.out.println( " got a pointer "+temp );
1832 if (temp.getType().isNull())
1833 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
1835 outputStructs.println(" struct "+
1836 temp.getType().getSafeSymbol()+" * "+
1837 temp.getSafeSymbol()+";");
1839 outputStructs.println("};\n");
1842 // generate the SESE record structure
1843 outputStructs.println(fsen.getSESErecordName()+" {");
1845 // data common to any SESE, and it must be placed first so
1846 // a module that doesn't know what kind of SESE record this
1847 // is can cast the pointer to a common struct
1848 outputStructs.println(" SESEcommon common;");
1850 // then garbage list stuff
1851 outputStructs.println(" INTPTR size;");
1852 outputStructs.println(" void * next;");
1854 // in-set source tracking
1855 // in-vars that are READY come from parent, don't need anything
1856 // stuff STATIC needs a custom SESE pointer for each age pair
1857 Iterator<SESEandAgePair> itrStaticInVarSrcs = fsen.getStaticInVarSrcs().iterator();
1858 while( itrStaticInVarSrcs.hasNext() ) {
1859 SESEandAgePair srcPair = itrStaticInVarSrcs.next();
1860 outputStructs.println(" "+srcPair.getSESE().getSESErecordName()+"* "+srcPair+";");
1863 // DYNAMIC stuff needs a source SESE ptr and offset
1864 Iterator<TempDescriptor> itrDynInVars = fsen.getDynamicInVarSet().iterator();
1865 while( itrDynInVars.hasNext() ) {
1866 TempDescriptor dynInVar = itrDynInVars.next();
1867 outputStructs.println(" void* "+dynInVar+"_srcSESE;");
1868 outputStructs.println(" int "+dynInVar+"_srcOffset;");
1871 // space for all in and out set primitives
1872 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1873 inSetAndOutSet.addAll( fsen.getInVarSet() );
1874 inSetAndOutSet.addAll( fsen.getOutVarSet() );
1876 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
1878 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1879 while( itr.hasNext() ) {
1880 TempDescriptor temp = itr.next();
1881 TypeDescriptor type = temp.getType();
1882 if( !type.isPtr() ) {
1883 inSetAndOutSetPrims.add( temp );
1887 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
1888 while( itrPrims.hasNext() ) {
1889 TempDescriptor temp = itrPrims.next();
1890 TypeDescriptor type = temp.getType();
1891 outputStructs.println(" "+temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol()+";");
1894 for(int i=0; i<objectparams.numPointers(); i++) {
1895 TempDescriptor temp=objectparams.getPointer(i);
1896 if (temp.getType().isNull())
1897 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
1899 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1902 outputStructs.println("};\n");
1905 // write method declaration to header file
1906 outputMethHead.print("void ");
1907 outputMethHead.print(fsen.getSESEmethodName()+"(");
1908 outputMethHead.print(fsen.getSESErecordName()+"* "+paramsprefix);
1909 outputMethHead.println(");\n");
1912 generateFlatMethodSESE( fsen.getfmBogus(),
1913 fsen.getcdEnclosing(),
1919 private void generateFlatMethodSESE(FlatMethod fm,
1921 FlatSESEEnterNode fsen,
1922 FlatSESEExitNode seseExit,
1926 MethodDescriptor md=fm.getMethod();
1928 output.print("void ");
1929 output.print(fsen.getSESEmethodName()+"(");
1930 output.print(fsen.getSESErecordName()+"* "+paramsprefix);
1931 output.println("){\n");
1933 TempObject objecttemp=(TempObject) tempstable.get(md);
1935 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1936 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1937 output.print(objecttemp.numPointers()+",");
1938 output.print("(void*) &("+paramsprefix+"->size)");
1939 for(int j=0; j<objecttemp.numPointers(); j++)
1940 output.print(", NULL");
1941 output.println("};");
1944 output.println(" /* regular local primitives */");
1945 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1946 TempDescriptor td=objecttemp.getPrimitive(i);
1947 TypeDescriptor type=td.getType();
1949 output.println(" void * "+td.getSafeSymbol()+";");
1950 else if (type.isClass()||type.isArray())
1951 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1953 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1957 // declare variables for naming static SESE's
1958 output.println(" /* static SESE names */");
1959 Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
1960 while( pItr.hasNext() ) {
1961 SESEandAgePair p = pItr.next();
1962 output.println(" void* "+p+";");
1965 // declare variables for tracking dynamic sources
1966 output.println(" /* dynamic variable sources */");
1967 Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
1968 while( dynSrcItr.hasNext() ) {
1969 TempDescriptor dynSrcVar = dynSrcItr.next();
1970 output.println(" void* "+dynSrcVar+"_srcSESE;");
1971 output.println(" int "+dynSrcVar+"_srcOffset;");
1974 // declare local temps for in-set primitives, and if it is
1975 // a ready-source variable, get the value from the record
1976 output.println(" /* local temps for in-set primitives */");
1977 Iterator<TempDescriptor> itrInSet = fsen.getInVarSet().iterator();
1978 while( itrInSet.hasNext() ) {
1979 TempDescriptor temp = itrInSet.next();
1980 TypeDescriptor type = temp.getType();
1981 if( !type.isPtr() ) {
1982 if( fsen.getReadyInVarSet().contains( temp ) ) {
1983 output.println(" "+type+" "+temp+" = "+paramsprefix+"->"+temp+";");
1985 output.println(" "+type+" "+temp+";");
1990 // declare local temps for out-set primitives if its not already
1991 // in the in-set, and it's value will get written so no problem
1992 output.println(" /* local temp for out-set prim, not already in the in-set */");
1993 Iterator<TempDescriptor> itrOutSet = fsen.getOutVarSet().iterator();
1994 while( itrOutSet.hasNext() ) {
1995 TempDescriptor temp = itrOutSet.next();
1996 TypeDescriptor type = temp.getType();
1997 if( !type.isPtr() && !fsen.getInVarSet().contains( temp ) ) {
1998 output.println(" "+type+" "+temp+";");
2002 // copy in-set into place, ready vars were already
2003 // copied when the SESE was issued
2004 Iterator<TempDescriptor> tempItr;
2006 // static vars are from a known SESE
2007 tempItr = fsen.getStaticInVarSet().iterator();
2008 while( tempItr.hasNext() ) {
2009 TempDescriptor temp = tempItr.next();
2010 VariableSourceToken vst = fsen.getStaticInVarSrc( temp );
2011 SESEandAgePair srcPair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2013 // can't grab something from this source until it is done
2014 output.println(" {");
2015 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+srcPair+";" );
2016 output.println(" pthread_mutex_lock( &(com->lock) );");
2017 output.println(" while( com->doneExecuting == FALSE ) {");
2018 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
2019 output.println(" }");
2020 output.println(" pthread_mutex_unlock( &(com->lock) );");
2022 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2023 " = "+paramsprefix+"->"+srcPair+"->"+vst.getAddrVar()+";");
2025 output.println(" }");
2028 // dynamic vars come from an SESE and src
2029 tempItr = fsen.getDynamicInVarSet().iterator();
2030 while( tempItr.hasNext() ) {
2031 TempDescriptor temp = tempItr.next();
2032 TypeDescriptor type = temp.getType();
2034 // go grab it from the SESE source
2035 output.println(" if( "+paramsprefix+"->"+temp+"_srcSESE != NULL ) {");
2037 // gotta wait until the source is done
2038 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+temp+"_srcSESE;" );
2039 output.println(" pthread_mutex_lock( &(com->lock) );");
2040 output.println(" while( com->doneExecuting == FALSE ) {");
2041 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
2042 output.println(" }");
2043 output.println(" pthread_mutex_unlock( &(com->lock) );");
2046 if( type.isNull() ) {
2048 } else if( type.isClass() || type.isArray() ) {
2049 typeStr = "struct "+type.getSafeSymbol()+"*";
2051 typeStr = type.getSafeSymbol();
2054 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2055 " = *(("+typeStr+"*) ("+
2056 paramsprefix+"->"+temp+"_srcSESE + "+
2057 paramsprefix+"->"+temp+"_srcOffset));");
2059 // or if the source was our parent, its in the record to grab
2060 output.println(" } else {");
2061 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2062 " = "+paramsprefix+"->"+temp+";");
2063 output.println(" }");
2066 // Check to see if we need to do a GC if this is a
2067 // multi-threaded program...
2068 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2069 //Don't bother if we aren't in recursive methods...The loops case will catch it
2070 if (callgraph.getAllMethods(md).contains(md)) {
2071 if(this.state.MULTICOREGC) {
2072 output.println("if(gcflag) gc("+localsprefixaddr+");");
2074 output.println("if (needtocollect) checkcollect("+localsprefixaddr+");");
2079 // initialize thread-local var to a non-zero, invalid address
2080 output.println(" seseCaller = (SESEcommon*) 0x2;");
2082 HashSet<FlatNode> exitset=new HashSet<FlatNode>();
2083 exitset.add(seseExit);
2085 generateCode(fsen.getNext(0), fm, null, exitset, output, true);
2087 output.println("}\n\n");
2091 // when a new mlp thread is created for an issued SESE, it is started
2092 // by running this method which blocks on a cond variable until
2093 // it is allowed to transition to execute. Then a case statement
2094 // allows it to invoke the method with the proper SESE body, and after
2095 // exiting the SESE method, executes proper SESE exit code before the
2096 // thread can be destroyed
2097 private void generateSESEinvocationMethod(PrintWriter outmethodheader,
2098 PrintWriter outmethod
2101 outmethodheader.println("void* invokeSESEmethod( void* seseRecord );");
2102 outmethod.println( "void* invokeSESEmethod( void* seseRecord ) {");
2103 outmethod.println( " int status;");
2104 outmethod.println( " char errmsg[128];");
2106 // generate a case for each SESE class that can be invoked
2107 outmethod.println( " switch( *((int*)seseRecord) ) {");
2108 outmethod.println( " ");
2109 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
2110 FlatSESEEnterNode fsen = seseit.next();
2112 outmethod.println( " /* "+fsen.getPrettyIdentifier()+" */");
2113 outmethod.println( " case "+fsen.getIdentifier()+":");
2114 outmethod.println( " "+fsen.getSESEmethodName()+"( seseRecord );");
2116 if( fsen.equals( mlpa.getMainSESE() ) ) {
2117 outmethod.println( " /* work scheduler works forever, explicitly exit */");
2118 outmethod.println( " exit( 0 );");
2121 outmethod.println( " break;");
2122 outmethod.println( "");
2125 // default case should never be taken, error out
2126 outmethod.println( " default:");
2127 outmethod.println( " printf(\"Error: unknown SESE class ID in invoke method.\\n\");");
2128 outmethod.println( " exit(-30);");
2129 outmethod.println( " break;");
2130 outmethod.println( " }");
2131 outmethod.println( " return NULL;");
2132 outmethod.println( "}\n\n");
2136 protected void generateCode(FlatNode first,
2139 Set<FlatNode> stopset,
2140 PrintWriter output, boolean firstpass) {
2142 /* Assign labels to FlatNode's if necessary.*/
2143 Hashtable<FlatNode, Integer> nodetolabel=assignLabels(first, stopset);
2145 Set<FlatNode> storeset=null;
2146 HashSet<FlatNode> genset=null;
2147 Set<FlatNode> unionset=null;
2149 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
2150 storeset=delaycomp.livecode(lb);
2151 genset=new HashSet<FlatNode>();
2153 genset.addAll(delaycomp.getCannotDelay(lb));
2154 genset.addAll(delaycomp.getOther(lb));
2156 genset.addAll(delaycomp.getNotReady(lb));
2158 unionset=new HashSet<FlatNode>();
2159 unionset.addAll(storeset);
2160 unionset.addAll(genset);
2163 /* Do the actual code generation */
2164 FlatNode current_node=null;
2165 HashSet tovisit=new HashSet();
2166 HashSet visited=new HashSet();
2168 tovisit.add(first.getNext(0));
2171 while(current_node!=null||!tovisit.isEmpty()) {
2172 if (current_node==null) {
2173 current_node=(FlatNode)tovisit.iterator().next();
2174 tovisit.remove(current_node);
2175 } else if (tovisit.contains(current_node)) {
2176 tovisit.remove(current_node);
2178 visited.add(current_node);
2179 if (nodetolabel.containsKey(current_node)) {
2180 output.println("L"+nodetolabel.get(current_node)+":");
2182 if (state.INSTRUCTIONFAILURE) {
2183 if (state.THREAD||state.DSM||state.SINGLETM) {
2184 output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
2186 output.println("if ((--instructioncount)==0) injectinstructionfailure();");
2188 if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
2190 if (!state.DELAYCOMP||firstpass) {
2191 generateFlatNode(fm, lb, current_node, output);
2193 //store primitive variables in out set
2194 AtomicRecord ar=atomicmethodmap.get((FlatAtomicEnterNode)first);
2195 Set<TempDescriptor> liveout=ar.liveout;
2196 for(Iterator<TempDescriptor> tmpit=liveout.iterator();tmpit.hasNext();) {
2197 TempDescriptor tmp=tmpit.next();
2198 output.println("primitives->"+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2201 if (state.MLP && stopset!=null) {
2202 assert first.getPrev( 0 ) instanceof FlatSESEEnterNode;
2203 assert current_node instanceof FlatSESEExitNode;
2204 FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev( 0 );
2205 FlatSESEExitNode fsxn = (FlatSESEExitNode) current_node;
2206 assert fsen.getFlatExit().equals( fsxn );
2207 assert fsxn.getFlatEnter().equals( fsen );
2209 if (current_node.kind()!=FKind.FlatReturnNode) {
2210 output.println(" return;");
2213 } else if(current_node.numNext()==1) {
2216 current_node.kind()==FKind.FlatSESEEnterNode &&
2217 !((FlatSESEEnterNode)current_node).getIsCallerSESEplaceholder()
2219 FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
2220 generateFlatNode(fm, lb, current_node, output);
2221 nextnode=fsen.getFlatExit().getNext(0);
2222 } else if (state.DELAYCOMP) {
2223 boolean specialprimitive=false;
2224 //skip literals...no need to add extra overhead
2225 if (storeset!=null&&storeset.contains(current_node)&¤t_node.kind()==FKind.FlatLiteralNode) {
2226 TypeDescriptor typedesc=((FlatLiteralNode)current_node).getType();
2227 if (!typedesc.isClass()&&!typedesc.isArray()) {
2228 specialprimitive=true;
2232 if (genset==null||genset.contains(current_node)||specialprimitive)
2233 generateFlatNode(fm, lb, current_node, output);
2234 if (storeset!=null&&storeset.contains(current_node)&&!specialprimitive) {
2235 TempDescriptor wrtmp=current_node.writesTemps()[0];
2237 //need to store value written by previous node
2238 if (wrtmp.getType().isPtr()) {
2239 //only lock the objects that may actually need locking
2240 if (recorddc.getNeedTrans(lb, current_node)) {
2241 output.println("STOREPTR("+generateTemp(fm, wrtmp,lb)+");");
2243 output.println("STOREPTRNOLOCK("+generateTemp(fm, wrtmp,lb)+");");
2246 output.println("STORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");");
2249 //need to read value read by previous node
2250 if (wrtmp.getType().isPtr()) {
2251 output.println("RESTOREPTR("+generateTemp(fm, wrtmp,lb)+");");
2253 output.println("RESTORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");");
2257 nextnode=current_node.getNext(0);
2260 generateFlatNode(fm, lb, current_node, output);
2261 nextnode=current_node.getNext(0);
2263 if (visited.contains(nextnode)) {
2264 output.println("goto L"+nodetolabel.get(nextnode)+";");
2267 current_node=nextnode;
2268 } else if (current_node.numNext()==2) {
2270 if (state.DELAYCOMP) {
2271 boolean computeside=false;
2273 //need to record which way it should go
2274 if (genset==null||genset.contains(current_node)) {
2275 if (storeset!=null&&storeset.contains(current_node)) {
2276 //need to store which way branch goes
2277 generateStoreFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2279 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2281 //which side to execute
2285 if (genset.contains(current_node)) {
2286 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2287 } else if (storeset.contains(current_node)) {
2289 output.println("RESTOREANDBRANCH(L"+nodetolabel.get(current_node.getNext(1))+");");
2291 //which side to execute
2296 Set<FlatNode> leftset=DelayComputation.getNext(current_node, 0, unionset, lb,locality, true);
2298 if (leftset.size()==0)
2300 if (visited.contains(current_node.getNext(branch))) {
2301 //already visited -- build jump
2302 output.println("goto L"+nodetolabel.get(current_node.getNext(branch))+";");
2305 current_node=current_node.getNext(branch);
2308 if (!visited.contains(current_node.getNext(1)))
2309 tovisit.add(current_node.getNext(1));
2310 if (visited.contains(current_node.getNext(0))) {
2311 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2314 current_node=current_node.getNext(0);
2318 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2319 if (!visited.contains(current_node.getNext(1)))
2320 tovisit.add(current_node.getNext(1));
2321 if (visited.contains(current_node.getNext(0))) {
2322 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2325 current_node=current_node.getNext(0);
2327 } else throw new Error();
2331 /** This method assigns labels to FlatNodes */
2332 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first) {
2333 return assignLabels(first, null);
2336 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
2337 HashSet tovisit=new HashSet();
2338 HashSet visited=new HashSet();
2340 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2343 /*Assign labels first. A node needs a label if the previous
2344 * node has two exits or this node is a join point. */
2346 while(!tovisit.isEmpty()) {
2347 FlatNode fn=(FlatNode)tovisit.iterator().next();
2352 if(lastset!=null&&lastset.contains(fn)) {
2353 // if last is not null and matches, don't go
2354 // any further for assigning labels
2358 for(int i=0; i<fn.numNext(); i++) {
2359 FlatNode nn=fn.getNext(i);
2362 //1) Edge >1 of node
2363 nodetolabel.put(nn,new Integer(labelindex++));
2365 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2369 nodetolabel.put(nn,new Integer(labelindex++));
2377 /** Generate text string that corresponds to the TempDescriptor td. */
2378 protected String generateTemp(FlatMethod fm, TempDescriptor td, LocalityBinding lb) {
2379 MethodDescriptor md=fm.getMethod();
2380 TaskDescriptor task=fm.getTask();
2381 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
2383 if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
2384 //System.out.println("generateTemp returns " + td.getSafeSymbol());
2385 return td.getSafeSymbol();
2388 if (objecttemps.isLocalPtr(td)) {
2389 return localsprefixderef+td.getSafeSymbol();
2392 if (objecttemps.isParamPtr(td)) {
2393 return paramsprefix+"->"+td.getSafeSymbol();
2399 protected void generateFlatNode(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output) {
2401 // insert pre-node actions from the code plan
2404 CodePlan cp = mlpa.getCodePlan( fn );
2407 FlatSESEEnterNode currentSESE = cp.getCurrentSESE();
2409 // for each sese and age pair that this parent statement
2410 // must stall on, take that child's stall semaphore, the
2411 // copying of values comes after the statement
2412 Iterator<VariableSourceToken> vstItr = cp.getStallTokens().iterator();
2413 while( vstItr.hasNext() ) {
2414 VariableSourceToken vst = vstItr.next();
2416 SESEandAgePair p = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2418 output.println(" {");
2419 output.println(" SESEcommon* common = (SESEcommon*) "+p+";");
2421 output.println(" pthread_mutex_lock( &(common->lock) );");
2422 output.println(" while( common->doneExecuting == FALSE ) {");
2423 output.println(" pthread_cond_wait( &(common->doneCond), &(common->lock) );");
2424 output.println(" }");
2425 output.println(" pthread_mutex_unlock( &(common->lock) );");
2427 //output.println(" psem_take( &(common->stallSem) );");
2429 // copy things we might have stalled for
2430 output.println(" "+p.getSESE().getSESErecordName()+"* child = ("+
2431 p.getSESE().getSESErecordName()+"*) "+p+";");
2433 Iterator<TempDescriptor> tdItr = cp.getCopySet( vst ).iterator();
2434 while( tdItr.hasNext() ) {
2435 TempDescriptor td = tdItr.next();
2436 FlatMethod fmContext;
2437 if( currentSESE.getIsCallerSESEplaceholder() ) {
2438 fmContext = currentSESE.getfmEnclosing();
2440 fmContext = currentSESE.getfmBogus();
2442 output.println(" "+generateTemp( fmContext, td, null )+
2443 " = child->"+vst.getAddrVar().getSafeSymbol()+";");
2446 output.println(" }");
2449 // for each variable with a dynamic source, stall just for that variable
2450 Iterator<TempDescriptor> dynItr = cp.getDynamicStallSet().iterator();
2451 while( dynItr.hasNext() ) {
2452 TempDescriptor dynVar = dynItr.next();
2454 // only stall if the dynamic source is not yourself, denoted by src==NULL
2455 // otherwise the dynamic write nodes will have the local var up-to-date
2456 output.println(" {");
2457 output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
2458 output.println(" SESEcommon* common = (SESEcommon*) "+dynVar+"_srcSESE;");
2459 output.println(" psem_take( &(common->stallSem) );");
2461 FlatMethod fmContext;
2462 if( currentSESE.getIsCallerSESEplaceholder() ) {
2463 fmContext = currentSESE.getfmEnclosing();
2465 fmContext = currentSESE.getfmBogus();
2467 output.println(" "+generateTemp( fmContext, dynVar, null )+
2468 " = *(("+dynVar.getType()+"*) ("+
2469 dynVar+"_srcSESE + "+dynVar+"_srcOffset));");
2471 output.println(" }");
2472 output.println(" }");
2475 // for each assignment of a variable to rhs that has a dynamic source,
2476 // copy the dynamic sources
2477 Iterator dynAssignItr = cp.getDynAssigns().entrySet().iterator();
2478 while( dynAssignItr.hasNext() ) {
2479 Map.Entry me = (Map.Entry) dynAssignItr.next();
2480 TempDescriptor lhs = (TempDescriptor) me.getKey();
2481 TempDescriptor rhs = (TempDescriptor) me.getValue();
2482 output.println(" "+lhs+"_srcSESE = "+rhs+"_srcSESE;");
2483 output.println(" "+lhs+"_srcOffset = "+rhs+"_srcOffset;");
2486 // for each lhs that is dynamic from a non-dynamic source, set the
2487 // dynamic source vars to the current SESE
2488 dynItr = cp.getDynAssignCurr().iterator();
2489 while( dynItr.hasNext() ) {
2490 TempDescriptor dynVar = dynItr.next();
2491 output.println(" "+dynVar+"_srcSESE = NULL;");
2497 case FKind.FlatAtomicEnterNode:
2498 generateFlatAtomicEnterNode(fm, lb, (FlatAtomicEnterNode) fn, output);
2501 case FKind.FlatAtomicExitNode:
2502 generateFlatAtomicExitNode(fm, lb, (FlatAtomicExitNode) fn, output);
2505 case FKind.FlatInstanceOfNode:
2506 generateFlatInstanceOfNode(fm, lb, (FlatInstanceOfNode)fn, output);
2509 case FKind.FlatSESEEnterNode:
2510 generateFlatSESEEnterNode(fm, lb, (FlatSESEEnterNode)fn, output);
2513 case FKind.FlatSESEExitNode:
2514 generateFlatSESEExitNode(fm, lb, (FlatSESEExitNode)fn, output);
2517 case FKind.FlatWriteDynamicVarNode:
2518 generateFlatWriteDynamicVarNode(fm, lb, (FlatWriteDynamicVarNode)fn, output);
2521 case FKind.FlatGlobalConvNode:
2522 generateFlatGlobalConvNode(fm, lb, (FlatGlobalConvNode) fn, output);
2525 case FKind.FlatTagDeclaration:
2526 generateFlatTagDeclaration(fm, lb, (FlatTagDeclaration) fn,output);
2529 case FKind.FlatCall:
2530 generateFlatCall(fm, lb, (FlatCall) fn,output);
2533 case FKind.FlatFieldNode:
2534 generateFlatFieldNode(fm, lb, (FlatFieldNode) fn,output);
2537 case FKind.FlatElementNode:
2538 generateFlatElementNode(fm, lb, (FlatElementNode) fn,output);
2541 case FKind.FlatSetElementNode:
2542 generateFlatSetElementNode(fm, lb, (FlatSetElementNode) fn,output);
2545 case FKind.FlatSetFieldNode:
2546 generateFlatSetFieldNode(fm, lb, (FlatSetFieldNode) fn,output);
2550 generateFlatNew(fm, lb, (FlatNew) fn,output);
2553 case FKind.FlatOpNode:
2554 generateFlatOpNode(fm, lb, (FlatOpNode) fn,output);
2557 case FKind.FlatCastNode:
2558 generateFlatCastNode(fm, lb, (FlatCastNode) fn,output);
2561 case FKind.FlatLiteralNode:
2562 generateFlatLiteralNode(fm, lb, (FlatLiteralNode) fn,output);
2565 case FKind.FlatReturnNode:
2566 generateFlatReturnNode(fm, lb, (FlatReturnNode) fn,output);
2570 output.println("/* nop */");
2573 case FKind.FlatExit:
2574 output.println("/* exit */");
2577 case FKind.FlatBackEdge:
2578 if (state.SINGLETM&&state.SANDBOX&&locality.getAtomic(locality.getAtomic(lb).get(fn).intValue()>0)) {
2579 output.println("if ((--transaction_check_counter)<=0) checkObjects();");
2581 if (((state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
2582 || (this.state.MULTICOREGC)) {
2583 if(state.DSM&&locality.getAtomic(lb).get(fn).intValue()>0) {
2584 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
2585 } else if(this.state.MULTICOREGC) {
2586 output.println("if (gcflag) gc("+localsprefixaddr+");");
2588 output.println("if (needtocollect) checkcollect("+localsprefixaddr+");");
2590 output.println("/* nop */");
2593 case FKind.FlatCheckNode:
2594 generateFlatCheckNode(fm, lb, (FlatCheckNode) fn, output);
2597 case FKind.FlatFlagActionNode:
2598 generateFlatFlagActionNode(fm, lb, (FlatFlagActionNode) fn, output);
2601 case FKind.FlatPrefetchNode:
2602 generateFlatPrefetchNode(fm,lb, (FlatPrefetchNode) fn, output);
2605 case FKind.FlatOffsetNode:
2606 generateFlatOffsetNode(fm, lb, (FlatOffsetNode)fn, output);
2613 // insert post-node actions from the code-plan
2615 CodePlan cp = mlpa.getCodePlan( fn );
2622 public void generateFlatOffsetNode(FlatMethod fm, LocalityBinding lb, FlatOffsetNode fofn, PrintWriter output) {
2623 output.println("/* FlatOffsetNode */");
2624 FieldDescriptor fd=fofn.getField();
2625 output.println(generateTemp(fm, fofn.getDst(),lb)+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+ fd.getSafeSymbol()+");");
2626 output.println("/* offset */");
2629 public void generateFlatPrefetchNode(FlatMethod fm, LocalityBinding lb, FlatPrefetchNode fpn, PrintWriter output) {
2630 if (state.PREFETCH) {
2631 Vector oids = new Vector();
2632 Vector fieldoffset = new Vector();
2633 Vector endoffset = new Vector();
2634 int tuplecount = 0; //Keeps track of number of prefetch tuples that need to be generated
2635 for(Iterator it = fpn.hspp.iterator(); it.hasNext();) {
2636 PrefetchPair pp = (PrefetchPair) it.next();
2637 Integer statusbase = locality.getNodePreTempInfo(lb,fpn).get(pp.base);
2638 /* Find prefetches that can generate oid */
2639 if(statusbase == LocalityAnalysis.GLOBAL) {
2640 generateTransCode(fm, lb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(lb).get(fpn).intValue()>0, false);
2642 } else if (statusbase == LocalityAnalysis.LOCAL) {
2643 generateTransCode(fm,lb,pp,oids,fieldoffset,endoffset,tuplecount,false,true);
2650 System.out.println("Adding prefetch "+fpn+ " to method:" +fm);
2651 output.println("{");
2652 output.println("/* prefetch */");
2653 output.println("/* prefetchid_" + fpn.siteid + " */");
2654 output.println("void * prefptr;");
2655 output.println("int tmpindex;");
2657 output.println("if((evalPrefetch["+fpn.siteid+"].operMode) || (evalPrefetch["+fpn.siteid+"].retrycount <= 0)) {");
2658 /*Create C code for oid array */
2659 output.print(" unsigned int oidarray_[] = {");
2660 boolean needcomma=false;
2661 for (Iterator it = oids.iterator(); it.hasNext();) {
2664 output.print(it.next());
2667 output.println("};");
2669 /*Create C code for endoffset values */
2670 output.print(" unsigned short endoffsetarry_[] = {");
2672 for (Iterator it = endoffset.iterator(); it.hasNext();) {
2675 output.print(it.next());
2678 output.println("};");
2680 /*Create C code for Field Offset Values */
2681 output.print(" short fieldarry_[] = {");
2683 for (Iterator it = fieldoffset.iterator(); it.hasNext();) {
2686 output.print(it.next());
2689 output.println("};");
2690 /* make the prefetch call to Runtime */
2691 output.println(" if(!evalPrefetch["+fpn.siteid+"].operMode) {");
2692 output.println(" evalPrefetch["+fpn.siteid+"].retrycount = RETRYINTERVAL;");
2693 output.println(" }");
2694 output.println(" prefetch("+fpn.siteid+" ,"+tuplecount+", oidarray_, endoffsetarry_, fieldarry_);");
2695 output.println(" } else {");
2696 output.println(" evalPrefetch["+fpn.siteid+"].retrycount--;");
2697 output.println(" }");
2698 output.println("}");
2702 public void generateTransCode(FlatMethod fm, LocalityBinding lb,PrefetchPair pp, Vector oids, Vector fieldoffset, Vector endoffset, int tuplecount, boolean inside, boolean localbase) {
2703 short offsetcount = 0;
2707 } else if (localbase) {
2708 for(; breakindex<pp.desc.size(); breakindex++) {
2709 Descriptor desc=pp.getDescAt(breakindex);
2710 if (desc instanceof FieldDescriptor) {
2711 FieldDescriptor fd=(FieldDescriptor)desc;
2712 if (fd.isGlobal()) {
2720 if (breakindex>pp.desc.size()) //all local
2723 TypeDescriptor lasttype=pp.base.getType();
2724 String basestr=generateTemp(fm, pp.base, lb);
2726 boolean maybenull=fm.getMethod().isStatic()||
2727 !pp.base.equals(fm.getParameter(0));
2729 for(int i=0; i<breakindex; i++) {
2730 String indexcheck="";
2732 Descriptor desc=pp.getDescAt(i);
2733 if (desc instanceof FieldDescriptor) {
2734 FieldDescriptor fd=(FieldDescriptor)desc;
2736 if (!teststr.equals(""))
2738 teststr+="((prefptr="+basestr+")!=NULL)";
2739 basestr="((struct "+lasttype.getSafeSymbol()+" *)prefptr)->"+fd.getSafeSymbol();
2741 basestr=basestr+"->"+fd.getSafeSymbol();
2744 lasttype=fd.getType();
2746 IndexDescriptor id=(IndexDescriptor)desc;
2747 indexcheck="((tmpindex=";
2748 for(int j=0; j<id.tddesc.size(); j++) {
2749 indexcheck+=generateTemp(fm, id.getTempDescAt(j), lb)+"+";
2751 indexcheck+=id.offset+")>=0)&(tmpindex<((struct ArrayObject *)prefptr)->___length___)";
2753 if (!teststr.equals(""))
2755 teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck;
2756 basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]";
2758 lasttype=lasttype.dereference();
2763 if (teststr.equals("")) {
2764 oid="((unsigned int)"+basestr+")";
2766 oid="((unsigned int)(("+teststr+")?"+basestr+":NULL))";
2770 for(int i = breakindex; i < pp.desc.size(); i++) {
2771 String newfieldoffset;
2772 Object desc = pp.getDescAt(i);
2773 if(desc instanceof FieldDescriptor) {
2774 FieldDescriptor fd=(FieldDescriptor)desc;
2775 newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))");
2776 lasttype=fd.getType();
2778 newfieldoffset = "";
2779 IndexDescriptor id=(IndexDescriptor)desc;
2780 for(int j = 0; j < id.tddesc.size(); j++) {
2781 newfieldoffset += generateTemp(fm, id.getTempDescAt(j), lb) + "+";
2783 newfieldoffset += id.offset.toString();
2784 lasttype=lasttype.dereference();
2786 fieldoffset.add(newfieldoffset);
2789 int base=(tuplecount>0) ? ((Short)endoffset.get(tuplecount-1)).intValue() : 0;
2790 base+=pp.desc.size()-breakindex;
2791 endoffset.add(new Short((short)base));
2796 public void generateFlatGlobalConvNode(FlatMethod fm, LocalityBinding lb, FlatGlobalConvNode fgcn, PrintWriter output) {
2797 if (lb!=fgcn.getLocality())
2799 /* Have to generate flat globalconv */
2800 if (fgcn.getMakePtr()) {
2802 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+");");
2804 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fgcn)||state.READSET&&dc.getNeedWriteTrans(lb, fgcn)) {
2805 //need to do translation
2806 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+", (void *)("+localsprefixaddr+"));");
2807 } else if (state.READSET&&dc.getNeedTrans(lb, fgcn)) {
2808 output.println("TRANSREADRD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
2812 /* Need to convert to OID */
2813 if ((dc==null)||dc.getNeedSrcTrans(lb,fgcn)) {
2814 if (fgcn.doConvert()||(delaycomp!=null&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) {
2815 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc(),lb)+");");
2817 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=NULL;");
2823 public void generateFlatInstanceOfNode(FlatMethod fm, LocalityBinding lb, FlatInstanceOfNode fion, PrintWriter output) {
2825 if (fion.getType().isArray()) {
2826 type=state.getArrayNumber(fion.getType())+state.numClasses();
2828 type=fion.getType().getClassDesc().getId();
2831 if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
2832 output.println(generateTemp(fm, fion.getDst(), lb)+"=1;");
2834 output.println(generateTemp(fm, fion.getDst(), lb)+"=instanceof("+generateTemp(fm,fion.getSrc(),lb)+","+type+");");
2837 int sandboxcounter=0;
2838 public void generateFlatAtomicEnterNode(FlatMethod fm, LocalityBinding lb, FlatAtomicEnterNode faen, PrintWriter output) {
2839 /* Check to see if we need to generate code for this atomic */
2840 if (locality==null) {
2841 output.println("pthread_mutex_lock(&atomiclock);");
2845 if (locality.getAtomic(lb).get(faen.getPrev(0)).intValue()>0)
2849 if (state.SANDBOX) {
2850 outsandbox.println("int atomiccounter"+sandboxcounter+"=LOW_CHECK_FREQUENCY;");
2851 output.println("counter_reset_pointer=&atomiccounter"+sandboxcounter+";");
2854 if (state.DELAYCOMP) {
2855 AtomicRecord ar=atomicmethodmap.get(faen);
2857 for(Iterator<TempDescriptor> tmpit=ar.livein.iterator();tmpit.hasNext();) {
2858 TempDescriptor tmp=tmpit.next();
2859 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2862 //copy outs that depend on path
2863 for(Iterator<TempDescriptor> tmpit=ar.liveoutvirtualread.iterator();tmpit.hasNext();) {
2864 TempDescriptor tmp=tmpit.next();
2865 if (!ar.livein.contains(tmp))
2866 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2870 /* Backup the temps. */
2871 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
2872 TempDescriptor tmp=tmpit.next();
2873 output.println(generateTemp(fm, backuptable.get(lb).get(tmp),lb)+"="+generateTemp(fm,tmp,lb)+";");
2876 output.println("goto transstart"+faen.getIdentifier()+";");
2878 /******* Print code to retry aborted transaction *******/
2879 output.println("transretry"+faen.getIdentifier()+":");
2882 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
2883 TempDescriptor tmp=tmpit.next();
2884 output.println(generateTemp(fm, tmp,lb)+"="+generateTemp(fm,backuptable.get(lb).get(tmp),lb)+";");
2888 /********* Need to revert local object store ********/
2889 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
2891 output.println("while ("+revertptr+") {");
2892 output.println("struct ___Object___ * tmpptr;");
2893 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
2894 output.println("REVERT_OBJ("+revertptr+");");
2895 output.println(revertptr+"=tmpptr;");
2896 output.println("}");
2898 /******* Tell the runtime to start the transaction *******/
2900 output.println("transstart"+faen.getIdentifier()+":");
2901 if (state.SANDBOX) {
2902 output.println("transaction_check_counter=*counter_reset_pointer;");
2905 output.println("transStart();");
2907 if (state.ABORTREADERS||state.SANDBOX) {
2909 output.println("abortenabled=1;");
2910 output.println("if (_setjmp(aborttrans)) {");
2911 output.println(" goto transretry"+faen.getIdentifier()+"; }");
2915 public void generateFlatAtomicExitNode(FlatMethod fm, LocalityBinding lb, FlatAtomicExitNode faen, PrintWriter output) {
2916 /* Check to see if we need to generate code for this atomic */
2917 if (locality==null) {
2918 output.println("pthread_mutex_unlock(&atomiclock);");
2921 if (locality.getAtomic(lb).get(faen).intValue()>0)
2923 //store the revert list before we lose the transaction object
2924 String revertptr=null;
2926 revertptr=generateTemp(fm, reverttable.get(lb),lb);
2927 output.println(revertptr+"=revertlist;");
2929 if (state.DELAYCOMP) {
2930 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
2933 output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {");
2935 output.println("if (transCommit()) {");
2936 /* Transaction aborts if it returns true */
2937 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
2939 output.println("} else {");
2940 /* Need to commit local object store */
2941 output.println("while ("+revertptr+") {");
2942 output.println("struct ___Object___ * tmpptr;");
2943 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
2944 output.println("COMMIT_OBJ("+revertptr+");");
2945 output.println(revertptr+"=tmpptr;");
2946 output.println("}");
2948 output.println("}");
2949 if (state.DELAYCOMP) {
2951 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
2952 output.println("else {");
2953 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
2954 TempDescriptor tmp=tmpit.next();
2955 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
2957 output.println("}");
2961 public void generateFlatSESEEnterNode( FlatMethod fm,
2963 FlatSESEEnterNode fsen,
2967 // if MLP flag is off, okay that SESE nodes are in IR graph,
2968 // just skip over them and code generates exactly the same
2973 // there may be an SESE in an unreachable method, skip over
2974 if( !mlpa.getAllSESEs().contains( fsen ) ) {
2978 // also, if we have encountered a placeholder, just skip it
2979 if( fsen.getIsCallerSESEplaceholder() ) {
2983 output.println(" {");
2985 // set up the parent
2986 if( fsen == mlpa.getMainSESE() ) {
2987 output.println(" SESEcommon* parentCommon = NULL;");
2989 if( fsen.getParent() == null ) {
2990 System.out.println( "in "+fm+", "+fsen+" has null parent" );
2992 assert fsen.getParent() != null;
2993 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
2994 output.println(" SESEcommon* parentCommon = &("+paramsprefix+"->common);");
2996 //output.println(" SESEcommon* parentCommon = (SESEcommon*) peekItem( seseCallStack );");
2997 output.println(" SESEcommon* parentCommon = seseCaller;");
3001 // before doing anything, lock your own record and increment the running children
3002 if( fsen != mlpa.getMainSESE() ) {
3003 output.println(" pthread_mutex_lock( &(parentCommon->lock) );");
3004 output.println(" ++(parentCommon->numRunningChildren);");
3005 output.println(" pthread_mutex_unlock( &(parentCommon->lock) );");
3008 // just allocate the space for this record
3009 output.println(" "+fsen.getSESErecordName()+"* seseToIssue = ("+
3010 fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
3011 fsen.getSESErecordName()+" ) );");
3013 // and keep the thread-local sese stack up to date
3014 //output.println(" addNewItem( seseCallStack, (void*) seseToIssue);");
3016 // fill in common data
3017 output.println(" seseToIssue->common.classID = "+fsen.getIdentifier()+";");
3018 output.println(" psem_init( &(seseToIssue->common.stallSem) );");
3020 output.println(" seseToIssue->common.forwardList = createQueue();");
3021 output.println(" seseToIssue->common.unresolvedDependencies = 0;");
3022 output.println(" pthread_cond_init( &(seseToIssue->common.doneCond), NULL );");
3023 output.println(" seseToIssue->common.doneExecuting = FALSE;");
3024 output.println(" pthread_cond_init( &(seseToIssue->common.runningChildrenCond), NULL );");
3025 output.println(" seseToIssue->common.numRunningChildren = 0;");
3026 output.println(" seseToIssue->common.parent = parentCommon;");
3028 // all READY in-vars should be copied now and be done with it
3029 Iterator<TempDescriptor> tempItr = fsen.getReadyInVarSet().iterator();
3030 while( tempItr.hasNext() ) {
3031 TempDescriptor temp = tempItr.next();
3033 // when we are issuing the main SESE or an SESE with placeholder
3034 // caller SESE as parent, generate temp child child's eclosing method,
3035 // otherwise use the parent's enclosing method as the context
3036 boolean useParentContext = false;
3038 if( fsen != mlpa.getMainSESE() ) {
3039 assert fsen.getParent() != null;
3040 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3041 useParentContext = true;
3045 if( useParentContext ) {
3046 output.println(" seseToIssue->"+temp+" = "+
3047 generateTemp( fsen.getParent().getfmBogus(), temp, null )+";");
3049 output.println(" seseToIssue->"+temp+" = "+
3050 generateTemp( fsen.getfmEnclosing(), temp, null )+";");
3054 // before potentially adding this SESE to other forwarding lists,
3055 // create it's lock and take it immediately
3056 output.println(" pthread_mutex_init( &(seseToIssue->common.lock), NULL );");
3057 output.println(" pthread_mutex_lock( &(seseToIssue->common.lock) );");
3059 if( fsen != mlpa.getMainSESE() ) {
3060 // count up outstanding dependencies, static first, then dynamic
3061 Iterator<SESEandAgePair> staticSrcsItr = fsen.getStaticInVarSrcs().iterator();
3062 while( staticSrcsItr.hasNext() ) {
3063 SESEandAgePair srcPair = staticSrcsItr.next();
3064 output.println(" {");
3065 output.println(" SESEcommon* src = (SESEcommon*)"+srcPair+";");
3066 output.println(" pthread_mutex_lock( &(src->lock) );");
3067 output.println(" if( !isEmpty( src->forwardList ) &&");
3068 output.println(" seseToIssue == peekItem( src->forwardList ) ) {");
3069 output.println(" printf( \"This shouldnt already be here\\n\");");
3070 output.println(" exit( -1 );");
3071 output.println(" }");
3072 output.println(" if( !src->doneExecuting ) {");
3073 output.println(" addNewItem( src->forwardList, seseToIssue );");
3074 output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3075 output.println(" }");
3076 output.println(" pthread_mutex_unlock( &(src->lock) );");
3077 output.println(" }");
3079 // whether or not it is an outstanding dependency, make sure
3080 // to pass the static name to the child's record
3081 output.println(" seseToIssue->"+srcPair+" = "+srcPair+";");
3084 // dynamic sources might already be accounted for in the static list,
3085 // so only add them to forwarding lists if they're not already there
3086 Iterator<TempDescriptor> dynVarsItr = fsen.getDynamicInVarSet().iterator();
3087 while( dynVarsItr.hasNext() ) {
3088 TempDescriptor dynInVar = dynVarsItr.next();
3089 output.println(" {");
3090 output.println(" SESEcommon* src = (SESEcommon*)"+dynInVar+"_srcSESE;");
3092 // the dynamic source is NULL if it comes from your own space--you can't pass
3093 // the address off to the new child, because you're not done executing and
3094 // might change the variable, so copy it right now
3095 output.println(" if( src != NULL ) {");
3096 output.println(" pthread_mutex_lock( &(src->lock) );");
3097 output.println(" if( isEmpty( src->forwardList ) ||");
3098 output.println(" seseToIssue != peekItem( src->forwardList ) ) {");
3099 output.println(" if( !src->doneExecuting ) {");
3100 output.println(" addNewItem( src->forwardList, seseToIssue );");
3101 output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3102 output.println(" }");
3103 output.println(" }");
3104 output.println(" pthread_mutex_unlock( &(src->lock) );");
3105 output.println(" seseToIssue->"+dynInVar+"_srcOffset = "+dynInVar+"_srcOffset;");
3106 output.println(" } else {");
3108 boolean useParentContext = false;
3109 if( fsen != mlpa.getMainSESE() ) {
3110 assert fsen.getParent() != null;
3111 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3112 useParentContext = true;
3115 if( useParentContext ) {
3116 output.println(" seseToIssue->"+dynInVar+" = "+
3117 generateTemp( fsen.getParent().getfmBogus(), dynInVar, null )+";");
3119 output.println(" seseToIssue->"+dynInVar+" = "+
3120 generateTemp( fsen.getfmEnclosing(), dynInVar, null )+";");
3123 output.println(" }");
3124 output.println(" }");
3126 // even if the value is already copied, make sure your NULL source
3127 // gets passed so child knows it already has the dynamic value
3128 output.println(" seseToIssue->"+dynInVar+"_srcSESE = "+dynInVar+"_srcSESE;");
3131 // maintain pointers for for finding dynamic SESE
3132 // instances from static names
3133 SESEandAgePair p = new SESEandAgePair( fsen, 0 );
3134 if( fsen.getParent() != null &&
3135 //!fsen.getParent().getIsCallerSESEplaceholder() &&
3136 fsen.getParent().getNeededStaticNames().contains( p )
3139 for( int i = fsen.getOldestAgeToTrack(); i > 0; --i ) {
3140 SESEandAgePair p1 = new SESEandAgePair( fsen, i );
3141 SESEandAgePair p2 = new SESEandAgePair( fsen, i-1 );
3142 output.println(" "+p1+" = "+p2+";");
3144 output.println(" "+p+" = seseToIssue;");
3148 // if there were no outstanding dependencies, issue here
3149 output.println(" if( seseToIssue->common.unresolvedDependencies == 0 ) {");
3150 output.println(" workScheduleSubmit( (void*)seseToIssue );");
3151 output.println(" }");
3153 // release this SESE for siblings to update its dependencies or,
3154 // eventually, for it to mark itself finished
3155 output.println(" pthread_mutex_unlock( &(seseToIssue->common.lock) );");
3156 output.println(" }");
3160 public void generateFlatSESEExitNode( FlatMethod fm,
3162 FlatSESEExitNode fsexn,
3166 // if MLP flag is off, okay that SESE nodes are in IR graph,
3167 // just skip over them and code generates exactly the same
3172 // get the enter node for this exit that has meta data embedded
3173 FlatSESEEnterNode fsen = fsexn.getFlatEnter();
3175 // there may be an SESE in an unreachable method, skip over
3176 if( !mlpa.getAllSESEs().contains( fsen ) ) {
3180 // also, if we have encountered a placeholder, just jump it
3181 if( fsen.getIsCallerSESEplaceholder() ) {
3185 output.println(" /* SESE exiting */");
3187 String com = paramsprefix+"->common";
3189 // this SESE cannot be done until all of its children are done
3190 // so grab your own lock with the condition variable for watching
3191 // that the number of your running children is greater than zero
3192 output.println(" pthread_mutex_lock( &("+com+".lock) );");
3193 output.println(" while( "+com+".numRunningChildren > 0 ) {");
3194 output.println(" pthread_cond_wait( &("+com+".runningChildrenCond), &("+com+".lock) );");
3195 output.println(" }");
3197 // copy out-set from local temps into the sese record
3198 Iterator<TempDescriptor> itr = fsen.getOutVarSet().iterator();
3199 while( itr.hasNext() ) {
3200 TempDescriptor temp = itr.next();
3202 // only have to do this for primitives
3203 if( !temp.getType().isPrimitive() ) {
3207 // have to determine the context enclosing this sese
3208 boolean useParentContext = false;
3210 if( fsen != mlpa.getMainSESE() ) {
3211 assert fsen.getParent() != null;
3212 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3213 useParentContext = true;
3218 if( useParentContext ) {
3219 from = generateTemp( fsen.getParent().getfmBogus(), temp, null );
3221 from = generateTemp( fsen.getfmEnclosing(), temp, null );
3224 output.println(" "+paramsprefix+
3225 "->"+temp.getSafeSymbol()+
3229 // mark yourself done, your SESE data is now read-only
3230 output.println(" "+com+".doneExecuting = TRUE;");
3231 output.println(" pthread_cond_signal( &("+com+".doneCond) );");
3232 output.println(" pthread_mutex_unlock( &("+com+".lock) );");
3234 // decrement dependency count for all SESE's on your forwarding list
3235 output.println(" while( !isEmpty( "+com+".forwardList ) ) {");
3236 output.println(" SESEcommon* consumer = (SESEcommon*) getItem( "+com+".forwardList );");
3237 output.println(" pthread_mutex_lock( &(consumer->lock) );");
3238 output.println(" --(consumer->unresolvedDependencies);");
3239 output.println(" if( consumer->unresolvedDependencies == 0 ) {");
3240 output.println(" workScheduleSubmit( (void*)consumer );");
3241 output.println(" }");
3242 output.println(" pthread_mutex_unlock( &(consumer->lock) );");
3243 output.println(" }");
3245 // if parent is stalling on you, let them know you're done
3246 if( fsexn.getFlatEnter() != mlpa.getMainSESE() ) {
3247 output.println(" psem_give( &("+paramsprefix+"->common.stallSem) );");
3250 // last of all, decrement your parent's number of running children
3251 output.println(" if( "+paramsprefix+"->common.parent != NULL ) {");
3252 output.println(" pthread_mutex_lock( &("+paramsprefix+"->common.parent->lock) );");
3253 output.println(" --("+paramsprefix+"->common.parent->numRunningChildren);");
3254 output.println(" pthread_cond_signal( &("+paramsprefix+"->common.parent->runningChildrenCond) );");
3255 output.println(" pthread_mutex_unlock( &("+paramsprefix+"->common.parent->lock) );");
3256 output.println(" }");
3258 // this is a thread-only variable that can be handled when critical sese-to-sese
3259 // data has been taken care of--set sese pointer to remember self over method
3260 // calls to a non-zero, invalid address
3261 output.println(" seseCaller = (SESEcommon*) 0x1;");
3264 public void generateFlatWriteDynamicVarNode( FlatMethod fm,
3266 FlatWriteDynamicVarNode fwdvn,
3270 // should node should not be in an IR graph if the
3271 // MLP flag is not set
3272 throw new Error("Unexpected presence of FlatWriteDynamicVarNode");
3275 Hashtable<TempDescriptor, VariableSourceToken> writeDynamic =
3278 assert writeDynamic != null;
3280 Iterator wdItr = writeDynamic.entrySet().iterator();
3281 while( wdItr.hasNext() ) {
3282 Map.Entry me = (Map.Entry) wdItr.next();
3283 TempDescriptor refVar = (TempDescriptor) me.getKey();
3284 VariableSourceToken vst = (VariableSourceToken) me.getValue();
3286 FlatSESEEnterNode current = fwdvn.getEnclosingSESE();
3288 // only do this if the variable in question should be tracked,
3289 // meaning that it was explicitly added to the dynamic var set
3290 if( !current.getDynamicVarSet().contains( vst.getAddrVar() ) ) {
3294 SESEandAgePair instance = new SESEandAgePair( vst.getSESE(), vst.getAge() );
3296 output.println(" {");
3298 if( current.equals( vst.getSESE() ) ) {
3299 // if the src comes from this SESE, it's a method local variable,
3300 // mark src pointer NULL to signify that the var is up-to-date
3301 output.println(" "+vst.getAddrVar()+"_srcSESE = NULL;");
3304 // otherwise we track where it will come from
3305 output.println(" "+vst.getAddrVar()+"_srcSESE = "+instance+";");
3306 output.println(" "+vst.getAddrVar()+"_srcOffset = (int) &((("+
3307 vst.getSESE().getSESErecordName()+"*)0)->"+vst.getAddrVar()+");");
3310 output.println(" }");
3315 private void generateFlatCheckNode(FlatMethod fm, LocalityBinding lb, FlatCheckNode fcn, PrintWriter output) {
3316 if (state.CONSCHECK) {
3317 String specname=fcn.getSpec();
3318 String varname="repairstate___";
3319 output.println("{");
3320 output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
3322 TempDescriptor[] temps=fcn.getTemps();
3323 String[] vars=fcn.getVars();
3324 for(int i=0; i<temps.length; i++) {
3325 output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i],lb)+";");
3328 output.println("if (doanalysis"+specname+"("+varname+")) {");
3329 output.println("free"+specname+"_state("+varname+");");
3330 output.println("} else {");
3331 output.println("/* Bad invariant */");
3332 output.println("free"+specname+"_state("+varname+");");
3333 output.println("abort_task();");
3334 output.println("}");
3335 output.println("}");
3339 private void generateFlatCall(FlatMethod fm, LocalityBinding lb, FlatCall fc, PrintWriter output) {
3341 if( state.MLP && !nonSESEpass ) {
3342 output.println(" seseCaller = (SESEcommon*)"+paramsprefix+";");
3345 MethodDescriptor md=fc.getMethod();
3346 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? locality.getBinding(lb, fc) : md);
3347 ClassDescriptor cn=md.getClassDesc();
3348 output.println("{");
3349 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3351 LocalityBinding fclb=locality.getBinding(lb, fc);
3352 output.print(" struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
3354 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
3356 output.print(objectparams.numPointers());
3357 output.print(", "+localsprefixaddr);
3358 if (md.getThis()!=null) {
3360 output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis(),lb));
3362 if (fc.getThis()!=null&&md.getThis()==null) {
3363 System.out.println("WARNING!!!!!!!!!!!!");
3364 System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
3368 for(int i=0; i<fc.numArgs(); i++) {
3369 Descriptor var=md.getParameter(i);
3370 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
3371 if (objectparams.isParamPtr(paramtemp)) {
3372 TempDescriptor targ=fc.getArg(i);
3374 TypeDescriptor td=md.getParamType(i);
3376 output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
3378 output.print("(struct "+md.getParamType(i).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
3381 output.println("};");
3386 if (fc.getReturnTemp()!=null)
3387 output.print(generateTemp(fm,fc.getReturnTemp(),lb)+"=");
3389 /* Do we need to do virtual dispatch? */
3390 if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
3393 LocalityBinding fclb=locality.getBinding(lb, fc);
3394 output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
3396 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
3401 if (md.getReturnType().isClass()||md.getReturnType().isArray())
3402 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
3404 output.print(md.getReturnType().getSafeSymbol()+" ");
3405 output.print("(*)(");
3407 boolean printcomma=false;
3408 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3410 LocalityBinding fclb=locality.getBinding(lb, fc);
3411 output.print("struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
3413 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
3417 for(int i=0; i<objectparams.numPrimitives(); i++) {
3418 TempDescriptor temp=objectparams.getPrimitive(i);
3422 if (temp.getType().isClass()||temp.getType().isArray())
3423 output.print("struct " + temp.getType().getSafeSymbol()+" * ");
3425 output.print(temp.getType().getSafeSymbol());
3430 LocalityBinding fclb=locality.getBinding(lb, fc);
3431 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])");
3433 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
3437 boolean needcomma=false;
3438 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3439 output.print("&__parameterlist__");
3443 if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
3444 if (fc.getThis()!=null) {
3445 TypeDescriptor ptd=md.getThis().getType();
3448 if (ptd.isClass()&&!ptd.isArray())
3449 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
3450 output.print(generateTemp(fm,fc.getThis(),lb));
3455 for(int i=0; i<fc.numArgs(); i++) {
3456 Descriptor var=md.getParameter(i);
3457 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
3458 if (objectparams.isParamPrim(paramtemp)) {
3459 TempDescriptor targ=fc.getArg(i);
3463 TypeDescriptor ptd=md.getParamType(i);
3464 if (ptd.isClass()&&!ptd.isArray())
3465 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
3466 output.print(generateTemp(fm, targ,lb));
3470 output.println(");");
3471 output.println(" }");
3474 private boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
3475 Set subclasses=typeutil.getSubClasses(thiscd);
3476 if (subclasses==null)
3478 for(Iterator classit=subclasses.iterator(); classit.hasNext();) {
3479 ClassDescriptor cd=(ClassDescriptor)classit.next();
3480 Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol());
3481 for(Iterator matchit=possiblematches.iterator(); matchit.hasNext();) {
3482 MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
3483 if (md.matches(matchmd))
3490 private void generateFlatFieldNode(FlatMethod fm, LocalityBinding lb, FlatFieldNode ffn, PrintWriter output) {
3491 if (state.SINGLETM) {
3492 //single machine transactional memory case
3493 String field=ffn.getField().getSafeSymbol();
3494 String src=generateTemp(fm, ffn.getSrc(),lb);
3495 String dst=generateTemp(fm, ffn.getDst(),lb);
3497 output.println(dst+"="+ src +"->"+field+ ";");
3498 if (ffn.getField().getType().isPtr()&&locality.getAtomic(lb).get(ffn).intValue()>0&&
3499 locality.getNodePreTempInfo(lb, ffn).get(ffn.getSrc())!=LocalityAnalysis.SCRATCH) {
3500 if ((dc==null)||(!state.READSET&&dc.getNeedTrans(lb, ffn))||
3501 (state.READSET&&dc.getNeedWriteTrans(lb, ffn))) {
3502 output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));");
3503 } else if (state.READSET&&dc.getNeedTrans(lb, ffn)) {
3504 output.println("TRANSREADRD("+dst+", "+dst+");");
3507 } else if (state.DSM) {
3508 Integer status=locality.getNodePreTempInfo(lb,ffn).get(ffn.getSrc());
3509 if (status==LocalityAnalysis.GLOBAL) {
3510 String field=ffn.getField().getSafeSymbol();
3511 String src=generateTemp(fm, ffn.getSrc(),lb);
3512 String dst=generateTemp(fm, ffn.getDst(),lb);
3514 if (ffn.getField().getType().isPtr()) {
3516 //TODO: Uncomment this when we have runtime support
3517 //if (ffn.getSrc()==ffn.getDst()) {
3518 //output.println("{");
3519 //output.println("void * temp="+src+";");
3520 //output.println("if (temp&0x1) {");
3521 //output.println("temp=(void *) transRead(trans, (unsigned int) temp);");
3522 //output.println(src+"->"+field+"="+temp+";");
3523 //output.println("}");
3524 //output.println(dst+"=temp;");
3525 //output.println("}");
3527 output.println(dst+"="+ src +"->"+field+ ";");
3528 //output.println("if ("+dst+"&0x1) {");
3529 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
3530 //output.println(src+"->"+field+"="+src+"->"+field+";");
3531 //output.println("}");
3534 output.println(dst+"="+ src+"->"+field+";");
3536 } else if (status==LocalityAnalysis.LOCAL) {
3537 if (ffn.getField().getType().isPtr()&&
3538 ffn.getField().isGlobal()) {
3539 String field=ffn.getField().getSafeSymbol();
3540 String src=generateTemp(fm, ffn.getSrc(),lb);
3541 String dst=generateTemp(fm, ffn.getDst(),lb);
3542 output.println(dst+"="+ src +"->"+field+ ";");
3543 if (locality.getAtomic(lb).get(ffn).intValue()>0)
3544 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
3546 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
3547 } else if (status==LocalityAnalysis.EITHER) {
3548 //Code is reading from a null pointer
3549 output.println("if ("+generateTemp(fm, ffn.getSrc(),lb)+") {");
3550 output.println("#ifndef RAW");
3551 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
3552 output.println("#endif");
3553 //This should throw a suitable null pointer error
3554 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
3556 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
3558 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
3562 private void generateFlatSetFieldNode(FlatMethod fm, LocalityBinding lb, FlatSetFieldNode fsfn, PrintWriter output) {
3563 if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
3564 throw new Error("Can't set array length");
3565 if (state.SINGLETM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
3566 //Single Machine Transaction Case
3567 boolean srcptr=fsfn.getSrc().getType().isPtr();
3568 String src=generateTemp(fm,fsfn.getSrc(),lb);
3569 String dst=generateTemp(fm,fsfn.getDst(),lb);
3570 output.println("//"+srcptr+" "+fsfn.getSrc().getType().isNull());
3571 if (srcptr&&!fsfn.getSrc().getType().isNull()) {
3572 output.println("{");
3573 if ((dc==null)||dc.getNeedSrcTrans(lb, fsfn)&&
3574 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) {
3575 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3577 output.println("INTPTR srcoid=(INTPTR)"+src+";");
3580 if (wb.needBarrier(fsfn)&&
3581 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getDst())!=LocalityAnalysis.SCRATCH) {
3582 output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;");
3584 if (srcptr&!fsfn.getSrc().getType().isNull()) {
3585 output.println("*((unsigned INTPTR *)&("+dst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
3586 output.println("}");
3588 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3590 } else if (state.DSM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
3591 Integer statussrc=locality.getNodePreTempInfo(lb,fsfn).get(fsfn.getSrc());
3592 Integer statusdst=locality.getNodeTempInfo(lb).get(fsfn).get(fsfn.getDst());
3593 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
3595 String src=generateTemp(fm,fsfn.getSrc(),lb);
3596 String dst=generateTemp(fm,fsfn.getDst(),lb);
3598 output.println("{");
3599 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3601 if (statusdst.equals(LocalityAnalysis.GLOBAL)) {
3604 if (wb.needBarrier(fsfn))
3605 output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;");
3607 output.println("*((unsigned INTPTR *)&("+glbdst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
3609 output.println(glbdst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3610 } else if (statusdst.equals(LocalityAnalysis.LOCAL)) {
3611 /** Check if we need to copy */
3612 output.println("if(!"+dst+"->"+localcopystr+") {");
3613 /* Link object into list */
3614 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3615 output.println(revertptr+"=revertlist;");
3616 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
3617 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3619 output.println("COPY_OBJ("+dst+");");
3620 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
3621 output.println("revertlist=(struct ___Object___ *)"+dst+";");
3622 output.println("}");
3624 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
3626 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3627 } else if (statusdst.equals(LocalityAnalysis.EITHER)) {
3628 //writing to a null...bad
3629 output.println("if ("+dst+") {");
3630 output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}");
3632 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
3634 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3637 output.println("}");
3640 if (state.FASTCHECK) {
3641 String dst=generateTemp(fm, fsfn.getDst(),lb);
3642 output.println("if(!"+dst+"->"+localcopystr+") {");
3643 /* Link object into list */
3644 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
3645 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3647 output.println("COPY_OBJ("+dst+");");
3648 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
3649 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
3650 output.println("}");
3652 output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
3656 private void generateFlatElementNode(FlatMethod fm, LocalityBinding lb, FlatElementNode fen, PrintWriter output) {
3657 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
3660 if (elementtype.isArray()||elementtype.isClass())
3663 type=elementtype.getSafeSymbol()+" ";
3665 if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
3666 output.println("if ("+generateTemp(fm, fen.getIndex(),lb)+"< 0 | "+generateTemp(fm, fen.getIndex(),lb)+" >= "+generateTemp(fm,fen.getSrc(),lb) + "->___length___)");
3667 output.println("failedboundschk();");
3669 if (state.SINGLETM) {
3670 //Single machine transaction case
3671 String dst=generateTemp(fm, fen.getDst(),lb);
3672 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3674 if (elementtype.isPtr()&&locality.getAtomic(lb).get(fen).intValue()>0&&
3675 locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())!=LocalityAnalysis.SCRATCH) {
3676 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fen)||state.READSET&&dc.getNeedWriteTrans(lb, fen)) {
3677 output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));");
3678 } else if (state.READSET&&dc.getNeedTrans(lb, fen)) {
3679 output.println("TRANSREADRD("+dst+", "+dst+");");
3682 } else if (state.DSM) {
3683 Integer status=locality.getNodePreTempInfo(lb,fen).get(fen.getSrc());
3684 if (status==LocalityAnalysis.GLOBAL) {
3685 String dst=generateTemp(fm, fen.getDst(),lb);
3687 if (elementtype.isPtr()) {
3688 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3689 output.println("TRANSREAD("+dst+", "+dst+");");
3691 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3693 } else if (status==LocalityAnalysis.LOCAL) {
3694 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3695 } else if (status==LocalityAnalysis.EITHER) {
3696 //Code is reading from a null pointer
3697 output.println("if ("+generateTemp(fm, fen.getSrc(),lb)+") {");
3698 output.println("#ifndef RAW");
3699 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
3700 output.println("#endif");
3701 //This should throw a suitable null pointer error
3702 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3704 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
3706 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3710 private void generateFlatSetElementNode(FlatMethod fm, LocalityBinding lb, FlatSetElementNode fsen, PrintWriter output) {
3711 //TODO: need dynamic check to make sure this assignment is actually legal
3712 //Because Object[] could actually be something more specific...ie. Integer[]
3714 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
3717 if (elementtype.isArray()||elementtype.isClass())
3720 type=elementtype.getSafeSymbol()+" ";
3722 if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
3723 output.println("if ("+generateTemp(fm, fsen.getIndex(),lb)+"< 0 | "+generateTemp(fm, fsen.getIndex(),lb)+" >= "+generateTemp(fm,fsen.getDst(),lb) + "->___length___)");
3724 output.println("failedboundschk();");
3727 if (state.SINGLETM && locality.getAtomic(lb).get(fsen).intValue()>0) {
3728 //Transaction set element case
3729 if (wb.needBarrier(fsen)&&
3730 locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH) {
3731 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___objstatus___))|=DIRTY;");
3733 if (fsen.getSrc().getType().isPtr()&&!fsen.getSrc().getType().isNull()) {
3734 output.println("{");
3735 String src=generateTemp(fm, fsen.getSrc(), lb);
3736 if ((dc==null)||dc.getNeedSrcTrans(lb, fsen)&&
3737 locality.getNodePreTempInfo(lb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) {
3738 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3740 output.println("INTPTR srcoid=(INTPTR)"+src+";");
3742 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
3743 output.println("}");
3745 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
3747 } else if (state.DSM && locality.getAtomic(lb).get(fsen).intValue()>0) {
3748 Integer statussrc=locality.getNodePreTempInfo(lb,fsen).get(fsen.getSrc());
3749 Integer statusdst=locality.getNodePreTempInfo(lb,fsen).get(fsen.getDst());
3750 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
3751 boolean dstglobal=statusdst==LocalityAnalysis.GLOBAL;
3752 boolean dstlocal=statusdst==LocalityAnalysis.LOCAL;
3755 if (wb.needBarrier(fsen))
3756 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___localcopy___))|=DIRTY;");
3757 } else if (dstlocal) {
3758 /** Check if we need to copy */
3759 String dst=generateTemp(fm, fsen.getDst(),lb);
3760 output.println("if(!"+dst+"->"+localcopystr+") {");
3761 /* Link object into list */
3762 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3763 output.println(revertptr+"=revertlist;");
3764 if ((GENERATEPRECISEGC) || this.state.MULTICOREGC)
3765 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3767 output.println("COPY_OBJ("+dst+");");
3768 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
3769 output.println("revertlist=(struct ___Object___ *)"+dst+";");
3770 output.println("}");
3771 } else throw new Error("Unknown array type");
3773 output.println("{");
3774 String src=generateTemp(fm, fsen.getSrc(), lb);
3775 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3776 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
3777 output.println("}");
3779 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
3782 if (state.FASTCHECK) {
3783 String dst=generateTemp(fm, fsen.getDst(),lb);
3784 output.println("if(!"+dst+"->"+localcopystr+") {");
3785 /* Link object into list */
3786 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
3787 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3789 output.println("COPY_OBJ("+dst+");");
3790 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
3791 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
3792 output.println("}");
3794 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
3798 protected void generateFlatNew(FlatMethod fm, LocalityBinding lb, FlatNew fn, PrintWriter output) {
3799 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
3800 //Stash pointer in case of GC
3801 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3802 output.println(revertptr+"=revertlist;");
3804 if (state.SINGLETM) {
3805 if (fn.getType().isArray()) {
3806 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
3807 if (locality.getAtomic(lb).get(fn).intValue()>0) {
3808 //inside transaction
3809 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3811 //outside transaction
3812 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3815 if (locality.getAtomic(lb).get(fn).intValue()>0) {
3816 //inside transaction
3817 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
3819 //outside transaction
3820 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
3823 } else if (fn.getType().isArray()) {
3824 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
3825 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
3826 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3827 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3828 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3830 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3833 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
3834 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");");
3835 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3836 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
3838 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
3841 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
3842 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3843 String dst=generateTemp(fm,fn.getDst(),lb);
3844 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
3845 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
3846 output.println("revertlist=(struct ___Object___ *)"+dst+";");
3848 if (state.FASTCHECK) {
3849 String dst=generateTemp(fm,fn.getDst(),lb);
3850 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
3851 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
3852 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
3856 private void generateFlatTagDeclaration(FlatMethod fm, LocalityBinding lb, FlatTagDeclaration fn, PrintWriter output) {
3857 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3858 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
3860 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+state.getTagId(fn.getType())+");");
3864 private void generateFlatOpNode(FlatMethod fm, LocalityBinding lb, FlatOpNode fon, PrintWriter output) {
3865 if (fon.getRight()!=null) {
3866 if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
3867 if (fon.getLeft().getType().isLong())
3868 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
3870 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned int)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
3872 } else if (dc!=null) {
3873 output.print(generateTemp(fm, fon.getDest(),lb)+" = ");
3874 if (dc.getNeedLeftSrcTrans(lb, fon))
3875 output.print("("+generateTemp(fm, fon.getLeft(),lb)+"!=NULL?"+generateTemp(fm, fon.getLeft(),lb)+"->"+oidstr+":NULL)");
3877 output.print(generateTemp(fm, fon.getLeft(),lb));
3878 output.print(fon.getOp().toString());
3879 if (dc.getNeedRightSrcTrans(lb, fon))
3880 output.println("("+generateTemp(fm, fon.getRight(),lb)+"!=NULL?"+generateTemp(fm, fon.getRight(),lb)+"->"+oidstr+":NULL);");
3882 output.println(generateTemp(fm,fon.getRight(),lb)+";");
3884 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+fon.getOp().toString()+generateTemp(fm,fon.getRight(),lb)+";");
3885 } else if (fon.getOp().getOp()==Operation.ASSIGN)
3886 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
3887 else if (fon.getOp().getOp()==Operation.UNARYPLUS)
3888 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
3889 else if (fon.getOp().getOp()==Operation.UNARYMINUS)
3890 output.println(generateTemp(fm, fon.getDest(),lb)+" = -"+generateTemp(fm, fon.getLeft(),lb)+";");
3891 else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
3892 output.println(generateTemp(fm, fon.getDest(),lb)+" = !"+generateTemp(fm, fon.getLeft(),lb)+";");
3893 else if (fon.getOp().getOp()==Operation.COMP)
3894 output.println(generateTemp(fm, fon.getDest(),lb)+" = ~"+generateTemp(fm, fon.getLeft(),lb)+";");
3895 else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
3896 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+"->fses==NULL;");
3898 output.println(generateTemp(fm, fon.getDest(),lb)+fon.getOp().toString()+generateTemp(fm, fon.getLeft(),lb)+";");
3901 private void generateFlatCastNode(FlatMethod fm, LocalityBinding lb, FlatCastNode fcn, PrintWriter output) {
3902 /* TODO: Do type check here */
3903 if (fcn.getType().isArray()) {
3904 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
3905 } else if (fcn.getType().isClass())
3906 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
3908 output.println(generateTemp(fm,fcn.getDst(),lb)+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc(),lb)+";");
3911 private void generateFlatLiteralNode(FlatMethod fm, LocalityBinding lb, FlatLiteralNode fln, PrintWriter output) {
3912 if (fln.getValue()==null)
3913 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
3914 else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
3915 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3916 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
3917 //Stash pointer in case of GC
3918 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3919 output.println(revertptr+"=revertlist;");
3921 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
3922 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
3923 //Stash pointer in case of GC
3924 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3925 output.println("revertlist="+revertptr+";");
3928 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
3930 } else if (fln.getType().isBoolean()) {
3931 if (((Boolean)fln.getValue()).booleanValue())
3932 output.println(generateTemp(fm, fln.getDst(),lb)+"=1;");
3934 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
3935 } else if (fln.getType().isChar()) {
3936 String st=FlatLiteralNode.escapeString(fln.getValue().toString());
3937 output.println(generateTemp(fm, fln.getDst(),lb)+"='"+st+"';");
3938 } else if (fln.getType().isLong()) {
3939 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+"LL;");
3941 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+";");
3944 protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) {
3945 if (frn.getReturnTemp()!=null) {
3946 if (frn.getReturnTemp().getType().isPtr())
3947 output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";");
3949 output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";");
3951 output.println("return;");
3955 protected void generateStoreFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
3956 output.println("STOREANDBRANCH(!"+generateTemp(fm, fcb.getTest(),lb)+", "+label+");");
3959 protected void generateFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
3960 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") goto "+label+";");
3963 /** This method generates header information for the method or
3964 * task referenced by the Descriptor des. */
3965 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) {
3966 generateHeader(fm, lb, des, output, false);
3969 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output, boolean addSESErecord) {
3971 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : des);
3972 MethodDescriptor md=null;
3973 TaskDescriptor task=null;
3974 if (des instanceof MethodDescriptor)
3975 md=(MethodDescriptor) des;
3977 task=(TaskDescriptor) des;
3979 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
3981 if (md!=null&&md.getReturnType()!=null) {
3982 if (md.getReturnType().isClass()||md.getReturnType().isArray())
3983 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
3985 output.print(md.getReturnType().getSafeSymbol()+" ");
3987 //catch the constructor case
3988 output.print("void ");
3990 if (state.DSM||state.SINGLETM) {
3991 output.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
3993 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
3995 output.print(task.getSafeSymbol()+"(");
3997 boolean printcomma=false;
3998 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4000 if (state.DSM||state.SINGLETM) {
4001 output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
4003 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
4005 output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
4011 for(int i=0; i<objectparams.numPrimitives(); i++) {
4012 TempDescriptor temp=objectparams.getPrimitive(i);
4016 if (temp.getType().isClass()||temp.getType().isArray())
4017 output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
4019 output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
4021 output.println(") {");
4022 } else if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
4023 /* Imprecise Task */
4024 output.println("void * parameterarray[]) {");
4025 /* Unpack variables */
4026 for(int i=0; i<objectparams.numPrimitives(); i++) {
4027 TempDescriptor temp=objectparams.getPrimitive(i);
4028 output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
4030 for(int i=0; i<fm.numTags(); i++) {
4031 TempDescriptor temp=fm.getTag(i);
4032 int offset=i+objectparams.numPrimitives();
4033 output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
4036 if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
4037 maxtaskparams=objectparams.numPrimitives()+fm.numTags();
4038 } else output.println(") {");
4041 public void generateFlatFlagActionNode(FlatMethod fm, LocalityBinding lb, FlatFlagActionNode ffan, PrintWriter output) {
4042 output.println("/* FlatFlagActionNode */");
4045 /* Process tag changes */
4046 Relation tagsettable=new Relation();
4047 Relation tagcleartable=new Relation();
4049 Iterator tagsit=ffan.getTempTagPairs();
4050 while (tagsit.hasNext()) {
4051 TempTagPair ttp=(TempTagPair) tagsit.next();
4052 TempDescriptor objtmp=ttp.getTemp();
4053 TagDescriptor tag=ttp.getTag();
4054 TempDescriptor tagtmp=ttp.getTagTemp();
4055 boolean tagstatus=ffan.getTagChange(ttp);
4057 tagsettable.put(objtmp, tagtmp);
4059 tagcleartable.put(objtmp, tagtmp);
4064 Hashtable flagandtable=new Hashtable();
4065 Hashtable flagortable=new Hashtable();
4067 /* Process flag changes */
4068 Iterator flagsit=ffan.getTempFlagPairs();
4069 while(flagsit.hasNext()) {
4070 TempFlagPair tfp=(TempFlagPair)flagsit.next();
4071 TempDescriptor temp=tfp.getTemp();
4072 Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
4073 FlagDescriptor flag=tfp.getFlag();
4075 //Newly allocate objects that don't set any flags case
4076 if (flagortable.containsKey(temp)) {
4080 flagortable.put(temp,new Integer(mask));
4082 int flagid=1<<((Integer)flagtable.get(flag)).intValue();
4083 boolean flagstatus=ffan.getFlagChange(tfp);
4086 if (flagortable.containsKey(temp)) {
4087 mask=((Integer)flagortable.get(temp)).intValue();
4090 flagortable.put(temp,new Integer(mask));
4092 int mask=0xFFFFFFFF;
4093 if (flagandtable.containsKey(temp)) {
4094 mask=((Integer)flagandtable.get(temp)).intValue();
4096 mask&=(0xFFFFFFFF^flagid);
4097 flagandtable.put(temp,new Integer(mask));
4103 HashSet flagtagset=new HashSet();
4104 flagtagset.addAll(flagortable.keySet());
4105 flagtagset.addAll(flagandtable.keySet());
4106 flagtagset.addAll(tagsettable.keySet());
4107 flagtagset.addAll(tagcleartable.keySet());
4109 Iterator ftit=flagtagset.iterator();
4110 while(ftit.hasNext()) {
4111 TempDescriptor temp=(TempDescriptor)ftit.next();
4114 Set tagtmps=tagcleartable.get(temp);
4115 if (tagtmps!=null) {
4116 Iterator tagit=tagtmps.iterator();
4117 while(tagit.hasNext()) {
4118 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
4119 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
4120 output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4122 output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4126 tagtmps=tagsettable.get(temp);
4127 if (tagtmps!=null) {
4128 Iterator tagit=tagtmps.iterator();
4129 while(tagit.hasNext()) {
4130 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
4131 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
4132 output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4134 output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp, lb)+", "+generateTemp(fm,tagtmp, lb)+");");
4139 int andmask=0xFFFFFFF;
4141 if (flagortable.containsKey(temp))
4142 ormask=((Integer)flagortable.get(temp)).intValue();
4143 if (flagandtable.containsKey(temp))
4144 andmask=((Integer)flagandtable.get(temp)).intValue();
4145 generateFlagOrAnd(ffan, fm, lb, temp, output, ormask, andmask);
4146 generateObjectDistribute(ffan, fm, lb, temp, output);
4150 protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp,
4151 PrintWriter output, int ormask, int andmask) {
4152 if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
4153 output.println("flagorandinit("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
4155 output.println("flagorand("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
4159 protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, PrintWriter output) {
4160 output.println("enqueueObject("+generateTemp(fm, temp, lb)+");");
4163 void generateOptionalHeader(PrintWriter headers) {
4166 headers.println("#include \"task.h\"\n\n");
4167 headers.println("#ifndef _OPTIONAL_STRUCT_");
4168 headers.println("#define _OPTIONAL_STRUCT_");
4170 //STRUCT PREDICATEMEMBER
4171 headers.println("struct predicatemember{");
4172 headers.println("int type;");
4173 headers.println("int numdnfterms;");
4174 headers.println("int * flags;");
4175 headers.println("int numtags;");
4176 headers.println("int * tags;\n};\n\n");
4178 //STRUCT OPTIONALTASKDESCRIPTOR
4179 headers.println("struct optionaltaskdescriptor{");
4180 headers.println("struct taskdescriptor * task;");
4181 headers.println("int index;");
4182 headers.println("int numenterflags;");
4183 headers.println("int * enterflags;");
4184 headers.println("int numpredicatemembers;");
4185 headers.println("struct predicatemember ** predicatememberarray;");
4186 headers.println("};\n\n");
4188 //STRUCT TASKFAILURE
4189 headers.println("struct taskfailure {");
4190 headers.println("struct taskdescriptor * task;");
4191 headers.println("int index;");
4192 headers.println("int numoptionaltaskdescriptors;");
4193 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
4195 //STRUCT FSANALYSISWRAPPER
4196 headers.println("struct fsanalysiswrapper{");
4197 headers.println("int flags;");
4198 headers.println("int numtags;");
4199 headers.println("int * tags;");
4200 headers.println("int numtaskfailures;");
4201 headers.println("struct taskfailure ** taskfailurearray;");
4202 headers.println("int numoptionaltaskdescriptors;");
4203 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
4205 //STRUCT CLASSANALYSISWRAPPER
4206 headers.println("struct classanalysiswrapper{");
4207 headers.println("int type;");
4208 headers.println("int numotd;");
4209 headers.println("struct optionaltaskdescriptor ** otdarray;");
4210 headers.println("int numfsanalysiswrappers;");
4211 headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
4213 headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
4215 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
4216 while(taskit.hasNext()) {
4217 TaskDescriptor td=(TaskDescriptor)taskit.next();
4218 headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
4223 //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
4224 int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
4225 int predicateindex = 0;
4226 //iterate through the classes concerned by the predicate
4227 Set c_vard = predicate.vardescriptors;
4228 Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
4231 for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext();) {
4232 VarDescriptor vard = (VarDescriptor)vard_it.next();
4233 TypeDescriptor typed = vard.getType();
4235 //generate for flags
4236 HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
4237 output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4239 if (fen_hashset!=null) {
4240 for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext();) {
4241 FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
4243 DNFFlag dflag=fen.getDNF();
4244 numberterms+=dflag.size();
4246 Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
4248 for(int j=0; j<dflag.size(); j++) {
4250 output.println(",");
4251 Vector term=dflag.get(j);
4254 for(int k=0; k<term.size(); k++) {
4255 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
4256 FlagDescriptor fd=dfa.getFlag();
4257 boolean negated=dfa.getNegated();
4258 int flagid=1<<((Integer)flags.get(fd)).intValue();
4263 output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
4268 output.println("};\n");
4271 TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
4272 output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4275 for(int j=0; j<tagel.numTags(); j++) {
4277 output.println(",");
4278 TempDescriptor tmp=tagel.getTemp(j);
4279 if (!slotnumber.containsKey(tmp)) {
4280 Integer slotint=new Integer(current_slot++);
4281 slotnumber.put(tmp,slotint);
4283 int slot=slotnumber.get(tmp).intValue();
4284 output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
4286 numtags = tagel.numTags();
4288 output.println("};");
4290 //store the result into a predicatemember struct
4291 output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
4292 output.println("/*type*/"+typed.getClassDesc().getId()+",");
4293 output.println("/* number of dnf terms */"+numberterms+",");
4294 output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4295 output.println("/* number of tag */"+numtags+",");
4296 output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4297 output.println("};\n");
4302 //generate an array that stores the entire predicate
4303 output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4304 for( int j = 0; j<predicateindex; j++) {
4305 if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4306 else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4308 output.println("};\n");
4309 return predicateindex;
4313 void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
4314 generateOptionalHeader(headers);
4316 output.println("#include \"optionalstruct.h\"\n\n");
4317 output.println("#include \"stdlib.h\"\n");
4319 HashSet processedcd = new HashSet();
4321 Enumeration e = safeexecution.keys();
4322 while (e.hasMoreElements()) {
4325 ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
4326 Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp); //will be used several times
4328 //Generate the struct of optionals
4329 Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
4330 numotd = c_otd.size();
4331 if(maxotd<numotd) maxotd = numotd;
4332 if( !c_otd.isEmpty() ) {
4333 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
4334 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
4336 //generate the int arrays for the predicate
4337 Predicate predicate = otd.predicate;
4338 int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
4339 TreeSet<Integer> fsset=new TreeSet<Integer>();
4340 //iterate through possible FSes corresponding to
4341 //the state when entering
4343 for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext();) {
4344 FlagState fs = (FlagState)fses.next();
4346 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
4347 FlagDescriptor flagd = (FlagDescriptor)flags.next();
4348 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
4351 fsset.add(new Integer(flagid));
4352 //tag information not needed because tag
4353 //changes are not tolerated.
4356 output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4357 boolean needcomma=false;
4358 for(Iterator<Integer> it=fsset.iterator(); it.hasNext();) {
4361 output.println(it.next());
4364 output.println("};\n");
4367 //generate optionaltaskdescriptor that actually
4368 //includes exit fses, predicate and the task
4370 output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
4371 output.println("&task_"+otd.td.getSafeSymbol()+",");
4372 output.println("/*index*/"+otd.getIndex()+",");
4373 output.println("/*number of enter flags*/"+fsset.size()+",");
4374 output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4375 output.println("/*number of members */"+predicateindex+",");
4376 output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4377 output.println("};\n");
4381 // if there are no optionals, there is no need to build the rest of the struct
4383 output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
4384 c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
4385 if( !c_otd.isEmpty() ) {
4386 boolean needcomma=false;
4387 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
4388 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
4390 output.println(",");
4392 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4395 output.println("};\n");
4397 //get all the possible flagstates reachable by an object
4398 Hashtable hashtbtemp = safeexecution.get(cdtemp);
4400 TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
4401 fsts.addAll(hashtbtemp.keySet());
4402 for(Iterator fsit=fsts.iterator(); fsit.hasNext();) {
4403 FlagState fs = (FlagState)fsit.next();
4406 //get the set of OptionalTaskDescriptors corresponding
4407 HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
4408 //iterate through the OptionalTaskDescriptors and
4409 //store the pointers to the optionals struct (see on
4410 //top) into an array
4412 output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
4413 for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext();) {
4414 OptionalTaskDescriptor mm = mos.next();
4416 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
4418 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4421 output.println("};\n");
4423 //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
4426 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
4427 FlagDescriptor flagd = (FlagDescriptor)flags.next();
4428 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
4432 //process tag information
4435 boolean first = true;
4436 Enumeration tag_enum = fs.getTags();
4437 output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
4438 while(tag_enum.hasMoreElements()) {
4440 TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
4444 output.println(", ");
4445 output.println("/*tagid*/"+state.getTagId(tagd));
4447 output.println("};");
4449 Set<TaskIndex> tiset=sa.getTaskIndex(fs);
4450 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
4451 TaskIndex ti=itti.next();
4455 Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
4457 output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
4458 boolean needcomma=false;
4459 for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext();) {
4460 OptionalTaskDescriptor otd=otdit.next();
4464 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4466 output.println("};");
4468 output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
4469 output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
4470 output.print(ti.getIndex()+", ");
4471 output.print(otdset.size()+", ");
4472 output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
4473 output.println("};");
4476 tiset=sa.getTaskIndex(fs);
4477 boolean needcomma=false;
4479 output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
4480 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
4481 TaskIndex ti=itti.next();
4482 if (ti.isRuntime()) {
4489 output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
4491 output.println("};\n");
4493 //Store the result in fsanalysiswrapper
4495 output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
4496 output.println("/*flag*/"+flagid+",");
4497 output.println("/* number of tags*/"+tagcounter+",");
4498 output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
4499 output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
4500 output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
4501 output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
4502 output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
4503 output.println("};\n");
4507 //Build the array of fsanalysiswrappers
4508 output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
4509 boolean needcomma=false;
4510 for(int i = 0; i<fscounter; i++) {
4511 if (needcomma) output.print(",");
4512 output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
4515 output.println("};");
4517 //Build the classanalysiswrapper referring to the previous array
4518 output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
4519 output.println("/*type*/"+cdtemp.getId()+",");
4520 output.println("/*numotd*/"+numotd+",");
4521 output.println("otdarray"+cdtemp.getSafeSymbol()+",");
4522 output.println("/* number of fsanalysiswrappers */"+fscounter+",");
4523 output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
4524 processedcd.add(cdtemp);
4527 //build an array containing every classes for which code has been build
4528 output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
4529 for(int i=0; i<state.numClasses(); i++) {
4530 ClassDescriptor cn=cdarray[i];
4533 if ((cn != null) && (processedcd.contains(cn)))
4534 output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
4536 output.print("NULL");
4538 output.println("};");
4540 output.println("#define MAXOTD "+maxotd);
4541 headers.println("#endif");
4544 public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
4545 Relation r=new Relation();
4546 for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext();) {
4547 OptionalTaskDescriptor otd=otdit.next();
4548 TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
4552 LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
4553 for(Iterator it=r.keySet().iterator(); it.hasNext();) {
4554 Set s=r.get(it.next());
4555 for(Iterator it2=s.iterator(); it2.hasNext();) {
4556 OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
4564 protected void outputTransCode(PrintWriter output) {