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.ConflictGraph;
31 import Analysis.MLP.MLPAnalysis;
32 import Analysis.MLP.VariableSourceToken;
33 import Analysis.MLP.CodePlan;
34 import Analysis.MLP.SESEandAgePair;
36 public class BuildCode {
39 Hashtable paramstable;
44 String localsprefix="___locals___";
45 String localsprefixaddr="&"+localsprefix;
46 String localsprefixderef=localsprefix+".";
47 String fcrevert="___fcrevert___";
48 String paramsprefix="___params___";
49 String oidstr="___nextobject___";
50 String nextobjstr="___nextobject___";
51 String localcopystr="___localcopy___";
52 public static boolean GENERATEPRECISEGC=false;
53 public static String PREFIX="";
54 public static String arraytype="ArrayObject";
55 public static int flagcount = 0;
58 protected int maxtaskparams=0;
59 private int maxcount=0;
60 ClassDescriptor[] cdarray;
61 TypeDescriptor[] arraytable;
62 LocalityAnalysis locality;
63 Hashtable<LocalityBinding, TempDescriptor> reverttable;
64 Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>> backuptable;
68 String mlperrstr = "if(status != 0) { "+
69 "sprintf(errmsg, \"MLP error at %s:%d\", __FILE__, __LINE__); "+
70 "perror(errmsg); exit(-1); }";
71 boolean nonSESEpass=true;
74 DiscoverConflicts recorddc;
79 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa) {
80 this(st, temptovar, typeutil, null, sa, pa, null);
83 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa) {
84 this(st, temptovar, typeutil, null, sa, pa, mlpa);
87 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, PrefetchAnalysis pa, MLPAnalysis mlpa) {
88 this(st, temptovar, typeutil, locality, null, pa, mlpa);
91 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa) {
96 callgraph=new CallGraph(state);
98 oidstr="___objlocation___";
99 this.temptovar=temptovar;
100 paramstable=new Hashtable();
101 tempstable=new Hashtable();
102 fieldorder=new Hashtable();
103 flagorder=new Hashtable();
104 this.typeutil=typeutil;
105 virtualcalls=new Virtual(state,locality);
106 if (locality!=null) {
107 this.locality=locality;
108 this.reverttable=new Hashtable<LocalityBinding, TempDescriptor>();
109 this.backuptable=new Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>>();
110 this.wb=new WriteBarrier(locality, st);
112 if (state.SINGLETM&&state.DCOPTS) {
113 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
114 GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
115 this.dc=new DiscoverConflicts(locality, st, typeanalysis, gft);
118 if (state.DELAYCOMP) {
119 //TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
120 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
121 GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
122 delaycomp=new DCWrapper(locality, st, typeanalysis, gft);
123 dc=delaycomp.getConflicts();
124 recorddc=new DiscoverConflicts(locality, st, typeanalysis, delaycomp.getCannotDelayMap(), true, true, null);
125 recorddc.doAnalysis();
129 /** The buildCode method outputs C code for all the methods. The Flat
130 * versions of the methods must already be generated and stored in
131 * the State object. */
132 PrintWriter outsandbox=null;
134 public void buildCode() {
135 /* Create output streams to write to */
136 PrintWriter outclassdefs=null;
137 PrintWriter outstructs=null;
138 PrintWriter outrepairstructs=null;
139 PrintWriter outmethodheader=null;
140 PrintWriter outmethod=null;
141 PrintWriter outvirtual=null;
142 PrintWriter outtask=null;
143 PrintWriter outtaskdefs=null;
144 PrintWriter outoptionalarrays=null;
145 PrintWriter optionalheaders=null;
149 outsandbox=new PrintWriter(new FileOutputStream(PREFIX+"sandboxdefs.c"), true);
151 outstructs=new PrintWriter(new FileOutputStream(PREFIX+"structdefs.h"), true);
152 outmethodheader=new PrintWriter(new FileOutputStream(PREFIX+"methodheaders.h"), true);
153 outclassdefs=new PrintWriter(new FileOutputStream(PREFIX+"classdefs.h"), true);
154 outmethod=new PrintWriter(new FileOutputStream(PREFIX+"methods.c"), true);
155 outvirtual=new PrintWriter(new FileOutputStream(PREFIX+"virtualtable.h"), true);
157 outtask=new PrintWriter(new FileOutputStream(PREFIX+"task.h"), true);
158 outtaskdefs=new PrintWriter(new FileOutputStream(PREFIX+"taskdefs.c"), true);
159 if (state.OPTIONAL) {
160 outoptionalarrays=new PrintWriter(new FileOutputStream(PREFIX+"optionalarrays.c"), true);
161 optionalheaders=new PrintWriter(new FileOutputStream(PREFIX+"optionalstruct.h"), true);
164 if (state.structfile!=null) {
165 outrepairstructs=new PrintWriter(new FileOutputStream(PREFIX+state.structfile+".struct"), true);
167 } catch (Exception e) {
172 /* Build the virtual dispatch tables */
173 buildVirtualTables(outvirtual);
175 /* Output includes */
176 outmethodheader.println("#ifndef METHODHEADERS_H");
177 outmethodheader.println("#define METHODHEADERS_H");
178 outmethodheader.println("#include \"structdefs.h\"");
180 outmethodheader.println("#include \"dstm.h\"");
182 outmethodheader.println("#include \"sandbox.h\"");
184 if (state.SINGLETM) {
185 outmethodheader.println("#include \"tm.h\"");
186 outmethodheader.println("#include \"delaycomp.h\"");
187 outmethodheader.println("#include \"inlinestm.h\"");
189 if (state.ABORTREADERS) {
190 outmethodheader.println("#include \"abortreaders.h\"");
191 outmethodheader.println("#include <setjmp.h>");
194 outmethodheader.println("#include <stdlib.h>");
195 outmethodheader.println("#include <stdio.h>");
196 outmethodheader.println("#include <string.h>");
197 outmethodheader.println("#include \"mlp_runtime.h\"");
198 outmethodheader.println("#include \"psemaphore.h\"");
201 /* Output Structures */
202 outputStructs(outstructs);
204 // Output the C class declarations
205 // These could mutually reference each other
206 outputClassDeclarations(outclassdefs);
208 // Output function prototypes and structures for parameters
209 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
210 while(it.hasNext()) {
211 ClassDescriptor cn=(ClassDescriptor)it.next();
212 generateCallStructs(cn, outclassdefs, outstructs, outmethodheader);
214 outclassdefs.close();
217 /* Map flags to integers */
218 /* The runtime keeps track of flags using these integers */
219 it=state.getClassSymbolTable().getDescriptorsIterator();
220 while(it.hasNext()) {
221 ClassDescriptor cn=(ClassDescriptor)it.next();
225 generateTaskStructs(outstructs, outmethodheader);
227 /* Outputs generic task structures if this is a task
229 outputTaskTypes(outtask);
233 // have to initialize some SESE compiler data before
234 // analyzing normal methods, which must happen before
235 // generating SESE internal code
236 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
237 FlatSESEEnterNode fsen = seseit.next();
238 initializeSESE( fsen );
242 /* Build the actual methods */
243 outputMethods(outmethod);
245 // Output function prototypes and structures for SESE's and code
248 // used to differentiate, during code generation, whether we are
249 // passing over SESE body code, or non-SESE code
252 // first generate code for each sese's internals
253 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
254 FlatSESEEnterNode fsen = seseit.next();
255 generateMethodSESE(fsen, null, outstructs, outmethodheader, outmethod);
258 // then write the invokeSESE switch to decouple scheduler
259 // from having to do unique details of sese invocation
260 generateSESEinvocationMethod(outmethodheader, outmethod);
264 /* Output code for tasks */
265 outputTaskCode(outtaskdefs, outmethod);
267 /* Record maximum number of task parameters */
268 outstructs.println("#define MAXTASKPARAMS "+maxtaskparams);
269 } else if (state.main!=null) {
270 /* Generate main method */
271 outputMainMethod(outmethod);
274 /* Generate information for task with optional parameters */
275 if (state.TASK&&state.OPTIONAL) {
276 generateOptionalArrays(outoptionalarrays, optionalheaders, state.getAnalysisResult(), state.getOptionalTaskDescriptors());
277 outoptionalarrays.close();
280 /* Output structure definitions for repair tool */
281 if (state.structfile!=null) {
282 buildRepairStructs(outrepairstructs);
283 outrepairstructs.close();
287 outmethodheader.println("#endif");
288 outmethodheader.close();
290 outstructs.println("#endif");
295 /* This code just generates the main C method for java programs.
296 * The main C method packs up the arguments into a string array
297 * and passes it to the java main method. */
299 private void outputMainMethod(PrintWriter outmethod) {
300 outmethod.println("int main(int argc, const char *argv[]) {");
301 outmethod.println(" int i;");
304 //outmethod.println(" pthread_once( &mlpOnceObj, mlpInitOncePerThread );");
305 outmethod.println(" workScheduleInit( "+state.MLP_NUMCORES+", invokeSESEmethod );");
309 outmethod.println("#ifdef TRANSSTATS \n");
310 outmethod.println("handle();\n");
311 outmethod.println("#endif\n");
313 if (state.THREAD||state.DSM||state.SINGLETM) {
314 outmethod.println("initializethreads();");
317 outmethod.println("if (dstmStartup(argv[1])) {");
318 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
319 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-2);");
321 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-2);");
324 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
325 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1);");
327 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1);");
331 outmethod.println(" for(i=2;i<argc;i++) {");
333 outmethod.println(" for(i=1;i<argc;i++) {");
334 outmethod.println(" int length=strlen(argv[i]);");
335 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
336 outmethod.println(" struct ___String___ *newstring=NewString(NULL, argv[i], length);");
338 outmethod.println(" struct ___String___ *newstring=NewString(argv[i], length);");
341 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-2]=newstring;");
343 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-1]=newstring;");
344 outmethod.println(" }");
346 MethodDescriptor md=typeutil.getMain();
347 ClassDescriptor cd=typeutil.getMainClass();
349 outmethod.println(" {");
350 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
351 if (state.DSM||state.SINGLETM) {
352 outmethod.print(" struct "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
354 outmethod.print(" struct "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
355 outmethod.println("1, NULL,"+"stringarray};");
356 if (state.DSM||state.SINGLETM)
357 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
359 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
361 if (state.DSM||state.SINGLETM)
362 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
364 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
366 outmethod.println(" }");
369 outmethod.println("}");
372 if (state.THREAD||state.DSM||state.SINGLETM) {
373 outmethod.println("pthread_mutex_lock(&gclistlock);");
374 outmethod.println("threadcount--;");
375 outmethod.println("pthread_cond_signal(&gccond);");
376 outmethod.println("pthread_mutex_unlock(&gclistlock);");
379 if (state.DSM||state.SINGLETM) {
380 outmethod.println("#ifdef TRANSSTATS \n");
381 outmethod.println("printf(\"****** Transaction Stats ******\\n\");");
382 outmethod.println("printf(\"numTransCommit= %d\\n\", numTransCommit);");
383 outmethod.println("printf(\"numTransAbort= %d\\n\", numTransAbort);");
384 outmethod.println("printf(\"nSoftAbort= %d\\n\", nSoftAbort);");
386 outmethod.println("printf(\"nchashSearch= %d\\n\", nchashSearch);");
387 outmethod.println("printf(\"nmhashSearch= %d\\n\", nmhashSearch);");
388 outmethod.println("printf(\"nprehashSearch= %d\\n\", nprehashSearch);");
389 outmethod.println("printf(\"ndirtyCacheObj= %d\\n\", ndirtyCacheObj);");
390 outmethod.println("printf(\"nRemoteReadSend= %d\\n\", nRemoteSend);");
391 outmethod.println("printf(\"bytesSent= %d\\n\", bytesSent);");
392 outmethod.println("printf(\"bytesRecv= %d\\n\", bytesRecv);");
393 outmethod.println("printf(\"totalObjSize= %d\\n\", totalObjSize);");
394 outmethod.println("printf(\"sendRemoteReq= %d\\n\", sendRemoteReq);");
395 outmethod.println("printf(\"getResponse= %d\\n\", getResponse);");
396 } else if (state.SINGLETM) {
397 outmethod.println("printf(\"nSoftAbortAbort= %d\\n\", nSoftAbortAbort);");
398 outmethod.println("printf(\"nSoftAbortCommit= %d\\n\", nSoftAbortCommit);");
399 outmethod.println("#ifdef STMSTATS\n");
400 outmethod.println("for(i=0; i<TOTALNUMCLASSANDARRAY; i++) {\n");
401 outmethod.println(" printf(\"typesCausingAbort[%2d] numaccess= %5d numabort= %3d\\n\", i, typesCausingAbort[i].numaccess, typesCausingAbort[i].numabort);\n");
402 outmethod.println("}\n");
403 outmethod.println("#endif\n");
404 outmethod.println("fflush(stdout);");
406 outmethod.println("#endif\n");
409 if (state.THREAD||state.SINGLETM)
410 outmethod.println("pthread_exit(NULL);");
413 outmethod.println(" workScheduleBegin();");
416 outmethod.println("}");
419 /* This method outputs code for each task. */
421 private void outputTaskCode(PrintWriter outtaskdefs, PrintWriter outmethod) {
422 /* Compile task based program */
423 outtaskdefs.println("#include \"task.h\"");
424 outtaskdefs.println("#include \"methodheaders.h\"");
425 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
426 while(taskit.hasNext()) {
427 TaskDescriptor td=(TaskDescriptor)taskit.next();
428 FlatMethod fm=state.getMethodFlat(td);
429 generateFlatMethod(fm, null, outmethod);
430 generateTaskDescriptor(outtaskdefs, fm, td);
433 //Output task descriptors
434 taskit=state.getTaskSymbolTable().getDescriptorsIterator();
435 outtaskdefs.println("struct taskdescriptor * taskarray[]= {");
437 while(taskit.hasNext()) {
438 TaskDescriptor td=(TaskDescriptor)taskit.next();
442 outtaskdefs.println(",");
443 outtaskdefs.print("&task_"+td.getSafeSymbol());
445 outtaskdefs.println("};");
447 outtaskdefs.println("int numtasks="+state.getTaskSymbolTable().getValueSet().size()+";");
450 /* This method outputs most of the methods.c file. This includes
451 * some standard includes and then an array with the sizes of
452 * objets and array that stores supertype and then the code for
453 * the Java methods.. */
455 protected void outputMethods(PrintWriter outmethod) {
456 outmethod.println("#include \"methodheaders.h\"");
457 outmethod.println("#include \"virtualtable.h\"");
458 outmethod.println("#include \"runtime.h\"");
460 outmethod.println("#include \"sandboxdefs.c\"");
463 outmethod.println("#include \"addPrefetchEnhance.h\"");
464 outmethod.println("#include \"localobjects.h\"");
466 if (state.FASTCHECK) {
467 outmethod.println("#include \"localobjects.h\"");
469 if(state.MULTICORE) {
470 outmethod.println("#include \"task.h\"");
471 outmethod.println("#include \"multicoreruntime.h\"");
472 outmethod.println("#include \"runtime_arch.h\"");
474 if (state.THREAD||state.DSM||state.SINGLETM)
475 outmethod.println("#include <thread.h>");
476 if (state.main!=null) {
477 outmethod.println("#include <string.h>");
479 if (state.CONSCHECK) {
480 outmethod.println("#include \"checkers.h\"");
483 outmethod.println("#include <stdlib.h>");
484 outmethod.println("#include <stdio.h>");
485 outmethod.println("#include \"mlp_runtime.h\"");
486 outmethod.println("#include \"psemaphore.h\"");
490 //Store the sizes of classes & array elements
491 generateSizeArray(outmethod);
493 //Store table of supertypes
494 generateSuperTypeTable(outmethod);
496 //Store the layout of classes
497 generateLayoutStructs(outmethod);
499 /* Generate code for methods */
500 if (state.DSM||state.SINGLETM) {
501 for(Iterator<LocalityBinding> lbit=locality.getLocalityBindings().iterator(); lbit.hasNext();) {
502 LocalityBinding lb=lbit.next();
503 MethodDescriptor md=lb.getMethod();
504 FlatMethod fm=state.getMethodFlat(md);
506 if (!md.getModifiers().isNative()) {
507 generateFlatMethod(fm, lb, outmethod);
508 //System.out.println("fm= " + fm + " md= " + md);
512 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
513 while(classit.hasNext()) {
514 ClassDescriptor cn=(ClassDescriptor)classit.next();
515 Iterator methodit=cn.getMethods();
516 while(methodit.hasNext()) {
517 /* Classify parameters */
518 MethodDescriptor md=(MethodDescriptor)methodit.next();
519 FlatMethod fm=state.getMethodFlat(md);
520 if (!md.getModifiers().isNative()) {
521 generateFlatMethod(fm, null, outmethod);
528 protected void outputStructs(PrintWriter outstructs) {
529 outstructs.println("#ifndef STRUCTDEFS_H");
530 outstructs.println("#define STRUCTDEFS_H");
531 outstructs.println("#include \"classdefs.h\"");
532 outstructs.println("#ifndef INTPTR");
533 outstructs.println("#ifdef BIT64");
534 outstructs.println("#define INTPTR long");
535 outstructs.println("#else");
536 outstructs.println("#define INTPTR int");
537 outstructs.println("#endif");
538 outstructs.println("#endif");
540 outstructs.println("#include \"mlp_runtime.h\"");
541 outstructs.println("#include \"psemaphore.h\"");
544 /* Output #defines that the runtime uses to determine type
545 * numbers for various objects it needs */
546 outstructs.println("#define MAXCOUNT "+maxcount);
547 if (state.DSM||state.SINGLETM) {
548 LocalityBinding lbrun=new LocalityBinding(typeutil.getRun(), false);
550 lbrun.setGlobalThis(LocalityAnalysis.GLOBAL);
552 else if (state.SINGLETM) {
553 lbrun.setGlobalThis(LocalityAnalysis.NORMAL);
555 outstructs.println("#define RUNMETHOD "+virtualcalls.getLocalityNumber(lbrun));
559 LocalityBinding lbexecute = new LocalityBinding(typeutil.getExecute(), false);
561 lbexecute.setGlobalThis(LocalityAnalysis.GLOBAL);
562 else if( state.SINGLETM)
563 lbexecute.setGlobalThis(LocalityAnalysis.NORMAL);
564 outstructs.println("#define EXECUTEMETHOD " + virtualcalls.getLocalityNumber(lbexecute));
567 outstructs.println("#define STRINGARRAYTYPE "+
568 (state.getArrayNumber(
569 (new TypeDescriptor(typeutil.getClass(TypeUtil.StringClass))).makeArray(state))+state.numClasses()));
571 outstructs.println("#define OBJECTARRAYTYPE "+
572 (state.getArrayNumber(
573 (new TypeDescriptor(typeutil.getClass(TypeUtil.ObjectClass))).makeArray(state))+state.numClasses()));
576 outstructs.println("#define STRINGTYPE "+typeutil.getClass(TypeUtil.StringClass).getId());
577 outstructs.println("#define CHARARRAYTYPE "+
578 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.CHAR)).makeArray(state))+state.numClasses()));
580 outstructs.println("#define BYTEARRAYTYPE "+
581 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state))+state.numClasses()));
583 outstructs.println("#define BYTEARRAYARRAYTYPE "+
584 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state).makeArray(state))+state.numClasses()));
586 outstructs.println("#define NUMCLASSES "+state.numClasses());
587 int totalClassSize = state.numClasses() + state.numArrays();
588 outstructs.println("#define TOTALNUMCLASSANDARRAY "+ totalClassSize);
590 outstructs.println("#define STARTUPTYPE "+typeutil.getClass(TypeUtil.StartupClass).getId());
591 outstructs.println("#define TAGTYPE "+typeutil.getClass(TypeUtil.TagClass).getId());
592 outstructs.println("#define TAGARRAYTYPE "+
593 (state.getArrayNumber(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)).makeArray(state))+state.numClasses()));
597 protected void outputClassDeclarations(PrintWriter outclassdefs) {
598 if (state.THREAD||state.DSM||state.SINGLETM)
599 outclassdefs.println("#include <pthread.h>");
600 outclassdefs.println("#ifndef INTPTR");
601 outclassdefs.println("#ifdef BIT64");
602 outclassdefs.println("#define INTPTR long");
603 outclassdefs.println("#else");
604 outclassdefs.println("#define INTPTR int");
605 outclassdefs.println("#endif");
606 outclassdefs.println("#endif");
608 outclassdefs.println("#include \"optionalstruct.h\"");
609 outclassdefs.println("struct "+arraytype+";");
610 /* Start by declaring all structs */
611 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
612 while(it.hasNext()) {
613 ClassDescriptor cn=(ClassDescriptor)it.next();
614 outclassdefs.println("struct "+cn.getSafeSymbol()+";");
616 outclassdefs.println("");
617 //Print out definition for array type
618 outclassdefs.println("struct "+arraytype+" {");
619 outclassdefs.println(" int type;");
621 outclassdefs.println(" pthread_t tid;");
622 outclassdefs.println(" void * lockentry;");
623 outclassdefs.println(" int lockcount;");
626 outclassdefs.println(" int flag;");
627 if(!state.MULTICORE) {
628 outclassdefs.println(" void * flagptr;");
630 outclassdefs.println(" int version;");
631 outclassdefs.println(" int * lock;"); // lock entry for this obj
632 outclassdefs.println(" int mutex;");
633 outclassdefs.println(" int lockcount;");
634 if(state.MULTICOREGC) {
635 outclassdefs.println(" int marked;");
639 outclassdefs.println(" int numfses;");
640 outclassdefs.println(" int * fses;");
643 printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs);
645 if (state.STMARRAY) {
646 outclassdefs.println(" int lowindex;");
647 outclassdefs.println(" int highindex;");
650 outclassdefs.println(" int paddingforarray;");
651 if (state.DUALVIEW) {
652 outclassdefs.println(" int arrayversion;");
655 outclassdefs.println(" int ___length___;");
656 outclassdefs.println("};\n");
657 outclassdefs.println("extern int classsize[];");
658 outclassdefs.println("extern int hasflags[];");
659 outclassdefs.println("extern unsigned INTPTR * pointerarray[];");
660 outclassdefs.println("extern int supertypes[];");
663 /** Prints out definitions for generic task structures */
665 private void outputTaskTypes(PrintWriter outtask) {
666 outtask.println("#ifndef _TASK_H");
667 outtask.println("#define _TASK_H");
668 outtask.println("struct parameterdescriptor {");
669 outtask.println("int type;");
670 outtask.println("int numberterms;");
671 outtask.println("int *intarray;");
672 outtask.println("void * queue;");
673 outtask.println("int numbertags;");
674 outtask.println("int *tagarray;");
675 outtask.println("};");
677 outtask.println("struct taskdescriptor {");
678 outtask.println("void * taskptr;");
679 outtask.println("int numParameters;");
680 outtask.println(" int numTotal;");
681 outtask.println("struct parameterdescriptor **descriptorarray;");
682 outtask.println("char * name;");
683 outtask.println("};");
684 outtask.println("extern struct taskdescriptor * taskarray[];");
685 outtask.println("extern numtasks;");
686 outtask.println("#endif");
690 private void buildRepairStructs(PrintWriter outrepairstructs) {
691 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
692 while(classit.hasNext()) {
693 ClassDescriptor cn=(ClassDescriptor)classit.next();
694 outrepairstructs.println("structure "+cn.getSymbol()+" {");
695 outrepairstructs.println(" int __type__;");
697 outrepairstructs.println(" int __flag__;");
698 if(!state.MULTICORE) {
699 outrepairstructs.println(" int __flagptr__;");
702 printRepairStruct(cn, outrepairstructs);
703 outrepairstructs.println("}\n");
706 for(int i=0; i<state.numArrays(); i++) {
707 TypeDescriptor tdarray=arraytable[i];
708 TypeDescriptor tdelement=tdarray.dereference();
709 outrepairstructs.println("structure "+arraytype+"_"+state.getArrayNumber(tdarray)+" {");
710 outrepairstructs.println(" int __type__;");
711 printRepairStruct(typeutil.getClass(TypeUtil.ObjectClass), outrepairstructs);
712 outrepairstructs.println(" int length;");
714 // Need to add support to repair tool for this
715 if (tdelement.isClass()||tdelement.isArray())
716 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" * elem[this.length];");
718 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" elem[this.length];");
720 outrepairstructs.println("}\n");
724 private void printRepairStruct(ClassDescriptor cn, PrintWriter output) {
725 ClassDescriptor sp=cn.getSuperDesc();
727 printRepairStruct(sp, output);
729 Vector fields=(Vector)fieldorder.get(cn);
731 for(int i=0; i<fields.size(); i++) {
732 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
733 if (fd.getType().isArray()) {
734 output.println(" "+arraytype+"_"+ state.getArrayNumber(fd.getType()) +" * "+fd.getSymbol()+";");
735 } else if (fd.getType().isClass())
736 output.println(" "+fd.getType().getRepairSymbol()+" * "+fd.getSymbol()+";");
737 else if (fd.getType().isFloat())
738 output.println(" int "+fd.getSymbol()+"; /* really float */");
740 output.println(" "+fd.getType().getRepairSymbol()+" "+fd.getSymbol()+";");
744 /** This method outputs TaskDescriptor information */
745 private void generateTaskDescriptor(PrintWriter output, FlatMethod fm, TaskDescriptor task) {
746 for (int i=0; i<task.numParameters(); i++) {
747 VarDescriptor param_var=task.getParameter(i);
748 TypeDescriptor param_type=task.getParamType(i);
749 FlagExpressionNode param_flag=task.getFlag(param_var);
750 TagExpressionList param_tag=task.getTag(param_var);
753 if (param_flag==null) {
754 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
755 output.println("0x0, 0x0 };");
758 DNFFlag dflag=param_flag.getDNF();
759 dnfterms=dflag.size();
761 Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
762 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
763 for(int j=0; j<dflag.size(); j++) {
766 Vector term=dflag.get(j);
769 for(int k=0; k<term.size(); k++) {
770 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
771 FlagDescriptor fd=dfa.getFlag();
772 boolean negated=dfa.getNegated();
773 int flagid=1<<((Integer)flags.get(fd)).intValue();
778 output.print("0x"+Integer.toHexString(andmask)+", 0x"+Integer.toHexString(checkmask));
780 output.println("};");
783 output.println("int parametertag_"+i+"_"+task.getSafeSymbol()+"[]={");
784 //BUG...added next line to fix, test with any task program
786 for(int j=0; j<param_tag.numTags(); j++) {
789 /* for each tag we need */
790 /* which slot it is */
791 /* what type it is */
792 TagVarDescriptor tvd=(TagVarDescriptor)task.getParameterTable().get(param_tag.getName(j));
793 TempDescriptor tmp=param_tag.getTemp(j);
794 int slot=fm.getTagInt(tmp);
795 output.println(slot+", "+state.getTagId(tvd.getTag()));
797 output.println("};");
799 output.println("struct parameterdescriptor parameter_"+i+"_"+task.getSafeSymbol()+"={");
800 output.println("/* type */"+param_type.getClassDesc().getId()+",");
801 output.println("/* number of DNF terms */"+dnfterms+",");
802 output.println("parameterdnf_"+i+"_"+task.getSafeSymbol()+",");
803 output.println("0,");
804 //BUG, added next line to fix and else statement...test
805 //with any task program
807 output.println("/* number of tags */"+param_tag.numTags()+",");
809 output.println("/* number of tags */ 0,");
810 output.println("parametertag_"+i+"_"+task.getSafeSymbol());
811 output.println("};");
815 output.println("struct parameterdescriptor * parameterdescriptors_"+task.getSafeSymbol()+"[] = {");
816 for (int i=0; i<task.numParameters(); i++) {
819 output.print("¶meter_"+i+"_"+task.getSafeSymbol());
821 output.println("};");
823 output.println("struct taskdescriptor task_"+task.getSafeSymbol()+"={");
824 output.println("&"+task.getSafeSymbol()+",");
825 output.println("/* number of parameters */" +task.numParameters() + ",");
826 int numtotal=task.numParameters()+fm.numTags();
827 output.println("/* number total parameters */" +numtotal + ",");
828 output.println("parameterdescriptors_"+task.getSafeSymbol()+",");
829 output.println("\""+task.getSymbol()+"\"");
830 output.println("};");
834 /** The buildVirtualTables method outputs the virtual dispatch
835 * tables for methods. */
837 protected void buildVirtualTables(PrintWriter outvirtual) {
838 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
839 while(classit.hasNext()) {
840 ClassDescriptor cd=(ClassDescriptor)classit.next();
841 if (virtualcalls.getMethodCount(cd)>maxcount)
842 maxcount=virtualcalls.getMethodCount(cd);
844 MethodDescriptor[][] virtualtable=null;
845 LocalityBinding[][] lbvirtualtable=null;
846 if (state.DSM||state.SINGLETM)
847 lbvirtualtable=new LocalityBinding[state.numClasses()+state.numArrays()][maxcount];
849 virtualtable=new MethodDescriptor[state.numClasses()+state.numArrays()][maxcount];
851 /* Fill in virtual table */
852 classit=state.getClassSymbolTable().getDescriptorsIterator();
853 while(classit.hasNext()) {
854 ClassDescriptor cd=(ClassDescriptor)classit.next();
855 if (state.DSM||state.SINGLETM)
856 fillinRow(cd, lbvirtualtable, cd.getId());
858 fillinRow(cd, virtualtable, cd.getId());
861 ClassDescriptor objectcd=typeutil.getClass(TypeUtil.ObjectClass);
862 Iterator arrayit=state.getArrayIterator();
863 while(arrayit.hasNext()) {
864 TypeDescriptor td=(TypeDescriptor)arrayit.next();
865 int id=state.getArrayNumber(td);
866 if (state.DSM||state.SINGLETM)
867 fillinRow(objectcd, lbvirtualtable, id+state.numClasses());
869 fillinRow(objectcd, virtualtable, id+state.numClasses());
872 outvirtual.print("void * virtualtable[]={");
873 boolean needcomma=false;
874 for(int i=0; i<state.numClasses()+state.numArrays(); i++) {
875 for(int j=0; j<maxcount; j++) {
877 outvirtual.print(", ");
878 if ((state.DSM||state.SINGLETM)&&lbvirtualtable[i][j]!=null) {
879 LocalityBinding lb=lbvirtualtable[i][j];
880 MethodDescriptor md=lb.getMethod();
881 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
882 } else if (!(state.DSM||state.SINGLETM)&&virtualtable[i][j]!=null) {
883 MethodDescriptor md=virtualtable[i][j];
884 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
886 outvirtual.print("0");
890 outvirtual.println("");
892 outvirtual.println("};");
896 private void fillinRow(ClassDescriptor cd, MethodDescriptor[][] virtualtable, int rownum) {
897 /* Get inherited methods */
898 if (cd.getSuperDesc()!=null)
899 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
900 /* Override them with our methods */
901 for(Iterator it=cd.getMethods(); it.hasNext();) {
902 MethodDescriptor md=(MethodDescriptor)it.next();
903 if (md.isStatic()||md.getReturnType()==null)
905 int methodnum=virtualcalls.getMethodNumber(md);
906 virtualtable[rownum][methodnum]=md;
910 private void fillinRow(ClassDescriptor cd, LocalityBinding[][] virtualtable, int rownum) {
911 /* Get inherited methods */
912 if (cd.getSuperDesc()!=null)
913 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
914 /* Override them with our methods */
915 if (locality.getClassBindings(cd)!=null)
916 for(Iterator<LocalityBinding> lbit=locality.getClassBindings(cd).iterator(); lbit.hasNext();) {
917 LocalityBinding lb=lbit.next();
918 MethodDescriptor md=lb.getMethod();
919 //Is the method static or a constructor
920 if (md.isStatic()||md.getReturnType()==null)
922 int methodnum=virtualcalls.getLocalityNumber(lb);
923 virtualtable[rownum][methodnum]=lb;
927 /** Generate array that contains the sizes of class objects. The
928 * object allocation functions in the runtime use this
931 private void generateSizeArray(PrintWriter outclassdefs) {
932 outclassdefs.print("extern struct prefetchCountStats * evalPrefetch;\n");
933 outclassdefs.print("#ifdef TRANSSTATS \n");
934 outclassdefs.print("extern int numTransAbort;\n");
935 outclassdefs.print("extern int numTransCommit;\n");
936 outclassdefs.print("extern int nSoftAbort;\n");
938 outclassdefs.print("extern int nchashSearch;\n");
939 outclassdefs.print("extern int nmhashSearch;\n");
940 outclassdefs.print("extern int nprehashSearch;\n");
941 outclassdefs.print("extern int ndirtyCacheObj;\n");
942 outclassdefs.print("extern int nRemoteSend;\n");
943 outclassdefs.print("extern int sendRemoteReq;\n");
944 outclassdefs.print("extern int getResponse;\n");
945 outclassdefs.print("extern int bytesSent;\n");
946 outclassdefs.print("extern int bytesRecv;\n");
947 outclassdefs.print("extern int totalObjSize;\n");
948 outclassdefs.print("extern void handle();\n");
949 } else if (state.SINGLETM) {
950 outclassdefs.println("extern int nSoftAbortAbort;");
951 outclassdefs.println("extern int nSoftAbortCommit;");
952 outclassdefs.println("#ifdef STMSTATS\n");
953 outclassdefs.println("extern objtypestat_t typesCausingAbort[];");
954 outclassdefs.println("#endif\n");
956 outclassdefs.print("#endif\n");
957 outclassdefs.print("int numprefetchsites = " + pa.prefetchsiteid + ";\n");
959 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
960 cdarray=new ClassDescriptor[state.numClasses()];
962 while(it.hasNext()) {
963 ClassDescriptor cd=(ClassDescriptor)it.next();
964 cdarray[cd.getId()]=cd;
967 arraytable=new TypeDescriptor[state.numArrays()];
969 Iterator arrayit=state.getArrayIterator();
970 while(arrayit.hasNext()) {
971 TypeDescriptor td=(TypeDescriptor)arrayit.next();
972 int id=state.getArrayNumber(td);
978 /* Print out types */
979 outclassdefs.println("/* ");
980 for(int i=0; i<state.numClasses(); i++) {
981 ClassDescriptor cd=cdarray[i];
983 outclassdefs.println("NULL " + i);
985 outclassdefs.println(cd +" "+i);
989 for(int i=0; i<state.numArrays(); i++) {
990 TypeDescriptor arraytd=arraytable[i];
991 outclassdefs.println(arraytd.toPrettyString() +" "+(i+state.numClasses()));
994 outclassdefs.println("*/");
997 outclassdefs.print("int classsize[]={");
999 boolean needcomma=false;
1000 for(int i=0; i<state.numClasses(); i++) {
1002 outclassdefs.print(", ");
1004 outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")");
1006 outclassdefs.print("0");
1012 for(int i=0; i<state.numArrays(); i++) {
1014 outclassdefs.print(", ");
1015 TypeDescriptor tdelement=arraytable[i].dereference();
1016 if (tdelement.isArray()||tdelement.isClass())
1017 outclassdefs.print("sizeof(void *)");
1019 outclassdefs.print("sizeof("+tdelement.getSafeSymbol()+")");
1023 outclassdefs.println("};");
1025 ClassDescriptor objectclass=typeutil.getClass(TypeUtil.ObjectClass);
1027 outclassdefs.print("int typearray[]={");
1028 for(int i=0; i<state.numClasses(); i++) {
1029 ClassDescriptor cd=cdarray[i];
1030 ClassDescriptor supercd=i>0?cd.getSuperDesc():null;
1032 outclassdefs.print(", ");
1034 outclassdefs.print("-1");
1036 outclassdefs.print(supercd.getId());
1040 for(int i=0; i<state.numArrays(); i++) {
1041 TypeDescriptor arraytd=arraytable[i];
1042 ClassDescriptor arraycd=arraytd.getClassDesc();
1043 if (arraycd==null) {
1045 outclassdefs.print(", ");
1046 outclassdefs.print(objectclass.getId());
1050 ClassDescriptor cd=arraycd.getSuperDesc();
1053 TypeDescriptor supertd=new TypeDescriptor(cd);
1054 supertd.setArrayCount(arraytd.getArrayCount());
1055 type=state.getArrayNumber(supertd);
1057 type+=state.numClasses();
1060 cd=cd.getSuperDesc();
1063 outclassdefs.print(", ");
1064 outclassdefs.print(type);
1068 outclassdefs.println("};");
1073 outclassdefs.print("int typearray2[]={");
1074 for(int i=0; i<state.numArrays(); i++) {
1075 TypeDescriptor arraytd=arraytable[i];
1076 ClassDescriptor arraycd=arraytd.getClassDesc();
1077 if (arraycd==null) {
1079 outclassdefs.print(", ");
1080 outclassdefs.print("-1");
1084 ClassDescriptor cd=arraycd.getSuperDesc();
1085 int level=arraytd.getArrayCount()-1;
1087 for(; level>0; level--) {
1088 TypeDescriptor supertd=new TypeDescriptor(objectclass);
1089 supertd.setArrayCount(level);
1090 type=state.getArrayNumber(supertd);
1092 type+=state.numClasses();
1097 outclassdefs.print(", ");
1098 outclassdefs.print(type);
1102 outclassdefs.println("};");
1105 /** Constructs params and temp objects for each method or task.
1106 * These objects tell the compiler which temps need to be
1109 protected void generateTempStructs(FlatMethod fm, LocalityBinding lb) {
1110 MethodDescriptor md=fm.getMethod();
1111 TaskDescriptor task=fm.getTask();
1112 Set<TempDescriptor> saveset=lb!=null ? locality.getTempSet(lb) : null;
1113 ParamsObject objectparams=md!=null ? new ParamsObject(md,tag++) : new ParamsObject(task, tag++);
1115 paramstable.put(lb, objectparams);
1116 backuptable.put(lb, new Hashtable<TempDescriptor, TempDescriptor>());
1117 } else if (md!=null)
1118 paramstable.put(md, objectparams);
1120 paramstable.put(task, objectparams);
1122 for(int i=0; i<fm.numParameters(); i++) {
1123 TempDescriptor temp=fm.getParameter(i);
1124 TypeDescriptor type=temp.getType();
1125 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1126 objectparams.addPtr(temp);
1128 objectparams.addPrim(temp);
1129 if(lb!=null&&saveset.contains(temp)) {
1130 backuptable.get(lb).put(temp, temp.createNew());
1134 for(int i=0; i<fm.numTags(); i++) {
1135 TempDescriptor temp=fm.getTag(i);
1136 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1137 objectparams.addPtr(temp);
1139 objectparams.addPrim(temp);
1142 TempObject objecttemps=md!=null ? new TempObject(objectparams,md,tag++) : new TempObject(objectparams, task, tag++);
1144 tempstable.put(lb, objecttemps);
1146 tempstable.put(md, objecttemps);
1148 tempstable.put(task, objecttemps);
1150 for(Iterator nodeit=fm.getNodeSet().iterator(); nodeit.hasNext();) {
1151 FlatNode fn=(FlatNode)nodeit.next();
1152 TempDescriptor[] writes=fn.writesTemps();
1153 for(int i=0; i<writes.length; i++) {
1154 TempDescriptor temp=writes[i];
1155 TypeDescriptor type=temp.getType();
1156 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1157 objecttemps.addPtr(temp);
1159 objecttemps.addPrim(temp);
1160 if(lb!=null&&saveset.contains(temp)&&
1161 !backuptable.get(lb).containsKey(temp))
1162 backuptable.get(lb).put(temp, temp.createNew());
1166 /* Create backup temps */
1168 for(Iterator<TempDescriptor> tmpit=backuptable.get(lb).values().iterator(); tmpit.hasNext();) {
1169 TempDescriptor tmp=tmpit.next();
1170 TypeDescriptor type=tmp.getType();
1171 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1172 objecttemps.addPtr(tmp);
1174 objecttemps.addPrim(tmp);
1176 /* Create temp to hold revert table */
1177 if (state.DSM&&(lb.getHasAtomic()||lb.isAtomic())) {
1178 TempDescriptor reverttmp=new TempDescriptor("revertlist", typeutil.getClass(TypeUtil.ObjectClass));
1179 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1180 objecttemps.addPtr(reverttmp);
1182 objecttemps.addPrim(reverttmp);
1183 reverttable.put(lb, reverttmp);
1188 /** This method outputs the following information about classes
1190 * (1) For classes, what are the locations of pointers.
1191 * (2) For arrays, does the array contain pointers or primitives.
1192 * (3) For classes, does the class contain flags.
1195 private void generateLayoutStructs(PrintWriter output) {
1196 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1197 while(it.hasNext()) {
1198 ClassDescriptor cn=(ClassDescriptor)it.next();
1199 output.println("unsigned INTPTR "+cn.getSafeSymbol()+"_pointers[]={");
1200 Iterator allit=cn.getFieldTable().getAllDescriptorsIterator();
1202 while(allit.hasNext()) {
1203 FieldDescriptor fd=(FieldDescriptor)allit.next();
1204 TypeDescriptor type=fd.getType();
1205 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1210 output.print(count);
1211 allit=cn.getFieldTable().getAllDescriptorsIterator();
1212 while(allit.hasNext()) {
1213 FieldDescriptor fd=(FieldDescriptor)allit.next();
1214 TypeDescriptor type=fd.getType();
1215 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1218 output.println(",");
1219 output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+fd.getSafeSymbol()+"))");
1222 output.println("};");
1224 output.println("unsigned INTPTR * pointerarray[]={");
1225 boolean needcomma=false;
1226 for(int i=0; i<state.numClasses(); i++) {
1227 ClassDescriptor cn=cdarray[i];
1229 output.println(",");
1232 output.print(cn.getSafeSymbol()+"_pointers");
1234 output.print("NULL");
1238 for(int i=0; i<state.numArrays(); i++) {
1240 output.println(", ");
1241 TypeDescriptor tdelement=arraytable[i].dereference();
1242 if (tdelement.isArray()||tdelement.isClass())
1243 output.print("((unsigned INTPTR *)1)");
1249 output.println("};");
1251 output.println("int hasflags[]={");
1252 for(int i=0; i<state.numClasses(); i++) {
1253 ClassDescriptor cn=cdarray[i];
1255 output.println(", ");
1257 if ((cn != null) && (cn.hasFlags()))
1262 output.println("};");
1265 /** Print out table to give us supertypes */
1266 private void generateSuperTypeTable(PrintWriter output) {
1267 output.println("int supertypes[]={");
1268 boolean needcomma=false;
1269 for(int i=0; i<state.numClasses(); i++) {
1270 ClassDescriptor cn=cdarray[i];
1272 output.println(",");
1274 if ((cn != null) && (cn.getSuperDesc()!=null)) {
1275 ClassDescriptor cdsuper=cn.getSuperDesc();
1276 output.print(cdsuper.getId());
1280 output.println("};");
1283 /** Force consistent field ordering between inherited classes. */
1285 private void printClassStruct(ClassDescriptor cn, PrintWriter classdefout) {
1287 ClassDescriptor sp=cn.getSuperDesc();
1289 printClassStruct(sp, classdefout);
1291 if (!fieldorder.containsKey(cn)) {
1292 Vector fields=new Vector();
1293 fieldorder.put(cn,fields);
1294 Vector fieldvec=cn.getFieldVec();
1295 for(int i=0;i<fieldvec.size();i++) {
1296 FieldDescriptor fd=(FieldDescriptor)fieldvec.get(i);
1297 if ((sp==null||!sp.getFieldTable().contains(fd.getSymbol())))
1301 Vector fields=(Vector)fieldorder.get(cn);
1303 for(int i=0; i<fields.size(); i++) {
1304 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
1305 if (fd.getType().isClass()||fd.getType().isArray())
1306 classdefout.println(" struct "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1308 classdefout.println(" "+fd.getType().getSafeSymbol()+" "+fd.getSafeSymbol()+";");
1313 /* Map flags to integers consistently between inherited
1316 protected void mapFlags(ClassDescriptor cn) {
1317 ClassDescriptor sp=cn.getSuperDesc();
1321 if (!flagorder.containsKey(cn)) {
1322 Hashtable flags=new Hashtable();
1323 flagorder.put(cn,flags);
1325 Hashtable superflags=(Hashtable)flagorder.get(sp);
1326 Iterator superflagit=superflags.keySet().iterator();
1327 while(superflagit.hasNext()) {
1328 FlagDescriptor fd=(FlagDescriptor)superflagit.next();
1329 Integer number=(Integer)superflags.get(fd);
1330 flags.put(fd, number);
1331 if ((number.intValue()+1)>max)
1332 max=number.intValue()+1;
1336 Iterator flagit=cn.getFlags();
1337 while(flagit.hasNext()) {
1338 FlagDescriptor fd=(FlagDescriptor)flagit.next();
1339 if (sp==null||!sp.getFlagTable().contains(fd.getSymbol()))
1340 flags.put(fd, new Integer(max++));
1346 /** This function outputs (1) structures that parameters are
1347 * passed in (when PRECISE GC is enabled) and (2) function
1348 * prototypes for the methods */
1350 protected void generateCallStructs(ClassDescriptor cn, PrintWriter classdefout, PrintWriter output, PrintWriter headersout) {
1351 /* Output class structure */
1352 classdefout.println("struct "+cn.getSafeSymbol()+" {");
1353 classdefout.println(" int type;");
1355 classdefout.println(" pthread_t tid;");
1356 classdefout.println(" void * lockentry;");
1357 classdefout.println(" int lockcount;");
1361 classdefout.println(" int flag;");
1362 if((!state.MULTICORE) || (cn.getSymbol().equals("TagDescriptor"))) {
1363 classdefout.println(" void * flagptr;");
1364 } else if (state.MULTICORE) {
1365 classdefout.println(" int version;");
1366 classdefout.println(" int * lock;"); // lock entry for this obj
1367 classdefout.println(" int mutex;");
1368 classdefout.println(" int lockcount;");
1369 if(state.MULTICOREGC) {
1370 classdefout.println(" int marked;");
1373 if (state.OPTIONAL) {
1374 classdefout.println(" int numfses;");
1375 classdefout.println(" int * fses;");
1378 printClassStruct(cn, classdefout);
1379 classdefout.println("};\n");
1381 if (state.DSM||state.SINGLETM) {
1382 /* Cycle through LocalityBindings */
1383 HashSet<MethodDescriptor> nativemethods=new HashSet<MethodDescriptor>();
1384 Set<LocalityBinding> lbset=locality.getClassBindings(cn);
1386 for(Iterator<LocalityBinding> lbit=lbset.iterator(); lbit.hasNext();) {
1387 LocalityBinding lb=lbit.next();
1388 MethodDescriptor md=lb.getMethod();
1389 if (md.getModifiers().isNative()) {
1390 //make sure we only print a native method once
1391 if (nativemethods.contains(md)) {
1392 FlatMethod fm=state.getMethodFlat(md);
1393 generateTempStructs(fm, lb);
1396 nativemethods.add(md);
1398 generateMethod(cn, md, lb, headersout, output);
1401 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1402 MethodDescriptor md=(MethodDescriptor)methodit.next();
1403 if (md.getModifiers().isNative()&&!nativemethods.contains(md)) {
1404 //Need to build param structure for library code
1405 FlatMethod fm=state.getMethodFlat(md);
1406 generateTempStructs(fm, null);
1407 generateMethodParam(cn, md, null, output);
1412 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1413 MethodDescriptor md=(MethodDescriptor)methodit.next();
1414 generateMethod(cn, md, null, headersout, output);
1418 private void generateMethodParam(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter output) {
1419 /* Output parameter structure */
1420 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1421 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1422 if ((state.DSM||state.SINGLETM)&&lb!=null)
1423 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1425 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1426 output.println(" INTPTR size;");
1427 output.println(" void * next;");
1428 for(int i=0; i<objectparams.numPointers(); i++) {
1429 TempDescriptor temp=objectparams.getPointer(i);
1430 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1432 output.println("};\n");
1436 private void generateMethod(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter headersout, PrintWriter output) {
1437 FlatMethod fm=state.getMethodFlat(md);
1438 generateTempStructs(fm, lb);
1440 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1441 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md);
1443 generateMethodParam(cn, md, lb, output);
1445 /* Output temp structure */
1446 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1447 if (state.DSM||state.SINGLETM)
1448 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1450 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1451 output.println(" INTPTR size;");
1452 output.println(" void * next;");
1453 for(int i=0; i<objecttemps.numPointers(); i++) {
1454 TempDescriptor temp=objecttemps.getPointer(i);
1455 if (temp.getType().isNull())
1456 output.println(" void * "+temp.getSafeSymbol()+";");
1458 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1460 output.println("};\n");
1463 /********* Output method declaration ***********/
1464 if (state.DSM||state.SINGLETM) {
1465 headersout.println("#define D"+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1467 headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1469 /* First the return type */
1470 if (md.getReturnType()!=null) {
1471 if (md.getReturnType().isClass()||md.getReturnType().isArray())
1472 headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1474 headersout.print(md.getReturnType().getSafeSymbol()+" ");
1476 //catch the constructor case
1477 headersout.print("void ");
1479 /* Next the method name */
1480 if (state.DSM||state.SINGLETM) {
1481 headersout.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1483 headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1485 boolean printcomma=false;
1486 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1487 if (state.DSM||state.SINGLETM) {
1488 headersout.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1490 headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1494 /* Output parameter list*/
1495 for(int i=0; i<objectparams.numPrimitives(); i++) {
1496 TempDescriptor temp=objectparams.getPrimitive(i);
1498 headersout.print(", ");
1500 if (temp.getType().isClass()||temp.getType().isArray())
1501 headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1503 headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1505 headersout.println(");\n");
1509 /** This function outputs (1) structures that parameters are
1510 * passed in (when PRECISE GC is enabled) and (2) function
1511 * prototypes for the tasks */
1513 private void generateTaskStructs(PrintWriter output, PrintWriter headersout) {
1514 /* Cycle through tasks */
1515 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
1517 while(taskit.hasNext()) {
1518 /* Classify parameters */
1519 TaskDescriptor task=(TaskDescriptor)taskit.next();
1520 FlatMethod fm=state.getMethodFlat(task);
1521 generateTempStructs(fm, null);
1523 ParamsObject objectparams=(ParamsObject) paramstable.get(task);
1524 TempObject objecttemps=(TempObject) tempstable.get(task);
1526 /* Output parameter structure */
1527 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1528 output.println("struct "+task.getSafeSymbol()+"_params {");
1530 output.println(" INTPTR size;");
1531 output.println(" void * next;");
1532 for(int i=0; i<objectparams.numPointers(); i++) {
1533 TempDescriptor temp=objectparams.getPointer(i);
1534 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1537 output.println("};\n");
1538 if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
1539 maxtaskparams=objectparams.numPointers()+fm.numTags();
1543 /* Output temp structure */
1544 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1545 output.println("struct "+task.getSafeSymbol()+"_locals {");
1546 output.println(" INTPTR size;");
1547 output.println(" void * next;");
1548 for(int i=0; i<objecttemps.numPointers(); i++) {
1549 TempDescriptor temp=objecttemps.getPointer(i);
1550 if (temp.getType().isNull())
1551 output.println(" void * "+temp.getSafeSymbol()+";");
1552 else if(temp.getType().isTag())
1553 output.println(" struct "+
1554 (new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1556 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1558 output.println("};\n");
1561 /* Output task declaration */
1562 headersout.print("void " + task.getSafeSymbol()+"(");
1564 boolean printcomma=false;
1565 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1566 headersout.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
1568 headersout.print("void * parameterarray[]");
1569 headersout.println(");\n");
1573 /***** Generate code for FlatMethod fm. *****/
1575 Hashtable<FlatAtomicEnterNode, AtomicRecord> atomicmethodmap;
1576 static int atomicmethodcount=0;
1579 BranchAnalysis branchanalysis;
1580 private void generateFlatMethod(FlatMethod fm, LocalityBinding lb, PrintWriter output) {
1581 if (State.PRINTFLAT)
1582 System.out.println(fm.printMethod());
1583 MethodDescriptor md=fm.getMethod();
1584 TaskDescriptor task=fm.getTask();
1585 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
1586 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : md!=null ? md : task);
1588 HashSet<AtomicRecord> arset=null;
1589 branchanalysis=null;
1591 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1593 if (atomicmethodmap==null)
1594 atomicmethodmap=new Hashtable<FlatAtomicEnterNode, AtomicRecord>();
1596 //fix these so we get right strings for local variables
1597 localsprefixaddr=localsprefix;
1598 localsprefixderef=localsprefix+"->";
1599 arset=new HashSet<AtomicRecord>();
1601 //build branchanalysis
1602 branchanalysis=new BranchAnalysis(locality, lb, delaycomp.getNotReady(lb), delaycomp.livecode(lb), state);
1604 //Generate commit methods here
1605 for(Iterator<FlatNode> fnit=fm.getNodeSet().iterator();fnit.hasNext();) {
1606 FlatNode fn=fnit.next();
1607 if (fn.kind()==FKind.FlatAtomicEnterNode&&
1608 locality.getAtomic(lb).get(fn.getPrev(0)).intValue()==0&&
1609 delaycomp.needsFission(lb, (FlatAtomicEnterNode) fn)) {
1610 //We have an atomic enter
1611 FlatAtomicEnterNode faen=(FlatAtomicEnterNode) fn;
1612 Set<FlatNode> exitset=faen.getExits();
1614 String methodname=md.getSymbol()+(atomicmethodcount++);
1615 AtomicRecord ar=new AtomicRecord();
1619 atomicmethodmap.put(faen, ar);
1621 //build data structure declaration
1622 output.println("struct atomicprimitives_"+methodname+" {");
1624 Set<FlatNode> recordset=delaycomp.livecode(lb);
1625 Set<TempDescriptor> liveinto=delaycomp.liveinto(lb, faen, recordset);
1626 Set<TempDescriptor> liveout=delaycomp.liveout(lb, faen);
1627 Set<TempDescriptor> liveoutvirtualread=delaycomp.liveoutvirtualread(lb, faen);
1629 ar.reallivein=new HashSet(liveinto);
1631 ar.liveoutvirtualread=liveoutvirtualread;
1633 for(Iterator<TempDescriptor> it=liveinto.iterator(); it.hasNext();) {
1634 TempDescriptor tmp=it.next();
1635 //remove the pointers
1636 if (tmp.getType().isPtr()) {
1639 //let's print it here
1640 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1643 for(Iterator<TempDescriptor> it=liveout.iterator(); it.hasNext();) {
1644 TempDescriptor tmp=it.next();
1645 //remove the pointers
1646 if (tmp.getType().isPtr()) {
1648 } else if (!liveinto.contains(tmp)) {
1649 //let's print it here
1650 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1653 output.println("};");
1655 //print out method name
1656 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) {");
1657 //build code for commit method
1659 //first define local primitives
1660 Set<TempDescriptor> alltemps=delaycomp.alltemps(lb, faen, recordset);
1661 for(Iterator<TempDescriptor> tmpit=alltemps.iterator();tmpit.hasNext();) {
1662 TempDescriptor tmp=tmpit.next();
1663 if (!tmp.getType().isPtr()) {
1664 if (liveinto.contains(tmp)||liveoutvirtualread.contains(tmp)) {
1665 //read from live into set
1666 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+"=primitives->"+tmp.getSafeSymbol()+";");
1669 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1673 //turn off write barrier generation
1675 state.SINGLETM=false;
1676 generateCode(faen, fm, lb, exitset, output, false);
1677 state.SINGLETM=true;
1678 //turn on write barrier generation
1680 output.println("}\n\n");
1684 //redefine these back to normal
1686 localsprefixaddr="&"+localsprefix;
1687 localsprefixderef=localsprefix+".";
1689 generateHeader(fm, lb, md!=null ? md : task,output);
1690 TempObject objecttemp=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
1692 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1693 for(Iterator<AtomicRecord> arit=arset.iterator();arit.hasNext();) {
1694 AtomicRecord ar=arit.next();
1695 output.println("struct atomicprimitives_"+ar.name+" primitives_"+ar.name+";");
1699 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1700 if (md!=null&&(state.DSM||state.SINGLETM))
1701 output.print(" struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1702 else if (md!=null&&!(state.DSM||state.SINGLETM))
1703 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1705 output.print(" struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={");
1707 output.print(objecttemp.numPointers()+",");
1708 output.print(paramsprefix);
1709 for(int j=0; j<objecttemp.numPointers(); j++)
1710 output.print(", NULL");
1711 output.println("};");
1714 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1715 TempDescriptor td=objecttemp.getPrimitive(i);
1716 TypeDescriptor type=td.getType();
1718 output.println(" void * "+td.getSafeSymbol()+";");
1719 else if (type.isClass()||type.isArray())
1720 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1722 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1727 if( fm.getNext(0) instanceof FlatSESEEnterNode ) {
1728 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
1729 if( callerSESEplaceholder != mlpa.getMainSESE() ) {
1730 // declare variables for naming static SESE's
1731 output.println(" /* static SESE names */");
1732 Iterator<SESEandAgePair> pItr = callerSESEplaceholder.getNeededStaticNames().iterator();
1733 while( pItr.hasNext() ) {
1734 SESEandAgePair p = pItr.next();
1735 output.println(" void* "+p+";");
1738 // declare variables for tracking dynamic sources
1739 output.println(" /* dynamic variable sources */");
1740 Iterator<TempDescriptor> dynSrcItr = callerSESEplaceholder.getDynamicVarSet().iterator();
1741 while( dynSrcItr.hasNext() ) {
1742 TempDescriptor dynSrcVar = dynSrcItr.next();
1743 output.println(" void* "+dynSrcVar+"_srcSESE;");
1744 output.println(" int "+dynSrcVar+"_srcOffset;");
1749 // set up related allocation sites's waiting queues
1751 output.println(" /* set up waiting queues */");
1752 ConflictGraph graph=null;
1753 graph=mlpa.getConflictGraphResults().get(fm);
1755 Set<Integer> allocSet=graph.getAllocationSiteIDSet();
1757 if(allocSet.size()>0){
1758 output.println(" int numRelatedAllocSites="+allocSet.size()+";");
1759 output.println(" seseCaller->numRelatedAllocSites=numRelatedAllocSites;");
1760 output.println(" seseCaller->allocSiteArray=mlpCreateAllocSiteArray(numRelatedAllocSites);");
1762 for (Iterator iterator = allocSet.iterator(); iterator.hasNext();) {
1763 Integer allocID = (Integer) iterator.next();
1764 output.println(" seseCaller->allocSiteArray["+idx+"].id="+allocID+";");
1773 /* Check to see if we need to do a GC if this is a
1774 * multi-threaded program...*/
1776 if (((state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
1777 || this.state.MULTICOREGC) {
1778 //Don't bother if we aren't in recursive methods...The loops case will catch it
1779 if (callgraph.getAllMethods(md).contains(md)) {
1780 if (state.DSM&&lb.isAtomic())
1781 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
1782 else if (this.state.MULTICOREGC) {
1783 output.println("if(gcflag) gc("+localsprefixaddr+");");
1785 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
1790 generateCode(fm.getNext(0), fm, lb, null, output, true);
1792 output.println("}\n\n");
1796 protected void initializeSESE( FlatSESEEnterNode fsen ) {
1798 FlatMethod fm = fsen.getfmEnclosing();
1799 MethodDescriptor md = fm.getMethod();
1800 ClassDescriptor cn = md.getClassDesc();
1803 // Creates bogus method descriptor to index into tables
1804 Modifiers modBogus = new Modifiers();
1805 MethodDescriptor mdBogus =
1806 new MethodDescriptor( modBogus,
1807 new TypeDescriptor( TypeDescriptor.VOID ),
1808 "sese_"+fsen.getPrettyIdentifier()+fsen.getIdentifier()
1811 mdBogus.setClassDesc( fsen.getcdEnclosing() );
1812 FlatMethod fmBogus = new FlatMethod( mdBogus, null );
1813 fsen.setfmBogus( fmBogus );
1814 fsen.setmdBogus( mdBogus );
1816 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1817 inSetAndOutSet.addAll( fsen.getInVarSet() );
1818 inSetAndOutSet.addAll( fsen.getOutVarSet() );
1820 // Build paramsobj for bogus method descriptor
1821 ParamsObject objectparams = new ParamsObject( mdBogus, tag++ );
1822 paramstable.put( mdBogus, objectparams );
1824 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1825 while( itr.hasNext() ) {
1826 TempDescriptor temp = itr.next();
1827 TypeDescriptor type = temp.getType();
1828 if( type.isPtr() ) {
1829 objectparams.addPtr( temp );
1831 objectparams.addPrim( temp );
1835 // Build normal temp object for bogus method descriptor
1836 TempObject objecttemps = new TempObject( objectparams, mdBogus, tag++ );
1837 tempstable.put( mdBogus, objecttemps );
1839 for( Iterator nodeit = fsen.getNodeSet().iterator(); nodeit.hasNext(); ) {
1840 FlatNode fn = (FlatNode)nodeit.next();
1841 TempDescriptor[] writes = fn.writesTemps();
1843 for( int i = 0; i < writes.length; i++ ) {
1844 TempDescriptor temp = writes[i];
1845 TypeDescriptor type = temp.getType();
1847 if( type.isPtr() ) {
1848 objecttemps.addPtr( temp );
1850 objecttemps.addPrim( temp );
1856 protected void generateMethodSESE(FlatSESEEnterNode fsen,
1858 PrintWriter outputStructs,
1859 PrintWriter outputMethHead,
1860 PrintWriter outputMethods
1863 ParamsObject objectparams = (ParamsObject) paramstable.get( fsen.getmdBogus() );
1864 TempObject objecttemps = (TempObject) tempstable .get( fsen.getmdBogus() );
1866 // generate locals structure
1867 outputStructs.println("struct "+
1868 fsen.getcdEnclosing().getSafeSymbol()+
1869 fsen.getmdBogus().getSafeSymbol()+"_"+
1870 fsen.getmdBogus().getSafeMethodDescriptor()+
1872 outputStructs.println(" INTPTR size;");
1873 outputStructs.println(" void * next;");
1874 for(int i=0; i<objecttemps.numPointers(); i++) {
1875 TempDescriptor temp=objecttemps.getPointer(i);
1877 if( fsen.getPrettyIdentifier().equals( "calc" ) ) {
1878 System.out.println( " got a pointer "+temp );
1881 if (temp.getType().isNull())
1882 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
1884 outputStructs.println(" struct "+
1885 temp.getType().getSafeSymbol()+" * "+
1886 temp.getSafeSymbol()+";");
1888 outputStructs.println("};\n");
1891 // generate the SESE record structure
1892 outputStructs.println(fsen.getSESErecordName()+" {");
1894 // data common to any SESE, and it must be placed first so
1895 // a module that doesn't know what kind of SESE record this
1896 // is can cast the pointer to a common struct
1897 outputStructs.println(" SESEcommon common;");
1899 // then garbage list stuff
1900 outputStructs.println(" INTPTR size;");
1901 outputStructs.println(" void * next;");
1903 // in-set source tracking
1904 // in-vars that are READY come from parent, don't need anything
1905 // stuff STATIC needs a custom SESE pointer for each age pair
1906 Iterator<SESEandAgePair> itrStaticInVarSrcs = fsen.getStaticInVarSrcs().iterator();
1907 while( itrStaticInVarSrcs.hasNext() ) {
1908 SESEandAgePair srcPair = itrStaticInVarSrcs.next();
1909 outputStructs.println(" "+srcPair.getSESE().getSESErecordName()+"* "+srcPair+";");
1912 // DYNAMIC stuff needs a source SESE ptr and offset
1913 Iterator<TempDescriptor> itrDynInVars = fsen.getDynamicInVarSet().iterator();
1914 while( itrDynInVars.hasNext() ) {
1915 TempDescriptor dynInVar = itrDynInVars.next();
1916 outputStructs.println(" void* "+dynInVar+"_srcSESE;");
1917 outputStructs.println(" int "+dynInVar+"_srcOffset;");
1920 // space for all in and out set primitives
1921 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1922 inSetAndOutSet.addAll( fsen.getInVarSet() );
1923 inSetAndOutSet.addAll( fsen.getOutVarSet() );
1925 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
1927 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1928 while( itr.hasNext() ) {
1929 TempDescriptor temp = itr.next();
1930 TypeDescriptor type = temp.getType();
1931 if( !type.isPtr() ) {
1932 inSetAndOutSetPrims.add( temp );
1936 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
1937 while( itrPrims.hasNext() ) {
1938 TempDescriptor temp = itrPrims.next();
1939 TypeDescriptor type = temp.getType();
1940 outputStructs.println(" "+temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol()+";");
1943 for(int i=0; i<objectparams.numPointers(); i++) {
1944 TempDescriptor temp=objectparams.getPointer(i);
1945 if (temp.getType().isNull())
1946 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
1948 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1951 outputStructs.println("};\n");
1954 // write method declaration to header file
1955 outputMethHead.print("void ");
1956 outputMethHead.print(fsen.getSESEmethodName()+"(");
1957 outputMethHead.print(fsen.getSESErecordName()+"* "+paramsprefix);
1958 outputMethHead.println(");\n");
1961 generateFlatMethodSESE( fsen.getfmBogus(),
1962 fsen.getcdEnclosing(),
1968 private void generateFlatMethodSESE(FlatMethod fm,
1970 FlatSESEEnterNode fsen,
1971 FlatSESEExitNode seseExit,
1975 MethodDescriptor md=fm.getMethod();
1977 output.print("void ");
1978 output.print(fsen.getSESEmethodName()+"(");
1979 output.print(fsen.getSESErecordName()+"* "+paramsprefix);
1980 output.println("){\n");
1982 TempObject objecttemp=(TempObject) tempstable.get(md);
1984 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1985 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1986 output.print(objecttemp.numPointers()+",");
1987 output.print("(void*) &("+paramsprefix+"->size)");
1988 for(int j=0; j<objecttemp.numPointers(); j++)
1989 output.print(", NULL");
1990 output.println("};");
1993 output.println(" /* regular local primitives */");
1994 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1995 TempDescriptor td=objecttemp.getPrimitive(i);
1996 TypeDescriptor type=td.getType();
1998 output.println(" void * "+td.getSafeSymbol()+";");
1999 else if (type.isClass()||type.isArray())
2000 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
2002 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
2006 // declare variables for naming static SESE's
2007 output.println(" /* static SESE names */");
2008 Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
2009 while( pItr.hasNext() ) {
2010 SESEandAgePair p = pItr.next();
2011 output.println(" void* "+p+";");
2014 // declare variables for tracking dynamic sources
2015 output.println(" /* dynamic variable sources */");
2016 Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
2017 while( dynSrcItr.hasNext() ) {
2018 TempDescriptor dynSrcVar = dynSrcItr.next();
2019 output.println(" void* "+dynSrcVar+"_srcSESE;");
2020 output.println(" int "+dynSrcVar+"_srcOffset;");
2023 // declare local temps for in-set primitives, and if it is
2024 // a ready-source variable, get the value from the record
2025 output.println(" /* local temps for in-set primitives */");
2026 Iterator<TempDescriptor> itrInSet = fsen.getInVarSet().iterator();
2027 while( itrInSet.hasNext() ) {
2028 TempDescriptor temp = itrInSet.next();
2029 TypeDescriptor type = temp.getType();
2030 if( !type.isPtr() ) {
2031 if( fsen.getReadyInVarSet().contains( temp ) ) {
2032 output.println(" "+type+" "+temp+" = "+paramsprefix+"->"+temp+";");
2034 output.println(" "+type+" "+temp+";");
2039 // declare local temps for out-set primitives if its not already
2040 // in the in-set, and it's value will get written so no problem
2041 output.println(" /* local temp for out-set prim, not already in the in-set */");
2042 Iterator<TempDescriptor> itrOutSet = fsen.getOutVarSet().iterator();
2043 while( itrOutSet.hasNext() ) {
2044 TempDescriptor temp = itrOutSet.next();
2045 TypeDescriptor type = temp.getType();
2046 if( !type.isPtr() && !fsen.getInVarSet().contains( temp ) ) {
2047 output.println(" "+type+" "+temp+";");
2051 // copy in-set into place, ready vars were already
2052 // copied when the SESE was issued
2053 Iterator<TempDescriptor> tempItr;
2055 // static vars are from a known SESE
2056 tempItr = fsen.getStaticInVarSet().iterator();
2057 while( tempItr.hasNext() ) {
2058 TempDescriptor temp = tempItr.next();
2059 VariableSourceToken vst = fsen.getStaticInVarSrc( temp );
2060 SESEandAgePair srcPair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2062 // can't grab something from this source until it is done
2063 output.println(" {");
2064 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+srcPair+";" );
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) );");
2071 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2072 " = "+paramsprefix+"->"+srcPair+"->"+vst.getAddrVar()+";");
2074 output.println(" }");
2077 // dynamic vars come from an SESE and src
2078 tempItr = fsen.getDynamicInVarSet().iterator();
2079 while( tempItr.hasNext() ) {
2080 TempDescriptor temp = tempItr.next();
2081 TypeDescriptor type = temp.getType();
2083 // go grab it from the SESE source
2084 output.println(" if( "+paramsprefix+"->"+temp+"_srcSESE != NULL ) {");
2086 // gotta wait until the source is done
2087 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+temp+"_srcSESE;" );
2088 output.println(" pthread_mutex_lock( &(com->lock) );");
2089 output.println(" while( com->doneExecuting == FALSE ) {");
2090 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
2091 output.println(" }");
2092 output.println(" pthread_mutex_unlock( &(com->lock) );");
2095 if( type.isNull() ) {
2097 } else if( type.isClass() || type.isArray() ) {
2098 typeStr = "struct "+type.getSafeSymbol()+"*";
2100 typeStr = type.getSafeSymbol();
2103 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2104 " = *(("+typeStr+"*) ("+
2105 paramsprefix+"->"+temp+"_srcSESE + "+
2106 paramsprefix+"->"+temp+"_srcOffset));");
2108 // or if the source was our parent, its in the record to grab
2109 output.println(" } else {");
2110 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2111 " = "+paramsprefix+"->"+temp+";");
2112 output.println(" }");
2115 // Check to see if we need to do a GC if this is a
2116 // multi-threaded program...
2117 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2118 //Don't bother if we aren't in recursive methods...The loops case will catch it
2119 if (callgraph.getAllMethods(md).contains(md)) {
2120 if(this.state.MULTICOREGC) {
2121 output.println("if(gcflag) gc("+localsprefixaddr+");");
2123 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2128 // initialize thread-local var to a non-zero, invalid address
2129 output.println(" seseCaller = (SESEcommon*) 0x2;");
2130 HashSet<FlatNode> exitset=new HashSet<FlatNode>();
2131 exitset.add(seseExit);
2132 generateCode(fsen.getNext(0), fm, null, exitset, output, true);
2133 output.println("}\n\n");
2137 // when a new mlp thread is created for an issued SESE, it is started
2138 // by running this method which blocks on a cond variable until
2139 // it is allowed to transition to execute. Then a case statement
2140 // allows it to invoke the method with the proper SESE body, and after
2141 // exiting the SESE method, executes proper SESE exit code before the
2142 // thread can be destroyed
2143 private void generateSESEinvocationMethod(PrintWriter outmethodheader,
2144 PrintWriter outmethod
2147 outmethodheader.println("void* invokeSESEmethod( void* seseRecord );");
2148 outmethod.println( "void* invokeSESEmethod( void* seseRecord ) {");
2149 outmethod.println( " int status;");
2150 outmethod.println( " char errmsg[128];");
2152 // generate a case for each SESE class that can be invoked
2153 outmethod.println( " switch( *((int*)seseRecord) ) {");
2154 outmethod.println( " ");
2155 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
2156 FlatSESEEnterNode fsen = seseit.next();
2158 outmethod.println( " /* "+fsen.getPrettyIdentifier()+" */");
2159 outmethod.println( " case "+fsen.getIdentifier()+":");
2160 outmethod.println( " "+fsen.getSESEmethodName()+"( seseRecord );");
2162 if( fsen.equals( mlpa.getMainSESE() ) ) {
2163 outmethod.println( " /* work scheduler works forever, explicitly exit */");
2164 outmethod.println( " exit( 0 );");
2167 outmethod.println( " break;");
2168 outmethod.println( "");
2171 // default case should never be taken, error out
2172 outmethod.println( " default:");
2173 outmethod.println( " printf(\"Error: unknown SESE class ID in invoke method.\\n\");");
2174 outmethod.println( " exit(-30);");
2175 outmethod.println( " break;");
2176 outmethod.println( " }");
2177 outmethod.println( " return NULL;");
2178 outmethod.println( "}\n\n");
2182 protected void generateCode(FlatNode first,
2185 Set<FlatNode> stopset,
2186 PrintWriter output, boolean firstpass) {
2188 /* Assign labels to FlatNode's if necessary.*/
2190 Hashtable<FlatNode, Integer> nodetolabel;
2192 if (state.DELAYCOMP&&!firstpass)
2193 nodetolabel=dcassignLabels(first, stopset);
2195 nodetolabel=assignLabels(first, stopset);
2197 Set<FlatNode> storeset=null;
2198 HashSet<FlatNode> genset=null;
2199 HashSet<FlatNode> refset=null;
2200 Set<FlatNode> unionset=null;
2202 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
2203 storeset=delaycomp.livecode(lb);
2204 genset=new HashSet<FlatNode>();
2205 if (state.STMARRAY&&!state.DUALVIEW) {
2206 refset=new HashSet<FlatNode>();
2207 refset.addAll(delaycomp.getDeref(lb));
2208 refset.removeAll(delaycomp.getCannotDelay(lb));
2209 refset.removeAll(delaycomp.getOther(lb));
2212 genset.addAll(delaycomp.getCannotDelay(lb));
2213 genset.addAll(delaycomp.getOther(lb));
2215 genset.addAll(delaycomp.getNotReady(lb));
2216 if (state.STMARRAY&&!state.DUALVIEW) {
2217 genset.removeAll(refset);
2220 unionset=new HashSet<FlatNode>();
2221 unionset.addAll(storeset);
2222 unionset.addAll(genset);
2223 if (state.STMARRAY&&!state.DUALVIEW)
2224 unionset.addAll(refset);
2227 /* Do the actual code generation */
2228 FlatNode current_node=null;
2229 HashSet tovisit=new HashSet();
2230 HashSet visited=new HashSet();
2232 tovisit.add(first.getNext(0));
2235 while(current_node!=null||!tovisit.isEmpty()) {
2236 if (current_node==null) {
2237 current_node=(FlatNode)tovisit.iterator().next();
2238 tovisit.remove(current_node);
2239 } else if (tovisit.contains(current_node)) {
2240 tovisit.remove(current_node);
2242 visited.add(current_node);
2243 if (nodetolabel.containsKey(current_node)) {
2244 output.println("L"+nodetolabel.get(current_node)+":");
2246 if (state.INSTRUCTIONFAILURE) {
2247 if (state.THREAD||state.DSM||state.SINGLETM) {
2248 output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
2250 output.println("if ((--instructioncount)==0) injectinstructionfailure();");
2252 if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
2254 if (!state.DELAYCOMP||firstpass) {
2255 generateFlatNode(fm, lb, current_node, output);
2257 //store primitive variables in out set
2258 AtomicRecord ar=atomicmethodmap.get((FlatAtomicEnterNode)first);
2259 Set<TempDescriptor> liveout=ar.liveout;
2260 for(Iterator<TempDescriptor> tmpit=liveout.iterator();tmpit.hasNext();) {
2261 TempDescriptor tmp=tmpit.next();
2262 output.println("primitives->"+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2265 if (state.MLP && stopset!=null) {
2266 assert first.getPrev( 0 ) instanceof FlatSESEEnterNode;
2267 assert current_node instanceof FlatSESEExitNode;
2268 FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev( 0 );
2269 FlatSESEExitNode fsxn = (FlatSESEExitNode) current_node;
2270 assert fsen.getFlatExit().equals( fsxn );
2271 assert fsxn.getFlatEnter().equals( fsen );
2273 if (current_node.kind()!=FKind.FlatReturnNode) {
2274 output.println(" return;");
2277 } else if(current_node.numNext()==1) {
2280 current_node.kind()==FKind.FlatSESEEnterNode &&
2281 !((FlatSESEEnterNode)current_node).getIsCallerSESEplaceholder()
2283 FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
2284 generateFlatNode(fm, lb, current_node, output);
2285 nextnode=fsen.getFlatExit().getNext(0);
2286 } else if (state.DELAYCOMP) {
2287 boolean specialprimitive=false;
2288 //skip literals...no need to add extra overhead
2289 if (storeset!=null&&storeset.contains(current_node)&¤t_node.kind()==FKind.FlatLiteralNode) {
2290 TypeDescriptor typedesc=((FlatLiteralNode)current_node).getType();
2291 if (!typedesc.isClass()&&!typedesc.isArray()) {
2292 specialprimitive=true;
2296 if (genset==null||genset.contains(current_node)||specialprimitive)
2297 generateFlatNode(fm, lb, current_node, output);
2298 if (state.STMARRAY&&!state.DUALVIEW&&refset!=null&&refset.contains(current_node)) {
2299 //need to acquire lock
2300 handleArrayDeref(fm, lb, current_node, output, firstpass);
2302 if (storeset!=null&&storeset.contains(current_node)&&!specialprimitive) {
2303 TempDescriptor wrtmp=current_node.writesTemps()[0];
2305 //need to store value written by previous node
2306 if (wrtmp.getType().isPtr()) {
2307 //only lock the objects that may actually need locking
2308 if (recorddc.getNeedTrans(lb, current_node)&&
2309 (!state.STMARRAY||state.DUALVIEW||!wrtmp.getType().isArray()||
2310 wrtmp.getType().getSymbol().equals(TypeUtil.ObjectClass))) {
2311 output.println("STOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2313 output.println("STOREPTRNOLOCK("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2316 output.println("STORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");/* "+current_node.nodeid+" */");
2319 //need to read value read by previous node
2320 if (wrtmp.getType().isPtr()) {
2321 output.println("RESTOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2323 output.println("RESTORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+"); /* "+current_node.nodeid+" */");
2327 nextnode=current_node.getNext(0);
2330 generateFlatNode(fm, lb, current_node, output);
2331 nextnode=current_node.getNext(0);
2333 if (visited.contains(nextnode)) {
2334 output.println("goto L"+nodetolabel.get(nextnode)+";");
2337 current_node=nextnode;
2338 } else if (current_node.numNext()==2) {
2340 if (state.DELAYCOMP) {
2341 boolean computeside=false;
2343 //need to record which way it should go
2344 if (genset==null||genset.contains(current_node)) {
2345 if (storeset!=null&&storeset.contains(current_node)) {
2346 //need to store which way branch goes
2347 generateStoreFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2349 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2351 //which side to execute
2355 if (genset.contains(current_node)) {
2356 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2357 } else if (storeset.contains(current_node)) {
2359 branchanalysis.generateGroupCode(current_node, output, nodetolabel);
2361 //which side to execute
2366 Set<FlatNode> leftset=DelayComputation.getNext(current_node, 0, unionset, lb,locality, true);
2368 if (leftset.size()==0)
2370 if (visited.contains(current_node.getNext(branch))) {
2371 //already visited -- build jump
2372 output.println("goto L"+nodetolabel.get(current_node.getNext(branch))+";");
2375 current_node=current_node.getNext(branch);
2378 if (!visited.contains(current_node.getNext(1)))
2379 tovisit.add(current_node.getNext(1));
2380 if (visited.contains(current_node.getNext(0))) {
2381 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2384 current_node=current_node.getNext(0);
2388 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2389 if (!visited.contains(current_node.getNext(1)))
2390 tovisit.add(current_node.getNext(1));
2391 if (visited.contains(current_node.getNext(0))) {
2392 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2395 current_node=current_node.getNext(0);
2397 } else throw new Error();
2401 protected void handleArrayDeref(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output, boolean firstpass) {
2402 if (fn.kind()==FKind.FlatSetElementNode) {
2403 FlatSetElementNode fsen=(FlatSetElementNode) fn;
2404 String dst=generateTemp(fm, fsen.getDst(), lb);
2405 String src=generateTemp(fm, fsen.getSrc(), lb);
2406 String index=generateTemp(fm, fsen.getIndex(), lb);
2407 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
2409 if (elementtype.isArray()||elementtype.isClass())
2412 type=elementtype.getSafeSymbol()+" ";
2414 output.println("STOREARRAY("+dst+","+index+","+type+")");
2416 output.println("{");
2417 output.println(" struct ArrayObject *array;");
2418 output.println(" int index;");
2419 output.println(" RESTOREARRAY(array,index);");
2420 output.println(" (("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index]="+src+";");
2421 output.println("}");
2423 } else if (fn.kind()==FKind.FlatElementNode) {
2424 FlatElementNode fen=(FlatElementNode) fn;
2425 String src=generateTemp(fm, fen.getSrc(), lb);
2426 String index=generateTemp(fm, fen.getIndex(), lb);
2427 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
2428 String dst=generateTemp(fm, fen.getDst(), lb);
2430 if (elementtype.isArray()||elementtype.isClass())
2433 type=elementtype.getSafeSymbol()+" ";
2435 output.println("STOREARRAY("+src+","+index+","+type+")");
2437 output.println("{");
2438 output.println(" struct ArrayObject *array;");
2439 output.println(" int index;");
2440 output.println(" RESTOREARRAY(array,index);");
2441 output.println(" "+dst+"=(("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index];");
2442 output.println("}");
2446 /** Special label assignment for delaycomputation */
2447 protected Hashtable<FlatNode, Integer> dcassignLabels(FlatNode first, Set<FlatNode> lastset) {
2448 HashSet tovisit=new HashSet();
2449 HashSet visited=new HashSet();
2451 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2453 //Label targets of branches
2454 Set<FlatNode> targets=branchanalysis.getTargets();
2455 for(Iterator<FlatNode> it=targets.iterator();it.hasNext();) {
2456 nodetolabel.put(it.next(), new Integer(labelindex++));
2461 /*Assign labels first. A node needs a label if the previous
2462 * node has two exits or this node is a join point. */
2464 while(!tovisit.isEmpty()) {
2465 FlatNode fn=(FlatNode)tovisit.iterator().next();
2470 if(lastset!=null&&lastset.contains(fn)) {
2471 // if last is not null and matches, don't go
2472 // any further for assigning labels
2476 for(int i=0; i<fn.numNext(); i++) {
2477 FlatNode nn=fn.getNext(i);
2480 //1) Edge >1 of node
2481 nodetolabel.put(nn,new Integer(labelindex++));
2483 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2487 nodetolabel.put(nn,new Integer(labelindex++));
2495 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first) {
2496 return assignLabels(first, null);
2499 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
2500 HashSet tovisit=new HashSet();
2501 HashSet visited=new HashSet();
2503 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2506 /*Assign labels first. A node needs a label if the previous
2507 * node has two exits or this node is a join point. */
2509 while(!tovisit.isEmpty()) {
2510 FlatNode fn=(FlatNode)tovisit.iterator().next();
2515 if(lastset!=null&&lastset.contains(fn)) {
2516 // if last is not null and matches, don't go
2517 // any further for assigning labels
2521 for(int i=0; i<fn.numNext(); i++) {
2522 FlatNode nn=fn.getNext(i);
2525 //1) Edge >1 of node
2526 nodetolabel.put(nn,new Integer(labelindex++));
2528 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2532 nodetolabel.put(nn,new Integer(labelindex++));
2540 /** Generate text string that corresponds to the TempDescriptor td. */
2541 protected String generateTemp(FlatMethod fm, TempDescriptor td, LocalityBinding lb) {
2542 MethodDescriptor md=fm.getMethod();
2543 TaskDescriptor task=fm.getTask();
2544 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
2546 if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
2547 //System.out.println("generateTemp returns " + td.getSafeSymbol());
2548 return td.getSafeSymbol();
2551 if (objecttemps.isLocalPtr(td)) {
2552 return localsprefixderef+td.getSafeSymbol();
2555 if (objecttemps.isParamPtr(td)) {
2556 return paramsprefix+"->"+td.getSafeSymbol();
2562 protected void generateFlatNode(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output) {
2564 // insert pre-node actions from the code plan
2567 CodePlan cp = mlpa.getCodePlan( fn );
2570 FlatSESEEnterNode currentSESE = cp.getCurrentSESE();
2572 // for each sese and age pair that this parent statement
2573 // must stall on, take that child's stall semaphore, the
2574 // copying of values comes after the statement
2575 Iterator<VariableSourceToken> vstItr = cp.getStallTokens().iterator();
2576 while( vstItr.hasNext() ) {
2577 VariableSourceToken vst = vstItr.next();
2579 SESEandAgePair p = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2581 output.println(" {");
2582 output.println(" SESEcommon* common = (SESEcommon*) "+p+";");
2584 output.println(" pthread_mutex_lock( &(common->lock) );");
2585 output.println(" while( common->doneExecuting == FALSE ) {");
2586 output.println(" pthread_cond_wait( &(common->doneCond), &(common->lock) );");
2587 output.println(" }");
2588 output.println(" pthread_mutex_unlock( &(common->lock) );");
2590 //output.println(" psem_take( &(common->stallSem) );");
2592 // copy things we might have stalled for
2593 output.println(" "+p.getSESE().getSESErecordName()+"* child = ("+
2594 p.getSESE().getSESErecordName()+"*) "+p+";");
2596 Iterator<TempDescriptor> tdItr = cp.getCopySet( vst ).iterator();
2597 while( tdItr.hasNext() ) {
2598 TempDescriptor td = tdItr.next();
2599 FlatMethod fmContext;
2600 if( currentSESE.getIsCallerSESEplaceholder() ) {
2601 fmContext = currentSESE.getfmEnclosing();
2603 fmContext = currentSESE.getfmBogus();
2605 output.println(" "+generateTemp( fmContext, td, null )+
2606 " = child->"+vst.getAddrVar().getSafeSymbol()+";");
2609 output.println(" }");
2612 // for each variable with a dynamic source, stall just for that variable
2613 Iterator<TempDescriptor> dynItr = cp.getDynamicStallSet().iterator();
2614 while( dynItr.hasNext() ) {
2615 TempDescriptor dynVar = dynItr.next();
2617 // only stall if the dynamic source is not yourself, denoted by src==NULL
2618 // otherwise the dynamic write nodes will have the local var up-to-date
2619 output.println(" {");
2620 output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
2621 output.println(" SESEcommon* common = (SESEcommon*) "+dynVar+"_srcSESE;");
2622 output.println(" psem_take( &(common->stallSem) );");
2624 FlatMethod fmContext;
2625 if( currentSESE.getIsCallerSESEplaceholder() ) {
2626 fmContext = currentSESE.getfmEnclosing();
2628 fmContext = currentSESE.getfmBogus();
2630 output.println(" "+generateTemp( fmContext, dynVar, null )+
2631 " = *(("+dynVar.getType()+"*) ("+
2632 dynVar+"_srcSESE + "+dynVar+"_srcOffset));");
2634 output.println(" }");
2635 output.println(" }");
2638 // for each assignment of a variable to rhs that has a dynamic source,
2639 // copy the dynamic sources
2640 Iterator dynAssignItr = cp.getDynAssigns().entrySet().iterator();
2641 while( dynAssignItr.hasNext() ) {
2642 Map.Entry me = (Map.Entry) dynAssignItr.next();
2643 TempDescriptor lhs = (TempDescriptor) me.getKey();
2644 TempDescriptor rhs = (TempDescriptor) me.getValue();
2645 output.println(" "+lhs+"_srcSESE = "+rhs+"_srcSESE;");
2646 output.println(" "+lhs+"_srcOffset = "+rhs+"_srcOffset;");
2649 // for each lhs that is dynamic from a non-dynamic source, set the
2650 // dynamic source vars to the current SESE
2651 dynItr = cp.getDynAssignCurr().iterator();
2652 while( dynItr.hasNext() ) {
2653 TempDescriptor dynVar = dynItr.next();
2654 output.println(" "+dynVar+"_srcSESE = NULL;");
2660 case FKind.FlatAtomicEnterNode:
2661 generateFlatAtomicEnterNode(fm, lb, (FlatAtomicEnterNode) fn, output);
2664 case FKind.FlatAtomicExitNode:
2665 generateFlatAtomicExitNode(fm, lb, (FlatAtomicExitNode) fn, output);
2668 case FKind.FlatInstanceOfNode:
2669 generateFlatInstanceOfNode(fm, lb, (FlatInstanceOfNode)fn, output);
2672 case FKind.FlatSESEEnterNode:
2673 generateFlatSESEEnterNode(fm, lb, (FlatSESEEnterNode)fn, output);
2676 case FKind.FlatSESEExitNode:
2677 generateFlatSESEExitNode(fm, lb, (FlatSESEExitNode)fn, output);
2680 case FKind.FlatWriteDynamicVarNode:
2681 generateFlatWriteDynamicVarNode(fm, lb, (FlatWriteDynamicVarNode)fn, output);
2684 case FKind.FlatGlobalConvNode:
2685 generateFlatGlobalConvNode(fm, lb, (FlatGlobalConvNode) fn, output);
2688 case FKind.FlatTagDeclaration:
2689 generateFlatTagDeclaration(fm, lb, (FlatTagDeclaration) fn,output);
2692 case FKind.FlatCall:
2693 generateFlatCall(fm, lb, (FlatCall) fn,output);
2696 case FKind.FlatFieldNode:
2697 generateFlatFieldNode(fm, lb, (FlatFieldNode) fn,output);
2700 case FKind.FlatElementNode:
2701 generateFlatElementNode(fm, lb, (FlatElementNode) fn,output);
2704 case FKind.FlatSetElementNode:
2705 generateFlatSetElementNode(fm, lb, (FlatSetElementNode) fn,output);
2708 case FKind.FlatSetFieldNode:
2709 generateFlatSetFieldNode(fm, lb, (FlatSetFieldNode) fn,output);
2713 generateFlatNew(fm, lb, (FlatNew) fn,output);
2716 case FKind.FlatOpNode:
2717 generateFlatOpNode(fm, lb, (FlatOpNode) fn,output);
2720 case FKind.FlatCastNode:
2721 generateFlatCastNode(fm, lb, (FlatCastNode) fn,output);
2724 case FKind.FlatLiteralNode:
2725 generateFlatLiteralNode(fm, lb, (FlatLiteralNode) fn,output);
2728 case FKind.FlatReturnNode:
2729 generateFlatReturnNode(fm, lb, (FlatReturnNode) fn,output);
2733 output.println("/* nop */");
2736 case FKind.FlatExit:
2737 output.println("/* exit */");
2740 case FKind.FlatBackEdge:
2741 if (state.SINGLETM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
2742 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
2744 if (((state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
2745 || (this.state.MULTICOREGC)) {
2746 if(state.DSM&&locality.getAtomic(lb).get(fn).intValue()>0) {
2747 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
2748 } else if(this.state.MULTICOREGC) {
2749 output.println("if (gcflag) gc("+localsprefixaddr+");");
2751 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2754 output.println("/* nop */");
2757 case FKind.FlatCheckNode:
2758 generateFlatCheckNode(fm, lb, (FlatCheckNode) fn, output);
2761 case FKind.FlatFlagActionNode:
2762 generateFlatFlagActionNode(fm, lb, (FlatFlagActionNode) fn, output);
2765 case FKind.FlatPrefetchNode:
2766 generateFlatPrefetchNode(fm,lb, (FlatPrefetchNode) fn, output);
2769 case FKind.FlatOffsetNode:
2770 generateFlatOffsetNode(fm, lb, (FlatOffsetNode)fn, output);
2777 // insert post-node actions from the code-plan
2779 CodePlan cp = mlpa.getCodePlan( fn );
2786 public void generateFlatOffsetNode(FlatMethod fm, LocalityBinding lb, FlatOffsetNode fofn, PrintWriter output) {
2787 output.println("/* FlatOffsetNode */");
2788 FieldDescriptor fd=fofn.getField();
2789 output.println(generateTemp(fm, fofn.getDst(),lb)+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+ fd.getSafeSymbol()+");");
2790 output.println("/* offset */");
2793 public void generateFlatPrefetchNode(FlatMethod fm, LocalityBinding lb, FlatPrefetchNode fpn, PrintWriter output) {
2794 if (state.PREFETCH) {
2795 Vector oids = new Vector();
2796 Vector fieldoffset = new Vector();
2797 Vector endoffset = new Vector();
2798 int tuplecount = 0; //Keeps track of number of prefetch tuples that need to be generated
2799 for(Iterator it = fpn.hspp.iterator(); it.hasNext();) {
2800 PrefetchPair pp = (PrefetchPair) it.next();
2801 Integer statusbase = locality.getNodePreTempInfo(lb,fpn).get(pp.base);
2802 /* Find prefetches that can generate oid */
2803 if(statusbase == LocalityAnalysis.GLOBAL) {
2804 generateTransCode(fm, lb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(lb).get(fpn).intValue()>0, false);
2806 } else if (statusbase == LocalityAnalysis.LOCAL) {
2807 generateTransCode(fm,lb,pp,oids,fieldoffset,endoffset,tuplecount,false,true);
2814 System.out.println("Adding prefetch "+fpn+ " to method:" +fm);
2815 output.println("{");
2816 output.println("/* prefetch */");
2817 output.println("/* prefetchid_" + fpn.siteid + " */");
2818 output.println("void * prefptr;");
2819 output.println("int tmpindex;");
2821 output.println("if((evalPrefetch["+fpn.siteid+"].operMode) || (evalPrefetch["+fpn.siteid+"].retrycount <= 0)) {");
2822 /*Create C code for oid array */
2823 output.print(" unsigned int oidarray_[] = {");
2824 boolean needcomma=false;
2825 for (Iterator it = oids.iterator(); it.hasNext();) {
2828 output.print(it.next());
2831 output.println("};");
2833 /*Create C code for endoffset values */
2834 output.print(" unsigned short endoffsetarry_[] = {");
2836 for (Iterator it = endoffset.iterator(); it.hasNext();) {
2839 output.print(it.next());
2842 output.println("};");
2844 /*Create C code for Field Offset Values */
2845 output.print(" short fieldarry_[] = {");
2847 for (Iterator it = fieldoffset.iterator(); it.hasNext();) {
2850 output.print(it.next());
2853 output.println("};");
2854 /* make the prefetch call to Runtime */
2855 output.println(" if(!evalPrefetch["+fpn.siteid+"].operMode) {");
2856 output.println(" evalPrefetch["+fpn.siteid+"].retrycount = RETRYINTERVAL;");
2857 output.println(" }");
2858 output.println(" prefetch("+fpn.siteid+" ,"+tuplecount+", oidarray_, endoffsetarry_, fieldarry_);");
2859 output.println(" } else {");
2860 output.println(" evalPrefetch["+fpn.siteid+"].retrycount--;");
2861 output.println(" }");
2862 output.println("}");
2866 public void generateTransCode(FlatMethod fm, LocalityBinding lb,PrefetchPair pp, Vector oids, Vector fieldoffset, Vector endoffset, int tuplecount, boolean inside, boolean localbase) {
2867 short offsetcount = 0;
2871 } else if (localbase) {
2872 for(; breakindex<pp.desc.size(); breakindex++) {
2873 Descriptor desc=pp.getDescAt(breakindex);
2874 if (desc instanceof FieldDescriptor) {
2875 FieldDescriptor fd=(FieldDescriptor)desc;
2876 if (fd.isGlobal()) {
2884 if (breakindex>pp.desc.size()) //all local
2887 TypeDescriptor lasttype=pp.base.getType();
2888 String basestr=generateTemp(fm, pp.base, lb);
2890 boolean maybenull=fm.getMethod().isStatic()||
2891 !pp.base.equals(fm.getParameter(0));
2893 for(int i=0; i<breakindex; i++) {
2894 String indexcheck="";
2896 Descriptor desc=pp.getDescAt(i);
2897 if (desc instanceof FieldDescriptor) {
2898 FieldDescriptor fd=(FieldDescriptor)desc;
2900 if (!teststr.equals(""))
2902 teststr+="((prefptr="+basestr+")!=NULL)";
2903 basestr="((struct "+lasttype.getSafeSymbol()+" *)prefptr)->"+fd.getSafeSymbol();
2905 basestr=basestr+"->"+fd.getSafeSymbol();
2908 lasttype=fd.getType();
2910 IndexDescriptor id=(IndexDescriptor)desc;
2911 indexcheck="((tmpindex=";
2912 for(int j=0; j<id.tddesc.size(); j++) {
2913 indexcheck+=generateTemp(fm, id.getTempDescAt(j), lb)+"+";
2915 indexcheck+=id.offset+")>=0)&(tmpindex<((struct ArrayObject *)prefptr)->___length___)";
2917 if (!teststr.equals(""))
2919 teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck;
2920 basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]";
2922 lasttype=lasttype.dereference();
2927 if (teststr.equals("")) {
2928 oid="((unsigned int)"+basestr+")";
2930 oid="((unsigned int)(("+teststr+")?"+basestr+":NULL))";
2934 for(int i = breakindex; i < pp.desc.size(); i++) {
2935 String newfieldoffset;
2936 Object desc = pp.getDescAt(i);
2937 if(desc instanceof FieldDescriptor) {
2938 FieldDescriptor fd=(FieldDescriptor)desc;
2939 newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))");
2940 lasttype=fd.getType();
2942 newfieldoffset = "";
2943 IndexDescriptor id=(IndexDescriptor)desc;
2944 for(int j = 0; j < id.tddesc.size(); j++) {
2945 newfieldoffset += generateTemp(fm, id.getTempDescAt(j), lb) + "+";
2947 newfieldoffset += id.offset.toString();
2948 lasttype=lasttype.dereference();
2950 fieldoffset.add(newfieldoffset);
2953 int base=(tuplecount>0) ? ((Short)endoffset.get(tuplecount-1)).intValue() : 0;
2954 base+=pp.desc.size()-breakindex;
2955 endoffset.add(new Short((short)base));
2960 public void generateFlatGlobalConvNode(FlatMethod fm, LocalityBinding lb, FlatGlobalConvNode fgcn, PrintWriter output) {
2961 if (lb!=fgcn.getLocality())
2963 /* Have to generate flat globalconv */
2964 if (fgcn.getMakePtr()) {
2966 //DEBUG: output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+",\" "+fm+":"+fgcn+"\");");
2967 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+");");
2969 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fgcn)||state.READSET&&dc.getNeedWriteTrans(lb, fgcn)) {
2970 //need to do translation
2971 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+", (void *)("+localsprefixaddr+"));");
2972 } else if (state.READSET&&dc.getNeedTrans(lb, fgcn)) {
2973 if (state.HYBRID&&delaycomp.getConv(lb).contains(fgcn)) {
2974 output.println("TRANSREADRDFISSION("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
2976 output.println("TRANSREADRD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
2980 /* Need to convert to OID */
2981 if ((dc==null)||dc.getNeedSrcTrans(lb,fgcn)) {
2982 if (fgcn.doConvert()||(delaycomp!=null&&delaycomp.needsFission(lb, fgcn.getAtomicEnter())&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) {
2983 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc(),lb)+");");
2985 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=NULL;");
2991 public void generateFlatInstanceOfNode(FlatMethod fm, LocalityBinding lb, FlatInstanceOfNode fion, PrintWriter output) {
2993 if (fion.getType().isArray()) {
2994 type=state.getArrayNumber(fion.getType())+state.numClasses();
2996 type=fion.getType().getClassDesc().getId();
2999 if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
3000 output.println(generateTemp(fm, fion.getDst(), lb)+"=1;");
3002 output.println(generateTemp(fm, fion.getDst(), lb)+"=instanceof("+generateTemp(fm,fion.getSrc(),lb)+","+type+");");
3005 int sandboxcounter=0;
3006 public void generateFlatAtomicEnterNode(FlatMethod fm, LocalityBinding lb, FlatAtomicEnterNode faen, PrintWriter output) {
3007 /* Check to see if we need to generate code for this atomic */
3008 if (locality==null) {
3009 if (GENERATEPRECISEGC) {
3010 output.println("if (pthread_mutex_trylock(&atomiclock)!=0) {");
3011 output.println("stopforgc((struct garbagelist *) &___locals___);");
3012 output.println("pthread_mutex_lock(&atomiclock);");
3013 output.println("restartaftergc();");
3014 output.println("}");
3016 output.println("pthread_mutex_lock(&atomiclock);");
3021 if (locality.getAtomic(lb).get(faen.getPrev(0)).intValue()>0)
3025 if (state.SANDBOX) {
3026 outsandbox.println("int atomiccounter"+sandboxcounter+"=LOW_CHECK_FREQUENCY;");
3027 output.println("counter_reset_pointer=&atomiccounter"+sandboxcounter+";");
3030 if (state.DELAYCOMP&&delaycomp.needsFission(lb, faen)) {
3031 AtomicRecord ar=atomicmethodmap.get(faen);
3033 for(Iterator<TempDescriptor> tmpit=ar.livein.iterator();tmpit.hasNext();) {
3034 TempDescriptor tmp=tmpit.next();
3035 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3038 //copy outs that depend on path
3039 for(Iterator<TempDescriptor> tmpit=ar.liveoutvirtualread.iterator();tmpit.hasNext();) {
3040 TempDescriptor tmp=tmpit.next();
3041 if (!ar.livein.contains(tmp))
3042 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3046 /* Backup the temps. */
3047 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3048 TempDescriptor tmp=tmpit.next();
3049 output.println(generateTemp(fm, backuptable.get(lb).get(tmp),lb)+"="+generateTemp(fm,tmp,lb)+";");
3052 output.println("goto transstart"+faen.getIdentifier()+";");
3054 /******* Print code to retry aborted transaction *******/
3055 output.println("transretry"+faen.getIdentifier()+":");
3058 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3059 TempDescriptor tmp=tmpit.next();
3060 output.println(generateTemp(fm, tmp,lb)+"="+generateTemp(fm,backuptable.get(lb).get(tmp),lb)+";");
3064 /********* Need to revert local object store ********/
3065 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3067 output.println("while ("+revertptr+") {");
3068 output.println("struct ___Object___ * tmpptr;");
3069 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3070 output.println("REVERT_OBJ("+revertptr+");");
3071 output.println(revertptr+"=tmpptr;");
3072 output.println("}");
3074 /******* Tell the runtime to start the transaction *******/
3076 output.println("transstart"+faen.getIdentifier()+":");
3077 if (state.SANDBOX) {
3078 output.println("transaction_check_counter=*counter_reset_pointer;");
3081 output.println("transStart();");
3083 if (state.ABORTREADERS||state.SANDBOX) {
3085 output.println("abortenabled=1;");
3086 output.println("if (_setjmp(aborttrans)) {");
3087 output.println(" goto transretry"+faen.getIdentifier()+"; }");
3091 public void generateFlatAtomicExitNode(FlatMethod fm, LocalityBinding lb, FlatAtomicExitNode faen, PrintWriter output) {
3092 /* Check to see if we need to generate code for this atomic */
3093 if (locality==null) {
3094 output.println("pthread_mutex_unlock(&atomiclock);");
3097 if (locality.getAtomic(lb).get(faen).intValue()>0)
3099 //store the revert list before we lose the transaction object
3102 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3103 output.println(revertptr+"=revertlist;");
3104 output.println("if (transCommit()) {");
3105 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3106 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3107 output.println("} else {");
3108 /* Need to commit local object store */
3109 output.println("while ("+revertptr+") {");
3110 output.println("struct ___Object___ * tmpptr;");
3111 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3112 output.println("COMMIT_OBJ("+revertptr+");");
3113 output.println(revertptr+"=tmpptr;");
3114 output.println("}");
3115 output.println("}");
3119 if (!state.DELAYCOMP) {
3121 output.println("if (transCommit()) {");
3122 /* Transaction aborts if it returns true */
3123 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3124 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3125 output.println("}");
3127 if (delaycomp.optimizeTrans(lb, faen.getAtomicEnter())&&(!state.STMARRAY||state.DUALVIEW)) {
3128 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3129 output.println("LIGHTWEIGHTCOMMIT("+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+", transretry"+faen.getAtomicEnter().getIdentifier()+");");
3131 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3132 TempDescriptor tmp=tmpit.next();
3133 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3135 } else if (delaycomp.needsFission(lb, faen.getAtomicEnter())) {
3136 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3138 output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {");
3139 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3140 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3141 output.println("}");
3143 output.println("else {");
3144 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3145 TempDescriptor tmp=tmpit.next();
3146 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3148 output.println("}");
3150 output.println("if (transCommit(NULL, NULL, NULL, NULL)) {");
3151 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3152 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3153 output.println("}");
3158 public void generateFlatSESEEnterNode( FlatMethod fm,
3160 FlatSESEEnterNode fsen,
3164 // if MLP flag is off, okay that SESE nodes are in IR graph,
3165 // just skip over them and code generates exactly the same
3170 // there may be an SESE in an unreachable method, skip over
3171 if( !mlpa.getAllSESEs().contains( fsen ) ) {
3175 // also, if we have encountered a placeholder, just skip it
3176 if( fsen.getIsCallerSESEplaceholder() ) {
3180 output.println(" {");
3182 // set up the parent
3183 if( fsen == mlpa.getMainSESE() ) {
3184 output.println(" SESEcommon* parentCommon = NULL;");
3186 if( fsen.getParent() == null ) {
3187 System.out.println( "in "+fm+", "+fsen+" has null parent" );
3189 assert fsen.getParent() != null;
3190 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3191 output.println(" SESEcommon* parentCommon = &("+paramsprefix+"->common);");
3193 //output.println(" SESEcommon* parentCommon = (SESEcommon*) peekItem( seseCallStack );");
3194 output.println(" SESEcommon* parentCommon = seseCaller;");
3198 // before doing anything, lock your own record and increment the running children
3199 if( fsen != mlpa.getMainSESE() ) {
3200 output.println(" pthread_mutex_lock( &(parentCommon->lock) );");
3201 output.println(" ++(parentCommon->numRunningChildren);");
3202 output.println(" pthread_mutex_unlock( &(parentCommon->lock) );");
3205 // just allocate the space for this record
3206 output.println(" "+fsen.getSESErecordName()+"* seseToIssue = ("+
3207 fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
3208 fsen.getSESErecordName()+" ) );");
3210 // and keep the thread-local sese stack up to date
3211 //output.println(" addNewItem( seseCallStack, (void*) seseToIssue);");
3213 // fill in common data
3214 output.println(" seseToIssue->common.classID = "+fsen.getIdentifier()+";");
3215 output.println(" psem_init( &(seseToIssue->common.stallSem) );");
3217 output.println(" seseToIssue->common.forwardList = createQueue();");
3218 output.println(" seseToIssue->common.unresolvedDependencies = 0;");
3219 output.println(" pthread_cond_init( &(seseToIssue->common.doneCond), NULL );");
3220 output.println(" seseToIssue->common.doneExecuting = FALSE;");
3221 output.println(" pthread_cond_init( &(seseToIssue->common.runningChildrenCond), NULL );");
3222 output.println(" seseToIssue->common.numRunningChildren = 0;");
3223 output.println(" seseToIssue->common.parent = parentCommon;");
3225 // all READY in-vars should be copied now and be done with it
3226 Iterator<TempDescriptor> tempItr = fsen.getReadyInVarSet().iterator();
3227 while( tempItr.hasNext() ) {
3228 TempDescriptor temp = tempItr.next();
3230 // when we are issuing the main SESE or an SESE with placeholder
3231 // caller SESE as parent, generate temp child child's eclosing method,
3232 // otherwise use the parent's enclosing method as the context
3233 boolean useParentContext = false;
3235 if( fsen != mlpa.getMainSESE() ) {
3236 assert fsen.getParent() != null;
3237 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3238 useParentContext = true;
3242 if( useParentContext ) {
3243 output.println(" seseToIssue->"+temp+" = "+
3244 generateTemp( fsen.getParent().getfmBogus(), temp, null )+";");
3246 output.println(" seseToIssue->"+temp+" = "+
3247 generateTemp( fsen.getfmEnclosing(), temp, null )+";");
3251 // count up memory conflict dependencies,
3253 ConflictGraph graph=null;
3254 FlatSESEEnterNode parent=fsen.getParent();
3256 if(parent.isCallerSESEplaceholder){
3257 graph=mlpa.getConflictGraphResults().get(parent.getfmEnclosing());
3259 graph=mlpa.getConflictGraphResults().get(fsen);
3262 if (graph != null) {
3264 output.println(" /*add waiting queue element*/");
3266 Set<Integer> allocSet = graph.getAllocationSiteIDSetBySESEID(fsen
3268 if (allocSet.size() > 0) {
3269 output.println(" {");
3271 .println(" pthread_mutex_lock( &(parentCommon->lock) );");
3273 for (Iterator iterator = allocSet.iterator(); iterator
3275 Integer allocID = (Integer) iterator.next();
3277 .println(" addWaitingQueueElement(parentCommon->allocSiteArray,numRelatedAllocSites,"
3279 + ",seseToIssue);");
3281 .println(" ++(seseToIssue->common.unresolvedDependencies);");
3284 .println(" pthread_mutex_unlock( &(parentCommon->lock) );");
3285 output.println(" }");
3288 output.println(" /*decide whether it is runnable or not in regarding to memory conflicts*/");
3289 output.println(" {");
3290 output.println(" int idx;");
3291 output.println(" for(idx = 0 ; idx < numRelatedAllocSites ; idx++){");
3292 output.println(" SESEcommon* item=peekItem(seseCaller->allocSiteArray[idx].waitingQueue);");
3293 output.println(" if(item->classID==seseToIssue->common.classID){");
3294 output.println(" --(seseToIssue->common.unresolvedDependencies);");
3295 output.println(" }");
3296 output.println(" }");
3297 output.println(" }");
3301 // before potentially adding this SESE to other forwarding lists,
3302 // create it's lock and take it immediately
3303 output.println(" pthread_mutex_init( &(seseToIssue->common.lock), NULL );");
3304 output.println(" pthread_mutex_lock( &(seseToIssue->common.lock) );");
3306 if( fsen != mlpa.getMainSESE() ) {
3307 // count up outstanding dependencies, static first, then dynamic
3308 Iterator<SESEandAgePair> staticSrcsItr = fsen.getStaticInVarSrcs().iterator();
3309 while( staticSrcsItr.hasNext() ) {
3310 SESEandAgePair srcPair = staticSrcsItr.next();
3311 output.println(" {");
3312 output.println(" SESEcommon* src = (SESEcommon*)"+srcPair+";");
3313 output.println(" pthread_mutex_lock( &(src->lock) );");
3314 output.println(" if( !isEmpty( src->forwardList ) &&");
3315 output.println(" seseToIssue == peekItem( src->forwardList ) ) {");
3316 output.println(" printf( \"This shouldnt already be here\\n\");");
3317 output.println(" exit( -1 );");
3318 output.println(" }");
3319 output.println(" if( !src->doneExecuting ) {");
3320 output.println(" addNewItem( src->forwardList, seseToIssue );");
3321 output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3322 output.println(" }");
3323 output.println(" pthread_mutex_unlock( &(src->lock) );");
3324 output.println(" }");
3326 // whether or not it is an outstanding dependency, make sure
3327 // to pass the static name to the child's record
3328 output.println(" seseToIssue->"+srcPair+" = "+srcPair+";");
3331 // dynamic sources might already be accounted for in the static list,
3332 // so only add them to forwarding lists if they're not already there
3333 Iterator<TempDescriptor> dynVarsItr = fsen.getDynamicInVarSet().iterator();
3334 while( dynVarsItr.hasNext() ) {
3335 TempDescriptor dynInVar = dynVarsItr.next();
3336 output.println(" {");
3337 output.println(" SESEcommon* src = (SESEcommon*)"+dynInVar+"_srcSESE;");
3339 // the dynamic source is NULL if it comes from your own space--you can't pass
3340 // the address off to the new child, because you're not done executing and
3341 // might change the variable, so copy it right now
3342 output.println(" if( src != NULL ) {");
3343 output.println(" pthread_mutex_lock( &(src->lock) );");
3344 output.println(" if( isEmpty( src->forwardList ) ||");
3345 output.println(" seseToIssue != peekItem( src->forwardList ) ) {");
3346 output.println(" if( !src->doneExecuting ) {");
3347 output.println(" addNewItem( src->forwardList, seseToIssue );");
3348 output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3349 output.println(" }");
3350 output.println(" }");
3351 output.println(" pthread_mutex_unlock( &(src->lock) );");
3352 output.println(" seseToIssue->"+dynInVar+"_srcOffset = "+dynInVar+"_srcOffset;");
3353 output.println(" } else {");
3355 boolean useParentContext = false;
3356 if( fsen != mlpa.getMainSESE() ) {
3357 assert fsen.getParent() != null;
3358 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3359 useParentContext = true;
3362 if( useParentContext ) {
3363 output.println(" seseToIssue->"+dynInVar+" = "+
3364 generateTemp( fsen.getParent().getfmBogus(), dynInVar, null )+";");
3366 output.println(" seseToIssue->"+dynInVar+" = "+
3367 generateTemp( fsen.getfmEnclosing(), dynInVar, null )+";");
3370 output.println(" }");
3371 output.println(" }");
3373 // even if the value is already copied, make sure your NULL source
3374 // gets passed so child knows it already has the dynamic value
3375 output.println(" seseToIssue->"+dynInVar+"_srcSESE = "+dynInVar+"_srcSESE;");
3378 // maintain pointers for for finding dynamic SESE
3379 // instances from static names
3380 SESEandAgePair p = new SESEandAgePair( fsen, 0 );
3381 if( fsen.getParent() != null &&
3382 //!fsen.getParent().getIsCallerSESEplaceholder() &&
3383 fsen.getParent().getNeededStaticNames().contains( p )
3386 for( int i = fsen.getOldestAgeToTrack(); i > 0; --i ) {
3387 SESEandAgePair p1 = new SESEandAgePair( fsen, i );
3388 SESEandAgePair p2 = new SESEandAgePair( fsen, i-1 );
3389 output.println(" "+p1+" = "+p2+";");
3391 output.println(" "+p+" = seseToIssue;");
3396 // if there were no outstanding dependencies, issue here
3397 output.println(" if( seseToIssue->common.unresolvedDependencies == 0 ) {");
3398 output.println(" workScheduleSubmit( (void*)seseToIssue );");
3399 output.println(" }");
3401 // release this SESE for siblings to update its dependencies or,
3402 // eventually, for it to mark itself finished
3403 output.println(" pthread_mutex_unlock( &(seseToIssue->common.lock) );");
3404 output.println(" }");
3408 public void generateFlatSESEExitNode( FlatMethod fm,
3410 FlatSESEExitNode fsexn,
3414 // if MLP flag is off, okay that SESE nodes are in IR graph,
3415 // just skip over them and code generates exactly the same
3420 // get the enter node for this exit that has meta data embedded
3421 FlatSESEEnterNode fsen = fsexn.getFlatEnter();
3423 // there may be an SESE in an unreachable method, skip over
3424 if( !mlpa.getAllSESEs().contains( fsen ) ) {
3428 // also, if we have encountered a placeholder, just jump it
3429 if( fsen.getIsCallerSESEplaceholder() ) {
3433 output.println(" /* SESE exiting */");
3435 String com = paramsprefix+"->common";
3437 // this SESE cannot be done until all of its children are done
3438 // so grab your own lock with the condition variable for watching
3439 // that the number of your running children is greater than zero
3440 output.println(" pthread_mutex_lock( &("+com+".lock) );");
3441 output.println(" while( "+com+".numRunningChildren > 0 ) {");
3442 output.println(" pthread_cond_wait( &("+com+".runningChildrenCond), &("+com+".lock) );");
3443 output.println(" }");
3445 // copy out-set from local temps into the sese record
3446 Iterator<TempDescriptor> itr = fsen.getOutVarSet().iterator();
3447 while( itr.hasNext() ) {
3448 TempDescriptor temp = itr.next();
3450 // only have to do this for primitives
3451 if( !temp.getType().isPrimitive() ) {
3455 // have to determine the context enclosing this sese
3456 boolean useParentContext = false;
3458 if( fsen != mlpa.getMainSESE() ) {
3459 assert fsen.getParent() != null;
3460 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3461 useParentContext = true;
3466 if( useParentContext ) {
3467 from = generateTemp( fsen.getParent().getfmBogus(), temp, null );
3469 from = generateTemp( fsen.getfmEnclosing(), temp, null );
3472 output.println(" "+paramsprefix+
3473 "->"+temp.getSafeSymbol()+
3477 // mark yourself done, your SESE data is now read-only
3478 output.println(" "+com+".doneExecuting = TRUE;");
3479 output.println(" pthread_cond_signal( &("+com+".doneCond) );");
3480 output.println(" pthread_mutex_unlock( &("+com+".lock) );");
3482 // decrement dependency count for all SESE's on your forwarding list
3483 output.println(" while( !isEmpty( "+com+".forwardList ) ) {");
3484 output.println(" SESEcommon* consumer = (SESEcommon*) getItem( "+com+".forwardList );");
3485 output.println(" pthread_mutex_lock( &(consumer->lock) );");
3486 output.println(" --(consumer->unresolvedDependencies);");
3487 output.println(" if( consumer->unresolvedDependencies == 0 ) {");
3488 output.println(" workScheduleSubmit( (void*)consumer );");
3489 output.println(" }");
3490 output.println(" pthread_mutex_unlock( &(consumer->lock) );");
3491 output.println(" }");
3494 // clean up its lock element from waiting queue, and decrement dependency count for next SESE block
3495 if( fsen != mlpa.getMainSESE() ) {
3497 output.println(" /* check memory dependency*/");
3498 output.println(" {");
3499 output.println(" int idx;");
3500 output.println(" for(idx = 0 ; idx < ___params___->common.parent->numRelatedAllocSites ; idx++){");
3501 output.println(" SESEcommon* item=peekItem(___params___->common.parent->allocSiteArray[idx].waitingQueue);");
3502 output.println(" if( item->classID == ___params___->common.classID ){");
3503 output.println(" struct QueueItem* qItem=findItem(___params___->common.parent->allocSiteArray[idx].waitingQueue,item);");
3504 output.println(" removeItem(___params___->common.parent->allocSiteArray[idx].waitingQueue,qItem);");
3505 output.println(" if( !isEmpty(___params___->common.parent->allocSiteArray[idx].waitingQueue) ){");
3506 output.println(" SESEcommon* nextItem=peekItem(___params___->common.parent->allocSiteArray[idx].waitingQueue);");
3507 output.println(" pthread_mutex_lock( &(nextItem->lock) );");
3508 output.println(" --(nextItem->unresolvedDependencies);");
3509 output.println(" if( nextItem->unresolvedDependencies == 0){");
3510 output.println(" workScheduleSubmit( (void*)nextItem);");
3511 output.println(" }");
3512 output.println(" pthread_mutex_unlock( &(nextItem->lock) );");
3513 output.println(" }");
3514 output.println(" }");
3515 output.println(" }");
3516 output.println(" }");
3520 // if parent is stalling on you, let them know you're done
3521 if( fsexn.getFlatEnter() != mlpa.getMainSESE() ) {
3522 output.println(" psem_give( &("+paramsprefix+"->common.stallSem) );");
3525 // last of all, decrement your parent's number of running children
3526 output.println(" if( "+paramsprefix+"->common.parent != NULL ) {");
3527 output.println(" pthread_mutex_lock( &("+paramsprefix+"->common.parent->lock) );");
3528 output.println(" --("+paramsprefix+"->common.parent->numRunningChildren);");
3529 output.println(" pthread_cond_signal( &("+paramsprefix+"->common.parent->runningChildrenCond) );");
3530 output.println(" pthread_mutex_unlock( &("+paramsprefix+"->common.parent->lock) );");
3531 output.println(" }");
3533 // this is a thread-only variable that can be handled when critical sese-to-sese
3534 // data has been taken care of--set sese pointer to remember self over method
3535 // calls to a non-zero, invalid address
3536 output.println(" seseCaller = (SESEcommon*) 0x1;");
3539 public void generateFlatWriteDynamicVarNode( FlatMethod fm,
3541 FlatWriteDynamicVarNode fwdvn,
3545 // should node should not be in an IR graph if the
3546 // MLP flag is not set
3547 throw new Error("Unexpected presence of FlatWriteDynamicVarNode");
3550 Hashtable<TempDescriptor, VariableSourceToken> writeDynamic =
3553 assert writeDynamic != null;
3555 Iterator wdItr = writeDynamic.entrySet().iterator();
3556 while( wdItr.hasNext() ) {
3557 Map.Entry me = (Map.Entry) wdItr.next();
3558 TempDescriptor refVar = (TempDescriptor) me.getKey();
3559 VariableSourceToken vst = (VariableSourceToken) me.getValue();
3561 FlatSESEEnterNode current = fwdvn.getEnclosingSESE();
3563 // only do this if the variable in question should be tracked,
3564 // meaning that it was explicitly added to the dynamic var set
3565 if( !current.getDynamicVarSet().contains( vst.getAddrVar() ) ) {
3569 SESEandAgePair instance = new SESEandAgePair( vst.getSESE(), vst.getAge() );
3571 output.println(" {");
3573 if( current.equals( vst.getSESE() ) ) {
3574 // if the src comes from this SESE, it's a method local variable,
3575 // mark src pointer NULL to signify that the var is up-to-date
3576 output.println(" "+vst.getAddrVar()+"_srcSESE = NULL;");
3579 // otherwise we track where it will come from
3580 output.println(" "+vst.getAddrVar()+"_srcSESE = "+instance+";");
3581 output.println(" "+vst.getAddrVar()+"_srcOffset = (int) &((("+
3582 vst.getSESE().getSESErecordName()+"*)0)->"+vst.getAddrVar()+");");
3585 output.println(" }");
3590 private void generateFlatCheckNode(FlatMethod fm, LocalityBinding lb, FlatCheckNode fcn, PrintWriter output) {
3591 if (state.CONSCHECK) {
3592 String specname=fcn.getSpec();
3593 String varname="repairstate___";
3594 output.println("{");
3595 output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
3597 TempDescriptor[] temps=fcn.getTemps();
3598 String[] vars=fcn.getVars();
3599 for(int i=0; i<temps.length; i++) {
3600 output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i],lb)+";");
3603 output.println("if (doanalysis"+specname+"("+varname+")) {");
3604 output.println("free"+specname+"_state("+varname+");");
3605 output.println("} else {");
3606 output.println("/* Bad invariant */");
3607 output.println("free"+specname+"_state("+varname+");");
3608 output.println("abort_task();");
3609 output.println("}");
3610 output.println("}");
3614 private void generateFlatCall(FlatMethod fm, LocalityBinding lb, FlatCall fc, PrintWriter output) {
3616 if( state.MLP && !nonSESEpass ) {
3617 output.println(" seseCaller = (SESEcommon*)"+paramsprefix+";");
3620 MethodDescriptor md=fc.getMethod();
3621 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? locality.getBinding(lb, fc) : md);
3622 ClassDescriptor cn=md.getClassDesc();
3623 output.println("{");
3624 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3626 LocalityBinding fclb=locality.getBinding(lb, fc);
3627 output.print(" struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
3629 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
3631 output.print(objectparams.numPointers());
3632 output.print(", "+localsprefixaddr);
3633 if (md.getThis()!=null) {
3635 output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis(),lb));
3637 if (fc.getThis()!=null&&md.getThis()==null) {
3638 System.out.println("WARNING!!!!!!!!!!!!");
3639 System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
3643 for(int i=0; i<fc.numArgs(); i++) {
3644 Descriptor var=md.getParameter(i);
3645 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
3646 if (objectparams.isParamPtr(paramtemp)) {
3647 TempDescriptor targ=fc.getArg(i);
3649 TypeDescriptor td=md.getParamType(i);
3651 output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
3653 output.print("(struct "+md.getParamType(i).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
3656 output.println("};");
3661 if (fc.getReturnTemp()!=null)
3662 output.print(generateTemp(fm,fc.getReturnTemp(),lb)+"=");
3664 /* Do we need to do virtual dispatch? */
3665 if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
3668 LocalityBinding fclb=locality.getBinding(lb, fc);
3669 output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
3671 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
3676 if (md.getReturnType().isClass()||md.getReturnType().isArray())
3677 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
3679 output.print(md.getReturnType().getSafeSymbol()+" ");
3680 output.print("(*)(");
3682 boolean printcomma=false;
3683 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3685 LocalityBinding fclb=locality.getBinding(lb, fc);
3686 output.print("struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
3688 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
3692 for(int i=0; i<objectparams.numPrimitives(); i++) {
3693 TempDescriptor temp=objectparams.getPrimitive(i);
3697 if (temp.getType().isClass()||temp.getType().isArray())
3698 output.print("struct " + temp.getType().getSafeSymbol()+" * ");
3700 output.print(temp.getType().getSafeSymbol());
3705 LocalityBinding fclb=locality.getBinding(lb, fc);
3706 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])");
3708 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
3712 boolean needcomma=false;
3713 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3714 output.print("&__parameterlist__");
3718 if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
3719 if (fc.getThis()!=null) {
3720 TypeDescriptor ptd=md.getThis().getType();
3723 if (ptd.isClass()&&!ptd.isArray())
3724 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
3725 output.print(generateTemp(fm,fc.getThis(),lb));
3730 for(int i=0; i<fc.numArgs(); i++) {
3731 Descriptor var=md.getParameter(i);
3732 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
3733 if (objectparams.isParamPrim(paramtemp)) {
3734 TempDescriptor targ=fc.getArg(i);
3738 TypeDescriptor ptd=md.getParamType(i);
3739 if (ptd.isClass()&&!ptd.isArray())
3740 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
3741 output.print(generateTemp(fm, targ,lb));
3745 output.println(");");
3746 output.println(" }");
3749 private boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
3750 Set subclasses=typeutil.getSubClasses(thiscd);
3751 if (subclasses==null)
3753 for(Iterator classit=subclasses.iterator(); classit.hasNext();) {
3754 ClassDescriptor cd=(ClassDescriptor)classit.next();
3755 Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol());
3756 for(Iterator matchit=possiblematches.iterator(); matchit.hasNext();) {
3757 MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
3758 if (md.matches(matchmd))
3765 private void generateFlatFieldNode(FlatMethod fm, LocalityBinding lb, FlatFieldNode ffn, PrintWriter output) {
3766 if (state.SINGLETM) {
3767 //single machine transactional memory case
3768 String field=ffn.getField().getSafeSymbol();
3769 String src=generateTemp(fm, ffn.getSrc(),lb);
3770 String dst=generateTemp(fm, ffn.getDst(),lb);
3772 output.println(dst+"="+ src +"->"+field+ ";");
3773 if (ffn.getField().getType().isPtr()&&locality.getAtomic(lb).get(ffn).intValue()>0&&
3774 locality.getNodePreTempInfo(lb, ffn).get(ffn.getSrc())!=LocalityAnalysis.SCRATCH) {
3775 if ((dc==null)||(!state.READSET&&dc.getNeedTrans(lb, ffn))||
3776 (state.READSET&&dc.getNeedWriteTrans(lb, ffn))) {
3777 output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));");
3778 } else if (state.READSET&&dc.getNeedTrans(lb, ffn)) {
3779 if (state.HYBRID&&delaycomp.getConv(lb).contains(ffn)) {
3780 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
3782 output.println("TRANSREADRD("+dst+", "+dst+");");
3785 } else if (state.DSM) {
3786 Integer status=locality.getNodePreTempInfo(lb,ffn).get(ffn.getSrc());
3787 if (status==LocalityAnalysis.GLOBAL) {
3788 String field=ffn.getField().getSafeSymbol();
3789 String src=generateTemp(fm, ffn.getSrc(),lb);
3790 String dst=generateTemp(fm, ffn.getDst(),lb);
3792 if (ffn.getField().getType().isPtr()) {
3794 //TODO: Uncomment this when we have runtime support
3795 //if (ffn.getSrc()==ffn.getDst()) {
3796 //output.println("{");
3797 //output.println("void * temp="+src+";");
3798 //output.println("if (temp&0x1) {");
3799 //output.println("temp=(void *) transRead(trans, (unsigned int) temp);");
3800 //output.println(src+"->"+field+"="+temp+";");
3801 //output.println("}");
3802 //output.println(dst+"=temp;");
3803 //output.println("}");
3805 output.println(dst+"="+ src +"->"+field+ ";");
3806 //output.println("if ("+dst+"&0x1) {");
3807 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
3808 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
3809 //output.println(src+"->"+field+"="+src+"->"+field+";");
3810 //output.println("}");
3813 output.println(dst+"="+ src+"->"+field+";");
3815 } else if (status==LocalityAnalysis.LOCAL) {
3816 if (ffn.getField().getType().isPtr()&&
3817 ffn.getField().isGlobal()) {
3818 String field=ffn.getField().getSafeSymbol();
3819 String src=generateTemp(fm, ffn.getSrc(),lb);
3820 String dst=generateTemp(fm, ffn.getDst(),lb);
3821 output.println(dst+"="+ src +"->"+field+ ";");
3822 if (locality.getAtomic(lb).get(ffn).intValue()>0)
3823 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
3824 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
3826 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
3827 } else if (status==LocalityAnalysis.EITHER) {
3828 //Code is reading from a null pointer
3829 output.println("if ("+generateTemp(fm, ffn.getSrc(),lb)+") {");
3830 output.println("#ifndef RAW");
3831 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
3832 output.println("#endif");
3833 //This should throw a suitable null pointer error
3834 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
3836 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
3838 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
3842 private void generateFlatSetFieldNode(FlatMethod fm, LocalityBinding lb, FlatSetFieldNode fsfn, PrintWriter output) {
3843 if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
3844 throw new Error("Can't set array length");
3845 if (state.SINGLETM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
3846 //Single Machine Transaction Case
3847 boolean srcptr=fsfn.getSrc().getType().isPtr();
3848 String src=generateTemp(fm,fsfn.getSrc(),lb);
3849 String dst=generateTemp(fm,fsfn.getDst(),lb);
3850 output.println("//"+srcptr+" "+fsfn.getSrc().getType().isNull());
3851 if (srcptr&&!fsfn.getSrc().getType().isNull()) {
3852 output.println("{");
3853 if ((dc==null)||dc.getNeedSrcTrans(lb, fsfn)&&
3854 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) {
3855 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3857 output.println("INTPTR srcoid=(INTPTR)"+src+";");
3860 if (wb.needBarrier(fsfn)&&
3861 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getDst())!=LocalityAnalysis.SCRATCH) {
3862 output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;");
3864 if (srcptr&!fsfn.getSrc().getType().isNull()) {
3865 output.println("*((unsigned INTPTR *)&("+dst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
3866 output.println("}");
3868 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3870 } else if (state.DSM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
3871 Integer statussrc=locality.getNodePreTempInfo(lb,fsfn).get(fsfn.getSrc());
3872 Integer statusdst=locality.getNodeTempInfo(lb).get(fsfn).get(fsfn.getDst());
3873 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
3875 String src=generateTemp(fm,fsfn.getSrc(),lb);
3876 String dst=generateTemp(fm,fsfn.getDst(),lb);
3878 output.println("{");
3879 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3881 if (statusdst.equals(LocalityAnalysis.GLOBAL)) {
3884 if (wb.needBarrier(fsfn))
3885 output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;");
3887 output.println("*((unsigned INTPTR *)&("+glbdst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
3889 output.println(glbdst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3890 } else if (statusdst.equals(LocalityAnalysis.LOCAL)) {
3891 /** Check if we need to copy */
3892 output.println("if(!"+dst+"->"+localcopystr+") {");
3893 /* Link object into list */
3894 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3895 output.println(revertptr+"=revertlist;");
3896 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
3897 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3899 output.println("COPY_OBJ("+dst+");");
3900 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
3901 output.println("revertlist=(struct ___Object___ *)"+dst+";");
3902 output.println("}");
3904 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
3906 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3907 } else if (statusdst.equals(LocalityAnalysis.EITHER)) {
3908 //writing to a null...bad
3909 output.println("if ("+dst+") {");
3910 output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}");
3912 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
3914 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3917 output.println("}");
3920 if (state.FASTCHECK) {
3921 String dst=generateTemp(fm, fsfn.getDst(),lb);
3922 output.println("if(!"+dst+"->"+localcopystr+") {");
3923 /* Link object into list */
3924 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
3925 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3927 output.println("COPY_OBJ("+dst+");");
3928 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
3929 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
3930 output.println("}");
3932 output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
3936 private void generateFlatElementNode(FlatMethod fm, LocalityBinding lb, FlatElementNode fen, PrintWriter output) {
3937 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
3940 if (elementtype.isArray()||elementtype.isClass())
3943 type=elementtype.getSafeSymbol()+" ";
3945 if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
3946 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fen.getIndex(),lb)+") >= "+generateTemp(fm,fen.getSrc(),lb) + "->___length___))");
3947 output.println("failedboundschk();");
3949 if (state.SINGLETM) {
3950 //Single machine transaction case
3951 String dst=generateTemp(fm, fen.getDst(),lb);
3952 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))) {
3953 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3955 output.println("STMGETARRAY("+dst+", "+ generateTemp(fm,fen.getSrc(),lb)+", "+generateTemp(fm, fen.getIndex(),lb)+", "+type+");");
3958 if (elementtype.isPtr()&&locality.getAtomic(lb).get(fen).intValue()>0&&
3959 locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())!=LocalityAnalysis.SCRATCH) {
3960 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fen)||state.READSET&&dc.getNeedWriteTrans(lb, fen)) {
3961 output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));");
3962 } else if (state.READSET&&dc.getNeedTrans(lb, fen)) {
3963 if (state.HYBRID&&delaycomp.getConv(lb).contains(fen)) {
3964 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
3966 output.println("TRANSREADRD("+dst+", "+dst+");");
3969 } else if (state.DSM) {
3970 Integer status=locality.getNodePreTempInfo(lb,fen).get(fen.getSrc());
3971 if (status==LocalityAnalysis.GLOBAL) {
3972 String dst=generateTemp(fm, fen.getDst(),lb);
3973 if (elementtype.isPtr()) {
3974 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3975 //DEBUG: output.println("TRANSREAD("+dst+", "+dst+",\""+fm+":"+fen+"\");");
3976 output.println("TRANSREAD("+dst+", "+dst+");");
3978 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3980 } else if (status==LocalityAnalysis.LOCAL) {
3981 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3982 } else if (status==LocalityAnalysis.EITHER) {
3983 //Code is reading from a null pointer
3984 output.println("if ("+generateTemp(fm, fen.getSrc(),lb)+") {");
3985 output.println("#ifndef RAW");
3986 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
3987 output.println("#endif");
3988 //This should throw a suitable null pointer error
3989 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3991 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
3993 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3997 private void generateFlatSetElementNode(FlatMethod fm, LocalityBinding lb, FlatSetElementNode fsen, PrintWriter output) {
3998 //TODO: need dynamic check to make sure this assignment is actually legal
3999 //Because Object[] could actually be something more specific...ie. Integer[]
4001 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
4004 if (elementtype.isArray()||elementtype.isClass())
4007 type=elementtype.getSafeSymbol()+" ";
4009 if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
4010 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fsen.getIndex(),lb)+") >= "+generateTemp(fm,fsen.getDst(),lb) + "->___length___))");
4011 output.println("failedboundschk();");
4014 if (state.SINGLETM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4015 //Transaction set element case
4016 if (wb.needBarrier(fsen)&&
4017 locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH) {
4018 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___objstatus___))|=DIRTY;");
4020 if (fsen.getSrc().getType().isPtr()&&!fsen.getSrc().getType().isNull()) {
4021 output.println("{");
4022 String src=generateTemp(fm, fsen.getSrc(), lb);
4023 if ((dc==null)||dc.getNeedSrcTrans(lb, fsen)&&
4024 locality.getNodePreTempInfo(lb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) {
4025 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4027 output.println("INTPTR srcoid=(INTPTR)"+src+";");
4029 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
4030 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", srcoid, INTPTR);");
4032 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
4034 output.println("}");
4036 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
4037 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", "+ generateTemp(fm, fsen.getSrc(), lb) +", "+type+");");
4039 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4042 } else if (state.DSM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4043 Integer statussrc=locality.getNodePreTempInfo(lb,fsen).get(fsen.getSrc());
4044 Integer statusdst=locality.getNodePreTempInfo(lb,fsen).get(fsen.getDst());
4045 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4046 boolean dstglobal=statusdst==LocalityAnalysis.GLOBAL;
4047 boolean dstlocal=(statusdst==LocalityAnalysis.LOCAL)||(statusdst==LocalityAnalysis.EITHER);
4050 if (wb.needBarrier(fsen))
4051 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___localcopy___))|=DIRTY;");
4052 } else if (dstlocal) {
4053 /** Check if we need to copy */
4054 String dst=generateTemp(fm, fsen.getDst(),lb);
4055 output.println("if(!"+dst+"->"+localcopystr+") {");
4056 /* Link object into list */
4057 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4058 output.println(revertptr+"=revertlist;");
4059 if ((GENERATEPRECISEGC) || this.state.MULTICOREGC)
4060 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4062 output.println("COPY_OBJ("+dst+");");
4063 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4064 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4065 output.println("}");
4067 System.out.println("Node: "+fsen);
4068 System.out.println(lb);
4069 System.out.println("statusdst="+statusdst);
4070 System.out.println(fm.printMethod());
4071 throw new Error("Unknown array type");
4074 output.println("{");
4075 String src=generateTemp(fm, fsen.getSrc(), lb);
4076 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4077 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
4078 output.println("}");
4080 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4083 if (state.FASTCHECK) {
4084 String dst=generateTemp(fm, fsen.getDst(),lb);
4085 output.println("if(!"+dst+"->"+localcopystr+") {");
4086 /* Link object into list */
4087 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4088 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4090 output.println("COPY_OBJ("+dst+");");
4091 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4092 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4093 output.println("}");
4095 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4099 protected void generateFlatNew(FlatMethod fm, LocalityBinding lb, FlatNew fn, PrintWriter output) {
4100 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
4101 //Stash pointer in case of GC
4102 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4103 output.println(revertptr+"=revertlist;");
4105 if (state.SINGLETM) {
4106 if (fn.getType().isArray()) {
4107 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4108 if (locality.getAtomic(lb).get(fn).intValue()>0) {
4109 //inside transaction
4110 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4112 //outside transaction
4113 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4116 if (locality.getAtomic(lb).get(fn).intValue()>0) {
4117 //inside transaction
4118 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4120 //outside transaction
4121 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4124 } else if (fn.getType().isArray()) {
4125 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4126 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4127 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4128 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4129 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4131 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4134 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4135 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");");
4136 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4137 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4139 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
4142 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
4143 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4144 String dst=generateTemp(fm,fn.getDst(),lb);
4145 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
4146 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4147 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4149 if (state.FASTCHECK) {
4150 String dst=generateTemp(fm,fn.getDst(),lb);
4151 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
4152 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4153 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4157 private void generateFlatTagDeclaration(FlatMethod fm, LocalityBinding lb, FlatTagDeclaration fn, PrintWriter output) {
4158 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4159 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
4161 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+state.getTagId(fn.getType())+");");
4165 private void generateFlatOpNode(FlatMethod fm, LocalityBinding lb, FlatOpNode fon, PrintWriter output) {
4166 if (fon.getRight()!=null) {
4167 if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
4168 if (fon.getLeft().getType().isLong())
4169 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
4171 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned int)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
4173 } else if (dc!=null) {
4174 output.print(generateTemp(fm, fon.getDest(),lb)+" = (");
4175 if (fon.getLeft().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
4176 output.print("(void *)");
4177 if (dc.getNeedLeftSrcTrans(lb, fon))
4178 output.print("("+generateTemp(fm, fon.getLeft(),lb)+"!=NULL?"+generateTemp(fm, fon.getLeft(),lb)+"->"+oidstr+":NULL)");
4180 output.print(generateTemp(fm, fon.getLeft(),lb));
4181 output.print(")"+fon.getOp().toString()+"(");
4182 if (fon.getRight().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
4183 output.print("(void *)");
4184 if (dc.getNeedRightSrcTrans(lb, fon))
4185 output.println("("+generateTemp(fm, fon.getRight(),lb)+"!=NULL?"+generateTemp(fm, fon.getRight(),lb)+"->"+oidstr+":NULL));");
4187 output.println(generateTemp(fm,fon.getRight(),lb)+");");
4189 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+fon.getOp().toString()+generateTemp(fm,fon.getRight(),lb)+";");
4190 } else if (fon.getOp().getOp()==Operation.ASSIGN)
4191 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
4192 else if (fon.getOp().getOp()==Operation.UNARYPLUS)
4193 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
4194 else if (fon.getOp().getOp()==Operation.UNARYMINUS)
4195 output.println(generateTemp(fm, fon.getDest(),lb)+" = -"+generateTemp(fm, fon.getLeft(),lb)+";");
4196 else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
4197 output.println(generateTemp(fm, fon.getDest(),lb)+" = !"+generateTemp(fm, fon.getLeft(),lb)+";");
4198 else if (fon.getOp().getOp()==Operation.COMP)
4199 output.println(generateTemp(fm, fon.getDest(),lb)+" = ~"+generateTemp(fm, fon.getLeft(),lb)+";");
4200 else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
4201 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+"->fses==NULL;");
4203 output.println(generateTemp(fm, fon.getDest(),lb)+fon.getOp().toString()+generateTemp(fm, fon.getLeft(),lb)+";");
4206 private void generateFlatCastNode(FlatMethod fm, LocalityBinding lb, FlatCastNode fcn, PrintWriter output) {
4207 /* TODO: Do type check here */
4208 if (fcn.getType().isArray()) {
4209 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
4210 } else if (fcn.getType().isClass())
4211 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
4213 output.println(generateTemp(fm,fcn.getDst(),lb)+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc(),lb)+";");
4216 private void generateFlatLiteralNode(FlatMethod fm, LocalityBinding lb, FlatLiteralNode fln, PrintWriter output) {
4217 if (fln.getValue()==null)
4218 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
4219 else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
4220 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4221 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
4222 //Stash pointer in case of GC
4223 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4224 output.println(revertptr+"=revertlist;");
4226 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
4227 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
4228 //Stash pointer in case of GC
4229 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4230 output.println("revertlist="+revertptr+";");
4233 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
4235 } else if (fln.getType().isBoolean()) {
4236 if (((Boolean)fln.getValue()).booleanValue())
4237 output.println(generateTemp(fm, fln.getDst(),lb)+"=1;");
4239 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
4240 } else if (fln.getType().isChar()) {
4241 String st=FlatLiteralNode.escapeString(fln.getValue().toString());
4242 output.println(generateTemp(fm, fln.getDst(),lb)+"='"+st+"';");
4243 } else if (fln.getType().isLong()) {
4244 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+"LL;");
4246 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+";");
4249 protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) {
4250 if (frn.getReturnTemp()!=null) {
4251 if (frn.getReturnTemp().getType().isPtr())
4252 output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";");
4254 output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";");
4256 output.println("return;");
4260 protected void generateStoreFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
4263 //only record if this group has more than one exit
4264 if (branchanalysis.numJumps(fcb)>1) {
4265 left=branchanalysis.jumpValue(fcb, 0);
4266 right=branchanalysis.jumpValue(fcb, 1);
4268 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") {");
4270 output.println("STOREBRANCH("+right+");");
4271 output.println("goto "+label+";");
4272 output.println("}");
4274 output.println("STOREBRANCH("+left+");");
4277 protected void generateFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
4278 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") goto "+label+";");
4281 /** This method generates header information for the method or
4282 * task referenced by the Descriptor des. */
4283 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) {
4284 generateHeader(fm, lb, des, output, false);
4287 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output, boolean addSESErecord) {
4289 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : des);
4290 MethodDescriptor md=null;
4291 TaskDescriptor task=null;
4292 if (des instanceof MethodDescriptor)
4293 md=(MethodDescriptor) des;
4295 task=(TaskDescriptor) des;
4297 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
4299 if (md!=null&&md.getReturnType()!=null) {
4300 if (md.getReturnType().isClass()||md.getReturnType().isArray())
4301 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
4303 output.print(md.getReturnType().getSafeSymbol()+" ");
4305 //catch the constructor case
4306 output.print("void ");
4308 if (state.DSM||state.SINGLETM) {
4309 output.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
4311 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
4313 output.print(task.getSafeSymbol()+"(");
4315 boolean printcomma=false;
4316 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4318 if (state.DSM||state.SINGLETM) {
4319 output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
4321 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
4323 output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
4329 for(int i=0; i<objectparams.numPrimitives(); i++) {
4330 TempDescriptor temp=objectparams.getPrimitive(i);
4334 if (temp.getType().isClass()||temp.getType().isArray())
4335 output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
4337 output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
4339 output.println(") {");
4340 } else if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
4341 /* Imprecise Task */
4342 output.println("void * parameterarray[]) {");
4343 /* Unpack variables */
4344 for(int i=0; i<objectparams.numPrimitives(); i++) {
4345 TempDescriptor temp=objectparams.getPrimitive(i);
4346 output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
4348 for(int i=0; i<fm.numTags(); i++) {
4349 TempDescriptor temp=fm.getTag(i);
4350 int offset=i+objectparams.numPrimitives();
4351 output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
4354 if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
4355 maxtaskparams=objectparams.numPrimitives()+fm.numTags();
4356 } else output.println(") {");
4359 public void generateFlatFlagActionNode(FlatMethod fm, LocalityBinding lb, FlatFlagActionNode ffan, PrintWriter output) {
4360 output.println("/* FlatFlagActionNode */");
4363 /* Process tag changes */
4364 Relation tagsettable=new Relation();
4365 Relation tagcleartable=new Relation();
4367 Iterator tagsit=ffan.getTempTagPairs();
4368 while (tagsit.hasNext()) {
4369 TempTagPair ttp=(TempTagPair) tagsit.next();
4370 TempDescriptor objtmp=ttp.getTemp();
4371 TagDescriptor tag=ttp.getTag();
4372 TempDescriptor tagtmp=ttp.getTagTemp();
4373 boolean tagstatus=ffan.getTagChange(ttp);
4375 tagsettable.put(objtmp, tagtmp);
4377 tagcleartable.put(objtmp, tagtmp);
4382 Hashtable flagandtable=new Hashtable();
4383 Hashtable flagortable=new Hashtable();
4385 /* Process flag changes */
4386 Iterator flagsit=ffan.getTempFlagPairs();
4387 while(flagsit.hasNext()) {
4388 TempFlagPair tfp=(TempFlagPair)flagsit.next();
4389 TempDescriptor temp=tfp.getTemp();
4390 Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
4391 FlagDescriptor flag=tfp.getFlag();
4393 //Newly allocate objects that don't set any flags case
4394 if (flagortable.containsKey(temp)) {
4398 flagortable.put(temp,new Integer(mask));
4400 int flagid=1<<((Integer)flagtable.get(flag)).intValue();
4401 boolean flagstatus=ffan.getFlagChange(tfp);
4404 if (flagortable.containsKey(temp)) {
4405 mask=((Integer)flagortable.get(temp)).intValue();
4408 flagortable.put(temp,new Integer(mask));
4410 int mask=0xFFFFFFFF;
4411 if (flagandtable.containsKey(temp)) {
4412 mask=((Integer)flagandtable.get(temp)).intValue();
4414 mask&=(0xFFFFFFFF^flagid);
4415 flagandtable.put(temp,new Integer(mask));
4421 HashSet flagtagset=new HashSet();
4422 flagtagset.addAll(flagortable.keySet());
4423 flagtagset.addAll(flagandtable.keySet());
4424 flagtagset.addAll(tagsettable.keySet());
4425 flagtagset.addAll(tagcleartable.keySet());
4427 Iterator ftit=flagtagset.iterator();
4428 while(ftit.hasNext()) {
4429 TempDescriptor temp=(TempDescriptor)ftit.next();
4432 Set tagtmps=tagcleartable.get(temp);
4433 if (tagtmps!=null) {
4434 Iterator tagit=tagtmps.iterator();
4435 while(tagit.hasNext()) {
4436 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
4437 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
4438 output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4440 output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4444 tagtmps=tagsettable.get(temp);
4445 if (tagtmps!=null) {
4446 Iterator tagit=tagtmps.iterator();
4447 while(tagit.hasNext()) {
4448 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
4449 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
4450 output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4452 output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp, lb)+", "+generateTemp(fm,tagtmp, lb)+");");
4457 int andmask=0xFFFFFFF;
4459 if (flagortable.containsKey(temp))
4460 ormask=((Integer)flagortable.get(temp)).intValue();
4461 if (flagandtable.containsKey(temp))
4462 andmask=((Integer)flagandtable.get(temp)).intValue();
4463 generateFlagOrAnd(ffan, fm, lb, temp, output, ormask, andmask);
4464 generateObjectDistribute(ffan, fm, lb, temp, output);
4468 protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp,
4469 PrintWriter output, int ormask, int andmask) {
4470 if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
4471 output.println("flagorandinit("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
4473 output.println("flagorand("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
4477 protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, PrintWriter output) {
4478 output.println("enqueueObject("+generateTemp(fm, temp, lb)+");");
4481 void generateOptionalHeader(PrintWriter headers) {
4484 headers.println("#include \"task.h\"\n\n");
4485 headers.println("#ifndef _OPTIONAL_STRUCT_");
4486 headers.println("#define _OPTIONAL_STRUCT_");
4488 //STRUCT PREDICATEMEMBER
4489 headers.println("struct predicatemember{");
4490 headers.println("int type;");
4491 headers.println("int numdnfterms;");
4492 headers.println("int * flags;");
4493 headers.println("int numtags;");
4494 headers.println("int * tags;\n};\n\n");
4496 //STRUCT OPTIONALTASKDESCRIPTOR
4497 headers.println("struct optionaltaskdescriptor{");
4498 headers.println("struct taskdescriptor * task;");
4499 headers.println("int index;");
4500 headers.println("int numenterflags;");
4501 headers.println("int * enterflags;");
4502 headers.println("int numpredicatemembers;");
4503 headers.println("struct predicatemember ** predicatememberarray;");
4504 headers.println("};\n\n");
4506 //STRUCT TASKFAILURE
4507 headers.println("struct taskfailure {");
4508 headers.println("struct taskdescriptor * task;");
4509 headers.println("int index;");
4510 headers.println("int numoptionaltaskdescriptors;");
4511 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
4513 //STRUCT FSANALYSISWRAPPER
4514 headers.println("struct fsanalysiswrapper{");
4515 headers.println("int flags;");
4516 headers.println("int numtags;");
4517 headers.println("int * tags;");
4518 headers.println("int numtaskfailures;");
4519 headers.println("struct taskfailure ** taskfailurearray;");
4520 headers.println("int numoptionaltaskdescriptors;");
4521 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
4523 //STRUCT CLASSANALYSISWRAPPER
4524 headers.println("struct classanalysiswrapper{");
4525 headers.println("int type;");
4526 headers.println("int numotd;");
4527 headers.println("struct optionaltaskdescriptor ** otdarray;");
4528 headers.println("int numfsanalysiswrappers;");
4529 headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
4531 headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
4533 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
4534 while(taskit.hasNext()) {
4535 TaskDescriptor td=(TaskDescriptor)taskit.next();
4536 headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
4541 //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
4542 int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
4543 int predicateindex = 0;
4544 //iterate through the classes concerned by the predicate
4545 Set c_vard = predicate.vardescriptors;
4546 Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
4549 for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext();) {
4550 VarDescriptor vard = (VarDescriptor)vard_it.next();
4551 TypeDescriptor typed = vard.getType();
4553 //generate for flags
4554 HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
4555 output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4557 if (fen_hashset!=null) {
4558 for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext();) {
4559 FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
4561 DNFFlag dflag=fen.getDNF();
4562 numberterms+=dflag.size();
4564 Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
4566 for(int j=0; j<dflag.size(); j++) {
4568 output.println(",");
4569 Vector term=dflag.get(j);
4572 for(int k=0; k<term.size(); k++) {
4573 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
4574 FlagDescriptor fd=dfa.getFlag();
4575 boolean negated=dfa.getNegated();
4576 int flagid=1<<((Integer)flags.get(fd)).intValue();
4581 output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
4586 output.println("};\n");
4589 TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
4590 output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4593 for(int j=0; j<tagel.numTags(); j++) {
4595 output.println(",");
4596 TempDescriptor tmp=tagel.getTemp(j);
4597 if (!slotnumber.containsKey(tmp)) {
4598 Integer slotint=new Integer(current_slot++);
4599 slotnumber.put(tmp,slotint);
4601 int slot=slotnumber.get(tmp).intValue();
4602 output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
4604 numtags = tagel.numTags();
4606 output.println("};");
4608 //store the result into a predicatemember struct
4609 output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
4610 output.println("/*type*/"+typed.getClassDesc().getId()+",");
4611 output.println("/* number of dnf terms */"+numberterms+",");
4612 output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4613 output.println("/* number of tag */"+numtags+",");
4614 output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4615 output.println("};\n");
4620 //generate an array that stores the entire predicate
4621 output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4622 for( int j = 0; j<predicateindex; j++) {
4623 if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4624 else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4626 output.println("};\n");
4627 return predicateindex;
4631 void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
4632 generateOptionalHeader(headers);
4634 output.println("#include \"optionalstruct.h\"\n\n");
4635 output.println("#include \"stdlib.h\"\n");
4637 HashSet processedcd = new HashSet();
4639 Enumeration e = safeexecution.keys();
4640 while (e.hasMoreElements()) {
4643 ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
4644 Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp); //will be used several times
4646 //Generate the struct of optionals
4647 Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
4648 numotd = c_otd.size();
4649 if(maxotd<numotd) maxotd = numotd;
4650 if( !c_otd.isEmpty() ) {
4651 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
4652 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
4654 //generate the int arrays for the predicate
4655 Predicate predicate = otd.predicate;
4656 int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
4657 TreeSet<Integer> fsset=new TreeSet<Integer>();
4658 //iterate through possible FSes corresponding to
4659 //the state when entering
4661 for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext();) {
4662 FlagState fs = (FlagState)fses.next();
4664 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
4665 FlagDescriptor flagd = (FlagDescriptor)flags.next();
4666 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
4669 fsset.add(new Integer(flagid));
4670 //tag information not needed because tag
4671 //changes are not tolerated.
4674 output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4675 boolean needcomma=false;
4676 for(Iterator<Integer> it=fsset.iterator(); it.hasNext();) {
4679 output.println(it.next());
4682 output.println("};\n");
4685 //generate optionaltaskdescriptor that actually
4686 //includes exit fses, predicate and the task
4688 output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
4689 output.println("&task_"+otd.td.getSafeSymbol()+",");
4690 output.println("/*index*/"+otd.getIndex()+",");
4691 output.println("/*number of enter flags*/"+fsset.size()+",");
4692 output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4693 output.println("/*number of members */"+predicateindex+",");
4694 output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4695 output.println("};\n");
4699 // if there are no optionals, there is no need to build the rest of the struct
4701 output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
4702 c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
4703 if( !c_otd.isEmpty() ) {
4704 boolean needcomma=false;
4705 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
4706 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
4708 output.println(",");
4710 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4713 output.println("};\n");
4715 //get all the possible flagstates reachable by an object
4716 Hashtable hashtbtemp = safeexecution.get(cdtemp);
4718 TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
4719 fsts.addAll(hashtbtemp.keySet());
4720 for(Iterator fsit=fsts.iterator(); fsit.hasNext();) {
4721 FlagState fs = (FlagState)fsit.next();
4724 //get the set of OptionalTaskDescriptors corresponding
4725 HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
4726 //iterate through the OptionalTaskDescriptors and
4727 //store the pointers to the optionals struct (see on
4728 //top) into an array
4730 output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
4731 for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext();) {
4732 OptionalTaskDescriptor mm = mos.next();
4734 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
4736 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4739 output.println("};\n");
4741 //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
4744 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
4745 FlagDescriptor flagd = (FlagDescriptor)flags.next();
4746 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
4750 //process tag information
4753 boolean first = true;
4754 Enumeration tag_enum = fs.getTags();
4755 output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
4756 while(tag_enum.hasMoreElements()) {
4758 TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
4762 output.println(", ");
4763 output.println("/*tagid*/"+state.getTagId(tagd));
4765 output.println("};");
4767 Set<TaskIndex> tiset=sa.getTaskIndex(fs);
4768 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
4769 TaskIndex ti=itti.next();
4773 Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
4775 output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
4776 boolean needcomma=false;
4777 for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext();) {
4778 OptionalTaskDescriptor otd=otdit.next();
4782 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4784 output.println("};");
4786 output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
4787 output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
4788 output.print(ti.getIndex()+", ");
4789 output.print(otdset.size()+", ");
4790 output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
4791 output.println("};");
4794 tiset=sa.getTaskIndex(fs);
4795 boolean needcomma=false;
4797 output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
4798 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
4799 TaskIndex ti=itti.next();
4800 if (ti.isRuntime()) {
4807 output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
4809 output.println("};\n");
4811 //Store the result in fsanalysiswrapper
4813 output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
4814 output.println("/*flag*/"+flagid+",");
4815 output.println("/* number of tags*/"+tagcounter+",");
4816 output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
4817 output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
4818 output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
4819 output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
4820 output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
4821 output.println("};\n");
4825 //Build the array of fsanalysiswrappers
4826 output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
4827 boolean needcomma=false;
4828 for(int i = 0; i<fscounter; i++) {
4829 if (needcomma) output.print(",");
4830 output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
4833 output.println("};");
4835 //Build the classanalysiswrapper referring to the previous array
4836 output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
4837 output.println("/*type*/"+cdtemp.getId()+",");
4838 output.println("/*numotd*/"+numotd+",");
4839 output.println("otdarray"+cdtemp.getSafeSymbol()+",");
4840 output.println("/* number of fsanalysiswrappers */"+fscounter+",");
4841 output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
4842 processedcd.add(cdtemp);
4845 //build an array containing every classes for which code has been build
4846 output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
4847 for(int i=0; i<state.numClasses(); i++) {
4848 ClassDescriptor cn=cdarray[i];
4851 if ((cn != null) && (processedcd.contains(cn)))
4852 output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
4854 output.print("NULL");
4856 output.println("};");
4858 output.println("#define MAXOTD "+maxotd);
4859 headers.println("#endif");
4862 public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
4863 Relation r=new Relation();
4864 for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext();) {
4865 OptionalTaskDescriptor otd=otdit.next();
4866 TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
4870 LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
4871 for(Iterator it=r.keySet().iterator(); it.hasNext();) {
4872 Set s=r.get(it.next());
4873 for(Iterator it2=s.iterator(); it2.hasNext();) {
4874 OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
4882 protected void outputTransCode(PrintWriter output) {