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.DCWrapper;
23 import Analysis.Locality.DelayComputation;
24 import Analysis.Locality.BranchAnalysis;
25 import Analysis.CallGraph.CallGraph;
26 import Analysis.Prefetch.*;
27 import Analysis.Loops.WriteBarrier;
28 import Analysis.Loops.GlobalFieldType;
29 import Analysis.Locality.TypeAnalysis;
30 import Analysis.MLP.MLPAnalysis;
31 import Analysis.MLP.VariableSourceToken;
32 import Analysis.MLP.CodePlan;
33 import Analysis.MLP.SESEandAgePair;
35 public class BuildCode {
38 Hashtable paramstable;
43 String localsprefix="___locals___";
44 String localsprefixaddr="&"+localsprefix;
45 String localsprefixderef=localsprefix+".";
46 String fcrevert="___fcrevert___";
47 String paramsprefix="___params___";
48 String oidstr="___nextobject___";
49 String nextobjstr="___nextobject___";
50 String localcopystr="___localcopy___";
51 public static boolean GENERATEPRECISEGC=false;
52 public static String PREFIX="";
53 public static String arraytype="ArrayObject";
54 public static int flagcount = 0;
57 protected int maxtaskparams=0;
58 private int maxcount=0;
59 ClassDescriptor[] cdarray;
60 TypeDescriptor[] arraytable;
61 LocalityAnalysis locality;
62 Hashtable<LocalityBinding, TempDescriptor> reverttable;
63 Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>> backuptable;
67 String mlperrstr = "if(status != 0) { "+
68 "sprintf(errmsg, \"MLP error at %s:%d\", __FILE__, __LINE__); "+
69 "perror(errmsg); exit(-1); }";
70 boolean nonSESEpass=true;
73 DiscoverConflicts recorddc;
78 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa) {
79 this(st, temptovar, typeutil, null, sa, pa, null);
82 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa) {
83 this(st, temptovar, typeutil, null, sa, pa, mlpa);
86 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, PrefetchAnalysis pa, MLPAnalysis mlpa) {
87 this(st, temptovar, typeutil, locality, null, pa, mlpa);
90 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa) {
95 callgraph=new CallGraph(state);
97 oidstr="___objlocation___";
98 this.temptovar=temptovar;
99 paramstable=new Hashtable();
100 tempstable=new Hashtable();
101 fieldorder=new Hashtable();
102 flagorder=new Hashtable();
103 this.typeutil=typeutil;
104 virtualcalls=new Virtual(state,locality);
105 if (locality!=null) {
106 this.locality=locality;
107 this.reverttable=new Hashtable<LocalityBinding, TempDescriptor>();
108 this.backuptable=new Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>>();
109 this.wb=new WriteBarrier(locality, st);
111 if (state.SINGLETM&&state.DCOPTS) {
112 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
113 GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
114 this.dc=new DiscoverConflicts(locality, st, typeanalysis, gft);
117 if (state.DELAYCOMP) {
118 //TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
119 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
120 GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
121 delaycomp=new DCWrapper(locality, st, typeanalysis, gft);
122 dc=delaycomp.getConflicts();
123 recorddc=new DiscoverConflicts(locality, st, typeanalysis, delaycomp.getCannotDelayMap(), true, true, null);
124 recorddc.doAnalysis();
128 /** The buildCode method outputs C code for all the methods. The Flat
129 * versions of the methods must already be generated and stored in
130 * the State object. */
131 PrintWriter outsandbox=null;
133 public void buildCode() {
134 /* Create output streams to write to */
135 PrintWriter outclassdefs=null;
136 PrintWriter outstructs=null;
137 PrintWriter outrepairstructs=null;
138 PrintWriter outmethodheader=null;
139 PrintWriter outmethod=null;
140 PrintWriter outvirtual=null;
141 PrintWriter outtask=null;
142 PrintWriter outtaskdefs=null;
143 PrintWriter outoptionalarrays=null;
144 PrintWriter optionalheaders=null;
148 outsandbox=new PrintWriter(new FileOutputStream(PREFIX+"sandboxdefs.c"), true);
150 outstructs=new PrintWriter(new FileOutputStream(PREFIX+"structdefs.h"), true);
151 outmethodheader=new PrintWriter(new FileOutputStream(PREFIX+"methodheaders.h"), true);
152 outclassdefs=new PrintWriter(new FileOutputStream(PREFIX+"classdefs.h"), true);
153 outmethod=new PrintWriter(new FileOutputStream(PREFIX+"methods.c"), true);
154 outvirtual=new PrintWriter(new FileOutputStream(PREFIX+"virtualtable.h"), true);
156 outtask=new PrintWriter(new FileOutputStream(PREFIX+"task.h"), true);
157 outtaskdefs=new PrintWriter(new FileOutputStream(PREFIX+"taskdefs.c"), true);
158 if (state.OPTIONAL) {
159 outoptionalarrays=new PrintWriter(new FileOutputStream(PREFIX+"optionalarrays.c"), true);
160 optionalheaders=new PrintWriter(new FileOutputStream(PREFIX+"optionalstruct.h"), true);
163 if (state.structfile!=null) {
164 outrepairstructs=new PrintWriter(new FileOutputStream(PREFIX+state.structfile+".struct"), true);
166 } catch (Exception e) {
171 /* Build the virtual dispatch tables */
172 buildVirtualTables(outvirtual);
174 /* Output includes */
175 outmethodheader.println("#ifndef METHODHEADERS_H");
176 outmethodheader.println("#define METHODHEADERS_H");
177 outmethodheader.println("#include \"structdefs.h\"");
179 outmethodheader.println("#include \"dstm.h\"");
181 outmethodheader.println("#include \"sandbox.h\"");
183 if (state.SINGLETM) {
184 outmethodheader.println("#include \"tm.h\"");
185 outmethodheader.println("#include \"delaycomp.h\"");
186 outmethodheader.println("#include \"inlinestm.h\"");
188 if (state.ABORTREADERS) {
189 outmethodheader.println("#include \"abortreaders.h\"");
190 outmethodheader.println("#include <setjmp.h>");
193 outmethodheader.println("#include <stdlib.h>");
194 outmethodheader.println("#include <stdio.h>");
195 outmethodheader.println("#include <string.h>");
196 outmethodheader.println("#include \"mlp_runtime.h\"");
197 outmethodheader.println("#include \"psemaphore.h\"");
200 /* Output Structures */
201 outputStructs(outstructs);
203 // Output the C class declarations
204 // These could mutually reference each other
205 outputClassDeclarations(outclassdefs);
207 // Output function prototypes and structures for parameters
208 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
209 while(it.hasNext()) {
210 ClassDescriptor cn=(ClassDescriptor)it.next();
211 generateCallStructs(cn, outclassdefs, outstructs, outmethodheader);
213 outclassdefs.close();
216 /* Map flags to integers */
217 /* The runtime keeps track of flags using these integers */
218 it=state.getClassSymbolTable().getDescriptorsIterator();
219 while(it.hasNext()) {
220 ClassDescriptor cn=(ClassDescriptor)it.next();
224 generateTaskStructs(outstructs, outmethodheader);
226 /* Outputs generic task structures if this is a task
228 outputTaskTypes(outtask);
232 // have to initialize some SESE compiler data before
233 // analyzing normal methods, which must happen before
234 // generating SESE internal code
235 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
236 FlatSESEEnterNode fsen = seseit.next();
237 initializeSESE( fsen );
241 /* Build the actual methods */
242 outputMethods(outmethod);
244 // Output function prototypes and structures for SESE's and code
247 // used to differentiate, during code generation, whether we are
248 // passing over SESE body code, or non-SESE code
251 // first generate code for each sese's internals
252 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
253 FlatSESEEnterNode fsen = seseit.next();
254 generateMethodSESE(fsen, null, outstructs, outmethodheader, outmethod);
257 // then write the invokeSESE switch to decouple scheduler
258 // from having to do unique details of sese invocation
259 generateSESEinvocationMethod(outmethodheader, outmethod);
263 /* Output code for tasks */
264 outputTaskCode(outtaskdefs, outmethod);
266 /* Record maximum number of task parameters */
267 outstructs.println("#define MAXTASKPARAMS "+maxtaskparams);
268 } else if (state.main!=null) {
269 /* Generate main method */
270 outputMainMethod(outmethod);
273 /* Generate information for task with optional parameters */
274 if (state.TASK&&state.OPTIONAL) {
275 generateOptionalArrays(outoptionalarrays, optionalheaders, state.getAnalysisResult(), state.getOptionalTaskDescriptors());
276 outoptionalarrays.close();
279 /* Output structure definitions for repair tool */
280 if (state.structfile!=null) {
281 buildRepairStructs(outrepairstructs);
282 outrepairstructs.close();
286 outmethodheader.println("#endif");
287 outmethodheader.close();
289 outstructs.println("#endif");
294 /* This code just generates the main C method for java programs.
295 * The main C method packs up the arguments into a string array
296 * and passes it to the java main method. */
298 private void outputMainMethod(PrintWriter outmethod) {
299 outmethod.println("int main(int argc, const char *argv[]) {");
300 outmethod.println(" int i;");
303 //outmethod.println(" pthread_once( &mlpOnceObj, mlpInitOncePerThread );");
304 outmethod.println(" workScheduleInit( "+state.MLP_NUMCORES+", invokeSESEmethod );");
308 outmethod.println("#ifdef TRANSSTATS \n");
309 outmethod.println("handle();\n");
310 outmethod.println("#endif\n");
312 if (state.THREAD||state.DSM||state.SINGLETM) {
313 outmethod.println("initializethreads();");
316 outmethod.println("if (dstmStartup(argv[1])) {");
317 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
318 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-2);");
320 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-2);");
323 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
324 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1);");
326 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1);");
330 outmethod.println(" for(i=2;i<argc;i++) {");
332 outmethod.println(" for(i=1;i<argc;i++) {");
333 outmethod.println(" int length=strlen(argv[i]);");
334 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
335 outmethod.println(" struct ___String___ *newstring=NewString(NULL, argv[i], length);");
337 outmethod.println(" struct ___String___ *newstring=NewString(argv[i], length);");
340 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-2]=newstring;");
342 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-1]=newstring;");
343 outmethod.println(" }");
345 MethodDescriptor md=typeutil.getMain();
346 ClassDescriptor cd=typeutil.getMainClass();
348 outmethod.println(" {");
349 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
350 if (state.DSM||state.SINGLETM) {
351 outmethod.print(" struct "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
353 outmethod.print(" struct "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
354 outmethod.println("1, NULL,"+"stringarray};");
355 if (state.DSM||state.SINGLETM)
356 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
358 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
360 if (state.DSM||state.SINGLETM)
361 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
363 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
365 outmethod.println(" }");
368 outmethod.println("}");
371 if (state.THREAD||state.DSM||state.SINGLETM) {
372 outmethod.println("pthread_mutex_lock(&gclistlock);");
373 outmethod.println("threadcount--;");
374 outmethod.println("pthread_cond_signal(&gccond);");
375 outmethod.println("pthread_mutex_unlock(&gclistlock);");
378 if (state.DSM||state.SINGLETM) {
379 outmethod.println("#ifdef TRANSSTATS \n");
380 outmethod.println("printf(\"****** Transaction Stats ******\\n\");");
381 outmethod.println("printf(\"numTransCommit= %d\\n\", numTransCommit);");
382 outmethod.println("printf(\"numTransAbort= %d\\n\", numTransAbort);");
383 outmethod.println("printf(\"nSoftAbort= %d\\n\", nSoftAbort);");
385 outmethod.println("printf(\"nchashSearch= %d\\n\", nchashSearch);");
386 outmethod.println("printf(\"nmhashSearch= %d\\n\", nmhashSearch);");
387 outmethod.println("printf(\"nprehashSearch= %d\\n\", nprehashSearch);");
388 outmethod.println("printf(\"ndirtyCacheObj= %d\\n\", ndirtyCacheObj);");
389 outmethod.println("printf(\"nRemoteReadSend= %d\\n\", nRemoteSend);");
390 outmethod.println("printf(\"bytesSent= %d\\n\", bytesSent);");
391 outmethod.println("printf(\"bytesRecv= %d\\n\", bytesRecv);");
392 outmethod.println("printf(\"totalObjSize= %d\\n\", totalObjSize);");
393 outmethod.println("printf(\"sendRemoteReq= %d\\n\", sendRemoteReq);");
394 outmethod.println("printf(\"getResponse= %d\\n\", getResponse);");
395 } else if (state.SINGLETM) {
396 outmethod.println("printf(\"nSoftAbortAbort= %d\\n\", nSoftAbortAbort);");
397 outmethod.println("printf(\"nSoftAbortCommit= %d\\n\", nSoftAbortCommit);");
398 outmethod.println("#ifdef STMSTATS\n");
399 outmethod.println("for(i=0; i<TOTALNUMCLASSANDARRAY; i++) {\n");
400 outmethod.println(" printf(\"typesCausingAbort[%2d] numaccess= %5d numabort= %3d\\n\", i, typesCausingAbort[i].numaccess, typesCausingAbort[i].numabort);\n");
401 outmethod.println("}\n");
402 outmethod.println("#endif\n");
403 outmethod.println("fflush(stdout);");
405 outmethod.println("#endif\n");
408 if (state.THREAD||state.SINGLETM)
409 outmethod.println("pthread_exit(NULL);");
412 outmethod.println(" workScheduleBegin();");
415 outmethod.println("}");
418 /* This method outputs code for each task. */
420 private void outputTaskCode(PrintWriter outtaskdefs, PrintWriter outmethod) {
421 /* Compile task based program */
422 outtaskdefs.println("#include \"task.h\"");
423 outtaskdefs.println("#include \"methodheaders.h\"");
424 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
425 while(taskit.hasNext()) {
426 TaskDescriptor td=(TaskDescriptor)taskit.next();
427 FlatMethod fm=state.getMethodFlat(td);
428 generateFlatMethod(fm, null, outmethod);
429 generateTaskDescriptor(outtaskdefs, fm, td);
432 //Output task descriptors
433 taskit=state.getTaskSymbolTable().getDescriptorsIterator();
434 outtaskdefs.println("struct taskdescriptor * taskarray[]= {");
436 while(taskit.hasNext()) {
437 TaskDescriptor td=(TaskDescriptor)taskit.next();
441 outtaskdefs.println(",");
442 outtaskdefs.print("&task_"+td.getSafeSymbol());
444 outtaskdefs.println("};");
446 outtaskdefs.println("int numtasks="+state.getTaskSymbolTable().getValueSet().size()+";");
449 /* This method outputs most of the methods.c file. This includes
450 * some standard includes and then an array with the sizes of
451 * objets and array that stores supertype and then the code for
452 * the Java methods.. */
454 protected void outputMethods(PrintWriter outmethod) {
455 outmethod.println("#include \"methodheaders.h\"");
456 outmethod.println("#include \"virtualtable.h\"");
457 outmethod.println("#include \"runtime.h\"");
459 outmethod.println("#include \"sandboxdefs.c\"");
462 outmethod.println("#include \"addPrefetchEnhance.h\"");
463 outmethod.println("#include \"localobjects.h\"");
465 if (state.FASTCHECK) {
466 outmethod.println("#include \"localobjects.h\"");
468 if(state.MULTICORE) {
469 outmethod.println("#include \"task.h\"");
470 outmethod.println("#include \"multicoreruntime.h\"");
471 outmethod.println("#include \"runtime_arch.h\"");
473 if (state.THREAD||state.DSM||state.SINGLETM)
474 outmethod.println("#include <thread.h>");
475 if (state.main!=null) {
476 outmethod.println("#include <string.h>");
478 if (state.CONSCHECK) {
479 outmethod.println("#include \"checkers.h\"");
482 outmethod.println("#include <stdlib.h>");
483 outmethod.println("#include <stdio.h>");
484 outmethod.println("#include \"mlp_runtime.h\"");
485 outmethod.println("#include \"psemaphore.h\"");
489 //Store the sizes of classes & array elements
490 generateSizeArray(outmethod);
492 //Store table of supertypes
493 generateSuperTypeTable(outmethod);
495 //Store the layout of classes
496 generateLayoutStructs(outmethod);
498 /* Generate code for methods */
499 if (state.DSM||state.SINGLETM) {
500 for(Iterator<LocalityBinding> lbit=locality.getLocalityBindings().iterator(); lbit.hasNext();) {
501 LocalityBinding lb=lbit.next();
502 MethodDescriptor md=lb.getMethod();
503 FlatMethod fm=state.getMethodFlat(md);
505 if (!md.getModifiers().isNative()) {
506 generateFlatMethod(fm, lb, outmethod);
507 //System.out.println("fm= " + fm + " md= " + md);
511 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
512 while(classit.hasNext()) {
513 ClassDescriptor cn=(ClassDescriptor)classit.next();
514 Iterator methodit=cn.getMethods();
515 while(methodit.hasNext()) {
516 /* Classify parameters */
517 MethodDescriptor md=(MethodDescriptor)methodit.next();
518 FlatMethod fm=state.getMethodFlat(md);
519 if (!md.getModifiers().isNative()) {
520 generateFlatMethod(fm, null, outmethod);
527 protected void outputStructs(PrintWriter outstructs) {
528 outstructs.println("#ifndef STRUCTDEFS_H");
529 outstructs.println("#define STRUCTDEFS_H");
530 outstructs.println("#include \"classdefs.h\"");
531 outstructs.println("#ifndef INTPTR");
532 outstructs.println("#ifdef BIT64");
533 outstructs.println("#define INTPTR long");
534 outstructs.println("#else");
535 outstructs.println("#define INTPTR int");
536 outstructs.println("#endif");
537 outstructs.println("#endif");
539 outstructs.println("#include \"mlp_runtime.h\"");
540 outstructs.println("#include \"psemaphore.h\"");
543 /* Output #defines that the runtime uses to determine type
544 * numbers for various objects it needs */
545 outstructs.println("#define MAXCOUNT "+maxcount);
546 if (state.DSM||state.SINGLETM) {
547 LocalityBinding lbrun=new LocalityBinding(typeutil.getRun(), false);
549 lbrun.setGlobalThis(LocalityAnalysis.GLOBAL);
551 else if (state.SINGLETM) {
552 lbrun.setGlobalThis(LocalityAnalysis.NORMAL);
554 outstructs.println("#define RUNMETHOD "+virtualcalls.getLocalityNumber(lbrun));
558 LocalityBinding lbexecute = new LocalityBinding(typeutil.getExecute(), false);
560 lbexecute.setGlobalThis(LocalityAnalysis.GLOBAL);
561 else if( state.SINGLETM)
562 lbexecute.setGlobalThis(LocalityAnalysis.NORMAL);
563 outstructs.println("#define EXECUTEMETHOD " + virtualcalls.getLocalityNumber(lbexecute));
566 outstructs.println("#define STRINGARRAYTYPE "+
567 (state.getArrayNumber(
568 (new TypeDescriptor(typeutil.getClass(TypeUtil.StringClass))).makeArray(state))+state.numClasses()));
570 outstructs.println("#define OBJECTARRAYTYPE "+
571 (state.getArrayNumber(
572 (new TypeDescriptor(typeutil.getClass(TypeUtil.ObjectClass))).makeArray(state))+state.numClasses()));
575 outstructs.println("#define STRINGTYPE "+typeutil.getClass(TypeUtil.StringClass).getId());
576 outstructs.println("#define CHARARRAYTYPE "+
577 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.CHAR)).makeArray(state))+state.numClasses()));
579 outstructs.println("#define BYTEARRAYTYPE "+
580 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state))+state.numClasses()));
582 outstructs.println("#define BYTEARRAYARRAYTYPE "+
583 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state).makeArray(state))+state.numClasses()));
585 outstructs.println("#define NUMCLASSES "+state.numClasses());
586 int totalClassSize = state.numClasses() + state.numArrays();
587 outstructs.println("#define TOTALNUMCLASSANDARRAY "+ totalClassSize);
589 outstructs.println("#define STARTUPTYPE "+typeutil.getClass(TypeUtil.StartupClass).getId());
590 outstructs.println("#define TAGTYPE "+typeutil.getClass(TypeUtil.TagClass).getId());
591 outstructs.println("#define TAGARRAYTYPE "+
592 (state.getArrayNumber(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)).makeArray(state))+state.numClasses()));
596 protected void outputClassDeclarations(PrintWriter outclassdefs) {
597 if (state.THREAD||state.DSM||state.SINGLETM)
598 outclassdefs.println("#include <pthread.h>");
599 outclassdefs.println("#ifndef INTPTR");
600 outclassdefs.println("#ifdef BIT64");
601 outclassdefs.println("#define INTPTR long");
602 outclassdefs.println("#else");
603 outclassdefs.println("#define INTPTR int");
604 outclassdefs.println("#endif");
605 outclassdefs.println("#endif");
607 outclassdefs.println("#include \"optionalstruct.h\"");
608 outclassdefs.println("struct "+arraytype+";");
609 /* Start by declaring all structs */
610 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
611 while(it.hasNext()) {
612 ClassDescriptor cn=(ClassDescriptor)it.next();
613 outclassdefs.println("struct "+cn.getSafeSymbol()+";");
615 outclassdefs.println("");
616 //Print out definition for array type
617 outclassdefs.println("struct "+arraytype+" {");
618 outclassdefs.println(" int type;");
620 outclassdefs.println(" pthread_t tid;");
621 outclassdefs.println(" void * lockentry;");
622 outclassdefs.println(" int lockcount;");
625 outclassdefs.println(" int flag;");
626 if(!state.MULTICORE) {
627 outclassdefs.println(" void * flagptr;");
629 outclassdefs.println(" int version;");
630 outclassdefs.println(" int * lock;"); // lock entry for this obj
631 outclassdefs.println(" int mutex;");
632 outclassdefs.println(" int lockcount;");
633 if(state.MULTICOREGC) {
634 outclassdefs.println(" int marked;");
638 outclassdefs.println(" int numfses;");
639 outclassdefs.println(" int * fses;");
642 printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs);
644 if (state.STMARRAY) {
645 outclassdefs.println(" int lowindex;");
646 outclassdefs.println(" int highindex;");
649 outclassdefs.println(" int paddingforarray;");
650 if (state.DUALVIEW) {
651 outclassdefs.println(" int arrayversion;");
654 outclassdefs.println(" int ___length___;");
655 outclassdefs.println("};\n");
656 outclassdefs.println("extern int classsize[];");
657 outclassdefs.println("extern int hasflags[];");
658 outclassdefs.println("extern unsigned INTPTR * pointerarray[];");
659 outclassdefs.println("extern int supertypes[];");
662 /** Prints out definitions for generic task structures */
664 private void outputTaskTypes(PrintWriter outtask) {
665 outtask.println("#ifndef _TASK_H");
666 outtask.println("#define _TASK_H");
667 outtask.println("struct parameterdescriptor {");
668 outtask.println("int type;");
669 outtask.println("int numberterms;");
670 outtask.println("int *intarray;");
671 outtask.println("void * queue;");
672 outtask.println("int numbertags;");
673 outtask.println("int *tagarray;");
674 outtask.println("};");
676 outtask.println("struct taskdescriptor {");
677 outtask.println("void * taskptr;");
678 outtask.println("int numParameters;");
679 outtask.println(" int numTotal;");
680 outtask.println("struct parameterdescriptor **descriptorarray;");
681 outtask.println("char * name;");
682 outtask.println("};");
683 outtask.println("extern struct taskdescriptor * taskarray[];");
684 outtask.println("extern numtasks;");
685 outtask.println("#endif");
689 private void buildRepairStructs(PrintWriter outrepairstructs) {
690 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
691 while(classit.hasNext()) {
692 ClassDescriptor cn=(ClassDescriptor)classit.next();
693 outrepairstructs.println("structure "+cn.getSymbol()+" {");
694 outrepairstructs.println(" int __type__;");
696 outrepairstructs.println(" int __flag__;");
697 if(!state.MULTICORE) {
698 outrepairstructs.println(" int __flagptr__;");
701 printRepairStruct(cn, outrepairstructs);
702 outrepairstructs.println("}\n");
705 for(int i=0; i<state.numArrays(); i++) {
706 TypeDescriptor tdarray=arraytable[i];
707 TypeDescriptor tdelement=tdarray.dereference();
708 outrepairstructs.println("structure "+arraytype+"_"+state.getArrayNumber(tdarray)+" {");
709 outrepairstructs.println(" int __type__;");
710 printRepairStruct(typeutil.getClass(TypeUtil.ObjectClass), outrepairstructs);
711 outrepairstructs.println(" int length;");
713 // Need to add support to repair tool for this
714 if (tdelement.isClass()||tdelement.isArray())
715 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" * elem[this.length];");
717 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" elem[this.length];");
719 outrepairstructs.println("}\n");
723 private void printRepairStruct(ClassDescriptor cn, PrintWriter output) {
724 ClassDescriptor sp=cn.getSuperDesc();
726 printRepairStruct(sp, output);
728 Vector fields=(Vector)fieldorder.get(cn);
730 for(int i=0; i<fields.size(); i++) {
731 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
732 if (fd.getType().isArray()) {
733 output.println(" "+arraytype+"_"+ state.getArrayNumber(fd.getType()) +" * "+fd.getSymbol()+";");
734 } else if (fd.getType().isClass())
735 output.println(" "+fd.getType().getRepairSymbol()+" * "+fd.getSymbol()+";");
736 else if (fd.getType().isFloat())
737 output.println(" int "+fd.getSymbol()+"; /* really float */");
739 output.println(" "+fd.getType().getRepairSymbol()+" "+fd.getSymbol()+";");
743 /** This method outputs TaskDescriptor information */
744 private void generateTaskDescriptor(PrintWriter output, FlatMethod fm, TaskDescriptor task) {
745 for (int i=0; i<task.numParameters(); i++) {
746 VarDescriptor param_var=task.getParameter(i);
747 TypeDescriptor param_type=task.getParamType(i);
748 FlagExpressionNode param_flag=task.getFlag(param_var);
749 TagExpressionList param_tag=task.getTag(param_var);
752 if (param_flag==null) {
753 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
754 output.println("0x0, 0x0 };");
757 DNFFlag dflag=param_flag.getDNF();
758 dnfterms=dflag.size();
760 Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
761 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
762 for(int j=0; j<dflag.size(); j++) {
765 Vector term=dflag.get(j);
768 for(int k=0; k<term.size(); k++) {
769 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
770 FlagDescriptor fd=dfa.getFlag();
771 boolean negated=dfa.getNegated();
772 int flagid=1<<((Integer)flags.get(fd)).intValue();
777 output.print("0x"+Integer.toHexString(andmask)+", 0x"+Integer.toHexString(checkmask));
779 output.println("};");
782 output.println("int parametertag_"+i+"_"+task.getSafeSymbol()+"[]={");
783 //BUG...added next line to fix, test with any task program
785 for(int j=0; j<param_tag.numTags(); j++) {
788 /* for each tag we need */
789 /* which slot it is */
790 /* what type it is */
791 TagVarDescriptor tvd=(TagVarDescriptor)task.getParameterTable().get(param_tag.getName(j));
792 TempDescriptor tmp=param_tag.getTemp(j);
793 int slot=fm.getTagInt(tmp);
794 output.println(slot+", "+state.getTagId(tvd.getTag()));
796 output.println("};");
798 output.println("struct parameterdescriptor parameter_"+i+"_"+task.getSafeSymbol()+"={");
799 output.println("/* type */"+param_type.getClassDesc().getId()+",");
800 output.println("/* number of DNF terms */"+dnfterms+",");
801 output.println("parameterdnf_"+i+"_"+task.getSafeSymbol()+",");
802 output.println("0,");
803 //BUG, added next line to fix and else statement...test
804 //with any task program
806 output.println("/* number of tags */"+param_tag.numTags()+",");
808 output.println("/* number of tags */ 0,");
809 output.println("parametertag_"+i+"_"+task.getSafeSymbol());
810 output.println("};");
814 output.println("struct parameterdescriptor * parameterdescriptors_"+task.getSafeSymbol()+"[] = {");
815 for (int i=0; i<task.numParameters(); i++) {
818 output.print("¶meter_"+i+"_"+task.getSafeSymbol());
820 output.println("};");
822 output.println("struct taskdescriptor task_"+task.getSafeSymbol()+"={");
823 output.println("&"+task.getSafeSymbol()+",");
824 output.println("/* number of parameters */" +task.numParameters() + ",");
825 int numtotal=task.numParameters()+fm.numTags();
826 output.println("/* number total parameters */" +numtotal + ",");
827 output.println("parameterdescriptors_"+task.getSafeSymbol()+",");
828 output.println("\""+task.getSymbol()+"\"");
829 output.println("};");
833 /** The buildVirtualTables method outputs the virtual dispatch
834 * tables for methods. */
836 protected void buildVirtualTables(PrintWriter outvirtual) {
837 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
838 while(classit.hasNext()) {
839 ClassDescriptor cd=(ClassDescriptor)classit.next();
840 if (virtualcalls.getMethodCount(cd)>maxcount)
841 maxcount=virtualcalls.getMethodCount(cd);
843 MethodDescriptor[][] virtualtable=null;
844 LocalityBinding[][] lbvirtualtable=null;
845 if (state.DSM||state.SINGLETM)
846 lbvirtualtable=new LocalityBinding[state.numClasses()+state.numArrays()][maxcount];
848 virtualtable=new MethodDescriptor[state.numClasses()+state.numArrays()][maxcount];
850 /* Fill in virtual table */
851 classit=state.getClassSymbolTable().getDescriptorsIterator();
852 while(classit.hasNext()) {
853 ClassDescriptor cd=(ClassDescriptor)classit.next();
854 if (state.DSM||state.SINGLETM)
855 fillinRow(cd, lbvirtualtable, cd.getId());
857 fillinRow(cd, virtualtable, cd.getId());
860 ClassDescriptor objectcd=typeutil.getClass(TypeUtil.ObjectClass);
861 Iterator arrayit=state.getArrayIterator();
862 while(arrayit.hasNext()) {
863 TypeDescriptor td=(TypeDescriptor)arrayit.next();
864 int id=state.getArrayNumber(td);
865 if (state.DSM||state.SINGLETM)
866 fillinRow(objectcd, lbvirtualtable, id+state.numClasses());
868 fillinRow(objectcd, virtualtable, id+state.numClasses());
871 outvirtual.print("void * virtualtable[]={");
872 boolean needcomma=false;
873 for(int i=0; i<state.numClasses()+state.numArrays(); i++) {
874 for(int j=0; j<maxcount; j++) {
876 outvirtual.print(", ");
877 if ((state.DSM||state.SINGLETM)&&lbvirtualtable[i][j]!=null) {
878 LocalityBinding lb=lbvirtualtable[i][j];
879 MethodDescriptor md=lb.getMethod();
880 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
881 } else if (!(state.DSM||state.SINGLETM)&&virtualtable[i][j]!=null) {
882 MethodDescriptor md=virtualtable[i][j];
883 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
885 outvirtual.print("0");
889 outvirtual.println("");
891 outvirtual.println("};");
895 private void fillinRow(ClassDescriptor cd, MethodDescriptor[][] virtualtable, int rownum) {
896 /* Get inherited methods */
897 if (cd.getSuperDesc()!=null)
898 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
899 /* Override them with our methods */
900 for(Iterator it=cd.getMethods(); it.hasNext();) {
901 MethodDescriptor md=(MethodDescriptor)it.next();
902 if (md.isStatic()||md.getReturnType()==null)
904 int methodnum=virtualcalls.getMethodNumber(md);
905 virtualtable[rownum][methodnum]=md;
909 private void fillinRow(ClassDescriptor cd, LocalityBinding[][] virtualtable, int rownum) {
910 /* Get inherited methods */
911 if (cd.getSuperDesc()!=null)
912 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
913 /* Override them with our methods */
914 if (locality.getClassBindings(cd)!=null)
915 for(Iterator<LocalityBinding> lbit=locality.getClassBindings(cd).iterator(); lbit.hasNext();) {
916 LocalityBinding lb=lbit.next();
917 MethodDescriptor md=lb.getMethod();
918 //Is the method static or a constructor
919 if (md.isStatic()||md.getReturnType()==null)
921 int methodnum=virtualcalls.getLocalityNumber(lb);
922 virtualtable[rownum][methodnum]=lb;
926 /** Generate array that contains the sizes of class objects. The
927 * object allocation functions in the runtime use this
930 private void generateSizeArray(PrintWriter outclassdefs) {
931 outclassdefs.print("extern struct prefetchCountStats * evalPrefetch;\n");
932 outclassdefs.print("#ifdef TRANSSTATS \n");
933 outclassdefs.print("extern int numTransAbort;\n");
934 outclassdefs.print("extern int numTransCommit;\n");
935 outclassdefs.print("extern int nSoftAbort;\n");
937 outclassdefs.print("extern int nchashSearch;\n");
938 outclassdefs.print("extern int nmhashSearch;\n");
939 outclassdefs.print("extern int nprehashSearch;\n");
940 outclassdefs.print("extern int ndirtyCacheObj;\n");
941 outclassdefs.print("extern int nRemoteSend;\n");
942 outclassdefs.print("extern int sendRemoteReq;\n");
943 outclassdefs.print("extern int getResponse;\n");
944 outclassdefs.print("extern int bytesSent;\n");
945 outclassdefs.print("extern int bytesRecv;\n");
946 outclassdefs.print("extern int totalObjSize;\n");
947 outclassdefs.print("extern void handle();\n");
948 } else if (state.SINGLETM) {
949 outclassdefs.println("extern int nSoftAbortAbort;");
950 outclassdefs.println("extern int nSoftAbortCommit;");
951 outclassdefs.println("#ifdef STMSTATS\n");
952 outclassdefs.println("extern objtypestat_t typesCausingAbort[];");
953 outclassdefs.println("#endif\n");
955 outclassdefs.print("#endif\n");
956 outclassdefs.print("int numprefetchsites = " + pa.prefetchsiteid + ";\n");
958 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
959 cdarray=new ClassDescriptor[state.numClasses()];
961 while(it.hasNext()) {
962 ClassDescriptor cd=(ClassDescriptor)it.next();
963 cdarray[cd.getId()]=cd;
966 arraytable=new TypeDescriptor[state.numArrays()];
968 Iterator arrayit=state.getArrayIterator();
969 while(arrayit.hasNext()) {
970 TypeDescriptor td=(TypeDescriptor)arrayit.next();
971 int id=state.getArrayNumber(td);
977 /* Print out types */
978 outclassdefs.println("/* ");
979 for(int i=0; i<state.numClasses(); i++) {
980 ClassDescriptor cd=cdarray[i];
982 outclassdefs.println("NULL " + i);
984 outclassdefs.println(cd +" "+i);
988 for(int i=0; i<state.numArrays(); i++) {
989 TypeDescriptor arraytd=arraytable[i];
990 outclassdefs.println(arraytd.toPrettyString() +" "+(i+state.numClasses()));
993 outclassdefs.println("*/");
996 outclassdefs.print("int classsize[]={");
998 boolean needcomma=false;
999 for(int i=0; i<state.numClasses(); i++) {
1001 outclassdefs.print(", ");
1003 outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")");
1005 outclassdefs.print("0");
1011 for(int i=0; i<state.numArrays(); i++) {
1013 outclassdefs.print(", ");
1014 TypeDescriptor tdelement=arraytable[i].dereference();
1015 if (tdelement.isArray()||tdelement.isClass())
1016 outclassdefs.print("sizeof(void *)");
1018 outclassdefs.print("sizeof("+tdelement.getSafeSymbol()+")");
1022 outclassdefs.println("};");
1024 ClassDescriptor objectclass=typeutil.getClass(TypeUtil.ObjectClass);
1026 outclassdefs.print("int typearray[]={");
1027 for(int i=0; i<state.numClasses(); i++) {
1028 ClassDescriptor cd=cdarray[i];
1029 ClassDescriptor supercd=i>0?cd.getSuperDesc():null;
1031 outclassdefs.print(", ");
1033 outclassdefs.print("-1");
1035 outclassdefs.print(supercd.getId());
1039 for(int i=0; i<state.numArrays(); i++) {
1040 TypeDescriptor arraytd=arraytable[i];
1041 ClassDescriptor arraycd=arraytd.getClassDesc();
1042 if (arraycd==null) {
1044 outclassdefs.print(", ");
1045 outclassdefs.print(objectclass.getId());
1049 ClassDescriptor cd=arraycd.getSuperDesc();
1052 TypeDescriptor supertd=new TypeDescriptor(cd);
1053 supertd.setArrayCount(arraytd.getArrayCount());
1054 type=state.getArrayNumber(supertd);
1056 type+=state.numClasses();
1059 cd=cd.getSuperDesc();
1062 outclassdefs.print(", ");
1063 outclassdefs.print(type);
1067 outclassdefs.println("};");
1072 outclassdefs.print("int typearray2[]={");
1073 for(int i=0; i<state.numArrays(); i++) {
1074 TypeDescriptor arraytd=arraytable[i];
1075 ClassDescriptor arraycd=arraytd.getClassDesc();
1076 if (arraycd==null) {
1078 outclassdefs.print(", ");
1079 outclassdefs.print("-1");
1083 ClassDescriptor cd=arraycd.getSuperDesc();
1084 int level=arraytd.getArrayCount()-1;
1086 for(; level>0; level--) {
1087 TypeDescriptor supertd=new TypeDescriptor(objectclass);
1088 supertd.setArrayCount(level);
1089 type=state.getArrayNumber(supertd);
1091 type+=state.numClasses();
1096 outclassdefs.print(", ");
1097 outclassdefs.print(type);
1101 outclassdefs.println("};");
1104 /** Constructs params and temp objects for each method or task.
1105 * These objects tell the compiler which temps need to be
1108 protected void generateTempStructs(FlatMethod fm, LocalityBinding lb) {
1109 MethodDescriptor md=fm.getMethod();
1110 TaskDescriptor task=fm.getTask();
1111 Set<TempDescriptor> saveset=lb!=null ? locality.getTempSet(lb) : null;
1112 ParamsObject objectparams=md!=null ? new ParamsObject(md,tag++) : new ParamsObject(task, tag++);
1114 paramstable.put(lb, objectparams);
1115 backuptable.put(lb, new Hashtable<TempDescriptor, TempDescriptor>());
1116 } else if (md!=null)
1117 paramstable.put(md, objectparams);
1119 paramstable.put(task, objectparams);
1121 for(int i=0; i<fm.numParameters(); i++) {
1122 TempDescriptor temp=fm.getParameter(i);
1123 TypeDescriptor type=temp.getType();
1124 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1125 objectparams.addPtr(temp);
1127 objectparams.addPrim(temp);
1128 if(lb!=null&&saveset.contains(temp)) {
1129 backuptable.get(lb).put(temp, temp.createNew());
1133 for(int i=0; i<fm.numTags(); i++) {
1134 TempDescriptor temp=fm.getTag(i);
1135 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1136 objectparams.addPtr(temp);
1138 objectparams.addPrim(temp);
1141 TempObject objecttemps=md!=null ? new TempObject(objectparams,md,tag++) : new TempObject(objectparams, task, tag++);
1143 tempstable.put(lb, objecttemps);
1145 tempstable.put(md, objecttemps);
1147 tempstable.put(task, objecttemps);
1149 for(Iterator nodeit=fm.getNodeSet().iterator(); nodeit.hasNext();) {
1150 FlatNode fn=(FlatNode)nodeit.next();
1151 TempDescriptor[] writes=fn.writesTemps();
1152 for(int i=0; i<writes.length; i++) {
1153 TempDescriptor temp=writes[i];
1154 TypeDescriptor type=temp.getType();
1155 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1156 objecttemps.addPtr(temp);
1158 objecttemps.addPrim(temp);
1159 if(lb!=null&&saveset.contains(temp)&&
1160 !backuptable.get(lb).containsKey(temp))
1161 backuptable.get(lb).put(temp, temp.createNew());
1165 /* Create backup temps */
1167 for(Iterator<TempDescriptor> tmpit=backuptable.get(lb).values().iterator(); tmpit.hasNext();) {
1168 TempDescriptor tmp=tmpit.next();
1169 TypeDescriptor type=tmp.getType();
1170 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1171 objecttemps.addPtr(tmp);
1173 objecttemps.addPrim(tmp);
1175 /* Create temp to hold revert table */
1176 if (state.DSM&&(lb.getHasAtomic()||lb.isAtomic())) {
1177 TempDescriptor reverttmp=new TempDescriptor("revertlist", typeutil.getClass(TypeUtil.ObjectClass));
1178 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1179 objecttemps.addPtr(reverttmp);
1181 objecttemps.addPrim(reverttmp);
1182 reverttable.put(lb, reverttmp);
1187 /** This method outputs the following information about classes
1189 * (1) For classes, what are the locations of pointers.
1190 * (2) For arrays, does the array contain pointers or primitives.
1191 * (3) For classes, does the class contain flags.
1194 private void generateLayoutStructs(PrintWriter output) {
1195 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1196 while(it.hasNext()) {
1197 ClassDescriptor cn=(ClassDescriptor)it.next();
1198 output.println("unsigned INTPTR "+cn.getSafeSymbol()+"_pointers[]={");
1199 Iterator allit=cn.getFieldTable().getAllDescriptorsIterator();
1201 while(allit.hasNext()) {
1202 FieldDescriptor fd=(FieldDescriptor)allit.next();
1203 TypeDescriptor type=fd.getType();
1204 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1209 output.print(count);
1210 allit=cn.getFieldTable().getAllDescriptorsIterator();
1211 while(allit.hasNext()) {
1212 FieldDescriptor fd=(FieldDescriptor)allit.next();
1213 TypeDescriptor type=fd.getType();
1214 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1217 output.println(",");
1218 output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+fd.getSafeSymbol()+"))");
1221 output.println("};");
1223 output.println("unsigned INTPTR * pointerarray[]={");
1224 boolean needcomma=false;
1225 for(int i=0; i<state.numClasses(); i++) {
1226 ClassDescriptor cn=cdarray[i];
1228 output.println(",");
1231 output.print(cn.getSafeSymbol()+"_pointers");
1233 output.print("NULL");
1237 for(int i=0; i<state.numArrays(); i++) {
1239 output.println(", ");
1240 TypeDescriptor tdelement=arraytable[i].dereference();
1241 if (tdelement.isArray()||tdelement.isClass())
1242 output.print("((unsigned INTPTR *)1)");
1248 output.println("};");
1250 output.println("int hasflags[]={");
1251 for(int i=0; i<state.numClasses(); i++) {
1252 ClassDescriptor cn=cdarray[i];
1254 output.println(", ");
1256 if ((cn != null) && (cn.hasFlags()))
1261 output.println("};");
1264 /** Print out table to give us supertypes */
1265 private void generateSuperTypeTable(PrintWriter output) {
1266 output.println("int supertypes[]={");
1267 boolean needcomma=false;
1268 for(int i=0; i<state.numClasses(); i++) {
1269 ClassDescriptor cn=cdarray[i];
1271 output.println(",");
1273 if ((cn != null) && (cn.getSuperDesc()!=null)) {
1274 ClassDescriptor cdsuper=cn.getSuperDesc();
1275 output.print(cdsuper.getId());
1279 output.println("};");
1282 /** Force consistent field ordering between inherited classes. */
1284 private void printClassStruct(ClassDescriptor cn, PrintWriter classdefout) {
1286 ClassDescriptor sp=cn.getSuperDesc();
1288 printClassStruct(sp, classdefout);
1290 if (!fieldorder.containsKey(cn)) {
1291 Vector fields=new Vector();
1292 fieldorder.put(cn,fields);
1293 Vector fieldvec=cn.getFieldVec();
1294 for(int i=0;i<fieldvec.size();i++) {
1295 FieldDescriptor fd=(FieldDescriptor)fieldvec.get(i);
1296 if ((sp==null||!sp.getFieldTable().contains(fd.getSymbol())))
1300 Vector fields=(Vector)fieldorder.get(cn);
1302 for(int i=0; i<fields.size(); i++) {
1303 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
1304 if (fd.getType().isClass()||fd.getType().isArray())
1305 classdefout.println(" struct "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1307 classdefout.println(" "+fd.getType().getSafeSymbol()+" "+fd.getSafeSymbol()+";");
1312 /* Map flags to integers consistently between inherited
1315 protected void mapFlags(ClassDescriptor cn) {
1316 ClassDescriptor sp=cn.getSuperDesc();
1320 if (!flagorder.containsKey(cn)) {
1321 Hashtable flags=new Hashtable();
1322 flagorder.put(cn,flags);
1324 Hashtable superflags=(Hashtable)flagorder.get(sp);
1325 Iterator superflagit=superflags.keySet().iterator();
1326 while(superflagit.hasNext()) {
1327 FlagDescriptor fd=(FlagDescriptor)superflagit.next();
1328 Integer number=(Integer)superflags.get(fd);
1329 flags.put(fd, number);
1330 if ((number.intValue()+1)>max)
1331 max=number.intValue()+1;
1335 Iterator flagit=cn.getFlags();
1336 while(flagit.hasNext()) {
1337 FlagDescriptor fd=(FlagDescriptor)flagit.next();
1338 if (sp==null||!sp.getFlagTable().contains(fd.getSymbol()))
1339 flags.put(fd, new Integer(max++));
1345 /** This function outputs (1) structures that parameters are
1346 * passed in (when PRECISE GC is enabled) and (2) function
1347 * prototypes for the methods */
1349 protected void generateCallStructs(ClassDescriptor cn, PrintWriter classdefout, PrintWriter output, PrintWriter headersout) {
1350 /* Output class structure */
1351 classdefout.println("struct "+cn.getSafeSymbol()+" {");
1352 classdefout.println(" int type;");
1354 classdefout.println(" pthread_t tid;");
1355 classdefout.println(" void * lockentry;");
1356 classdefout.println(" int lockcount;");
1360 classdefout.println(" int flag;");
1361 if((!state.MULTICORE) || (cn.getSymbol().equals("TagDescriptor"))) {
1362 classdefout.println(" void * flagptr;");
1363 } else if (state.MULTICORE) {
1364 classdefout.println(" int version;");
1365 classdefout.println(" int * lock;"); // lock entry for this obj
1366 classdefout.println(" int mutex;");
1367 classdefout.println(" int lockcount;");
1368 if(state.MULTICOREGC) {
1369 classdefout.println(" int marked;");
1372 if (state.OPTIONAL) {
1373 classdefout.println(" int numfses;");
1374 classdefout.println(" int * fses;");
1377 printClassStruct(cn, classdefout);
1378 classdefout.println("};\n");
1380 if (state.DSM||state.SINGLETM) {
1381 /* Cycle through LocalityBindings */
1382 HashSet<MethodDescriptor> nativemethods=new HashSet<MethodDescriptor>();
1383 Set<LocalityBinding> lbset=locality.getClassBindings(cn);
1385 for(Iterator<LocalityBinding> lbit=lbset.iterator(); lbit.hasNext();) {
1386 LocalityBinding lb=lbit.next();
1387 MethodDescriptor md=lb.getMethod();
1388 if (md.getModifiers().isNative()) {
1389 //make sure we only print a native method once
1390 if (nativemethods.contains(md)) {
1391 FlatMethod fm=state.getMethodFlat(md);
1392 generateTempStructs(fm, lb);
1395 nativemethods.add(md);
1397 generateMethod(cn, md, lb, headersout, output);
1400 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1401 MethodDescriptor md=(MethodDescriptor)methodit.next();
1402 if (md.getModifiers().isNative()&&!nativemethods.contains(md)) {
1403 //Need to build param structure for library code
1404 FlatMethod fm=state.getMethodFlat(md);
1405 generateTempStructs(fm, null);
1406 generateMethodParam(cn, md, null, output);
1411 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1412 MethodDescriptor md=(MethodDescriptor)methodit.next();
1413 generateMethod(cn, md, null, headersout, output);
1417 private void generateMethodParam(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter output) {
1418 /* Output parameter structure */
1419 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1420 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1421 if ((state.DSM||state.SINGLETM)&&lb!=null)
1422 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1424 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1425 output.println(" INTPTR size;");
1426 output.println(" void * next;");
1427 for(int i=0; i<objectparams.numPointers(); i++) {
1428 TempDescriptor temp=objectparams.getPointer(i);
1429 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1431 output.println("};\n");
1435 private void generateMethod(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter headersout, PrintWriter output) {
1436 FlatMethod fm=state.getMethodFlat(md);
1437 generateTempStructs(fm, lb);
1439 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1440 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md);
1442 generateMethodParam(cn, md, lb, output);
1444 /* Output temp structure */
1445 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1446 if (state.DSM||state.SINGLETM)
1447 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1449 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1450 output.println(" INTPTR size;");
1451 output.println(" void * next;");
1452 for(int i=0; i<objecttemps.numPointers(); i++) {
1453 TempDescriptor temp=objecttemps.getPointer(i);
1454 if (temp.getType().isNull())
1455 output.println(" void * "+temp.getSafeSymbol()+";");
1457 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1459 output.println("};\n");
1462 /********* Output method declaration ***********/
1463 if (state.DSM||state.SINGLETM) {
1464 headersout.println("#define D"+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1466 headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1468 /* First the return type */
1469 if (md.getReturnType()!=null) {
1470 if (md.getReturnType().isClass()||md.getReturnType().isArray())
1471 headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1473 headersout.print(md.getReturnType().getSafeSymbol()+" ");
1475 //catch the constructor case
1476 headersout.print("void ");
1478 /* Next the method name */
1479 if (state.DSM||state.SINGLETM) {
1480 headersout.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1482 headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1484 boolean printcomma=false;
1485 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1486 if (state.DSM||state.SINGLETM) {
1487 headersout.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1489 headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1493 /* Output parameter list*/
1494 for(int i=0; i<objectparams.numPrimitives(); i++) {
1495 TempDescriptor temp=objectparams.getPrimitive(i);
1497 headersout.print(", ");
1499 if (temp.getType().isClass()||temp.getType().isArray())
1500 headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1502 headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1504 headersout.println(");\n");
1508 /** This function outputs (1) structures that parameters are
1509 * passed in (when PRECISE GC is enabled) and (2) function
1510 * prototypes for the tasks */
1512 private void generateTaskStructs(PrintWriter output, PrintWriter headersout) {
1513 /* Cycle through tasks */
1514 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
1516 while(taskit.hasNext()) {
1517 /* Classify parameters */
1518 TaskDescriptor task=(TaskDescriptor)taskit.next();
1519 FlatMethod fm=state.getMethodFlat(task);
1520 generateTempStructs(fm, null);
1522 ParamsObject objectparams=(ParamsObject) paramstable.get(task);
1523 TempObject objecttemps=(TempObject) tempstable.get(task);
1525 /* Output parameter structure */
1526 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1527 output.println("struct "+task.getSafeSymbol()+"_params {");
1529 output.println(" INTPTR size;");
1530 output.println(" void * next;");
1531 for(int i=0; i<objectparams.numPointers(); i++) {
1532 TempDescriptor temp=objectparams.getPointer(i);
1533 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1536 output.println("};\n");
1537 if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
1538 maxtaskparams=objectparams.numPointers()+fm.numTags();
1542 /* Output temp structure */
1543 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1544 output.println("struct "+task.getSafeSymbol()+"_locals {");
1545 output.println(" INTPTR size;");
1546 output.println(" void * next;");
1547 for(int i=0; i<objecttemps.numPointers(); i++) {
1548 TempDescriptor temp=objecttemps.getPointer(i);
1549 if (temp.getType().isNull())
1550 output.println(" void * "+temp.getSafeSymbol()+";");
1551 else if(temp.getType().isTag())
1552 output.println(" struct "+
1553 (new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1555 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1557 output.println("};\n");
1560 /* Output task declaration */
1561 headersout.print("void " + task.getSafeSymbol()+"(");
1563 boolean printcomma=false;
1564 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1565 headersout.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
1567 headersout.print("void * parameterarray[]");
1568 headersout.println(");\n");
1572 /***** Generate code for FlatMethod fm. *****/
1574 Hashtable<FlatAtomicEnterNode, AtomicRecord> atomicmethodmap;
1575 static int atomicmethodcount=0;
1578 BranchAnalysis branchanalysis;
1579 private void generateFlatMethod(FlatMethod fm, LocalityBinding lb, PrintWriter output) {
1580 if (State.PRINTFLAT)
1581 System.out.println(fm.printMethod());
1582 MethodDescriptor md=fm.getMethod();
1583 TaskDescriptor task=fm.getTask();
1584 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
1585 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : md!=null ? md : task);
1587 HashSet<AtomicRecord> arset=null;
1588 branchanalysis=null;
1590 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1592 if (atomicmethodmap==null)
1593 atomicmethodmap=new Hashtable<FlatAtomicEnterNode, AtomicRecord>();
1595 //fix these so we get right strings for local variables
1596 localsprefixaddr=localsprefix;
1597 localsprefixderef=localsprefix+"->";
1598 arset=new HashSet<AtomicRecord>();
1600 //build branchanalysis
1601 branchanalysis=new BranchAnalysis(locality, lb, delaycomp.getNotReady(lb), delaycomp.livecode(lb), state);
1603 //Generate commit methods here
1604 for(Iterator<FlatNode> fnit=fm.getNodeSet().iterator();fnit.hasNext();) {
1605 FlatNode fn=fnit.next();
1606 if (fn.kind()==FKind.FlatAtomicEnterNode&&
1607 locality.getAtomic(lb).get(fn.getPrev(0)).intValue()==0&&
1608 delaycomp.needsFission(lb, (FlatAtomicEnterNode) fn)) {
1609 //We have an atomic enter
1610 FlatAtomicEnterNode faen=(FlatAtomicEnterNode) fn;
1611 Set<FlatNode> exitset=faen.getExits();
1613 String methodname=md.getSymbol()+(atomicmethodcount++);
1614 AtomicRecord ar=new AtomicRecord();
1618 atomicmethodmap.put(faen, ar);
1620 //build data structure declaration
1621 output.println("struct atomicprimitives_"+methodname+" {");
1623 Set<FlatNode> recordset=delaycomp.livecode(lb);
1624 Set<TempDescriptor> liveinto=delaycomp.liveinto(lb, faen, recordset);
1625 Set<TempDescriptor> liveout=delaycomp.liveout(lb, faen);
1626 Set<TempDescriptor> liveoutvirtualread=delaycomp.liveoutvirtualread(lb, faen);
1628 ar.reallivein=new HashSet(liveinto);
1630 ar.liveoutvirtualread=liveoutvirtualread;
1632 for(Iterator<TempDescriptor> it=liveinto.iterator(); it.hasNext();) {
1633 TempDescriptor tmp=it.next();
1634 //remove the pointers
1635 if (tmp.getType().isPtr()) {
1638 //let's print it here
1639 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1642 for(Iterator<TempDescriptor> it=liveout.iterator(); it.hasNext();) {
1643 TempDescriptor tmp=it.next();
1644 //remove the pointers
1645 if (tmp.getType().isPtr()) {
1647 } else if (!liveinto.contains(tmp)) {
1648 //let's print it here
1649 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1652 output.println("};");
1654 //print out method name
1655 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) {");
1656 //build code for commit method
1658 //first define local primitives
1659 Set<TempDescriptor> alltemps=delaycomp.alltemps(lb, faen, recordset);
1660 for(Iterator<TempDescriptor> tmpit=alltemps.iterator();tmpit.hasNext();) {
1661 TempDescriptor tmp=tmpit.next();
1662 if (!tmp.getType().isPtr()) {
1663 if (liveinto.contains(tmp)||liveoutvirtualread.contains(tmp)) {
1664 //read from live into set
1665 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+"=primitives->"+tmp.getSafeSymbol()+";");
1668 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1672 //turn off write barrier generation
1674 state.SINGLETM=false;
1675 generateCode(faen, fm, lb, exitset, output, false);
1676 state.SINGLETM=true;
1677 //turn on write barrier generation
1679 output.println("}\n\n");
1683 //redefine these back to normal
1685 localsprefixaddr="&"+localsprefix;
1686 localsprefixderef=localsprefix+".";
1688 generateHeader(fm, lb, md!=null ? md : task,output);
1689 TempObject objecttemp=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
1691 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1692 for(Iterator<AtomicRecord> arit=arset.iterator();arit.hasNext();) {
1693 AtomicRecord ar=arit.next();
1694 output.println("struct atomicprimitives_"+ar.name+" primitives_"+ar.name+";");
1698 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1699 if (md!=null&&(state.DSM||state.SINGLETM))
1700 output.print(" struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1701 else if (md!=null&&!(state.DSM||state.SINGLETM))
1702 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1704 output.print(" struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={");
1706 output.print(objecttemp.numPointers()+",");
1707 output.print(paramsprefix);
1708 for(int j=0; j<objecttemp.numPointers(); j++)
1709 output.print(", NULL");
1710 output.println("};");
1713 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1714 TempDescriptor td=objecttemp.getPrimitive(i);
1715 TypeDescriptor type=td.getType();
1717 output.println(" void * "+td.getSafeSymbol()+";");
1718 else if (type.isClass()||type.isArray())
1719 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1721 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1726 if( fm.getNext(0) instanceof FlatSESEEnterNode ) {
1727 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
1728 if( callerSESEplaceholder != mlpa.getMainSESE() ) {
1729 // declare variables for naming static SESE's
1730 output.println(" /* static SESE names */");
1731 Iterator<SESEandAgePair> pItr = callerSESEplaceholder.getNeededStaticNames().iterator();
1732 while( pItr.hasNext() ) {
1733 SESEandAgePair p = pItr.next();
1734 output.println(" void* "+p+";");
1737 // declare variables for tracking dynamic sources
1738 output.println(" /* dynamic variable sources */");
1739 Iterator<TempDescriptor> dynSrcItr = callerSESEplaceholder.getDynamicVarSet().iterator();
1740 while( dynSrcItr.hasNext() ) {
1741 TempDescriptor dynSrcVar = dynSrcItr.next();
1742 output.println(" void* "+dynSrcVar+"_srcSESE;");
1743 output.println(" int "+dynSrcVar+"_srcOffset;");
1750 /* Check to see if we need to do a GC if this is a
1751 * multi-threaded program...*/
1753 if (((state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
1754 || this.state.MULTICOREGC) {
1755 //Don't bother if we aren't in recursive methods...The loops case will catch it
1756 if (callgraph.getAllMethods(md).contains(md)) {
1757 if (state.DSM&&lb.isAtomic())
1758 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
1759 else if (this.state.MULTICOREGC) {
1760 output.println("if(gcflag) gc("+localsprefixaddr+");");
1762 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
1767 generateCode(fm.getNext(0), fm, lb, null, output, true);
1769 output.println("}\n\n");
1773 protected void initializeSESE( FlatSESEEnterNode fsen ) {
1775 FlatMethod fm = fsen.getfmEnclosing();
1776 MethodDescriptor md = fm.getMethod();
1777 ClassDescriptor cn = md.getClassDesc();
1780 // Creates bogus method descriptor to index into tables
1781 Modifiers modBogus = new Modifiers();
1782 MethodDescriptor mdBogus =
1783 new MethodDescriptor( modBogus,
1784 new TypeDescriptor( TypeDescriptor.VOID ),
1785 "sese_"+fsen.getPrettyIdentifier()+fsen.getIdentifier()
1788 mdBogus.setClassDesc( fsen.getcdEnclosing() );
1789 FlatMethod fmBogus = new FlatMethod( mdBogus, null );
1790 fsen.setfmBogus( fmBogus );
1791 fsen.setmdBogus( mdBogus );
1793 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1794 inSetAndOutSet.addAll( fsen.getInVarSet() );
1795 inSetAndOutSet.addAll( fsen.getOutVarSet() );
1797 // Build paramsobj for bogus method descriptor
1798 ParamsObject objectparams = new ParamsObject( mdBogus, tag++ );
1799 paramstable.put( mdBogus, objectparams );
1801 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1802 while( itr.hasNext() ) {
1803 TempDescriptor temp = itr.next();
1804 TypeDescriptor type = temp.getType();
1805 if( type.isPtr() ) {
1806 objectparams.addPtr( temp );
1808 objectparams.addPrim( temp );
1812 // Build normal temp object for bogus method descriptor
1813 TempObject objecttemps = new TempObject( objectparams, mdBogus, tag++ );
1814 tempstable.put( mdBogus, objecttemps );
1816 for( Iterator nodeit = fsen.getNodeSet().iterator(); nodeit.hasNext(); ) {
1817 FlatNode fn = (FlatNode)nodeit.next();
1818 TempDescriptor[] writes = fn.writesTemps();
1820 for( int i = 0; i < writes.length; i++ ) {
1821 TempDescriptor temp = writes[i];
1822 TypeDescriptor type = temp.getType();
1824 if( type.isPtr() ) {
1825 objecttemps.addPtr( temp );
1827 objecttemps.addPrim( temp );
1833 protected void generateMethodSESE(FlatSESEEnterNode fsen,
1835 PrintWriter outputStructs,
1836 PrintWriter outputMethHead,
1837 PrintWriter outputMethods
1840 ParamsObject objectparams = (ParamsObject) paramstable.get( fsen.getmdBogus() );
1841 TempObject objecttemps = (TempObject) tempstable .get( fsen.getmdBogus() );
1843 // generate locals structure
1844 outputStructs.println("struct "+
1845 fsen.getcdEnclosing().getSafeSymbol()+
1846 fsen.getmdBogus().getSafeSymbol()+"_"+
1847 fsen.getmdBogus().getSafeMethodDescriptor()+
1849 outputStructs.println(" INTPTR size;");
1850 outputStructs.println(" void * next;");
1851 for(int i=0; i<objecttemps.numPointers(); i++) {
1852 TempDescriptor temp=objecttemps.getPointer(i);
1854 if( fsen.getPrettyIdentifier().equals( "calc" ) ) {
1855 System.out.println( " got a pointer "+temp );
1858 if (temp.getType().isNull())
1859 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
1861 outputStructs.println(" struct "+
1862 temp.getType().getSafeSymbol()+" * "+
1863 temp.getSafeSymbol()+";");
1865 outputStructs.println("};\n");
1868 // generate the SESE record structure
1869 outputStructs.println(fsen.getSESErecordName()+" {");
1871 // data common to any SESE, and it must be placed first so
1872 // a module that doesn't know what kind of SESE record this
1873 // is can cast the pointer to a common struct
1874 outputStructs.println(" SESEcommon common;");
1876 // then garbage list stuff
1877 outputStructs.println(" INTPTR size;");
1878 outputStructs.println(" void * next;");
1880 // in-set source tracking
1881 // in-vars that are READY come from parent, don't need anything
1882 // stuff STATIC needs a custom SESE pointer for each age pair
1883 Iterator<SESEandAgePair> itrStaticInVarSrcs = fsen.getStaticInVarSrcs().iterator();
1884 while( itrStaticInVarSrcs.hasNext() ) {
1885 SESEandAgePair srcPair = itrStaticInVarSrcs.next();
1886 outputStructs.println(" "+srcPair.getSESE().getSESErecordName()+"* "+srcPair+";");
1889 // DYNAMIC stuff needs a source SESE ptr and offset
1890 Iterator<TempDescriptor> itrDynInVars = fsen.getDynamicInVarSet().iterator();
1891 while( itrDynInVars.hasNext() ) {
1892 TempDescriptor dynInVar = itrDynInVars.next();
1893 outputStructs.println(" void* "+dynInVar+"_srcSESE;");
1894 outputStructs.println(" int "+dynInVar+"_srcOffset;");
1897 // space for all in and out set primitives
1898 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1899 inSetAndOutSet.addAll( fsen.getInVarSet() );
1900 inSetAndOutSet.addAll( fsen.getOutVarSet() );
1902 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
1904 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1905 while( itr.hasNext() ) {
1906 TempDescriptor temp = itr.next();
1907 TypeDescriptor type = temp.getType();
1908 if( !type.isPtr() ) {
1909 inSetAndOutSetPrims.add( temp );
1913 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
1914 while( itrPrims.hasNext() ) {
1915 TempDescriptor temp = itrPrims.next();
1916 TypeDescriptor type = temp.getType();
1917 outputStructs.println(" "+temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol()+";");
1920 for(int i=0; i<objectparams.numPointers(); i++) {
1921 TempDescriptor temp=objectparams.getPointer(i);
1922 if (temp.getType().isNull())
1923 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
1925 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1928 outputStructs.println("};\n");
1931 // write method declaration to header file
1932 outputMethHead.print("void ");
1933 outputMethHead.print(fsen.getSESEmethodName()+"(");
1934 outputMethHead.print(fsen.getSESErecordName()+"* "+paramsprefix);
1935 outputMethHead.println(");\n");
1938 generateFlatMethodSESE( fsen.getfmBogus(),
1939 fsen.getcdEnclosing(),
1945 private void generateFlatMethodSESE(FlatMethod fm,
1947 FlatSESEEnterNode fsen,
1948 FlatSESEExitNode seseExit,
1952 MethodDescriptor md=fm.getMethod();
1954 output.print("void ");
1955 output.print(fsen.getSESEmethodName()+"(");
1956 output.print(fsen.getSESErecordName()+"* "+paramsprefix);
1957 output.println("){\n");
1959 TempObject objecttemp=(TempObject) tempstable.get(md);
1961 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1962 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1963 output.print(objecttemp.numPointers()+",");
1964 output.print("(void*) &("+paramsprefix+"->size)");
1965 for(int j=0; j<objecttemp.numPointers(); j++)
1966 output.print(", NULL");
1967 output.println("};");
1970 output.println(" /* regular local primitives */");
1971 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1972 TempDescriptor td=objecttemp.getPrimitive(i);
1973 TypeDescriptor type=td.getType();
1975 output.println(" void * "+td.getSafeSymbol()+";");
1976 else if (type.isClass()||type.isArray())
1977 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1979 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1983 // declare variables for naming static SESE's
1984 output.println(" /* static SESE names */");
1985 Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
1986 while( pItr.hasNext() ) {
1987 SESEandAgePair p = pItr.next();
1988 output.println(" void* "+p+";");
1991 // declare variables for tracking dynamic sources
1992 output.println(" /* dynamic variable sources */");
1993 Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
1994 while( dynSrcItr.hasNext() ) {
1995 TempDescriptor dynSrcVar = dynSrcItr.next();
1996 output.println(" void* "+dynSrcVar+"_srcSESE;");
1997 output.println(" int "+dynSrcVar+"_srcOffset;");
2000 // declare local temps for in-set primitives, and if it is
2001 // a ready-source variable, get the value from the record
2002 output.println(" /* local temps for in-set primitives */");
2003 Iterator<TempDescriptor> itrInSet = fsen.getInVarSet().iterator();
2004 while( itrInSet.hasNext() ) {
2005 TempDescriptor temp = itrInSet.next();
2006 TypeDescriptor type = temp.getType();
2007 if( !type.isPtr() ) {
2008 if( fsen.getReadyInVarSet().contains( temp ) ) {
2009 output.println(" "+type+" "+temp+" = "+paramsprefix+"->"+temp+";");
2011 output.println(" "+type+" "+temp+";");
2016 // declare local temps for out-set primitives if its not already
2017 // in the in-set, and it's value will get written so no problem
2018 output.println(" /* local temp for out-set prim, not already in the in-set */");
2019 Iterator<TempDescriptor> itrOutSet = fsen.getOutVarSet().iterator();
2020 while( itrOutSet.hasNext() ) {
2021 TempDescriptor temp = itrOutSet.next();
2022 TypeDescriptor type = temp.getType();
2023 if( !type.isPtr() && !fsen.getInVarSet().contains( temp ) ) {
2024 output.println(" "+type+" "+temp+";");
2028 // copy in-set into place, ready vars were already
2029 // copied when the SESE was issued
2030 Iterator<TempDescriptor> tempItr;
2032 // static vars are from a known SESE
2033 tempItr = fsen.getStaticInVarSet().iterator();
2034 while( tempItr.hasNext() ) {
2035 TempDescriptor temp = tempItr.next();
2036 VariableSourceToken vst = fsen.getStaticInVarSrc( temp );
2037 SESEandAgePair srcPair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2039 // can't grab something from this source until it is done
2040 output.println(" {");
2041 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+srcPair+";" );
2042 output.println(" pthread_mutex_lock( &(com->lock) );");
2043 output.println(" while( com->doneExecuting == FALSE ) {");
2044 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
2045 output.println(" }");
2046 output.println(" pthread_mutex_unlock( &(com->lock) );");
2048 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2049 " = "+paramsprefix+"->"+srcPair+"->"+vst.getAddrVar()+";");
2051 output.println(" }");
2054 // dynamic vars come from an SESE and src
2055 tempItr = fsen.getDynamicInVarSet().iterator();
2056 while( tempItr.hasNext() ) {
2057 TempDescriptor temp = tempItr.next();
2058 TypeDescriptor type = temp.getType();
2060 // go grab it from the SESE source
2061 output.println(" if( "+paramsprefix+"->"+temp+"_srcSESE != NULL ) {");
2063 // gotta wait until the source is done
2064 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+temp+"_srcSESE;" );
2065 output.println(" pthread_mutex_lock( &(com->lock) );");
2066 output.println(" while( com->doneExecuting == FALSE ) {");
2067 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
2068 output.println(" }");
2069 output.println(" pthread_mutex_unlock( &(com->lock) );");
2072 if( type.isNull() ) {
2074 } else if( type.isClass() || type.isArray() ) {
2075 typeStr = "struct "+type.getSafeSymbol()+"*";
2077 typeStr = type.getSafeSymbol();
2080 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2081 " = *(("+typeStr+"*) ("+
2082 paramsprefix+"->"+temp+"_srcSESE + "+
2083 paramsprefix+"->"+temp+"_srcOffset));");
2085 // or if the source was our parent, its in the record to grab
2086 output.println(" } else {");
2087 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2088 " = "+paramsprefix+"->"+temp+";");
2089 output.println(" }");
2092 // Check to see if we need to do a GC if this is a
2093 // multi-threaded program...
2094 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2095 //Don't bother if we aren't in recursive methods...The loops case will catch it
2096 if (callgraph.getAllMethods(md).contains(md)) {
2097 if(this.state.MULTICOREGC) {
2098 output.println("if(gcflag) gc("+localsprefixaddr+");");
2100 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2105 // initialize thread-local var to a non-zero, invalid address
2106 output.println(" seseCaller = (SESEcommon*) 0x2;");
2107 HashSet<FlatNode> exitset=new HashSet<FlatNode>();
2108 exitset.add(seseExit);
2109 generateCode(fsen.getNext(0), fm, null, exitset, output, true);
2110 output.println("}\n\n");
2114 // when a new mlp thread is created for an issued SESE, it is started
2115 // by running this method which blocks on a cond variable until
2116 // it is allowed to transition to execute. Then a case statement
2117 // allows it to invoke the method with the proper SESE body, and after
2118 // exiting the SESE method, executes proper SESE exit code before the
2119 // thread can be destroyed
2120 private void generateSESEinvocationMethod(PrintWriter outmethodheader,
2121 PrintWriter outmethod
2124 outmethodheader.println("void* invokeSESEmethod( void* seseRecord );");
2125 outmethod.println( "void* invokeSESEmethod( void* seseRecord ) {");
2126 outmethod.println( " int status;");
2127 outmethod.println( " char errmsg[128];");
2129 // generate a case for each SESE class that can be invoked
2130 outmethod.println( " switch( *((int*)seseRecord) ) {");
2131 outmethod.println( " ");
2132 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
2133 FlatSESEEnterNode fsen = seseit.next();
2135 outmethod.println( " /* "+fsen.getPrettyIdentifier()+" */");
2136 outmethod.println( " case "+fsen.getIdentifier()+":");
2137 outmethod.println( " "+fsen.getSESEmethodName()+"( seseRecord );");
2139 if( fsen.equals( mlpa.getMainSESE() ) ) {
2140 outmethod.println( " /* work scheduler works forever, explicitly exit */");
2141 outmethod.println( " exit( 0 );");
2144 outmethod.println( " break;");
2145 outmethod.println( "");
2148 // default case should never be taken, error out
2149 outmethod.println( " default:");
2150 outmethod.println( " printf(\"Error: unknown SESE class ID in invoke method.\\n\");");
2151 outmethod.println( " exit(-30);");
2152 outmethod.println( " break;");
2153 outmethod.println( " }");
2154 outmethod.println( " return NULL;");
2155 outmethod.println( "}\n\n");
2159 protected void generateCode(FlatNode first,
2162 Set<FlatNode> stopset,
2163 PrintWriter output, boolean firstpass) {
2165 /* Assign labels to FlatNode's if necessary.*/
2167 Hashtable<FlatNode, Integer> nodetolabel;
2169 if (state.DELAYCOMP&&!firstpass)
2170 nodetolabel=dcassignLabels(first, stopset);
2172 nodetolabel=assignLabels(first, stopset);
2174 Set<FlatNode> storeset=null;
2175 HashSet<FlatNode> genset=null;
2176 HashSet<FlatNode> refset=null;
2177 Set<FlatNode> unionset=null;
2179 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
2180 storeset=delaycomp.livecode(lb);
2181 genset=new HashSet<FlatNode>();
2182 if (state.STMARRAY&&!state.DUALVIEW) {
2183 refset=new HashSet<FlatNode>();
2184 refset.addAll(delaycomp.getDeref(lb));
2185 refset.removeAll(delaycomp.getCannotDelay(lb));
2186 refset.removeAll(delaycomp.getOther(lb));
2189 genset.addAll(delaycomp.getCannotDelay(lb));
2190 genset.addAll(delaycomp.getOther(lb));
2192 genset.addAll(delaycomp.getNotReady(lb));
2193 if (state.STMARRAY&&!state.DUALVIEW) {
2194 genset.removeAll(refset);
2197 unionset=new HashSet<FlatNode>();
2198 unionset.addAll(storeset);
2199 unionset.addAll(genset);
2200 if (state.STMARRAY&&!state.DUALVIEW)
2201 unionset.addAll(refset);
2204 /* Do the actual code generation */
2205 FlatNode current_node=null;
2206 HashSet tovisit=new HashSet();
2207 HashSet visited=new HashSet();
2209 tovisit.add(first.getNext(0));
2212 while(current_node!=null||!tovisit.isEmpty()) {
2213 if (current_node==null) {
2214 current_node=(FlatNode)tovisit.iterator().next();
2215 tovisit.remove(current_node);
2216 } else if (tovisit.contains(current_node)) {
2217 tovisit.remove(current_node);
2219 visited.add(current_node);
2220 if (nodetolabel.containsKey(current_node)) {
2221 output.println("L"+nodetolabel.get(current_node)+":");
2223 if (state.INSTRUCTIONFAILURE) {
2224 if (state.THREAD||state.DSM||state.SINGLETM) {
2225 output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
2227 output.println("if ((--instructioncount)==0) injectinstructionfailure();");
2229 if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
2231 if (!state.DELAYCOMP||firstpass) {
2232 generateFlatNode(fm, lb, current_node, output);
2234 //store primitive variables in out set
2235 AtomicRecord ar=atomicmethodmap.get((FlatAtomicEnterNode)first);
2236 Set<TempDescriptor> liveout=ar.liveout;
2237 for(Iterator<TempDescriptor> tmpit=liveout.iterator();tmpit.hasNext();) {
2238 TempDescriptor tmp=tmpit.next();
2239 output.println("primitives->"+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2242 if (state.MLP && stopset!=null) {
2243 assert first.getPrev( 0 ) instanceof FlatSESEEnterNode;
2244 assert current_node instanceof FlatSESEExitNode;
2245 FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev( 0 );
2246 FlatSESEExitNode fsxn = (FlatSESEExitNode) current_node;
2247 assert fsen.getFlatExit().equals( fsxn );
2248 assert fsxn.getFlatEnter().equals( fsen );
2250 if (current_node.kind()!=FKind.FlatReturnNode) {
2251 output.println(" return;");
2254 } else if(current_node.numNext()==1) {
2257 current_node.kind()==FKind.FlatSESEEnterNode &&
2258 !((FlatSESEEnterNode)current_node).getIsCallerSESEplaceholder()
2260 FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
2261 generateFlatNode(fm, lb, current_node, output);
2262 nextnode=fsen.getFlatExit().getNext(0);
2263 } else if (state.DELAYCOMP) {
2264 boolean specialprimitive=false;
2265 //skip literals...no need to add extra overhead
2266 if (storeset!=null&&storeset.contains(current_node)&¤t_node.kind()==FKind.FlatLiteralNode) {
2267 TypeDescriptor typedesc=((FlatLiteralNode)current_node).getType();
2268 if (!typedesc.isClass()&&!typedesc.isArray()) {
2269 specialprimitive=true;
2273 if (genset==null||genset.contains(current_node)||specialprimitive)
2274 generateFlatNode(fm, lb, current_node, output);
2275 if (state.STMARRAY&&!state.DUALVIEW&&refset!=null&&refset.contains(current_node)) {
2276 //need to acquire lock
2277 handleArrayDeref(fm, lb, current_node, output, firstpass);
2279 if (storeset!=null&&storeset.contains(current_node)&&!specialprimitive) {
2280 TempDescriptor wrtmp=current_node.writesTemps()[0];
2282 //need to store value written by previous node
2283 if (wrtmp.getType().isPtr()) {
2284 //only lock the objects that may actually need locking
2285 if (recorddc.getNeedTrans(lb, current_node)&&
2286 (!state.STMARRAY||state.DUALVIEW||!wrtmp.getType().isArray()||
2287 wrtmp.getType().getSymbol().equals(TypeUtil.ObjectClass))) {
2288 output.println("STOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2290 output.println("STOREPTRNOLOCK("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2293 output.println("STORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");/* "+current_node.nodeid+" */");
2296 //need to read value read by previous node
2297 if (wrtmp.getType().isPtr()) {
2298 output.println("RESTOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2300 output.println("RESTORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+"); /* "+current_node.nodeid+" */");
2304 nextnode=current_node.getNext(0);
2307 generateFlatNode(fm, lb, current_node, output);
2308 nextnode=current_node.getNext(0);
2310 if (visited.contains(nextnode)) {
2311 output.println("goto L"+nodetolabel.get(nextnode)+";");
2314 current_node=nextnode;
2315 } else if (current_node.numNext()==2) {
2317 if (state.DELAYCOMP) {
2318 boolean computeside=false;
2320 //need to record which way it should go
2321 if (genset==null||genset.contains(current_node)) {
2322 if (storeset!=null&&storeset.contains(current_node)) {
2323 //need to store which way branch goes
2324 generateStoreFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2326 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2328 //which side to execute
2332 if (genset.contains(current_node)) {
2333 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2334 } else if (storeset.contains(current_node)) {
2336 branchanalysis.generateGroupCode(current_node, output, nodetolabel);
2338 //which side to execute
2343 Set<FlatNode> leftset=DelayComputation.getNext(current_node, 0, unionset, lb,locality, true);
2345 if (leftset.size()==0)
2347 if (visited.contains(current_node.getNext(branch))) {
2348 //already visited -- build jump
2349 output.println("goto L"+nodetolabel.get(current_node.getNext(branch))+";");
2352 current_node=current_node.getNext(branch);
2355 if (!visited.contains(current_node.getNext(1)))
2356 tovisit.add(current_node.getNext(1));
2357 if (visited.contains(current_node.getNext(0))) {
2358 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2361 current_node=current_node.getNext(0);
2365 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2366 if (!visited.contains(current_node.getNext(1)))
2367 tovisit.add(current_node.getNext(1));
2368 if (visited.contains(current_node.getNext(0))) {
2369 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2372 current_node=current_node.getNext(0);
2374 } else throw new Error();
2378 protected void handleArrayDeref(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output, boolean firstpass) {
2379 if (fn.kind()==FKind.FlatSetElementNode) {
2380 FlatSetElementNode fsen=(FlatSetElementNode) fn;
2381 String dst=generateTemp(fm, fsen.getDst(), lb);
2382 String src=generateTemp(fm, fsen.getSrc(), lb);
2383 String index=generateTemp(fm, fsen.getIndex(), lb);
2384 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
2386 if (elementtype.isArray()||elementtype.isClass())
2389 type=elementtype.getSafeSymbol()+" ";
2391 output.println("STOREARRAY("+dst+","+index+","+type+")");
2393 output.println("{");
2394 output.println(" struct ArrayObject *array;");
2395 output.println(" int index;");
2396 output.println(" RESTOREARRAY(array,index);");
2397 output.println(" (("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index]="+src+";");
2398 output.println("}");
2400 } else if (fn.kind()==FKind.FlatElementNode) {
2401 FlatElementNode fen=(FlatElementNode) fn;
2402 String src=generateTemp(fm, fen.getSrc(), lb);
2403 String index=generateTemp(fm, fen.getIndex(), lb);
2404 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
2405 String dst=generateTemp(fm, fen.getDst(), lb);
2407 if (elementtype.isArray()||elementtype.isClass())
2410 type=elementtype.getSafeSymbol()+" ";
2412 output.println("STOREARRAY("+src+","+index+","+type+")");
2414 output.println("{");
2415 output.println(" struct ArrayObject *array;");
2416 output.println(" int index;");
2417 output.println(" RESTOREARRAY(array,index);");
2418 output.println(" "+dst+"=(("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index];");
2419 output.println("}");
2423 /** Special label assignment for delaycomputation */
2424 protected Hashtable<FlatNode, Integer> dcassignLabels(FlatNode first, Set<FlatNode> lastset) {
2425 HashSet tovisit=new HashSet();
2426 HashSet visited=new HashSet();
2428 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2430 //Label targets of branches
2431 Set<FlatNode> targets=branchanalysis.getTargets();
2432 for(Iterator<FlatNode> it=targets.iterator();it.hasNext();) {
2433 nodetolabel.put(it.next(), new Integer(labelindex++));
2438 /*Assign labels first. A node needs a label if the previous
2439 * node has two exits or this node is a join point. */
2441 while(!tovisit.isEmpty()) {
2442 FlatNode fn=(FlatNode)tovisit.iterator().next();
2447 if(lastset!=null&&lastset.contains(fn)) {
2448 // if last is not null and matches, don't go
2449 // any further for assigning labels
2453 for(int i=0; i<fn.numNext(); i++) {
2454 FlatNode nn=fn.getNext(i);
2457 //1) Edge >1 of node
2458 nodetolabel.put(nn,new Integer(labelindex++));
2460 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2464 nodetolabel.put(nn,new Integer(labelindex++));
2472 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first) {
2473 return assignLabels(first, null);
2476 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
2477 HashSet tovisit=new HashSet();
2478 HashSet visited=new HashSet();
2480 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2483 /*Assign labels first. A node needs a label if the previous
2484 * node has two exits or this node is a join point. */
2486 while(!tovisit.isEmpty()) {
2487 FlatNode fn=(FlatNode)tovisit.iterator().next();
2492 if(lastset!=null&&lastset.contains(fn)) {
2493 // if last is not null and matches, don't go
2494 // any further for assigning labels
2498 for(int i=0; i<fn.numNext(); i++) {
2499 FlatNode nn=fn.getNext(i);
2502 //1) Edge >1 of node
2503 nodetolabel.put(nn,new Integer(labelindex++));
2505 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2509 nodetolabel.put(nn,new Integer(labelindex++));
2517 /** Generate text string that corresponds to the TempDescriptor td. */
2518 protected String generateTemp(FlatMethod fm, TempDescriptor td, LocalityBinding lb) {
2519 MethodDescriptor md=fm.getMethod();
2520 TaskDescriptor task=fm.getTask();
2521 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
2523 if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
2524 //System.out.println("generateTemp returns " + td.getSafeSymbol());
2525 return td.getSafeSymbol();
2528 if (objecttemps.isLocalPtr(td)) {
2529 return localsprefixderef+td.getSafeSymbol();
2532 if (objecttemps.isParamPtr(td)) {
2533 return paramsprefix+"->"+td.getSafeSymbol();
2539 protected void generateFlatNode(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output) {
2541 // insert pre-node actions from the code plan
2544 CodePlan cp = mlpa.getCodePlan( fn );
2547 FlatSESEEnterNode currentSESE = cp.getCurrentSESE();
2549 // for each sese and age pair that this parent statement
2550 // must stall on, take that child's stall semaphore, the
2551 // copying of values comes after the statement
2552 Iterator<VariableSourceToken> vstItr = cp.getStallTokens().iterator();
2553 while( vstItr.hasNext() ) {
2554 VariableSourceToken vst = vstItr.next();
2556 SESEandAgePair p = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2558 output.println(" {");
2559 output.println(" SESEcommon* common = (SESEcommon*) "+p+";");
2561 output.println(" pthread_mutex_lock( &(common->lock) );");
2562 output.println(" while( common->doneExecuting == FALSE ) {");
2563 output.println(" pthread_cond_wait( &(common->doneCond), &(common->lock) );");
2564 output.println(" }");
2565 output.println(" pthread_mutex_unlock( &(common->lock) );");
2567 //output.println(" psem_take( &(common->stallSem) );");
2569 // copy things we might have stalled for
2570 output.println(" "+p.getSESE().getSESErecordName()+"* child = ("+
2571 p.getSESE().getSESErecordName()+"*) "+p+";");
2573 Iterator<TempDescriptor> tdItr = cp.getCopySet( vst ).iterator();
2574 while( tdItr.hasNext() ) {
2575 TempDescriptor td = tdItr.next();
2576 FlatMethod fmContext;
2577 if( currentSESE.getIsCallerSESEplaceholder() ) {
2578 fmContext = currentSESE.getfmEnclosing();
2580 fmContext = currentSESE.getfmBogus();
2582 output.println(" "+generateTemp( fmContext, td, null )+
2583 " = child->"+vst.getAddrVar().getSafeSymbol()+";");
2586 output.println(" }");
2589 // for each variable with a dynamic source, stall just for that variable
2590 Iterator<TempDescriptor> dynItr = cp.getDynamicStallSet().iterator();
2591 while( dynItr.hasNext() ) {
2592 TempDescriptor dynVar = dynItr.next();
2594 // only stall if the dynamic source is not yourself, denoted by src==NULL
2595 // otherwise the dynamic write nodes will have the local var up-to-date
2596 output.println(" {");
2597 output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
2598 output.println(" SESEcommon* common = (SESEcommon*) "+dynVar+"_srcSESE;");
2599 output.println(" psem_take( &(common->stallSem) );");
2601 FlatMethod fmContext;
2602 if( currentSESE.getIsCallerSESEplaceholder() ) {
2603 fmContext = currentSESE.getfmEnclosing();
2605 fmContext = currentSESE.getfmBogus();
2607 output.println(" "+generateTemp( fmContext, dynVar, null )+
2608 " = *(("+dynVar.getType()+"*) ("+
2609 dynVar+"_srcSESE + "+dynVar+"_srcOffset));");
2611 output.println(" }");
2612 output.println(" }");
2615 // for each assignment of a variable to rhs that has a dynamic source,
2616 // copy the dynamic sources
2617 Iterator dynAssignItr = cp.getDynAssigns().entrySet().iterator();
2618 while( dynAssignItr.hasNext() ) {
2619 Map.Entry me = (Map.Entry) dynAssignItr.next();
2620 TempDescriptor lhs = (TempDescriptor) me.getKey();
2621 TempDescriptor rhs = (TempDescriptor) me.getValue();
2622 output.println(" "+lhs+"_srcSESE = "+rhs+"_srcSESE;");
2623 output.println(" "+lhs+"_srcOffset = "+rhs+"_srcOffset;");
2626 // for each lhs that is dynamic from a non-dynamic source, set the
2627 // dynamic source vars to the current SESE
2628 dynItr = cp.getDynAssignCurr().iterator();
2629 while( dynItr.hasNext() ) {
2630 TempDescriptor dynVar = dynItr.next();
2631 output.println(" "+dynVar+"_srcSESE = NULL;");
2637 case FKind.FlatAtomicEnterNode:
2638 generateFlatAtomicEnterNode(fm, lb, (FlatAtomicEnterNode) fn, output);
2641 case FKind.FlatAtomicExitNode:
2642 generateFlatAtomicExitNode(fm, lb, (FlatAtomicExitNode) fn, output);
2645 case FKind.FlatInstanceOfNode:
2646 generateFlatInstanceOfNode(fm, lb, (FlatInstanceOfNode)fn, output);
2649 case FKind.FlatSESEEnterNode:
2650 generateFlatSESEEnterNode(fm, lb, (FlatSESEEnterNode)fn, output);
2653 case FKind.FlatSESEExitNode:
2654 generateFlatSESEExitNode(fm, lb, (FlatSESEExitNode)fn, output);
2657 case FKind.FlatWriteDynamicVarNode:
2658 generateFlatWriteDynamicVarNode(fm, lb, (FlatWriteDynamicVarNode)fn, output);
2661 case FKind.FlatGlobalConvNode:
2662 generateFlatGlobalConvNode(fm, lb, (FlatGlobalConvNode) fn, output);
2665 case FKind.FlatTagDeclaration:
2666 generateFlatTagDeclaration(fm, lb, (FlatTagDeclaration) fn,output);
2669 case FKind.FlatCall:
2670 generateFlatCall(fm, lb, (FlatCall) fn,output);
2673 case FKind.FlatFieldNode:
2674 generateFlatFieldNode(fm, lb, (FlatFieldNode) fn,output);
2677 case FKind.FlatElementNode:
2678 generateFlatElementNode(fm, lb, (FlatElementNode) fn,output);
2681 case FKind.FlatSetElementNode:
2682 generateFlatSetElementNode(fm, lb, (FlatSetElementNode) fn,output);
2685 case FKind.FlatSetFieldNode:
2686 generateFlatSetFieldNode(fm, lb, (FlatSetFieldNode) fn,output);
2690 generateFlatNew(fm, lb, (FlatNew) fn,output);
2693 case FKind.FlatOpNode:
2694 generateFlatOpNode(fm, lb, (FlatOpNode) fn,output);
2697 case FKind.FlatCastNode:
2698 generateFlatCastNode(fm, lb, (FlatCastNode) fn,output);
2701 case FKind.FlatLiteralNode:
2702 generateFlatLiteralNode(fm, lb, (FlatLiteralNode) fn,output);
2705 case FKind.FlatReturnNode:
2706 generateFlatReturnNode(fm, lb, (FlatReturnNode) fn,output);
2710 output.println("/* nop */");
2713 case FKind.FlatExit:
2714 output.println("/* exit */");
2717 case FKind.FlatBackEdge:
2718 if (state.SINGLETM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
2719 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
2721 if (((state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
2722 || (this.state.MULTICOREGC)) {
2723 if(state.DSM&&locality.getAtomic(lb).get(fn).intValue()>0) {
2724 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
2725 } else if(this.state.MULTICOREGC) {
2726 output.println("if (gcflag) gc("+localsprefixaddr+");");
2728 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2731 output.println("/* nop */");
2734 case FKind.FlatCheckNode:
2735 generateFlatCheckNode(fm, lb, (FlatCheckNode) fn, output);
2738 case FKind.FlatFlagActionNode:
2739 generateFlatFlagActionNode(fm, lb, (FlatFlagActionNode) fn, output);
2742 case FKind.FlatPrefetchNode:
2743 generateFlatPrefetchNode(fm,lb, (FlatPrefetchNode) fn, output);
2746 case FKind.FlatOffsetNode:
2747 generateFlatOffsetNode(fm, lb, (FlatOffsetNode)fn, output);
2754 // insert post-node actions from the code-plan
2756 CodePlan cp = mlpa.getCodePlan( fn );
2763 public void generateFlatOffsetNode(FlatMethod fm, LocalityBinding lb, FlatOffsetNode fofn, PrintWriter output) {
2764 output.println("/* FlatOffsetNode */");
2765 FieldDescriptor fd=fofn.getField();
2766 output.println(generateTemp(fm, fofn.getDst(),lb)+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+ fd.getSafeSymbol()+");");
2767 output.println("/* offset */");
2770 public void generateFlatPrefetchNode(FlatMethod fm, LocalityBinding lb, FlatPrefetchNode fpn, PrintWriter output) {
2771 if (state.PREFETCH) {
2772 Vector oids = new Vector();
2773 Vector fieldoffset = new Vector();
2774 Vector endoffset = new Vector();
2775 int tuplecount = 0; //Keeps track of number of prefetch tuples that need to be generated
2776 for(Iterator it = fpn.hspp.iterator(); it.hasNext();) {
2777 PrefetchPair pp = (PrefetchPair) it.next();
2778 Integer statusbase = locality.getNodePreTempInfo(lb,fpn).get(pp.base);
2779 /* Find prefetches that can generate oid */
2780 if(statusbase == LocalityAnalysis.GLOBAL) {
2781 generateTransCode(fm, lb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(lb).get(fpn).intValue()>0, false);
2783 } else if (statusbase == LocalityAnalysis.LOCAL) {
2784 generateTransCode(fm,lb,pp,oids,fieldoffset,endoffset,tuplecount,false,true);
2791 System.out.println("Adding prefetch "+fpn+ " to method:" +fm);
2792 output.println("{");
2793 output.println("/* prefetch */");
2794 output.println("/* prefetchid_" + fpn.siteid + " */");
2795 output.println("void * prefptr;");
2796 output.println("int tmpindex;");
2798 output.println("if((evalPrefetch["+fpn.siteid+"].operMode) || (evalPrefetch["+fpn.siteid+"].retrycount <= 0)) {");
2799 /*Create C code for oid array */
2800 output.print(" unsigned int oidarray_[] = {");
2801 boolean needcomma=false;
2802 for (Iterator it = oids.iterator(); it.hasNext();) {
2805 output.print(it.next());
2808 output.println("};");
2810 /*Create C code for endoffset values */
2811 output.print(" unsigned short endoffsetarry_[] = {");
2813 for (Iterator it = endoffset.iterator(); it.hasNext();) {
2816 output.print(it.next());
2819 output.println("};");
2821 /*Create C code for Field Offset Values */
2822 output.print(" short fieldarry_[] = {");
2824 for (Iterator it = fieldoffset.iterator(); it.hasNext();) {
2827 output.print(it.next());
2830 output.println("};");
2831 /* make the prefetch call to Runtime */
2832 output.println(" if(!evalPrefetch["+fpn.siteid+"].operMode) {");
2833 output.println(" evalPrefetch["+fpn.siteid+"].retrycount = RETRYINTERVAL;");
2834 output.println(" }");
2835 output.println(" prefetch("+fpn.siteid+" ,"+tuplecount+", oidarray_, endoffsetarry_, fieldarry_);");
2836 output.println(" } else {");
2837 output.println(" evalPrefetch["+fpn.siteid+"].retrycount--;");
2838 output.println(" }");
2839 output.println("}");
2843 public void generateTransCode(FlatMethod fm, LocalityBinding lb,PrefetchPair pp, Vector oids, Vector fieldoffset, Vector endoffset, int tuplecount, boolean inside, boolean localbase) {
2844 short offsetcount = 0;
2848 } else if (localbase) {
2849 for(; breakindex<pp.desc.size(); breakindex++) {
2850 Descriptor desc=pp.getDescAt(breakindex);
2851 if (desc instanceof FieldDescriptor) {
2852 FieldDescriptor fd=(FieldDescriptor)desc;
2853 if (fd.isGlobal()) {
2861 if (breakindex>pp.desc.size()) //all local
2864 TypeDescriptor lasttype=pp.base.getType();
2865 String basestr=generateTemp(fm, pp.base, lb);
2867 boolean maybenull=fm.getMethod().isStatic()||
2868 !pp.base.equals(fm.getParameter(0));
2870 for(int i=0; i<breakindex; i++) {
2871 String indexcheck="";
2873 Descriptor desc=pp.getDescAt(i);
2874 if (desc instanceof FieldDescriptor) {
2875 FieldDescriptor fd=(FieldDescriptor)desc;
2877 if (!teststr.equals(""))
2879 teststr+="((prefptr="+basestr+")!=NULL)";
2880 basestr="((struct "+lasttype.getSafeSymbol()+" *)prefptr)->"+fd.getSafeSymbol();
2882 basestr=basestr+"->"+fd.getSafeSymbol();
2885 lasttype=fd.getType();
2887 IndexDescriptor id=(IndexDescriptor)desc;
2888 indexcheck="((tmpindex=";
2889 for(int j=0; j<id.tddesc.size(); j++) {
2890 indexcheck+=generateTemp(fm, id.getTempDescAt(j), lb)+"+";
2892 indexcheck+=id.offset+")>=0)&(tmpindex<((struct ArrayObject *)prefptr)->___length___)";
2894 if (!teststr.equals(""))
2896 teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck;
2897 basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]";
2899 lasttype=lasttype.dereference();
2904 if (teststr.equals("")) {
2905 oid="((unsigned int)"+basestr+")";
2907 oid="((unsigned int)(("+teststr+")?"+basestr+":NULL))";
2911 for(int i = breakindex; i < pp.desc.size(); i++) {
2912 String newfieldoffset;
2913 Object desc = pp.getDescAt(i);
2914 if(desc instanceof FieldDescriptor) {
2915 FieldDescriptor fd=(FieldDescriptor)desc;
2916 newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))");
2917 lasttype=fd.getType();
2919 newfieldoffset = "";
2920 IndexDescriptor id=(IndexDescriptor)desc;
2921 for(int j = 0; j < id.tddesc.size(); j++) {
2922 newfieldoffset += generateTemp(fm, id.getTempDescAt(j), lb) + "+";
2924 newfieldoffset += id.offset.toString();
2925 lasttype=lasttype.dereference();
2927 fieldoffset.add(newfieldoffset);
2930 int base=(tuplecount>0) ? ((Short)endoffset.get(tuplecount-1)).intValue() : 0;
2931 base+=pp.desc.size()-breakindex;
2932 endoffset.add(new Short((short)base));
2937 public void generateFlatGlobalConvNode(FlatMethod fm, LocalityBinding lb, FlatGlobalConvNode fgcn, PrintWriter output) {
2938 if (lb!=fgcn.getLocality())
2940 /* Have to generate flat globalconv */
2941 if (fgcn.getMakePtr()) {
2943 //DEBUG: output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+",\" "+fm+":"+fgcn+"\");");
2944 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+");");
2946 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fgcn)||state.READSET&&dc.getNeedWriteTrans(lb, fgcn)) {
2947 //need to do translation
2948 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+", (void *)("+localsprefixaddr+"));");
2949 } else if (state.READSET&&dc.getNeedTrans(lb, fgcn)) {
2950 if (state.HYBRID&&delaycomp.getConv(lb).contains(fgcn)) {
2951 output.println("TRANSREADRDFISSION("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
2953 output.println("TRANSREADRD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
2957 /* Need to convert to OID */
2958 if ((dc==null)||dc.getNeedSrcTrans(lb,fgcn)) {
2959 if (fgcn.doConvert()||(delaycomp!=null&&delaycomp.needsFission(lb, fgcn.getAtomicEnter())&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) {
2960 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc(),lb)+");");
2962 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=NULL;");
2968 public void generateFlatInstanceOfNode(FlatMethod fm, LocalityBinding lb, FlatInstanceOfNode fion, PrintWriter output) {
2970 if (fion.getType().isArray()) {
2971 type=state.getArrayNumber(fion.getType())+state.numClasses();
2973 type=fion.getType().getClassDesc().getId();
2976 if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
2977 output.println(generateTemp(fm, fion.getDst(), lb)+"=1;");
2979 output.println(generateTemp(fm, fion.getDst(), lb)+"=instanceof("+generateTemp(fm,fion.getSrc(),lb)+","+type+");");
2982 int sandboxcounter=0;
2983 public void generateFlatAtomicEnterNode(FlatMethod fm, LocalityBinding lb, FlatAtomicEnterNode faen, PrintWriter output) {
2984 /* Check to see if we need to generate code for this atomic */
2985 if (locality==null) {
2986 if (GENERATEPRECISEGC) {
2987 output.println("if (pthread_mutex_trylock(&atomiclock)!=0) {");
2988 output.println("stopforgc((struct garbagelist *) &___locals___);");
2989 output.println("pthread_mutex_lock(&atomiclock);");
2990 output.println("restartaftergc();");
2991 output.println("}");
2993 output.println("pthread_mutex_lock(&atomiclock);");
2998 if (locality.getAtomic(lb).get(faen.getPrev(0)).intValue()>0)
3002 if (state.SANDBOX) {
3003 outsandbox.println("int atomiccounter"+sandboxcounter+"=LOW_CHECK_FREQUENCY;");
3004 output.println("counter_reset_pointer=&atomiccounter"+sandboxcounter+";");
3007 if (state.DELAYCOMP&&delaycomp.needsFission(lb, faen)) {
3008 AtomicRecord ar=atomicmethodmap.get(faen);
3010 for(Iterator<TempDescriptor> tmpit=ar.livein.iterator();tmpit.hasNext();) {
3011 TempDescriptor tmp=tmpit.next();
3012 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3015 //copy outs that depend on path
3016 for(Iterator<TempDescriptor> tmpit=ar.liveoutvirtualread.iterator();tmpit.hasNext();) {
3017 TempDescriptor tmp=tmpit.next();
3018 if (!ar.livein.contains(tmp))
3019 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3023 /* Backup the temps. */
3024 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3025 TempDescriptor tmp=tmpit.next();
3026 output.println(generateTemp(fm, backuptable.get(lb).get(tmp),lb)+"="+generateTemp(fm,tmp,lb)+";");
3029 output.println("goto transstart"+faen.getIdentifier()+";");
3031 /******* Print code to retry aborted transaction *******/
3032 output.println("transretry"+faen.getIdentifier()+":");
3035 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3036 TempDescriptor tmp=tmpit.next();
3037 output.println(generateTemp(fm, tmp,lb)+"="+generateTemp(fm,backuptable.get(lb).get(tmp),lb)+";");
3041 /********* Need to revert local object store ********/
3042 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3044 output.println("while ("+revertptr+") {");
3045 output.println("struct ___Object___ * tmpptr;");
3046 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3047 output.println("REVERT_OBJ("+revertptr+");");
3048 output.println(revertptr+"=tmpptr;");
3049 output.println("}");
3051 /******* Tell the runtime to start the transaction *******/
3053 output.println("transstart"+faen.getIdentifier()+":");
3054 if (state.SANDBOX) {
3055 output.println("transaction_check_counter=*counter_reset_pointer;");
3058 //output.println("transStart();");
3060 if (state.ABORTREADERS||state.SANDBOX) {
3062 output.println("abortenabled=1;");
3063 output.println("if (_setjmp(aborttrans)) {");
3064 output.println(" goto transretry"+faen.getIdentifier()+"; }");
3068 public void generateFlatAtomicExitNode(FlatMethod fm, LocalityBinding lb, FlatAtomicExitNode faen, PrintWriter output) {
3069 /* Check to see if we need to generate code for this atomic */
3070 if (locality==null) {
3071 output.println("pthread_mutex_unlock(&atomiclock);");
3074 if (locality.getAtomic(lb).get(faen).intValue()>0)
3076 //store the revert list before we lose the transaction object
3079 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3080 output.println(revertptr+"=revertlist;");
3081 output.println("if (transCommit()) {");
3082 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3083 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3084 output.println("} else {");
3085 /* Need to commit local object store */
3086 output.println("while ("+revertptr+") {");
3087 output.println("struct ___Object___ * tmpptr;");
3088 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3089 output.println("COMMIT_OBJ("+revertptr+");");
3090 output.println(revertptr+"=tmpptr;");
3091 output.println("}");
3092 output.println("}");
3096 if (!state.DELAYCOMP) {
3098 output.println("if (transCommit()) {");
3099 /* Transaction aborts if it returns true */
3100 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3101 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3102 output.println("}");
3104 if (delaycomp.optimizeTrans(lb, faen.getAtomicEnter())&&(!state.STMARRAY||state.DUALVIEW)) {
3105 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3106 output.println("LIGHTWEIGHTCOMMIT("+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+", transretry"+faen.getAtomicEnter().getIdentifier()+");");
3108 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3109 TempDescriptor tmp=tmpit.next();
3110 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3112 } else if (delaycomp.needsFission(lb, faen.getAtomicEnter())) {
3113 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3115 output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {");
3116 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3117 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3118 output.println("}");
3120 output.println("else {");
3121 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3122 TempDescriptor tmp=tmpit.next();
3123 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3125 output.println("}");
3127 output.println("if (transCommit(NULL, NULL, NULL, NULL)) {");
3128 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3129 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3130 output.println("}");
3135 public void generateFlatSESEEnterNode( FlatMethod fm,
3137 FlatSESEEnterNode fsen,
3141 // if MLP flag is off, okay that SESE nodes are in IR graph,
3142 // just skip over them and code generates exactly the same
3147 // there may be an SESE in an unreachable method, skip over
3148 if( !mlpa.getAllSESEs().contains( fsen ) ) {
3152 // also, if we have encountered a placeholder, just skip it
3153 if( fsen.getIsCallerSESEplaceholder() ) {
3157 output.println(" {");
3159 // set up the parent
3160 if( fsen == mlpa.getMainSESE() ) {
3161 output.println(" SESEcommon* parentCommon = NULL;");
3163 if( fsen.getParent() == null ) {
3164 System.out.println( "in "+fm+", "+fsen+" has null parent" );
3166 assert fsen.getParent() != null;
3167 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3168 output.println(" SESEcommon* parentCommon = &("+paramsprefix+"->common);");
3170 //output.println(" SESEcommon* parentCommon = (SESEcommon*) peekItem( seseCallStack );");
3171 output.println(" SESEcommon* parentCommon = seseCaller;");
3175 // before doing anything, lock your own record and increment the running children
3176 if( fsen != mlpa.getMainSESE() ) {
3177 output.println(" pthread_mutex_lock( &(parentCommon->lock) );");
3178 output.println(" ++(parentCommon->numRunningChildren);");
3179 output.println(" pthread_mutex_unlock( &(parentCommon->lock) );");
3182 // just allocate the space for this record
3183 output.println(" "+fsen.getSESErecordName()+"* seseToIssue = ("+
3184 fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
3185 fsen.getSESErecordName()+" ) );");
3187 // and keep the thread-local sese stack up to date
3188 //output.println(" addNewItem( seseCallStack, (void*) seseToIssue);");
3190 // fill in common data
3191 output.println(" seseToIssue->common.classID = "+fsen.getIdentifier()+";");
3192 output.println(" psem_init( &(seseToIssue->common.stallSem) );");
3194 output.println(" seseToIssue->common.forwardList = createQueue();");
3195 output.println(" seseToIssue->common.unresolvedDependencies = 0;");
3196 output.println(" pthread_cond_init( &(seseToIssue->common.doneCond), NULL );");
3197 output.println(" seseToIssue->common.doneExecuting = FALSE;");
3198 output.println(" pthread_cond_init( &(seseToIssue->common.runningChildrenCond), NULL );");
3199 output.println(" seseToIssue->common.numRunningChildren = 0;");
3200 output.println(" seseToIssue->common.parent = parentCommon;");
3202 // all READY in-vars should be copied now and be done with it
3203 Iterator<TempDescriptor> tempItr = fsen.getReadyInVarSet().iterator();
3204 while( tempItr.hasNext() ) {
3205 TempDescriptor temp = tempItr.next();
3207 // when we are issuing the main SESE or an SESE with placeholder
3208 // caller SESE as parent, generate temp child child's eclosing method,
3209 // otherwise use the parent's enclosing method as the context
3210 boolean useParentContext = false;
3212 if( fsen != mlpa.getMainSESE() ) {
3213 assert fsen.getParent() != null;
3214 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3215 useParentContext = true;
3219 if( useParentContext ) {
3220 output.println(" seseToIssue->"+temp+" = "+
3221 generateTemp( fsen.getParent().getfmBogus(), temp, null )+";");
3223 output.println(" seseToIssue->"+temp+" = "+
3224 generateTemp( fsen.getfmEnclosing(), temp, null )+";");
3228 // before potentially adding this SESE to other forwarding lists,
3229 // create it's lock and take it immediately
3230 output.println(" pthread_mutex_init( &(seseToIssue->common.lock), NULL );");
3231 output.println(" pthread_mutex_lock( &(seseToIssue->common.lock) );");
3233 if( fsen != mlpa.getMainSESE() ) {
3234 // count up outstanding dependencies, static first, then dynamic
3235 Iterator<SESEandAgePair> staticSrcsItr = fsen.getStaticInVarSrcs().iterator();
3236 while( staticSrcsItr.hasNext() ) {
3237 SESEandAgePair srcPair = staticSrcsItr.next();
3238 output.println(" {");
3239 output.println(" SESEcommon* src = (SESEcommon*)"+srcPair+";");
3240 output.println(" pthread_mutex_lock( &(src->lock) );");
3241 output.println(" if( !isEmpty( src->forwardList ) &&");
3242 output.println(" seseToIssue == peekItem( src->forwardList ) ) {");
3243 output.println(" printf( \"This shouldnt already be here\\n\");");
3244 output.println(" exit( -1 );");
3245 output.println(" }");
3246 output.println(" if( !src->doneExecuting ) {");
3247 output.println(" addNewItem( src->forwardList, seseToIssue );");
3248 output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3249 output.println(" }");
3250 output.println(" pthread_mutex_unlock( &(src->lock) );");
3251 output.println(" }");
3253 // whether or not it is an outstanding dependency, make sure
3254 // to pass the static name to the child's record
3255 output.println(" seseToIssue->"+srcPair+" = "+srcPair+";");
3258 // dynamic sources might already be accounted for in the static list,
3259 // so only add them to forwarding lists if they're not already there
3260 Iterator<TempDescriptor> dynVarsItr = fsen.getDynamicInVarSet().iterator();
3261 while( dynVarsItr.hasNext() ) {
3262 TempDescriptor dynInVar = dynVarsItr.next();
3263 output.println(" {");
3264 output.println(" SESEcommon* src = (SESEcommon*)"+dynInVar+"_srcSESE;");
3266 // the dynamic source is NULL if it comes from your own space--you can't pass
3267 // the address off to the new child, because you're not done executing and
3268 // might change the variable, so copy it right now
3269 output.println(" if( src != NULL ) {");
3270 output.println(" pthread_mutex_lock( &(src->lock) );");
3271 output.println(" if( isEmpty( src->forwardList ) ||");
3272 output.println(" seseToIssue != peekItem( src->forwardList ) ) {");
3273 output.println(" if( !src->doneExecuting ) {");
3274 output.println(" addNewItem( src->forwardList, seseToIssue );");
3275 output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3276 output.println(" }");
3277 output.println(" }");
3278 output.println(" pthread_mutex_unlock( &(src->lock) );");
3279 output.println(" seseToIssue->"+dynInVar+"_srcOffset = "+dynInVar+"_srcOffset;");
3280 output.println(" } else {");
3282 boolean useParentContext = false;
3283 if( fsen != mlpa.getMainSESE() ) {
3284 assert fsen.getParent() != null;
3285 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3286 useParentContext = true;
3289 if( useParentContext ) {
3290 output.println(" seseToIssue->"+dynInVar+" = "+
3291 generateTemp( fsen.getParent().getfmBogus(), dynInVar, null )+";");
3293 output.println(" seseToIssue->"+dynInVar+" = "+
3294 generateTemp( fsen.getfmEnclosing(), dynInVar, null )+";");
3297 output.println(" }");
3298 output.println(" }");
3300 // even if the value is already copied, make sure your NULL source
3301 // gets passed so child knows it already has the dynamic value
3302 output.println(" seseToIssue->"+dynInVar+"_srcSESE = "+dynInVar+"_srcSESE;");
3305 // maintain pointers for for finding dynamic SESE
3306 // instances from static names
3307 SESEandAgePair p = new SESEandAgePair( fsen, 0 );
3308 if( fsen.getParent() != null &&
3309 //!fsen.getParent().getIsCallerSESEplaceholder() &&
3310 fsen.getParent().getNeededStaticNames().contains( p )
3313 for( int i = fsen.getOldestAgeToTrack(); i > 0; --i ) {
3314 SESEandAgePair p1 = new SESEandAgePair( fsen, i );
3315 SESEandAgePair p2 = new SESEandAgePair( fsen, i-1 );
3316 output.println(" "+p1+" = "+p2+";");
3318 output.println(" "+p+" = seseToIssue;");
3322 // if there were no outstanding dependencies, issue here
3323 output.println(" if( seseToIssue->common.unresolvedDependencies == 0 ) {");
3324 output.println(" workScheduleSubmit( (void*)seseToIssue );");
3325 output.println(" }");
3327 // release this SESE for siblings to update its dependencies or,
3328 // eventually, for it to mark itself finished
3329 output.println(" pthread_mutex_unlock( &(seseToIssue->common.lock) );");
3330 output.println(" }");
3334 public void generateFlatSESEExitNode( FlatMethod fm,
3336 FlatSESEExitNode fsexn,
3340 // if MLP flag is off, okay that SESE nodes are in IR graph,
3341 // just skip over them and code generates exactly the same
3346 // get the enter node for this exit that has meta data embedded
3347 FlatSESEEnterNode fsen = fsexn.getFlatEnter();
3349 // there may be an SESE in an unreachable method, skip over
3350 if( !mlpa.getAllSESEs().contains( fsen ) ) {
3354 // also, if we have encountered a placeholder, just jump it
3355 if( fsen.getIsCallerSESEplaceholder() ) {
3359 output.println(" /* SESE exiting */");
3361 String com = paramsprefix+"->common";
3363 // this SESE cannot be done until all of its children are done
3364 // so grab your own lock with the condition variable for watching
3365 // that the number of your running children is greater than zero
3366 output.println(" pthread_mutex_lock( &("+com+".lock) );");
3367 output.println(" while( "+com+".numRunningChildren > 0 ) {");
3368 output.println(" pthread_cond_wait( &("+com+".runningChildrenCond), &("+com+".lock) );");
3369 output.println(" }");
3371 // copy out-set from local temps into the sese record
3372 Iterator<TempDescriptor> itr = fsen.getOutVarSet().iterator();
3373 while( itr.hasNext() ) {
3374 TempDescriptor temp = itr.next();
3376 // only have to do this for primitives
3377 if( !temp.getType().isPrimitive() ) {
3381 // have to determine the context enclosing this sese
3382 boolean useParentContext = false;
3384 if( fsen != mlpa.getMainSESE() ) {
3385 assert fsen.getParent() != null;
3386 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3387 useParentContext = true;
3392 if( useParentContext ) {
3393 from = generateTemp( fsen.getParent().getfmBogus(), temp, null );
3395 from = generateTemp( fsen.getfmEnclosing(), temp, null );
3398 output.println(" "+paramsprefix+
3399 "->"+temp.getSafeSymbol()+
3403 // mark yourself done, your SESE data is now read-only
3404 output.println(" "+com+".doneExecuting = TRUE;");
3405 output.println(" pthread_cond_signal( &("+com+".doneCond) );");
3406 output.println(" pthread_mutex_unlock( &("+com+".lock) );");
3408 // decrement dependency count for all SESE's on your forwarding list
3409 output.println(" while( !isEmpty( "+com+".forwardList ) ) {");
3410 output.println(" SESEcommon* consumer = (SESEcommon*) getItem( "+com+".forwardList );");
3411 output.println(" pthread_mutex_lock( &(consumer->lock) );");
3412 output.println(" --(consumer->unresolvedDependencies);");
3413 output.println(" if( consumer->unresolvedDependencies == 0 ) {");
3414 output.println(" workScheduleSubmit( (void*)consumer );");
3415 output.println(" }");
3416 output.println(" pthread_mutex_unlock( &(consumer->lock) );");
3417 output.println(" }");
3419 // if parent is stalling on you, let them know you're done
3420 if( fsexn.getFlatEnter() != mlpa.getMainSESE() ) {
3421 output.println(" psem_give( &("+paramsprefix+"->common.stallSem) );");
3424 // last of all, decrement your parent's number of running children
3425 output.println(" if( "+paramsprefix+"->common.parent != NULL ) {");
3426 output.println(" pthread_mutex_lock( &("+paramsprefix+"->common.parent->lock) );");
3427 output.println(" --("+paramsprefix+"->common.parent->numRunningChildren);");
3428 output.println(" pthread_cond_signal( &("+paramsprefix+"->common.parent->runningChildrenCond) );");
3429 output.println(" pthread_mutex_unlock( &("+paramsprefix+"->common.parent->lock) );");
3430 output.println(" }");
3432 // this is a thread-only variable that can be handled when critical sese-to-sese
3433 // data has been taken care of--set sese pointer to remember self over method
3434 // calls to a non-zero, invalid address
3435 output.println(" seseCaller = (SESEcommon*) 0x1;");
3438 public void generateFlatWriteDynamicVarNode( FlatMethod fm,
3440 FlatWriteDynamicVarNode fwdvn,
3444 // should node should not be in an IR graph if the
3445 // MLP flag is not set
3446 throw new Error("Unexpected presence of FlatWriteDynamicVarNode");
3449 Hashtable<TempDescriptor, VariableSourceToken> writeDynamic =
3452 assert writeDynamic != null;
3454 Iterator wdItr = writeDynamic.entrySet().iterator();
3455 while( wdItr.hasNext() ) {
3456 Map.Entry me = (Map.Entry) wdItr.next();
3457 TempDescriptor refVar = (TempDescriptor) me.getKey();
3458 VariableSourceToken vst = (VariableSourceToken) me.getValue();
3460 FlatSESEEnterNode current = fwdvn.getEnclosingSESE();
3462 // only do this if the variable in question should be tracked,
3463 // meaning that it was explicitly added to the dynamic var set
3464 if( !current.getDynamicVarSet().contains( vst.getAddrVar() ) ) {
3468 SESEandAgePair instance = new SESEandAgePair( vst.getSESE(), vst.getAge() );
3470 output.println(" {");
3472 if( current.equals( vst.getSESE() ) ) {
3473 // if the src comes from this SESE, it's a method local variable,
3474 // mark src pointer NULL to signify that the var is up-to-date
3475 output.println(" "+vst.getAddrVar()+"_srcSESE = NULL;");
3478 // otherwise we track where it will come from
3479 output.println(" "+vst.getAddrVar()+"_srcSESE = "+instance+";");
3480 output.println(" "+vst.getAddrVar()+"_srcOffset = (int) &((("+
3481 vst.getSESE().getSESErecordName()+"*)0)->"+vst.getAddrVar()+");");
3484 output.println(" }");
3489 private void generateFlatCheckNode(FlatMethod fm, LocalityBinding lb, FlatCheckNode fcn, PrintWriter output) {
3490 if (state.CONSCHECK) {
3491 String specname=fcn.getSpec();
3492 String varname="repairstate___";
3493 output.println("{");
3494 output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
3496 TempDescriptor[] temps=fcn.getTemps();
3497 String[] vars=fcn.getVars();
3498 for(int i=0; i<temps.length; i++) {
3499 output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i],lb)+";");
3502 output.println("if (doanalysis"+specname+"("+varname+")) {");
3503 output.println("free"+specname+"_state("+varname+");");
3504 output.println("} else {");
3505 output.println("/* Bad invariant */");
3506 output.println("free"+specname+"_state("+varname+");");
3507 output.println("abort_task();");
3508 output.println("}");
3509 output.println("}");
3513 private void generateFlatCall(FlatMethod fm, LocalityBinding lb, FlatCall fc, PrintWriter output) {
3515 if( state.MLP && !nonSESEpass ) {
3516 output.println(" seseCaller = (SESEcommon*)"+paramsprefix+";");
3519 MethodDescriptor md=fc.getMethod();
3520 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? locality.getBinding(lb, fc) : md);
3521 ClassDescriptor cn=md.getClassDesc();
3522 output.println("{");
3523 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3525 LocalityBinding fclb=locality.getBinding(lb, fc);
3526 output.print(" struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
3528 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
3530 output.print(objectparams.numPointers());
3531 output.print(", "+localsprefixaddr);
3532 if (md.getThis()!=null) {
3534 output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis(),lb));
3536 if (fc.getThis()!=null&&md.getThis()==null) {
3537 System.out.println("WARNING!!!!!!!!!!!!");
3538 System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
3542 for(int i=0; i<fc.numArgs(); i++) {
3543 Descriptor var=md.getParameter(i);
3544 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
3545 if (objectparams.isParamPtr(paramtemp)) {
3546 TempDescriptor targ=fc.getArg(i);
3548 TypeDescriptor td=md.getParamType(i);
3550 output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
3552 output.print("(struct "+md.getParamType(i).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
3555 output.println("};");
3560 if (fc.getReturnTemp()!=null)
3561 output.print(generateTemp(fm,fc.getReturnTemp(),lb)+"=");
3563 /* Do we need to do virtual dispatch? */
3564 if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
3567 LocalityBinding fclb=locality.getBinding(lb, fc);
3568 output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
3570 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
3575 if (md.getReturnType().isClass()||md.getReturnType().isArray())
3576 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
3578 output.print(md.getReturnType().getSafeSymbol()+" ");
3579 output.print("(*)(");
3581 boolean printcomma=false;
3582 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3584 LocalityBinding fclb=locality.getBinding(lb, fc);
3585 output.print("struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
3587 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
3591 for(int i=0; i<objectparams.numPrimitives(); i++) {
3592 TempDescriptor temp=objectparams.getPrimitive(i);
3596 if (temp.getType().isClass()||temp.getType().isArray())
3597 output.print("struct " + temp.getType().getSafeSymbol()+" * ");
3599 output.print(temp.getType().getSafeSymbol());
3604 LocalityBinding fclb=locality.getBinding(lb, fc);
3605 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])");
3607 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
3611 boolean needcomma=false;
3612 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3613 output.print("&__parameterlist__");
3617 if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
3618 if (fc.getThis()!=null) {
3619 TypeDescriptor ptd=md.getThis().getType();
3622 if (ptd.isClass()&&!ptd.isArray())
3623 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
3624 output.print(generateTemp(fm,fc.getThis(),lb));
3629 for(int i=0; i<fc.numArgs(); i++) {
3630 Descriptor var=md.getParameter(i);
3631 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
3632 if (objectparams.isParamPrim(paramtemp)) {
3633 TempDescriptor targ=fc.getArg(i);
3637 TypeDescriptor ptd=md.getParamType(i);
3638 if (ptd.isClass()&&!ptd.isArray())
3639 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
3640 output.print(generateTemp(fm, targ,lb));
3644 output.println(");");
3645 output.println(" }");
3648 private boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
3649 Set subclasses=typeutil.getSubClasses(thiscd);
3650 if (subclasses==null)
3652 for(Iterator classit=subclasses.iterator(); classit.hasNext();) {
3653 ClassDescriptor cd=(ClassDescriptor)classit.next();
3654 Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol());
3655 for(Iterator matchit=possiblematches.iterator(); matchit.hasNext();) {
3656 MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
3657 if (md.matches(matchmd))
3664 private void generateFlatFieldNode(FlatMethod fm, LocalityBinding lb, FlatFieldNode ffn, PrintWriter output) {
3665 if (state.SINGLETM) {
3666 //single machine transactional memory case
3667 String field=ffn.getField().getSafeSymbol();
3668 String src=generateTemp(fm, ffn.getSrc(),lb);
3669 String dst=generateTemp(fm, ffn.getDst(),lb);
3671 output.println(dst+"="+ src +"->"+field+ ";");
3672 if (ffn.getField().getType().isPtr()&&locality.getAtomic(lb).get(ffn).intValue()>0&&
3673 locality.getNodePreTempInfo(lb, ffn).get(ffn.getSrc())!=LocalityAnalysis.SCRATCH) {
3674 if ((dc==null)||(!state.READSET&&dc.getNeedTrans(lb, ffn))||
3675 (state.READSET&&dc.getNeedWriteTrans(lb, ffn))) {
3676 output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));");
3677 } else if (state.READSET&&dc.getNeedTrans(lb, ffn)) {
3678 if (state.HYBRID&&delaycomp.getConv(lb).contains(ffn)) {
3679 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
3681 output.println("TRANSREADRD("+dst+", "+dst+");");
3684 } else if (state.DSM) {
3685 Integer status=locality.getNodePreTempInfo(lb,ffn).get(ffn.getSrc());
3686 if (status==LocalityAnalysis.GLOBAL) {
3687 String field=ffn.getField().getSafeSymbol();
3688 String src=generateTemp(fm, ffn.getSrc(),lb);
3689 String dst=generateTemp(fm, ffn.getDst(),lb);
3691 if (ffn.getField().getType().isPtr()) {
3693 //TODO: Uncomment this when we have runtime support
3694 //if (ffn.getSrc()==ffn.getDst()) {
3695 //output.println("{");
3696 //output.println("void * temp="+src+";");
3697 //output.println("if (temp&0x1) {");
3698 //output.println("temp=(void *) transRead(trans, (unsigned int) temp);");
3699 //output.println(src+"->"+field+"="+temp+";");
3700 //output.println("}");
3701 //output.println(dst+"=temp;");
3702 //output.println("}");
3704 output.println(dst+"="+ src +"->"+field+ ";");
3705 //output.println("if ("+dst+"&0x1) {");
3706 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
3707 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
3708 //output.println(src+"->"+field+"="+src+"->"+field+";");
3709 //output.println("}");
3712 output.println(dst+"="+ src+"->"+field+";");
3714 } else if (status==LocalityAnalysis.LOCAL) {
3715 if (ffn.getField().getType().isPtr()&&
3716 ffn.getField().isGlobal()) {
3717 String field=ffn.getField().getSafeSymbol();
3718 String src=generateTemp(fm, ffn.getSrc(),lb);
3719 String dst=generateTemp(fm, ffn.getDst(),lb);
3720 output.println(dst+"="+ src +"->"+field+ ";");
3721 if (locality.getAtomic(lb).get(ffn).intValue()>0)
3722 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
3723 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
3725 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
3726 } else if (status==LocalityAnalysis.EITHER) {
3727 //Code is reading from a null pointer
3728 output.println("if ("+generateTemp(fm, ffn.getSrc(),lb)+") {");
3729 output.println("#ifndef RAW");
3730 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
3731 output.println("#endif");
3732 //This should throw a suitable null pointer error
3733 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
3735 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
3737 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
3741 private void generateFlatSetFieldNode(FlatMethod fm, LocalityBinding lb, FlatSetFieldNode fsfn, PrintWriter output) {
3742 if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
3743 throw new Error("Can't set array length");
3744 if (state.SINGLETM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
3745 //Single Machine Transaction Case
3746 boolean srcptr=fsfn.getSrc().getType().isPtr();
3747 String src=generateTemp(fm,fsfn.getSrc(),lb);
3748 String dst=generateTemp(fm,fsfn.getDst(),lb);
3749 output.println("//"+srcptr+" "+fsfn.getSrc().getType().isNull());
3750 if (srcptr&&!fsfn.getSrc().getType().isNull()) {
3751 output.println("{");
3752 if ((dc==null)||dc.getNeedSrcTrans(lb, fsfn)&&
3753 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) {
3754 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3756 output.println("INTPTR srcoid=(INTPTR)"+src+";");
3759 if (wb.needBarrier(fsfn)&&
3760 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getDst())!=LocalityAnalysis.SCRATCH) {
3761 output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;");
3763 if (srcptr&!fsfn.getSrc().getType().isNull()) {
3764 output.println("*((unsigned INTPTR *)&("+dst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
3765 output.println("}");
3767 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3769 } else if (state.DSM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
3770 Integer statussrc=locality.getNodePreTempInfo(lb,fsfn).get(fsfn.getSrc());
3771 Integer statusdst=locality.getNodeTempInfo(lb).get(fsfn).get(fsfn.getDst());
3772 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
3774 String src=generateTemp(fm,fsfn.getSrc(),lb);
3775 String dst=generateTemp(fm,fsfn.getDst(),lb);
3777 output.println("{");
3778 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3780 if (statusdst.equals(LocalityAnalysis.GLOBAL)) {
3783 if (wb.needBarrier(fsfn))
3784 output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;");
3786 output.println("*((unsigned INTPTR *)&("+glbdst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
3788 output.println(glbdst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3789 } else if (statusdst.equals(LocalityAnalysis.LOCAL)) {
3790 /** Check if we need to copy */
3791 output.println("if(!"+dst+"->"+localcopystr+") {");
3792 /* Link object into list */
3793 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3794 output.println(revertptr+"=revertlist;");
3795 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
3796 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3798 output.println("COPY_OBJ("+dst+");");
3799 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
3800 output.println("revertlist=(struct ___Object___ *)"+dst+";");
3801 output.println("}");
3803 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
3805 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3806 } else if (statusdst.equals(LocalityAnalysis.EITHER)) {
3807 //writing to a null...bad
3808 output.println("if ("+dst+") {");
3809 output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}");
3811 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
3813 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3816 output.println("}");
3819 if (state.FASTCHECK) {
3820 String dst=generateTemp(fm, fsfn.getDst(),lb);
3821 output.println("if(!"+dst+"->"+localcopystr+") {");
3822 /* Link object into list */
3823 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
3824 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3826 output.println("COPY_OBJ("+dst+");");
3827 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
3828 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
3829 output.println("}");
3831 output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
3835 private void generateFlatElementNode(FlatMethod fm, LocalityBinding lb, FlatElementNode fen, PrintWriter output) {
3836 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
3839 if (elementtype.isArray()||elementtype.isClass())
3842 type=elementtype.getSafeSymbol()+" ";
3844 if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
3845 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fen.getIndex(),lb)+") >= "+generateTemp(fm,fen.getSrc(),lb) + "->___length___))");
3846 output.println("failedboundschk();");
3848 if (state.SINGLETM) {
3849 //Single machine transaction case
3850 String dst=generateTemp(fm, fen.getDst(),lb);
3851 if ((!state.STMARRAY)||(!wb.needBarrier(fen))||locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())==LocalityAnalysis.SCRATCH||locality.getAtomic(lb).get(fen).intValue()==0||(state.READSET&&!dc.getNeedGet(lb, fen))) {
3852 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3854 output.println("STMGETARRAY("+dst+", "+ generateTemp(fm,fen.getSrc(),lb)+", "+generateTemp(fm, fen.getIndex(),lb)+", "+type+");");
3857 if (elementtype.isPtr()&&locality.getAtomic(lb).get(fen).intValue()>0&&
3858 locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())!=LocalityAnalysis.SCRATCH) {
3859 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fen)||state.READSET&&dc.getNeedWriteTrans(lb, fen)) {
3860 output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));");
3861 } else if (state.READSET&&dc.getNeedTrans(lb, fen)) {
3862 if (state.HYBRID&&delaycomp.getConv(lb).contains(fen)) {
3863 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
3865 output.println("TRANSREADRD("+dst+", "+dst+");");
3868 } else if (state.DSM) {
3869 Integer status=locality.getNodePreTempInfo(lb,fen).get(fen.getSrc());
3870 if (status==LocalityAnalysis.GLOBAL) {
3871 String dst=generateTemp(fm, fen.getDst(),lb);
3872 if (elementtype.isPtr()) {
3873 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3874 //DEBUG: output.println("TRANSREAD("+dst+", "+dst+",\""+fm+":"+fen+"\");");
3875 output.println("TRANSREAD("+dst+", "+dst+");");
3877 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3879 } else if (status==LocalityAnalysis.LOCAL) {
3880 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3881 } else if (status==LocalityAnalysis.EITHER) {
3882 //Code is reading from a null pointer
3883 output.println("if ("+generateTemp(fm, fen.getSrc(),lb)+") {");
3884 output.println("#ifndef RAW");
3885 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
3886 output.println("#endif");
3887 //This should throw a suitable null pointer error
3888 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3890 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
3892 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3896 private void generateFlatSetElementNode(FlatMethod fm, LocalityBinding lb, FlatSetElementNode fsen, PrintWriter output) {
3897 //TODO: need dynamic check to make sure this assignment is actually legal
3898 //Because Object[] could actually be something more specific...ie. Integer[]
3900 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
3903 if (elementtype.isArray()||elementtype.isClass())
3906 type=elementtype.getSafeSymbol()+" ";
3908 if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
3909 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fsen.getIndex(),lb)+") >= "+generateTemp(fm,fsen.getDst(),lb) + "->___length___))");
3910 output.println("failedboundschk();");
3913 if (state.SINGLETM && locality.getAtomic(lb).get(fsen).intValue()>0) {
3914 //Transaction set element case
3915 if (wb.needBarrier(fsen)&&
3916 locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH) {
3917 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___objstatus___))|=DIRTY;");
3919 if (fsen.getSrc().getType().isPtr()&&!fsen.getSrc().getType().isNull()) {
3920 output.println("{");
3921 String src=generateTemp(fm, fsen.getSrc(), lb);
3922 if ((dc==null)||dc.getNeedSrcTrans(lb, fsen)&&
3923 locality.getNodePreTempInfo(lb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) {
3924 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3926 output.println("INTPTR srcoid=(INTPTR)"+src+";");
3928 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
3929 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", srcoid, INTPTR);");
3931 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
3933 output.println("}");
3935 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
3936 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", "+ generateTemp(fm, fsen.getSrc(), lb) +", "+type+");");
3938 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
3941 } else if (state.DSM && locality.getAtomic(lb).get(fsen).intValue()>0) {
3942 Integer statussrc=locality.getNodePreTempInfo(lb,fsen).get(fsen.getSrc());
3943 Integer statusdst=locality.getNodePreTempInfo(lb,fsen).get(fsen.getDst());
3944 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
3945 boolean dstglobal=statusdst==LocalityAnalysis.GLOBAL;
3946 boolean dstlocal=(statusdst==LocalityAnalysis.LOCAL)||(statusdst==LocalityAnalysis.EITHER);
3949 if (wb.needBarrier(fsen))
3950 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___localcopy___))|=DIRTY;");
3951 } else if (dstlocal) {
3952 /** Check if we need to copy */
3953 String dst=generateTemp(fm, fsen.getDst(),lb);
3954 output.println("if(!"+dst+"->"+localcopystr+") {");
3955 /* Link object into list */
3956 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3957 output.println(revertptr+"=revertlist;");
3958 if ((GENERATEPRECISEGC) || this.state.MULTICOREGC)
3959 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3961 output.println("COPY_OBJ("+dst+");");
3962 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
3963 output.println("revertlist=(struct ___Object___ *)"+dst+";");
3964 output.println("}");
3966 System.out.println("Node: "+fsen);
3967 System.out.println(lb);
3968 System.out.println("statusdst="+statusdst);
3969 System.out.println(fm.printMethod());
3970 throw new Error("Unknown array type");
3973 output.println("{");
3974 String src=generateTemp(fm, fsen.getSrc(), lb);
3975 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3976 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
3977 output.println("}");
3979 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
3982 if (state.FASTCHECK) {
3983 String dst=generateTemp(fm, fsen.getDst(),lb);
3984 output.println("if(!"+dst+"->"+localcopystr+") {");
3985 /* Link object into list */
3986 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
3987 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3989 output.println("COPY_OBJ("+dst+");");
3990 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
3991 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
3992 output.println("}");
3994 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
3998 protected void generateFlatNew(FlatMethod fm, LocalityBinding lb, FlatNew fn, PrintWriter output) {
3999 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
4000 //Stash pointer in case of GC
4001 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4002 output.println(revertptr+"=revertlist;");
4004 if (state.SINGLETM) {
4005 if (fn.getType().isArray()) {
4006 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4007 if (locality.getAtomic(lb).get(fn).intValue()>0) {
4008 //inside transaction
4009 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4011 //outside transaction
4012 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4015 if (locality.getAtomic(lb).get(fn).intValue()>0) {
4016 //inside transaction
4017 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4019 //outside transaction
4020 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4023 } else if (fn.getType().isArray()) {
4024 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4025 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4026 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4027 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4028 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4030 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4033 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4034 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");");
4035 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4036 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4038 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
4041 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
4042 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4043 String dst=generateTemp(fm,fn.getDst(),lb);
4044 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
4045 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4046 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4048 if (state.FASTCHECK) {
4049 String dst=generateTemp(fm,fn.getDst(),lb);
4050 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
4051 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4052 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4056 private void generateFlatTagDeclaration(FlatMethod fm, LocalityBinding lb, FlatTagDeclaration fn, PrintWriter output) {
4057 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4058 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
4060 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+state.getTagId(fn.getType())+");");
4064 private void generateFlatOpNode(FlatMethod fm, LocalityBinding lb, FlatOpNode fon, PrintWriter output) {
4065 if (fon.getRight()!=null) {
4066 if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
4067 if (fon.getLeft().getType().isLong())
4068 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
4070 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned int)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
4072 } else if (dc!=null) {
4073 output.print(generateTemp(fm, fon.getDest(),lb)+" = (");
4074 if (fon.getLeft().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
4075 output.print("(void *)");
4076 if (dc.getNeedLeftSrcTrans(lb, fon))
4077 output.print("("+generateTemp(fm, fon.getLeft(),lb)+"!=NULL?"+generateTemp(fm, fon.getLeft(),lb)+"->"+oidstr+":NULL)");
4079 output.print(generateTemp(fm, fon.getLeft(),lb));
4080 output.print(")"+fon.getOp().toString()+"(");
4081 if (fon.getRight().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
4082 output.print("(void *)");
4083 if (dc.getNeedRightSrcTrans(lb, fon))
4084 output.println("("+generateTemp(fm, fon.getRight(),lb)+"!=NULL?"+generateTemp(fm, fon.getRight(),lb)+"->"+oidstr+":NULL));");
4086 output.println(generateTemp(fm,fon.getRight(),lb)+");");
4088 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+fon.getOp().toString()+generateTemp(fm,fon.getRight(),lb)+";");
4089 } else if (fon.getOp().getOp()==Operation.ASSIGN)
4090 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
4091 else if (fon.getOp().getOp()==Operation.UNARYPLUS)
4092 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
4093 else if (fon.getOp().getOp()==Operation.UNARYMINUS)
4094 output.println(generateTemp(fm, fon.getDest(),lb)+" = -"+generateTemp(fm, fon.getLeft(),lb)+";");
4095 else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
4096 output.println(generateTemp(fm, fon.getDest(),lb)+" = !"+generateTemp(fm, fon.getLeft(),lb)+";");
4097 else if (fon.getOp().getOp()==Operation.COMP)
4098 output.println(generateTemp(fm, fon.getDest(),lb)+" = ~"+generateTemp(fm, fon.getLeft(),lb)+";");
4099 else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
4100 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+"->fses==NULL;");
4102 output.println(generateTemp(fm, fon.getDest(),lb)+fon.getOp().toString()+generateTemp(fm, fon.getLeft(),lb)+";");
4105 private void generateFlatCastNode(FlatMethod fm, LocalityBinding lb, FlatCastNode fcn, PrintWriter output) {
4106 /* TODO: Do type check here */
4107 if (fcn.getType().isArray()) {
4108 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
4109 } else if (fcn.getType().isClass())
4110 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
4112 output.println(generateTemp(fm,fcn.getDst(),lb)+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc(),lb)+";");
4115 private void generateFlatLiteralNode(FlatMethod fm, LocalityBinding lb, FlatLiteralNode fln, PrintWriter output) {
4116 if (fln.getValue()==null)
4117 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
4118 else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
4119 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4120 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
4121 //Stash pointer in case of GC
4122 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4123 output.println(revertptr+"=revertlist;");
4125 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
4126 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
4127 //Stash pointer in case of GC
4128 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4129 output.println("revertlist="+revertptr+";");
4132 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
4134 } else if (fln.getType().isBoolean()) {
4135 if (((Boolean)fln.getValue()).booleanValue())
4136 output.println(generateTemp(fm, fln.getDst(),lb)+"=1;");
4138 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
4139 } else if (fln.getType().isChar()) {
4140 String st=FlatLiteralNode.escapeString(fln.getValue().toString());
4141 output.println(generateTemp(fm, fln.getDst(),lb)+"='"+st+"';");
4142 } else if (fln.getType().isLong()) {
4143 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+"LL;");
4145 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+";");
4148 protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) {
4149 if (frn.getReturnTemp()!=null) {
4150 if (frn.getReturnTemp().getType().isPtr())
4151 output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";");
4153 output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";");
4155 output.println("return;");
4159 protected void generateStoreFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
4162 //only record if this group has more than one exit
4163 if (branchanalysis.numJumps(fcb)>1) {
4164 left=branchanalysis.jumpValue(fcb, 0);
4165 right=branchanalysis.jumpValue(fcb, 1);
4167 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") {");
4169 output.println("STOREBRANCH("+right+");");
4170 output.println("goto "+label+";");
4171 output.println("}");
4173 output.println("STOREBRANCH("+left+");");
4176 protected void generateFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
4177 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") goto "+label+";");
4180 /** This method generates header information for the method or
4181 * task referenced by the Descriptor des. */
4182 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) {
4183 generateHeader(fm, lb, des, output, false);
4186 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output, boolean addSESErecord) {
4188 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : des);
4189 MethodDescriptor md=null;
4190 TaskDescriptor task=null;
4191 if (des instanceof MethodDescriptor)
4192 md=(MethodDescriptor) des;
4194 task=(TaskDescriptor) des;
4196 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
4198 if (md!=null&&md.getReturnType()!=null) {
4199 if (md.getReturnType().isClass()||md.getReturnType().isArray())
4200 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
4202 output.print(md.getReturnType().getSafeSymbol()+" ");
4204 //catch the constructor case
4205 output.print("void ");
4207 if (state.DSM||state.SINGLETM) {
4208 output.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
4210 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
4212 output.print(task.getSafeSymbol()+"(");
4214 boolean printcomma=false;
4215 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4217 if (state.DSM||state.SINGLETM) {
4218 output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
4220 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
4222 output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
4228 for(int i=0; i<objectparams.numPrimitives(); i++) {
4229 TempDescriptor temp=objectparams.getPrimitive(i);
4233 if (temp.getType().isClass()||temp.getType().isArray())
4234 output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
4236 output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
4238 output.println(") {");
4239 } else if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
4240 /* Imprecise Task */
4241 output.println("void * parameterarray[]) {");
4242 /* Unpack variables */
4243 for(int i=0; i<objectparams.numPrimitives(); i++) {
4244 TempDescriptor temp=objectparams.getPrimitive(i);
4245 output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
4247 for(int i=0; i<fm.numTags(); i++) {
4248 TempDescriptor temp=fm.getTag(i);
4249 int offset=i+objectparams.numPrimitives();
4250 output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
4253 if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
4254 maxtaskparams=objectparams.numPrimitives()+fm.numTags();
4255 } else output.println(") {");
4258 public void generateFlatFlagActionNode(FlatMethod fm, LocalityBinding lb, FlatFlagActionNode ffan, PrintWriter output) {
4259 output.println("/* FlatFlagActionNode */");
4262 /* Process tag changes */
4263 Relation tagsettable=new Relation();
4264 Relation tagcleartable=new Relation();
4266 Iterator tagsit=ffan.getTempTagPairs();
4267 while (tagsit.hasNext()) {
4268 TempTagPair ttp=(TempTagPair) tagsit.next();
4269 TempDescriptor objtmp=ttp.getTemp();
4270 TagDescriptor tag=ttp.getTag();
4271 TempDescriptor tagtmp=ttp.getTagTemp();
4272 boolean tagstatus=ffan.getTagChange(ttp);
4274 tagsettable.put(objtmp, tagtmp);
4276 tagcleartable.put(objtmp, tagtmp);
4281 Hashtable flagandtable=new Hashtable();
4282 Hashtable flagortable=new Hashtable();
4284 /* Process flag changes */
4285 Iterator flagsit=ffan.getTempFlagPairs();
4286 while(flagsit.hasNext()) {
4287 TempFlagPair tfp=(TempFlagPair)flagsit.next();
4288 TempDescriptor temp=tfp.getTemp();
4289 Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
4290 FlagDescriptor flag=tfp.getFlag();
4292 //Newly allocate objects that don't set any flags case
4293 if (flagortable.containsKey(temp)) {
4297 flagortable.put(temp,new Integer(mask));
4299 int flagid=1<<((Integer)flagtable.get(flag)).intValue();
4300 boolean flagstatus=ffan.getFlagChange(tfp);
4303 if (flagortable.containsKey(temp)) {
4304 mask=((Integer)flagortable.get(temp)).intValue();
4307 flagortable.put(temp,new Integer(mask));
4309 int mask=0xFFFFFFFF;
4310 if (flagandtable.containsKey(temp)) {
4311 mask=((Integer)flagandtable.get(temp)).intValue();
4313 mask&=(0xFFFFFFFF^flagid);
4314 flagandtable.put(temp,new Integer(mask));
4320 HashSet flagtagset=new HashSet();
4321 flagtagset.addAll(flagortable.keySet());
4322 flagtagset.addAll(flagandtable.keySet());
4323 flagtagset.addAll(tagsettable.keySet());
4324 flagtagset.addAll(tagcleartable.keySet());
4326 Iterator ftit=flagtagset.iterator();
4327 while(ftit.hasNext()) {
4328 TempDescriptor temp=(TempDescriptor)ftit.next();
4331 Set tagtmps=tagcleartable.get(temp);
4332 if (tagtmps!=null) {
4333 Iterator tagit=tagtmps.iterator();
4334 while(tagit.hasNext()) {
4335 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
4336 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
4337 output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4339 output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4343 tagtmps=tagsettable.get(temp);
4344 if (tagtmps!=null) {
4345 Iterator tagit=tagtmps.iterator();
4346 while(tagit.hasNext()) {
4347 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
4348 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
4349 output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4351 output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp, lb)+", "+generateTemp(fm,tagtmp, lb)+");");
4356 int andmask=0xFFFFFFF;
4358 if (flagortable.containsKey(temp))
4359 ormask=((Integer)flagortable.get(temp)).intValue();
4360 if (flagandtable.containsKey(temp))
4361 andmask=((Integer)flagandtable.get(temp)).intValue();
4362 generateFlagOrAnd(ffan, fm, lb, temp, output, ormask, andmask);
4363 generateObjectDistribute(ffan, fm, lb, temp, output);
4367 protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp,
4368 PrintWriter output, int ormask, int andmask) {
4369 if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
4370 output.println("flagorandinit("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
4372 output.println("flagorand("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
4376 protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, PrintWriter output) {
4377 output.println("enqueueObject("+generateTemp(fm, temp, lb)+");");
4380 void generateOptionalHeader(PrintWriter headers) {
4383 headers.println("#include \"task.h\"\n\n");
4384 headers.println("#ifndef _OPTIONAL_STRUCT_");
4385 headers.println("#define _OPTIONAL_STRUCT_");
4387 //STRUCT PREDICATEMEMBER
4388 headers.println("struct predicatemember{");
4389 headers.println("int type;");
4390 headers.println("int numdnfterms;");
4391 headers.println("int * flags;");
4392 headers.println("int numtags;");
4393 headers.println("int * tags;\n};\n\n");
4395 //STRUCT OPTIONALTASKDESCRIPTOR
4396 headers.println("struct optionaltaskdescriptor{");
4397 headers.println("struct taskdescriptor * task;");
4398 headers.println("int index;");
4399 headers.println("int numenterflags;");
4400 headers.println("int * enterflags;");
4401 headers.println("int numpredicatemembers;");
4402 headers.println("struct predicatemember ** predicatememberarray;");
4403 headers.println("};\n\n");
4405 //STRUCT TASKFAILURE
4406 headers.println("struct taskfailure {");
4407 headers.println("struct taskdescriptor * task;");
4408 headers.println("int index;");
4409 headers.println("int numoptionaltaskdescriptors;");
4410 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
4412 //STRUCT FSANALYSISWRAPPER
4413 headers.println("struct fsanalysiswrapper{");
4414 headers.println("int flags;");
4415 headers.println("int numtags;");
4416 headers.println("int * tags;");
4417 headers.println("int numtaskfailures;");
4418 headers.println("struct taskfailure ** taskfailurearray;");
4419 headers.println("int numoptionaltaskdescriptors;");
4420 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
4422 //STRUCT CLASSANALYSISWRAPPER
4423 headers.println("struct classanalysiswrapper{");
4424 headers.println("int type;");
4425 headers.println("int numotd;");
4426 headers.println("struct optionaltaskdescriptor ** otdarray;");
4427 headers.println("int numfsanalysiswrappers;");
4428 headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
4430 headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
4432 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
4433 while(taskit.hasNext()) {
4434 TaskDescriptor td=(TaskDescriptor)taskit.next();
4435 headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
4440 //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
4441 int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
4442 int predicateindex = 0;
4443 //iterate through the classes concerned by the predicate
4444 Set c_vard = predicate.vardescriptors;
4445 Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
4448 for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext();) {
4449 VarDescriptor vard = (VarDescriptor)vard_it.next();
4450 TypeDescriptor typed = vard.getType();
4452 //generate for flags
4453 HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
4454 output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4456 if (fen_hashset!=null) {
4457 for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext();) {
4458 FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
4460 DNFFlag dflag=fen.getDNF();
4461 numberterms+=dflag.size();
4463 Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
4465 for(int j=0; j<dflag.size(); j++) {
4467 output.println(",");
4468 Vector term=dflag.get(j);
4471 for(int k=0; k<term.size(); k++) {
4472 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
4473 FlagDescriptor fd=dfa.getFlag();
4474 boolean negated=dfa.getNegated();
4475 int flagid=1<<((Integer)flags.get(fd)).intValue();
4480 output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
4485 output.println("};\n");
4488 TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
4489 output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4492 for(int j=0; j<tagel.numTags(); j++) {
4494 output.println(",");
4495 TempDescriptor tmp=tagel.getTemp(j);
4496 if (!slotnumber.containsKey(tmp)) {
4497 Integer slotint=new Integer(current_slot++);
4498 slotnumber.put(tmp,slotint);
4500 int slot=slotnumber.get(tmp).intValue();
4501 output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
4503 numtags = tagel.numTags();
4505 output.println("};");
4507 //store the result into a predicatemember struct
4508 output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
4509 output.println("/*type*/"+typed.getClassDesc().getId()+",");
4510 output.println("/* number of dnf terms */"+numberterms+",");
4511 output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4512 output.println("/* number of tag */"+numtags+",");
4513 output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4514 output.println("};\n");
4519 //generate an array that stores the entire predicate
4520 output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4521 for( int j = 0; j<predicateindex; j++) {
4522 if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4523 else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4525 output.println("};\n");
4526 return predicateindex;
4530 void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
4531 generateOptionalHeader(headers);
4533 output.println("#include \"optionalstruct.h\"\n\n");
4534 output.println("#include \"stdlib.h\"\n");
4536 HashSet processedcd = new HashSet();
4538 Enumeration e = safeexecution.keys();
4539 while (e.hasMoreElements()) {
4542 ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
4543 Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp); //will be used several times
4545 //Generate the struct of optionals
4546 Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
4547 numotd = c_otd.size();
4548 if(maxotd<numotd) maxotd = numotd;
4549 if( !c_otd.isEmpty() ) {
4550 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
4551 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
4553 //generate the int arrays for the predicate
4554 Predicate predicate = otd.predicate;
4555 int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
4556 TreeSet<Integer> fsset=new TreeSet<Integer>();
4557 //iterate through possible FSes corresponding to
4558 //the state when entering
4560 for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext();) {
4561 FlagState fs = (FlagState)fses.next();
4563 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
4564 FlagDescriptor flagd = (FlagDescriptor)flags.next();
4565 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
4568 fsset.add(new Integer(flagid));
4569 //tag information not needed because tag
4570 //changes are not tolerated.
4573 output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4574 boolean needcomma=false;
4575 for(Iterator<Integer> it=fsset.iterator(); it.hasNext();) {
4578 output.println(it.next());
4581 output.println("};\n");
4584 //generate optionaltaskdescriptor that actually
4585 //includes exit fses, predicate and the task
4587 output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
4588 output.println("&task_"+otd.td.getSafeSymbol()+",");
4589 output.println("/*index*/"+otd.getIndex()+",");
4590 output.println("/*number of enter flags*/"+fsset.size()+",");
4591 output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4592 output.println("/*number of members */"+predicateindex+",");
4593 output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4594 output.println("};\n");
4598 // if there are no optionals, there is no need to build the rest of the struct
4600 output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
4601 c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
4602 if( !c_otd.isEmpty() ) {
4603 boolean needcomma=false;
4604 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
4605 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
4607 output.println(",");
4609 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4612 output.println("};\n");
4614 //get all the possible flagstates reachable by an object
4615 Hashtable hashtbtemp = safeexecution.get(cdtemp);
4617 TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
4618 fsts.addAll(hashtbtemp.keySet());
4619 for(Iterator fsit=fsts.iterator(); fsit.hasNext();) {
4620 FlagState fs = (FlagState)fsit.next();
4623 //get the set of OptionalTaskDescriptors corresponding
4624 HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
4625 //iterate through the OptionalTaskDescriptors and
4626 //store the pointers to the optionals struct (see on
4627 //top) into an array
4629 output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
4630 for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext();) {
4631 OptionalTaskDescriptor mm = mos.next();
4633 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
4635 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4638 output.println("};\n");
4640 //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
4643 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
4644 FlagDescriptor flagd = (FlagDescriptor)flags.next();
4645 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
4649 //process tag information
4652 boolean first = true;
4653 Enumeration tag_enum = fs.getTags();
4654 output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
4655 while(tag_enum.hasMoreElements()) {
4657 TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
4661 output.println(", ");
4662 output.println("/*tagid*/"+state.getTagId(tagd));
4664 output.println("};");
4666 Set<TaskIndex> tiset=sa.getTaskIndex(fs);
4667 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
4668 TaskIndex ti=itti.next();
4672 Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
4674 output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
4675 boolean needcomma=false;
4676 for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext();) {
4677 OptionalTaskDescriptor otd=otdit.next();
4681 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4683 output.println("};");
4685 output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
4686 output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
4687 output.print(ti.getIndex()+", ");
4688 output.print(otdset.size()+", ");
4689 output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
4690 output.println("};");
4693 tiset=sa.getTaskIndex(fs);
4694 boolean needcomma=false;
4696 output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
4697 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
4698 TaskIndex ti=itti.next();
4699 if (ti.isRuntime()) {
4706 output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
4708 output.println("};\n");
4710 //Store the result in fsanalysiswrapper
4712 output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
4713 output.println("/*flag*/"+flagid+",");
4714 output.println("/* number of tags*/"+tagcounter+",");
4715 output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
4716 output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
4717 output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
4718 output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
4719 output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
4720 output.println("};\n");
4724 //Build the array of fsanalysiswrappers
4725 output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
4726 boolean needcomma=false;
4727 for(int i = 0; i<fscounter; i++) {
4728 if (needcomma) output.print(",");
4729 output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
4732 output.println("};");
4734 //Build the classanalysiswrapper referring to the previous array
4735 output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
4736 output.println("/*type*/"+cdtemp.getId()+",");
4737 output.println("/*numotd*/"+numotd+",");
4738 output.println("otdarray"+cdtemp.getSafeSymbol()+",");
4739 output.println("/* number of fsanalysiswrappers */"+fscounter+",");
4740 output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
4741 processedcd.add(cdtemp);
4744 //build an array containing every classes for which code has been build
4745 output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
4746 for(int i=0; i<state.numClasses(); i++) {
4747 ClassDescriptor cn=cdarray[i];
4750 if ((cn != null) && (processedcd.contains(cn)))
4751 output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
4753 output.print("NULL");
4755 output.println("};");
4757 output.println("#define MAXOTD "+maxotd);
4758 headers.println("#endif");
4761 public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
4762 Relation r=new Relation();
4763 for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext();) {
4764 OptionalTaskDescriptor otd=otdit.next();
4765 TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
4769 LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
4770 for(Iterator it=r.keySet().iterator(); it.hasNext();) {
4771 Set s=r.get(it.next());
4772 for(Iterator it2=s.iterator(); it2.hasNext();) {
4773 OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
4781 protected void outputTransCode(PrintWriter output) {