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("handle();\n");
320 outmethod.println("#ifdef TRANSSTATS \n");
321 outmethod.println("handle();\n");
322 outmethod.println("#endif\n");
326 if (state.THREAD||state.DSM||state.SINGLETM) {
327 outmethod.println("initializethreads();");
330 outmethod.println("if (dstmStartup(argv[1])) {");
331 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
332 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-2);");
334 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-2);");
337 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
338 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1);");
340 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1);");
344 outmethod.println(" for(i=2;i<argc;i++) {");
346 outmethod.println(" for(i=1;i<argc;i++) {");
347 outmethod.println(" int length=strlen(argv[i]);");
348 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
349 outmethod.println(" struct ___String___ *newstring=NewString(NULL, argv[i], length);");
351 outmethod.println(" struct ___String___ *newstring=NewString(argv[i], length);");
354 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-2]=newstring;");
356 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-1]=newstring;");
357 outmethod.println(" }");
359 MethodDescriptor md=typeutil.getMain();
360 ClassDescriptor cd=typeutil.getMainClass();
362 outmethod.println(" {");
363 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
364 if (state.DSM||state.SINGLETM) {
365 outmethod.print(" struct "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
367 outmethod.print(" struct "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
368 outmethod.println("1, NULL,"+"stringarray};");
369 if (state.DSM||state.SINGLETM)
370 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
372 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
374 if (state.DSM||state.SINGLETM)
375 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
377 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
379 outmethod.println(" }");
382 outmethod.println("}");
385 if (state.THREAD||state.DSM||state.SINGLETM) {
386 outmethod.println("pthread_mutex_lock(&gclistlock);");
387 outmethod.println("threadcount--;");
388 outmethod.println("pthread_cond_signal(&gccond);");
389 outmethod.println("pthread_mutex_unlock(&gclistlock);");
392 if (state.DSM||state.SINGLETM) {
393 outmethod.println("#ifdef TRANSSTATS \n");
394 outmethod.println("printf(\"****** Transaction Stats ******\\n\");");
395 outmethod.println("printf(\"numTransCommit= %d\\n\", numTransCommit);");
396 outmethod.println("printf(\"numTransAbort= %d\\n\", numTransAbort);");
397 outmethod.println("printf(\"nSoftAbort= %d\\n\", nSoftAbort);");
399 outmethod.println("printf(\"nchashSearch= %d\\n\", nchashSearch);");
400 outmethod.println("printf(\"nmhashSearch= %d\\n\", nmhashSearch);");
401 outmethod.println("printf(\"nprehashSearch= %d\\n\", nprehashSearch);");
402 outmethod.println("printf(\"ndirtyCacheObj= %d\\n\", ndirtyCacheObj);");
403 outmethod.println("printf(\"nRemoteReadSend= %d\\n\", nRemoteSend);");
404 outmethod.println("printf(\"bytesSent= %d\\n\", bytesSent);");
405 outmethod.println("printf(\"bytesRecv= %d\\n\", bytesRecv);");
406 outmethod.println("printf(\"totalObjSize= %d\\n\", totalObjSize);");
407 outmethod.println("printf(\"sendRemoteReq= %d\\n\", sendRemoteReq);");
408 outmethod.println("printf(\"getResponse= %d\\n\", getResponse);");
409 } else if (state.SINGLETM) {
410 outmethod.println("printf(\"nSoftAbortAbort= %d\\n\", nSoftAbortAbort);");
411 outmethod.println("printf(\"nSoftAbortCommit= %d\\n\", nSoftAbortCommit);");
412 outmethod.println("#ifdef STMSTATS\n");
413 outmethod.println("for(i=0; i<TOTALNUMCLASSANDARRAY; i++) {\n");
414 outmethod.println(" printf(\"typesCausingAbort[%2d] numaccess= %5d numabort= %3d\\n\", i, typesCausingAbort[i].numaccess, typesCausingAbort[i].numabort);\n");
415 outmethod.println("}\n");
416 outmethod.println("#endif\n");
417 outmethod.println("fflush(stdout);");
419 outmethod.println("#endif\n");
422 if (state.EVENTMONITOR) {
423 outmethod.println("dumpdata();");
426 if (state.THREAD||state.SINGLETM)
427 outmethod.println("pthread_exit(NULL);");
430 outmethod.println(" workScheduleBegin();");
433 outmethod.println("}");
436 /* This method outputs code for each task. */
438 private void outputTaskCode(PrintWriter outtaskdefs, PrintWriter outmethod) {
439 /* Compile task based program */
440 outtaskdefs.println("#include \"task.h\"");
441 outtaskdefs.println("#include \"methodheaders.h\"");
442 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
443 while(taskit.hasNext()) {
444 TaskDescriptor td=(TaskDescriptor)taskit.next();
445 FlatMethod fm=state.getMethodFlat(td);
446 generateFlatMethod(fm, null, outmethod);
447 generateTaskDescriptor(outtaskdefs, fm, td);
450 //Output task descriptors
451 taskit=state.getTaskSymbolTable().getDescriptorsIterator();
452 outtaskdefs.println("struct taskdescriptor * taskarray[]= {");
454 while(taskit.hasNext()) {
455 TaskDescriptor td=(TaskDescriptor)taskit.next();
459 outtaskdefs.println(",");
460 outtaskdefs.print("&task_"+td.getSafeSymbol());
462 outtaskdefs.println("};");
464 outtaskdefs.println("int numtasks="+state.getTaskSymbolTable().getValueSet().size()+";");
467 /* This method outputs most of the methods.c file. This includes
468 * some standard includes and then an array with the sizes of
469 * objets and array that stores supertype and then the code for
470 * the Java methods.. */
472 protected void outputMethods(PrintWriter outmethod) {
473 outmethod.println("#include \"methodheaders.h\"");
474 outmethod.println("#include \"virtualtable.h\"");
475 outmethod.println("#include \"runtime.h\"");
477 outmethod.println("#include \"sandboxdefs.c\"");
480 outmethod.println("#include \"addPrefetchEnhance.h\"");
481 outmethod.println("#include \"localobjects.h\"");
483 if (state.FASTCHECK) {
484 outmethod.println("#include \"localobjects.h\"");
486 if(state.MULTICORE) {
487 outmethod.println("#include \"task.h\"");
488 outmethod.println("#include \"multicoreruntime.h\"");
489 outmethod.println("#include \"runtime_arch.h\"");
491 if (state.THREAD||state.DSM||state.SINGLETM)
492 outmethod.println("#include <thread.h>");
493 if (state.main!=null) {
494 outmethod.println("#include <string.h>");
496 if (state.CONSCHECK) {
497 outmethod.println("#include \"checkers.h\"");
500 outmethod.println("#include <stdlib.h>");
501 outmethod.println("#include <stdio.h>");
502 outmethod.println("#include \"mlp_runtime.h\"");
503 outmethod.println("#include \"psemaphore.h\"");
507 //Store the sizes of classes & array elements
508 generateSizeArray(outmethod);
510 //Store table of supertypes
511 generateSuperTypeTable(outmethod);
513 //Store the layout of classes
514 generateLayoutStructs(outmethod);
516 /* Generate code for methods */
517 if (state.DSM||state.SINGLETM) {
518 for(Iterator<LocalityBinding> lbit=locality.getLocalityBindings().iterator(); lbit.hasNext();) {
519 LocalityBinding lb=lbit.next();
520 MethodDescriptor md=lb.getMethod();
521 FlatMethod fm=state.getMethodFlat(md);
523 if (!md.getModifiers().isNative()) {
524 generateFlatMethod(fm, lb, outmethod);
525 //System.out.println("fm= " + fm + " md= " + md);
529 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
530 while(classit.hasNext()) {
531 ClassDescriptor cn=(ClassDescriptor)classit.next();
532 Iterator methodit=cn.getMethods();
533 while(methodit.hasNext()) {
534 /* Classify parameters */
535 MethodDescriptor md=(MethodDescriptor)methodit.next();
536 FlatMethod fm=state.getMethodFlat(md);
537 if (!md.getModifiers().isNative()) {
538 generateFlatMethod(fm, null, outmethod);
545 protected void outputStructs(PrintWriter outstructs) {
546 outstructs.println("#ifndef STRUCTDEFS_H");
547 outstructs.println("#define STRUCTDEFS_H");
548 outstructs.println("#include \"classdefs.h\"");
549 outstructs.println("#ifndef INTPTR");
550 outstructs.println("#ifdef BIT64");
551 outstructs.println("#define INTPTR long");
552 outstructs.println("#else");
553 outstructs.println("#define INTPTR int");
554 outstructs.println("#endif");
555 outstructs.println("#endif");
557 outstructs.println("#include \"mlp_runtime.h\"");
558 outstructs.println("#include \"psemaphore.h\"");
561 /* Output #defines that the runtime uses to determine type
562 * numbers for various objects it needs */
563 outstructs.println("#define MAXCOUNT "+maxcount);
564 if (state.DSM||state.SINGLETM) {
565 LocalityBinding lbrun=new LocalityBinding(typeutil.getRun(), false);
567 lbrun.setGlobalThis(LocalityAnalysis.GLOBAL);
569 else if (state.SINGLETM) {
570 lbrun.setGlobalThis(LocalityAnalysis.NORMAL);
572 outstructs.println("#define RUNMETHOD "+virtualcalls.getLocalityNumber(lbrun));
576 LocalityBinding lbexecute = new LocalityBinding(typeutil.getExecute(), false);
578 lbexecute.setGlobalThis(LocalityAnalysis.GLOBAL);
579 else if( state.SINGLETM)
580 lbexecute.setGlobalThis(LocalityAnalysis.NORMAL);
581 outstructs.println("#define EXECUTEMETHOD " + virtualcalls.getLocalityNumber(lbexecute));
584 outstructs.println("#define STRINGARRAYTYPE "+
585 (state.getArrayNumber(
586 (new TypeDescriptor(typeutil.getClass(TypeUtil.StringClass))).makeArray(state))+state.numClasses()));
588 outstructs.println("#define OBJECTARRAYTYPE "+
589 (state.getArrayNumber(
590 (new TypeDescriptor(typeutil.getClass(TypeUtil.ObjectClass))).makeArray(state))+state.numClasses()));
593 outstructs.println("#define STRINGTYPE "+typeutil.getClass(TypeUtil.StringClass).getId());
594 outstructs.println("#define CHARARRAYTYPE "+
595 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.CHAR)).makeArray(state))+state.numClasses()));
597 outstructs.println("#define BYTEARRAYTYPE "+
598 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state))+state.numClasses()));
600 outstructs.println("#define BYTEARRAYARRAYTYPE "+
601 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state).makeArray(state))+state.numClasses()));
603 outstructs.println("#define NUMCLASSES "+state.numClasses());
604 int totalClassSize = state.numClasses() + state.numArrays();
605 outstructs.println("#define TOTALNUMCLASSANDARRAY "+ totalClassSize);
607 outstructs.println("#define STARTUPTYPE "+typeutil.getClass(TypeUtil.StartupClass).getId());
608 outstructs.println("#define TAGTYPE "+typeutil.getClass(TypeUtil.TagClass).getId());
609 outstructs.println("#define TAGARRAYTYPE "+
610 (state.getArrayNumber(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)).makeArray(state))+state.numClasses()));
614 protected void outputClassDeclarations(PrintWriter outclassdefs) {
615 if (state.THREAD||state.DSM||state.SINGLETM)
616 outclassdefs.println("#include <pthread.h>");
617 outclassdefs.println("#ifndef INTPTR");
618 outclassdefs.println("#ifdef BIT64");
619 outclassdefs.println("#define INTPTR long");
620 outclassdefs.println("#else");
621 outclassdefs.println("#define INTPTR int");
622 outclassdefs.println("#endif");
623 outclassdefs.println("#endif");
625 outclassdefs.println("#include \"optionalstruct.h\"");
626 outclassdefs.println("struct "+arraytype+";");
627 /* Start by declaring all structs */
628 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
629 while(it.hasNext()) {
630 ClassDescriptor cn=(ClassDescriptor)it.next();
631 outclassdefs.println("struct "+cn.getSafeSymbol()+";");
633 outclassdefs.println("");
634 //Print out definition for array type
635 outclassdefs.println("struct "+arraytype+" {");
636 outclassdefs.println(" int type;");
637 if (state.EVENTMONITOR) {
638 outclassdefs.println(" int objuid;");
641 outclassdefs.println(" pthread_t tid;");
642 outclassdefs.println(" void * lockentry;");
643 outclassdefs.println(" int lockcount;");
646 outclassdefs.println(" int flag;");
647 if(!state.MULTICORE) {
648 outclassdefs.println(" void * flagptr;");
650 outclassdefs.println(" int version;");
651 outclassdefs.println(" int * lock;"); // lock entry for this obj
652 outclassdefs.println(" int mutex;");
653 outclassdefs.println(" int lockcount;");
654 if(state.MULTICOREGC) {
655 outclassdefs.println(" int marked;");
659 outclassdefs.println(" int numfses;");
660 outclassdefs.println(" int * fses;");
663 printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs);
665 if (state.STMARRAY) {
666 outclassdefs.println(" int lowindex;");
667 outclassdefs.println(" int highindex;");
670 outclassdefs.println(" int paddingforarray;");
671 if (state.DUALVIEW) {
672 outclassdefs.println(" int arrayversion;");
675 outclassdefs.println(" int ___length___;");
676 outclassdefs.println("};\n");
677 outclassdefs.println("extern int classsize[];");
678 outclassdefs.println("extern int hasflags[];");
679 outclassdefs.println("extern unsigned INTPTR * pointerarray[];");
680 outclassdefs.println("extern int supertypes[];");
683 /** Prints out definitions for generic task structures */
685 private void outputTaskTypes(PrintWriter outtask) {
686 outtask.println("#ifndef _TASK_H");
687 outtask.println("#define _TASK_H");
688 outtask.println("struct parameterdescriptor {");
689 outtask.println("int type;");
690 outtask.println("int numberterms;");
691 outtask.println("int *intarray;");
692 outtask.println("void * queue;");
693 outtask.println("int numbertags;");
694 outtask.println("int *tagarray;");
695 outtask.println("};");
697 outtask.println("struct taskdescriptor {");
698 outtask.println("void * taskptr;");
699 outtask.println("int numParameters;");
700 outtask.println(" int numTotal;");
701 outtask.println("struct parameterdescriptor **descriptorarray;");
702 outtask.println("char * name;");
703 outtask.println("};");
704 outtask.println("extern struct taskdescriptor * taskarray[];");
705 outtask.println("extern numtasks;");
706 outtask.println("#endif");
710 private void buildRepairStructs(PrintWriter outrepairstructs) {
711 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
712 while(classit.hasNext()) {
713 ClassDescriptor cn=(ClassDescriptor)classit.next();
714 outrepairstructs.println("structure "+cn.getSymbol()+" {");
715 outrepairstructs.println(" int __type__;");
717 outrepairstructs.println(" int __flag__;");
718 if(!state.MULTICORE) {
719 outrepairstructs.println(" int __flagptr__;");
722 printRepairStruct(cn, outrepairstructs);
723 outrepairstructs.println("}\n");
726 for(int i=0; i<state.numArrays(); i++) {
727 TypeDescriptor tdarray=arraytable[i];
728 TypeDescriptor tdelement=tdarray.dereference();
729 outrepairstructs.println("structure "+arraytype+"_"+state.getArrayNumber(tdarray)+" {");
730 outrepairstructs.println(" int __type__;");
731 printRepairStruct(typeutil.getClass(TypeUtil.ObjectClass), outrepairstructs);
732 outrepairstructs.println(" int length;");
734 // Need to add support to repair tool for this
735 if (tdelement.isClass()||tdelement.isArray())
736 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" * elem[this.length];");
738 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" elem[this.length];");
740 outrepairstructs.println("}\n");
744 private void printRepairStruct(ClassDescriptor cn, PrintWriter output) {
745 ClassDescriptor sp=cn.getSuperDesc();
747 printRepairStruct(sp, output);
749 Vector fields=(Vector)fieldorder.get(cn);
751 for(int i=0; i<fields.size(); i++) {
752 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
753 if (fd.getType().isArray()) {
754 output.println(" "+arraytype+"_"+ state.getArrayNumber(fd.getType()) +" * "+fd.getSymbol()+";");
755 } else if (fd.getType().isClass())
756 output.println(" "+fd.getType().getRepairSymbol()+" * "+fd.getSymbol()+";");
757 else if (fd.getType().isFloat())
758 output.println(" int "+fd.getSymbol()+"; /* really float */");
760 output.println(" "+fd.getType().getRepairSymbol()+" "+fd.getSymbol()+";");
764 /** This method outputs TaskDescriptor information */
765 private void generateTaskDescriptor(PrintWriter output, FlatMethod fm, TaskDescriptor task) {
766 for (int i=0; i<task.numParameters(); i++) {
767 VarDescriptor param_var=task.getParameter(i);
768 TypeDescriptor param_type=task.getParamType(i);
769 FlagExpressionNode param_flag=task.getFlag(param_var);
770 TagExpressionList param_tag=task.getTag(param_var);
773 if (param_flag==null) {
774 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
775 output.println("0x0, 0x0 };");
778 DNFFlag dflag=param_flag.getDNF();
779 dnfterms=dflag.size();
781 Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
782 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
783 for(int j=0; j<dflag.size(); j++) {
786 Vector term=dflag.get(j);
789 for(int k=0; k<term.size(); k++) {
790 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
791 FlagDescriptor fd=dfa.getFlag();
792 boolean negated=dfa.getNegated();
793 int flagid=1<<((Integer)flags.get(fd)).intValue();
798 output.print("0x"+Integer.toHexString(andmask)+", 0x"+Integer.toHexString(checkmask));
800 output.println("};");
803 output.println("int parametertag_"+i+"_"+task.getSafeSymbol()+"[]={");
804 //BUG...added next line to fix, test with any task program
806 for(int j=0; j<param_tag.numTags(); j++) {
809 /* for each tag we need */
810 /* which slot it is */
811 /* what type it is */
812 TagVarDescriptor tvd=(TagVarDescriptor)task.getParameterTable().get(param_tag.getName(j));
813 TempDescriptor tmp=param_tag.getTemp(j);
814 int slot=fm.getTagInt(tmp);
815 output.println(slot+", "+state.getTagId(tvd.getTag()));
817 output.println("};");
819 output.println("struct parameterdescriptor parameter_"+i+"_"+task.getSafeSymbol()+"={");
820 output.println("/* type */"+param_type.getClassDesc().getId()+",");
821 output.println("/* number of DNF terms */"+dnfterms+",");
822 output.println("parameterdnf_"+i+"_"+task.getSafeSymbol()+",");
823 output.println("0,");
824 //BUG, added next line to fix and else statement...test
825 //with any task program
827 output.println("/* number of tags */"+param_tag.numTags()+",");
829 output.println("/* number of tags */ 0,");
830 output.println("parametertag_"+i+"_"+task.getSafeSymbol());
831 output.println("};");
835 output.println("struct parameterdescriptor * parameterdescriptors_"+task.getSafeSymbol()+"[] = {");
836 for (int i=0; i<task.numParameters(); i++) {
839 output.print("¶meter_"+i+"_"+task.getSafeSymbol());
841 output.println("};");
843 output.println("struct taskdescriptor task_"+task.getSafeSymbol()+"={");
844 output.println("&"+task.getSafeSymbol()+",");
845 output.println("/* number of parameters */" +task.numParameters() + ",");
846 int numtotal=task.numParameters()+fm.numTags();
847 output.println("/* number total parameters */" +numtotal + ",");
848 output.println("parameterdescriptors_"+task.getSafeSymbol()+",");
849 output.println("\""+task.getSymbol()+"\"");
850 output.println("};");
854 /** The buildVirtualTables method outputs the virtual dispatch
855 * tables for methods. */
857 protected void buildVirtualTables(PrintWriter outvirtual) {
858 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
859 while(classit.hasNext()) {
860 ClassDescriptor cd=(ClassDescriptor)classit.next();
861 if (virtualcalls.getMethodCount(cd)>maxcount)
862 maxcount=virtualcalls.getMethodCount(cd);
864 MethodDescriptor[][] virtualtable=null;
865 LocalityBinding[][] lbvirtualtable=null;
866 if (state.DSM||state.SINGLETM)
867 lbvirtualtable=new LocalityBinding[state.numClasses()+state.numArrays()][maxcount];
869 virtualtable=new MethodDescriptor[state.numClasses()+state.numArrays()][maxcount];
871 /* Fill in virtual table */
872 classit=state.getClassSymbolTable().getDescriptorsIterator();
873 while(classit.hasNext()) {
874 ClassDescriptor cd=(ClassDescriptor)classit.next();
875 if (state.DSM||state.SINGLETM)
876 fillinRow(cd, lbvirtualtable, cd.getId());
878 fillinRow(cd, virtualtable, cd.getId());
881 ClassDescriptor objectcd=typeutil.getClass(TypeUtil.ObjectClass);
882 Iterator arrayit=state.getArrayIterator();
883 while(arrayit.hasNext()) {
884 TypeDescriptor td=(TypeDescriptor)arrayit.next();
885 int id=state.getArrayNumber(td);
886 if (state.DSM||state.SINGLETM)
887 fillinRow(objectcd, lbvirtualtable, id+state.numClasses());
889 fillinRow(objectcd, virtualtable, id+state.numClasses());
892 outvirtual.print("void * virtualtable[]={");
893 boolean needcomma=false;
894 for(int i=0; i<state.numClasses()+state.numArrays(); i++) {
895 for(int j=0; j<maxcount; j++) {
897 outvirtual.print(", ");
898 if ((state.DSM||state.SINGLETM)&&lbvirtualtable[i][j]!=null) {
899 LocalityBinding lb=lbvirtualtable[i][j];
900 MethodDescriptor md=lb.getMethod();
901 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
902 } else if (!(state.DSM||state.SINGLETM)&&virtualtable[i][j]!=null) {
903 MethodDescriptor md=virtualtable[i][j];
904 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
906 outvirtual.print("0");
910 outvirtual.println("");
912 outvirtual.println("};");
916 private void fillinRow(ClassDescriptor cd, MethodDescriptor[][] virtualtable, int rownum) {
917 /* Get inherited methods */
918 if (cd.getSuperDesc()!=null)
919 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
920 /* Override them with our methods */
921 for(Iterator it=cd.getMethods(); it.hasNext();) {
922 MethodDescriptor md=(MethodDescriptor)it.next();
923 if (md.isStatic()||md.getReturnType()==null)
925 int methodnum=virtualcalls.getMethodNumber(md);
926 virtualtable[rownum][methodnum]=md;
930 private void fillinRow(ClassDescriptor cd, LocalityBinding[][] virtualtable, int rownum) {
931 /* Get inherited methods */
932 if (cd.getSuperDesc()!=null)
933 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
934 /* Override them with our methods */
935 if (locality.getClassBindings(cd)!=null)
936 for(Iterator<LocalityBinding> lbit=locality.getClassBindings(cd).iterator(); lbit.hasNext();) {
937 LocalityBinding lb=lbit.next();
938 MethodDescriptor md=lb.getMethod();
939 //Is the method static or a constructor
940 if (md.isStatic()||md.getReturnType()==null)
942 int methodnum=virtualcalls.getLocalityNumber(lb);
943 virtualtable[rownum][methodnum]=lb;
947 /** Generate array that contains the sizes of class objects. The
948 * object allocation functions in the runtime use this
951 private void generateSizeArray(PrintWriter outclassdefs) {
952 outclassdefs.print("extern struct prefetchCountStats * evalPrefetch;\n");
953 outclassdefs.print("#ifdef TRANSSTATS \n");
954 outclassdefs.print("extern int numTransAbort;\n");
955 outclassdefs.print("extern int numTransCommit;\n");
956 outclassdefs.print("extern int nSoftAbort;\n");
958 outclassdefs.print("extern int nchashSearch;\n");
959 outclassdefs.print("extern int nmhashSearch;\n");
960 outclassdefs.print("extern int nprehashSearch;\n");
961 outclassdefs.print("extern int ndirtyCacheObj;\n");
962 outclassdefs.print("extern int nRemoteSend;\n");
963 outclassdefs.print("extern int sendRemoteReq;\n");
964 outclassdefs.print("extern int getResponse;\n");
965 outclassdefs.print("extern int bytesSent;\n");
966 outclassdefs.print("extern int bytesRecv;\n");
967 outclassdefs.print("extern int totalObjSize;\n");
968 outclassdefs.print("extern void handle();\n");
969 } else if (state.SINGLETM) {
970 outclassdefs.println("extern int nSoftAbortAbort;");
971 outclassdefs.println("extern int nSoftAbortCommit;");
972 outclassdefs.println("#ifdef STMSTATS\n");
973 outclassdefs.println("extern objtypestat_t typesCausingAbort[];");
974 outclassdefs.println("#endif\n");
976 outclassdefs.print("#endif\n");
978 outclassdefs.print("int numprefetchsites = " + pa.prefetchsiteid + ";\n");
980 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
981 cdarray=new ClassDescriptor[state.numClasses()];
983 while(it.hasNext()) {
984 ClassDescriptor cd=(ClassDescriptor)it.next();
985 cdarray[cd.getId()]=cd;
988 arraytable=new TypeDescriptor[state.numArrays()];
990 Iterator arrayit=state.getArrayIterator();
991 while(arrayit.hasNext()) {
992 TypeDescriptor td=(TypeDescriptor)arrayit.next();
993 int id=state.getArrayNumber(td);
999 /* Print out types */
1000 outclassdefs.println("/* ");
1001 for(int i=0; i<state.numClasses(); i++) {
1002 ClassDescriptor cd=cdarray[i];
1004 outclassdefs.println("NULL " + i);
1006 outclassdefs.println(cd +" "+i);
1010 for(int i=0; i<state.numArrays(); i++) {
1011 TypeDescriptor arraytd=arraytable[i];
1012 outclassdefs.println(arraytd.toPrettyString() +" "+(i+state.numClasses()));
1015 outclassdefs.println("*/");
1018 outclassdefs.print("int classsize[]={");
1020 boolean needcomma=false;
1021 for(int i=0; i<state.numClasses(); i++) {
1023 outclassdefs.print(", ");
1025 outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")");
1027 outclassdefs.print("0");
1033 for(int i=0; i<state.numArrays(); i++) {
1035 outclassdefs.print(", ");
1036 TypeDescriptor tdelement=arraytable[i].dereference();
1037 if (tdelement.isArray()||tdelement.isClass())
1038 outclassdefs.print("sizeof(void *)");
1040 outclassdefs.print("sizeof("+tdelement.getSafeSymbol()+")");
1044 outclassdefs.println("};");
1046 ClassDescriptor objectclass=typeutil.getClass(TypeUtil.ObjectClass);
1048 outclassdefs.print("int typearray[]={");
1049 for(int i=0; i<state.numClasses(); i++) {
1050 ClassDescriptor cd=cdarray[i];
1051 ClassDescriptor supercd=i>0?cd.getSuperDesc():null;
1053 outclassdefs.print(", ");
1055 outclassdefs.print("-1");
1057 outclassdefs.print(supercd.getId());
1061 for(int i=0; i<state.numArrays(); i++) {
1062 TypeDescriptor arraytd=arraytable[i];
1063 ClassDescriptor arraycd=arraytd.getClassDesc();
1064 if (arraycd==null) {
1066 outclassdefs.print(", ");
1067 outclassdefs.print(objectclass.getId());
1071 ClassDescriptor cd=arraycd.getSuperDesc();
1074 TypeDescriptor supertd=new TypeDescriptor(cd);
1075 supertd.setArrayCount(arraytd.getArrayCount());
1076 type=state.getArrayNumber(supertd);
1078 type+=state.numClasses();
1081 cd=cd.getSuperDesc();
1084 outclassdefs.print(", ");
1085 outclassdefs.print(type);
1089 outclassdefs.println("};");
1094 outclassdefs.print("int typearray2[]={");
1095 for(int i=0; i<state.numArrays(); i++) {
1096 TypeDescriptor arraytd=arraytable[i];
1097 ClassDescriptor arraycd=arraytd.getClassDesc();
1098 if (arraycd==null) {
1100 outclassdefs.print(", ");
1101 outclassdefs.print("-1");
1105 ClassDescriptor cd=arraycd.getSuperDesc();
1106 int level=arraytd.getArrayCount()-1;
1108 for(; level>0; level--) {
1109 TypeDescriptor supertd=new TypeDescriptor(objectclass);
1110 supertd.setArrayCount(level);
1111 type=state.getArrayNumber(supertd);
1113 type+=state.numClasses();
1118 outclassdefs.print(", ");
1119 outclassdefs.print(type);
1123 outclassdefs.println("};");
1126 /** Constructs params and temp objects for each method or task.
1127 * These objects tell the compiler which temps need to be
1130 protected void generateTempStructs(FlatMethod fm, LocalityBinding lb) {
1131 MethodDescriptor md=fm.getMethod();
1132 TaskDescriptor task=fm.getTask();
1133 Set<TempDescriptor> saveset=lb!=null ? locality.getTempSet(lb) : null;
1134 ParamsObject objectparams=md!=null ? new ParamsObject(md,tag++) : new ParamsObject(task, tag++);
1136 paramstable.put(lb, objectparams);
1137 backuptable.put(lb, new Hashtable<TempDescriptor, TempDescriptor>());
1138 } else if (md!=null)
1139 paramstable.put(md, objectparams);
1141 paramstable.put(task, objectparams);
1143 for(int i=0; i<fm.numParameters(); i++) {
1144 TempDescriptor temp=fm.getParameter(i);
1145 TypeDescriptor type=temp.getType();
1146 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1147 objectparams.addPtr(temp);
1149 objectparams.addPrim(temp);
1150 if(lb!=null&&saveset.contains(temp)) {
1151 backuptable.get(lb).put(temp, temp.createNew());
1155 for(int i=0; i<fm.numTags(); i++) {
1156 TempDescriptor temp=fm.getTag(i);
1157 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1158 objectparams.addPtr(temp);
1160 objectparams.addPrim(temp);
1163 TempObject objecttemps=md!=null ? new TempObject(objectparams,md,tag++) : new TempObject(objectparams, task, tag++);
1165 tempstable.put(lb, objecttemps);
1167 tempstable.put(md, objecttemps);
1169 tempstable.put(task, objecttemps);
1171 for(Iterator nodeit=fm.getNodeSet().iterator(); nodeit.hasNext();) {
1172 FlatNode fn=(FlatNode)nodeit.next();
1173 TempDescriptor[] writes=fn.writesTemps();
1174 for(int i=0; i<writes.length; i++) {
1175 TempDescriptor temp=writes[i];
1176 TypeDescriptor type=temp.getType();
1177 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1178 objecttemps.addPtr(temp);
1180 objecttemps.addPrim(temp);
1181 if(lb!=null&&saveset.contains(temp)&&
1182 !backuptable.get(lb).containsKey(temp))
1183 backuptable.get(lb).put(temp, temp.createNew());
1187 /* Create backup temps */
1189 for(Iterator<TempDescriptor> tmpit=backuptable.get(lb).values().iterator(); tmpit.hasNext();) {
1190 TempDescriptor tmp=tmpit.next();
1191 TypeDescriptor type=tmp.getType();
1192 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1193 objecttemps.addPtr(tmp);
1195 objecttemps.addPrim(tmp);
1197 /* Create temp to hold revert table */
1198 if (state.DSM&&(lb.getHasAtomic()||lb.isAtomic())) {
1199 TempDescriptor reverttmp=new TempDescriptor("revertlist", typeutil.getClass(TypeUtil.ObjectClass));
1200 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1201 objecttemps.addPtr(reverttmp);
1203 objecttemps.addPrim(reverttmp);
1204 reverttable.put(lb, reverttmp);
1209 /** This method outputs the following information about classes
1211 * (1) For classes, what are the locations of pointers.
1212 * (2) For arrays, does the array contain pointers or primitives.
1213 * (3) For classes, does the class contain flags.
1216 private void generateLayoutStructs(PrintWriter output) {
1217 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1218 while(it.hasNext()) {
1219 ClassDescriptor cn=(ClassDescriptor)it.next();
1220 output.println("unsigned INTPTR "+cn.getSafeSymbol()+"_pointers[]={");
1221 Iterator allit=cn.getFieldTable().getAllDescriptorsIterator();
1223 while(allit.hasNext()) {
1224 FieldDescriptor fd=(FieldDescriptor)allit.next();
1225 TypeDescriptor type=fd.getType();
1226 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1231 output.print(count);
1232 allit=cn.getFieldTable().getAllDescriptorsIterator();
1233 while(allit.hasNext()) {
1234 FieldDescriptor fd=(FieldDescriptor)allit.next();
1235 TypeDescriptor type=fd.getType();
1236 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1239 output.println(",");
1240 output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+fd.getSafeSymbol()+"))");
1243 output.println("};");
1245 output.println("unsigned INTPTR * pointerarray[]={");
1246 boolean needcomma=false;
1247 for(int i=0; i<state.numClasses(); i++) {
1248 ClassDescriptor cn=cdarray[i];
1250 output.println(",");
1253 output.print(cn.getSafeSymbol()+"_pointers");
1255 output.print("NULL");
1259 for(int i=0; i<state.numArrays(); i++) {
1261 output.println(", ");
1262 TypeDescriptor tdelement=arraytable[i].dereference();
1263 if (tdelement.isArray()||tdelement.isClass())
1264 output.print("((unsigned INTPTR *)1)");
1270 output.println("};");
1272 output.println("int hasflags[]={");
1273 for(int i=0; i<state.numClasses(); i++) {
1274 ClassDescriptor cn=cdarray[i];
1276 output.println(", ");
1278 if ((cn != null) && (cn.hasFlags()))
1283 output.println("};");
1286 /** Print out table to give us supertypes */
1287 private void generateSuperTypeTable(PrintWriter output) {
1288 output.println("int supertypes[]={");
1289 boolean needcomma=false;
1290 for(int i=0; i<state.numClasses(); i++) {
1291 ClassDescriptor cn=cdarray[i];
1293 output.println(",");
1295 if ((cn != null) && (cn.getSuperDesc()!=null)) {
1296 ClassDescriptor cdsuper=cn.getSuperDesc();
1297 output.print(cdsuper.getId());
1301 output.println("};");
1304 /** Force consistent field ordering between inherited classes. */
1306 private void printClassStruct(ClassDescriptor cn, PrintWriter classdefout) {
1308 ClassDescriptor sp=cn.getSuperDesc();
1310 printClassStruct(sp, classdefout);
1312 if (!fieldorder.containsKey(cn)) {
1313 Vector fields=new Vector();
1314 fieldorder.put(cn,fields);
1315 Vector fieldvec=cn.getFieldVec();
1316 for(int i=0;i<fieldvec.size();i++) {
1317 FieldDescriptor fd=(FieldDescriptor)fieldvec.get(i);
1318 if ((sp==null||!sp.getFieldTable().contains(fd.getSymbol())))
1322 Vector fields=(Vector)fieldorder.get(cn);
1324 for(int i=0; i<fields.size(); i++) {
1325 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
1326 if (fd.getType().isClass()||fd.getType().isArray())
1327 classdefout.println(" struct "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1329 classdefout.println(" "+fd.getType().getSafeSymbol()+" "+fd.getSafeSymbol()+";");
1334 /* Map flags to integers consistently between inherited
1337 protected void mapFlags(ClassDescriptor cn) {
1338 ClassDescriptor sp=cn.getSuperDesc();
1342 if (!flagorder.containsKey(cn)) {
1343 Hashtable flags=new Hashtable();
1344 flagorder.put(cn,flags);
1346 Hashtable superflags=(Hashtable)flagorder.get(sp);
1347 Iterator superflagit=superflags.keySet().iterator();
1348 while(superflagit.hasNext()) {
1349 FlagDescriptor fd=(FlagDescriptor)superflagit.next();
1350 Integer number=(Integer)superflags.get(fd);
1351 flags.put(fd, number);
1352 if ((number.intValue()+1)>max)
1353 max=number.intValue()+1;
1357 Iterator flagit=cn.getFlags();
1358 while(flagit.hasNext()) {
1359 FlagDescriptor fd=(FlagDescriptor)flagit.next();
1360 if (sp==null||!sp.getFlagTable().contains(fd.getSymbol()))
1361 flags.put(fd, new Integer(max++));
1367 /** This function outputs (1) structures that parameters are
1368 * passed in (when PRECISE GC is enabled) and (2) function
1369 * prototypes for the methods */
1371 protected void generateCallStructs(ClassDescriptor cn, PrintWriter classdefout, PrintWriter output, PrintWriter headersout) {
1372 /* Output class structure */
1373 classdefout.println("struct "+cn.getSafeSymbol()+" {");
1374 classdefout.println(" int type;");
1375 if (state.EVENTMONITOR) {
1376 classdefout.println(" int objuid;");
1379 classdefout.println(" pthread_t tid;");
1380 classdefout.println(" void * lockentry;");
1381 classdefout.println(" int lockcount;");
1385 classdefout.println(" int flag;");
1386 if((!state.MULTICORE) || (cn.getSymbol().equals("TagDescriptor"))) {
1387 classdefout.println(" void * flagptr;");
1388 } else if (state.MULTICORE) {
1389 classdefout.println(" int version;");
1390 classdefout.println(" int * lock;"); // lock entry for this obj
1391 classdefout.println(" int mutex;");
1392 classdefout.println(" int lockcount;");
1393 if(state.MULTICOREGC) {
1394 classdefout.println(" int marked;");
1397 if (state.OPTIONAL) {
1398 classdefout.println(" int numfses;");
1399 classdefout.println(" int * fses;");
1402 printClassStruct(cn, classdefout);
1403 classdefout.println("};\n");
1405 if (state.DSM||state.SINGLETM) {
1406 /* Cycle through LocalityBindings */
1407 HashSet<MethodDescriptor> nativemethods=new HashSet<MethodDescriptor>();
1408 Set<LocalityBinding> lbset=locality.getClassBindings(cn);
1410 for(Iterator<LocalityBinding> lbit=lbset.iterator(); lbit.hasNext();) {
1411 LocalityBinding lb=lbit.next();
1412 MethodDescriptor md=lb.getMethod();
1413 if (md.getModifiers().isNative()) {
1414 //make sure we only print a native method once
1415 if (nativemethods.contains(md)) {
1416 FlatMethod fm=state.getMethodFlat(md);
1417 generateTempStructs(fm, lb);
1420 nativemethods.add(md);
1422 generateMethod(cn, md, lb, headersout, output);
1425 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1426 MethodDescriptor md=(MethodDescriptor)methodit.next();
1427 if (md.getModifiers().isNative()&&!nativemethods.contains(md)) {
1428 //Need to build param structure for library code
1429 FlatMethod fm=state.getMethodFlat(md);
1430 generateTempStructs(fm, null);
1431 generateMethodParam(cn, md, null, output);
1436 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1437 MethodDescriptor md=(MethodDescriptor)methodit.next();
1438 generateMethod(cn, md, null, headersout, output);
1442 private void generateMethodParam(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter output) {
1443 /* Output parameter structure */
1444 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1445 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1446 if ((state.DSM||state.SINGLETM)&&lb!=null)
1447 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1449 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1450 output.println(" INTPTR size;");
1451 output.println(" void * next;");
1452 for(int i=0; i<objectparams.numPointers(); i++) {
1453 TempDescriptor temp=objectparams.getPointer(i);
1454 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1456 output.println("};\n");
1460 private void generateMethod(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter headersout, PrintWriter output) {
1461 FlatMethod fm=state.getMethodFlat(md);
1462 generateTempStructs(fm, lb);
1464 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1465 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md);
1467 generateMethodParam(cn, md, lb, output);
1469 /* Output temp structure */
1470 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1471 if (state.DSM||state.SINGLETM)
1472 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1474 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1475 output.println(" INTPTR size;");
1476 output.println(" void * next;");
1477 for(int i=0; i<objecttemps.numPointers(); i++) {
1478 TempDescriptor temp=objecttemps.getPointer(i);
1479 if (temp.getType().isNull())
1480 output.println(" void * "+temp.getSafeSymbol()+";");
1482 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1484 output.println("};\n");
1487 /********* Output method declaration ***********/
1488 if (state.DSM||state.SINGLETM) {
1489 headersout.println("#define D"+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1491 headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1493 /* First the return type */
1494 if (md.getReturnType()!=null) {
1495 if (md.getReturnType().isClass()||md.getReturnType().isArray())
1496 headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1498 headersout.print(md.getReturnType().getSafeSymbol()+" ");
1500 //catch the constructor case
1501 headersout.print("void ");
1503 /* Next the method name */
1504 if (state.DSM||state.SINGLETM) {
1505 headersout.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1507 headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1509 boolean printcomma=false;
1510 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1511 if (state.DSM||state.SINGLETM) {
1512 headersout.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1514 headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1518 /* Output parameter list*/
1519 for(int i=0; i<objectparams.numPrimitives(); i++) {
1520 TempDescriptor temp=objectparams.getPrimitive(i);
1522 headersout.print(", ");
1524 if (temp.getType().isClass()||temp.getType().isArray())
1525 headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1527 headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1529 headersout.println(");\n");
1533 /** This function outputs (1) structures that parameters are
1534 * passed in (when PRECISE GC is enabled) and (2) function
1535 * prototypes for the tasks */
1537 private void generateTaskStructs(PrintWriter output, PrintWriter headersout) {
1538 /* Cycle through tasks */
1539 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
1541 while(taskit.hasNext()) {
1542 /* Classify parameters */
1543 TaskDescriptor task=(TaskDescriptor)taskit.next();
1544 FlatMethod fm=state.getMethodFlat(task);
1545 generateTempStructs(fm, null);
1547 ParamsObject objectparams=(ParamsObject) paramstable.get(task);
1548 TempObject objecttemps=(TempObject) tempstable.get(task);
1550 /* Output parameter structure */
1551 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1552 output.println("struct "+task.getSafeSymbol()+"_params {");
1554 output.println(" INTPTR size;");
1555 output.println(" void * next;");
1556 for(int i=0; i<objectparams.numPointers(); i++) {
1557 TempDescriptor temp=objectparams.getPointer(i);
1558 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1561 output.println("};\n");
1562 if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
1563 maxtaskparams=objectparams.numPointers()+fm.numTags();
1567 /* Output temp structure */
1568 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1569 output.println("struct "+task.getSafeSymbol()+"_locals {");
1570 output.println(" INTPTR size;");
1571 output.println(" void * next;");
1572 for(int i=0; i<objecttemps.numPointers(); i++) {
1573 TempDescriptor temp=objecttemps.getPointer(i);
1574 if (temp.getType().isNull())
1575 output.println(" void * "+temp.getSafeSymbol()+";");
1576 else if(temp.getType().isTag())
1577 output.println(" struct "+
1578 (new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1580 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1582 output.println("};\n");
1585 /* Output task declaration */
1586 headersout.print("void " + task.getSafeSymbol()+"(");
1588 boolean printcomma=false;
1589 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1590 headersout.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
1592 headersout.print("void * parameterarray[]");
1593 headersout.println(");\n");
1597 /***** Generate code for FlatMethod fm. *****/
1599 Hashtable<FlatAtomicEnterNode, AtomicRecord> atomicmethodmap;
1600 static int atomicmethodcount=0;
1603 BranchAnalysis branchanalysis;
1604 private void generateFlatMethod(FlatMethod fm, LocalityBinding lb, PrintWriter output) {
1605 if (State.PRINTFLAT)
1606 System.out.println(fm.printMethod());
1607 MethodDescriptor md=fm.getMethod();
1608 TaskDescriptor task=fm.getTask();
1609 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
1610 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : md!=null ? md : task);
1612 HashSet<AtomicRecord> arset=null;
1613 branchanalysis=null;
1615 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1617 if (atomicmethodmap==null)
1618 atomicmethodmap=new Hashtable<FlatAtomicEnterNode, AtomicRecord>();
1620 //fix these so we get right strings for local variables
1621 localsprefixaddr=localsprefix;
1622 localsprefixderef=localsprefix+"->";
1623 arset=new HashSet<AtomicRecord>();
1625 //build branchanalysis
1626 branchanalysis=new BranchAnalysis(locality, lb, delaycomp.getNotReady(lb), delaycomp.livecode(lb), state);
1628 //Generate commit methods here
1629 for(Iterator<FlatNode> fnit=fm.getNodeSet().iterator();fnit.hasNext();) {
1630 FlatNode fn=fnit.next();
1631 if (fn.kind()==FKind.FlatAtomicEnterNode&&
1632 locality.getAtomic(lb).get(fn.getPrev(0)).intValue()==0&&
1633 delaycomp.needsFission(lb, (FlatAtomicEnterNode) fn)) {
1634 //We have an atomic enter
1635 FlatAtomicEnterNode faen=(FlatAtomicEnterNode) fn;
1636 Set<FlatNode> exitset=faen.getExits();
1638 String methodname=md.getSymbol()+(atomicmethodcount++);
1639 AtomicRecord ar=new AtomicRecord();
1643 atomicmethodmap.put(faen, ar);
1645 //build data structure declaration
1646 output.println("struct atomicprimitives_"+methodname+" {");
1648 Set<FlatNode> recordset=delaycomp.livecode(lb);
1649 Set<TempDescriptor> liveinto=delaycomp.liveinto(lb, faen, recordset);
1650 Set<TempDescriptor> liveout=delaycomp.liveout(lb, faen);
1651 Set<TempDescriptor> liveoutvirtualread=delaycomp.liveoutvirtualread(lb, faen);
1653 ar.reallivein=new HashSet(liveinto);
1655 ar.liveoutvirtualread=liveoutvirtualread;
1658 for(Iterator<TempDescriptor> it=liveinto.iterator(); it.hasNext();) {
1659 TempDescriptor tmp=it.next();
1660 //remove the pointers
1661 if (tmp.getType().isPtr()) {
1664 //let's print it here
1665 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1668 for(Iterator<TempDescriptor> it=liveout.iterator(); it.hasNext();) {
1669 TempDescriptor tmp=it.next();
1670 //remove the pointers
1671 if (tmp.getType().isPtr()) {
1673 } else if (!liveinto.contains(tmp)) {
1674 //let's print it here
1675 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1678 output.println("};");
1680 //print out method name
1681 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) {");
1682 //build code for commit method
1684 //first define local primitives
1685 Set<TempDescriptor> alltemps=delaycomp.alltemps(lb, faen, recordset);
1686 for(Iterator<TempDescriptor> tmpit=alltemps.iterator();tmpit.hasNext();) {
1687 TempDescriptor tmp=tmpit.next();
1688 if (!tmp.getType().isPtr()) {
1689 if (liveinto.contains(tmp)||liveoutvirtualread.contains(tmp)) {
1690 //read from live into set
1691 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+"=primitives->"+tmp.getSafeSymbol()+";");
1694 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1698 //turn off write barrier generation
1700 state.SINGLETM=false;
1701 generateCode(faen, fm, lb, exitset, output, false);
1702 state.SINGLETM=true;
1703 //turn on write barrier generation
1705 output.println("}\n\n");
1709 //redefine these back to normal
1711 localsprefixaddr="&"+localsprefix;
1712 localsprefixderef=localsprefix+".";
1714 generateHeader(fm, lb, md!=null ? md : task,output);
1715 TempObject objecttemp=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
1717 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1718 for(Iterator<AtomicRecord> arit=arset.iterator();arit.hasNext();) {
1719 AtomicRecord ar=arit.next();
1720 output.println("struct atomicprimitives_"+ar.name+" primitives_"+ar.name+";");
1724 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1725 if (md!=null&&(state.DSM||state.SINGLETM))
1726 output.print(" struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1727 else if (md!=null&&!(state.DSM||state.SINGLETM))
1728 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1730 output.print(" struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={");
1732 output.print(objecttemp.numPointers()+",");
1733 output.print(paramsprefix);
1734 for(int j=0; j<objecttemp.numPointers(); j++)
1735 output.print(", NULL");
1736 output.println("};");
1739 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1740 TempDescriptor td=objecttemp.getPrimitive(i);
1741 TypeDescriptor type=td.getType();
1743 output.println(" void * "+td.getSafeSymbol()+";");
1744 else if (type.isClass()||type.isArray())
1745 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1747 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1752 if( fm.getNext(0) instanceof FlatSESEEnterNode ) {
1753 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
1754 if( callerSESEplaceholder != mlpa.getMainSESE() ) {
1755 // declare variables for naming static SESE's
1756 output.println(" /* static SESE names */");
1757 Iterator<SESEandAgePair> pItr = callerSESEplaceholder.getNeededStaticNames().iterator();
1758 while( pItr.hasNext() ) {
1759 SESEandAgePair pair = pItr.next();
1760 output.println(" void* "+pair+";");
1763 // declare variables for tracking dynamic sources
1764 output.println(" /* dynamic variable sources */");
1765 Iterator<TempDescriptor> dynSrcItr = callerSESEplaceholder.getDynamicVarSet().iterator();
1766 while( dynSrcItr.hasNext() ) {
1767 TempDescriptor dynSrcVar = dynSrcItr.next();
1768 output.println(" void* "+dynSrcVar+"_srcSESE;");
1769 output.println(" int "+dynSrcVar+"_srcOffset;");
1774 // set up related allocation sites's waiting queues
1776 ConflictGraph graph = null;
1777 graph = mlpa.getConflictGraphResults().get(fm);
1778 if (graph != null) {
1779 output.println(" /* set up waiting queues */");
1780 output.println(" int numMemoryQueue=0;");
1781 output.println(" int memoryQueueItemID=0;");
1782 HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
1784 System.out.println("lockset="+lockSet);
1785 for (Iterator iterator = lockSet.iterator(); iterator.hasNext();) {
1786 SESELock seseLock = (SESELock) iterator.next();
1787 System.out.println("id="+seseLock.getID());
1788 System.out.println("#="+seseLock);
1790 System.out.println("size="+lockSet.size());
1791 if (lockSet.size() > 0) {
1792 output.println(" numMemoryQueue=" + lockSet.size() + ";");
1794 .println(" seseCaller->numMemoryQueue=numMemoryQueue;");
1796 .println(" seseCaller->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
1803 /* Check to see if we need to do a GC if this is a
1804 * multi-threaded program...*/
1806 if (((state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
1807 || this.state.MULTICOREGC) {
1808 //Don't bother if we aren't in recursive methods...The loops case will catch it
1809 if (callgraph.getAllMethods(md).contains(md)) {
1810 if (state.DSM&&lb.isAtomic())
1811 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
1812 else if (this.state.MULTICOREGC) {
1813 output.println("if(gcflag) gc("+localsprefixaddr+");");
1815 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
1820 generateCode(fm.getNext(0), fm, lb, null, output, true);
1822 output.println("}\n\n");
1826 protected void initializeSESE( FlatSESEEnterNode fsen ) {
1828 FlatMethod fm = fsen.getfmEnclosing();
1829 MethodDescriptor md = fm.getMethod();
1830 ClassDescriptor cn = md.getClassDesc();
1833 // Creates bogus method descriptor to index into tables
1834 Modifiers modBogus = new Modifiers();
1835 MethodDescriptor mdBogus =
1836 new MethodDescriptor( modBogus,
1837 new TypeDescriptor( TypeDescriptor.VOID ),
1838 "sese_"+fsen.getPrettyIdentifier()+fsen.getIdentifier()
1841 mdBogus.setClassDesc( fsen.getcdEnclosing() );
1842 FlatMethod fmBogus = new FlatMethod( mdBogus, null );
1843 fsen.setfmBogus( fmBogus );
1844 fsen.setmdBogus( mdBogus );
1846 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1847 inSetAndOutSet.addAll( fsen.getInVarSet() );
1848 inSetAndOutSet.addAll( fsen.getOutVarSet() );
1850 // Build paramsobj for bogus method descriptor
1851 ParamsObject objectparams = new ParamsObject( mdBogus, tag++ );
1852 paramstable.put( mdBogus, objectparams );
1854 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1855 while( itr.hasNext() ) {
1856 TempDescriptor temp = itr.next();
1857 TypeDescriptor type = temp.getType();
1858 if( type.isPtr() ) {
1859 objectparams.addPtr( temp );
1861 objectparams.addPrim( temp );
1865 // Build normal temp object for bogus method descriptor
1866 TempObject objecttemps = new TempObject( objectparams, mdBogus, tag++ );
1867 tempstable.put( mdBogus, objecttemps );
1869 for( Iterator nodeit = fsen.getNodeSet().iterator(); nodeit.hasNext(); ) {
1870 FlatNode fn = (FlatNode)nodeit.next();
1871 TempDescriptor[] writes = fn.writesTemps();
1873 for( int i = 0; i < writes.length; i++ ) {
1874 TempDescriptor temp = writes[i];
1875 TypeDescriptor type = temp.getType();
1877 if( type.isPtr() ) {
1878 objecttemps.addPtr( temp );
1880 objecttemps.addPrim( temp );
1886 protected void generateMethodSESE(FlatSESEEnterNode fsen,
1888 PrintWriter outputStructs,
1889 PrintWriter outputMethHead,
1890 PrintWriter outputMethods
1893 ParamsObject objectparams = (ParamsObject) paramstable.get( fsen.getmdBogus() );
1894 TempObject objecttemps = (TempObject) tempstable .get( fsen.getmdBogus() );
1896 // generate locals structure
1897 outputStructs.println("struct "+
1898 fsen.getcdEnclosing().getSafeSymbol()+
1899 fsen.getmdBogus().getSafeSymbol()+"_"+
1900 fsen.getmdBogus().getSafeMethodDescriptor()+
1902 outputStructs.println(" INTPTR size;");
1903 outputStructs.println(" void * next;");
1904 for(int i=0; i<objecttemps.numPointers(); i++) {
1905 TempDescriptor temp=objecttemps.getPointer(i);
1907 if (temp.getType().isNull())
1908 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
1910 outputStructs.println(" struct "+
1911 temp.getType().getSafeSymbol()+" * "+
1912 temp.getSafeSymbol()+";");
1914 outputStructs.println("};\n");
1917 // generate the SESE record structure
1918 outputStructs.println(fsen.getSESErecordName()+" {");
1920 // data common to any SESE, and it must be placed first so
1921 // a module that doesn't know what kind of SESE record this
1922 // is can cast the pointer to a common struct
1923 outputStructs.println(" SESEcommon common;");
1925 // then garbage list stuff
1926 outputStructs.println(" INTPTR size;");
1927 outputStructs.println(" void * next;");
1929 // in-set source tracking
1930 // in-vars that are READY come from parent, don't need anything
1931 // stuff STATIC needs a custom SESE pointer for each age pair
1932 Iterator<SESEandAgePair> itrStaticInVarSrcs = fsen.getStaticInVarSrcs().iterator();
1933 while( itrStaticInVarSrcs.hasNext() ) {
1934 SESEandAgePair srcPair = itrStaticInVarSrcs.next();
1935 outputStructs.println(" "+srcPair.getSESE().getSESErecordName()+"* "+srcPair+";");
1938 // DYNAMIC stuff needs a source SESE ptr and offset
1939 Iterator<TempDescriptor> itrDynInVars = fsen.getDynamicInVarSet().iterator();
1940 while( itrDynInVars.hasNext() ) {
1941 TempDescriptor dynInVar = itrDynInVars.next();
1942 outputStructs.println(" void* "+dynInVar+"_srcSESE;");
1943 outputStructs.println(" int "+dynInVar+"_srcOffset;");
1946 // space for all in and out set primitives
1947 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1948 inSetAndOutSet.addAll( fsen.getInVarSet() );
1949 inSetAndOutSet.addAll( fsen.getOutVarSet() );
1951 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
1953 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1954 while( itr.hasNext() ) {
1955 TempDescriptor temp = itr.next();
1956 TypeDescriptor type = temp.getType();
1957 if( !type.isPtr() ) {
1958 inSetAndOutSetPrims.add( temp );
1962 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
1963 while( itrPrims.hasNext() ) {
1964 TempDescriptor temp = itrPrims.next();
1965 TypeDescriptor type = temp.getType();
1966 outputStructs.println(" "+temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol()+";");
1969 for(int i=0; i<objectparams.numPointers(); i++) {
1970 TempDescriptor temp=objectparams.getPointer(i);
1971 if (temp.getType().isNull())
1972 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
1974 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1977 outputStructs.println("};\n");
1980 // write method declaration to header file
1981 outputMethHead.print("void ");
1982 outputMethHead.print(fsen.getSESEmethodName()+"(");
1983 outputMethHead.print(fsen.getSESErecordName()+"* "+paramsprefix);
1984 outputMethHead.println(");\n");
1987 generateFlatMethodSESE( fsen.getfmBogus(),
1988 fsen.getcdEnclosing(),
1994 private void generateFlatMethodSESE(FlatMethod fm,
1996 FlatSESEEnterNode fsen,
1997 FlatSESEExitNode seseExit,
2001 MethodDescriptor md=fm.getMethod();
2003 output.print("void ");
2004 output.print(fsen.getSESEmethodName()+"(");
2005 output.print(fsen.getSESErecordName()+"* "+paramsprefix);
2006 output.println("){\n");
2008 TempObject objecttemp=(TempObject) tempstable.get(md);
2010 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2011 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
2012 output.print(objecttemp.numPointers()+",");
2013 output.print("(void*) &("+paramsprefix+"->size)");
2014 for(int j=0; j<objecttemp.numPointers(); j++)
2015 output.print(", NULL");
2016 output.println("};");
2019 output.println(" /* regular local primitives */");
2020 for(int i=0; i<objecttemp.numPrimitives(); i++) {
2021 TempDescriptor td=objecttemp.getPrimitive(i);
2022 TypeDescriptor type=td.getType();
2024 output.println(" void * "+td.getSafeSymbol()+";");
2025 else if (type.isClass()||type.isArray())
2026 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
2028 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
2032 // declare variables for naming static SESE's
2033 output.println(" /* static SESE names */");
2034 Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
2035 while( pItr.hasNext() ) {
2036 SESEandAgePair pair = pItr.next();
2037 output.println(" void* "+pair+";");
2040 // declare variables for tracking dynamic sources
2041 output.println(" /* dynamic variable sources */");
2042 Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
2043 while( dynSrcItr.hasNext() ) {
2044 TempDescriptor dynSrcVar = dynSrcItr.next();
2045 output.println(" void* "+dynSrcVar+"_srcSESE;");
2046 output.println(" int "+dynSrcVar+"_srcOffset;");
2049 // declare local temps for in-set primitives, and if it is
2050 // a ready-source variable, get the value from the record
2051 output.println(" /* local temps for in-set primitives */");
2052 Iterator<TempDescriptor> itrInSet = fsen.getInVarSet().iterator();
2053 while( itrInSet.hasNext() ) {
2054 TempDescriptor temp = itrInSet.next();
2055 TypeDescriptor type = temp.getType();
2056 if( !type.isPtr() ) {
2057 if( fsen.getReadyInVarSet().contains( temp ) ) {
2058 output.println(" "+type+" "+temp+" = "+paramsprefix+"->"+temp+";");
2060 output.println(" "+type+" "+temp+";");
2065 // declare local temps for out-set primitives if its not already
2066 // in the in-set, and it's value will get written so no problem
2067 output.println(" /* local temp for out-set prim, not already in the in-set */");
2068 Iterator<TempDescriptor> itrOutSet = fsen.getOutVarSet().iterator();
2069 while( itrOutSet.hasNext() ) {
2070 TempDescriptor temp = itrOutSet.next();
2071 TypeDescriptor type = temp.getType();
2072 if( !type.isPtr() && !fsen.getInVarSet().contains( temp ) ) {
2073 output.println(" "+type+" "+temp+";");
2077 // setup memory queue
2079 output.println(" // set up memory queues ");
2080 output.println(" int numMemoryQueue=0;");
2081 output.println(" int memoryQueueItemID=0;");
2082 ConflictGraph graph = null;
2083 graph = mlpa.getConflictGraphResults().get(fsen);
2084 if (graph != null) {
2085 output.println(" {");
2087 .println(" SESEcommon* parentCommon = &(___params___->common);");
2088 HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
2091 if (lockSet.size() > 0) {
2092 output.println(" numMemoryQueue=" + lockSet.size() + ";");
2094 .println(" parentCommon->numMemoryQueue=numMemoryQueue;");
2096 .println(" parentCommon->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2099 output.println(" }");
2103 // copy in-set into place, ready vars were already
2104 // copied when the SESE was issued
2105 Iterator<TempDescriptor> tempItr;
2107 // static vars are from a known SESE
2108 tempItr = fsen.getStaticInVarSet().iterator();
2109 while( tempItr.hasNext() ) {
2110 TempDescriptor temp = tempItr.next();
2111 VariableSourceToken vst = fsen.getStaticInVarSrc( temp );
2112 SESEandAgePair srcPair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2114 // can't grab something from this source until it is done
2115 output.println(" {");
2117 If we are running, everything is done. This check is redundant.
2119 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+srcPair+";" );
2120 output.println(" pthread_mutex_lock( &(com->lock) );");
2121 output.println(" while( com->doneExecuting == FALSE ) {");
2122 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
2123 output.println(" }");
2124 output.println(" pthread_mutex_unlock( &(com->lock) );");
2126 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2127 " = "+paramsprefix+"->"+srcPair+"->"+vst.getAddrVar()+";");
2129 output.println(" }");
2132 // dynamic vars come from an SESE and src
2133 tempItr = fsen.getDynamicInVarSet().iterator();
2134 while( tempItr.hasNext() ) {
2135 TempDescriptor temp = tempItr.next();
2136 TypeDescriptor type = temp.getType();
2138 // go grab it from the SESE source
2139 output.println(" if( "+paramsprefix+"->"+temp+"_srcSESE != NULL ) {");
2141 // gotta wait until the source is done
2142 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+temp+"_srcSESE;" );
2144 If we are running, everything is done!
2145 output.println(" pthread_mutex_lock( &(com->lock) );");
2146 output.println(" while( com->doneExecuting == FALSE ) {");
2147 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
2148 output.println(" }");
2149 output.println(" pthread_mutex_unlock( &(com->lock) );");
2153 if( type.isNull() ) {
2155 } else if( type.isClass() || type.isArray() ) {
2156 typeStr = "struct "+type.getSafeSymbol()+"*";
2158 typeStr = type.getSafeSymbol();
2161 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2162 " = *(("+typeStr+"*) ("+
2163 paramsprefix+"->"+temp+"_srcSESE + "+
2164 paramsprefix+"->"+temp+"_srcOffset));");
2166 // or if the source was our parent, its in the record to grab
2167 output.println(" } else {");
2168 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2169 " = "+paramsprefix+"->"+temp+";");
2170 output.println(" }");
2173 // Check to see if we need to do a GC if this is a
2174 // multi-threaded program...
2175 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2176 //Don't bother if we aren't in recursive methods...The loops case will catch it
2177 if (callgraph.getAllMethods(md).contains(md)) {
2178 if(this.state.MULTICOREGC) {
2179 output.println("if(gcflag) gc("+localsprefixaddr+");");
2181 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2186 // initialize thread-local var to a non-zero, invalid address
2187 output.println(" seseCaller = (SESEcommon*) 0x2;");
2188 HashSet<FlatNode> exitset=new HashSet<FlatNode>();
2189 exitset.add(seseExit);
2190 generateCode(fsen.getNext(0), fm, null, exitset, output, true);
2191 output.println("}\n\n");
2196 // when a new mlp thread is created for an issued SESE, it is started
2197 // by running this method which blocks on a cond variable until
2198 // it is allowed to transition to execute. Then a case statement
2199 // allows it to invoke the method with the proper SESE body, and after
2200 // exiting the SESE method, executes proper SESE exit code before the
2201 // thread can be destroyed
2202 private void generateSESEinvocationMethod(PrintWriter outmethodheader,
2203 PrintWriter outmethod
2206 outmethodheader.println("void* invokeSESEmethod( void* seseRecord );");
2207 outmethod.println( "void* invokeSESEmethod( void* seseRecord ) {");
2208 outmethod.println( " int status;");
2209 outmethod.println( " char errmsg[128];");
2211 // generate a case for each SESE class that can be invoked
2212 outmethod.println( " switch( *((int*)seseRecord) ) {");
2213 outmethod.println( " ");
2214 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
2215 FlatSESEEnterNode fsen = seseit.next();
2217 outmethod.println( " /* "+fsen.getPrettyIdentifier()+" */");
2218 outmethod.println( " case "+fsen.getIdentifier()+":");
2219 outmethod.println( " "+fsen.getSESEmethodName()+"( seseRecord );");
2221 if( fsen.equals( mlpa.getMainSESE() ) ) {
2222 outmethod.println( " /* work scheduler works forever, explicitly exit */");
2223 outmethod.println( " exit( 0 );");
2226 outmethod.println( " break;");
2227 outmethod.println( "");
2230 // default case should never be taken, error out
2231 outmethod.println( " default:");
2232 outmethod.println( " printf(\"Error: unknown SESE class ID in invoke method.\\n\");");
2233 outmethod.println( " exit(-30);");
2234 outmethod.println( " break;");
2235 outmethod.println( " }");
2236 outmethod.println( " return NULL;");
2237 outmethod.println( "}\n\n");
2241 protected void generateCode(FlatNode first,
2244 Set<FlatNode> stopset,
2245 PrintWriter output, boolean firstpass) {
2247 /* Assign labels to FlatNode's if necessary.*/
2249 Hashtable<FlatNode, Integer> nodetolabel;
2251 if (state.DELAYCOMP&&!firstpass)
2252 nodetolabel=dcassignLabels(first, stopset);
2254 nodetolabel=assignLabels(first, stopset);
2256 Set<FlatNode> storeset=null;
2257 HashSet<FlatNode> genset=null;
2258 HashSet<FlatNode> refset=null;
2259 Set<FlatNode> unionset=null;
2261 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
2262 storeset=delaycomp.livecode(lb);
2263 genset=new HashSet<FlatNode>();
2264 if (state.STMARRAY&&!state.DUALVIEW) {
2265 refset=new HashSet<FlatNode>();
2266 refset.addAll(delaycomp.getDeref(lb));
2267 refset.removeAll(delaycomp.getCannotDelay(lb));
2268 refset.removeAll(delaycomp.getOther(lb));
2271 genset.addAll(delaycomp.getCannotDelay(lb));
2272 genset.addAll(delaycomp.getOther(lb));
2274 genset.addAll(delaycomp.getNotReady(lb));
2275 if (state.STMARRAY&&!state.DUALVIEW) {
2276 genset.removeAll(refset);
2279 unionset=new HashSet<FlatNode>();
2280 unionset.addAll(storeset);
2281 unionset.addAll(genset);
2282 if (state.STMARRAY&&!state.DUALVIEW)
2283 unionset.addAll(refset);
2286 /* Do the actual code generation */
2287 FlatNode current_node=null;
2288 HashSet tovisit=new HashSet();
2289 HashSet visited=new HashSet();
2291 tovisit.add(first.getNext(0));
2294 while(current_node!=null||!tovisit.isEmpty()) {
2295 if (current_node==null) {
2296 current_node=(FlatNode)tovisit.iterator().next();
2297 tovisit.remove(current_node);
2298 } else if (tovisit.contains(current_node)) {
2299 tovisit.remove(current_node);
2301 visited.add(current_node);
2302 if (nodetolabel.containsKey(current_node)) {
2303 output.println("L"+nodetolabel.get(current_node)+":");
2305 if (state.INSTRUCTIONFAILURE) {
2306 if (state.THREAD||state.DSM||state.SINGLETM) {
2307 output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
2309 output.println("if ((--instructioncount)==0) injectinstructionfailure();");
2311 if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
2313 if (!state.DELAYCOMP||firstpass) {
2314 generateFlatNode(fm, lb, current_node, output);
2316 //store primitive variables in out set
2317 AtomicRecord ar=atomicmethodmap.get((FlatAtomicEnterNode)first);
2318 Set<TempDescriptor> liveout=ar.liveout;
2319 for(Iterator<TempDescriptor> tmpit=liveout.iterator();tmpit.hasNext();) {
2320 TempDescriptor tmp=tmpit.next();
2321 output.println("primitives->"+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2324 if (state.MLP && stopset!=null) {
2325 assert first.getPrev( 0 ) instanceof FlatSESEEnterNode;
2326 assert current_node instanceof FlatSESEExitNode;
2327 FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev( 0 );
2328 FlatSESEExitNode fsxn = (FlatSESEExitNode) current_node;
2329 assert fsen.getFlatExit().equals( fsxn );
2330 assert fsxn.getFlatEnter().equals( fsen );
2332 if (current_node.kind()!=FKind.FlatReturnNode) {
2333 output.println(" return;");
2336 } else if(current_node.numNext()==1) {
2339 current_node.kind()==FKind.FlatSESEEnterNode &&
2340 !((FlatSESEEnterNode)current_node).getIsCallerSESEplaceholder()
2342 FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
2343 generateFlatNode(fm, lb, current_node, output);
2344 nextnode=fsen.getFlatExit().getNext(0);
2345 } else if (state.DELAYCOMP) {
2346 boolean specialprimitive=false;
2347 //skip literals...no need to add extra overhead
2348 if (storeset!=null&&storeset.contains(current_node)&¤t_node.kind()==FKind.FlatLiteralNode) {
2349 TypeDescriptor typedesc=((FlatLiteralNode)current_node).getType();
2350 if (!typedesc.isClass()&&!typedesc.isArray()) {
2351 specialprimitive=true;
2355 if (genset==null||genset.contains(current_node)||specialprimitive)
2356 generateFlatNode(fm, lb, current_node, output);
2357 if (state.STMARRAY&&!state.DUALVIEW&&refset!=null&&refset.contains(current_node)) {
2358 //need to acquire lock
2359 handleArrayDeref(fm, lb, current_node, output, firstpass);
2361 if (storeset!=null&&storeset.contains(current_node)&&!specialprimitive) {
2362 TempDescriptor wrtmp=current_node.writesTemps()[0];
2364 //need to store value written by previous node
2365 if (wrtmp.getType().isPtr()) {
2366 //only lock the objects that may actually need locking
2367 if (recorddc.getNeedTrans(lb, current_node)&&
2368 (!state.STMARRAY||state.DUALVIEW||!wrtmp.getType().isArray()||
2369 wrtmp.getType().getSymbol().equals(TypeUtil.ObjectClass))) {
2370 output.println("STOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2372 output.println("STOREPTRNOLOCK("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2375 output.println("STORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");/* "+current_node.nodeid+" */");
2378 //need to read value read by previous node
2379 if (wrtmp.getType().isPtr()) {
2380 output.println("RESTOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2382 output.println("RESTORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+"); /* "+current_node.nodeid+" */");
2386 nextnode=current_node.getNext(0);
2389 generateFlatNode(fm, lb, current_node, output);
2390 nextnode=current_node.getNext(0);
2392 if (visited.contains(nextnode)) {
2393 output.println("goto L"+nodetolabel.get(nextnode)+";");
2396 current_node=nextnode;
2397 } else if (current_node.numNext()==2) {
2399 if (state.DELAYCOMP) {
2400 boolean computeside=false;
2402 //need to record which way it should go
2403 if (genset==null||genset.contains(current_node)) {
2404 if (storeset!=null&&storeset.contains(current_node)) {
2405 //need to store which way branch goes
2406 generateStoreFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2408 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2410 //which side to execute
2414 if (genset.contains(current_node)) {
2415 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2416 } else if (storeset.contains(current_node)) {
2418 branchanalysis.generateGroupCode(current_node, output, nodetolabel);
2420 //which side to execute
2425 Set<FlatNode> leftset=DelayComputation.getNext(current_node, 0, unionset, lb,locality, true);
2427 if (leftset.size()==0)
2429 if (visited.contains(current_node.getNext(branch))) {
2430 //already visited -- build jump
2431 output.println("goto L"+nodetolabel.get(current_node.getNext(branch))+";");
2434 current_node=current_node.getNext(branch);
2437 if (!visited.contains(current_node.getNext(1)))
2438 tovisit.add(current_node.getNext(1));
2439 if (visited.contains(current_node.getNext(0))) {
2440 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2443 current_node=current_node.getNext(0);
2447 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2448 if (!visited.contains(current_node.getNext(1)))
2449 tovisit.add(current_node.getNext(1));
2450 if (visited.contains(current_node.getNext(0))) {
2451 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2454 current_node=current_node.getNext(0);
2456 } else throw new Error();
2460 protected void handleArrayDeref(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output, boolean firstpass) {
2461 if (fn.kind()==FKind.FlatSetElementNode) {
2462 FlatSetElementNode fsen=(FlatSetElementNode) fn;
2463 String dst=generateTemp(fm, fsen.getDst(), lb);
2464 String src=generateTemp(fm, fsen.getSrc(), lb);
2465 String index=generateTemp(fm, fsen.getIndex(), lb);
2466 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
2468 if (elementtype.isArray()||elementtype.isClass())
2471 type=elementtype.getSafeSymbol()+" ";
2473 output.println("STOREARRAY("+dst+","+index+","+type+")");
2475 output.println("{");
2476 output.println(" struct ArrayObject *array;");
2477 output.println(" int index;");
2478 output.println(" RESTOREARRAY(array,index);");
2479 output.println(" (("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index]="+src+";");
2480 output.println("}");
2482 } else if (fn.kind()==FKind.FlatElementNode) {
2483 FlatElementNode fen=(FlatElementNode) fn;
2484 String src=generateTemp(fm, fen.getSrc(), lb);
2485 String index=generateTemp(fm, fen.getIndex(), lb);
2486 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
2487 String dst=generateTemp(fm, fen.getDst(), lb);
2489 if (elementtype.isArray()||elementtype.isClass())
2492 type=elementtype.getSafeSymbol()+" ";
2494 output.println("STOREARRAY("+src+","+index+","+type+")");
2496 output.println("{");
2497 output.println(" struct ArrayObject *array;");
2498 output.println(" int index;");
2499 output.println(" RESTOREARRAY(array,index);");
2500 output.println(" "+dst+"=(("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index];");
2501 output.println("}");
2505 /** Special label assignment for delaycomputation */
2506 protected Hashtable<FlatNode, Integer> dcassignLabels(FlatNode first, Set<FlatNode> lastset) {
2507 HashSet tovisit=new HashSet();
2508 HashSet visited=new HashSet();
2510 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2512 //Label targets of branches
2513 Set<FlatNode> targets=branchanalysis.getTargets();
2514 for(Iterator<FlatNode> it=targets.iterator();it.hasNext();) {
2515 nodetolabel.put(it.next(), new Integer(labelindex++));
2520 /*Assign labels first. A node needs a label if the previous
2521 * node has two exits or this node is a join point. */
2523 while(!tovisit.isEmpty()) {
2524 FlatNode fn=(FlatNode)tovisit.iterator().next();
2529 if(lastset!=null&&lastset.contains(fn)) {
2530 // if last is not null and matches, don't go
2531 // any further for assigning labels
2535 for(int i=0; i<fn.numNext(); i++) {
2536 FlatNode nn=fn.getNext(i);
2539 //1) Edge >1 of node
2540 nodetolabel.put(nn,new Integer(labelindex++));
2542 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2546 nodetolabel.put(nn,new Integer(labelindex++));
2554 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first) {
2555 return assignLabels(first, null);
2558 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
2559 HashSet tovisit=new HashSet();
2560 HashSet visited=new HashSet();
2562 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2565 /*Assign labels first. A node needs a label if the previous
2566 * node has two exits or this node is a join point. */
2568 while(!tovisit.isEmpty()) {
2569 FlatNode fn=(FlatNode)tovisit.iterator().next();
2574 if(lastset!=null&&lastset.contains(fn)) {
2575 // if last is not null and matches, don't go
2576 // any further for assigning labels
2580 for(int i=0; i<fn.numNext(); i++) {
2581 FlatNode nn=fn.getNext(i);
2584 //1) Edge >1 of node
2585 nodetolabel.put(nn,new Integer(labelindex++));
2587 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2591 nodetolabel.put(nn,new Integer(labelindex++));
2599 /** Generate text string that corresponds to the TempDescriptor td. */
2600 protected String generateTemp(FlatMethod fm, TempDescriptor td, LocalityBinding lb) {
2601 MethodDescriptor md=fm.getMethod();
2602 TaskDescriptor task=fm.getTask();
2603 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
2605 if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
2606 return td.getSafeSymbol();
2609 if (objecttemps.isLocalPtr(td)) {
2610 return localsprefixderef+td.getSafeSymbol();
2613 if (objecttemps.isParamPtr(td)) {
2614 return paramsprefix+"->"+td.getSafeSymbol();
2620 protected void generateFlatNode(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output) {
2622 // insert pre-node actions from the code plan
2625 CodePlan cp = mlpa.getCodePlan( fn );
2628 FlatSESEEnterNode currentSESE = cp.getCurrentSESE();
2630 // for each sese and age pair that this parent statement
2631 // must stall on, take that child's stall semaphore, the
2632 // copying of values comes after the statement
2633 Iterator<VariableSourceToken> vstItr = cp.getStallTokens().iterator();
2634 while( vstItr.hasNext() ) {
2635 VariableSourceToken vst = vstItr.next();
2637 SESEandAgePair pair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2639 output.println(" {");
2640 output.println(" SESEcommon* common = (SESEcommon*) "+pair+";");
2642 output.println(" pthread_mutex_lock( &(common->lock) );");
2643 output.println(" while( common->doneExecuting == FALSE ) {");
2644 output.println(" pthread_cond_wait( &(common->doneCond), &(common->lock) );");
2645 output.println(" }");
2646 output.println(" pthread_mutex_unlock( &(common->lock) );");
2648 // copy things we might have stalled for
2649 output.println(" "+pair.getSESE().getSESErecordName()+"* child = ("+
2650 pair.getSESE().getSESErecordName()+"*) "+pair+";");
2652 Iterator<TempDescriptor> tdItr = cp.getCopySet( vst ).iterator();
2653 while( tdItr.hasNext() ) {
2654 TempDescriptor td = tdItr.next();
2655 FlatMethod fmContext;
2656 if( currentSESE.getIsCallerSESEplaceholder() ) {
2657 fmContext = currentSESE.getfmEnclosing();
2659 fmContext = currentSESE.getfmBogus();
2661 output.println(" "+generateTemp( fmContext, td, null )+
2662 " = child->"+vst.getAddrVar().getSafeSymbol()+";");
2665 output.println(" }");
2668 // for each variable with a dynamic source, stall just for that variable
2669 Iterator<TempDescriptor> dynItr = cp.getDynamicStallSet().iterator();
2670 while( dynItr.hasNext() ) {
2671 TempDescriptor dynVar = dynItr.next();
2673 // only stall if the dynamic source is not yourself, denoted by src==NULL
2674 // otherwise the dynamic write nodes will have the local var up-to-date
2675 output.println(" {");
2676 output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
2677 output.println(" SESEcommon* common = (SESEcommon*) "+dynVar+"_srcSESE;");
2678 output.println(" psem_take( &(common->stallSem) );");
2680 FlatMethod fmContext;
2681 if( currentSESE.getIsCallerSESEplaceholder() ) {
2682 fmContext = currentSESE.getfmEnclosing();
2684 fmContext = currentSESE.getfmBogus();
2686 output.println(" "+generateTemp( fmContext, dynVar, null )+
2687 " = *(("+dynVar.getType()+"*) ("+
2688 dynVar+"_srcSESE + "+dynVar+"_srcOffset));");
2690 output.println(" }");
2691 output.println(" }");
2694 // for each assignment of a variable to rhs that has a dynamic source,
2695 // copy the dynamic sources
2696 Iterator dynAssignItr = cp.getDynAssigns().entrySet().iterator();
2697 while( dynAssignItr.hasNext() ) {
2698 Map.Entry me = (Map.Entry) dynAssignItr.next();
2699 TempDescriptor lhs = (TempDescriptor) me.getKey();
2700 TempDescriptor rhs = (TempDescriptor) me.getValue();
2701 output.println(" "+lhs+"_srcSESE = "+rhs+"_srcSESE;");
2702 output.println(" "+lhs+"_srcOffset = "+rhs+"_srcOffset;");
2705 // for each lhs that is dynamic from a non-dynamic source, set the
2706 // dynamic source vars to the current SESE
2707 dynItr = cp.getDynAssignCurr().iterator();
2708 while( dynItr.hasNext() ) {
2709 TempDescriptor dynVar = dynItr.next();
2710 assert currentSESE.getDynamicVarSet().contains( dynVar );
2711 output.println(" "+dynVar+"_srcSESE = NULL;");
2715 // handling stall site
2716 ParentChildConflictsMap conflictsMap = mlpa.getConflictsResults().get(fn);
2717 if (conflictsMap != null) {
2718 Set<Long> allocSet = conflictsMap.getAllocationSiteIDSetofStallSite();
2719 if (allocSet.size() > 0) {
2720 FlatNode enclosingFlatNode=null;
2721 if( currentSESE.getIsCallerSESEplaceholder() && currentSESE.getParent()==null){
2722 enclosingFlatNode=currentSESE.getfmEnclosing();
2724 enclosingFlatNode=currentSESE;
2726 ConflictGraph graph=mlpa.getConflictGraphResults().get(enclosingFlatNode);
2727 HashSet<SESELock> seseLockSet=mlpa.getConflictGraphLockMap().get(graph);
2728 Set<WaitingElement> waitingElementSet=graph.getStallSiteWaitingElementSet(conflictsMap, seseLockSet);
2730 if(waitingElementSet.size()>0){
2731 output.println("// stall on parent's stall sites ");
2732 output.println(" {");
2733 output.println(" REntry* rentry;");
2735 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
2736 WaitingElement waitingElement = (WaitingElement) iterator.next();
2738 if( waitingElement.getStatus() >= ConflictNode.COARSE ){
2739 output.println(" rentry=mlpCreateREntry("+ waitingElement.getStatus()+ ", seseCaller);");
2741 output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", seseCaller, ___locals___."+ waitingElement.getDynID() + ");");
2743 output.println(" psem_init( &(rentry->parentStallSem) );");
2744 output.println(" rentry->queue=seseCaller->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
2746 .println(" if(ADDRENTRY(seseCaller->memoryQueueArray["+ waitingElement.getQueueID()
2747 + "],rentry)==NOTREADY){");
2748 output.println(" psem_take( &(rentry->parentStallSem) );");
2749 output.println(" } ");
2751 output.println(" }");
2760 case FKind.FlatAtomicEnterNode:
2761 generateFlatAtomicEnterNode(fm, lb, (FlatAtomicEnterNode) fn, output);
2764 case FKind.FlatAtomicExitNode:
2765 generateFlatAtomicExitNode(fm, lb, (FlatAtomicExitNode) fn, output);
2768 case FKind.FlatInstanceOfNode:
2769 generateFlatInstanceOfNode(fm, lb, (FlatInstanceOfNode)fn, output);
2772 case FKind.FlatSESEEnterNode:
2773 generateFlatSESEEnterNode(fm, lb, (FlatSESEEnterNode)fn, output);
2776 case FKind.FlatSESEExitNode:
2777 generateFlatSESEExitNode(fm, lb, (FlatSESEExitNode)fn, output);
2780 case FKind.FlatWriteDynamicVarNode:
2781 generateFlatWriteDynamicVarNode(fm, lb, (FlatWriteDynamicVarNode)fn, output);
2784 case FKind.FlatGlobalConvNode:
2785 generateFlatGlobalConvNode(fm, lb, (FlatGlobalConvNode) fn, output);
2788 case FKind.FlatTagDeclaration:
2789 generateFlatTagDeclaration(fm, lb, (FlatTagDeclaration) fn,output);
2792 case FKind.FlatCall:
2793 generateFlatCall(fm, lb, (FlatCall) fn,output);
2796 case FKind.FlatFieldNode:
2797 generateFlatFieldNode(fm, lb, (FlatFieldNode) fn,output);
2800 case FKind.FlatElementNode:
2801 generateFlatElementNode(fm, lb, (FlatElementNode) fn,output);
2804 case FKind.FlatSetElementNode:
2805 generateFlatSetElementNode(fm, lb, (FlatSetElementNode) fn,output);
2808 case FKind.FlatSetFieldNode:
2809 generateFlatSetFieldNode(fm, lb, (FlatSetFieldNode) fn,output);
2813 generateFlatNew(fm, lb, (FlatNew) fn,output);
2816 case FKind.FlatOpNode:
2817 generateFlatOpNode(fm, lb, (FlatOpNode) fn,output);
2820 case FKind.FlatCastNode:
2821 generateFlatCastNode(fm, lb, (FlatCastNode) fn,output);
2824 case FKind.FlatLiteralNode:
2825 generateFlatLiteralNode(fm, lb, (FlatLiteralNode) fn,output);
2828 case FKind.FlatReturnNode:
2829 generateFlatReturnNode(fm, lb, (FlatReturnNode) fn,output);
2833 output.println("/* nop */");
2836 case FKind.FlatExit:
2837 output.println("/* exit */");
2840 case FKind.FlatBackEdge:
2841 if (state.SINGLETM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
2842 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
2844 if(state.DSM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
2845 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
2847 if (((state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
2848 || (this.state.MULTICOREGC)) {
2849 if(state.DSM&&locality.getAtomic(lb).get(fn).intValue()>0) {
2850 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
2851 } else if(this.state.MULTICOREGC) {
2852 output.println("if (gcflag) gc("+localsprefixaddr+");");
2854 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2857 output.println("/* nop */");
2860 case FKind.FlatCheckNode:
2861 generateFlatCheckNode(fm, lb, (FlatCheckNode) fn, output);
2864 case FKind.FlatFlagActionNode:
2865 generateFlatFlagActionNode(fm, lb, (FlatFlagActionNode) fn, output);
2868 case FKind.FlatPrefetchNode:
2869 generateFlatPrefetchNode(fm,lb, (FlatPrefetchNode) fn, output);
2872 case FKind.FlatOffsetNode:
2873 generateFlatOffsetNode(fm, lb, (FlatOffsetNode)fn, output);
2880 // insert post-node actions from the code-plan
2882 CodePlan cp = mlpa.getCodePlan( fn );
2889 public void generateFlatOffsetNode(FlatMethod fm, LocalityBinding lb, FlatOffsetNode fofn, PrintWriter output) {
2890 output.println("/* FlatOffsetNode */");
2891 FieldDescriptor fd=fofn.getField();
2892 output.println(generateTemp(fm, fofn.getDst(),lb)+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+ fd.getSafeSymbol()+");");
2893 output.println("/* offset */");
2896 public void generateFlatPrefetchNode(FlatMethod fm, LocalityBinding lb, FlatPrefetchNode fpn, PrintWriter output) {
2897 if (state.PREFETCH) {
2898 Vector oids = new Vector();
2899 Vector fieldoffset = new Vector();
2900 Vector endoffset = new Vector();
2901 int tuplecount = 0; //Keeps track of number of prefetch tuples that need to be generated
2902 for(Iterator it = fpn.hspp.iterator(); it.hasNext();) {
2903 PrefetchPair pp = (PrefetchPair) it.next();
2904 Integer statusbase = locality.getNodePreTempInfo(lb,fpn).get(pp.base);
2905 /* Find prefetches that can generate oid */
2906 if(statusbase == LocalityAnalysis.GLOBAL) {
2907 generateTransCode(fm, lb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(lb).get(fpn).intValue()>0, false);
2909 } else if (statusbase == LocalityAnalysis.LOCAL) {
2910 generateTransCode(fm,lb,pp,oids,fieldoffset,endoffset,tuplecount,false,true);
2917 System.out.println("Adding prefetch "+fpn+ " to method:" +fm);
2918 output.println("{");
2919 output.println("/* prefetch */");
2920 output.println("/* prefetchid_" + fpn.siteid + " */");
2921 output.println("void * prefptr;");
2922 output.println("int tmpindex;");
2924 output.println("if((evalPrefetch["+fpn.siteid+"].operMode) || (evalPrefetch["+fpn.siteid+"].retrycount <= 0)) {");
2925 /*Create C code for oid array */
2926 output.print(" unsigned int oidarray_[] = {");
2927 boolean needcomma=false;
2928 for (Iterator it = oids.iterator(); it.hasNext();) {
2931 output.print(it.next());
2934 output.println("};");
2936 /*Create C code for endoffset values */
2937 output.print(" unsigned short endoffsetarry_[] = {");
2939 for (Iterator it = endoffset.iterator(); it.hasNext();) {
2942 output.print(it.next());
2945 output.println("};");
2947 /*Create C code for Field Offset Values */
2948 output.print(" short fieldarry_[] = {");
2950 for (Iterator it = fieldoffset.iterator(); it.hasNext();) {
2953 output.print(it.next());
2956 output.println("};");
2957 /* make the prefetch call to Runtime */
2958 output.println(" if(!evalPrefetch["+fpn.siteid+"].operMode) {");
2959 output.println(" evalPrefetch["+fpn.siteid+"].retrycount = RETRYINTERVAL;");
2960 output.println(" }");
2961 output.println(" prefetch("+fpn.siteid+" ,"+tuplecount+", oidarray_, endoffsetarry_, fieldarry_);");
2962 output.println(" } else {");
2963 output.println(" evalPrefetch["+fpn.siteid+"].retrycount--;");
2964 output.println(" }");
2965 output.println("}");
2969 public void generateTransCode(FlatMethod fm, LocalityBinding lb,PrefetchPair pp, Vector oids, Vector fieldoffset, Vector endoffset, int tuplecount, boolean inside, boolean localbase) {
2970 short offsetcount = 0;
2974 } else if (localbase) {
2975 for(; breakindex<pp.desc.size(); breakindex++) {
2976 Descriptor desc=pp.getDescAt(breakindex);
2977 if (desc instanceof FieldDescriptor) {
2978 FieldDescriptor fd=(FieldDescriptor)desc;
2979 if (fd.isGlobal()) {
2987 if (breakindex>pp.desc.size()) //all local
2990 TypeDescriptor lasttype=pp.base.getType();
2991 String basestr=generateTemp(fm, pp.base, lb);
2993 boolean maybenull=fm.getMethod().isStatic()||
2994 !pp.base.equals(fm.getParameter(0));
2996 for(int i=0; i<breakindex; i++) {
2997 String indexcheck="";
2999 Descriptor desc=pp.getDescAt(i);
3000 if (desc instanceof FieldDescriptor) {
3001 FieldDescriptor fd=(FieldDescriptor)desc;
3003 if (!teststr.equals(""))
3005 teststr+="((prefptr="+basestr+")!=NULL)";
3006 basestr="((struct "+lasttype.getSafeSymbol()+" *)prefptr)->"+fd.getSafeSymbol();
3008 basestr=basestr+"->"+fd.getSafeSymbol();
3011 lasttype=fd.getType();
3013 IndexDescriptor id=(IndexDescriptor)desc;
3014 indexcheck="((tmpindex=";
3015 for(int j=0; j<id.tddesc.size(); j++) {
3016 indexcheck+=generateTemp(fm, id.getTempDescAt(j), lb)+"+";
3018 indexcheck+=id.offset+")>=0)&(tmpindex<((struct ArrayObject *)prefptr)->___length___)";
3020 if (!teststr.equals(""))
3022 teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck;
3023 basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]";
3025 lasttype=lasttype.dereference();
3030 if (teststr.equals("")) {
3031 oid="((unsigned int)"+basestr+")";
3033 oid="((unsigned int)(("+teststr+")?"+basestr+":NULL))";
3037 for(int i = breakindex; i < pp.desc.size(); i++) {
3038 String newfieldoffset;
3039 Object desc = pp.getDescAt(i);
3040 if(desc instanceof FieldDescriptor) {
3041 FieldDescriptor fd=(FieldDescriptor)desc;
3042 newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))");
3043 lasttype=fd.getType();
3045 newfieldoffset = "";
3046 IndexDescriptor id=(IndexDescriptor)desc;
3047 for(int j = 0; j < id.tddesc.size(); j++) {
3048 newfieldoffset += generateTemp(fm, id.getTempDescAt(j), lb) + "+";
3050 newfieldoffset += id.offset.toString();
3051 lasttype=lasttype.dereference();
3053 fieldoffset.add(newfieldoffset);
3056 int base=(tuplecount>0) ? ((Short)endoffset.get(tuplecount-1)).intValue() : 0;
3057 base+=pp.desc.size()-breakindex;
3058 endoffset.add(new Short((short)base));
3063 public void generateFlatGlobalConvNode(FlatMethod fm, LocalityBinding lb, FlatGlobalConvNode fgcn, PrintWriter output) {
3064 if (lb!=fgcn.getLocality())
3066 /* Have to generate flat globalconv */
3067 if (fgcn.getMakePtr()) {
3069 //DEBUG: output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+",\" "+fm+":"+fgcn+"\");");
3070 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3072 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fgcn)||state.READSET&&dc.getNeedWriteTrans(lb, fgcn)) {
3073 //need to do translation
3074 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+", (void *)("+localsprefixaddr+"));");
3075 } else if (state.READSET&&dc.getNeedTrans(lb, fgcn)) {
3076 if (state.HYBRID&&delaycomp.getConv(lb).contains(fgcn)) {
3077 output.println("TRANSREADRDFISSION("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3079 output.println("TRANSREADRD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3083 /* Need to convert to OID */
3084 if ((dc==null)||dc.getNeedSrcTrans(lb,fgcn)) {
3085 if (fgcn.doConvert()||(delaycomp!=null&&delaycomp.needsFission(lb, fgcn.getAtomicEnter())&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) {
3086 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc(),lb)+");");
3088 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=NULL;");
3094 public void generateFlatInstanceOfNode(FlatMethod fm, LocalityBinding lb, FlatInstanceOfNode fion, PrintWriter output) {
3096 if (fion.getType().isArray()) {
3097 type=state.getArrayNumber(fion.getType())+state.numClasses();
3099 type=fion.getType().getClassDesc().getId();
3102 if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
3103 output.println(generateTemp(fm, fion.getDst(), lb)+"=1;");
3105 output.println(generateTemp(fm, fion.getDst(), lb)+"=instanceof("+generateTemp(fm,fion.getSrc(),lb)+","+type+");");
3108 int sandboxcounter=0;
3109 public void generateFlatAtomicEnterNode(FlatMethod fm, LocalityBinding lb, FlatAtomicEnterNode faen, PrintWriter output) {
3110 /* Check to see if we need to generate code for this atomic */
3111 if (locality==null) {
3112 if (GENERATEPRECISEGC) {
3113 output.println("if (pthread_mutex_trylock(&atomiclock)!=0) {");
3114 output.println("stopforgc((struct garbagelist *) &___locals___);");
3115 output.println("pthread_mutex_lock(&atomiclock);");
3116 output.println("restartaftergc();");
3117 output.println("}");
3119 output.println("pthread_mutex_lock(&atomiclock);");
3124 if (locality.getAtomic(lb).get(faen.getPrev(0)).intValue()>0)
3128 if (state.SANDBOX) {
3129 outsandbox.println("int atomiccounter"+sandboxcounter+"=LOW_CHECK_FREQUENCY;");
3130 output.println("counter_reset_pointer=&atomiccounter"+sandboxcounter+";");
3133 if (state.DELAYCOMP&&delaycomp.needsFission(lb, faen)) {
3134 AtomicRecord ar=atomicmethodmap.get(faen);
3136 for(Iterator<TempDescriptor> tmpit=ar.livein.iterator();tmpit.hasNext();) {
3137 TempDescriptor tmp=tmpit.next();
3138 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3141 //copy outs that depend on path
3142 for(Iterator<TempDescriptor> tmpit=ar.liveoutvirtualread.iterator();tmpit.hasNext();) {
3143 TempDescriptor tmp=tmpit.next();
3144 if (!ar.livein.contains(tmp))
3145 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3149 /* Backup the temps. */
3150 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3151 TempDescriptor tmp=tmpit.next();
3152 output.println(generateTemp(fm, backuptable.get(lb).get(tmp),lb)+"="+generateTemp(fm,tmp,lb)+";");
3155 output.println("goto transstart"+faen.getIdentifier()+";");
3157 /******* Print code to retry aborted transaction *******/
3158 output.println("transretry"+faen.getIdentifier()+":");
3161 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3162 TempDescriptor tmp=tmpit.next();
3163 output.println(generateTemp(fm, tmp,lb)+"="+generateTemp(fm,backuptable.get(lb).get(tmp),lb)+";");
3167 /********* Need to revert local object store ********/
3168 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3170 output.println("while ("+revertptr+") {");
3171 output.println("struct ___Object___ * tmpptr;");
3172 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3173 output.println("REVERT_OBJ("+revertptr+");");
3174 output.println(revertptr+"=tmpptr;");
3175 output.println("}");
3177 /******* Tell the runtime to start the transaction *******/
3179 output.println("transstart"+faen.getIdentifier()+":");
3180 if (state.SANDBOX) {
3181 output.println("transaction_check_counter=*counter_reset_pointer;");
3184 output.println("transStart();");
3186 if (state.ABORTREADERS||state.SANDBOX) {
3188 output.println("abortenabled=1;");
3189 output.println("if (_setjmp(aborttrans)) {");
3190 output.println(" goto transretry"+faen.getIdentifier()+"; }");
3194 public void generateFlatAtomicExitNode(FlatMethod fm, LocalityBinding lb, FlatAtomicExitNode faen, PrintWriter output) {
3195 /* Check to see if we need to generate code for this atomic */
3196 if (locality==null) {
3197 output.println("pthread_mutex_unlock(&atomiclock);");
3200 if (locality.getAtomic(lb).get(faen).intValue()>0)
3202 //store the revert list before we lose the transaction object
3205 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3206 output.println(revertptr+"=revertlist;");
3207 output.println("if (transCommit()) {");
3208 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3209 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3210 output.println("} else {");
3211 /* Need to commit local object store */
3212 output.println("while ("+revertptr+") {");
3213 output.println("struct ___Object___ * tmpptr;");
3214 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3215 output.println("COMMIT_OBJ("+revertptr+");");
3216 output.println(revertptr+"=tmpptr;");
3217 output.println("}");
3218 output.println("}");
3222 if (!state.DELAYCOMP) {
3224 output.println("if (transCommit()) {");
3225 /* Transaction aborts if it returns true */
3226 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3227 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3228 output.println("}");
3230 if (delaycomp.optimizeTrans(lb, faen.getAtomicEnter())&&(!state.STMARRAY||state.DUALVIEW)) {
3231 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3232 output.println("LIGHTWEIGHTCOMMIT("+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+", transretry"+faen.getAtomicEnter().getIdentifier()+");");
3234 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3235 TempDescriptor tmp=tmpit.next();
3236 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3238 } else if (delaycomp.needsFission(lb, faen.getAtomicEnter())) {
3239 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3241 output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {");
3242 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3243 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3244 output.println("}");
3246 output.println("else {");
3247 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3248 TempDescriptor tmp=tmpit.next();
3249 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3251 output.println("}");
3253 output.println("if (transCommit(NULL, NULL, NULL, NULL)) {");
3254 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3255 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3256 output.println("}");
3261 public void generateFlatSESEEnterNode( FlatMethod fm,
3263 FlatSESEEnterNode fsen,
3267 // if MLP flag is off, okay that SESE nodes are in IR graph,
3268 // just skip over them and code generates exactly the same
3273 // there may be an SESE in an unreachable method, skip over
3274 if( !mlpa.getAllSESEs().contains( fsen ) ) {
3278 // also, if we have encountered a placeholder, just skip it
3279 if( fsen.getIsCallerSESEplaceholder() ) {
3283 output.println(" {");
3285 // set up the parent
3286 if( fsen == mlpa.getMainSESE() ) {
3287 output.println(" SESEcommon* parentCommon = NULL;");
3289 if( fsen.getParent() == null ) {
3290 System.out.println( "in "+fm+", "+fsen+" has null parent" );
3292 assert fsen.getParent() != null;
3293 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3294 output.println(" SESEcommon* parentCommon = &("+paramsprefix+"->common);");
3296 //output.println(" SESEcommon* parentCommon = (SESEcommon*) peekItem( seseCallStack );");
3297 output.println(" SESEcommon* parentCommon = seseCaller;");
3301 // before doing anything, lock your own record and increment the running children
3302 if( fsen != mlpa.getMainSESE() ) {
3303 output.println(" atomic_inc(&parentCommon->numRunningChildren);");
3306 // just allocate the space for this record
3307 output.println(" "+fsen.getSESErecordName()+"* seseToIssue = ("+
3308 fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
3309 fsen.getSESErecordName()+" ) );");
3311 // and keep the thread-local sese stack up to date
3312 //output.println(" addNewItem( seseCallStack, (void*) seseToIssue);");
3314 // fill in common data
3315 output.println(" int localCount=0;");
3316 output.println(" seseToIssue->common.classID = "+fsen.getIdentifier()+";");
3317 output.println(" psem_init( &(seseToIssue->common.stallSem) );");
3319 output.println(" seseToIssue->common.forwardList = createQueue();");
3320 output.println(" seseToIssue->common.unresolvedDependencies = 10000;");
3321 output.println(" pthread_cond_init( &(seseToIssue->common.doneCond), NULL );");
3322 output.println(" seseToIssue->common.doneExecuting = FALSE;");
3323 output.println(" pthread_cond_init( &(seseToIssue->common.runningChildrenCond), NULL );");
3324 output.println(" seseToIssue->common.numRunningChildren = 0;");
3325 output.println(" seseToIssue->common.parent = parentCommon;");
3327 // all READY in-vars should be copied now and be done with it
3328 Iterator<TempDescriptor> tempItr = fsen.getReadyInVarSet().iterator();
3329 while( tempItr.hasNext() ) {
3330 TempDescriptor temp = tempItr.next();
3332 // when we are issuing the main SESE or an SESE with placeholder
3333 // caller SESE as parent, generate temp child child's eclosing method,
3334 // otherwise use the parent's enclosing method as the context
3335 boolean useParentContext = false;
3337 if( fsen != mlpa.getMainSESE() ) {
3338 assert fsen.getParent() != null;
3339 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3340 useParentContext = true;
3344 if( useParentContext ) {
3345 output.println(" seseToIssue->"+temp+" = "+
3346 generateTemp( fsen.getParent().getfmBogus(), temp, null )+";");
3348 output.println(" seseToIssue->"+temp+" = "+
3349 generateTemp( fsen.getfmEnclosing(), temp, null )+";");
3353 // before potentially adding this SESE to other forwarding lists,
3354 // create it's lock and take it immediately
3355 output.println(" pthread_mutex_init( &(seseToIssue->common.lock), NULL );");
3356 // output.println(" pthread_mutex_lock( &(seseToIssue->common.lock) );");
3358 // count up memory conflict dependencies,
3360 ConflictGraph graph = null;
3361 FlatSESEEnterNode parent = fsen.getParent();
3362 if (parent != null) {
3363 if (parent.isCallerSESEplaceholder) {
3364 graph = mlpa.getConflictGraphResults().get(parent.getfmEnclosing());
3366 graph = mlpa.getConflictGraphResults().get(parent);
3369 if (graph != null) {
3370 HashSet<SESELock> seseLockSet = mlpa.getConflictGraphLockMap().get(
3373 output.println(" //add memory queue element");
3374 Set<WaitingElement> waitingQueueSet = graph
3375 .getWaitingElementSetBySESEID(fsen.getIdentifier(),
3377 if (waitingQueueSet.size() > 0) {
3378 output.println(" {");
3379 output.println(" REntry* rentry=NULL;");
3380 output.println(" seseToIssue->common.rentryIdx=0;");
3381 for (Iterator iterator = waitingQueueSet.iterator(); iterator
3383 WaitingElement waitingElement = (WaitingElement) iterator
3386 if( waitingElement.getStatus() >= ConflictNode.COARSE ){
3387 output.println(" rentry=mlpCreateREntry("+ waitingElement.getStatus()+ ", seseToIssue);");
3389 output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", seseToIssue, seseToIssue->"+ waitingElement.getDynID() + ");");
3391 output.println(" rentry->queue=parentCommon->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
3392 output.println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
3394 .println(" if(ADDRENTRY(parentCommon->memoryQueueArray["
3395 + waitingElement.getQueueID()
3396 + "],rentry)==NOTREADY){");
3397 output.println(" ++(localCount);");
3398 output.println(" } ");
3401 output.println(" }");
3406 if( fsen != mlpa.getMainSESE() ) {
3407 // count up outstanding dependencies, static first, then dynamic
3408 Iterator<SESEandAgePair> staticSrcsItr = fsen.getStaticInVarSrcs().iterator();
3409 while( staticSrcsItr.hasNext() ) {
3410 SESEandAgePair srcPair = staticSrcsItr.next();
3411 output.println(" {");
3412 output.println(" SESEcommon* src = (SESEcommon*)"+srcPair+";");
3413 output.println(" pthread_mutex_lock( &(src->lock) );");
3414 output.println(" if( !isEmpty( src->forwardList ) &&");
3415 output.println(" seseToIssue == peekItem( src->forwardList ) ) {");
3416 output.println(" printf( \"This shouldnt already be here\\n\");");
3417 output.println(" exit( -1 );");
3418 output.println(" }");
3419 output.println(" if( !src->doneExecuting ) {");
3420 output.println(" addNewItem( src->forwardList, seseToIssue );");
3421 // output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3422 output.println(" ++(localCount);");
3423 output.println(" }");
3424 output.println(" pthread_mutex_unlock( &(src->lock) );");
3425 output.println(" }");
3427 // whether or not it is an outstanding dependency, make sure
3428 // to pass the static name to the child's record
3429 output.println(" seseToIssue->"+srcPair+" = "+srcPair+";");
3432 // dynamic sources might already be accounted for in the static list,
3433 // so only add them to forwarding lists if they're not already there
3434 Iterator<TempDescriptor> dynVarsItr = fsen.getDynamicInVarSet().iterator();
3435 while( dynVarsItr.hasNext() ) {
3436 TempDescriptor dynInVar = dynVarsItr.next();
3437 output.println(" {");
3438 output.println(" SESEcommon* src = (SESEcommon*)"+dynInVar+"_srcSESE;");
3440 // the dynamic source is NULL if it comes from your own space--you can't pass
3441 // the address off to the new child, because you're not done executing and
3442 // might change the variable, so copy it right now
3443 output.println(" if( src != NULL ) {");
3444 output.println(" pthread_mutex_lock( &(src->lock) );");
3445 output.println(" if( isEmpty( src->forwardList ) ||");
3446 output.println(" seseToIssue != peekItem( src->forwardList ) ) {");
3447 output.println(" if( !src->doneExecuting ) {");
3448 output.println(" addNewItem( src->forwardList, seseToIssue );");
3449 // output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3450 output.println(" ++(localCount);");
3451 output.println(" }");
3452 output.println(" }");
3453 output.println(" pthread_mutex_unlock( &(src->lock) );");
3454 output.println(" seseToIssue->"+dynInVar+"_srcOffset = "+dynInVar+"_srcOffset;");
3455 output.println(" } else {");
3457 boolean useParentContext = false;
3458 if( fsen != mlpa.getMainSESE() ) {
3459 assert fsen.getParent() != null;
3460 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3461 useParentContext = true;
3464 if( useParentContext ) {
3465 output.println(" seseToIssue->"+dynInVar+" = "+
3466 generateTemp( fsen.getParent().getfmBogus(), dynInVar, null )+";");
3468 output.println(" seseToIssue->"+dynInVar+" = "+
3469 generateTemp( fsen.getfmEnclosing(), dynInVar, null )+";");
3472 output.println(" }");
3473 output.println(" }");
3475 // even if the value is already copied, make sure your NULL source
3476 // gets passed so child knows it already has the dynamic value
3477 output.println(" seseToIssue->"+dynInVar+"_srcSESE = "+dynInVar+"_srcSESE;");
3480 // maintain pointers for finding dynamic SESE
3481 // instances from static names
3482 SESEandAgePair pair = new SESEandAgePair( fsen, 0 );
3483 if( fsen.getParent() != null &&
3484 //!fsen.getParent().getIsCallerSESEplaceholder() &&
3485 fsen.getParent().getNeededStaticNames().contains( pair )
3488 for( int i = fsen.getOldestAgeToTrack(); i > 0; --i ) {
3489 SESEandAgePair pair1 = new SESEandAgePair( fsen, i );
3490 SESEandAgePair pair2 = new SESEandAgePair( fsen, i-1 );
3491 output.println(" "+pair1+" = "+pair2+";");
3493 output.println(" "+pair+" = seseToIssue;");
3498 // release this SESE for siblings to update its dependencies or,
3499 // eventually, for it to mark itself finished
3500 // output.println(" pthread_mutex_unlock( &(seseToIssue->common.lock) );");
3502 // if there were no outstanding dependencies, issue here
3503 output.println(" if( atomic_sub_and_test(10000-localCount,&(seseToIssue->common.unresolvedDependencies) ) ) {");
3504 output.println(" workScheduleSubmit( (void*)seseToIssue );");
3505 output.println(" }");
3507 output.println(" if( seseToIssue->common.unresolvedDependencies == 0 ) {");
3508 output.println(" workScheduleSubmit( (void*)seseToIssue );");
3509 output.println(" }");
3511 // release this SESE for siblings to update its dependencies or,
3512 // eventually, for it to mark itself finished
3513 // output.println(" pthread_mutex_unlock( &(seseToIssue->common.lock) );");
3514 output.println(" }");
3518 public void generateFlatSESEExitNode( FlatMethod fm,
3520 FlatSESEExitNode fsexn,
3524 // if MLP flag is off, okay that SESE nodes are in IR graph,
3525 // just skip over them and code generates exactly the same
3530 // get the enter node for this exit that has meta data embedded
3531 FlatSESEEnterNode fsen = fsexn.getFlatEnter();
3533 // there may be an SESE in an unreachable method, skip over
3534 if( !mlpa.getAllSESEs().contains( fsen ) ) {
3538 // also, if we have encountered a placeholder, just jump it
3539 if( fsen.getIsCallerSESEplaceholder() ) {
3543 output.println(" /* SESE exiting */");
3545 String com = paramsprefix+"->common";
3547 // this SESE cannot be done until all of its children are done
3548 // so grab your own lock with the condition variable for watching
3549 // that the number of your running children is greater than zero
3550 output.println(" pthread_mutex_lock( &("+com+".lock) );");
3551 output.println(" while( "+com+".numRunningChildren > 0 ) {");
3552 output.println(" pthread_cond_wait( &("+com+".runningChildrenCond), &("+com+".lock) );");
3553 output.println(" }");
3555 // copy out-set from local temps into the sese record
3556 Iterator<TempDescriptor> itr = fsen.getOutVarSet().iterator();
3557 while( itr.hasNext() ) {
3558 TempDescriptor temp = itr.next();
3560 // only have to do this for primitives non-arrays
3562 temp.getType().isPrimitive() && !temp.getType().isArray()
3568 // have to determine the context enclosing this sese
3569 boolean useParentContext = false;
3571 if( fsen != mlpa.getMainSESE() ) {
3572 assert fsen.getParent() != null;
3573 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3574 useParentContext = true;
3579 if( useParentContext ) {
3580 from = generateTemp( fsen.getParent().getfmBogus(), temp, null );
3582 from = generateTemp( fsen.getfmEnclosing(), temp, null );
3585 output.println(" "+paramsprefix+
3586 "->"+temp.getSafeSymbol()+
3590 // mark yourself done, your SESE data is now read-only
3591 output.println(" "+com+".doneExecuting = TRUE;");
3592 output.println(" pthread_cond_signal( &("+com+".doneCond) );");
3593 output.println(" pthread_mutex_unlock( &("+com+".lock) );");
3595 // decrement dependency count for all SESE's on your forwarding list
3596 output.println(" while( !isEmpty( "+com+".forwardList ) ) {");
3597 output.println(" SESEcommon* consumer = (SESEcommon*) getItem( "+com+".forwardList );");
3598 // output.println(" pthread_mutex_lock( &(consumer->lock) );");
3599 // output.println(" --(consumer->unresolvedDependencies);");
3600 // output.println(" if( consumer->unresolvedDependencies == 0 ) {");
3601 output.println(" if( atomic_sub_and_test(1, &(consumer->unresolvedDependencies)) ){");
3602 output.println(" workScheduleSubmit( (void*)consumer );");
3603 output.println(" }");
3604 // output.println(" pthread_mutex_unlock( &(consumer->lock) );");
3605 output.println(" }");
3609 // clean up its lock element from waiting queue, and decrement dependency count for next SESE block
3610 if( fsen != mlpa.getMainSESE() ) {
3613 output.println(" /* check memory dependency*/");
3614 output.println(" {");
3615 output.println(" int idx;");
3616 output.println(" for(idx=0;idx<___params___->common.rentryIdx;idx++){");
3617 output.println(" REntry* re=___params___->common.rentryArray[idx];");
3618 output.println(" RETIRERENTRY(re->queue,re);");
3619 output.println(" }");
3620 output.println(" }");
3624 // if parent is stalling on you, let them know you're done
3625 if( fsexn.getFlatEnter() != mlpa.getMainSESE() ) {
3626 output.println(" psem_give( &("+paramsprefix+"->common.stallSem) );");
3629 // last of all, decrement your parent's number of running children
3630 output.println(" if( "+paramsprefix+"->common.parent != NULL ) {");
3631 output.println(" if (atomic_sub_and_test(1, &"+paramsprefix+"->common.parent->numRunningChildren)) {");
3632 output.println(" pthread_mutex_lock( &("+paramsprefix+"->common.parent->lock) );");
3633 output.println(" pthread_cond_signal( &("+paramsprefix+"->common.parent->runningChildrenCond) );");
3634 output.println(" pthread_mutex_unlock( &("+paramsprefix+"->common.parent->lock) );");
3635 output.println(" }");
3636 output.println(" }");
3638 // this is a thread-only variable that can be handled when critical sese-to-sese
3639 // data has been taken care of--set sese pointer to remember self over method
3640 // calls to a non-zero, invalid address
3641 output.println(" seseCaller = (SESEcommon*) 0x1;");
3645 public void generateFlatWriteDynamicVarNode( FlatMethod fm,
3647 FlatWriteDynamicVarNode fwdvn,
3651 // should node should not be in an IR graph if the
3652 // MLP flag is not set
3653 throw new Error("Unexpected presence of FlatWriteDynamicVarNode");
3656 Hashtable<TempDescriptor, VSTWrapper> writeDynamic = fwdvn.getVar2src();
3658 assert writeDynamic != null;
3660 Iterator wdItr = writeDynamic.entrySet().iterator();
3661 while( wdItr.hasNext() ) {
3662 Map.Entry me = (Map.Entry) wdItr.next();
3663 TempDescriptor refVar = (TempDescriptor) me.getKey();
3664 VSTWrapper vstW = (VSTWrapper) me.getValue();
3665 VariableSourceToken vst = vstW.vst;
3668 // only do this if the variable in question should be tracked,
3669 // meaning that it was explicitly added to the dynamic var set
3670 if( !current.getDynamicVarSet().contains( vst.getAddrVar() ) ) {
3676 // if there is no given source, this variable is ready so
3677 // mark src pointer NULL to signify that the var is up-to-date
3678 output.println(" "+refVar+"_srcSESE = NULL;");
3682 // otherwise we track where it will come from
3683 SESEandAgePair instance = new SESEandAgePair( vst.getSESE(), vst.getAge() );
3684 output.println(" "+refVar+"_srcSESE = "+instance+";");
3685 output.println(" "+refVar+"_srcOffset = (int) &((("+
3686 vst.getSESE().getSESErecordName()+"*)0)->"+vst.getAddrVar()+");");
3691 private void generateFlatCheckNode(FlatMethod fm, LocalityBinding lb, FlatCheckNode fcn, PrintWriter output) {
3692 if (state.CONSCHECK) {
3693 String specname=fcn.getSpec();
3694 String varname="repairstate___";
3695 output.println("{");
3696 output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
3698 TempDescriptor[] temps=fcn.getTemps();
3699 String[] vars=fcn.getVars();
3700 for(int i=0; i<temps.length; i++) {
3701 output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i],lb)+";");
3704 output.println("if (doanalysis"+specname+"("+varname+")) {");
3705 output.println("free"+specname+"_state("+varname+");");
3706 output.println("} else {");
3707 output.println("/* Bad invariant */");
3708 output.println("free"+specname+"_state("+varname+");");
3709 output.println("abort_task();");
3710 output.println("}");
3711 output.println("}");
3715 private void generateFlatCall(FlatMethod fm, LocalityBinding lb, FlatCall fc, PrintWriter output) {
3717 if( state.MLP && !nonSESEpass ) {
3718 output.println(" seseCaller = (SESEcommon*)"+paramsprefix+";");
3721 MethodDescriptor md=fc.getMethod();
3722 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? locality.getBinding(lb, fc) : md);
3723 ClassDescriptor cn=md.getClassDesc();
3724 output.println("{");
3725 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3727 LocalityBinding fclb=locality.getBinding(lb, fc);
3728 output.print(" struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
3730 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
3732 output.print(objectparams.numPointers());
3733 output.print(", "+localsprefixaddr);
3734 if (md.getThis()!=null) {
3736 output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis(),lb));
3738 if (fc.getThis()!=null&&md.getThis()==null) {
3739 System.out.println("WARNING!!!!!!!!!!!!");
3740 System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
3744 for(int i=0; i<fc.numArgs(); i++) {
3745 Descriptor var=md.getParameter(i);
3746 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
3747 if (objectparams.isParamPtr(paramtemp)) {
3748 TempDescriptor targ=fc.getArg(i);
3750 TypeDescriptor td=md.getParamType(i);
3752 output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
3754 output.print("(struct "+md.getParamType(i).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
3757 output.println("};");
3762 if (fc.getReturnTemp()!=null)
3763 output.print(generateTemp(fm,fc.getReturnTemp(),lb)+"=");
3765 /* Do we need to do virtual dispatch? */
3766 if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
3769 LocalityBinding fclb=locality.getBinding(lb, fc);
3770 output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
3772 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
3777 if (md.getReturnType().isClass()||md.getReturnType().isArray())
3778 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
3780 output.print(md.getReturnType().getSafeSymbol()+" ");
3781 output.print("(*)(");
3783 boolean printcomma=false;
3784 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3786 LocalityBinding fclb=locality.getBinding(lb, fc);
3787 output.print("struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
3789 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
3793 for(int i=0; i<objectparams.numPrimitives(); i++) {
3794 TempDescriptor temp=objectparams.getPrimitive(i);
3798 if (temp.getType().isClass()||temp.getType().isArray())
3799 output.print("struct " + temp.getType().getSafeSymbol()+" * ");
3801 output.print(temp.getType().getSafeSymbol());
3806 LocalityBinding fclb=locality.getBinding(lb, fc);
3807 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])");
3809 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
3813 boolean needcomma=false;
3814 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3815 output.print("&__parameterlist__");
3819 if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
3820 if (fc.getThis()!=null) {
3821 TypeDescriptor ptd=md.getThis().getType();
3824 if (ptd.isClass()&&!ptd.isArray())
3825 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
3826 output.print(generateTemp(fm,fc.getThis(),lb));
3831 for(int i=0; i<fc.numArgs(); i++) {
3832 Descriptor var=md.getParameter(i);
3833 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
3834 if (objectparams.isParamPrim(paramtemp)) {
3835 TempDescriptor targ=fc.getArg(i);
3839 TypeDescriptor ptd=md.getParamType(i);
3840 if (ptd.isClass()&&!ptd.isArray())
3841 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
3842 output.print(generateTemp(fm, targ,lb));
3846 output.println(");");
3847 output.println(" }");
3850 private boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
3851 Set subclasses=typeutil.getSubClasses(thiscd);
3852 if (subclasses==null)
3854 for(Iterator classit=subclasses.iterator(); classit.hasNext();) {
3855 ClassDescriptor cd=(ClassDescriptor)classit.next();
3856 Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol());
3857 for(Iterator matchit=possiblematches.iterator(); matchit.hasNext();) {
3858 MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
3859 if (md.matches(matchmd))
3866 private void generateFlatFieldNode(FlatMethod fm, LocalityBinding lb, FlatFieldNode ffn, PrintWriter output) {
3867 if (state.SINGLETM) {
3868 //single machine transactional memory case
3869 String field=ffn.getField().getSafeSymbol();
3870 String src=generateTemp(fm, ffn.getSrc(),lb);
3871 String dst=generateTemp(fm, ffn.getDst(),lb);
3873 output.println(dst+"="+ src +"->"+field+ ";");
3874 if (ffn.getField().getType().isPtr()&&locality.getAtomic(lb).get(ffn).intValue()>0&&
3875 locality.getNodePreTempInfo(lb, ffn).get(ffn.getSrc())!=LocalityAnalysis.SCRATCH) {
3876 if ((dc==null)||(!state.READSET&&dc.getNeedTrans(lb, ffn))||
3877 (state.READSET&&dc.getNeedWriteTrans(lb, ffn))) {
3878 output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));");
3879 } else if (state.READSET&&dc.getNeedTrans(lb, ffn)) {
3880 if (state.HYBRID&&delaycomp.getConv(lb).contains(ffn)) {
3881 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
3883 output.println("TRANSREADRD("+dst+", "+dst+");");
3886 } else if (state.DSM) {
3887 Integer status=locality.getNodePreTempInfo(lb,ffn).get(ffn.getSrc());
3888 if (status==LocalityAnalysis.GLOBAL) {
3889 String field=ffn.getField().getSafeSymbol();
3890 String src=generateTemp(fm, ffn.getSrc(),lb);
3891 String dst=generateTemp(fm, ffn.getDst(),lb);
3893 if (ffn.getField().getType().isPtr()) {
3895 //TODO: Uncomment this when we have runtime support
3896 //if (ffn.getSrc()==ffn.getDst()) {
3897 //output.println("{");
3898 //output.println("void * temp="+src+";");
3899 //output.println("if (temp&0x1) {");
3900 //output.println("temp=(void *) transRead(trans, (unsigned int) temp);");
3901 //output.println(src+"->"+field+"="+temp+";");
3902 //output.println("}");
3903 //output.println(dst+"=temp;");
3904 //output.println("}");
3906 output.println(dst+"="+ src +"->"+field+ ";");
3907 //output.println("if ("+dst+"&0x1) {");
3908 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
3909 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
3910 //output.println(src+"->"+field+"="+src+"->"+field+";");
3911 //output.println("}");
3914 output.println(dst+"="+ src+"->"+field+";");
3916 } else if (status==LocalityAnalysis.LOCAL) {
3917 if (ffn.getField().getType().isPtr()&&
3918 ffn.getField().isGlobal()) {
3919 String field=ffn.getField().getSafeSymbol();
3920 String src=generateTemp(fm, ffn.getSrc(),lb);
3921 String dst=generateTemp(fm, ffn.getDst(),lb);
3922 output.println(dst+"="+ src +"->"+field+ ";");
3923 if (locality.getAtomic(lb).get(ffn).intValue()>0)
3924 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
3925 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
3927 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
3928 } else if (status==LocalityAnalysis.EITHER) {
3929 //Code is reading from a null pointer
3930 output.println("if ("+generateTemp(fm, ffn.getSrc(),lb)+") {");
3931 output.println("#ifndef RAW");
3932 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
3933 output.println("#endif");
3934 //This should throw a suitable null pointer error
3935 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
3937 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
3939 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
3943 private void generateFlatSetFieldNode(FlatMethod fm, LocalityBinding lb, FlatSetFieldNode fsfn, PrintWriter output) {
3944 if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
3945 throw new Error("Can't set array length");
3946 if (state.SINGLETM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
3947 //Single Machine Transaction Case
3948 boolean srcptr=fsfn.getSrc().getType().isPtr();
3949 String src=generateTemp(fm,fsfn.getSrc(),lb);
3950 String dst=generateTemp(fm,fsfn.getDst(),lb);
3951 output.println("//"+srcptr+" "+fsfn.getSrc().getType().isNull());
3952 if (srcptr&&!fsfn.getSrc().getType().isNull()) {
3953 output.println("{");
3954 if ((dc==null)||dc.getNeedSrcTrans(lb, fsfn)&&
3955 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) {
3956 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3958 output.println("INTPTR srcoid=(INTPTR)"+src+";");
3961 if (wb.needBarrier(fsfn)&&
3962 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getDst())!=LocalityAnalysis.SCRATCH) {
3963 if (state.EVENTMONITOR) {
3964 output.println("if ("+dst+"->___objstatus___&DIRTY) EVLOGEVENTOBJ(EV_WRITE,"+dst+"->objuid)");
3966 output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;");
3968 if (srcptr&!fsfn.getSrc().getType().isNull()) {
3969 output.println("*((unsigned INTPTR *)&("+dst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
3970 output.println("}");
3972 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3974 } else if (state.DSM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
3975 Integer statussrc=locality.getNodePreTempInfo(lb,fsfn).get(fsfn.getSrc());
3976 Integer statusdst=locality.getNodeTempInfo(lb).get(fsfn).get(fsfn.getDst());
3977 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
3979 String src=generateTemp(fm,fsfn.getSrc(),lb);
3980 String dst=generateTemp(fm,fsfn.getDst(),lb);
3982 output.println("{");
3983 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3985 if (statusdst.equals(LocalityAnalysis.GLOBAL)) {
3988 if (wb.needBarrier(fsfn))
3989 output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;");
3991 output.println("*((unsigned INTPTR *)&("+glbdst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
3993 output.println(glbdst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3994 } else if (statusdst.equals(LocalityAnalysis.LOCAL)) {
3995 /** Check if we need to copy */
3996 output.println("if(!"+dst+"->"+localcopystr+") {");
3997 /* Link object into list */
3998 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3999 output.println(revertptr+"=revertlist;");
4000 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4001 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4003 output.println("COPY_OBJ("+dst+");");
4004 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4005 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4006 output.println("}");
4008 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4010 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4011 } else if (statusdst.equals(LocalityAnalysis.EITHER)) {
4012 //writing to a null...bad
4013 output.println("if ("+dst+") {");
4014 output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}");
4016 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4018 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4021 output.println("}");
4024 if (state.FASTCHECK) {
4025 String dst=generateTemp(fm, fsfn.getDst(),lb);
4026 output.println("if(!"+dst+"->"+localcopystr+") {");
4027 /* Link object into list */
4028 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4029 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4031 output.println("COPY_OBJ("+dst+");");
4032 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4033 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4034 output.println("}");
4036 output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
4040 private void generateFlatElementNode(FlatMethod fm, LocalityBinding lb, FlatElementNode fen, PrintWriter output) {
4041 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
4044 if (elementtype.isArray()||elementtype.isClass())
4047 type=elementtype.getSafeSymbol()+" ";
4049 if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
4050 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fen.getIndex(),lb)+") >= "+generateTemp(fm,fen.getSrc(),lb) + "->___length___))");
4051 output.println("failedboundschk();");
4053 if (state.SINGLETM) {
4054 //Single machine transaction case
4055 String dst=generateTemp(fm, fen.getDst(),lb);
4056 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))) {
4057 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4059 output.println("STMGETARRAY("+dst+", "+ generateTemp(fm,fen.getSrc(),lb)+", "+generateTemp(fm, fen.getIndex(),lb)+", "+type+");");
4062 if (elementtype.isPtr()&&locality.getAtomic(lb).get(fen).intValue()>0&&
4063 locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())!=LocalityAnalysis.SCRATCH) {
4064 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fen)||state.READSET&&dc.getNeedWriteTrans(lb, fen)) {
4065 output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));");
4066 } else if (state.READSET&&dc.getNeedTrans(lb, fen)) {
4067 if (state.HYBRID&&delaycomp.getConv(lb).contains(fen)) {
4068 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4070 output.println("TRANSREADRD("+dst+", "+dst+");");
4073 } else if (state.DSM) {
4074 Integer status=locality.getNodePreTempInfo(lb,fen).get(fen.getSrc());
4075 if (status==LocalityAnalysis.GLOBAL) {
4076 String dst=generateTemp(fm, fen.getDst(),lb);
4077 if (elementtype.isPtr()) {
4078 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4079 //DEBUG: output.println("TRANSREAD("+dst+", "+dst+",\""+fm+":"+fen+"\");");
4080 output.println("TRANSREAD("+dst+", "+dst+");");
4082 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4084 } else if (status==LocalityAnalysis.LOCAL) {
4085 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4086 } else if (status==LocalityAnalysis.EITHER) {
4087 //Code is reading from a null pointer
4088 output.println("if ("+generateTemp(fm, fen.getSrc(),lb)+") {");
4089 output.println("#ifndef RAW");
4090 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4091 output.println("#endif");
4092 //This should throw a suitable null pointer error
4093 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4095 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4097 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4101 private void generateFlatSetElementNode(FlatMethod fm, LocalityBinding lb, FlatSetElementNode fsen, PrintWriter output) {
4102 //TODO: need dynamic check to make sure this assignment is actually legal
4103 //Because Object[] could actually be something more specific...ie. Integer[]
4105 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
4108 if (elementtype.isArray()||elementtype.isClass())
4111 type=elementtype.getSafeSymbol()+" ";
4113 if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
4114 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fsen.getIndex(),lb)+") >= "+generateTemp(fm,fsen.getDst(),lb) + "->___length___))");
4115 output.println("failedboundschk();");
4118 if (state.SINGLETM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4119 //Transaction set element case
4120 if (wb.needBarrier(fsen)&&
4121 locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH) {
4122 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___objstatus___))|=DIRTY;");
4124 if (fsen.getSrc().getType().isPtr()&&!fsen.getSrc().getType().isNull()) {
4125 output.println("{");
4126 String src=generateTemp(fm, fsen.getSrc(), lb);
4127 if ((dc==null)||dc.getNeedSrcTrans(lb, fsen)&&
4128 locality.getNodePreTempInfo(lb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) {
4129 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4131 output.println("INTPTR srcoid=(INTPTR)"+src+";");
4133 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
4134 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", srcoid, INTPTR);");
4136 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
4138 output.println("}");
4140 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
4141 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", "+ generateTemp(fm, fsen.getSrc(), lb) +", "+type+");");
4143 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4146 } else if (state.DSM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4147 Integer statussrc=locality.getNodePreTempInfo(lb,fsen).get(fsen.getSrc());
4148 Integer statusdst=locality.getNodePreTempInfo(lb,fsen).get(fsen.getDst());
4149 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4150 boolean dstglobal=statusdst==LocalityAnalysis.GLOBAL;
4151 boolean dstlocal=(statusdst==LocalityAnalysis.LOCAL)||(statusdst==LocalityAnalysis.EITHER);
4154 if (wb.needBarrier(fsen))
4155 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___localcopy___))|=DIRTY;");
4156 } else if (dstlocal) {
4157 /** Check if we need to copy */
4158 String dst=generateTemp(fm, fsen.getDst(),lb);
4159 output.println("if(!"+dst+"->"+localcopystr+") {");
4160 /* Link object into list */
4161 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4162 output.println(revertptr+"=revertlist;");
4163 if ((GENERATEPRECISEGC) || this.state.MULTICOREGC)
4164 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4166 output.println("COPY_OBJ("+dst+");");
4167 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4168 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4169 output.println("}");
4171 System.out.println("Node: "+fsen);
4172 System.out.println(lb);
4173 System.out.println("statusdst="+statusdst);
4174 System.out.println(fm.printMethod());
4175 throw new Error("Unknown array type");
4178 output.println("{");
4179 String src=generateTemp(fm, fsen.getSrc(), lb);
4180 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4181 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
4182 output.println("}");
4184 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4187 if (state.FASTCHECK) {
4188 String dst=generateTemp(fm, fsen.getDst(),lb);
4189 output.println("if(!"+dst+"->"+localcopystr+") {");
4190 /* Link object into list */
4191 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4192 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4194 output.println("COPY_OBJ("+dst+");");
4195 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4196 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4197 output.println("}");
4199 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4203 protected void generateFlatNew(FlatMethod fm, LocalityBinding lb, FlatNew fn, PrintWriter output) {
4204 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
4205 //Stash pointer in case of GC
4206 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4207 output.println(revertptr+"=revertlist;");
4209 if (state.SINGLETM) {
4210 if (fn.getType().isArray()) {
4211 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4212 if (locality.getAtomic(lb).get(fn).intValue()>0) {
4213 //inside transaction
4214 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4216 //outside transaction
4217 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4220 if (locality.getAtomic(lb).get(fn).intValue()>0) {
4221 //inside transaction
4222 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4224 //outside transaction
4225 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4228 } else if (fn.getType().isArray()) {
4229 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4230 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4231 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4232 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4233 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4235 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4238 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4239 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");");
4240 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4241 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4243 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
4246 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
4247 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4248 String dst=generateTemp(fm,fn.getDst(),lb);
4249 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
4250 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4251 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4253 if (state.FASTCHECK) {
4254 String dst=generateTemp(fm,fn.getDst(),lb);
4255 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
4256 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4257 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4261 private void generateFlatTagDeclaration(FlatMethod fm, LocalityBinding lb, FlatTagDeclaration fn, PrintWriter output) {
4262 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4263 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
4265 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+state.getTagId(fn.getType())+");");
4269 private void generateFlatOpNode(FlatMethod fm, LocalityBinding lb, FlatOpNode fon, PrintWriter output) {
4270 if (fon.getRight()!=null) {
4271 if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
4272 if (fon.getLeft().getType().isLong())
4273 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
4275 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned int)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
4277 } else if (dc!=null) {
4278 output.print(generateTemp(fm, fon.getDest(),lb)+" = (");
4279 if (fon.getLeft().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
4280 output.print("(void *)");
4281 if (dc.getNeedLeftSrcTrans(lb, fon))
4282 output.print("("+generateTemp(fm, fon.getLeft(),lb)+"!=NULL?"+generateTemp(fm, fon.getLeft(),lb)+"->"+oidstr+":NULL)");
4284 output.print(generateTemp(fm, fon.getLeft(),lb));
4285 output.print(")"+fon.getOp().toString()+"(");
4286 if (fon.getRight().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
4287 output.print("(void *)");
4288 if (dc.getNeedRightSrcTrans(lb, fon))
4289 output.println("("+generateTemp(fm, fon.getRight(),lb)+"!=NULL?"+generateTemp(fm, fon.getRight(),lb)+"->"+oidstr+":NULL));");
4291 output.println(generateTemp(fm,fon.getRight(),lb)+");");
4293 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+fon.getOp().toString()+generateTemp(fm,fon.getRight(),lb)+";");
4294 } else if (fon.getOp().getOp()==Operation.ASSIGN)
4295 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
4296 else if (fon.getOp().getOp()==Operation.UNARYPLUS)
4297 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
4298 else if (fon.getOp().getOp()==Operation.UNARYMINUS)
4299 output.println(generateTemp(fm, fon.getDest(),lb)+" = -"+generateTemp(fm, fon.getLeft(),lb)+";");
4300 else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
4301 output.println(generateTemp(fm, fon.getDest(),lb)+" = !"+generateTemp(fm, fon.getLeft(),lb)+";");
4302 else if (fon.getOp().getOp()==Operation.COMP)
4303 output.println(generateTemp(fm, fon.getDest(),lb)+" = ~"+generateTemp(fm, fon.getLeft(),lb)+";");
4304 else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
4305 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+"->fses==NULL;");
4307 output.println(generateTemp(fm, fon.getDest(),lb)+fon.getOp().toString()+generateTemp(fm, fon.getLeft(),lb)+";");
4310 private void generateFlatCastNode(FlatMethod fm, LocalityBinding lb, FlatCastNode fcn, PrintWriter output) {
4311 /* TODO: Do type check here */
4312 if (fcn.getType().isArray()) {
4313 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
4314 } else if (fcn.getType().isClass())
4315 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
4317 output.println(generateTemp(fm,fcn.getDst(),lb)+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc(),lb)+";");
4320 private void generateFlatLiteralNode(FlatMethod fm, LocalityBinding lb, FlatLiteralNode fln, PrintWriter output) {
4321 if (fln.getValue()==null)
4322 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
4323 else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
4324 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4325 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
4326 //Stash pointer in case of GC
4327 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4328 output.println(revertptr+"=revertlist;");
4330 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
4331 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
4332 //Stash pointer in case of GC
4333 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4334 output.println("revertlist="+revertptr+";");
4337 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
4339 } else if (fln.getType().isBoolean()) {
4340 if (((Boolean)fln.getValue()).booleanValue())
4341 output.println(generateTemp(fm, fln.getDst(),lb)+"=1;");
4343 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
4344 } else if (fln.getType().isChar()) {
4345 String st=FlatLiteralNode.escapeString(fln.getValue().toString());
4346 output.println(generateTemp(fm, fln.getDst(),lb)+"='"+st+"';");
4347 } else if (fln.getType().isLong()) {
4348 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+"LL;");
4350 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+";");
4353 protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) {
4354 if (frn.getReturnTemp()!=null) {
4355 if (frn.getReturnTemp().getType().isPtr())
4356 output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";");
4358 output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";");
4360 output.println("return;");
4364 protected void generateStoreFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
4367 //only record if this group has more than one exit
4368 if (branchanalysis.numJumps(fcb)>1) {
4369 left=branchanalysis.jumpValue(fcb, 0);
4370 right=branchanalysis.jumpValue(fcb, 1);
4372 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") {");
4374 output.println("STOREBRANCH("+right+");");
4375 output.println("goto "+label+";");
4376 output.println("}");
4378 output.println("STOREBRANCH("+left+");");
4381 protected void generateFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
4382 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") goto "+label+";");
4385 /** This method generates header information for the method or
4386 * task referenced by the Descriptor des. */
4387 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) {
4388 generateHeader(fm, lb, des, output, false);
4391 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output, boolean addSESErecord) {
4393 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : des);
4394 MethodDescriptor md=null;
4395 TaskDescriptor task=null;
4396 if (des instanceof MethodDescriptor)
4397 md=(MethodDescriptor) des;
4399 task=(TaskDescriptor) des;
4401 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
4403 if (md!=null&&md.getReturnType()!=null) {
4404 if (md.getReturnType().isClass()||md.getReturnType().isArray())
4405 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
4407 output.print(md.getReturnType().getSafeSymbol()+" ");
4409 //catch the constructor case
4410 output.print("void ");
4412 if (state.DSM||state.SINGLETM) {
4413 output.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
4415 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
4417 output.print(task.getSafeSymbol()+"(");
4419 boolean printcomma=false;
4420 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4422 if (state.DSM||state.SINGLETM) {
4423 output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
4425 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
4427 output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
4433 for(int i=0; i<objectparams.numPrimitives(); i++) {
4434 TempDescriptor temp=objectparams.getPrimitive(i);
4438 if (temp.getType().isClass()||temp.getType().isArray())
4439 output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
4441 output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
4443 output.println(") {");
4444 } else if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
4445 /* Imprecise Task */
4446 output.println("void * parameterarray[]) {");
4447 /* Unpack variables */
4448 for(int i=0; i<objectparams.numPrimitives(); i++) {
4449 TempDescriptor temp=objectparams.getPrimitive(i);
4450 output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
4452 for(int i=0; i<fm.numTags(); i++) {
4453 TempDescriptor temp=fm.getTag(i);
4454 int offset=i+objectparams.numPrimitives();
4455 output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
4458 if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
4459 maxtaskparams=objectparams.numPrimitives()+fm.numTags();
4460 } else output.println(") {");
4463 public void generateFlatFlagActionNode(FlatMethod fm, LocalityBinding lb, FlatFlagActionNode ffan, PrintWriter output) {
4464 output.println("/* FlatFlagActionNode */");
4467 /* Process tag changes */
4468 Relation tagsettable=new Relation();
4469 Relation tagcleartable=new Relation();
4471 Iterator tagsit=ffan.getTempTagPairs();
4472 while (tagsit.hasNext()) {
4473 TempTagPair ttp=(TempTagPair) tagsit.next();
4474 TempDescriptor objtmp=ttp.getTemp();
4475 TagDescriptor tag=ttp.getTag();
4476 TempDescriptor tagtmp=ttp.getTagTemp();
4477 boolean tagstatus=ffan.getTagChange(ttp);
4479 tagsettable.put(objtmp, tagtmp);
4481 tagcleartable.put(objtmp, tagtmp);
4486 Hashtable flagandtable=new Hashtable();
4487 Hashtable flagortable=new Hashtable();
4489 /* Process flag changes */
4490 Iterator flagsit=ffan.getTempFlagPairs();
4491 while(flagsit.hasNext()) {
4492 TempFlagPair tfp=(TempFlagPair)flagsit.next();
4493 TempDescriptor temp=tfp.getTemp();
4494 Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
4495 FlagDescriptor flag=tfp.getFlag();
4497 //Newly allocate objects that don't set any flags case
4498 if (flagortable.containsKey(temp)) {
4502 flagortable.put(temp,new Integer(mask));
4504 int flagid=1<<((Integer)flagtable.get(flag)).intValue();
4505 boolean flagstatus=ffan.getFlagChange(tfp);
4508 if (flagortable.containsKey(temp)) {
4509 mask=((Integer)flagortable.get(temp)).intValue();
4512 flagortable.put(temp,new Integer(mask));
4514 int mask=0xFFFFFFFF;
4515 if (flagandtable.containsKey(temp)) {
4516 mask=((Integer)flagandtable.get(temp)).intValue();
4518 mask&=(0xFFFFFFFF^flagid);
4519 flagandtable.put(temp,new Integer(mask));
4525 HashSet flagtagset=new HashSet();
4526 flagtagset.addAll(flagortable.keySet());
4527 flagtagset.addAll(flagandtable.keySet());
4528 flagtagset.addAll(tagsettable.keySet());
4529 flagtagset.addAll(tagcleartable.keySet());
4531 Iterator ftit=flagtagset.iterator();
4532 while(ftit.hasNext()) {
4533 TempDescriptor temp=(TempDescriptor)ftit.next();
4536 Set tagtmps=tagcleartable.get(temp);
4537 if (tagtmps!=null) {
4538 Iterator tagit=tagtmps.iterator();
4539 while(tagit.hasNext()) {
4540 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
4541 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
4542 output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4544 output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4548 tagtmps=tagsettable.get(temp);
4549 if (tagtmps!=null) {
4550 Iterator tagit=tagtmps.iterator();
4551 while(tagit.hasNext()) {
4552 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
4553 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
4554 output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4556 output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp, lb)+", "+generateTemp(fm,tagtmp, lb)+");");
4561 int andmask=0xFFFFFFF;
4563 if (flagortable.containsKey(temp))
4564 ormask=((Integer)flagortable.get(temp)).intValue();
4565 if (flagandtable.containsKey(temp))
4566 andmask=((Integer)flagandtable.get(temp)).intValue();
4567 generateFlagOrAnd(ffan, fm, lb, temp, output, ormask, andmask);
4568 generateObjectDistribute(ffan, fm, lb, temp, output);
4572 protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp,
4573 PrintWriter output, int ormask, int andmask) {
4574 if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
4575 output.println("flagorandinit("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
4577 output.println("flagorand("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
4581 protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, PrintWriter output) {
4582 output.println("enqueueObject("+generateTemp(fm, temp, lb)+");");
4585 void generateOptionalHeader(PrintWriter headers) {
4588 headers.println("#include \"task.h\"\n\n");
4589 headers.println("#ifndef _OPTIONAL_STRUCT_");
4590 headers.println("#define _OPTIONAL_STRUCT_");
4592 //STRUCT PREDICATEMEMBER
4593 headers.println("struct predicatemember{");
4594 headers.println("int type;");
4595 headers.println("int numdnfterms;");
4596 headers.println("int * flags;");
4597 headers.println("int numtags;");
4598 headers.println("int * tags;\n};\n\n");
4600 //STRUCT OPTIONALTASKDESCRIPTOR
4601 headers.println("struct optionaltaskdescriptor{");
4602 headers.println("struct taskdescriptor * task;");
4603 headers.println("int index;");
4604 headers.println("int numenterflags;");
4605 headers.println("int * enterflags;");
4606 headers.println("int numpredicatemembers;");
4607 headers.println("struct predicatemember ** predicatememberarray;");
4608 headers.println("};\n\n");
4610 //STRUCT TASKFAILURE
4611 headers.println("struct taskfailure {");
4612 headers.println("struct taskdescriptor * task;");
4613 headers.println("int index;");
4614 headers.println("int numoptionaltaskdescriptors;");
4615 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
4617 //STRUCT FSANALYSISWRAPPER
4618 headers.println("struct fsanalysiswrapper{");
4619 headers.println("int flags;");
4620 headers.println("int numtags;");
4621 headers.println("int * tags;");
4622 headers.println("int numtaskfailures;");
4623 headers.println("struct taskfailure ** taskfailurearray;");
4624 headers.println("int numoptionaltaskdescriptors;");
4625 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
4627 //STRUCT CLASSANALYSISWRAPPER
4628 headers.println("struct classanalysiswrapper{");
4629 headers.println("int type;");
4630 headers.println("int numotd;");
4631 headers.println("struct optionaltaskdescriptor ** otdarray;");
4632 headers.println("int numfsanalysiswrappers;");
4633 headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
4635 headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
4637 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
4638 while(taskit.hasNext()) {
4639 TaskDescriptor td=(TaskDescriptor)taskit.next();
4640 headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
4645 //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
4646 int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
4647 int predicateindex = 0;
4648 //iterate through the classes concerned by the predicate
4649 Set c_vard = predicate.vardescriptors;
4650 Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
4653 for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext();) {
4654 VarDescriptor vard = (VarDescriptor)vard_it.next();
4655 TypeDescriptor typed = vard.getType();
4657 //generate for flags
4658 HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
4659 output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4661 if (fen_hashset!=null) {
4662 for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext();) {
4663 FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
4665 DNFFlag dflag=fen.getDNF();
4666 numberterms+=dflag.size();
4668 Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
4670 for(int j=0; j<dflag.size(); j++) {
4672 output.println(",");
4673 Vector term=dflag.get(j);
4676 for(int k=0; k<term.size(); k++) {
4677 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
4678 FlagDescriptor fd=dfa.getFlag();
4679 boolean negated=dfa.getNegated();
4680 int flagid=1<<((Integer)flags.get(fd)).intValue();
4685 output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
4690 output.println("};\n");
4693 TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
4694 output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4697 for(int j=0; j<tagel.numTags(); j++) {
4699 output.println(",");
4700 TempDescriptor tmp=tagel.getTemp(j);
4701 if (!slotnumber.containsKey(tmp)) {
4702 Integer slotint=new Integer(current_slot++);
4703 slotnumber.put(tmp,slotint);
4705 int slot=slotnumber.get(tmp).intValue();
4706 output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
4708 numtags = tagel.numTags();
4710 output.println("};");
4712 //store the result into a predicatemember struct
4713 output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
4714 output.println("/*type*/"+typed.getClassDesc().getId()+",");
4715 output.println("/* number of dnf terms */"+numberterms+",");
4716 output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4717 output.println("/* number of tag */"+numtags+",");
4718 output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4719 output.println("};\n");
4724 //generate an array that stores the entire predicate
4725 output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4726 for( int j = 0; j<predicateindex; j++) {
4727 if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4728 else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4730 output.println("};\n");
4731 return predicateindex;
4735 void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
4736 generateOptionalHeader(headers);
4738 output.println("#include \"optionalstruct.h\"\n\n");
4739 output.println("#include \"stdlib.h\"\n");
4741 HashSet processedcd = new HashSet();
4743 Enumeration e = safeexecution.keys();
4744 while (e.hasMoreElements()) {
4747 ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
4748 Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp); //will be used several times
4750 //Generate the struct of optionals
4751 Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
4752 numotd = c_otd.size();
4753 if(maxotd<numotd) maxotd = numotd;
4754 if( !c_otd.isEmpty() ) {
4755 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
4756 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
4758 //generate the int arrays for the predicate
4759 Predicate predicate = otd.predicate;
4760 int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
4761 TreeSet<Integer> fsset=new TreeSet<Integer>();
4762 //iterate through possible FSes corresponding to
4763 //the state when entering
4765 for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext();) {
4766 FlagState fs = (FlagState)fses.next();
4768 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
4769 FlagDescriptor flagd = (FlagDescriptor)flags.next();
4770 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
4773 fsset.add(new Integer(flagid));
4774 //tag information not needed because tag
4775 //changes are not tolerated.
4778 output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4779 boolean needcomma=false;
4780 for(Iterator<Integer> it=fsset.iterator(); it.hasNext();) {
4783 output.println(it.next());
4786 output.println("};\n");
4789 //generate optionaltaskdescriptor that actually
4790 //includes exit fses, predicate and the task
4792 output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
4793 output.println("&task_"+otd.td.getSafeSymbol()+",");
4794 output.println("/*index*/"+otd.getIndex()+",");
4795 output.println("/*number of enter flags*/"+fsset.size()+",");
4796 output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4797 output.println("/*number of members */"+predicateindex+",");
4798 output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4799 output.println("};\n");
4803 // if there are no optionals, there is no need to build the rest of the struct
4805 output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
4806 c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
4807 if( !c_otd.isEmpty() ) {
4808 boolean needcomma=false;
4809 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
4810 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
4812 output.println(",");
4814 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4817 output.println("};\n");
4819 //get all the possible flagstates reachable by an object
4820 Hashtable hashtbtemp = safeexecution.get(cdtemp);
4822 TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
4823 fsts.addAll(hashtbtemp.keySet());
4824 for(Iterator fsit=fsts.iterator(); fsit.hasNext();) {
4825 FlagState fs = (FlagState)fsit.next();
4828 //get the set of OptionalTaskDescriptors corresponding
4829 HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
4830 //iterate through the OptionalTaskDescriptors and
4831 //store the pointers to the optionals struct (see on
4832 //top) into an array
4834 output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
4835 for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext();) {
4836 OptionalTaskDescriptor mm = mos.next();
4838 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
4840 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4843 output.println("};\n");
4845 //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
4848 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
4849 FlagDescriptor flagd = (FlagDescriptor)flags.next();
4850 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
4854 //process tag information
4857 boolean first = true;
4858 Enumeration tag_enum = fs.getTags();
4859 output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
4860 while(tag_enum.hasMoreElements()) {
4862 TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
4866 output.println(", ");
4867 output.println("/*tagid*/"+state.getTagId(tagd));
4869 output.println("};");
4871 Set<TaskIndex> tiset=sa.getTaskIndex(fs);
4872 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
4873 TaskIndex ti=itti.next();
4877 Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
4879 output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
4880 boolean needcomma=false;
4881 for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext();) {
4882 OptionalTaskDescriptor otd=otdit.next();
4886 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4888 output.println("};");
4890 output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
4891 output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
4892 output.print(ti.getIndex()+", ");
4893 output.print(otdset.size()+", ");
4894 output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
4895 output.println("};");
4898 tiset=sa.getTaskIndex(fs);
4899 boolean needcomma=false;
4901 output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
4902 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
4903 TaskIndex ti=itti.next();
4904 if (ti.isRuntime()) {
4911 output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
4913 output.println("};\n");
4915 //Store the result in fsanalysiswrapper
4917 output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
4918 output.println("/*flag*/"+flagid+",");
4919 output.println("/* number of tags*/"+tagcounter+",");
4920 output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
4921 output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
4922 output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
4923 output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
4924 output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
4925 output.println("};\n");
4929 //Build the array of fsanalysiswrappers
4930 output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
4931 boolean needcomma=false;
4932 for(int i = 0; i<fscounter; i++) {
4933 if (needcomma) output.print(",");
4934 output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
4937 output.println("};");
4939 //Build the classanalysiswrapper referring to the previous array
4940 output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
4941 output.println("/*type*/"+cdtemp.getId()+",");
4942 output.println("/*numotd*/"+numotd+",");
4943 output.println("otdarray"+cdtemp.getSafeSymbol()+",");
4944 output.println("/* number of fsanalysiswrappers */"+fscounter+",");
4945 output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
4946 processedcd.add(cdtemp);
4949 //build an array containing every classes for which code has been build
4950 output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
4951 for(int i=0; i<state.numClasses(); i++) {
4952 ClassDescriptor cn=cdarray[i];
4955 if ((cn != null) && (processedcd.contains(cn)))
4956 output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
4958 output.print("NULL");
4960 output.println("};");
4962 output.println("#define MAXOTD "+maxotd);
4963 headers.println("#endif");
4966 public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
4967 Relation r=new Relation();
4968 for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext();) {
4969 OptionalTaskDescriptor otd=otdit.next();
4970 TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
4974 LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
4975 for(Iterator it=r.keySet().iterator(); it.hasNext();) {
4976 Set s=r.get(it.next());
4977 for(Iterator it2=s.iterator(); it2.hasNext();) {
4978 OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
4986 protected void outputTransCode(PrintWriter output) {