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.ConflictNode;
32 import Analysis.MLP.MLPAnalysis;
33 import Analysis.MLP.ParentChildConflictsMap;
34 import Analysis.MLP.SESELock;
35 import Analysis.MLP.VariableSourceToken;
36 import Analysis.MLP.VSTWrapper;
37 import Analysis.MLP.CodePlan;
38 import Analysis.MLP.SESEandAgePair;
39 import Analysis.MLP.WaitingElement;
41 public class BuildCode {
44 Hashtable paramstable;
49 String localsprefix="___locals___";
50 String localsprefixaddr="&"+localsprefix;
51 String localsprefixderef=localsprefix+".";
52 String fcrevert="___fcrevert___";
53 String paramsprefix="___params___";
54 String oidstr="___nextobject___";
55 String nextobjstr="___nextobject___";
56 String localcopystr="___localcopy___";
57 public static boolean GENERATEPRECISEGC=false;
58 public static String PREFIX="";
59 public static String arraytype="ArrayObject";
60 public static int flagcount = 0;
63 protected int maxtaskparams=0;
64 private int maxcount=0;
65 ClassDescriptor[] cdarray;
66 TypeDescriptor[] arraytable;
67 LocalityAnalysis locality;
68 Hashtable<LocalityBinding, TempDescriptor> reverttable;
69 Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>> backuptable;
73 String mlperrstr = "if(status != 0) { "+
74 "sprintf(errmsg, \"MLP error at %s:%d\", __FILE__, __LINE__); "+
75 "perror(errmsg); exit(-1); }";
76 boolean nonSESEpass=true;
79 DiscoverConflicts recorddc;
84 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa) {
85 this(st, temptovar, typeutil, null, sa, pa, null);
88 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa) {
89 this(st, temptovar, typeutil, null, sa, pa, mlpa);
92 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, PrefetchAnalysis pa, MLPAnalysis mlpa) {
93 this(st, temptovar, typeutil, locality, null, pa, mlpa);
96 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa) {
101 callgraph=new CallGraph(state);
103 oidstr="___objlocation___";
104 this.temptovar=temptovar;
105 paramstable=new Hashtable();
106 tempstable=new Hashtable();
107 fieldorder=new Hashtable();
108 flagorder=new Hashtable();
109 this.typeutil=typeutil;
110 virtualcalls=new Virtual(state,locality);
111 if (locality!=null) {
112 this.locality=locality;
113 this.reverttable=new Hashtable<LocalityBinding, TempDescriptor>();
114 this.backuptable=new Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>>();
115 this.wb=new WriteBarrier(locality, st);
117 if (state.SINGLETM&&state.DCOPTS) {
118 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
119 GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
120 this.dc=new DiscoverConflicts(locality, st, typeanalysis, gft);
123 if (state.DELAYCOMP) {
124 //TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
125 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
126 GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
127 delaycomp=new DCWrapper(locality, st, typeanalysis, gft);
128 dc=delaycomp.getConflicts();
129 recorddc=new DiscoverConflicts(locality, st, typeanalysis, delaycomp.getCannotDelayMap(), true, true, null);
130 recorddc.doAnalysis();
134 /** The buildCode method outputs C code for all the methods. The Flat
135 * versions of the methods must already be generated and stored in
136 * the State object. */
137 PrintWriter outsandbox=null;
139 public void buildCode() {
140 /* Create output streams to write to */
141 PrintWriter outclassdefs=null;
142 PrintWriter outstructs=null;
143 PrintWriter outrepairstructs=null;
144 PrintWriter outmethodheader=null;
145 PrintWriter outmethod=null;
146 PrintWriter outvirtual=null;
147 PrintWriter outtask=null;
148 PrintWriter outtaskdefs=null;
149 PrintWriter outoptionalarrays=null;
150 PrintWriter optionalheaders=null;
154 outsandbox=new PrintWriter(new FileOutputStream(PREFIX+"sandboxdefs.c"), true);
156 outstructs=new PrintWriter(new FileOutputStream(PREFIX+"structdefs.h"), true);
157 outmethodheader=new PrintWriter(new FileOutputStream(PREFIX+"methodheaders.h"), true);
158 outclassdefs=new PrintWriter(new FileOutputStream(PREFIX+"classdefs.h"), true);
159 outmethod=new PrintWriter(new FileOutputStream(PREFIX+"methods.c"), true);
160 outvirtual=new PrintWriter(new FileOutputStream(PREFIX+"virtualtable.h"), true);
162 outtask=new PrintWriter(new FileOutputStream(PREFIX+"task.h"), true);
163 outtaskdefs=new PrintWriter(new FileOutputStream(PREFIX+"taskdefs.c"), true);
164 if (state.OPTIONAL) {
165 outoptionalarrays=new PrintWriter(new FileOutputStream(PREFIX+"optionalarrays.c"), true);
166 optionalheaders=new PrintWriter(new FileOutputStream(PREFIX+"optionalstruct.h"), true);
169 if (state.structfile!=null) {
170 outrepairstructs=new PrintWriter(new FileOutputStream(PREFIX+state.structfile+".struct"), true);
172 } catch (Exception e) {
177 /* Build the virtual dispatch tables */
178 buildVirtualTables(outvirtual);
180 /* Output includes */
181 outmethodheader.println("#ifndef METHODHEADERS_H");
182 outmethodheader.println("#define METHODHEADERS_H");
183 outmethodheader.println("#include \"structdefs.h\"");
185 outmethodheader.println("#include \"dstm.h\"");
187 outmethodheader.println("#include \"sandbox.h\"");
189 if (state.EVENTMONITOR) {
190 outmethodheader.println("#include \"monitor.h\"");
192 if (state.SINGLETM) {
193 outmethodheader.println("#include \"tm.h\"");
194 outmethodheader.println("#include \"delaycomp.h\"");
195 outmethodheader.println("#include \"inlinestm.h\"");
197 if (state.ABORTREADERS) {
198 outmethodheader.println("#include \"abortreaders.h\"");
199 outmethodheader.println("#include <setjmp.h>");
202 outmethodheader.println("#include <stdlib.h>");
203 outmethodheader.println("#include <stdio.h>");
204 outmethodheader.println("#include <string.h>");
205 outmethodheader.println("#include \"mlp_runtime.h\"");
206 outmethodheader.println("#include \"psemaphore.h\"");
209 /* Output Structures */
210 outputStructs(outstructs);
212 // Output the C class declarations
213 // These could mutually reference each other
214 outputClassDeclarations(outclassdefs);
216 // Output function prototypes and structures for parameters
217 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
218 while(it.hasNext()) {
219 ClassDescriptor cn=(ClassDescriptor)it.next();
220 generateCallStructs(cn, outclassdefs, outstructs, outmethodheader);
222 outclassdefs.close();
225 /* Map flags to integers */
226 /* The runtime keeps track of flags using these integers */
227 it=state.getClassSymbolTable().getDescriptorsIterator();
228 while(it.hasNext()) {
229 ClassDescriptor cn=(ClassDescriptor)it.next();
233 generateTaskStructs(outstructs, outmethodheader);
235 /* Outputs generic task structures if this is a task
237 outputTaskTypes(outtask);
241 // have to initialize some SESE compiler data before
242 // analyzing normal methods, which must happen before
243 // generating SESE internal code
244 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
245 FlatSESEEnterNode fsen = seseit.next();
246 initializeSESE( fsen );
250 /* Build the actual methods */
251 outputMethods(outmethod);
253 // Output function prototypes and structures for SESE's and code
256 // used to differentiate, during code generation, whether we are
257 // passing over SESE body code, or non-SESE code
260 // first generate code for each sese's internals
261 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
262 FlatSESEEnterNode fsen = seseit.next();
263 generateMethodSESE(fsen, null, outstructs, outmethodheader, outmethod);
266 // then write the invokeSESE switch to decouple scheduler
267 // from having to do unique details of sese invocation
268 generateSESEinvocationMethod(outmethodheader, outmethod);
272 /* Output code for tasks */
273 outputTaskCode(outtaskdefs, outmethod);
275 /* Record maximum number of task parameters */
276 outstructs.println("#define MAXTASKPARAMS "+maxtaskparams);
277 } else if (state.main!=null) {
278 /* Generate main method */
279 outputMainMethod(outmethod);
282 /* Generate information for task with optional parameters */
283 if (state.TASK&&state.OPTIONAL) {
284 generateOptionalArrays(outoptionalarrays, optionalheaders, state.getAnalysisResult(), state.getOptionalTaskDescriptors());
285 outoptionalarrays.close();
288 /* Output structure definitions for repair tool */
289 if (state.structfile!=null) {
290 buildRepairStructs(outrepairstructs);
291 outrepairstructs.close();
295 outmethodheader.println("#endif");
296 outmethodheader.close();
298 outstructs.println("#endif");
303 /* This code just generates the main C method for java programs.
304 * The main C method packs up the arguments into a string array
305 * and passes it to the java main method. */
307 private void outputMainMethod(PrintWriter outmethod) {
308 outmethod.println("int main(int argc, const char *argv[]) {");
309 outmethod.println(" int i;");
312 //outmethod.println(" pthread_once( &mlpOnceObj, mlpInitOncePerThread );");
313 outmethod.println(" workScheduleInit( "+state.MLP_NUMCORES+", invokeSESEmethod );");
317 if (state.DSMRECOVERYSTATS) {
318 outmethod.println("#ifdef RECOVERYSTATS \n");
319 outmethod.println("handle();\n");
320 outmethod.println("#endif\n");
322 outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n");
323 outmethod.println("handle();\n");
324 outmethod.println("#endif\n");
328 if (state.THREAD||state.DSM||state.SINGLETM) {
329 outmethod.println("initializethreads();");
332 outmethod.println("if (dstmStartup(argv[1])) {");
333 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
334 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-2);");
336 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-2);");
339 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
340 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1);");
342 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1);");
346 outmethod.println(" for(i=2;i<argc;i++) {");
348 outmethod.println(" for(i=1;i<argc;i++) {");
349 outmethod.println(" int length=strlen(argv[i]);");
350 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
351 outmethod.println(" struct ___String___ *newstring=NewString(NULL, argv[i], length);");
353 outmethod.println(" struct ___String___ *newstring=NewString(argv[i], length);");
356 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-2]=newstring;");
358 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-1]=newstring;");
359 outmethod.println(" }");
361 MethodDescriptor md=typeutil.getMain();
362 ClassDescriptor cd=typeutil.getMainClass();
364 outmethod.println(" {");
365 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
366 if (state.DSM||state.SINGLETM) {
367 outmethod.print(" struct "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
369 outmethod.print(" struct "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
370 outmethod.println("1, NULL,"+"stringarray};");
371 if (state.DSM||state.SINGLETM)
372 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
374 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
376 if (state.DSM||state.SINGLETM)
377 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
379 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
381 outmethod.println(" }");
384 outmethod.println("}");
387 if (state.THREAD||state.DSM||state.SINGLETM) {
388 outmethod.println("pthread_mutex_lock(&gclistlock);");
389 outmethod.println("threadcount--;");
390 outmethod.println("pthread_cond_signal(&gccond);");
391 outmethod.println("pthread_mutex_unlock(&gclistlock);");
394 if (state.DSM||state.SINGLETM) {
395 //outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n");
396 outmethod.println("#if defined(TRANSSTATS) \n");
397 outmethod.println("printf(\"****** Transaction Stats ******\\n\");");
398 outmethod.println("printf(\"numTransCommit= %d\\n\", numTransCommit);");
399 outmethod.println("printf(\"numTransAbort= %d\\n\", numTransAbort);");
400 outmethod.println("printf(\"nSoftAbort= %d\\n\", nSoftAbort);");
402 outmethod.println("printf(\"nchashSearch= %d\\n\", nchashSearch);");
403 outmethod.println("printf(\"nmhashSearch= %d\\n\", nmhashSearch);");
404 outmethod.println("printf(\"nprehashSearch= %d\\n\", nprehashSearch);");
405 outmethod.println("printf(\"ndirtyCacheObj= %d\\n\", ndirtyCacheObj);");
406 outmethod.println("printf(\"nRemoteReadSend= %d\\n\", nRemoteSend);");
407 outmethod.println("printf(\"bytesSent= %d\\n\", bytesSent);");
408 outmethod.println("printf(\"bytesRecv= %d\\n\", bytesRecv);");
409 outmethod.println("printf(\"totalObjSize= %d\\n\", totalObjSize);");
410 outmethod.println("printf(\"sendRemoteReq= %d\\n\", sendRemoteReq);");
411 outmethod.println("printf(\"getResponse= %d\\n\", getResponse);");
412 } else if (state.SINGLETM) {
413 outmethod.println("printf(\"nSoftAbortAbort= %d\\n\", nSoftAbortAbort);");
414 outmethod.println("printf(\"nSoftAbortCommit= %d\\n\", nSoftAbortCommit);");
415 outmethod.println("#ifdef STMSTATS\n");
416 outmethod.println("for(i=0; i<TOTALNUMCLASSANDARRAY; i++) {\n");
417 outmethod.println(" printf(\"typesCausingAbort[%2d] numaccess= %5d numabort= %3d\\n\", i, typesCausingAbort[i].numaccess, typesCausingAbort[i].numabort);\n");
418 outmethod.println("}\n");
419 outmethod.println("#endif\n");
420 outmethod.println("fflush(stdout);");
422 outmethod.println("#endif\n");
425 if (state.EVENTMONITOR) {
426 outmethod.println("dumpdata();");
429 if (state.THREAD||state.SINGLETM)
430 outmethod.println("pthread_exit(NULL);");
433 outmethod.println(" workScheduleBegin();");
436 outmethod.println("}");
439 /* This method outputs code for each task. */
441 private void outputTaskCode(PrintWriter outtaskdefs, PrintWriter outmethod) {
442 /* Compile task based program */
443 outtaskdefs.println("#include \"task.h\"");
444 outtaskdefs.println("#include \"methodheaders.h\"");
445 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
446 while(taskit.hasNext()) {
447 TaskDescriptor td=(TaskDescriptor)taskit.next();
448 FlatMethod fm=state.getMethodFlat(td);
449 generateFlatMethod(fm, null, outmethod);
450 generateTaskDescriptor(outtaskdefs, fm, td);
453 //Output task descriptors
454 taskit=state.getTaskSymbolTable().getDescriptorsIterator();
455 outtaskdefs.println("struct taskdescriptor * taskarray[]= {");
457 while(taskit.hasNext()) {
458 TaskDescriptor td=(TaskDescriptor)taskit.next();
462 outtaskdefs.println(",");
463 outtaskdefs.print("&task_"+td.getSafeSymbol());
465 outtaskdefs.println("};");
467 outtaskdefs.println("int numtasks="+state.getTaskSymbolTable().getValueSet().size()+";");
470 /* This method outputs most of the methods.c file. This includes
471 * some standard includes and then an array with the sizes of
472 * objets and array that stores supertype and then the code for
473 * the Java methods.. */
475 protected void outputMethods(PrintWriter outmethod) {
476 outmethod.println("#include \"methodheaders.h\"");
477 outmethod.println("#include \"virtualtable.h\"");
478 outmethod.println("#include \"runtime.h\"");
480 outmethod.println("#include \"sandboxdefs.c\"");
483 outmethod.println("#include \"addPrefetchEnhance.h\"");
484 outmethod.println("#include \"localobjects.h\"");
486 if (state.FASTCHECK) {
487 outmethod.println("#include \"localobjects.h\"");
489 if(state.MULTICORE) {
490 outmethod.println("#include \"task.h\"");
491 outmethod.println("#include \"multicoreruntime.h\"");
492 outmethod.println("#include \"runtime_arch.h\"");
494 if (state.THREAD||state.DSM||state.SINGLETM)
495 outmethod.println("#include <thread.h>");
496 if (state.main!=null) {
497 outmethod.println("#include <string.h>");
499 if (state.CONSCHECK) {
500 outmethod.println("#include \"checkers.h\"");
503 outmethod.println("#include <stdlib.h>");
504 outmethod.println("#include <stdio.h>");
505 outmethod.println("#include \"mlp_runtime.h\"");
506 outmethod.println("#include \"psemaphore.h\"");
510 //Store the sizes of classes & array elements
511 generateSizeArray(outmethod);
513 //Store table of supertypes
514 generateSuperTypeTable(outmethod);
516 //Store the layout of classes
517 generateLayoutStructs(outmethod);
519 /* Generate code for methods */
520 if (state.DSM||state.SINGLETM) {
521 for(Iterator<LocalityBinding> lbit=locality.getLocalityBindings().iterator(); lbit.hasNext();) {
522 LocalityBinding lb=lbit.next();
523 MethodDescriptor md=lb.getMethod();
524 FlatMethod fm=state.getMethodFlat(md);
526 if (!md.getModifiers().isNative()) {
527 generateFlatMethod(fm, lb, outmethod);
528 //System.out.println("fm= " + fm + " md= " + md);
532 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
533 while(classit.hasNext()) {
534 ClassDescriptor cn=(ClassDescriptor)classit.next();
535 Iterator methodit=cn.getMethods();
536 while(methodit.hasNext()) {
537 /* Classify parameters */
538 MethodDescriptor md=(MethodDescriptor)methodit.next();
539 FlatMethod fm=state.getMethodFlat(md);
540 if (!md.getModifiers().isNative()) {
541 generateFlatMethod(fm, null, outmethod);
548 protected void outputStructs(PrintWriter outstructs) {
549 outstructs.println("#ifndef STRUCTDEFS_H");
550 outstructs.println("#define STRUCTDEFS_H");
551 outstructs.println("#include \"classdefs.h\"");
552 outstructs.println("#ifndef INTPTR");
553 outstructs.println("#ifdef BIT64");
554 outstructs.println("#define INTPTR long");
555 outstructs.println("#else");
556 outstructs.println("#define INTPTR int");
557 outstructs.println("#endif");
558 outstructs.println("#endif");
560 outstructs.println("#include \"mlp_runtime.h\"");
561 outstructs.println("#include \"psemaphore.h\"");
564 /* Output #defines that the runtime uses to determine type
565 * numbers for various objects it needs */
566 outstructs.println("#define MAXCOUNT "+maxcount);
567 if (state.DSM||state.SINGLETM) {
568 LocalityBinding lbrun=new LocalityBinding(typeutil.getRun(), false);
570 lbrun.setGlobalThis(LocalityAnalysis.GLOBAL);
572 else if (state.SINGLETM) {
573 lbrun.setGlobalThis(LocalityAnalysis.NORMAL);
575 outstructs.println("#define RUNMETHOD "+virtualcalls.getLocalityNumber(lbrun));
579 LocalityBinding lbexecute = new LocalityBinding(typeutil.getExecute(), false);
581 lbexecute.setGlobalThis(LocalityAnalysis.GLOBAL);
582 else if( state.SINGLETM)
583 lbexecute.setGlobalThis(LocalityAnalysis.NORMAL);
584 outstructs.println("#define EXECUTEMETHOD " + virtualcalls.getLocalityNumber(lbexecute));
587 outstructs.println("#define STRINGARRAYTYPE "+
588 (state.getArrayNumber(
589 (new TypeDescriptor(typeutil.getClass(TypeUtil.StringClass))).makeArray(state))+state.numClasses()));
591 outstructs.println("#define OBJECTARRAYTYPE "+
592 (state.getArrayNumber(
593 (new TypeDescriptor(typeutil.getClass(TypeUtil.ObjectClass))).makeArray(state))+state.numClasses()));
596 outstructs.println("#define STRINGTYPE "+typeutil.getClass(TypeUtil.StringClass).getId());
597 outstructs.println("#define CHARARRAYTYPE "+
598 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.CHAR)).makeArray(state))+state.numClasses()));
600 outstructs.println("#define BYTEARRAYTYPE "+
601 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state))+state.numClasses()));
603 outstructs.println("#define BYTEARRAYARRAYTYPE "+
604 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state).makeArray(state))+state.numClasses()));
606 outstructs.println("#define NUMCLASSES "+state.numClasses());
607 int totalClassSize = state.numClasses() + state.numArrays();
608 outstructs.println("#define TOTALNUMCLASSANDARRAY "+ totalClassSize);
610 outstructs.println("#define STARTUPTYPE "+typeutil.getClass(TypeUtil.StartupClass).getId());
611 outstructs.println("#define TAGTYPE "+typeutil.getClass(TypeUtil.TagClass).getId());
612 outstructs.println("#define TAGARRAYTYPE "+
613 (state.getArrayNumber(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)).makeArray(state))+state.numClasses()));
617 protected void outputClassDeclarations(PrintWriter outclassdefs) {
618 if (state.THREAD||state.DSM||state.SINGLETM)
619 outclassdefs.println("#include <pthread.h>");
620 outclassdefs.println("#ifndef INTPTR");
621 outclassdefs.println("#ifdef BIT64");
622 outclassdefs.println("#define INTPTR long");
623 outclassdefs.println("#else");
624 outclassdefs.println("#define INTPTR int");
625 outclassdefs.println("#endif");
626 outclassdefs.println("#endif");
628 outclassdefs.println("#include \"optionalstruct.h\"");
629 outclassdefs.println("struct "+arraytype+";");
630 /* Start by declaring all structs */
631 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
632 while(it.hasNext()) {
633 ClassDescriptor cn=(ClassDescriptor)it.next();
634 outclassdefs.println("struct "+cn.getSafeSymbol()+";");
636 outclassdefs.println("");
637 //Print out definition for array type
638 outclassdefs.println("struct "+arraytype+" {");
639 outclassdefs.println(" int type;");
640 if (state.EVENTMONITOR) {
641 outclassdefs.println(" int objuid;");
644 outclassdefs.println(" pthread_t tid;");
645 outclassdefs.println(" void * lockentry;");
646 outclassdefs.println(" int lockcount;");
649 outclassdefs.println(" int flag;");
650 if(!state.MULTICORE) {
651 outclassdefs.println(" void * flagptr;");
653 outclassdefs.println(" int version;");
654 outclassdefs.println(" int * lock;"); // lock entry for this obj
655 outclassdefs.println(" int mutex;");
656 outclassdefs.println(" int lockcount;");
657 if(state.MULTICOREGC) {
658 outclassdefs.println(" int marked;");
662 outclassdefs.println(" int numfses;");
663 outclassdefs.println(" int * fses;");
666 printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs);
668 if (state.STMARRAY) {
669 outclassdefs.println(" int lowindex;");
670 outclassdefs.println(" int highindex;");
673 outclassdefs.println(" int paddingforarray;");
674 if (state.DUALVIEW) {
675 outclassdefs.println(" int arrayversion;");
678 outclassdefs.println(" int ___length___;");
679 outclassdefs.println("};\n");
680 outclassdefs.println("extern int classsize[];");
681 outclassdefs.println("extern int hasflags[];");
682 outclassdefs.println("extern unsigned INTPTR * pointerarray[];");
683 outclassdefs.println("extern int supertypes[];");
686 /** Prints out definitions for generic task structures */
688 private void outputTaskTypes(PrintWriter outtask) {
689 outtask.println("#ifndef _TASK_H");
690 outtask.println("#define _TASK_H");
691 outtask.println("struct parameterdescriptor {");
692 outtask.println("int type;");
693 outtask.println("int numberterms;");
694 outtask.println("int *intarray;");
695 outtask.println("void * queue;");
696 outtask.println("int numbertags;");
697 outtask.println("int *tagarray;");
698 outtask.println("};");
700 outtask.println("struct taskdescriptor {");
701 outtask.println("void * taskptr;");
702 outtask.println("int numParameters;");
703 outtask.println(" int numTotal;");
704 outtask.println("struct parameterdescriptor **descriptorarray;");
705 outtask.println("char * name;");
706 outtask.println("};");
707 outtask.println("extern struct taskdescriptor * taskarray[];");
708 outtask.println("extern numtasks;");
709 outtask.println("#endif");
713 private void buildRepairStructs(PrintWriter outrepairstructs) {
714 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
715 while(classit.hasNext()) {
716 ClassDescriptor cn=(ClassDescriptor)classit.next();
717 outrepairstructs.println("structure "+cn.getSymbol()+" {");
718 outrepairstructs.println(" int __type__;");
720 outrepairstructs.println(" int __flag__;");
721 if(!state.MULTICORE) {
722 outrepairstructs.println(" int __flagptr__;");
725 printRepairStruct(cn, outrepairstructs);
726 outrepairstructs.println("}\n");
729 for(int i=0; i<state.numArrays(); i++) {
730 TypeDescriptor tdarray=arraytable[i];
731 TypeDescriptor tdelement=tdarray.dereference();
732 outrepairstructs.println("structure "+arraytype+"_"+state.getArrayNumber(tdarray)+" {");
733 outrepairstructs.println(" int __type__;");
734 printRepairStruct(typeutil.getClass(TypeUtil.ObjectClass), outrepairstructs);
735 outrepairstructs.println(" int length;");
737 // Need to add support to repair tool for this
738 if (tdelement.isClass()||tdelement.isArray())
739 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" * elem[this.length];");
741 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" elem[this.length];");
743 outrepairstructs.println("}\n");
747 private void printRepairStruct(ClassDescriptor cn, PrintWriter output) {
748 ClassDescriptor sp=cn.getSuperDesc();
750 printRepairStruct(sp, output);
752 Vector fields=(Vector)fieldorder.get(cn);
754 for(int i=0; i<fields.size(); i++) {
755 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
756 if (fd.getType().isArray()) {
757 output.println(" "+arraytype+"_"+ state.getArrayNumber(fd.getType()) +" * "+fd.getSymbol()+";");
758 } else if (fd.getType().isClass())
759 output.println(" "+fd.getType().getRepairSymbol()+" * "+fd.getSymbol()+";");
760 else if (fd.getType().isFloat())
761 output.println(" int "+fd.getSymbol()+"; /* really float */");
763 output.println(" "+fd.getType().getRepairSymbol()+" "+fd.getSymbol()+";");
767 /** This method outputs TaskDescriptor information */
768 private void generateTaskDescriptor(PrintWriter output, FlatMethod fm, TaskDescriptor task) {
769 for (int i=0; i<task.numParameters(); i++) {
770 VarDescriptor param_var=task.getParameter(i);
771 TypeDescriptor param_type=task.getParamType(i);
772 FlagExpressionNode param_flag=task.getFlag(param_var);
773 TagExpressionList param_tag=task.getTag(param_var);
776 if (param_flag==null) {
777 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
778 output.println("0x0, 0x0 };");
781 DNFFlag dflag=param_flag.getDNF();
782 dnfterms=dflag.size();
784 Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
785 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
786 for(int j=0; j<dflag.size(); j++) {
789 Vector term=dflag.get(j);
792 for(int k=0; k<term.size(); k++) {
793 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
794 FlagDescriptor fd=dfa.getFlag();
795 boolean negated=dfa.getNegated();
796 int flagid=1<<((Integer)flags.get(fd)).intValue();
801 output.print("0x"+Integer.toHexString(andmask)+", 0x"+Integer.toHexString(checkmask));
803 output.println("};");
806 output.println("int parametertag_"+i+"_"+task.getSafeSymbol()+"[]={");
807 //BUG...added next line to fix, test with any task program
809 for(int j=0; j<param_tag.numTags(); j++) {
812 /* for each tag we need */
813 /* which slot it is */
814 /* what type it is */
815 TagVarDescriptor tvd=(TagVarDescriptor)task.getParameterTable().get(param_tag.getName(j));
816 TempDescriptor tmp=param_tag.getTemp(j);
817 int slot=fm.getTagInt(tmp);
818 output.println(slot+", "+state.getTagId(tvd.getTag()));
820 output.println("};");
822 output.println("struct parameterdescriptor parameter_"+i+"_"+task.getSafeSymbol()+"={");
823 output.println("/* type */"+param_type.getClassDesc().getId()+",");
824 output.println("/* number of DNF terms */"+dnfterms+",");
825 output.println("parameterdnf_"+i+"_"+task.getSafeSymbol()+",");
826 output.println("0,");
827 //BUG, added next line to fix and else statement...test
828 //with any task program
830 output.println("/* number of tags */"+param_tag.numTags()+",");
832 output.println("/* number of tags */ 0,");
833 output.println("parametertag_"+i+"_"+task.getSafeSymbol());
834 output.println("};");
838 output.println("struct parameterdescriptor * parameterdescriptors_"+task.getSafeSymbol()+"[] = {");
839 for (int i=0; i<task.numParameters(); i++) {
842 output.print("¶meter_"+i+"_"+task.getSafeSymbol());
844 output.println("};");
846 output.println("struct taskdescriptor task_"+task.getSafeSymbol()+"={");
847 output.println("&"+task.getSafeSymbol()+",");
848 output.println("/* number of parameters */" +task.numParameters() + ",");
849 int numtotal=task.numParameters()+fm.numTags();
850 output.println("/* number total parameters */" +numtotal + ",");
851 output.println("parameterdescriptors_"+task.getSafeSymbol()+",");
852 output.println("\""+task.getSymbol()+"\"");
853 output.println("};");
857 /** The buildVirtualTables method outputs the virtual dispatch
858 * tables for methods. */
860 protected void buildVirtualTables(PrintWriter outvirtual) {
861 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
862 while(classit.hasNext()) {
863 ClassDescriptor cd=(ClassDescriptor)classit.next();
864 if (virtualcalls.getMethodCount(cd)>maxcount)
865 maxcount=virtualcalls.getMethodCount(cd);
867 MethodDescriptor[][] virtualtable=null;
868 LocalityBinding[][] lbvirtualtable=null;
869 if (state.DSM||state.SINGLETM)
870 lbvirtualtable=new LocalityBinding[state.numClasses()+state.numArrays()][maxcount];
872 virtualtable=new MethodDescriptor[state.numClasses()+state.numArrays()][maxcount];
874 /* Fill in virtual table */
875 classit=state.getClassSymbolTable().getDescriptorsIterator();
876 while(classit.hasNext()) {
877 ClassDescriptor cd=(ClassDescriptor)classit.next();
878 if (state.DSM||state.SINGLETM)
879 fillinRow(cd, lbvirtualtable, cd.getId());
881 fillinRow(cd, virtualtable, cd.getId());
884 ClassDescriptor objectcd=typeutil.getClass(TypeUtil.ObjectClass);
885 Iterator arrayit=state.getArrayIterator();
886 while(arrayit.hasNext()) {
887 TypeDescriptor td=(TypeDescriptor)arrayit.next();
888 int id=state.getArrayNumber(td);
889 if (state.DSM||state.SINGLETM)
890 fillinRow(objectcd, lbvirtualtable, id+state.numClasses());
892 fillinRow(objectcd, virtualtable, id+state.numClasses());
895 outvirtual.print("void * virtualtable[]={");
896 boolean needcomma=false;
897 for(int i=0; i<state.numClasses()+state.numArrays(); i++) {
898 for(int j=0; j<maxcount; j++) {
900 outvirtual.print(", ");
901 if ((state.DSM||state.SINGLETM)&&lbvirtualtable[i][j]!=null) {
902 LocalityBinding lb=lbvirtualtable[i][j];
903 MethodDescriptor md=lb.getMethod();
904 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
905 } else if (!(state.DSM||state.SINGLETM)&&virtualtable[i][j]!=null) {
906 MethodDescriptor md=virtualtable[i][j];
907 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
909 outvirtual.print("0");
913 outvirtual.println("");
915 outvirtual.println("};");
919 private void fillinRow(ClassDescriptor cd, MethodDescriptor[][] virtualtable, int rownum) {
920 /* Get inherited methods */
921 if (cd.getSuperDesc()!=null)
922 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
923 /* Override them with our methods */
924 for(Iterator it=cd.getMethods(); it.hasNext();) {
925 MethodDescriptor md=(MethodDescriptor)it.next();
926 if (md.isStatic()||md.getReturnType()==null)
928 int methodnum=virtualcalls.getMethodNumber(md);
929 virtualtable[rownum][methodnum]=md;
933 private void fillinRow(ClassDescriptor cd, LocalityBinding[][] virtualtable, int rownum) {
934 /* Get inherited methods */
935 if (cd.getSuperDesc()!=null)
936 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
937 /* Override them with our methods */
938 if (locality.getClassBindings(cd)!=null)
939 for(Iterator<LocalityBinding> lbit=locality.getClassBindings(cd).iterator(); lbit.hasNext();) {
940 LocalityBinding lb=lbit.next();
941 MethodDescriptor md=lb.getMethod();
942 //Is the method static or a constructor
943 if (md.isStatic()||md.getReturnType()==null)
945 int methodnum=virtualcalls.getLocalityNumber(lb);
946 virtualtable[rownum][methodnum]=lb;
950 /** Generate array that contains the sizes of class objects. The
951 * object allocation functions in the runtime use this
954 private void generateSizeArray(PrintWriter outclassdefs) {
955 outclassdefs.print("extern struct prefetchCountStats * evalPrefetch;\n");
956 outclassdefs.print("#ifdef TRANSSTATS \n");
957 outclassdefs.print("extern int numTransAbort;\n");
958 outclassdefs.print("extern int numTransCommit;\n");
959 outclassdefs.print("extern int nSoftAbort;\n");
961 outclassdefs.print("extern int nchashSearch;\n");
962 outclassdefs.print("extern int nmhashSearch;\n");
963 outclassdefs.print("extern int nprehashSearch;\n");
964 outclassdefs.print("extern int ndirtyCacheObj;\n");
965 outclassdefs.print("extern int nRemoteSend;\n");
966 outclassdefs.print("extern int sendRemoteReq;\n");
967 outclassdefs.print("extern int getResponse;\n");
968 outclassdefs.print("extern int bytesSent;\n");
969 outclassdefs.print("extern int bytesRecv;\n");
970 outclassdefs.print("extern int totalObjSize;\n");
971 outclassdefs.print("extern void handle();\n");
972 } else if (state.SINGLETM) {
973 outclassdefs.println("extern int nSoftAbortAbort;");
974 outclassdefs.println("extern int nSoftAbortCommit;");
975 outclassdefs.println("#ifdef STMSTATS\n");
976 outclassdefs.println("extern objtypestat_t typesCausingAbort[];");
977 outclassdefs.println("#endif\n");
979 outclassdefs.print("#endif\n");
981 outclassdefs.print("int numprefetchsites = " + pa.prefetchsiteid + ";\n");
983 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
984 cdarray=new ClassDescriptor[state.numClasses()];
986 while(it.hasNext()) {
987 ClassDescriptor cd=(ClassDescriptor)it.next();
988 cdarray[cd.getId()]=cd;
991 arraytable=new TypeDescriptor[state.numArrays()];
993 Iterator arrayit=state.getArrayIterator();
994 while(arrayit.hasNext()) {
995 TypeDescriptor td=(TypeDescriptor)arrayit.next();
996 int id=state.getArrayNumber(td);
1002 /* Print out types */
1003 outclassdefs.println("/* ");
1004 for(int i=0; i<state.numClasses(); i++) {
1005 ClassDescriptor cd=cdarray[i];
1007 outclassdefs.println("NULL " + i);
1009 outclassdefs.println(cd +" "+i);
1013 for(int i=0; i<state.numArrays(); i++) {
1014 TypeDescriptor arraytd=arraytable[i];
1015 outclassdefs.println(arraytd.toPrettyString() +" "+(i+state.numClasses()));
1018 outclassdefs.println("*/");
1021 outclassdefs.print("int classsize[]={");
1023 boolean needcomma=false;
1024 for(int i=0; i<state.numClasses(); i++) {
1026 outclassdefs.print(", ");
1028 outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")");
1030 outclassdefs.print("0");
1036 for(int i=0; i<state.numArrays(); i++) {
1038 outclassdefs.print(", ");
1039 TypeDescriptor tdelement=arraytable[i].dereference();
1040 if (tdelement.isArray()||tdelement.isClass())
1041 outclassdefs.print("sizeof(void *)");
1043 outclassdefs.print("sizeof("+tdelement.getSafeSymbol()+")");
1047 outclassdefs.println("};");
1049 ClassDescriptor objectclass=typeutil.getClass(TypeUtil.ObjectClass);
1051 outclassdefs.print("int typearray[]={");
1052 for(int i=0; i<state.numClasses(); i++) {
1053 ClassDescriptor cd=cdarray[i];
1054 ClassDescriptor supercd=i>0?cd.getSuperDesc():null;
1056 outclassdefs.print(", ");
1058 outclassdefs.print("-1");
1060 outclassdefs.print(supercd.getId());
1064 for(int i=0; i<state.numArrays(); i++) {
1065 TypeDescriptor arraytd=arraytable[i];
1066 ClassDescriptor arraycd=arraytd.getClassDesc();
1067 if (arraycd==null) {
1069 outclassdefs.print(", ");
1070 outclassdefs.print(objectclass.getId());
1074 ClassDescriptor cd=arraycd.getSuperDesc();
1077 TypeDescriptor supertd=new TypeDescriptor(cd);
1078 supertd.setArrayCount(arraytd.getArrayCount());
1079 type=state.getArrayNumber(supertd);
1081 type+=state.numClasses();
1084 cd=cd.getSuperDesc();
1087 outclassdefs.print(", ");
1088 outclassdefs.print(type);
1092 outclassdefs.println("};");
1097 outclassdefs.print("int typearray2[]={");
1098 for(int i=0; i<state.numArrays(); i++) {
1099 TypeDescriptor arraytd=arraytable[i];
1100 ClassDescriptor arraycd=arraytd.getClassDesc();
1101 if (arraycd==null) {
1103 outclassdefs.print(", ");
1104 outclassdefs.print("-1");
1108 ClassDescriptor cd=arraycd.getSuperDesc();
1109 int level=arraytd.getArrayCount()-1;
1111 for(; level>0; level--) {
1112 TypeDescriptor supertd=new TypeDescriptor(objectclass);
1113 supertd.setArrayCount(level);
1114 type=state.getArrayNumber(supertd);
1116 type+=state.numClasses();
1121 outclassdefs.print(", ");
1122 outclassdefs.print(type);
1126 outclassdefs.println("};");
1129 /** Constructs params and temp objects for each method or task.
1130 * These objects tell the compiler which temps need to be
1133 protected void generateTempStructs(FlatMethod fm, LocalityBinding lb) {
1134 MethodDescriptor md=fm.getMethod();
1135 TaskDescriptor task=fm.getTask();
1136 Set<TempDescriptor> saveset=lb!=null ? locality.getTempSet(lb) : null;
1137 ParamsObject objectparams=md!=null ? new ParamsObject(md,tag++) : new ParamsObject(task, tag++);
1139 paramstable.put(lb, objectparams);
1140 backuptable.put(lb, new Hashtable<TempDescriptor, TempDescriptor>());
1141 } else if (md!=null)
1142 paramstable.put(md, objectparams);
1144 paramstable.put(task, objectparams);
1146 for(int i=0; i<fm.numParameters(); i++) {
1147 TempDescriptor temp=fm.getParameter(i);
1148 TypeDescriptor type=temp.getType();
1149 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1150 objectparams.addPtr(temp);
1152 objectparams.addPrim(temp);
1153 if(lb!=null&&saveset.contains(temp)) {
1154 backuptable.get(lb).put(temp, temp.createNew());
1158 for(int i=0; i<fm.numTags(); i++) {
1159 TempDescriptor temp=fm.getTag(i);
1160 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1161 objectparams.addPtr(temp);
1163 objectparams.addPrim(temp);
1166 TempObject objecttemps=md!=null ? new TempObject(objectparams,md,tag++) : new TempObject(objectparams, task, tag++);
1168 tempstable.put(lb, objecttemps);
1170 tempstable.put(md, objecttemps);
1172 tempstable.put(task, objecttemps);
1174 for(Iterator nodeit=fm.getNodeSet().iterator(); nodeit.hasNext();) {
1175 FlatNode fn=(FlatNode)nodeit.next();
1176 TempDescriptor[] writes=fn.writesTemps();
1177 for(int i=0; i<writes.length; i++) {
1178 TempDescriptor temp=writes[i];
1179 TypeDescriptor type=temp.getType();
1180 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1181 objecttemps.addPtr(temp);
1183 objecttemps.addPrim(temp);
1184 if(lb!=null&&saveset.contains(temp)&&
1185 !backuptable.get(lb).containsKey(temp))
1186 backuptable.get(lb).put(temp, temp.createNew());
1190 /* Create backup temps */
1192 for(Iterator<TempDescriptor> tmpit=backuptable.get(lb).values().iterator(); tmpit.hasNext();) {
1193 TempDescriptor tmp=tmpit.next();
1194 TypeDescriptor type=tmp.getType();
1195 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1196 objecttemps.addPtr(tmp);
1198 objecttemps.addPrim(tmp);
1200 /* Create temp to hold revert table */
1201 if (state.DSM&&(lb.getHasAtomic()||lb.isAtomic())) {
1202 TempDescriptor reverttmp=new TempDescriptor("revertlist", typeutil.getClass(TypeUtil.ObjectClass));
1203 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1204 objecttemps.addPtr(reverttmp);
1206 objecttemps.addPrim(reverttmp);
1207 reverttable.put(lb, reverttmp);
1212 /** This method outputs the following information about classes
1214 * (1) For classes, what are the locations of pointers.
1215 * (2) For arrays, does the array contain pointers or primitives.
1216 * (3) For classes, does the class contain flags.
1219 private void generateLayoutStructs(PrintWriter output) {
1220 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1221 while(it.hasNext()) {
1222 ClassDescriptor cn=(ClassDescriptor)it.next();
1223 output.println("unsigned INTPTR "+cn.getSafeSymbol()+"_pointers[]={");
1224 Iterator allit=cn.getFieldTable().getAllDescriptorsIterator();
1226 while(allit.hasNext()) {
1227 FieldDescriptor fd=(FieldDescriptor)allit.next();
1228 TypeDescriptor type=fd.getType();
1229 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1234 output.print(count);
1235 allit=cn.getFieldTable().getAllDescriptorsIterator();
1236 while(allit.hasNext()) {
1237 FieldDescriptor fd=(FieldDescriptor)allit.next();
1238 TypeDescriptor type=fd.getType();
1239 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1242 output.println(",");
1243 output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+fd.getSafeSymbol()+"))");
1246 output.println("};");
1248 output.println("unsigned INTPTR * pointerarray[]={");
1249 boolean needcomma=false;
1250 for(int i=0; i<state.numClasses(); i++) {
1251 ClassDescriptor cn=cdarray[i];
1253 output.println(",");
1256 output.print(cn.getSafeSymbol()+"_pointers");
1258 output.print("NULL");
1262 for(int i=0; i<state.numArrays(); i++) {
1264 output.println(", ");
1265 TypeDescriptor tdelement=arraytable[i].dereference();
1266 if (tdelement.isArray()||tdelement.isClass())
1267 output.print("((unsigned INTPTR *)1)");
1273 output.println("};");
1275 output.println("int hasflags[]={");
1276 for(int i=0; i<state.numClasses(); i++) {
1277 ClassDescriptor cn=cdarray[i];
1279 output.println(", ");
1281 if ((cn != null) && (cn.hasFlags()))
1286 output.println("};");
1289 /** Print out table to give us supertypes */
1290 private void generateSuperTypeTable(PrintWriter output) {
1291 output.println("int supertypes[]={");
1292 boolean needcomma=false;
1293 for(int i=0; i<state.numClasses(); i++) {
1294 ClassDescriptor cn=cdarray[i];
1296 output.println(",");
1298 if ((cn != null) && (cn.getSuperDesc()!=null)) {
1299 ClassDescriptor cdsuper=cn.getSuperDesc();
1300 output.print(cdsuper.getId());
1304 output.println("};");
1307 /** Force consistent field ordering between inherited classes. */
1309 private void printClassStruct(ClassDescriptor cn, PrintWriter classdefout) {
1311 ClassDescriptor sp=cn.getSuperDesc();
1313 printClassStruct(sp, classdefout);
1315 if (!fieldorder.containsKey(cn)) {
1316 Vector fields=new Vector();
1317 fieldorder.put(cn,fields);
1318 Vector fieldvec=cn.getFieldVec();
1319 for(int i=0;i<fieldvec.size();i++) {
1320 FieldDescriptor fd=(FieldDescriptor)fieldvec.get(i);
1321 if ((sp==null||!sp.getFieldTable().contains(fd.getSymbol())))
1325 Vector fields=(Vector)fieldorder.get(cn);
1327 for(int i=0; i<fields.size(); i++) {
1328 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
1329 if (fd.getType().isClass()||fd.getType().isArray())
1330 classdefout.println(" struct "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1332 classdefout.println(" "+fd.getType().getSafeSymbol()+" "+fd.getSafeSymbol()+";");
1337 /* Map flags to integers consistently between inherited
1340 protected void mapFlags(ClassDescriptor cn) {
1341 ClassDescriptor sp=cn.getSuperDesc();
1345 if (!flagorder.containsKey(cn)) {
1346 Hashtable flags=new Hashtable();
1347 flagorder.put(cn,flags);
1349 Hashtable superflags=(Hashtable)flagorder.get(sp);
1350 Iterator superflagit=superflags.keySet().iterator();
1351 while(superflagit.hasNext()) {
1352 FlagDescriptor fd=(FlagDescriptor)superflagit.next();
1353 Integer number=(Integer)superflags.get(fd);
1354 flags.put(fd, number);
1355 if ((number.intValue()+1)>max)
1356 max=number.intValue()+1;
1360 Iterator flagit=cn.getFlags();
1361 while(flagit.hasNext()) {
1362 FlagDescriptor fd=(FlagDescriptor)flagit.next();
1363 if (sp==null||!sp.getFlagTable().contains(fd.getSymbol()))
1364 flags.put(fd, new Integer(max++));
1370 /** This function outputs (1) structures that parameters are
1371 * passed in (when PRECISE GC is enabled) and (2) function
1372 * prototypes for the methods */
1374 protected void generateCallStructs(ClassDescriptor cn, PrintWriter classdefout, PrintWriter output, PrintWriter headersout) {
1375 /* Output class structure */
1376 classdefout.println("struct "+cn.getSafeSymbol()+" {");
1377 classdefout.println(" int type;");
1378 if (state.EVENTMONITOR) {
1379 classdefout.println(" int objuid;");
1382 classdefout.println(" pthread_t tid;");
1383 classdefout.println(" void * lockentry;");
1384 classdefout.println(" int lockcount;");
1388 classdefout.println(" int flag;");
1389 if((!state.MULTICORE) || (cn.getSymbol().equals("TagDescriptor"))) {
1390 classdefout.println(" void * flagptr;");
1391 } else if (state.MULTICORE) {
1392 classdefout.println(" int version;");
1393 classdefout.println(" int * lock;"); // lock entry for this obj
1394 classdefout.println(" int mutex;");
1395 classdefout.println(" int lockcount;");
1396 if(state.MULTICOREGC) {
1397 classdefout.println(" int marked;");
1400 if (state.OPTIONAL) {
1401 classdefout.println(" int numfses;");
1402 classdefout.println(" int * fses;");
1405 printClassStruct(cn, classdefout);
1406 classdefout.println("};\n");
1408 if (state.DSM||state.SINGLETM) {
1409 /* Cycle through LocalityBindings */
1410 HashSet<MethodDescriptor> nativemethods=new HashSet<MethodDescriptor>();
1411 Set<LocalityBinding> lbset=locality.getClassBindings(cn);
1413 for(Iterator<LocalityBinding> lbit=lbset.iterator(); lbit.hasNext();) {
1414 LocalityBinding lb=lbit.next();
1415 MethodDescriptor md=lb.getMethod();
1416 if (md.getModifiers().isNative()) {
1417 //make sure we only print a native method once
1418 if (nativemethods.contains(md)) {
1419 FlatMethod fm=state.getMethodFlat(md);
1420 generateTempStructs(fm, lb);
1423 nativemethods.add(md);
1425 generateMethod(cn, md, lb, headersout, output);
1428 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1429 MethodDescriptor md=(MethodDescriptor)methodit.next();
1430 if (md.getModifiers().isNative()&&!nativemethods.contains(md)) {
1431 //Need to build param structure for library code
1432 FlatMethod fm=state.getMethodFlat(md);
1433 generateTempStructs(fm, null);
1434 generateMethodParam(cn, md, null, output);
1439 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1440 MethodDescriptor md=(MethodDescriptor)methodit.next();
1441 generateMethod(cn, md, null, headersout, output);
1445 private void generateMethodParam(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter output) {
1446 /* Output parameter structure */
1447 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1448 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1449 if ((state.DSM||state.SINGLETM)&&lb!=null)
1450 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1452 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1453 output.println(" INTPTR size;");
1454 output.println(" void * next;");
1455 for(int i=0; i<objectparams.numPointers(); i++) {
1456 TempDescriptor temp=objectparams.getPointer(i);
1457 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1459 output.println("};\n");
1463 private void generateMethod(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter headersout, PrintWriter output) {
1464 FlatMethod fm=state.getMethodFlat(md);
1465 generateTempStructs(fm, lb);
1467 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1468 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md);
1470 generateMethodParam(cn, md, lb, output);
1472 /* Output temp structure */
1473 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1474 if (state.DSM||state.SINGLETM)
1475 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1477 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1478 output.println(" INTPTR size;");
1479 output.println(" void * next;");
1480 for(int i=0; i<objecttemps.numPointers(); i++) {
1481 TempDescriptor temp=objecttemps.getPointer(i);
1482 if (temp.getType().isNull())
1483 output.println(" void * "+temp.getSafeSymbol()+";");
1485 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1487 output.println("};\n");
1490 /********* Output method declaration ***********/
1491 if (state.DSM||state.SINGLETM) {
1492 headersout.println("#define D"+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1494 headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1496 /* First the return type */
1497 if (md.getReturnType()!=null) {
1498 if (md.getReturnType().isClass()||md.getReturnType().isArray())
1499 headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1501 headersout.print(md.getReturnType().getSafeSymbol()+" ");
1503 //catch the constructor case
1504 headersout.print("void ");
1506 /* Next the method name */
1507 if (state.DSM||state.SINGLETM) {
1508 headersout.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1510 headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1512 boolean printcomma=false;
1513 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1514 if (state.DSM||state.SINGLETM) {
1515 headersout.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1517 headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1521 /* Output parameter list*/
1522 for(int i=0; i<objectparams.numPrimitives(); i++) {
1523 TempDescriptor temp=objectparams.getPrimitive(i);
1525 headersout.print(", ");
1527 if (temp.getType().isClass()||temp.getType().isArray())
1528 headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1530 headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1532 headersout.println(");\n");
1536 /** This function outputs (1) structures that parameters are
1537 * passed in (when PRECISE GC is enabled) and (2) function
1538 * prototypes for the tasks */
1540 private void generateTaskStructs(PrintWriter output, PrintWriter headersout) {
1541 /* Cycle through tasks */
1542 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
1544 while(taskit.hasNext()) {
1545 /* Classify parameters */
1546 TaskDescriptor task=(TaskDescriptor)taskit.next();
1547 FlatMethod fm=state.getMethodFlat(task);
1548 generateTempStructs(fm, null);
1550 ParamsObject objectparams=(ParamsObject) paramstable.get(task);
1551 TempObject objecttemps=(TempObject) tempstable.get(task);
1553 /* Output parameter structure */
1554 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1555 output.println("struct "+task.getSafeSymbol()+"_params {");
1557 output.println(" INTPTR size;");
1558 output.println(" void * next;");
1559 for(int i=0; i<objectparams.numPointers(); i++) {
1560 TempDescriptor temp=objectparams.getPointer(i);
1561 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1564 output.println("};\n");
1565 if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
1566 maxtaskparams=objectparams.numPointers()+fm.numTags();
1570 /* Output temp structure */
1571 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1572 output.println("struct "+task.getSafeSymbol()+"_locals {");
1573 output.println(" INTPTR size;");
1574 output.println(" void * next;");
1575 for(int i=0; i<objecttemps.numPointers(); i++) {
1576 TempDescriptor temp=objecttemps.getPointer(i);
1577 if (temp.getType().isNull())
1578 output.println(" void * "+temp.getSafeSymbol()+";");
1579 else if(temp.getType().isTag())
1580 output.println(" struct "+
1581 (new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1583 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1585 output.println("};\n");
1588 /* Output task declaration */
1589 headersout.print("void " + task.getSafeSymbol()+"(");
1591 boolean printcomma=false;
1592 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1593 headersout.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
1595 headersout.print("void * parameterarray[]");
1596 headersout.println(");\n");
1600 /***** Generate code for FlatMethod fm. *****/
1602 Hashtable<FlatAtomicEnterNode, AtomicRecord> atomicmethodmap;
1603 static int atomicmethodcount=0;
1606 BranchAnalysis branchanalysis;
1607 private void generateFlatMethod(FlatMethod fm, LocalityBinding lb, PrintWriter output) {
1608 if (State.PRINTFLAT)
1609 System.out.println(fm.printMethod());
1610 MethodDescriptor md=fm.getMethod();
1611 TaskDescriptor task=fm.getTask();
1612 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
1613 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : md!=null ? md : task);
1615 HashSet<AtomicRecord> arset=null;
1616 branchanalysis=null;
1618 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1620 if (atomicmethodmap==null)
1621 atomicmethodmap=new Hashtable<FlatAtomicEnterNode, AtomicRecord>();
1623 //fix these so we get right strings for local variables
1624 localsprefixaddr=localsprefix;
1625 localsprefixderef=localsprefix+"->";
1626 arset=new HashSet<AtomicRecord>();
1628 //build branchanalysis
1629 branchanalysis=new BranchAnalysis(locality, lb, delaycomp.getNotReady(lb), delaycomp.livecode(lb), state);
1631 //Generate commit methods here
1632 for(Iterator<FlatNode> fnit=fm.getNodeSet().iterator();fnit.hasNext();) {
1633 FlatNode fn=fnit.next();
1634 if (fn.kind()==FKind.FlatAtomicEnterNode&&
1635 locality.getAtomic(lb).get(fn.getPrev(0)).intValue()==0&&
1636 delaycomp.needsFission(lb, (FlatAtomicEnterNode) fn)) {
1637 //We have an atomic enter
1638 FlatAtomicEnterNode faen=(FlatAtomicEnterNode) fn;
1639 Set<FlatNode> exitset=faen.getExits();
1641 String methodname=md.getSymbol()+(atomicmethodcount++);
1642 AtomicRecord ar=new AtomicRecord();
1646 atomicmethodmap.put(faen, ar);
1648 //build data structure declaration
1649 output.println("struct atomicprimitives_"+methodname+" {");
1651 Set<FlatNode> recordset=delaycomp.livecode(lb);
1652 Set<TempDescriptor> liveinto=delaycomp.liveinto(lb, faen, recordset);
1653 Set<TempDescriptor> liveout=delaycomp.liveout(lb, faen);
1654 Set<TempDescriptor> liveoutvirtualread=delaycomp.liveoutvirtualread(lb, faen);
1656 ar.reallivein=new HashSet(liveinto);
1658 ar.liveoutvirtualread=liveoutvirtualread;
1661 for(Iterator<TempDescriptor> it=liveinto.iterator(); it.hasNext();) {
1662 TempDescriptor tmp=it.next();
1663 //remove the pointers
1664 if (tmp.getType().isPtr()) {
1667 //let's print it here
1668 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1671 for(Iterator<TempDescriptor> it=liveout.iterator(); it.hasNext();) {
1672 TempDescriptor tmp=it.next();
1673 //remove the pointers
1674 if (tmp.getType().isPtr()) {
1676 } else if (!liveinto.contains(tmp)) {
1677 //let's print it here
1678 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1681 output.println("};");
1683 //print out method name
1684 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) {");
1685 //build code for commit method
1687 //first define local primitives
1688 Set<TempDescriptor> alltemps=delaycomp.alltemps(lb, faen, recordset);
1689 for(Iterator<TempDescriptor> tmpit=alltemps.iterator();tmpit.hasNext();) {
1690 TempDescriptor tmp=tmpit.next();
1691 if (!tmp.getType().isPtr()) {
1692 if (liveinto.contains(tmp)||liveoutvirtualread.contains(tmp)) {
1693 //read from live into set
1694 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+"=primitives->"+tmp.getSafeSymbol()+";");
1697 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1701 //turn off write barrier generation
1703 state.SINGLETM=false;
1704 generateCode(faen, fm, lb, exitset, output, false);
1705 state.SINGLETM=true;
1706 //turn on write barrier generation
1708 output.println("}\n\n");
1712 //redefine these back to normal
1714 localsprefixaddr="&"+localsprefix;
1715 localsprefixderef=localsprefix+".";
1717 generateHeader(fm, lb, md!=null ? md : task,output);
1718 TempObject objecttemp=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
1720 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1721 for(Iterator<AtomicRecord> arit=arset.iterator();arit.hasNext();) {
1722 AtomicRecord ar=arit.next();
1723 output.println("struct atomicprimitives_"+ar.name+" primitives_"+ar.name+";");
1727 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1728 if (md!=null&&(state.DSM||state.SINGLETM))
1729 output.print(" struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1730 else if (md!=null&&!(state.DSM||state.SINGLETM))
1731 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1733 output.print(" struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={");
1735 output.print(objecttemp.numPointers()+",");
1736 output.print(paramsprefix);
1737 for(int j=0; j<objecttemp.numPointers(); j++)
1738 output.print(", NULL");
1739 output.println("};");
1742 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1743 TempDescriptor td=objecttemp.getPrimitive(i);
1744 TypeDescriptor type=td.getType();
1746 output.println(" void * "+td.getSafeSymbol()+";");
1747 else if (type.isClass()||type.isArray())
1748 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1750 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1755 if( fm.getNext(0) instanceof FlatSESEEnterNode ) {
1756 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
1757 if( callerSESEplaceholder != mlpa.getMainSESE() ) {
1758 // declare variables for naming static SESE's
1759 output.println(" /* static SESE names */");
1760 Iterator<SESEandAgePair> pItr = callerSESEplaceholder.getNeededStaticNames().iterator();
1761 while( pItr.hasNext() ) {
1762 SESEandAgePair pair = pItr.next();
1763 output.println(" void* "+pair+";");
1766 // declare variables for tracking dynamic sources
1767 output.println(" /* dynamic variable sources */");
1768 Iterator<TempDescriptor> dynSrcItr = callerSESEplaceholder.getDynamicVarSet().iterator();
1769 while( dynSrcItr.hasNext() ) {
1770 TempDescriptor dynSrcVar = dynSrcItr.next();
1771 output.println(" void* "+dynSrcVar+"_srcSESE;");
1772 output.println(" int "+dynSrcVar+"_srcOffset;");
1777 // set up related allocation sites's waiting queues
1779 ConflictGraph graph = null;
1780 graph = mlpa.getConflictGraphResults().get(fm);
1781 if (graph != null && graph.hasConflictEdge()) {
1782 output.println(" /* set up waiting queues */");
1783 output.println(" int numMemoryQueue=0;");
1784 output.println(" int memoryQueueItemID=0;");
1785 HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
1787 System.out.println("#lockSet="+lockSet.hashCode());
1788 System.out.println("lockset="+lockSet);
1789 for (Iterator iterator = lockSet.iterator(); iterator.hasNext();) {
1790 SESELock seseLock = (SESELock) iterator.next();
1791 System.out.println("id="+seseLock.getID());
1792 System.out.println("#="+seseLock);
1794 System.out.println("size="+lockSet.size());
1795 if (lockSet.size() > 0) {
1796 output.println(" numMemoryQueue=" + lockSet.size() + ";");
1798 .println(" seseCaller->numMemoryQueue=numMemoryQueue;");
1800 .println(" seseCaller->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
1807 /* Check to see if we need to do a GC if this is a
1808 * multi-threaded program...*/
1810 if (((state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
1811 || this.state.MULTICOREGC) {
1812 //Don't bother if we aren't in recursive methods...The loops case will catch it
1813 if (callgraph.getAllMethods(md).contains(md)) {
1814 if (state.DSM&&lb.isAtomic())
1815 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
1816 else if (this.state.MULTICOREGC) {
1817 output.println("if(gcflag) gc("+localsprefixaddr+");");
1819 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
1824 generateCode(fm.getNext(0), fm, lb, null, output, true);
1826 output.println("}\n\n");
1830 protected void initializeSESE( FlatSESEEnterNode fsen ) {
1832 FlatMethod fm = fsen.getfmEnclosing();
1833 MethodDescriptor md = fm.getMethod();
1834 ClassDescriptor cn = md.getClassDesc();
1837 // Creates bogus method descriptor to index into tables
1838 Modifiers modBogus = new Modifiers();
1839 MethodDescriptor mdBogus =
1840 new MethodDescriptor( modBogus,
1841 new TypeDescriptor( TypeDescriptor.VOID ),
1842 "sese_"+fsen.getPrettyIdentifier()+fsen.getIdentifier()
1845 mdBogus.setClassDesc( fsen.getcdEnclosing() );
1846 FlatMethod fmBogus = new FlatMethod( mdBogus, null );
1847 fsen.setfmBogus( fmBogus );
1848 fsen.setmdBogus( mdBogus );
1850 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1851 inSetAndOutSet.addAll( fsen.getInVarSet() );
1852 inSetAndOutSet.addAll( fsen.getOutVarSet() );
1854 // Build paramsobj for bogus method descriptor
1855 ParamsObject objectparams = new ParamsObject( mdBogus, tag++ );
1856 paramstable.put( mdBogus, objectparams );
1858 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1859 while( itr.hasNext() ) {
1860 TempDescriptor temp = itr.next();
1861 TypeDescriptor type = temp.getType();
1862 if( type.isPtr() ) {
1863 objectparams.addPtr( temp );
1865 objectparams.addPrim( temp );
1869 // Build normal temp object for bogus method descriptor
1870 TempObject objecttemps = new TempObject( objectparams, mdBogus, tag++ );
1871 tempstable.put( mdBogus, objecttemps );
1873 for( Iterator nodeit = fsen.getNodeSet().iterator(); nodeit.hasNext(); ) {
1874 FlatNode fn = (FlatNode)nodeit.next();
1875 TempDescriptor[] writes = fn.writesTemps();
1877 for( int i = 0; i < writes.length; i++ ) {
1878 TempDescriptor temp = writes[i];
1879 TypeDescriptor type = temp.getType();
1881 if( type.isPtr() ) {
1882 objecttemps.addPtr( temp );
1884 objecttemps.addPrim( temp );
1890 protected void generateMethodSESE(FlatSESEEnterNode fsen,
1892 PrintWriter outputStructs,
1893 PrintWriter outputMethHead,
1894 PrintWriter outputMethods
1897 ParamsObject objectparams = (ParamsObject) paramstable.get( fsen.getmdBogus() );
1898 TempObject objecttemps = (TempObject) tempstable .get( fsen.getmdBogus() );
1900 // generate locals structure
1901 outputStructs.println("struct "+
1902 fsen.getcdEnclosing().getSafeSymbol()+
1903 fsen.getmdBogus().getSafeSymbol()+"_"+
1904 fsen.getmdBogus().getSafeMethodDescriptor()+
1906 outputStructs.println(" INTPTR size;");
1907 outputStructs.println(" void * next;");
1908 for(int i=0; i<objecttemps.numPointers(); i++) {
1909 TempDescriptor temp=objecttemps.getPointer(i);
1911 if (temp.getType().isNull())
1912 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
1914 outputStructs.println(" struct "+
1915 temp.getType().getSafeSymbol()+" * "+
1916 temp.getSafeSymbol()+";");
1918 outputStructs.println("};\n");
1921 // generate the SESE record structure
1922 outputStructs.println(fsen.getSESErecordName()+" {");
1924 // data common to any SESE, and it must be placed first so
1925 // a module that doesn't know what kind of SESE record this
1926 // is can cast the pointer to a common struct
1927 outputStructs.println(" SESEcommon common;");
1929 // then garbage list stuff
1930 outputStructs.println(" INTPTR size;");
1931 outputStructs.println(" void * next;");
1933 // in-set source tracking
1934 // in-vars that are READY come from parent, don't need anything
1935 // stuff STATIC needs a custom SESE pointer for each age pair
1936 Iterator<SESEandAgePair> itrStaticInVarSrcs = fsen.getStaticInVarSrcs().iterator();
1937 while( itrStaticInVarSrcs.hasNext() ) {
1938 SESEandAgePair srcPair = itrStaticInVarSrcs.next();
1939 outputStructs.println(" "+srcPair.getSESE().getSESErecordName()+"* "+srcPair+";");
1942 // DYNAMIC stuff needs a source SESE ptr and offset
1943 Iterator<TempDescriptor> itrDynInVars = fsen.getDynamicInVarSet().iterator();
1944 while( itrDynInVars.hasNext() ) {
1945 TempDescriptor dynInVar = itrDynInVars.next();
1946 outputStructs.println(" void* "+dynInVar+"_srcSESE;");
1947 outputStructs.println(" int "+dynInVar+"_srcOffset;");
1950 // space for all in and out set primitives
1951 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1952 inSetAndOutSet.addAll( fsen.getInVarSet() );
1953 inSetAndOutSet.addAll( fsen.getOutVarSet() );
1955 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
1957 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1958 while( itr.hasNext() ) {
1959 TempDescriptor temp = itr.next();
1960 TypeDescriptor type = temp.getType();
1961 if( !type.isPtr() ) {
1962 inSetAndOutSetPrims.add( temp );
1966 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
1967 while( itrPrims.hasNext() ) {
1968 TempDescriptor temp = itrPrims.next();
1969 TypeDescriptor type = temp.getType();
1970 outputStructs.println(" "+temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol()+";");
1973 for(int i=0; i<objectparams.numPointers(); i++) {
1974 TempDescriptor temp=objectparams.getPointer(i);
1975 if (temp.getType().isNull())
1976 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
1978 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1981 outputStructs.println("};\n");
1984 // write method declaration to header file
1985 outputMethHead.print("void ");
1986 outputMethHead.print(fsen.getSESEmethodName()+"(");
1987 outputMethHead.print(fsen.getSESErecordName()+"* "+paramsprefix);
1988 outputMethHead.println(");\n");
1991 generateFlatMethodSESE( fsen.getfmBogus(),
1992 fsen.getcdEnclosing(),
1998 private void generateFlatMethodSESE(FlatMethod fm,
2000 FlatSESEEnterNode fsen,
2001 FlatSESEExitNode seseExit,
2005 MethodDescriptor md=fm.getMethod();
2007 output.print("void ");
2008 output.print(fsen.getSESEmethodName()+"(");
2009 output.print(fsen.getSESErecordName()+"* "+paramsprefix);
2010 output.println("){\n");
2012 TempObject objecttemp=(TempObject) tempstable.get(md);
2014 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2015 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
2016 output.print(objecttemp.numPointers()+",");
2017 output.print("(void*) &("+paramsprefix+"->size)");
2018 for(int j=0; j<objecttemp.numPointers(); j++)
2019 output.print(", NULL");
2020 output.println("};");
2023 output.println(" /* regular local primitives */");
2024 for(int i=0; i<objecttemp.numPrimitives(); i++) {
2025 TempDescriptor td=objecttemp.getPrimitive(i);
2026 TypeDescriptor type=td.getType();
2028 output.println(" void * "+td.getSafeSymbol()+";");
2029 else if (type.isClass()||type.isArray())
2030 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
2032 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
2036 // declare variables for naming static SESE's
2037 output.println(" /* static SESE names */");
2038 Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
2039 while( pItr.hasNext() ) {
2040 SESEandAgePair pair = pItr.next();
2041 output.println(" void* "+pair+";");
2044 // declare variables for tracking dynamic sources
2045 output.println(" /* dynamic variable sources */");
2046 Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
2047 while( dynSrcItr.hasNext() ) {
2048 TempDescriptor dynSrcVar = dynSrcItr.next();
2049 output.println(" void* "+dynSrcVar+"_srcSESE;");
2050 output.println(" int "+dynSrcVar+"_srcOffset;");
2053 // declare local temps for in-set primitives, and if it is
2054 // a ready-source variable, get the value from the record
2055 output.println(" /* local temps for in-set primitives */");
2056 Iterator<TempDescriptor> itrInSet = fsen.getInVarSet().iterator();
2057 while( itrInSet.hasNext() ) {
2058 TempDescriptor temp = itrInSet.next();
2059 TypeDescriptor type = temp.getType();
2060 if( !type.isPtr() ) {
2061 if( fsen.getReadyInVarSet().contains( temp ) ) {
2062 output.println(" "+type+" "+temp+" = "+paramsprefix+"->"+temp+";");
2064 output.println(" "+type+" "+temp+";");
2069 // declare local temps for out-set primitives if its not already
2070 // in the in-set, and it's value will get written so no problem
2071 output.println(" /* local temp for out-set prim, not already in the in-set */");
2072 Iterator<TempDescriptor> itrOutSet = fsen.getOutVarSet().iterator();
2073 while( itrOutSet.hasNext() ) {
2074 TempDescriptor temp = itrOutSet.next();
2075 TypeDescriptor type = temp.getType();
2076 if( !type.isPtr() && !fsen.getInVarSet().contains( temp ) ) {
2077 output.println(" "+type+" "+temp+";");
2081 // setup memory queue
2083 output.println(" // set up memory queues ");
2084 output.println(" int numMemoryQueue=0;");
2085 output.println(" int memoryQueueItemID=0;");
2086 ConflictGraph graph = null;
2087 graph = mlpa.getConflictGraphResults().get(fsen);
2088 if (graph != null && graph.hasConflictEdge()) {
2089 output.println(" {");
2091 .println(" SESEcommon* parentCommon = &(___params___->common);");
2092 HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
2094 System.out.println("#lockSet="+lockSet);
2096 if (lockSet.size() > 0) {
2097 output.println(" numMemoryQueue=" + lockSet.size() + ";");
2099 .println(" parentCommon->numMemoryQueue=numMemoryQueue;");
2101 .println(" parentCommon->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2104 output.println(" }");
2108 // copy in-set into place, ready vars were already
2109 // copied when the SESE was issued
2110 Iterator<TempDescriptor> tempItr;
2112 // static vars are from a known SESE
2113 tempItr = fsen.getStaticInVarSet().iterator();
2114 while( tempItr.hasNext() ) {
2115 TempDescriptor temp = tempItr.next();
2116 VariableSourceToken vst = fsen.getStaticInVarSrc( temp );
2117 SESEandAgePair srcPair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2119 // can't grab something from this source until it is done
2120 output.println(" {");
2122 If we are running, everything is done. This check is redundant.
2124 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+srcPair+";" );
2125 output.println(" pthread_mutex_lock( &(com->lock) );");
2126 output.println(" while( com->doneExecuting == FALSE ) {");
2127 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
2128 output.println(" }");
2129 output.println(" pthread_mutex_unlock( &(com->lock) );");
2131 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2132 " = "+paramsprefix+"->"+srcPair+"->"+vst.getAddrVar()+";");
2134 output.println(" }");
2137 // dynamic vars come from an SESE and src
2138 tempItr = fsen.getDynamicInVarSet().iterator();
2139 while( tempItr.hasNext() ) {
2140 TempDescriptor temp = tempItr.next();
2141 TypeDescriptor type = temp.getType();
2143 // go grab it from the SESE source
2144 output.println(" if( "+paramsprefix+"->"+temp+"_srcSESE != NULL ) {");
2146 // gotta wait until the source is done
2147 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+temp+"_srcSESE;" );
2149 If we are running, everything is done!
2150 output.println(" pthread_mutex_lock( &(com->lock) );");
2151 output.println(" while( com->doneExecuting == FALSE ) {");
2152 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
2153 output.println(" }");
2154 output.println(" pthread_mutex_unlock( &(com->lock) );");
2158 if( type.isNull() ) {
2160 } else if( type.isClass() || type.isArray() ) {
2161 typeStr = "struct "+type.getSafeSymbol()+"*";
2163 typeStr = type.getSafeSymbol();
2166 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2167 " = *(("+typeStr+"*) ("+
2168 paramsprefix+"->"+temp+"_srcSESE + "+
2169 paramsprefix+"->"+temp+"_srcOffset));");
2171 // or if the source was our parent, its in the record to grab
2172 output.println(" } else {");
2173 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2174 " = "+paramsprefix+"->"+temp+";");
2175 output.println(" }");
2178 // Check to see if we need to do a GC if this is a
2179 // multi-threaded program...
2180 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2181 //Don't bother if we aren't in recursive methods...The loops case will catch it
2182 if (callgraph.getAllMethods(md).contains(md)) {
2183 if(this.state.MULTICOREGC) {
2184 output.println("if(gcflag) gc("+localsprefixaddr+");");
2186 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2191 // initialize thread-local var to a non-zero, invalid address
2192 output.println(" seseCaller = (SESEcommon*) 0x2;");
2193 HashSet<FlatNode> exitset=new HashSet<FlatNode>();
2194 exitset.add(seseExit);
2195 generateCode(fsen.getNext(0), fm, null, exitset, output, true);
2196 output.println("}\n\n");
2201 // when a new mlp thread is created for an issued SESE, it is started
2202 // by running this method which blocks on a cond variable until
2203 // it is allowed to transition to execute. Then a case statement
2204 // allows it to invoke the method with the proper SESE body, and after
2205 // exiting the SESE method, executes proper SESE exit code before the
2206 // thread can be destroyed
2207 private void generateSESEinvocationMethod(PrintWriter outmethodheader,
2208 PrintWriter outmethod
2211 outmethodheader.println("void* invokeSESEmethod( void* seseRecord );");
2212 outmethod.println( "void* invokeSESEmethod( void* seseRecord ) {");
2213 outmethod.println( " int status;");
2214 outmethod.println( " char errmsg[128];");
2216 // generate a case for each SESE class that can be invoked
2217 outmethod.println( " switch( *((int*)seseRecord) ) {");
2218 outmethod.println( " ");
2219 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
2220 FlatSESEEnterNode fsen = seseit.next();
2222 outmethod.println( " /* "+fsen.getPrettyIdentifier()+" */");
2223 outmethod.println( " case "+fsen.getIdentifier()+":");
2224 outmethod.println( " "+fsen.getSESEmethodName()+"( seseRecord );");
2226 if( fsen.equals( mlpa.getMainSESE() ) ) {
2227 outmethod.println( " /* work scheduler works forever, explicitly exit */");
2228 outmethod.println( " exit( 0 );");
2231 outmethod.println( " break;");
2232 outmethod.println( "");
2235 // default case should never be taken, error out
2236 outmethod.println( " default:");
2237 outmethod.println( " printf(\"Error: unknown SESE class ID in invoke method.\\n\");");
2238 outmethod.println( " exit(-30);");
2239 outmethod.println( " break;");
2240 outmethod.println( " }");
2241 outmethod.println( " return NULL;");
2242 outmethod.println( "}\n\n");
2246 protected void generateCode(FlatNode first,
2249 Set<FlatNode> stopset,
2250 PrintWriter output, boolean firstpass) {
2252 /* Assign labels to FlatNode's if necessary.*/
2254 Hashtable<FlatNode, Integer> nodetolabel;
2256 if (state.DELAYCOMP&&!firstpass)
2257 nodetolabel=dcassignLabels(first, stopset);
2259 nodetolabel=assignLabels(first, stopset);
2261 Set<FlatNode> storeset=null;
2262 HashSet<FlatNode> genset=null;
2263 HashSet<FlatNode> refset=null;
2264 Set<FlatNode> unionset=null;
2266 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
2267 storeset=delaycomp.livecode(lb);
2268 genset=new HashSet<FlatNode>();
2269 if (state.STMARRAY&&!state.DUALVIEW) {
2270 refset=new HashSet<FlatNode>();
2271 refset.addAll(delaycomp.getDeref(lb));
2272 refset.removeAll(delaycomp.getCannotDelay(lb));
2273 refset.removeAll(delaycomp.getOther(lb));
2276 genset.addAll(delaycomp.getCannotDelay(lb));
2277 genset.addAll(delaycomp.getOther(lb));
2279 genset.addAll(delaycomp.getNotReady(lb));
2280 if (state.STMARRAY&&!state.DUALVIEW) {
2281 genset.removeAll(refset);
2284 unionset=new HashSet<FlatNode>();
2285 unionset.addAll(storeset);
2286 unionset.addAll(genset);
2287 if (state.STMARRAY&&!state.DUALVIEW)
2288 unionset.addAll(refset);
2291 /* Do the actual code generation */
2292 FlatNode current_node=null;
2293 HashSet tovisit=new HashSet();
2294 HashSet visited=new HashSet();
2296 tovisit.add(first.getNext(0));
2299 while(current_node!=null||!tovisit.isEmpty()) {
2300 if (current_node==null) {
2301 current_node=(FlatNode)tovisit.iterator().next();
2302 tovisit.remove(current_node);
2303 } else if (tovisit.contains(current_node)) {
2304 tovisit.remove(current_node);
2306 visited.add(current_node);
2307 if (nodetolabel.containsKey(current_node)) {
2308 output.println("L"+nodetolabel.get(current_node)+":");
2310 if (state.INSTRUCTIONFAILURE) {
2311 if (state.THREAD||state.DSM||state.SINGLETM) {
2312 output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
2314 output.println("if ((--instructioncount)==0) injectinstructionfailure();");
2316 if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
2318 if (!state.DELAYCOMP||firstpass) {
2319 generateFlatNode(fm, lb, current_node, output);
2321 //store primitive variables in out set
2322 AtomicRecord ar=atomicmethodmap.get((FlatAtomicEnterNode)first);
2323 Set<TempDescriptor> liveout=ar.liveout;
2324 for(Iterator<TempDescriptor> tmpit=liveout.iterator();tmpit.hasNext();) {
2325 TempDescriptor tmp=tmpit.next();
2326 output.println("primitives->"+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2329 if (state.MLP && stopset!=null) {
2330 assert first.getPrev( 0 ) instanceof FlatSESEEnterNode;
2331 assert current_node instanceof FlatSESEExitNode;
2332 FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev( 0 );
2333 FlatSESEExitNode fsxn = (FlatSESEExitNode) current_node;
2334 assert fsen.getFlatExit().equals( fsxn );
2335 assert fsxn.getFlatEnter().equals( fsen );
2337 if (current_node.kind()!=FKind.FlatReturnNode) {
2338 output.println(" return;");
2341 } else if(current_node.numNext()==1) {
2344 current_node.kind()==FKind.FlatSESEEnterNode &&
2345 !((FlatSESEEnterNode)current_node).getIsCallerSESEplaceholder()
2347 FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
2348 generateFlatNode(fm, lb, current_node, output);
2349 nextnode=fsen.getFlatExit().getNext(0);
2350 } else if (state.DELAYCOMP) {
2351 boolean specialprimitive=false;
2352 //skip literals...no need to add extra overhead
2353 if (storeset!=null&&storeset.contains(current_node)&¤t_node.kind()==FKind.FlatLiteralNode) {
2354 TypeDescriptor typedesc=((FlatLiteralNode)current_node).getType();
2355 if (!typedesc.isClass()&&!typedesc.isArray()) {
2356 specialprimitive=true;
2360 if (genset==null||genset.contains(current_node)||specialprimitive)
2361 generateFlatNode(fm, lb, current_node, output);
2362 if (state.STMARRAY&&!state.DUALVIEW&&refset!=null&&refset.contains(current_node)) {
2363 //need to acquire lock
2364 handleArrayDeref(fm, lb, current_node, output, firstpass);
2366 if (storeset!=null&&storeset.contains(current_node)&&!specialprimitive) {
2367 TempDescriptor wrtmp=current_node.writesTemps()[0];
2369 //need to store value written by previous node
2370 if (wrtmp.getType().isPtr()) {
2371 //only lock the objects that may actually need locking
2372 if (recorddc.getNeedTrans(lb, current_node)&&
2373 (!state.STMARRAY||state.DUALVIEW||!wrtmp.getType().isArray()||
2374 wrtmp.getType().getSymbol().equals(TypeUtil.ObjectClass))) {
2375 output.println("STOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2377 output.println("STOREPTRNOLOCK("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2380 output.println("STORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");/* "+current_node.nodeid+" */");
2383 //need to read value read by previous node
2384 if (wrtmp.getType().isPtr()) {
2385 output.println("RESTOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2387 output.println("RESTORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+"); /* "+current_node.nodeid+" */");
2391 nextnode=current_node.getNext(0);
2394 generateFlatNode(fm, lb, current_node, output);
2395 nextnode=current_node.getNext(0);
2397 if (visited.contains(nextnode)) {
2398 output.println("goto L"+nodetolabel.get(nextnode)+";");
2401 current_node=nextnode;
2402 } else if (current_node.numNext()==2) {
2404 if (state.DELAYCOMP) {
2405 boolean computeside=false;
2407 //need to record which way it should go
2408 if (genset==null||genset.contains(current_node)) {
2409 if (storeset!=null&&storeset.contains(current_node)) {
2410 //need to store which way branch goes
2411 generateStoreFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2413 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2415 //which side to execute
2419 if (genset.contains(current_node)) {
2420 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2421 } else if (storeset.contains(current_node)) {
2423 branchanalysis.generateGroupCode(current_node, output, nodetolabel);
2425 //which side to execute
2430 Set<FlatNode> leftset=DelayComputation.getNext(current_node, 0, unionset, lb,locality, true);
2432 if (leftset.size()==0)
2434 if (visited.contains(current_node.getNext(branch))) {
2435 //already visited -- build jump
2436 output.println("goto L"+nodetolabel.get(current_node.getNext(branch))+";");
2439 current_node=current_node.getNext(branch);
2442 if (!visited.contains(current_node.getNext(1)))
2443 tovisit.add(current_node.getNext(1));
2444 if (visited.contains(current_node.getNext(0))) {
2445 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2448 current_node=current_node.getNext(0);
2452 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2453 if (!visited.contains(current_node.getNext(1)))
2454 tovisit.add(current_node.getNext(1));
2455 if (visited.contains(current_node.getNext(0))) {
2456 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2459 current_node=current_node.getNext(0);
2461 } else throw new Error();
2465 protected void handleArrayDeref(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output, boolean firstpass) {
2466 if (fn.kind()==FKind.FlatSetElementNode) {
2467 FlatSetElementNode fsen=(FlatSetElementNode) fn;
2468 String dst=generateTemp(fm, fsen.getDst(), lb);
2469 String src=generateTemp(fm, fsen.getSrc(), lb);
2470 String index=generateTemp(fm, fsen.getIndex(), lb);
2471 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
2473 if (elementtype.isArray()||elementtype.isClass())
2476 type=elementtype.getSafeSymbol()+" ";
2478 output.println("STOREARRAY("+dst+","+index+","+type+")");
2480 output.println("{");
2481 output.println(" struct ArrayObject *array;");
2482 output.println(" int index;");
2483 output.println(" RESTOREARRAY(array,index);");
2484 output.println(" (("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index]="+src+";");
2485 output.println("}");
2487 } else if (fn.kind()==FKind.FlatElementNode) {
2488 FlatElementNode fen=(FlatElementNode) fn;
2489 String src=generateTemp(fm, fen.getSrc(), lb);
2490 String index=generateTemp(fm, fen.getIndex(), lb);
2491 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
2492 String dst=generateTemp(fm, fen.getDst(), lb);
2494 if (elementtype.isArray()||elementtype.isClass())
2497 type=elementtype.getSafeSymbol()+" ";
2499 output.println("STOREARRAY("+src+","+index+","+type+")");
2501 output.println("{");
2502 output.println(" struct ArrayObject *array;");
2503 output.println(" int index;");
2504 output.println(" RESTOREARRAY(array,index);");
2505 output.println(" "+dst+"=(("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index];");
2506 output.println("}");
2510 /** Special label assignment for delaycomputation */
2511 protected Hashtable<FlatNode, Integer> dcassignLabels(FlatNode first, Set<FlatNode> lastset) {
2512 HashSet tovisit=new HashSet();
2513 HashSet visited=new HashSet();
2515 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2517 //Label targets of branches
2518 Set<FlatNode> targets=branchanalysis.getTargets();
2519 for(Iterator<FlatNode> it=targets.iterator();it.hasNext();) {
2520 nodetolabel.put(it.next(), new Integer(labelindex++));
2525 /*Assign labels first. A node needs a label if the previous
2526 * node has two exits or this node is a join point. */
2528 while(!tovisit.isEmpty()) {
2529 FlatNode fn=(FlatNode)tovisit.iterator().next();
2534 if(lastset!=null&&lastset.contains(fn)) {
2535 // if last is not null and matches, don't go
2536 // any further for assigning labels
2540 for(int i=0; i<fn.numNext(); i++) {
2541 FlatNode nn=fn.getNext(i);
2544 //1) Edge >1 of node
2545 nodetolabel.put(nn,new Integer(labelindex++));
2547 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2551 nodetolabel.put(nn,new Integer(labelindex++));
2559 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first) {
2560 return assignLabels(first, null);
2563 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
2564 HashSet tovisit=new HashSet();
2565 HashSet visited=new HashSet();
2567 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2570 /*Assign labels first. A node needs a label if the previous
2571 * node has two exits or this node is a join point. */
2573 while(!tovisit.isEmpty()) {
2574 FlatNode fn=(FlatNode)tovisit.iterator().next();
2579 if(lastset!=null&&lastset.contains(fn)) {
2580 // if last is not null and matches, don't go
2581 // any further for assigning labels
2585 for(int i=0; i<fn.numNext(); i++) {
2586 FlatNode nn=fn.getNext(i);
2589 //1) Edge >1 of node
2590 nodetolabel.put(nn,new Integer(labelindex++));
2592 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2596 nodetolabel.put(nn,new Integer(labelindex++));
2604 /** Generate text string that corresponds to the TempDescriptor td. */
2605 protected String generateTemp(FlatMethod fm, TempDescriptor td, LocalityBinding lb) {
2606 MethodDescriptor md=fm.getMethod();
2607 TaskDescriptor task=fm.getTask();
2608 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
2610 if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
2611 return td.getSafeSymbol();
2614 if (objecttemps.isLocalPtr(td)) {
2615 return localsprefixderef+td.getSafeSymbol();
2618 if (objecttemps.isParamPtr(td)) {
2619 return paramsprefix+"->"+td.getSafeSymbol();
2625 protected void generateFlatNode(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output) {
2627 // insert pre-node actions from the code plan
2630 CodePlan cp = mlpa.getCodePlan( fn );
2633 FlatSESEEnterNode currentSESE = cp.getCurrentSESE();
2635 // for each sese and age pair that this parent statement
2636 // must stall on, take that child's stall semaphore, the
2637 // copying of values comes after the statement
2638 Iterator<VariableSourceToken> vstItr = cp.getStallTokens().iterator();
2639 while( vstItr.hasNext() ) {
2640 VariableSourceToken vst = vstItr.next();
2642 SESEandAgePair pair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2644 output.println(" {");
2645 output.println(" SESEcommon* common = (SESEcommon*) "+pair+";");
2647 output.println(" pthread_mutex_lock( &(common->lock) );");
2648 output.println(" while( common->doneExecuting == FALSE ) {");
2649 output.println(" pthread_cond_wait( &(common->doneCond), &(common->lock) );");
2650 output.println(" }");
2651 output.println(" pthread_mutex_unlock( &(common->lock) );");
2653 // copy things we might have stalled for
2654 output.println(" "+pair.getSESE().getSESErecordName()+"* child = ("+
2655 pair.getSESE().getSESErecordName()+"*) "+pair+";");
2657 Iterator<TempDescriptor> tdItr = cp.getCopySet( vst ).iterator();
2658 while( tdItr.hasNext() ) {
2659 TempDescriptor td = tdItr.next();
2660 FlatMethod fmContext;
2661 if( currentSESE.getIsCallerSESEplaceholder() ) {
2662 fmContext = currentSESE.getfmEnclosing();
2664 fmContext = currentSESE.getfmBogus();
2666 output.println(" "+generateTemp( fmContext, td, null )+
2667 " = child->"+vst.getAddrVar().getSafeSymbol()+";");
2670 output.println(" }");
2673 // for each variable with a dynamic source, stall just for that variable
2674 Iterator<TempDescriptor> dynItr = cp.getDynamicStallSet().iterator();
2675 while( dynItr.hasNext() ) {
2676 TempDescriptor dynVar = dynItr.next();
2678 // only stall if the dynamic source is not yourself, denoted by src==NULL
2679 // otherwise the dynamic write nodes will have the local var up-to-date
2680 output.println(" {");
2681 output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
2682 output.println(" SESEcommon* common = (SESEcommon*) "+dynVar+"_srcSESE;");
2683 output.println(" psem_take( &(common->stallSem) );");
2685 FlatMethod fmContext;
2686 if( currentSESE.getIsCallerSESEplaceholder() ) {
2687 fmContext = currentSESE.getfmEnclosing();
2689 fmContext = currentSESE.getfmBogus();
2691 output.println(" "+generateTemp( fmContext, dynVar, null )+
2692 " = *(("+dynVar.getType()+"*) ("+
2693 dynVar+"_srcSESE + "+dynVar+"_srcOffset));");
2695 output.println(" }");
2696 output.println(" }");
2699 // for each assignment of a variable to rhs that has a dynamic source,
2700 // copy the dynamic sources
2701 Iterator dynAssignItr = cp.getDynAssigns().entrySet().iterator();
2702 while( dynAssignItr.hasNext() ) {
2703 Map.Entry me = (Map.Entry) dynAssignItr.next();
2704 TempDescriptor lhs = (TempDescriptor) me.getKey();
2705 TempDescriptor rhs = (TempDescriptor) me.getValue();
2706 output.println(" "+lhs+"_srcSESE = "+rhs+"_srcSESE;");
2707 output.println(" "+lhs+"_srcOffset = "+rhs+"_srcOffset;");
2710 // for each lhs that is dynamic from a non-dynamic source, set the
2711 // dynamic source vars to the current SESE
2712 dynItr = cp.getDynAssignCurr().iterator();
2713 while( dynItr.hasNext() ) {
2714 TempDescriptor dynVar = dynItr.next();
2715 assert currentSESE.getDynamicVarSet().contains( dynVar );
2716 output.println(" "+dynVar+"_srcSESE = NULL;");
2720 // handling stall site
2721 ParentChildConflictsMap conflictsMap = mlpa.getConflictsResults().get(fn);
2722 if (conflictsMap != null) {
2723 Set<Long> allocSet = conflictsMap.getAllocationSiteIDSetofStallSite();
2724 if (allocSet.size() > 0) {
2725 FlatNode enclosingFlatNode=null;
2726 if( currentSESE.getIsCallerSESEplaceholder() && currentSESE.getParent()==null){
2727 enclosingFlatNode=currentSESE.getfmEnclosing();
2729 enclosingFlatNode=currentSESE;
2731 ConflictGraph graph=mlpa.getConflictGraphResults().get(enclosingFlatNode);
2732 HashSet<SESELock> seseLockSet=mlpa.getConflictGraphLockMap().get(graph);
2733 Set<WaitingElement> waitingElementSet=graph.getStallSiteWaitingElementSet(conflictsMap, seseLockSet);
2735 if(waitingElementSet.size()>0){
2736 output.println("// stall on parent's stall sites ");
2737 output.println(" {");
2738 output.println(" REntry* rentry;");
2740 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
2741 WaitingElement waitingElement = (WaitingElement) iterator.next();
2743 if( waitingElement.getStatus() >= ConflictNode.COARSE ){
2744 output.println(" rentry=mlpCreateREntry("+ waitingElement.getStatus()+ ", seseCaller);");
2746 output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", seseCaller, ___locals___."+ waitingElement.getDynID() + ");");
2748 output.println(" psem_init( &(rentry->parentStallSem) );");
2749 output.println(" rentry->queue=seseCaller->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
2751 .println(" if(ADDRENTRY(seseCaller->memoryQueueArray["+ waitingElement.getQueueID()
2752 + "],rentry)==NOTREADY){");
2753 output.println(" psem_take( &(rentry->parentStallSem) );");
2754 output.println(" } ");
2756 output.println(" }");
2765 case FKind.FlatAtomicEnterNode:
2766 generateFlatAtomicEnterNode(fm, lb, (FlatAtomicEnterNode) fn, output);
2769 case FKind.FlatAtomicExitNode:
2770 generateFlatAtomicExitNode(fm, lb, (FlatAtomicExitNode) fn, output);
2773 case FKind.FlatInstanceOfNode:
2774 generateFlatInstanceOfNode(fm, lb, (FlatInstanceOfNode)fn, output);
2777 case FKind.FlatSESEEnterNode:
2778 generateFlatSESEEnterNode(fm, lb, (FlatSESEEnterNode)fn, output);
2781 case FKind.FlatSESEExitNode:
2782 generateFlatSESEExitNode(fm, lb, (FlatSESEExitNode)fn, output);
2785 case FKind.FlatWriteDynamicVarNode:
2786 generateFlatWriteDynamicVarNode(fm, lb, (FlatWriteDynamicVarNode)fn, output);
2789 case FKind.FlatGlobalConvNode:
2790 generateFlatGlobalConvNode(fm, lb, (FlatGlobalConvNode) fn, output);
2793 case FKind.FlatTagDeclaration:
2794 generateFlatTagDeclaration(fm, lb, (FlatTagDeclaration) fn,output);
2797 case FKind.FlatCall:
2798 generateFlatCall(fm, lb, (FlatCall) fn,output);
2801 case FKind.FlatFieldNode:
2802 generateFlatFieldNode(fm, lb, (FlatFieldNode) fn,output);
2805 case FKind.FlatElementNode:
2806 generateFlatElementNode(fm, lb, (FlatElementNode) fn,output);
2809 case FKind.FlatSetElementNode:
2810 generateFlatSetElementNode(fm, lb, (FlatSetElementNode) fn,output);
2813 case FKind.FlatSetFieldNode:
2814 generateFlatSetFieldNode(fm, lb, (FlatSetFieldNode) fn,output);
2818 generateFlatNew(fm, lb, (FlatNew) fn,output);
2821 case FKind.FlatOpNode:
2822 generateFlatOpNode(fm, lb, (FlatOpNode) fn,output);
2825 case FKind.FlatCastNode:
2826 generateFlatCastNode(fm, lb, (FlatCastNode) fn,output);
2829 case FKind.FlatLiteralNode:
2830 generateFlatLiteralNode(fm, lb, (FlatLiteralNode) fn,output);
2833 case FKind.FlatReturnNode:
2834 generateFlatReturnNode(fm, lb, (FlatReturnNode) fn,output);
2838 output.println("/* nop */");
2841 case FKind.FlatExit:
2842 output.println("/* exit */");
2845 case FKind.FlatBackEdge:
2846 if (state.SINGLETM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
2847 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
2849 if(state.DSM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
2850 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
2852 if (((state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
2853 || (this.state.MULTICOREGC)) {
2854 if(state.DSM&&locality.getAtomic(lb).get(fn).intValue()>0) {
2855 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
2856 } else if(this.state.MULTICOREGC) {
2857 output.println("if (gcflag) gc("+localsprefixaddr+");");
2859 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2862 output.println("/* nop */");
2865 case FKind.FlatCheckNode:
2866 generateFlatCheckNode(fm, lb, (FlatCheckNode) fn, output);
2869 case FKind.FlatFlagActionNode:
2870 generateFlatFlagActionNode(fm, lb, (FlatFlagActionNode) fn, output);
2873 case FKind.FlatPrefetchNode:
2874 generateFlatPrefetchNode(fm,lb, (FlatPrefetchNode) fn, output);
2877 case FKind.FlatOffsetNode:
2878 generateFlatOffsetNode(fm, lb, (FlatOffsetNode)fn, output);
2885 // insert post-node actions from the code-plan
2887 CodePlan cp = mlpa.getCodePlan( fn );
2894 public void generateFlatOffsetNode(FlatMethod fm, LocalityBinding lb, FlatOffsetNode fofn, PrintWriter output) {
2895 output.println("/* FlatOffsetNode */");
2896 FieldDescriptor fd=fofn.getField();
2897 output.println(generateTemp(fm, fofn.getDst(),lb)+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+ fd.getSafeSymbol()+");");
2898 output.println("/* offset */");
2901 public void generateFlatPrefetchNode(FlatMethod fm, LocalityBinding lb, FlatPrefetchNode fpn, PrintWriter output) {
2902 if (state.PREFETCH) {
2903 Vector oids = new Vector();
2904 Vector fieldoffset = new Vector();
2905 Vector endoffset = new Vector();
2906 int tuplecount = 0; //Keeps track of number of prefetch tuples that need to be generated
2907 for(Iterator it = fpn.hspp.iterator(); it.hasNext();) {
2908 PrefetchPair pp = (PrefetchPair) it.next();
2909 Integer statusbase = locality.getNodePreTempInfo(lb,fpn).get(pp.base);
2910 /* Find prefetches that can generate oid */
2911 if(statusbase == LocalityAnalysis.GLOBAL) {
2912 generateTransCode(fm, lb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(lb).get(fpn).intValue()>0, false);
2914 } else if (statusbase == LocalityAnalysis.LOCAL) {
2915 generateTransCode(fm,lb,pp,oids,fieldoffset,endoffset,tuplecount,false,true);
2922 System.out.println("Adding prefetch "+fpn+ " to method:" +fm);
2923 output.println("{");
2924 output.println("/* prefetch */");
2925 output.println("/* prefetchid_" + fpn.siteid + " */");
2926 output.println("void * prefptr;");
2927 output.println("int tmpindex;");
2929 output.println("if((evalPrefetch["+fpn.siteid+"].operMode) || (evalPrefetch["+fpn.siteid+"].retrycount <= 0)) {");
2930 /*Create C code for oid array */
2931 output.print(" unsigned int oidarray_[] = {");
2932 boolean needcomma=false;
2933 for (Iterator it = oids.iterator(); it.hasNext();) {
2936 output.print(it.next());
2939 output.println("};");
2941 /*Create C code for endoffset values */
2942 output.print(" unsigned short endoffsetarry_[] = {");
2944 for (Iterator it = endoffset.iterator(); it.hasNext();) {
2947 output.print(it.next());
2950 output.println("};");
2952 /*Create C code for Field Offset Values */
2953 output.print(" short fieldarry_[] = {");
2955 for (Iterator it = fieldoffset.iterator(); it.hasNext();) {
2958 output.print(it.next());
2961 output.println("};");
2962 /* make the prefetch call to Runtime */
2963 output.println(" if(!evalPrefetch["+fpn.siteid+"].operMode) {");
2964 output.println(" evalPrefetch["+fpn.siteid+"].retrycount = RETRYINTERVAL;");
2965 output.println(" }");
2966 output.println(" prefetch("+fpn.siteid+" ,"+tuplecount+", oidarray_, endoffsetarry_, fieldarry_);");
2967 output.println(" } else {");
2968 output.println(" evalPrefetch["+fpn.siteid+"].retrycount--;");
2969 output.println(" }");
2970 output.println("}");
2974 public void generateTransCode(FlatMethod fm, LocalityBinding lb,PrefetchPair pp, Vector oids, Vector fieldoffset, Vector endoffset, int tuplecount, boolean inside, boolean localbase) {
2975 short offsetcount = 0;
2979 } else if (localbase) {
2980 for(; breakindex<pp.desc.size(); breakindex++) {
2981 Descriptor desc=pp.getDescAt(breakindex);
2982 if (desc instanceof FieldDescriptor) {
2983 FieldDescriptor fd=(FieldDescriptor)desc;
2984 if (fd.isGlobal()) {
2992 if (breakindex>pp.desc.size()) //all local
2995 TypeDescriptor lasttype=pp.base.getType();
2996 String basestr=generateTemp(fm, pp.base, lb);
2998 boolean maybenull=fm.getMethod().isStatic()||
2999 !pp.base.equals(fm.getParameter(0));
3001 for(int i=0; i<breakindex; i++) {
3002 String indexcheck="";
3004 Descriptor desc=pp.getDescAt(i);
3005 if (desc instanceof FieldDescriptor) {
3006 FieldDescriptor fd=(FieldDescriptor)desc;
3008 if (!teststr.equals(""))
3010 teststr+="((prefptr="+basestr+")!=NULL)";
3011 basestr="((struct "+lasttype.getSafeSymbol()+" *)prefptr)->"+fd.getSafeSymbol();
3013 basestr=basestr+"->"+fd.getSafeSymbol();
3016 lasttype=fd.getType();
3018 IndexDescriptor id=(IndexDescriptor)desc;
3019 indexcheck="((tmpindex=";
3020 for(int j=0; j<id.tddesc.size(); j++) {
3021 indexcheck+=generateTemp(fm, id.getTempDescAt(j), lb)+"+";
3023 indexcheck+=id.offset+")>=0)&(tmpindex<((struct ArrayObject *)prefptr)->___length___)";
3025 if (!teststr.equals(""))
3027 teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck;
3028 basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]";
3030 lasttype=lasttype.dereference();
3035 if (teststr.equals("")) {
3036 oid="((unsigned int)"+basestr+")";
3038 oid="((unsigned int)(("+teststr+")?"+basestr+":NULL))";
3042 for(int i = breakindex; i < pp.desc.size(); i++) {
3043 String newfieldoffset;
3044 Object desc = pp.getDescAt(i);
3045 if(desc instanceof FieldDescriptor) {
3046 FieldDescriptor fd=(FieldDescriptor)desc;
3047 newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))");
3048 lasttype=fd.getType();
3050 newfieldoffset = "";
3051 IndexDescriptor id=(IndexDescriptor)desc;
3052 for(int j = 0; j < id.tddesc.size(); j++) {
3053 newfieldoffset += generateTemp(fm, id.getTempDescAt(j), lb) + "+";
3055 newfieldoffset += id.offset.toString();
3056 lasttype=lasttype.dereference();
3058 fieldoffset.add(newfieldoffset);
3061 int base=(tuplecount>0) ? ((Short)endoffset.get(tuplecount-1)).intValue() : 0;
3062 base+=pp.desc.size()-breakindex;
3063 endoffset.add(new Short((short)base));
3068 public void generateFlatGlobalConvNode(FlatMethod fm, LocalityBinding lb, FlatGlobalConvNode fgcn, PrintWriter output) {
3069 if (lb!=fgcn.getLocality())
3071 /* Have to generate flat globalconv */
3072 if (fgcn.getMakePtr()) {
3074 //DEBUG: output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+",\" "+fm+":"+fgcn+"\");");
3075 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3077 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fgcn)||state.READSET&&dc.getNeedWriteTrans(lb, fgcn)) {
3078 //need to do translation
3079 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+", (void *)("+localsprefixaddr+"));");
3080 } else if (state.READSET&&dc.getNeedTrans(lb, fgcn)) {
3081 if (state.HYBRID&&delaycomp.getConv(lb).contains(fgcn)) {
3082 output.println("TRANSREADRDFISSION("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3084 output.println("TRANSREADRD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3088 /* Need to convert to OID */
3089 if ((dc==null)||dc.getNeedSrcTrans(lb,fgcn)) {
3090 if (fgcn.doConvert()||(delaycomp!=null&&delaycomp.needsFission(lb, fgcn.getAtomicEnter())&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) {
3091 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc(),lb)+");");
3093 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=NULL;");
3099 public void generateFlatInstanceOfNode(FlatMethod fm, LocalityBinding lb, FlatInstanceOfNode fion, PrintWriter output) {
3101 if (fion.getType().isArray()) {
3102 type=state.getArrayNumber(fion.getType())+state.numClasses();
3104 type=fion.getType().getClassDesc().getId();
3107 if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
3108 output.println(generateTemp(fm, fion.getDst(), lb)+"=1;");
3110 output.println(generateTemp(fm, fion.getDst(), lb)+"=instanceof("+generateTemp(fm,fion.getSrc(),lb)+","+type+");");
3113 int sandboxcounter=0;
3114 public void generateFlatAtomicEnterNode(FlatMethod fm, LocalityBinding lb, FlatAtomicEnterNode faen, PrintWriter output) {
3115 /* Check to see if we need to generate code for this atomic */
3116 if (locality==null) {
3117 if (GENERATEPRECISEGC) {
3118 output.println("if (pthread_mutex_trylock(&atomiclock)!=0) {");
3119 output.println("stopforgc((struct garbagelist *) &___locals___);");
3120 output.println("pthread_mutex_lock(&atomiclock);");
3121 output.println("restartaftergc();");
3122 output.println("}");
3124 output.println("pthread_mutex_lock(&atomiclock);");
3129 if (locality.getAtomic(lb).get(faen.getPrev(0)).intValue()>0)
3133 if (state.SANDBOX) {
3134 outsandbox.println("int atomiccounter"+sandboxcounter+"=LOW_CHECK_FREQUENCY;");
3135 output.println("counter_reset_pointer=&atomiccounter"+sandboxcounter+";");
3138 if (state.DELAYCOMP&&delaycomp.needsFission(lb, faen)) {
3139 AtomicRecord ar=atomicmethodmap.get(faen);
3141 for(Iterator<TempDescriptor> tmpit=ar.livein.iterator();tmpit.hasNext();) {
3142 TempDescriptor tmp=tmpit.next();
3143 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3146 //copy outs that depend on path
3147 for(Iterator<TempDescriptor> tmpit=ar.liveoutvirtualread.iterator();tmpit.hasNext();) {
3148 TempDescriptor tmp=tmpit.next();
3149 if (!ar.livein.contains(tmp))
3150 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3154 /* Backup the temps. */
3155 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3156 TempDescriptor tmp=tmpit.next();
3157 output.println(generateTemp(fm, backuptable.get(lb).get(tmp),lb)+"="+generateTemp(fm,tmp,lb)+";");
3160 output.println("goto transstart"+faen.getIdentifier()+";");
3162 /******* Print code to retry aborted transaction *******/
3163 output.println("transretry"+faen.getIdentifier()+":");
3166 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3167 TempDescriptor tmp=tmpit.next();
3168 output.println(generateTemp(fm, tmp,lb)+"="+generateTemp(fm,backuptable.get(lb).get(tmp),lb)+";");
3172 /********* Need to revert local object store ********/
3173 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3175 output.println("while ("+revertptr+") {");
3176 output.println("struct ___Object___ * tmpptr;");
3177 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3178 output.println("REVERT_OBJ("+revertptr+");");
3179 output.println(revertptr+"=tmpptr;");
3180 output.println("}");
3182 /******* Tell the runtime to start the transaction *******/
3184 output.println("transstart"+faen.getIdentifier()+":");
3185 if (state.SANDBOX) {
3186 output.println("transaction_check_counter=*counter_reset_pointer;");
3189 output.println("transStart();");
3191 if (state.ABORTREADERS||state.SANDBOX) {
3193 output.println("abortenabled=1;");
3194 output.println("if (_setjmp(aborttrans)) {");
3195 output.println(" goto transretry"+faen.getIdentifier()+"; }");
3199 public void generateFlatAtomicExitNode(FlatMethod fm, LocalityBinding lb, FlatAtomicExitNode faen, PrintWriter output) {
3200 /* Check to see if we need to generate code for this atomic */
3201 if (locality==null) {
3202 output.println("pthread_mutex_unlock(&atomiclock);");
3205 if (locality.getAtomic(lb).get(faen).intValue()>0)
3207 //store the revert list before we lose the transaction object
3210 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3211 output.println(revertptr+"=revertlist;");
3212 output.println("if (transCommit()) {");
3213 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3214 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3215 output.println("} else {");
3216 /* Need to commit local object store */
3217 output.println("while ("+revertptr+") {");
3218 output.println("struct ___Object___ * tmpptr;");
3219 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3220 output.println("COMMIT_OBJ("+revertptr+");");
3221 output.println(revertptr+"=tmpptr;");
3222 output.println("}");
3223 output.println("}");
3227 if (!state.DELAYCOMP) {
3229 output.println("if (transCommit()) {");
3230 /* Transaction aborts if it returns true */
3231 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3232 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3233 output.println("}");
3235 if (delaycomp.optimizeTrans(lb, faen.getAtomicEnter())&&(!state.STMARRAY||state.DUALVIEW)) {
3236 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3237 output.println("LIGHTWEIGHTCOMMIT("+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+", transretry"+faen.getAtomicEnter().getIdentifier()+");");
3239 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3240 TempDescriptor tmp=tmpit.next();
3241 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3243 } else if (delaycomp.needsFission(lb, faen.getAtomicEnter())) {
3244 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3246 output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {");
3247 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3248 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3249 output.println("}");
3251 output.println("else {");
3252 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3253 TempDescriptor tmp=tmpit.next();
3254 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3256 output.println("}");
3258 output.println("if (transCommit(NULL, NULL, NULL, NULL)) {");
3259 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3260 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3261 output.println("}");
3266 public void generateFlatSESEEnterNode( FlatMethod fm,
3268 FlatSESEEnterNode fsen,
3272 // if MLP flag is off, okay that SESE nodes are in IR graph,
3273 // just skip over them and code generates exactly the same
3278 // there may be an SESE in an unreachable method, skip over
3279 if( !mlpa.getAllSESEs().contains( fsen ) ) {
3283 // also, if we have encountered a placeholder, just skip it
3284 if( fsen.getIsCallerSESEplaceholder() ) {
3288 output.println(" {");
3290 // set up the parent
3291 if( fsen == mlpa.getMainSESE() ) {
3292 output.println(" SESEcommon* parentCommon = NULL;");
3294 if( fsen.getParent() == null ) {
3295 System.out.println( "in "+fm+", "+fsen+" has null parent" );
3297 assert fsen.getParent() != null;
3298 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3299 output.println(" SESEcommon* parentCommon = &("+paramsprefix+"->common);");
3301 //output.println(" SESEcommon* parentCommon = (SESEcommon*) peekItem( seseCallStack );");
3302 output.println(" SESEcommon* parentCommon = seseCaller;");
3306 // before doing anything, lock your own record and increment the running children
3307 if( fsen != mlpa.getMainSESE() ) {
3308 output.println(" atomic_inc(&parentCommon->numRunningChildren);");
3311 // just allocate the space for this record
3312 output.println(" "+fsen.getSESErecordName()+"* seseToIssue = ("+
3313 fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
3314 fsen.getSESErecordName()+" ) );");
3316 // and keep the thread-local sese stack up to date
3317 //output.println(" addNewItem( seseCallStack, (void*) seseToIssue);");
3319 // fill in common data
3320 output.println(" int localCount=0;");
3321 output.println(" seseToIssue->common.classID = "+fsen.getIdentifier()+";");
3322 output.println(" psem_init( &(seseToIssue->common.stallSem) );");
3324 output.println(" seseToIssue->common.forwardList = createQueue();");
3325 output.println(" seseToIssue->common.unresolvedDependencies = 10000;");
3326 output.println(" pthread_cond_init( &(seseToIssue->common.doneCond), NULL );");
3327 output.println(" seseToIssue->common.doneExecuting = FALSE;");
3328 output.println(" pthread_cond_init( &(seseToIssue->common.runningChildrenCond), NULL );");
3329 output.println(" seseToIssue->common.numRunningChildren = 0;");
3330 output.println(" seseToIssue->common.parent = parentCommon;");
3332 // all READY in-vars should be copied now and be done with it
3333 Iterator<TempDescriptor> tempItr = fsen.getReadyInVarSet().iterator();
3334 while( tempItr.hasNext() ) {
3335 TempDescriptor temp = tempItr.next();
3337 // when we are issuing the main SESE or an SESE with placeholder
3338 // caller SESE as parent, generate temp child child's eclosing method,
3339 // otherwise use the parent's enclosing method as the context
3340 boolean useParentContext = false;
3342 if( fsen != mlpa.getMainSESE() ) {
3343 assert fsen.getParent() != null;
3344 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3345 useParentContext = true;
3349 if( useParentContext ) {
3350 output.println(" seseToIssue->"+temp+" = "+
3351 generateTemp( fsen.getParent().getfmBogus(), temp, null )+";");
3353 output.println(" seseToIssue->"+temp+" = "+
3354 generateTemp( fsen.getfmEnclosing(), temp, null )+";");
3358 // before potentially adding this SESE to other forwarding lists,
3359 // create it's lock and take it immediately
3360 output.println(" pthread_mutex_init( &(seseToIssue->common.lock), NULL );");
3361 // output.println(" pthread_mutex_lock( &(seseToIssue->common.lock) );");
3363 if( fsen != mlpa.getMainSESE() ) {
3364 // count up outstanding dependencies, static first, then dynamic
3365 Iterator<SESEandAgePair> staticSrcsItr = fsen.getStaticInVarSrcs().iterator();
3366 while( staticSrcsItr.hasNext() ) {
3367 SESEandAgePair srcPair = staticSrcsItr.next();
3368 output.println(" {");
3369 output.println(" SESEcommon* src = (SESEcommon*)"+srcPair+";");
3370 output.println(" pthread_mutex_lock( &(src->lock) );");
3371 output.println(" if( !isEmpty( src->forwardList ) &&");
3372 output.println(" seseToIssue == peekItem( src->forwardList ) ) {");
3373 output.println(" printf( \"This shouldnt already be here\\n\");");
3374 output.println(" exit( -1 );");
3375 output.println(" }");
3376 output.println(" if( !src->doneExecuting ) {");
3377 output.println(" addNewItem( src->forwardList, seseToIssue );");
3378 // output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3379 output.println(" ++(localCount);");
3380 output.println(" }");
3381 output.println(" pthread_mutex_unlock( &(src->lock) );");
3382 output.println(" }");
3384 // whether or not it is an outstanding dependency, make sure
3385 // to pass the static name to the child's record
3386 output.println(" seseToIssue->"+srcPair+" = "+srcPair+";");
3390 // count up memory conflict dependencies,
3392 ConflictGraph graph = null;
3393 FlatSESEEnterNode parent = fsen.getParent();
3394 if (parent != null) {
3395 if (parent.isCallerSESEplaceholder) {
3396 graph = mlpa.getConflictGraphResults().get(parent.getfmEnclosing());
3398 graph = mlpa.getConflictGraphResults().get(parent);
3401 if (graph != null && graph.hasConflictEdge()) {
3402 HashSet<SESELock> seseLockSet = mlpa.getConflictGraphLockMap()
3405 output.println(" //add memory queue element");
3406 Set<WaitingElement> waitingQueueSet = graph
3407 .getWaitingElementSetBySESEID(fsen.getIdentifier(),
3409 if (waitingQueueSet.size() > 0) {
3410 output.println(" {");
3411 output.println(" REntry* rentry=NULL;");
3412 output.println(" seseToIssue->common.rentryIdx=0;");
3413 for (Iterator iterator = waitingQueueSet.iterator(); iterator
3415 WaitingElement waitingElement = (WaitingElement) iterator
3418 if (waitingElement.getStatus() >= ConflictNode.COARSE) {
3419 output.println(" rentry=mlpCreateREntry("
3420 + waitingElement.getStatus()
3421 + ", seseToIssue);");
3423 TempDescriptor td = waitingElement.getTempDesc();
3425 .println(" rentry=mlpCreateFineREntry("
3426 + waitingElement.getStatus()
3427 + ", seseToIssue, seseToIssue->"
3428 + waitingElement.getDynID()
3431 VariableSourceToken vst = fsen
3432 .getStaticInVarSrc(td);
3433 String srcId = "SESE_"
3434 + vst.getSESE().getPrettyIdentifier()
3435 + vst.getSESE().getIdentifier() + "_"
3437 output.println(" if(seseToIssue->"
3438 + waitingElement.getDynID()
3441 .println(" rentry->pointer=(void*)&seseToIssue->"
3444 + waitingElement.getDynID()
3447 .println(" seseToIssue->common.unresolvedRentryArray[seseToIssue->common.unresolvedRentryIdx++]=rentry;");
3448 output.println(" }");
3452 .println(" rentry->queue=parentCommon->memoryQueueArray["
3453 + waitingElement.getQueueID() + "];");
3455 .println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
3457 .println(" if(ADDRENTRY(parentCommon->memoryQueueArray["
3458 + waitingElement.getQueueID()
3459 + "],rentry)==NOTREADY){");
3460 output.println(" ++(localCount);");
3461 output.println(" } ");
3464 output.println(" }");
3471 // dynamic sources might already be accounted for in the static list,
3472 // so only add them to forwarding lists if they're not already there
3473 Iterator<TempDescriptor> dynVarsItr = fsen.getDynamicInVarSet().iterator();
3474 while( dynVarsItr.hasNext() ) {
3475 TempDescriptor dynInVar = dynVarsItr.next();
3476 output.println(" {");
3477 output.println(" SESEcommon* src = (SESEcommon*)"+dynInVar+"_srcSESE;");
3479 // the dynamic source is NULL if it comes from your own space--you can't pass
3480 // the address off to the new child, because you're not done executing and
3481 // might change the variable, so copy it right now
3482 output.println(" if( src != NULL ) {");
3483 output.println(" pthread_mutex_lock( &(src->lock) );");
3484 output.println(" if( isEmpty( src->forwardList ) ||");
3485 output.println(" seseToIssue != peekItem( src->forwardList ) ) {");
3486 output.println(" if( !src->doneExecuting ) {");
3487 output.println(" addNewItem( src->forwardList, seseToIssue );");
3488 // output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3489 output.println(" ++(localCount);");
3490 output.println(" }");
3491 output.println(" }");
3492 output.println(" pthread_mutex_unlock( &(src->lock) );");
3493 output.println(" seseToIssue->"+dynInVar+"_srcOffset = "+dynInVar+"_srcOffset;");
3494 output.println(" } else {");
3496 boolean useParentContext = false;
3497 if( fsen != mlpa.getMainSESE() ) {
3498 assert fsen.getParent() != null;
3499 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3500 useParentContext = true;
3503 if( useParentContext ) {
3504 output.println(" seseToIssue->"+dynInVar+" = "+
3505 generateTemp( fsen.getParent().getfmBogus(), dynInVar, null )+";");
3507 output.println(" seseToIssue->"+dynInVar+" = "+
3508 generateTemp( fsen.getfmEnclosing(), dynInVar, null )+";");
3511 output.println(" }");
3512 output.println(" }");
3514 // even if the value is already copied, make sure your NULL source
3515 // gets passed so child knows it already has the dynamic value
3516 output.println(" seseToIssue->"+dynInVar+"_srcSESE = "+dynInVar+"_srcSESE;");
3519 // maintain pointers for finding dynamic SESE
3520 // instances from static names
3521 SESEandAgePair pair = new SESEandAgePair( fsen, 0 );
3522 if( fsen.getParent() != null &&
3523 //!fsen.getParent().getIsCallerSESEplaceholder() &&
3524 fsen.getParent().getNeededStaticNames().contains( pair )
3527 for( int i = fsen.getOldestAgeToTrack(); i > 0; --i ) {
3528 SESEandAgePair pair1 = new SESEandAgePair( fsen, i );
3529 SESEandAgePair pair2 = new SESEandAgePair( fsen, i-1 );
3530 output.println(" "+pair1+" = "+pair2+";");
3532 output.println(" "+pair+" = seseToIssue;");
3537 // release this SESE for siblings to update its dependencies or,
3538 // eventually, for it to mark itself finished
3539 // output.println(" pthread_mutex_unlock( &(seseToIssue->common.lock) );");
3541 // if there were no outstanding dependencies, issue here
3542 output.println(" if( atomic_sub_and_test(10000-localCount,&(seseToIssue->common.unresolvedDependencies) ) ) {");
3543 output.println(" workScheduleSubmit( (void*)seseToIssue );");
3544 output.println(" }");
3546 output.println(" if( seseToIssue->common.unresolvedDependencies == 0 ) {");
3547 output.println(" workScheduleSubmit( (void*)seseToIssue );");
3548 output.println(" }");
3550 // release this SESE for siblings to update its dependencies or,
3551 // eventually, for it to mark itself finished
3552 // output.println(" pthread_mutex_unlock( &(seseToIssue->common.lock) );");
3553 output.println(" }");
3557 public void generateFlatSESEExitNode( FlatMethod fm,
3559 FlatSESEExitNode fsexn,
3563 // if MLP flag is off, okay that SESE nodes are in IR graph,
3564 // just skip over them and code generates exactly the same
3569 // get the enter node for this exit that has meta data embedded
3570 FlatSESEEnterNode fsen = fsexn.getFlatEnter();
3572 // there may be an SESE in an unreachable method, skip over
3573 if( !mlpa.getAllSESEs().contains( fsen ) ) {
3577 // also, if we have encountered a placeholder, just jump it
3578 if( fsen.getIsCallerSESEplaceholder() ) {
3582 output.println(" /* SESE exiting */");
3584 String com = paramsprefix+"->common";
3586 // this SESE cannot be done until all of its children are done
3587 // so grab your own lock with the condition variable for watching
3588 // that the number of your running children is greater than zero
3589 output.println(" pthread_mutex_lock( &("+com+".lock) );");
3590 output.println(" while( "+com+".numRunningChildren > 0 ) {");
3591 output.println(" pthread_cond_wait( &("+com+".runningChildrenCond), &("+com+".lock) );");
3592 output.println(" }");
3594 // copy out-set from local temps into the sese record
3595 Iterator<TempDescriptor> itr = fsen.getOutVarSet().iterator();
3596 while( itr.hasNext() ) {
3597 TempDescriptor temp = itr.next();
3599 // only have to do this for primitives non-arrays
3601 temp.getType().isPrimitive() && !temp.getType().isArray()
3607 // have to determine the context enclosing this sese
3608 boolean useParentContext = false;
3610 if( fsen != mlpa.getMainSESE() ) {
3611 assert fsen.getParent() != null;
3612 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3613 useParentContext = true;
3618 if( useParentContext ) {
3619 from = generateTemp( fsen.getParent().getfmBogus(), temp, null );
3621 from = generateTemp( fsen.getfmEnclosing(), temp, null );
3624 output.println(" "+paramsprefix+
3625 "->"+temp.getSafeSymbol()+
3629 // mark yourself done, your SESE data is now read-only
3630 output.println(" "+com+".doneExecuting = TRUE;");
3631 output.println(" pthread_cond_signal( &("+com+".doneCond) );");
3632 output.println(" pthread_mutex_unlock( &("+com+".lock) );");
3634 // decrement dependency count for all SESE's on your forwarding list
3635 output.println(" while( !isEmpty( "+com+".forwardList ) ) {");
3636 output.println(" SESEcommon* consumer = (SESEcommon*) getItem( "+com+".forwardList );");
3638 output.println(" if(consumer->unresolvedRentryIdx>0){");
3639 output.println(" // resolved null pointer");
3640 output.println(" int idx;");
3641 output.println(" for(idx=0;idx<consumer->unresolvedRentryIdx;idx++){");
3642 output.println(" resolvePointer(consumer->unresolvedRentryArray[idx]);");
3643 output.println(" }");
3644 output.println(" }");
3646 // output.println(" pthread_mutex_lock( &(consumer->lock) );");
3647 // output.println(" --(consumer->unresolvedDependencies);");
3648 // output.println(" if( consumer->unresolvedDependencies == 0 ) {");
3649 output.println(" if( atomic_sub_and_test(1, &(consumer->unresolvedDependencies)) ){");
3650 output.println(" workScheduleSubmit( (void*)consumer );");
3651 output.println(" }");
3652 // output.println(" pthread_mutex_unlock( &(consumer->lock) );");
3653 output.println(" }");
3657 // clean up its lock element from waiting queue, and decrement dependency count for next SESE block
3658 if( fsen != mlpa.getMainSESE() ) {
3661 output.println(" /* check memory dependency*/");
3662 output.println(" {");
3663 output.println(" int idx;");
3664 output.println(" for(idx=0;idx<___params___->common.rentryIdx;idx++){");
3665 output.println(" REntry* re=___params___->common.rentryArray[idx];");
3666 output.println(" RETIRERENTRY(re->queue,re);");
3667 output.println(" }");
3668 output.println(" }");
3672 // if parent is stalling on you, let them know you're done
3673 if( fsexn.getFlatEnter() != mlpa.getMainSESE() ) {
3674 output.println(" psem_give( &("+paramsprefix+"->common.stallSem) );");
3677 // last of all, decrement your parent's number of running children
3678 output.println(" if( "+paramsprefix+"->common.parent != NULL ) {");
3679 output.println(" if (atomic_sub_and_test(1, &"+paramsprefix+"->common.parent->numRunningChildren)) {");
3680 output.println(" pthread_mutex_lock( &("+paramsprefix+"->common.parent->lock) );");
3681 output.println(" pthread_cond_signal( &("+paramsprefix+"->common.parent->runningChildrenCond) );");
3682 output.println(" pthread_mutex_unlock( &("+paramsprefix+"->common.parent->lock) );");
3683 output.println(" }");
3684 output.println(" }");
3686 // this is a thread-only variable that can be handled when critical sese-to-sese
3687 // data has been taken care of--set sese pointer to remember self over method
3688 // calls to a non-zero, invalid address
3689 output.println(" seseCaller = (SESEcommon*) 0x1;");
3693 public void generateFlatWriteDynamicVarNode( FlatMethod fm,
3695 FlatWriteDynamicVarNode fwdvn,
3699 // should node should not be in an IR graph if the
3700 // MLP flag is not set
3701 throw new Error("Unexpected presence of FlatWriteDynamicVarNode");
3704 Hashtable<TempDescriptor, VSTWrapper> writeDynamic = fwdvn.getVar2src();
3706 assert writeDynamic != null;
3708 Iterator wdItr = writeDynamic.entrySet().iterator();
3709 while( wdItr.hasNext() ) {
3710 Map.Entry me = (Map.Entry) wdItr.next();
3711 TempDescriptor refVar = (TempDescriptor) me.getKey();
3712 VSTWrapper vstW = (VSTWrapper) me.getValue();
3713 VariableSourceToken vst = vstW.vst;
3716 // only do this if the variable in question should be tracked,
3717 // meaning that it was explicitly added to the dynamic var set
3718 if( !current.getDynamicVarSet().contains( vst.getAddrVar() ) ) {
3724 // if there is no given source, this variable is ready so
3725 // mark src pointer NULL to signify that the var is up-to-date
3726 output.println(" "+refVar+"_srcSESE = NULL;");
3730 // otherwise we track where it will come from
3731 SESEandAgePair instance = new SESEandAgePair( vst.getSESE(), vst.getAge() );
3732 output.println(" "+refVar+"_srcSESE = "+instance+";");
3733 output.println(" "+refVar+"_srcOffset = (int) &((("+
3734 vst.getSESE().getSESErecordName()+"*)0)->"+vst.getAddrVar()+");");
3739 private void generateFlatCheckNode(FlatMethod fm, LocalityBinding lb, FlatCheckNode fcn, PrintWriter output) {
3740 if (state.CONSCHECK) {
3741 String specname=fcn.getSpec();
3742 String varname="repairstate___";
3743 output.println("{");
3744 output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
3746 TempDescriptor[] temps=fcn.getTemps();
3747 String[] vars=fcn.getVars();
3748 for(int i=0; i<temps.length; i++) {
3749 output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i],lb)+";");
3752 output.println("if (doanalysis"+specname+"("+varname+")) {");
3753 output.println("free"+specname+"_state("+varname+");");
3754 output.println("} else {");
3755 output.println("/* Bad invariant */");
3756 output.println("free"+specname+"_state("+varname+");");
3757 output.println("abort_task();");
3758 output.println("}");
3759 output.println("}");
3763 private void generateFlatCall(FlatMethod fm, LocalityBinding lb, FlatCall fc, PrintWriter output) {
3765 if( state.MLP && !nonSESEpass ) {
3766 output.println(" seseCaller = (SESEcommon*)"+paramsprefix+";");
3769 MethodDescriptor md=fc.getMethod();
3770 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? locality.getBinding(lb, fc) : md);
3771 ClassDescriptor cn=md.getClassDesc();
3772 output.println("{");
3773 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3775 LocalityBinding fclb=locality.getBinding(lb, fc);
3776 output.print(" struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
3778 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
3780 output.print(objectparams.numPointers());
3781 output.print(", "+localsprefixaddr);
3782 if (md.getThis()!=null) {
3784 output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis(),lb));
3786 if (fc.getThis()!=null&&md.getThis()==null) {
3787 System.out.println("WARNING!!!!!!!!!!!!");
3788 System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
3792 for(int i=0; i<fc.numArgs(); i++) {
3793 Descriptor var=md.getParameter(i);
3794 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
3795 if (objectparams.isParamPtr(paramtemp)) {
3796 TempDescriptor targ=fc.getArg(i);
3798 TypeDescriptor td=md.getParamType(i);
3800 output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
3802 output.print("(struct "+md.getParamType(i).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
3805 output.println("};");
3810 if (fc.getReturnTemp()!=null)
3811 output.print(generateTemp(fm,fc.getReturnTemp(),lb)+"=");
3813 /* Do we need to do virtual dispatch? */
3814 if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
3817 LocalityBinding fclb=locality.getBinding(lb, fc);
3818 output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
3820 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
3825 if (md.getReturnType().isClass()||md.getReturnType().isArray())
3826 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
3828 output.print(md.getReturnType().getSafeSymbol()+" ");
3829 output.print("(*)(");
3831 boolean printcomma=false;
3832 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3834 LocalityBinding fclb=locality.getBinding(lb, fc);
3835 output.print("struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
3837 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
3841 for(int i=0; i<objectparams.numPrimitives(); i++) {
3842 TempDescriptor temp=objectparams.getPrimitive(i);
3846 if (temp.getType().isClass()||temp.getType().isArray())
3847 output.print("struct " + temp.getType().getSafeSymbol()+" * ");
3849 output.print(temp.getType().getSafeSymbol());
3854 LocalityBinding fclb=locality.getBinding(lb, fc);
3855 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])");
3857 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
3861 boolean needcomma=false;
3862 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3863 output.print("&__parameterlist__");
3867 if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
3868 if (fc.getThis()!=null) {
3869 TypeDescriptor ptd=md.getThis().getType();
3872 if (ptd.isClass()&&!ptd.isArray())
3873 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
3874 output.print(generateTemp(fm,fc.getThis(),lb));
3879 for(int i=0; i<fc.numArgs(); i++) {
3880 Descriptor var=md.getParameter(i);
3881 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
3882 if (objectparams.isParamPrim(paramtemp)) {
3883 TempDescriptor targ=fc.getArg(i);
3887 TypeDescriptor ptd=md.getParamType(i);
3888 if (ptd.isClass()&&!ptd.isArray())
3889 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
3890 output.print(generateTemp(fm, targ,lb));
3894 output.println(");");
3895 output.println(" }");
3898 private boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
3899 Set subclasses=typeutil.getSubClasses(thiscd);
3900 if (subclasses==null)
3902 for(Iterator classit=subclasses.iterator(); classit.hasNext();) {
3903 ClassDescriptor cd=(ClassDescriptor)classit.next();
3904 Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol());
3905 for(Iterator matchit=possiblematches.iterator(); matchit.hasNext();) {
3906 MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
3907 if (md.matches(matchmd))
3914 private void generateFlatFieldNode(FlatMethod fm, LocalityBinding lb, FlatFieldNode ffn, PrintWriter output) {
3915 if (state.SINGLETM) {
3916 //single machine transactional memory case
3917 String field=ffn.getField().getSafeSymbol();
3918 String src=generateTemp(fm, ffn.getSrc(),lb);
3919 String dst=generateTemp(fm, ffn.getDst(),lb);
3921 output.println(dst+"="+ src +"->"+field+ ";");
3922 if (ffn.getField().getType().isPtr()&&locality.getAtomic(lb).get(ffn).intValue()>0&&
3923 locality.getNodePreTempInfo(lb, ffn).get(ffn.getSrc())!=LocalityAnalysis.SCRATCH) {
3924 if ((dc==null)||(!state.READSET&&dc.getNeedTrans(lb, ffn))||
3925 (state.READSET&&dc.getNeedWriteTrans(lb, ffn))) {
3926 output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));");
3927 } else if (state.READSET&&dc.getNeedTrans(lb, ffn)) {
3928 if (state.HYBRID&&delaycomp.getConv(lb).contains(ffn)) {
3929 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
3931 output.println("TRANSREADRD("+dst+", "+dst+");");
3934 } else if (state.DSM) {
3935 Integer status=locality.getNodePreTempInfo(lb,ffn).get(ffn.getSrc());
3936 if (status==LocalityAnalysis.GLOBAL) {
3937 String field=ffn.getField().getSafeSymbol();
3938 String src=generateTemp(fm, ffn.getSrc(),lb);
3939 String dst=generateTemp(fm, ffn.getDst(),lb);
3941 if (ffn.getField().getType().isPtr()) {
3943 //TODO: Uncomment this when we have runtime support
3944 //if (ffn.getSrc()==ffn.getDst()) {
3945 //output.println("{");
3946 //output.println("void * temp="+src+";");
3947 //output.println("if (temp&0x1) {");
3948 //output.println("temp=(void *) transRead(trans, (unsigned int) temp);");
3949 //output.println(src+"->"+field+"="+temp+";");
3950 //output.println("}");
3951 //output.println(dst+"=temp;");
3952 //output.println("}");
3954 output.println(dst+"="+ src +"->"+field+ ";");
3955 //output.println("if ("+dst+"&0x1) {");
3956 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
3957 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
3958 //output.println(src+"->"+field+"="+src+"->"+field+";");
3959 //output.println("}");
3962 output.println(dst+"="+ src+"->"+field+";");
3964 } else if (status==LocalityAnalysis.LOCAL) {
3965 if (ffn.getField().getType().isPtr()&&
3966 ffn.getField().isGlobal()) {
3967 String field=ffn.getField().getSafeSymbol();
3968 String src=generateTemp(fm, ffn.getSrc(),lb);
3969 String dst=generateTemp(fm, ffn.getDst(),lb);
3970 output.println(dst+"="+ src +"->"+field+ ";");
3971 if (locality.getAtomic(lb).get(ffn).intValue()>0)
3972 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
3973 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
3975 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
3976 } else if (status==LocalityAnalysis.EITHER) {
3977 //Code is reading from a null pointer
3978 output.println("if ("+generateTemp(fm, ffn.getSrc(),lb)+") {");
3979 output.println("#ifndef RAW");
3980 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
3981 output.println("#endif");
3982 //This should throw a suitable null pointer error
3983 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
3985 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
3987 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
3991 private void generateFlatSetFieldNode(FlatMethod fm, LocalityBinding lb, FlatSetFieldNode fsfn, PrintWriter output) {
3992 if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
3993 throw new Error("Can't set array length");
3994 if (state.SINGLETM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
3995 //Single Machine Transaction Case
3996 boolean srcptr=fsfn.getSrc().getType().isPtr();
3997 String src=generateTemp(fm,fsfn.getSrc(),lb);
3998 String dst=generateTemp(fm,fsfn.getDst(),lb);
3999 output.println("//"+srcptr+" "+fsfn.getSrc().getType().isNull());
4000 if (srcptr&&!fsfn.getSrc().getType().isNull()) {
4001 output.println("{");
4002 if ((dc==null)||dc.getNeedSrcTrans(lb, fsfn)&&
4003 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) {
4004 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4006 output.println("INTPTR srcoid=(INTPTR)"+src+";");
4009 if (wb.needBarrier(fsfn)&&
4010 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getDst())!=LocalityAnalysis.SCRATCH) {
4011 if (state.EVENTMONITOR) {
4012 output.println("if ("+dst+"->___objstatus___&DIRTY) EVLOGEVENTOBJ(EV_WRITE,"+dst+"->objuid)");
4014 output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;");
4016 if (srcptr&!fsfn.getSrc().getType().isNull()) {
4017 output.println("*((unsigned INTPTR *)&("+dst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4018 output.println("}");
4020 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4022 } else if (state.DSM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
4023 Integer statussrc=locality.getNodePreTempInfo(lb,fsfn).get(fsfn.getSrc());
4024 Integer statusdst=locality.getNodeTempInfo(lb).get(fsfn).get(fsfn.getDst());
4025 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4027 String src=generateTemp(fm,fsfn.getSrc(),lb);
4028 String dst=generateTemp(fm,fsfn.getDst(),lb);
4030 output.println("{");
4031 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4033 if (statusdst.equals(LocalityAnalysis.GLOBAL)) {
4036 if (wb.needBarrier(fsfn))
4037 output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;");
4039 output.println("*((unsigned INTPTR *)&("+glbdst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4041 output.println(glbdst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4042 } else if (statusdst.equals(LocalityAnalysis.LOCAL)) {
4043 /** Check if we need to copy */
4044 output.println("if(!"+dst+"->"+localcopystr+") {");
4045 /* Link object into list */
4046 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4047 output.println(revertptr+"=revertlist;");
4048 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4049 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4051 output.println("COPY_OBJ("+dst+");");
4052 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4053 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4054 output.println("}");
4056 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4058 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4059 } else if (statusdst.equals(LocalityAnalysis.EITHER)) {
4060 //writing to a null...bad
4061 output.println("if ("+dst+") {");
4062 output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}");
4064 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4066 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4069 output.println("}");
4072 if (state.FASTCHECK) {
4073 String dst=generateTemp(fm, fsfn.getDst(),lb);
4074 output.println("if(!"+dst+"->"+localcopystr+") {");
4075 /* Link object into list */
4076 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4077 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4079 output.println("COPY_OBJ("+dst+");");
4080 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4081 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4082 output.println("}");
4084 output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
4088 private void generateFlatElementNode(FlatMethod fm, LocalityBinding lb, FlatElementNode fen, PrintWriter output) {
4089 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
4092 if (elementtype.isArray()||elementtype.isClass())
4095 type=elementtype.getSafeSymbol()+" ";
4097 if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
4098 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fen.getIndex(),lb)+") >= "+generateTemp(fm,fen.getSrc(),lb) + "->___length___))");
4099 output.println("failedboundschk();");
4101 if (state.SINGLETM) {
4102 //Single machine transaction case
4103 String dst=generateTemp(fm, fen.getDst(),lb);
4104 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))) {
4105 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4107 output.println("STMGETARRAY("+dst+", "+ generateTemp(fm,fen.getSrc(),lb)+", "+generateTemp(fm, fen.getIndex(),lb)+", "+type+");");
4110 if (elementtype.isPtr()&&locality.getAtomic(lb).get(fen).intValue()>0&&
4111 locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())!=LocalityAnalysis.SCRATCH) {
4112 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fen)||state.READSET&&dc.getNeedWriteTrans(lb, fen)) {
4113 output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));");
4114 } else if (state.READSET&&dc.getNeedTrans(lb, fen)) {
4115 if (state.HYBRID&&delaycomp.getConv(lb).contains(fen)) {
4116 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4118 output.println("TRANSREADRD("+dst+", "+dst+");");
4121 } else if (state.DSM) {
4122 Integer status=locality.getNodePreTempInfo(lb,fen).get(fen.getSrc());
4123 if (status==LocalityAnalysis.GLOBAL) {
4124 String dst=generateTemp(fm, fen.getDst(),lb);
4125 if (elementtype.isPtr()) {
4126 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4127 //DEBUG: output.println("TRANSREAD("+dst+", "+dst+",\""+fm+":"+fen+"\");");
4128 output.println("TRANSREAD("+dst+", "+dst+");");
4130 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4132 } else if (status==LocalityAnalysis.LOCAL) {
4133 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4134 } else if (status==LocalityAnalysis.EITHER) {
4135 //Code is reading from a null pointer
4136 output.println("if ("+generateTemp(fm, fen.getSrc(),lb)+") {");
4137 output.println("#ifndef RAW");
4138 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4139 output.println("#endif");
4140 //This should throw a suitable null pointer error
4141 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4143 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4145 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4149 private void generateFlatSetElementNode(FlatMethod fm, LocalityBinding lb, FlatSetElementNode fsen, PrintWriter output) {
4150 //TODO: need dynamic check to make sure this assignment is actually legal
4151 //Because Object[] could actually be something more specific...ie. Integer[]
4153 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
4156 if (elementtype.isArray()||elementtype.isClass())
4159 type=elementtype.getSafeSymbol()+" ";
4161 if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
4162 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fsen.getIndex(),lb)+") >= "+generateTemp(fm,fsen.getDst(),lb) + "->___length___))");
4163 output.println("failedboundschk();");
4166 if (state.SINGLETM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4167 //Transaction set element case
4168 if (wb.needBarrier(fsen)&&
4169 locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH) {
4170 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___objstatus___))|=DIRTY;");
4172 if (fsen.getSrc().getType().isPtr()&&!fsen.getSrc().getType().isNull()) {
4173 output.println("{");
4174 String src=generateTemp(fm, fsen.getSrc(), lb);
4175 if ((dc==null)||dc.getNeedSrcTrans(lb, fsen)&&
4176 locality.getNodePreTempInfo(lb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) {
4177 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4179 output.println("INTPTR srcoid=(INTPTR)"+src+";");
4181 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
4182 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", srcoid, INTPTR);");
4184 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
4186 output.println("}");
4188 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
4189 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", "+ generateTemp(fm, fsen.getSrc(), lb) +", "+type+");");
4191 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4194 } else if (state.DSM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4195 Integer statussrc=locality.getNodePreTempInfo(lb,fsen).get(fsen.getSrc());
4196 Integer statusdst=locality.getNodePreTempInfo(lb,fsen).get(fsen.getDst());
4197 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4198 boolean dstglobal=statusdst==LocalityAnalysis.GLOBAL;
4199 boolean dstlocal=(statusdst==LocalityAnalysis.LOCAL)||(statusdst==LocalityAnalysis.EITHER);
4202 if (wb.needBarrier(fsen))
4203 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___localcopy___))|=DIRTY;");
4204 } else if (dstlocal) {
4205 /** Check if we need to copy */
4206 String dst=generateTemp(fm, fsen.getDst(),lb);
4207 output.println("if(!"+dst+"->"+localcopystr+") {");
4208 /* Link object into list */
4209 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4210 output.println(revertptr+"=revertlist;");
4211 if ((GENERATEPRECISEGC) || this.state.MULTICOREGC)
4212 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4214 output.println("COPY_OBJ("+dst+");");
4215 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4216 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4217 output.println("}");
4219 System.out.println("Node: "+fsen);
4220 System.out.println(lb);
4221 System.out.println("statusdst="+statusdst);
4222 System.out.println(fm.printMethod());
4223 throw new Error("Unknown array type");
4226 output.println("{");
4227 String src=generateTemp(fm, fsen.getSrc(), lb);
4228 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4229 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
4230 output.println("}");
4232 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4235 if (state.FASTCHECK) {
4236 String dst=generateTemp(fm, fsen.getDst(),lb);
4237 output.println("if(!"+dst+"->"+localcopystr+") {");
4238 /* Link object into list */
4239 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4240 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4242 output.println("COPY_OBJ("+dst+");");
4243 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4244 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4245 output.println("}");
4247 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4251 protected void generateFlatNew(FlatMethod fm, LocalityBinding lb, FlatNew fn, PrintWriter output) {
4252 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
4253 //Stash pointer in case of GC
4254 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4255 output.println(revertptr+"=revertlist;");
4257 if (state.SINGLETM) {
4258 if (fn.getType().isArray()) {
4259 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4260 if (locality.getAtomic(lb).get(fn).intValue()>0) {
4261 //inside transaction
4262 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4264 //outside transaction
4265 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4268 if (locality.getAtomic(lb).get(fn).intValue()>0) {
4269 //inside transaction
4270 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4272 //outside transaction
4273 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4276 } else if (fn.getType().isArray()) {
4277 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4278 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4279 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4280 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4281 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4283 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4286 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4287 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");");
4288 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4289 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4291 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
4294 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
4295 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4296 String dst=generateTemp(fm,fn.getDst(),lb);
4297 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
4298 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4299 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4301 if (state.FASTCHECK) {
4302 String dst=generateTemp(fm,fn.getDst(),lb);
4303 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
4304 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4305 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4309 private void generateFlatTagDeclaration(FlatMethod fm, LocalityBinding lb, FlatTagDeclaration fn, PrintWriter output) {
4310 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4311 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
4313 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+state.getTagId(fn.getType())+");");
4317 private void generateFlatOpNode(FlatMethod fm, LocalityBinding lb, FlatOpNode fon, PrintWriter output) {
4318 if (fon.getRight()!=null) {
4319 if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
4320 if (fon.getLeft().getType().isLong())
4321 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
4323 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned int)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
4325 } else if (dc!=null) {
4326 output.print(generateTemp(fm, fon.getDest(),lb)+" = (");
4327 if (fon.getLeft().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
4328 output.print("(void *)");
4329 if (dc.getNeedLeftSrcTrans(lb, fon))
4330 output.print("("+generateTemp(fm, fon.getLeft(),lb)+"!=NULL?"+generateTemp(fm, fon.getLeft(),lb)+"->"+oidstr+":NULL)");
4332 output.print(generateTemp(fm, fon.getLeft(),lb));
4333 output.print(")"+fon.getOp().toString()+"(");
4334 if (fon.getRight().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
4335 output.print("(void *)");
4336 if (dc.getNeedRightSrcTrans(lb, fon))
4337 output.println("("+generateTemp(fm, fon.getRight(),lb)+"!=NULL?"+generateTemp(fm, fon.getRight(),lb)+"->"+oidstr+":NULL));");
4339 output.println(generateTemp(fm,fon.getRight(),lb)+");");
4341 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+fon.getOp().toString()+generateTemp(fm,fon.getRight(),lb)+";");
4342 } else if (fon.getOp().getOp()==Operation.ASSIGN)
4343 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
4344 else if (fon.getOp().getOp()==Operation.UNARYPLUS)
4345 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
4346 else if (fon.getOp().getOp()==Operation.UNARYMINUS)
4347 output.println(generateTemp(fm, fon.getDest(),lb)+" = -"+generateTemp(fm, fon.getLeft(),lb)+";");
4348 else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
4349 output.println(generateTemp(fm, fon.getDest(),lb)+" = !"+generateTemp(fm, fon.getLeft(),lb)+";");
4350 else if (fon.getOp().getOp()==Operation.COMP)
4351 output.println(generateTemp(fm, fon.getDest(),lb)+" = ~"+generateTemp(fm, fon.getLeft(),lb)+";");
4352 else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
4353 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+"->fses==NULL;");
4355 output.println(generateTemp(fm, fon.getDest(),lb)+fon.getOp().toString()+generateTemp(fm, fon.getLeft(),lb)+";");
4358 private void generateFlatCastNode(FlatMethod fm, LocalityBinding lb, FlatCastNode fcn, PrintWriter output) {
4359 /* TODO: Do type check here */
4360 if (fcn.getType().isArray()) {
4361 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
4362 } else if (fcn.getType().isClass())
4363 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
4365 output.println(generateTemp(fm,fcn.getDst(),lb)+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc(),lb)+";");
4368 private void generateFlatLiteralNode(FlatMethod fm, LocalityBinding lb, FlatLiteralNode fln, PrintWriter output) {
4369 if (fln.getValue()==null)
4370 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
4371 else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
4372 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4373 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
4374 //Stash pointer in case of GC
4375 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4376 output.println(revertptr+"=revertlist;");
4378 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
4379 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
4380 //Stash pointer in case of GC
4381 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4382 output.println("revertlist="+revertptr+";");
4385 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
4387 } else if (fln.getType().isBoolean()) {
4388 if (((Boolean)fln.getValue()).booleanValue())
4389 output.println(generateTemp(fm, fln.getDst(),lb)+"=1;");
4391 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
4392 } else if (fln.getType().isChar()) {
4393 String st=FlatLiteralNode.escapeString(fln.getValue().toString());
4394 output.println(generateTemp(fm, fln.getDst(),lb)+"='"+st+"';");
4395 } else if (fln.getType().isLong()) {
4396 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+"LL;");
4398 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+";");
4401 protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) {
4402 if (frn.getReturnTemp()!=null) {
4403 if (frn.getReturnTemp().getType().isPtr())
4404 output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";");
4406 output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";");
4408 output.println("return;");
4412 protected void generateStoreFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
4415 //only record if this group has more than one exit
4416 if (branchanalysis.numJumps(fcb)>1) {
4417 left=branchanalysis.jumpValue(fcb, 0);
4418 right=branchanalysis.jumpValue(fcb, 1);
4420 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") {");
4422 output.println("STOREBRANCH("+right+");");
4423 output.println("goto "+label+";");
4424 output.println("}");
4426 output.println("STOREBRANCH("+left+");");
4429 protected void generateFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
4430 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") goto "+label+";");
4433 /** This method generates header information for the method or
4434 * task referenced by the Descriptor des. */
4435 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) {
4436 generateHeader(fm, lb, des, output, false);
4439 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output, boolean addSESErecord) {
4441 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : des);
4442 MethodDescriptor md=null;
4443 TaskDescriptor task=null;
4444 if (des instanceof MethodDescriptor)
4445 md=(MethodDescriptor) des;
4447 task=(TaskDescriptor) des;
4449 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
4451 if (md!=null&&md.getReturnType()!=null) {
4452 if (md.getReturnType().isClass()||md.getReturnType().isArray())
4453 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
4455 output.print(md.getReturnType().getSafeSymbol()+" ");
4457 //catch the constructor case
4458 output.print("void ");
4460 if (state.DSM||state.SINGLETM) {
4461 output.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
4463 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
4465 output.print(task.getSafeSymbol()+"(");
4467 boolean printcomma=false;
4468 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4470 if (state.DSM||state.SINGLETM) {
4471 output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
4473 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
4475 output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
4481 for(int i=0; i<objectparams.numPrimitives(); i++) {
4482 TempDescriptor temp=objectparams.getPrimitive(i);
4486 if (temp.getType().isClass()||temp.getType().isArray())
4487 output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
4489 output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
4491 output.println(") {");
4492 } else if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
4493 /* Imprecise Task */
4494 output.println("void * parameterarray[]) {");
4495 /* Unpack variables */
4496 for(int i=0; i<objectparams.numPrimitives(); i++) {
4497 TempDescriptor temp=objectparams.getPrimitive(i);
4498 output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
4500 for(int i=0; i<fm.numTags(); i++) {
4501 TempDescriptor temp=fm.getTag(i);
4502 int offset=i+objectparams.numPrimitives();
4503 output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
4506 if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
4507 maxtaskparams=objectparams.numPrimitives()+fm.numTags();
4508 } else output.println(") {");
4511 public void generateFlatFlagActionNode(FlatMethod fm, LocalityBinding lb, FlatFlagActionNode ffan, PrintWriter output) {
4512 output.println("/* FlatFlagActionNode */");
4515 /* Process tag changes */
4516 Relation tagsettable=new Relation();
4517 Relation tagcleartable=new Relation();
4519 Iterator tagsit=ffan.getTempTagPairs();
4520 while (tagsit.hasNext()) {
4521 TempTagPair ttp=(TempTagPair) tagsit.next();
4522 TempDescriptor objtmp=ttp.getTemp();
4523 TagDescriptor tag=ttp.getTag();
4524 TempDescriptor tagtmp=ttp.getTagTemp();
4525 boolean tagstatus=ffan.getTagChange(ttp);
4527 tagsettable.put(objtmp, tagtmp);
4529 tagcleartable.put(objtmp, tagtmp);
4534 Hashtable flagandtable=new Hashtable();
4535 Hashtable flagortable=new Hashtable();
4537 /* Process flag changes */
4538 Iterator flagsit=ffan.getTempFlagPairs();
4539 while(flagsit.hasNext()) {
4540 TempFlagPair tfp=(TempFlagPair)flagsit.next();
4541 TempDescriptor temp=tfp.getTemp();
4542 Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
4543 FlagDescriptor flag=tfp.getFlag();
4545 //Newly allocate objects that don't set any flags case
4546 if (flagortable.containsKey(temp)) {
4550 flagortable.put(temp,new Integer(mask));
4552 int flagid=1<<((Integer)flagtable.get(flag)).intValue();
4553 boolean flagstatus=ffan.getFlagChange(tfp);
4556 if (flagortable.containsKey(temp)) {
4557 mask=((Integer)flagortable.get(temp)).intValue();
4560 flagortable.put(temp,new Integer(mask));
4562 int mask=0xFFFFFFFF;
4563 if (flagandtable.containsKey(temp)) {
4564 mask=((Integer)flagandtable.get(temp)).intValue();
4566 mask&=(0xFFFFFFFF^flagid);
4567 flagandtable.put(temp,new Integer(mask));
4573 HashSet flagtagset=new HashSet();
4574 flagtagset.addAll(flagortable.keySet());
4575 flagtagset.addAll(flagandtable.keySet());
4576 flagtagset.addAll(tagsettable.keySet());
4577 flagtagset.addAll(tagcleartable.keySet());
4579 Iterator ftit=flagtagset.iterator();
4580 while(ftit.hasNext()) {
4581 TempDescriptor temp=(TempDescriptor)ftit.next();
4584 Set tagtmps=tagcleartable.get(temp);
4585 if (tagtmps!=null) {
4586 Iterator tagit=tagtmps.iterator();
4587 while(tagit.hasNext()) {
4588 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
4589 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
4590 output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4592 output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4596 tagtmps=tagsettable.get(temp);
4597 if (tagtmps!=null) {
4598 Iterator tagit=tagtmps.iterator();
4599 while(tagit.hasNext()) {
4600 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
4601 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
4602 output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4604 output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp, lb)+", "+generateTemp(fm,tagtmp, lb)+");");
4609 int andmask=0xFFFFFFF;
4611 if (flagortable.containsKey(temp))
4612 ormask=((Integer)flagortable.get(temp)).intValue();
4613 if (flagandtable.containsKey(temp))
4614 andmask=((Integer)flagandtable.get(temp)).intValue();
4615 generateFlagOrAnd(ffan, fm, lb, temp, output, ormask, andmask);
4616 generateObjectDistribute(ffan, fm, lb, temp, output);
4620 protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp,
4621 PrintWriter output, int ormask, int andmask) {
4622 if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
4623 output.println("flagorandinit("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
4625 output.println("flagorand("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
4629 protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, PrintWriter output) {
4630 output.println("enqueueObject("+generateTemp(fm, temp, lb)+");");
4633 void generateOptionalHeader(PrintWriter headers) {
4636 headers.println("#include \"task.h\"\n\n");
4637 headers.println("#ifndef _OPTIONAL_STRUCT_");
4638 headers.println("#define _OPTIONAL_STRUCT_");
4640 //STRUCT PREDICATEMEMBER
4641 headers.println("struct predicatemember{");
4642 headers.println("int type;");
4643 headers.println("int numdnfterms;");
4644 headers.println("int * flags;");
4645 headers.println("int numtags;");
4646 headers.println("int * tags;\n};\n\n");
4648 //STRUCT OPTIONALTASKDESCRIPTOR
4649 headers.println("struct optionaltaskdescriptor{");
4650 headers.println("struct taskdescriptor * task;");
4651 headers.println("int index;");
4652 headers.println("int numenterflags;");
4653 headers.println("int * enterflags;");
4654 headers.println("int numpredicatemembers;");
4655 headers.println("struct predicatemember ** predicatememberarray;");
4656 headers.println("};\n\n");
4658 //STRUCT TASKFAILURE
4659 headers.println("struct taskfailure {");
4660 headers.println("struct taskdescriptor * task;");
4661 headers.println("int index;");
4662 headers.println("int numoptionaltaskdescriptors;");
4663 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
4665 //STRUCT FSANALYSISWRAPPER
4666 headers.println("struct fsanalysiswrapper{");
4667 headers.println("int flags;");
4668 headers.println("int numtags;");
4669 headers.println("int * tags;");
4670 headers.println("int numtaskfailures;");
4671 headers.println("struct taskfailure ** taskfailurearray;");
4672 headers.println("int numoptionaltaskdescriptors;");
4673 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
4675 //STRUCT CLASSANALYSISWRAPPER
4676 headers.println("struct classanalysiswrapper{");
4677 headers.println("int type;");
4678 headers.println("int numotd;");
4679 headers.println("struct optionaltaskdescriptor ** otdarray;");
4680 headers.println("int numfsanalysiswrappers;");
4681 headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
4683 headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
4685 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
4686 while(taskit.hasNext()) {
4687 TaskDescriptor td=(TaskDescriptor)taskit.next();
4688 headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
4693 //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
4694 int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
4695 int predicateindex = 0;
4696 //iterate through the classes concerned by the predicate
4697 Set c_vard = predicate.vardescriptors;
4698 Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
4701 for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext();) {
4702 VarDescriptor vard = (VarDescriptor)vard_it.next();
4703 TypeDescriptor typed = vard.getType();
4705 //generate for flags
4706 HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
4707 output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4709 if (fen_hashset!=null) {
4710 for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext();) {
4711 FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
4713 DNFFlag dflag=fen.getDNF();
4714 numberterms+=dflag.size();
4716 Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
4718 for(int j=0; j<dflag.size(); j++) {
4720 output.println(",");
4721 Vector term=dflag.get(j);
4724 for(int k=0; k<term.size(); k++) {
4725 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
4726 FlagDescriptor fd=dfa.getFlag();
4727 boolean negated=dfa.getNegated();
4728 int flagid=1<<((Integer)flags.get(fd)).intValue();
4733 output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
4738 output.println("};\n");
4741 TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
4742 output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4745 for(int j=0; j<tagel.numTags(); j++) {
4747 output.println(",");
4748 TempDescriptor tmp=tagel.getTemp(j);
4749 if (!slotnumber.containsKey(tmp)) {
4750 Integer slotint=new Integer(current_slot++);
4751 slotnumber.put(tmp,slotint);
4753 int slot=slotnumber.get(tmp).intValue();
4754 output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
4756 numtags = tagel.numTags();
4758 output.println("};");
4760 //store the result into a predicatemember struct
4761 output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
4762 output.println("/*type*/"+typed.getClassDesc().getId()+",");
4763 output.println("/* number of dnf terms */"+numberterms+",");
4764 output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4765 output.println("/* number of tag */"+numtags+",");
4766 output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4767 output.println("};\n");
4772 //generate an array that stores the entire predicate
4773 output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4774 for( int j = 0; j<predicateindex; j++) {
4775 if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4776 else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4778 output.println("};\n");
4779 return predicateindex;
4783 void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
4784 generateOptionalHeader(headers);
4786 output.println("#include \"optionalstruct.h\"\n\n");
4787 output.println("#include \"stdlib.h\"\n");
4789 HashSet processedcd = new HashSet();
4791 Enumeration e = safeexecution.keys();
4792 while (e.hasMoreElements()) {
4795 ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
4796 Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp); //will be used several times
4798 //Generate the struct of optionals
4799 Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
4800 numotd = c_otd.size();
4801 if(maxotd<numotd) maxotd = numotd;
4802 if( !c_otd.isEmpty() ) {
4803 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
4804 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
4806 //generate the int arrays for the predicate
4807 Predicate predicate = otd.predicate;
4808 int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
4809 TreeSet<Integer> fsset=new TreeSet<Integer>();
4810 //iterate through possible FSes corresponding to
4811 //the state when entering
4813 for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext();) {
4814 FlagState fs = (FlagState)fses.next();
4816 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
4817 FlagDescriptor flagd = (FlagDescriptor)flags.next();
4818 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
4821 fsset.add(new Integer(flagid));
4822 //tag information not needed because tag
4823 //changes are not tolerated.
4826 output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4827 boolean needcomma=false;
4828 for(Iterator<Integer> it=fsset.iterator(); it.hasNext();) {
4831 output.println(it.next());
4834 output.println("};\n");
4837 //generate optionaltaskdescriptor that actually
4838 //includes exit fses, predicate and the task
4840 output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
4841 output.println("&task_"+otd.td.getSafeSymbol()+",");
4842 output.println("/*index*/"+otd.getIndex()+",");
4843 output.println("/*number of enter flags*/"+fsset.size()+",");
4844 output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4845 output.println("/*number of members */"+predicateindex+",");
4846 output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4847 output.println("};\n");
4851 // if there are no optionals, there is no need to build the rest of the struct
4853 output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
4854 c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
4855 if( !c_otd.isEmpty() ) {
4856 boolean needcomma=false;
4857 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
4858 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
4860 output.println(",");
4862 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4865 output.println("};\n");
4867 //get all the possible flagstates reachable by an object
4868 Hashtable hashtbtemp = safeexecution.get(cdtemp);
4870 TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
4871 fsts.addAll(hashtbtemp.keySet());
4872 for(Iterator fsit=fsts.iterator(); fsit.hasNext();) {
4873 FlagState fs = (FlagState)fsit.next();
4876 //get the set of OptionalTaskDescriptors corresponding
4877 HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
4878 //iterate through the OptionalTaskDescriptors and
4879 //store the pointers to the optionals struct (see on
4880 //top) into an array
4882 output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
4883 for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext();) {
4884 OptionalTaskDescriptor mm = mos.next();
4886 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
4888 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4891 output.println("};\n");
4893 //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
4896 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
4897 FlagDescriptor flagd = (FlagDescriptor)flags.next();
4898 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
4902 //process tag information
4905 boolean first = true;
4906 Enumeration tag_enum = fs.getTags();
4907 output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
4908 while(tag_enum.hasMoreElements()) {
4910 TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
4914 output.println(", ");
4915 output.println("/*tagid*/"+state.getTagId(tagd));
4917 output.println("};");
4919 Set<TaskIndex> tiset=sa.getTaskIndex(fs);
4920 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
4921 TaskIndex ti=itti.next();
4925 Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
4927 output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
4928 boolean needcomma=false;
4929 for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext();) {
4930 OptionalTaskDescriptor otd=otdit.next();
4934 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4936 output.println("};");
4938 output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
4939 output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
4940 output.print(ti.getIndex()+", ");
4941 output.print(otdset.size()+", ");
4942 output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
4943 output.println("};");
4946 tiset=sa.getTaskIndex(fs);
4947 boolean needcomma=false;
4949 output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
4950 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
4951 TaskIndex ti=itti.next();
4952 if (ti.isRuntime()) {
4959 output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
4961 output.println("};\n");
4963 //Store the result in fsanalysiswrapper
4965 output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
4966 output.println("/*flag*/"+flagid+",");
4967 output.println("/* number of tags*/"+tagcounter+",");
4968 output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
4969 output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
4970 output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
4971 output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
4972 output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
4973 output.println("};\n");
4977 //Build the array of fsanalysiswrappers
4978 output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
4979 boolean needcomma=false;
4980 for(int i = 0; i<fscounter; i++) {
4981 if (needcomma) output.print(",");
4982 output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
4985 output.println("};");
4987 //Build the classanalysiswrapper referring to the previous array
4988 output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
4989 output.println("/*type*/"+cdtemp.getId()+",");
4990 output.println("/*numotd*/"+numotd+",");
4991 output.println("otdarray"+cdtemp.getSafeSymbol()+",");
4992 output.println("/* number of fsanalysiswrappers */"+fscounter+",");
4993 output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
4994 processedcd.add(cdtemp);
4997 //build an array containing every classes for which code has been build
4998 output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
4999 for(int i=0; i<state.numClasses(); i++) {
5000 ClassDescriptor cn=cdarray[i];
5003 if ((cn != null) && (processedcd.contains(cn)))
5004 output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
5006 output.print("NULL");
5008 output.println("};");
5010 output.println("#define MAXOTD "+maxotd);
5011 headers.println("#endif");
5014 public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
5015 Relation r=new Relation();
5016 for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext();) {
5017 OptionalTaskDescriptor otd=otdit.next();
5018 TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
5022 LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
5023 for(Iterator it=r.keySet().iterator(); it.hasNext();) {
5024 Set s=r.get(it.next());
5025 for(Iterator it2=s.iterator(); it2.hasNext();) {
5026 OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
5034 protected void outputTransCode(PrintWriter output) {