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;
14 import Analysis.TaskStateAnalysis.FlagState;
15 import Analysis.TaskStateAnalysis.FlagComparator;
16 import Analysis.TaskStateAnalysis.OptionalTaskDescriptor;
17 import Analysis.TaskStateAnalysis.Predicate;
18 import Analysis.TaskStateAnalysis.SafetyAnalysis;
19 import Analysis.TaskStateAnalysis.TaskIndex;
20 import Analysis.Locality.LocalityAnalysis;
21 import Analysis.Locality.LocalityBinding;
22 import Analysis.Locality.DiscoverConflicts;
23 import Analysis.Locality.DCWrapper;
24 import Analysis.Locality.DelayComputation;
25 import Analysis.Locality.BranchAnalysis;
26 import Analysis.CallGraph.CallGraph;
27 import Analysis.Disjoint.AllocSite;
28 import Analysis.Disjoint.Effect;
29 import Analysis.Disjoint.ReachGraph;
30 import Analysis.Disjoint.Taint;
31 import Analysis.OoOJava.OoOJavaAnalysis;
32 import Analysis.Prefetch.*;
33 import Analysis.Loops.WriteBarrier;
34 import Analysis.Loops.GlobalFieldType;
35 import Analysis.Locality.TypeAnalysis;
36 import Analysis.MLP.ConflictGraph;
37 import Analysis.MLP.ConflictNode;
38 import Analysis.MLP.MLPAnalysis;
39 import Analysis.MLP.ParentChildConflictsMap;
40 import Analysis.MLP.SESELock;
41 import Analysis.MLP.SESEWaitingQueue;
42 import Analysis.MLP.VariableSourceToken;
43 import Analysis.MLP.VSTWrapper;
44 import Analysis.MLP.CodePlan;
45 import Analysis.MLP.SESEandAgePair;
46 import Analysis.MLP.WaitingElement;
48 public class BuildCode {
51 Hashtable paramstable;
56 String localsprefix="___locals___";
57 String localsprefixaddr="&"+localsprefix;
58 String localsprefixderef=localsprefix+".";
59 String fcrevert="___fcrevert___";
60 String paramsprefix="___params___";
61 String oidstr="___nextobject___";
62 String nextobjstr="___nextobject___";
63 String localcopystr="___localcopy___";
64 public static boolean GENERATEPRECISEGC=false;
65 public static String PREFIX="";
66 public static String arraytype="ArrayObject";
67 public static int flagcount = 0;
70 protected int maxtaskparams=0;
71 private int maxcount=0;
72 ClassDescriptor[] cdarray;
73 TypeDescriptor[] arraytable;
74 LocalityAnalysis locality;
75 Hashtable<LocalityBinding, TempDescriptor> reverttable;
76 Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>> backuptable;
81 String mlperrstr = "if(status != 0) { "+
82 "sprintf(errmsg, \"MLP error at %s:%d\", __FILE__, __LINE__); "+
83 "perror(errmsg); exit(-1); }";
84 boolean nonSESEpass=true;
85 RuntimeConflictResolver rcr = null;
88 DiscoverConflicts recorddc;
93 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa) {
94 this(st, temptovar, typeutil, null, sa, pa, null, null);
97 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa, OoOJavaAnalysis oooa) {
98 this(st, temptovar, typeutil, null, sa, pa, mlpa, oooa);
101 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, PrefetchAnalysis pa, MLPAnalysis mlpa, OoOJavaAnalysis oooa) {
102 this(st, temptovar, typeutil, locality, null, pa, mlpa, oooa);
105 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa, OoOJavaAnalysis oooa) {
111 callgraph=new CallGraph(state);
113 oidstr="___objlocation___";
114 this.temptovar=temptovar;
115 paramstable=new Hashtable();
116 tempstable=new Hashtable();
117 fieldorder=new Hashtable();
118 flagorder=new Hashtable();
119 this.typeutil=typeutil;
120 virtualcalls=new Virtual(state,locality);
121 if (locality!=null) {
122 this.locality=locality;
123 this.reverttable=new Hashtable<LocalityBinding, TempDescriptor>();
124 this.backuptable=new Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>>();
125 this.wb=new WriteBarrier(locality, st);
127 if (state.SINGLETM&&state.DCOPTS) {
128 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
129 GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
130 this.dc=new DiscoverConflicts(locality, st, typeanalysis, gft);
133 if (state.DELAYCOMP) {
134 //TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
135 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
136 GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
137 delaycomp=new DCWrapper(locality, st, typeanalysis, gft);
138 dc=delaycomp.getConflicts();
139 recorddc=new DiscoverConflicts(locality, st, typeanalysis, delaycomp.getCannotDelayMap(), true, true, null);
140 recorddc.doAnalysis();
144 /** The buildCode method outputs C code for all the methods. The Flat
145 * versions of the methods must already be generated and stored in
146 * the State object. */
147 PrintWriter outsandbox=null;
149 public void buildCode() {
150 /* Create output streams to write to */
151 PrintWriter outclassdefs=null;
152 PrintWriter outstructs=null;
153 PrintWriter outrepairstructs=null;
154 PrintWriter outmethodheader=null;
155 PrintWriter outmethod=null;
156 PrintWriter outvirtual=null;
157 PrintWriter outtask=null;
158 PrintWriter outtaskdefs=null;
159 PrintWriter outoptionalarrays=null;
160 PrintWriter optionalheaders=null;
164 outsandbox=new PrintWriter(new FileOutputStream(PREFIX+"sandboxdefs.c"), true);
166 outstructs=new PrintWriter(new FileOutputStream(PREFIX+"structdefs.h"), true);
167 outmethodheader=new PrintWriter(new FileOutputStream(PREFIX+"methodheaders.h"), true);
168 outclassdefs=new PrintWriter(new FileOutputStream(PREFIX+"classdefs.h"), true);
169 outmethod=new PrintWriter(new FileOutputStream(PREFIX+"methods.c"), true);
170 outvirtual=new PrintWriter(new FileOutputStream(PREFIX+"virtualtable.h"), true);
172 outtask=new PrintWriter(new FileOutputStream(PREFIX+"task.h"), true);
173 outtaskdefs=new PrintWriter(new FileOutputStream(PREFIX+"taskdefs.c"), true);
174 if (state.OPTIONAL) {
175 outoptionalarrays=new PrintWriter(new FileOutputStream(PREFIX+"optionalarrays.c"), true);
176 optionalheaders=new PrintWriter(new FileOutputStream(PREFIX+"optionalstruct.h"), true);
179 if (state.structfile!=null) {
180 outrepairstructs=new PrintWriter(new FileOutputStream(PREFIX+state.structfile+".struct"), true);
182 } catch (Exception e) {
187 /* Build the virtual dispatch tables */
188 buildVirtualTables(outvirtual);
190 /* Output includes */
191 outmethodheader.println("#ifndef METHODHEADERS_H");
192 outmethodheader.println("#define METHODHEADERS_H");
193 outmethodheader.println("#include \"structdefs.h\"");
195 outmethodheader.println("#include \"dstm.h\"");
197 outmethodheader.println("#include \"sandbox.h\"");
199 if (state.EVENTMONITOR) {
200 outmethodheader.println("#include \"monitor.h\"");
202 if (state.SINGLETM) {
203 outmethodheader.println("#include \"tm.h\"");
204 outmethodheader.println("#include \"delaycomp.h\"");
205 outmethodheader.println("#include \"inlinestm.h\"");
207 if (state.ABORTREADERS) {
208 outmethodheader.println("#include \"abortreaders.h\"");
209 outmethodheader.println("#include <setjmp.h>");
211 if (state.MLP || state.OOOJAVA) {
212 outmethodheader.println("#include <stdlib.h>");
213 outmethodheader.println("#include <stdio.h>");
214 outmethodheader.println("#include <string.h>");
215 outmethodheader.println("#include \"mlp_runtime.h\"");
216 outmethodheader.println("#include \"psemaphore.h\"");
219 /* Output Structures */
220 outputStructs(outstructs);
222 // Output the C class declarations
223 // These could mutually reference each other
226 outclassdefs.println("#ifndef __CLASSDEF_H_");
227 outclassdefs.println("#define __CLASSDEF_H_");
228 outputClassDeclarations(outclassdefs);
230 // Output function prototypes and structures for parameters
231 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
232 while(it.hasNext()) {
233 ClassDescriptor cn=(ClassDescriptor)it.next();
234 generateCallStructs(cn, outclassdefs, outstructs, outmethodheader);
236 outclassdefs.println("#endif");
237 outclassdefs.close();
240 /* Map flags to integers */
241 /* The runtime keeps track of flags using these integers */
242 it=state.getClassSymbolTable().getDescriptorsIterator();
243 while(it.hasNext()) {
244 ClassDescriptor cn=(ClassDescriptor)it.next();
248 generateTaskStructs(outstructs, outmethodheader);
250 /* Outputs generic task structures if this is a task
252 outputTaskTypes(outtask);
255 if( state.MLP || state.OOOJAVA) {
256 // have to initialize some SESE compiler data before
257 // analyzing normal methods, which must happen before
258 // generating SESE internal code
260 Iterator<FlatSESEEnterNode> seseit;
262 seseit=mlpa.getAllSESEs().iterator();
264 seseit=oooa.getAllSESEs().iterator();
267 //TODO signal the object that will report errors
270 rcr = new RuntimeConflictResolver(PREFIX);
272 catch (FileNotFoundException e) {
273 System.out.println("Runtime Conflict Resolver could not create output file.");
277 while(seseit.hasNext()){
278 FlatSESEEnterNode fsen = seseit.next();
279 initializeSESE( fsen );
281 if(state.RCR && rcr != null){
282 Analysis.OoOJava.ConflictGraph conflictGraph;
283 Hashtable<Taint, Set<Effect>> conflicts;
284 if(!fsen.getIsCallerSESEplaceholder() && fsen.getParent()!=null &&
285 (conflictGraph = oooa.getConflictGraph(fsen.getParent())) != null &&
286 (conflicts = conflictGraph.getConflictEffectSet(fsen)) != null){
288 FlatMethod fm=fsen.getfmEnclosing();
291 ReachGraph rg=oooa.getDisjointAnalysis().getReachGraph(fm.getMethod());
293 //TODO remove this later
294 rg.writeGraph("RCRDEBUG");
297 Hashtable<Taint, Set<Effect>> effects=oooa.getDisjointAnalysis().getEffectsAnalysis().get(fsen);
299 rcr.traverse(fsen, effects, conflicts, rg);
306 System.out.println("Runtime Conflict Resolver Done.");
310 /* Build the actual methods */
311 outputMethods(outmethod);
313 // Output function prototypes and structures for SESE's and code
314 if( state.MLP || state.OOOJAVA ) {
316 // used to differentiate, during code generation, whether we are
317 // passing over SESE body code, or non-SESE code
320 // first generate code for each sese's internals
321 Iterator<FlatSESEEnterNode> seseit;
323 seseit=mlpa.getAllSESEs().iterator();
325 seseit=oooa.getAllSESEs().iterator();
328 while(seseit.hasNext()) {
329 FlatSESEEnterNode fsen = seseit.next();
330 generateMethodSESE(fsen, null, outstructs, outmethodheader, outmethod);
333 // then write the invokeSESE switch to decouple scheduler
334 // from having to do unique details of sese invocation
335 generateSESEinvocationMethod(outmethodheader, outmethod);
339 /* Output code for tasks */
340 outputTaskCode(outtaskdefs, outmethod);
342 /* Record maximum number of task parameters */
343 outstructs.println("#define MAXTASKPARAMS "+maxtaskparams);
344 } else if (state.main!=null) {
345 /* Generate main method */
346 outputMainMethod(outmethod);
349 /* Generate information for task with optional parameters */
350 if (state.TASK&&state.OPTIONAL) {
351 generateOptionalArrays(outoptionalarrays, optionalheaders, state.getAnalysisResult(), state.getOptionalTaskDescriptors());
352 outoptionalarrays.close();
355 /* Output structure definitions for repair tool */
356 if (state.structfile!=null) {
357 buildRepairStructs(outrepairstructs);
358 outrepairstructs.close();
362 outmethodheader.println("#endif");
363 outmethodheader.close();
365 outstructs.println("#endif");
370 /* This code just generates the main C method for java programs.
371 * The main C method packs up the arguments into a string array
372 * and passes it to the java main method. */
374 private void outputMainMethod(PrintWriter outmethod) {
375 outmethod.println("int main(int argc, const char *argv[]) {");
376 outmethod.println(" int i;");
378 if (state.MLP || state.OOOJAVA) {
379 //outmethod.println(" pthread_once( &mlpOnceObj, mlpInitOncePerThread );");
381 outmethod.println(" workScheduleInit( "+state.MLP_NUMCORES+", invokeSESEmethod );");
385 if (state.DSMRECOVERYSTATS) {
386 outmethod.println("#ifdef RECOVERYSTATS \n");
387 outmethod.println("handle();\n");
388 outmethod.println("#endif\n");
390 outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n");
391 outmethod.println("handle();\n");
392 outmethod.println("#endif\n");
396 if (state.THREAD||state.DSM||state.SINGLETM) {
397 outmethod.println("initializethreads();");
400 outmethod.println("if (dstmStartup(argv[1])) {");
401 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
402 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-2);");
404 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-2);");
407 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
408 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1);");
410 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1);");
414 outmethod.println(" for(i=2;i<argc;i++) {");
416 outmethod.println(" for(i=1;i<argc;i++) {");
417 outmethod.println(" int length=strlen(argv[i]);");
418 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
419 outmethod.println(" struct ___String___ *newstring=NewString(NULL, argv[i], length);");
421 outmethod.println(" struct ___String___ *newstring=NewString(argv[i], length);");
424 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-2]=newstring;");
426 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-1]=newstring;");
427 outmethod.println(" }");
429 MethodDescriptor md=typeutil.getMain();
430 ClassDescriptor cd=typeutil.getMainClass();
432 outmethod.println(" {");
433 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
434 if (state.DSM||state.SINGLETM) {
435 outmethod.print(" struct "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
437 outmethod.print(" struct "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
438 outmethod.println("1, NULL,"+"stringarray};");
439 if (state.DSM||state.SINGLETM)
440 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
442 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
444 if (state.DSM||state.SINGLETM)
445 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
447 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
449 outmethod.println(" }");
452 outmethod.println("}");
455 if (state.THREAD||state.DSM||state.SINGLETM) {
456 outmethod.println("pthread_mutex_lock(&gclistlock);");
457 outmethod.println("threadcount--;");
458 outmethod.println("pthread_cond_signal(&gccond);");
459 outmethod.println("pthread_mutex_unlock(&gclistlock);");
462 if (state.DSM||state.SINGLETM) {
463 //outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n");
464 outmethod.println("#if defined(TRANSSTATS) \n");
465 outmethod.println("printf(\"****** Transaction Stats ******\\n\");");
466 outmethod.println("printf(\"numTransCommit= %d\\n\", numTransCommit);");
467 outmethod.println("printf(\"numTransAbort= %d\\n\", numTransAbort);");
468 outmethod.println("printf(\"nSoftAbort= %d\\n\", nSoftAbort);");
470 outmethod.println("printf(\"nchashSearch= %d\\n\", nchashSearch);");
471 outmethod.println("printf(\"nmhashSearch= %d\\n\", nmhashSearch);");
472 outmethod.println("printf(\"nprehashSearch= %d\\n\", nprehashSearch);");
473 outmethod.println("printf(\"ndirtyCacheObj= %d\\n\", ndirtyCacheObj);");
474 outmethod.println("printf(\"nRemoteReadSend= %d\\n\", nRemoteSend);");
475 outmethod.println("printf(\"bytesSent= %d\\n\", bytesSent);");
476 outmethod.println("printf(\"bytesRecv= %d\\n\", bytesRecv);");
477 outmethod.println("printf(\"totalObjSize= %d\\n\", totalObjSize);");
478 outmethod.println("printf(\"sendRemoteReq= %d\\n\", sendRemoteReq);");
479 outmethod.println("printf(\"getResponse= %d\\n\", getResponse);");
480 } else if (state.SINGLETM) {
481 outmethod.println("printf(\"nSoftAbortAbort= %d\\n\", nSoftAbortAbort);");
482 outmethod.println("printf(\"nSoftAbortCommit= %d\\n\", nSoftAbortCommit);");
483 outmethod.println("#ifdef STMSTATS\n");
484 outmethod.println("for(i=0; i<TOTALNUMCLASSANDARRAY; i++) {\n");
485 outmethod.println(" printf(\"typesCausingAbort[%2d] numaccess= %5d numabort= %3d\\n\", i, typesCausingAbort[i].numaccess, typesCausingAbort[i].numabort);\n");
486 outmethod.println("}\n");
487 outmethod.println("#endif\n");
488 outmethod.println("fflush(stdout);");
490 outmethod.println("#endif\n");
493 if (state.EVENTMONITOR) {
494 outmethod.println("dumpdata();");
497 if (state.THREAD||state.SINGLETM)
498 outmethod.println("pthread_exit(NULL);");
500 if (state.MLP || state.OOOJAVA ) {
501 outmethod.println(" workScheduleBegin();");
504 outmethod.println("}");
507 /* This method outputs code for each task. */
509 private void outputTaskCode(PrintWriter outtaskdefs, PrintWriter outmethod) {
510 /* Compile task based program */
511 outtaskdefs.println("#include \"task.h\"");
512 outtaskdefs.println("#include \"methodheaders.h\"");
513 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
514 while(taskit.hasNext()) {
515 TaskDescriptor td=(TaskDescriptor)taskit.next();
516 FlatMethod fm=state.getMethodFlat(td);
517 generateFlatMethod(fm, null, outmethod);
518 generateTaskDescriptor(outtaskdefs, fm, td);
521 //Output task descriptors
522 taskit=state.getTaskSymbolTable().getDescriptorsIterator();
523 outtaskdefs.println("struct taskdescriptor * taskarray[]= {");
525 while(taskit.hasNext()) {
526 TaskDescriptor td=(TaskDescriptor)taskit.next();
530 outtaskdefs.println(",");
531 outtaskdefs.print("&task_"+td.getSafeSymbol());
533 outtaskdefs.println("};");
535 outtaskdefs.println("int numtasks="+state.getTaskSymbolTable().getValueSet().size()+";");
538 /* This method outputs most of the methods.c file. This includes
539 * some standard includes and then an array with the sizes of
540 * objets and array that stores supertype and then the code for
541 * the Java methods.. */
543 protected void outputMethods(PrintWriter outmethod) {
544 outmethod.println("#include \"methodheaders.h\"");
545 outmethod.println("#include \"virtualtable.h\"");
546 outmethod.println("#include \"runtime.h\"");
548 outmethod.println("#include \"sandboxdefs.c\"");
551 outmethod.println("#include \"addPrefetchEnhance.h\"");
552 outmethod.println("#include \"localobjects.h\"");
554 if (state.FASTCHECK) {
555 outmethod.println("#include \"localobjects.h\"");
557 if(state.MULTICORE) {
558 outmethod.println("#include \"task.h\"");
559 outmethod.println("#include \"multicoreruntime.h\"");
560 outmethod.println("#include \"runtime_arch.h\"");
562 if (state.THREAD||state.DSM||state.SINGLETM)
563 outmethod.println("#include <thread.h>");
564 if (state.main!=null) {
565 outmethod.println("#include <string.h>");
567 if (state.CONSCHECK) {
568 outmethod.println("#include \"checkers.h\"");
570 if (state.MLP || state.OOOJAVA ) {
571 outmethod.println("#include <stdlib.h>");
572 outmethod.println("#include <stdio.h>");
573 outmethod.println("#include \"mlp_runtime.h\"");
574 outmethod.println("#include \"psemaphore.h\"");
577 outmethod.println("#include \"RuntimeConflictResolver.h\"");
580 if (state.COREPROF) {
581 outmethod.println("#include \"coreprof.h\"");
584 //Store the sizes of classes & array elements
585 generateSizeArray(outmethod);
587 //Store table of supertypes
588 generateSuperTypeTable(outmethod);
590 //Store the layout of classes
591 generateLayoutStructs(outmethod);
593 /* Generate code for methods */
594 if (state.DSM||state.SINGLETM) {
595 for(Iterator<LocalityBinding> lbit=locality.getLocalityBindings().iterator(); lbit.hasNext();) {
596 LocalityBinding lb=lbit.next();
597 MethodDescriptor md=lb.getMethod();
598 FlatMethod fm=state.getMethodFlat(md);
600 if (!md.getModifiers().isNative()) {
601 generateFlatMethod(fm, lb, outmethod);
602 //System.out.println("fm= " + fm + " md= " + md);
606 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
607 while(classit.hasNext()) {
608 ClassDescriptor cn=(ClassDescriptor)classit.next();
609 Iterator methodit=cn.getMethods();
610 while(methodit.hasNext()) {
611 /* Classify parameters */
612 MethodDescriptor md=(MethodDescriptor)methodit.next();
613 FlatMethod fm=state.getMethodFlat(md);
614 if (!md.getModifiers().isNative()) {
615 generateFlatMethod(fm, null, outmethod);
622 protected void outputStructs(PrintWriter outstructs) {
623 outstructs.println("#ifndef STRUCTDEFS_H");
624 outstructs.println("#define STRUCTDEFS_H");
625 outstructs.println("#include \"classdefs.h\"");
626 outstructs.println("#ifndef INTPTR");
627 outstructs.println("#ifdef BIT64");
628 outstructs.println("#define INTPTR long");
629 outstructs.println("#else");
630 outstructs.println("#define INTPTR int");
631 outstructs.println("#endif");
632 outstructs.println("#endif");
633 if( state.MLP || state.OOOJAVA ) {
634 outstructs.println("#include \"mlp_runtime.h\"");
635 outstructs.println("#include \"psemaphore.h\"");
638 /* Output #defines that the runtime uses to determine type
639 * numbers for various objects it needs */
640 outstructs.println("#define MAXCOUNT "+maxcount);
641 if (state.DSM||state.SINGLETM) {
642 LocalityBinding lbrun=new LocalityBinding(typeutil.getRun(), false);
644 lbrun.setGlobalThis(LocalityAnalysis.GLOBAL);
646 else if (state.SINGLETM) {
647 lbrun.setGlobalThis(LocalityAnalysis.NORMAL);
649 outstructs.println("#define RUNMETHOD "+virtualcalls.getLocalityNumber(lbrun));
653 LocalityBinding lbexecute = new LocalityBinding(typeutil.getExecute(), false);
655 lbexecute.setGlobalThis(LocalityAnalysis.GLOBAL);
656 else if( state.SINGLETM)
657 lbexecute.setGlobalThis(LocalityAnalysis.NORMAL);
658 outstructs.println("#define EXECUTEMETHOD " + virtualcalls.getLocalityNumber(lbexecute));
661 outstructs.println("#define STRINGARRAYTYPE "+
662 (state.getArrayNumber(
663 (new TypeDescriptor(typeutil.getClass(TypeUtil.StringClass))).makeArray(state))+state.numClasses()));
665 outstructs.println("#define OBJECTARRAYTYPE "+
666 (state.getArrayNumber(
667 (new TypeDescriptor(typeutil.getClass(TypeUtil.ObjectClass))).makeArray(state))+state.numClasses()));
670 outstructs.println("#define STRINGTYPE "+typeutil.getClass(TypeUtil.StringClass).getId());
671 outstructs.println("#define CHARARRAYTYPE "+
672 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.CHAR)).makeArray(state))+state.numClasses()));
674 outstructs.println("#define BYTEARRAYTYPE "+
675 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state))+state.numClasses()));
677 outstructs.println("#define BYTEARRAYARRAYTYPE "+
678 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state).makeArray(state))+state.numClasses()));
680 outstructs.println("#define NUMCLASSES "+state.numClasses());
681 int totalClassSize = state.numClasses() + state.numArrays();
682 outstructs.println("#define TOTALNUMCLASSANDARRAY "+ totalClassSize);
684 outstructs.println("#define STARTUPTYPE "+typeutil.getClass(TypeUtil.StartupClass).getId());
685 outstructs.println("#define TAGTYPE "+typeutil.getClass(TypeUtil.TagClass).getId());
686 outstructs.println("#define TAGARRAYTYPE "+
687 (state.getArrayNumber(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)).makeArray(state))+state.numClasses()));
691 protected void outputClassDeclarations(PrintWriter outclassdefs) {
692 if (state.THREAD||state.DSM||state.SINGLETM)
693 outclassdefs.println("#include <pthread.h>");
694 outclassdefs.println("#ifndef INTPTR");
695 outclassdefs.println("#ifdef BIT64");
696 outclassdefs.println("#define INTPTR long");
697 outclassdefs.println("#else");
698 outclassdefs.println("#define INTPTR int");
699 outclassdefs.println("#endif");
700 outclassdefs.println("#endif");
702 outclassdefs.println("#include \"optionalstruct.h\"");
703 outclassdefs.println("struct "+arraytype+";");
704 /* Start by declaring all structs */
705 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
706 while(it.hasNext()) {
707 ClassDescriptor cn=(ClassDescriptor)it.next();
708 outclassdefs.println("struct "+cn.getSafeSymbol()+";");
710 outclassdefs.println("");
711 //Print out definition for array type
712 outclassdefs.println("struct "+arraytype+" {");
713 outclassdefs.println(" int type;");
714 if(state.MLP || state.OOOJAVA ){
715 outclassdefs.println(" int oid;");
716 outclassdefs.println(" int allocsite;");
718 if (state.EVENTMONITOR) {
719 outclassdefs.println(" int objuid;");
722 outclassdefs.println(" pthread_t tid;");
723 outclassdefs.println(" void * lockentry;");
724 outclassdefs.println(" int lockcount;");
727 outclassdefs.println(" int flag;");
728 if(!state.MULTICORE) {
729 outclassdefs.println(" void * flagptr;");
731 outclassdefs.println(" int version;");
732 outclassdefs.println(" int * lock;"); // lock entry for this obj
733 outclassdefs.println(" int mutex;");
734 outclassdefs.println(" int lockcount;");
735 if(state.MULTICOREGC) {
736 outclassdefs.println(" int marked;");
740 outclassdefs.println(" int numfses;");
741 outclassdefs.println(" int * fses;");
744 printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs);
746 if (state.STMARRAY) {
747 outclassdefs.println(" int lowindex;");
748 outclassdefs.println(" int highindex;");
751 outclassdefs.println(" int paddingforarray;");
752 if (state.DUALVIEW) {
753 outclassdefs.println(" int arrayversion;");
756 outclassdefs.println(" int ___length___;");
757 outclassdefs.println("};\n");
758 outclassdefs.println("extern int classsize[];");
759 outclassdefs.println("extern int hasflags[];");
760 outclassdefs.println("extern unsigned INTPTR * pointerarray[];");
761 outclassdefs.println("extern int supertypes[];");
764 /** Prints out definitions for generic task structures */
766 private void outputTaskTypes(PrintWriter outtask) {
767 outtask.println("#ifndef _TASK_H");
768 outtask.println("#define _TASK_H");
769 outtask.println("struct parameterdescriptor {");
770 outtask.println("int type;");
771 outtask.println("int numberterms;");
772 outtask.println("int *intarray;");
773 outtask.println("void * queue;");
774 outtask.println("int numbertags;");
775 outtask.println("int *tagarray;");
776 outtask.println("};");
778 outtask.println("struct taskdescriptor {");
779 outtask.println("void * taskptr;");
780 outtask.println("int numParameters;");
781 outtask.println(" int numTotal;");
782 outtask.println("struct parameterdescriptor **descriptorarray;");
783 outtask.println("char * name;");
784 outtask.println("};");
785 outtask.println("extern struct taskdescriptor * taskarray[];");
786 outtask.println("extern numtasks;");
787 outtask.println("#endif");
791 private void buildRepairStructs(PrintWriter outrepairstructs) {
792 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
793 while(classit.hasNext()) {
794 ClassDescriptor cn=(ClassDescriptor)classit.next();
795 outrepairstructs.println("structure "+cn.getSymbol()+" {");
796 outrepairstructs.println(" int __type__;");
798 outrepairstructs.println(" int __flag__;");
799 if(!state.MULTICORE) {
800 outrepairstructs.println(" int __flagptr__;");
803 printRepairStruct(cn, outrepairstructs);
804 outrepairstructs.println("}\n");
807 for(int i=0; i<state.numArrays(); i++) {
808 TypeDescriptor tdarray=arraytable[i];
809 TypeDescriptor tdelement=tdarray.dereference();
810 outrepairstructs.println("structure "+arraytype+"_"+state.getArrayNumber(tdarray)+" {");
811 outrepairstructs.println(" int __type__;");
812 printRepairStruct(typeutil.getClass(TypeUtil.ObjectClass), outrepairstructs);
813 outrepairstructs.println(" int length;");
815 // Need to add support to repair tool for this
816 if (tdelement.isClass()||tdelement.isArray())
817 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" * elem[this.length];");
819 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" elem[this.length];");
821 outrepairstructs.println("}\n");
825 private void printRepairStruct(ClassDescriptor cn, PrintWriter output) {
826 ClassDescriptor sp=cn.getSuperDesc();
828 printRepairStruct(sp, output);
830 Vector fields=(Vector)fieldorder.get(cn);
832 for(int i=0; i<fields.size(); i++) {
833 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
834 if (fd.getType().isArray()) {
835 output.println(" "+arraytype+"_"+ state.getArrayNumber(fd.getType()) +" * "+fd.getSymbol()+";");
836 } else if (fd.getType().isClass())
837 output.println(" "+fd.getType().getRepairSymbol()+" * "+fd.getSymbol()+";");
838 else if (fd.getType().isFloat())
839 output.println(" int "+fd.getSymbol()+"; /* really float */");
841 output.println(" "+fd.getType().getRepairSymbol()+" "+fd.getSymbol()+";");
845 /** This method outputs TaskDescriptor information */
846 private void generateTaskDescriptor(PrintWriter output, FlatMethod fm, TaskDescriptor task) {
847 for (int i=0; i<task.numParameters(); i++) {
848 VarDescriptor param_var=task.getParameter(i);
849 TypeDescriptor param_type=task.getParamType(i);
850 FlagExpressionNode param_flag=task.getFlag(param_var);
851 TagExpressionList param_tag=task.getTag(param_var);
854 if (param_flag==null) {
855 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
856 output.println("0x0, 0x0 };");
859 DNFFlag dflag=param_flag.getDNF();
860 dnfterms=dflag.size();
862 Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
863 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
864 for(int j=0; j<dflag.size(); j++) {
867 Vector term=dflag.get(j);
870 for(int k=0; k<term.size(); k++) {
871 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
872 FlagDescriptor fd=dfa.getFlag();
873 boolean negated=dfa.getNegated();
874 int flagid=1<<((Integer)flags.get(fd)).intValue();
879 output.print("0x"+Integer.toHexString(andmask)+", 0x"+Integer.toHexString(checkmask));
881 output.println("};");
884 output.println("int parametertag_"+i+"_"+task.getSafeSymbol()+"[]={");
885 //BUG...added next line to fix, test with any task program
887 for(int j=0; j<param_tag.numTags(); j++) {
890 /* for each tag we need */
891 /* which slot it is */
892 /* what type it is */
893 TagVarDescriptor tvd=(TagVarDescriptor)task.getParameterTable().get(param_tag.getName(j));
894 TempDescriptor tmp=param_tag.getTemp(j);
895 int slot=fm.getTagInt(tmp);
896 output.println(slot+", "+state.getTagId(tvd.getTag()));
898 output.println("};");
900 output.println("struct parameterdescriptor parameter_"+i+"_"+task.getSafeSymbol()+"={");
901 output.println("/* type */"+param_type.getClassDesc().getId()+",");
902 output.println("/* number of DNF terms */"+dnfterms+",");
903 output.println("parameterdnf_"+i+"_"+task.getSafeSymbol()+",");
904 output.println("0,");
905 //BUG, added next line to fix and else statement...test
906 //with any task program
908 output.println("/* number of tags */"+param_tag.numTags()+",");
910 output.println("/* number of tags */ 0,");
911 output.println("parametertag_"+i+"_"+task.getSafeSymbol());
912 output.println("};");
916 output.println("struct parameterdescriptor * parameterdescriptors_"+task.getSafeSymbol()+"[] = {");
917 for (int i=0; i<task.numParameters(); i++) {
920 output.print("¶meter_"+i+"_"+task.getSafeSymbol());
922 output.println("};");
924 output.println("struct taskdescriptor task_"+task.getSafeSymbol()+"={");
925 output.println("&"+task.getSafeSymbol()+",");
926 output.println("/* number of parameters */" +task.numParameters() + ",");
927 int numtotal=task.numParameters()+fm.numTags();
928 output.println("/* number total parameters */" +numtotal + ",");
929 output.println("parameterdescriptors_"+task.getSafeSymbol()+",");
930 output.println("\""+task.getSymbol()+"\"");
931 output.println("};");
935 /** The buildVirtualTables method outputs the virtual dispatch
936 * tables for methods. */
938 protected void buildVirtualTables(PrintWriter outvirtual) {
939 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
940 while(classit.hasNext()) {
941 ClassDescriptor cd=(ClassDescriptor)classit.next();
942 if (virtualcalls.getMethodCount(cd)>maxcount)
943 maxcount=virtualcalls.getMethodCount(cd);
945 MethodDescriptor[][] virtualtable=null;
946 LocalityBinding[][] lbvirtualtable=null;
947 if (state.DSM||state.SINGLETM)
948 lbvirtualtable=new LocalityBinding[state.numClasses()+state.numArrays()][maxcount];
950 virtualtable=new MethodDescriptor[state.numClasses()+state.numArrays()][maxcount];
952 /* Fill in virtual table */
953 classit=state.getClassSymbolTable().getDescriptorsIterator();
954 while(classit.hasNext()) {
955 ClassDescriptor cd=(ClassDescriptor)classit.next();
956 if (state.DSM||state.SINGLETM)
957 fillinRow(cd, lbvirtualtable, cd.getId());
959 fillinRow(cd, virtualtable, cd.getId());
962 ClassDescriptor objectcd=typeutil.getClass(TypeUtil.ObjectClass);
963 Iterator arrayit=state.getArrayIterator();
964 while(arrayit.hasNext()) {
965 TypeDescriptor td=(TypeDescriptor)arrayit.next();
966 int id=state.getArrayNumber(td);
967 if (state.DSM||state.SINGLETM)
968 fillinRow(objectcd, lbvirtualtable, id+state.numClasses());
970 fillinRow(objectcd, virtualtable, id+state.numClasses());
973 outvirtual.print("void * virtualtable[]={");
974 boolean needcomma=false;
975 for(int i=0; i<state.numClasses()+state.numArrays(); i++) {
976 for(int j=0; j<maxcount; j++) {
978 outvirtual.print(", ");
979 if ((state.DSM||state.SINGLETM)&&lbvirtualtable[i][j]!=null) {
980 LocalityBinding lb=lbvirtualtable[i][j];
981 MethodDescriptor md=lb.getMethod();
982 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
983 } else if (!(state.DSM||state.SINGLETM)&&virtualtable[i][j]!=null) {
984 MethodDescriptor md=virtualtable[i][j];
985 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
987 outvirtual.print("0");
991 outvirtual.println("");
993 outvirtual.println("};");
997 private void fillinRow(ClassDescriptor cd, MethodDescriptor[][] virtualtable, int rownum) {
998 /* Get inherited methods */
999 if (cd.getSuperDesc()!=null)
1000 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
1001 /* Override them with our methods */
1002 for(Iterator it=cd.getMethods(); it.hasNext();) {
1003 MethodDescriptor md=(MethodDescriptor)it.next();
1004 if (md.isStatic()||md.getReturnType()==null)
1006 int methodnum=virtualcalls.getMethodNumber(md);
1007 virtualtable[rownum][methodnum]=md;
1011 private void fillinRow(ClassDescriptor cd, LocalityBinding[][] virtualtable, int rownum) {
1012 /* Get inherited methods */
1013 if (cd.getSuperDesc()!=null)
1014 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
1015 /* Override them with our methods */
1016 if (locality.getClassBindings(cd)!=null)
1017 for(Iterator<LocalityBinding> lbit=locality.getClassBindings(cd).iterator(); lbit.hasNext();) {
1018 LocalityBinding lb=lbit.next();
1019 MethodDescriptor md=lb.getMethod();
1020 //Is the method static or a constructor
1021 if (md.isStatic()||md.getReturnType()==null)
1023 int methodnum=virtualcalls.getLocalityNumber(lb);
1024 virtualtable[rownum][methodnum]=lb;
1028 /** Generate array that contains the sizes of class objects. The
1029 * object allocation functions in the runtime use this
1032 private void generateSizeArray(PrintWriter outclassdefs) {
1033 outclassdefs.print("extern struct prefetchCountStats * evalPrefetch;\n");
1034 outclassdefs.print("#ifdef TRANSSTATS \n");
1035 outclassdefs.print("extern int numTransAbort;\n");
1036 outclassdefs.print("extern int numTransCommit;\n");
1037 outclassdefs.print("extern int nSoftAbort;\n");
1039 outclassdefs.print("extern int nchashSearch;\n");
1040 outclassdefs.print("extern int nmhashSearch;\n");
1041 outclassdefs.print("extern int nprehashSearch;\n");
1042 outclassdefs.print("extern int ndirtyCacheObj;\n");
1043 outclassdefs.print("extern int nRemoteSend;\n");
1044 outclassdefs.print("extern int sendRemoteReq;\n");
1045 outclassdefs.print("extern int getResponse;\n");
1046 outclassdefs.print("extern int bytesSent;\n");
1047 outclassdefs.print("extern int bytesRecv;\n");
1048 outclassdefs.print("extern int totalObjSize;\n");
1049 outclassdefs.print("extern void handle();\n");
1050 } else if (state.SINGLETM) {
1051 outclassdefs.println("extern int nSoftAbortAbort;");
1052 outclassdefs.println("extern int nSoftAbortCommit;");
1053 outclassdefs.println("#ifdef STMSTATS\n");
1054 outclassdefs.println("extern objtypestat_t typesCausingAbort[];");
1055 outclassdefs.println("#endif\n");
1057 outclassdefs.print("#endif\n");
1059 outclassdefs.print("int numprefetchsites = " + pa.prefetchsiteid + ";\n");
1060 if(this.state.MLP || state.OOOJAVA ){
1061 outclassdefs.print("extern __thread int oid;\n");
1062 outclassdefs.print("extern int numWorkers;\n");
1065 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1066 cdarray=new ClassDescriptor[state.numClasses()];
1068 while(it.hasNext()) {
1069 ClassDescriptor cd=(ClassDescriptor)it.next();
1070 cdarray[cd.getId()]=cd;
1073 arraytable=new TypeDescriptor[state.numArrays()];
1075 Iterator arrayit=state.getArrayIterator();
1076 while(arrayit.hasNext()) {
1077 TypeDescriptor td=(TypeDescriptor)arrayit.next();
1078 int id=state.getArrayNumber(td);
1084 /* Print out types */
1085 outclassdefs.println("/* ");
1086 for(int i=0; i<state.numClasses(); i++) {
1087 ClassDescriptor cd=cdarray[i];
1089 outclassdefs.println("NULL " + i);
1091 outclassdefs.println(cd +" "+i);
1095 for(int i=0; i<state.numArrays(); i++) {
1096 TypeDescriptor arraytd=arraytable[i];
1097 outclassdefs.println(arraytd.toPrettyString() +" "+(i+state.numClasses()));
1100 outclassdefs.println("*/");
1103 outclassdefs.print("int classsize[]={");
1105 boolean needcomma=false;
1106 for(int i=0; i<state.numClasses(); i++) {
1108 outclassdefs.print(", ");
1110 outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")");
1112 outclassdefs.print("0");
1118 for(int i=0; i<state.numArrays(); i++) {
1120 outclassdefs.print(", ");
1121 TypeDescriptor tdelement=arraytable[i].dereference();
1122 if (tdelement.isArray()||tdelement.isClass())
1123 outclassdefs.print("sizeof(void *)");
1125 outclassdefs.print("sizeof("+tdelement.getSafeSymbol()+")");
1129 outclassdefs.println("};");
1131 ClassDescriptor objectclass=typeutil.getClass(TypeUtil.ObjectClass);
1133 outclassdefs.print("int typearray[]={");
1134 for(int i=0; i<state.numClasses(); i++) {
1135 ClassDescriptor cd=cdarray[i];
1136 ClassDescriptor supercd=i>0?cd.getSuperDesc():null;
1138 outclassdefs.print(", ");
1140 outclassdefs.print("-1");
1142 outclassdefs.print(supercd.getId());
1146 for(int i=0; i<state.numArrays(); i++) {
1147 TypeDescriptor arraytd=arraytable[i];
1148 ClassDescriptor arraycd=arraytd.getClassDesc();
1149 if (arraycd==null) {
1151 outclassdefs.print(", ");
1152 outclassdefs.print(objectclass.getId());
1156 ClassDescriptor cd=arraycd.getSuperDesc();
1159 TypeDescriptor supertd=new TypeDescriptor(cd);
1160 supertd.setArrayCount(arraytd.getArrayCount());
1161 type=state.getArrayNumber(supertd);
1163 type+=state.numClasses();
1166 cd=cd.getSuperDesc();
1169 outclassdefs.print(", ");
1170 outclassdefs.print(type);
1174 outclassdefs.println("};");
1179 outclassdefs.print("int typearray2[]={");
1180 for(int i=0; i<state.numArrays(); i++) {
1181 TypeDescriptor arraytd=arraytable[i];
1182 ClassDescriptor arraycd=arraytd.getClassDesc();
1183 if (arraycd==null) {
1185 outclassdefs.print(", ");
1186 outclassdefs.print("-1");
1190 ClassDescriptor cd=arraycd.getSuperDesc();
1191 int level=arraytd.getArrayCount()-1;
1193 for(; level>0; level--) {
1194 TypeDescriptor supertd=new TypeDescriptor(objectclass);
1195 supertd.setArrayCount(level);
1196 type=state.getArrayNumber(supertd);
1198 type+=state.numClasses();
1203 outclassdefs.print(", ");
1204 outclassdefs.print(type);
1208 outclassdefs.println("};");
1211 /** Constructs params and temp objects for each method or task.
1212 * These objects tell the compiler which temps need to be
1215 protected void generateTempStructs(FlatMethod fm, LocalityBinding lb) {
1216 MethodDescriptor md=fm.getMethod();
1217 TaskDescriptor task=fm.getTask();
1218 Set<TempDescriptor> saveset=lb!=null ? locality.getTempSet(lb) : null;
1219 ParamsObject objectparams=md!=null ? new ParamsObject(md,tag++) : new ParamsObject(task, tag++);
1221 paramstable.put(lb, objectparams);
1222 backuptable.put(lb, new Hashtable<TempDescriptor, TempDescriptor>());
1223 } else if (md!=null)
1224 paramstable.put(md, objectparams);
1226 paramstable.put(task, objectparams);
1228 for(int i=0; i<fm.numParameters(); i++) {
1229 TempDescriptor temp=fm.getParameter(i);
1230 TypeDescriptor type=temp.getType();
1231 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1232 objectparams.addPtr(temp);
1234 objectparams.addPrim(temp);
1235 if(lb!=null&&saveset.contains(temp)) {
1236 backuptable.get(lb).put(temp, temp.createNew());
1240 for(int i=0; i<fm.numTags(); i++) {
1241 TempDescriptor temp=fm.getTag(i);
1242 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1243 objectparams.addPtr(temp);
1245 objectparams.addPrim(temp);
1248 TempObject objecttemps=md!=null ? new TempObject(objectparams,md,tag++) : new TempObject(objectparams, task, tag++);
1250 tempstable.put(lb, objecttemps);
1252 tempstable.put(md, objecttemps);
1254 tempstable.put(task, objecttemps);
1256 for(Iterator nodeit=fm.getNodeSet().iterator(); nodeit.hasNext();) {
1257 FlatNode fn=(FlatNode)nodeit.next();
1258 TempDescriptor[] writes=fn.writesTemps();
1259 for(int i=0; i<writes.length; i++) {
1260 TempDescriptor temp=writes[i];
1261 TypeDescriptor type=temp.getType();
1262 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1263 objecttemps.addPtr(temp);
1265 objecttemps.addPrim(temp);
1266 if(lb!=null&&saveset.contains(temp)&&
1267 !backuptable.get(lb).containsKey(temp))
1268 backuptable.get(lb).put(temp, temp.createNew());
1272 /* Create backup temps */
1274 for(Iterator<TempDescriptor> tmpit=backuptable.get(lb).values().iterator(); tmpit.hasNext();) {
1275 TempDescriptor tmp=tmpit.next();
1276 TypeDescriptor type=tmp.getType();
1277 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1278 objecttemps.addPtr(tmp);
1280 objecttemps.addPrim(tmp);
1282 /* Create temp to hold revert table */
1283 if (state.DSM&&(lb.getHasAtomic()||lb.isAtomic())) {
1284 TempDescriptor reverttmp=new TempDescriptor("revertlist", typeutil.getClass(TypeUtil.ObjectClass));
1285 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1286 objecttemps.addPtr(reverttmp);
1288 objecttemps.addPrim(reverttmp);
1289 reverttable.put(lb, reverttmp);
1294 /** This method outputs the following information about classes
1296 * (1) For classes, what are the locations of pointers.
1297 * (2) For arrays, does the array contain pointers or primitives.
1298 * (3) For classes, does the class contain flags.
1301 private void generateLayoutStructs(PrintWriter output) {
1302 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1303 while(it.hasNext()) {
1304 ClassDescriptor cn=(ClassDescriptor)it.next();
1305 output.println("unsigned INTPTR "+cn.getSafeSymbol()+"_pointers[]={");
1306 Iterator allit=cn.getFieldTable().getAllDescriptorsIterator();
1308 while(allit.hasNext()) {
1309 FieldDescriptor fd=(FieldDescriptor)allit.next();
1310 TypeDescriptor type=fd.getType();
1311 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1316 output.print(count);
1317 allit=cn.getFieldTable().getAllDescriptorsIterator();
1318 while(allit.hasNext()) {
1319 FieldDescriptor fd=(FieldDescriptor)allit.next();
1320 TypeDescriptor type=fd.getType();
1321 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1324 output.println(",");
1325 output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+fd.getSafeSymbol()+"))");
1328 output.println("};");
1330 output.println("unsigned INTPTR * pointerarray[]={");
1331 boolean needcomma=false;
1332 for(int i=0; i<state.numClasses(); i++) {
1333 ClassDescriptor cn=cdarray[i];
1335 output.println(",");
1338 output.print(cn.getSafeSymbol()+"_pointers");
1340 output.print("NULL");
1344 for(int i=0; i<state.numArrays(); i++) {
1346 output.println(", ");
1347 TypeDescriptor tdelement=arraytable[i].dereference();
1348 if (tdelement.isArray()||tdelement.isClass())
1349 output.print("((unsigned INTPTR *)1)");
1355 output.println("};");
1357 output.println("int hasflags[]={");
1358 for(int i=0; i<state.numClasses(); i++) {
1359 ClassDescriptor cn=cdarray[i];
1361 output.println(", ");
1363 if ((cn != null) && (cn.hasFlags()))
1368 output.println("};");
1371 /** Print out table to give us supertypes */
1372 private void generateSuperTypeTable(PrintWriter output) {
1373 output.println("int supertypes[]={");
1374 boolean needcomma=false;
1375 for(int i=0; i<state.numClasses(); i++) {
1376 ClassDescriptor cn=cdarray[i];
1378 output.println(",");
1380 if ((cn != null) && (cn.getSuperDesc()!=null)) {
1381 ClassDescriptor cdsuper=cn.getSuperDesc();
1382 output.print(cdsuper.getId());
1386 output.println("};");
1389 /** Force consistent field ordering between inherited classes. */
1391 private void printClassStruct(ClassDescriptor cn, PrintWriter classdefout) {
1393 ClassDescriptor sp=cn.getSuperDesc();
1395 printClassStruct(sp, classdefout);
1397 if (!fieldorder.containsKey(cn)) {
1398 Vector fields=new Vector();
1399 fieldorder.put(cn,fields);
1400 Vector fieldvec=cn.getFieldVec();
1401 for(int i=0;i<fieldvec.size();i++) {
1402 FieldDescriptor fd=(FieldDescriptor)fieldvec.get(i);
1403 if ((sp==null||!sp.getFieldTable().contains(fd.getSymbol())))
1407 Vector fields=(Vector)fieldorder.get(cn);
1409 for(int i=0; i<fields.size(); i++) {
1410 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
1411 if (fd.getType().isClass()||fd.getType().isArray())
1412 classdefout.println(" struct "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1414 classdefout.println(" "+fd.getType().getSafeSymbol()+" "+fd.getSafeSymbol()+";");
1419 /* Map flags to integers consistently between inherited
1422 protected void mapFlags(ClassDescriptor cn) {
1423 ClassDescriptor sp=cn.getSuperDesc();
1427 if (!flagorder.containsKey(cn)) {
1428 Hashtable flags=new Hashtable();
1429 flagorder.put(cn,flags);
1431 Hashtable superflags=(Hashtable)flagorder.get(sp);
1432 Iterator superflagit=superflags.keySet().iterator();
1433 while(superflagit.hasNext()) {
1434 FlagDescriptor fd=(FlagDescriptor)superflagit.next();
1435 Integer number=(Integer)superflags.get(fd);
1436 flags.put(fd, number);
1437 if ((number.intValue()+1)>max)
1438 max=number.intValue()+1;
1442 Iterator flagit=cn.getFlags();
1443 while(flagit.hasNext()) {
1444 FlagDescriptor fd=(FlagDescriptor)flagit.next();
1445 if (sp==null||!sp.getFlagTable().contains(fd.getSymbol()))
1446 flags.put(fd, new Integer(max++));
1452 /** This function outputs (1) structures that parameters are
1453 * passed in (when PRECISE GC is enabled) and (2) function
1454 * prototypes for the methods */
1456 protected void generateCallStructs(ClassDescriptor cn, PrintWriter classdefout, PrintWriter output, PrintWriter headersout) {
1457 /* Output class structure */
1458 classdefout.println("struct "+cn.getSafeSymbol()+" {");
1459 classdefout.println(" int type;");
1460 if(state.MLP || state.OOOJAVA){
1461 classdefout.println(" int oid;");
1462 classdefout.println(" int allocsite;");
1464 if (state.EVENTMONITOR) {
1465 classdefout.println(" int objuid;");
1468 classdefout.println(" pthread_t tid;");
1469 classdefout.println(" void * lockentry;");
1470 classdefout.println(" int lockcount;");
1474 classdefout.println(" int flag;");
1475 if((!state.MULTICORE) || (cn.getSymbol().equals("TagDescriptor"))) {
1476 classdefout.println(" void * flagptr;");
1477 } else if (state.MULTICORE) {
1478 classdefout.println(" int version;");
1479 classdefout.println(" int * lock;"); // lock entry for this obj
1480 classdefout.println(" int mutex;");
1481 classdefout.println(" int lockcount;");
1482 if(state.MULTICOREGC) {
1483 classdefout.println(" int marked;");
1486 if (state.OPTIONAL) {
1487 classdefout.println(" int numfses;");
1488 classdefout.println(" int * fses;");
1491 printClassStruct(cn, classdefout);
1492 classdefout.println("};\n");
1494 if (state.DSM||state.SINGLETM) {
1495 /* Cycle through LocalityBindings */
1496 HashSet<MethodDescriptor> nativemethods=new HashSet<MethodDescriptor>();
1497 Set<LocalityBinding> lbset=locality.getClassBindings(cn);
1499 for(Iterator<LocalityBinding> lbit=lbset.iterator(); lbit.hasNext();) {
1500 LocalityBinding lb=lbit.next();
1501 MethodDescriptor md=lb.getMethod();
1502 if (md.getModifiers().isNative()) {
1503 //make sure we only print a native method once
1504 if (nativemethods.contains(md)) {
1505 FlatMethod fm=state.getMethodFlat(md);
1506 generateTempStructs(fm, lb);
1509 nativemethods.add(md);
1511 generateMethod(cn, md, lb, headersout, output);
1514 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1515 MethodDescriptor md=(MethodDescriptor)methodit.next();
1516 if (md.getModifiers().isNative()&&!nativemethods.contains(md)) {
1517 //Need to build param structure for library code
1518 FlatMethod fm=state.getMethodFlat(md);
1519 generateTempStructs(fm, null);
1520 generateMethodParam(cn, md, null, output);
1525 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1526 MethodDescriptor md=(MethodDescriptor)methodit.next();
1527 generateMethod(cn, md, null, headersout, output);
1531 private void generateMethodParam(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter output) {
1532 /* Output parameter structure */
1533 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1534 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1535 if ((state.DSM||state.SINGLETM)&&lb!=null)
1536 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1538 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1539 output.println(" int size;");
1540 output.println(" void * next;");
1541 for(int i=0; i<objectparams.numPointers(); i++) {
1542 TempDescriptor temp=objectparams.getPointer(i);
1543 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1545 output.println("};\n");
1549 private void generateMethod(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter headersout, PrintWriter output) {
1550 FlatMethod fm=state.getMethodFlat(md);
1551 generateTempStructs(fm, lb);
1553 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1554 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md);
1556 generateMethodParam(cn, md, lb, output);
1558 /* Output temp structure */
1559 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1560 if (state.DSM||state.SINGLETM)
1561 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1563 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1564 output.println(" int size;");
1565 output.println(" void * next;");
1566 for(int i=0; i<objecttemps.numPointers(); i++) {
1567 TempDescriptor temp=objecttemps.getPointer(i);
1568 if (temp.getType().isNull())
1569 output.println(" void * "+temp.getSafeSymbol()+";");
1571 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1573 output.println("};\n");
1576 /********* Output method declaration ***********/
1577 if (state.DSM||state.SINGLETM) {
1578 headersout.println("#define D"+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1580 headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1582 /* First the return type */
1583 if (md.getReturnType()!=null) {
1584 if (md.getReturnType().isClass()||md.getReturnType().isArray())
1585 headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1587 headersout.print(md.getReturnType().getSafeSymbol()+" ");
1589 //catch the constructor case
1590 headersout.print("void ");
1592 /* Next the method name */
1593 if (state.DSM||state.SINGLETM) {
1594 headersout.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1596 headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1598 boolean printcomma=false;
1599 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1600 if (state.DSM||state.SINGLETM) {
1601 headersout.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1603 headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1607 /* Output parameter list*/
1608 for(int i=0; i<objectparams.numPrimitives(); i++) {
1609 TempDescriptor temp=objectparams.getPrimitive(i);
1611 headersout.print(", ");
1613 if (temp.getType().isClass()||temp.getType().isArray())
1614 headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1616 headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1618 headersout.println(");\n");
1622 /** This function outputs (1) structures that parameters are
1623 * passed in (when PRECISE GC is enabled) and (2) function
1624 * prototypes for the tasks */
1626 private void generateTaskStructs(PrintWriter output, PrintWriter headersout) {
1627 /* Cycle through tasks */
1628 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
1630 while(taskit.hasNext()) {
1631 /* Classify parameters */
1632 TaskDescriptor task=(TaskDescriptor)taskit.next();
1633 FlatMethod fm=state.getMethodFlat(task);
1634 generateTempStructs(fm, null);
1636 ParamsObject objectparams=(ParamsObject) paramstable.get(task);
1637 TempObject objecttemps=(TempObject) tempstable.get(task);
1639 /* Output parameter structure */
1640 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1641 output.println("struct "+task.getSafeSymbol()+"_params {");
1642 output.println(" int size;");
1643 output.println(" void * next;");
1644 for(int i=0; i<objectparams.numPointers(); i++) {
1645 TempDescriptor temp=objectparams.getPointer(i);
1646 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1649 output.println("};\n");
1650 if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
1651 maxtaskparams=objectparams.numPointers()+fm.numTags();
1655 /* Output temp structure */
1656 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1657 output.println("struct "+task.getSafeSymbol()+"_locals {");
1658 output.println(" int size;");
1659 output.println(" void * next;");
1660 for(int i=0; i<objecttemps.numPointers(); i++) {
1661 TempDescriptor temp=objecttemps.getPointer(i);
1662 if (temp.getType().isNull())
1663 output.println(" void * "+temp.getSafeSymbol()+";");
1664 else if(temp.getType().isTag())
1665 output.println(" struct "+
1666 (new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1668 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1670 output.println("};\n");
1673 /* Output task declaration */
1674 headersout.print("void " + task.getSafeSymbol()+"(");
1676 boolean printcomma=false;
1677 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1678 headersout.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
1680 headersout.print("void * parameterarray[]");
1681 headersout.println(");\n");
1685 /***** Generate code for FlatMethod fm. *****/
1687 Hashtable<FlatAtomicEnterNode, AtomicRecord> atomicmethodmap;
1688 static int atomicmethodcount=0;
1691 BranchAnalysis branchanalysis;
1692 private void generateFlatMethod(FlatMethod fm, LocalityBinding lb, PrintWriter output) {
1693 if (State.PRINTFLAT)
1694 System.out.println(fm.printMethod());
1695 MethodDescriptor md=fm.getMethod();
1696 TaskDescriptor task=fm.getTask();
1697 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
1698 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : md!=null ? md : task);
1700 HashSet<AtomicRecord> arset=null;
1701 branchanalysis=null;
1703 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1705 if (atomicmethodmap==null)
1706 atomicmethodmap=new Hashtable<FlatAtomicEnterNode, AtomicRecord>();
1708 //fix these so we get right strings for local variables
1709 localsprefixaddr=localsprefix;
1710 localsprefixderef=localsprefix+"->";
1711 arset=new HashSet<AtomicRecord>();
1713 //build branchanalysis
1714 branchanalysis=new BranchAnalysis(locality, lb, delaycomp.getNotReady(lb), delaycomp.livecode(lb), state);
1716 //Generate commit methods here
1717 for(Iterator<FlatNode> fnit=fm.getNodeSet().iterator();fnit.hasNext();) {
1718 FlatNode fn=fnit.next();
1719 if (fn.kind()==FKind.FlatAtomicEnterNode&&
1720 locality.getAtomic(lb).get(fn.getPrev(0)).intValue()==0&&
1721 delaycomp.needsFission(lb, (FlatAtomicEnterNode) fn)) {
1722 //We have an atomic enter
1723 FlatAtomicEnterNode faen=(FlatAtomicEnterNode) fn;
1724 Set<FlatNode> exitset=faen.getExits();
1726 String methodname=md.getSymbol()+(atomicmethodcount++);
1727 AtomicRecord ar=new AtomicRecord();
1731 atomicmethodmap.put(faen, ar);
1733 //build data structure declaration
1734 output.println("struct atomicprimitives_"+methodname+" {");
1736 Set<FlatNode> recordset=delaycomp.livecode(lb);
1737 Set<TempDescriptor> liveinto=delaycomp.liveinto(lb, faen, recordset);
1738 Set<TempDescriptor> liveout=delaycomp.liveout(lb, faen);
1739 Set<TempDescriptor> liveoutvirtualread=delaycomp.liveoutvirtualread(lb, faen);
1741 ar.reallivein=new HashSet(liveinto);
1743 ar.liveoutvirtualread=liveoutvirtualread;
1746 for(Iterator<TempDescriptor> it=liveinto.iterator(); it.hasNext();) {
1747 TempDescriptor tmp=it.next();
1748 //remove the pointers
1749 if (tmp.getType().isPtr()) {
1752 //let's print it here
1753 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1756 for(Iterator<TempDescriptor> it=liveout.iterator(); it.hasNext();) {
1757 TempDescriptor tmp=it.next();
1758 //remove the pointers
1759 if (tmp.getType().isPtr()) {
1761 } else if (!liveinto.contains(tmp)) {
1762 //let's print it here
1763 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1766 output.println("};");
1768 //print out method name
1769 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) {");
1770 //build code for commit method
1772 //first define local primitives
1773 Set<TempDescriptor> alltemps=delaycomp.alltemps(lb, faen, recordset);
1774 for(Iterator<TempDescriptor> tmpit=alltemps.iterator();tmpit.hasNext();) {
1775 TempDescriptor tmp=tmpit.next();
1776 if (!tmp.getType().isPtr()) {
1777 if (liveinto.contains(tmp)||liveoutvirtualread.contains(tmp)) {
1778 //read from live into set
1779 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+"=primitives->"+tmp.getSafeSymbol()+";");
1782 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1786 //turn off write barrier generation
1788 state.SINGLETM=false;
1789 generateCode(faen, fm, lb, exitset, output, false);
1790 state.SINGLETM=true;
1791 //turn on write barrier generation
1793 output.println("}\n\n");
1797 //redefine these back to normal
1799 localsprefixaddr="&"+localsprefix;
1800 localsprefixderef=localsprefix+".";
1802 generateHeader(fm, lb, md!=null ? md : task,output);
1803 TempObject objecttemp=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
1805 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1806 for(Iterator<AtomicRecord> arit=arset.iterator();arit.hasNext();) {
1807 AtomicRecord ar=arit.next();
1808 output.println("struct atomicprimitives_"+ar.name+" primitives_"+ar.name+";");
1812 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1813 if (md!=null&&(state.DSM||state.SINGLETM))
1814 output.print(" struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1815 else if (md!=null&&!(state.DSM||state.SINGLETM))
1816 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1818 output.print(" struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={");
1819 output.print(objecttemp.numPointers()+",");
1820 output.print(paramsprefix);
1821 for(int j=0; j<objecttemp.numPointers(); j++)
1822 output.print(", NULL");
1823 output.println("};");
1826 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1827 TempDescriptor td=objecttemp.getPrimitive(i);
1828 TypeDescriptor type=td.getType();
1830 output.println(" void * "+td.getSafeSymbol()+";");
1831 else if (type.isClass()||type.isArray())
1832 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1834 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1838 if( state.MLP || state.OOOJAVA ) {
1839 if( fm.getNext(0) instanceof FlatSESEEnterNode ) {
1840 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
1841 if( (state.MLP && callerSESEplaceholder != mlpa.getMainSESE()) ||
1842 (state.OOOJAVA && callerSESEplaceholder != oooa.getMainSESE())
1844 // declare variables for naming static SESE's
1845 output.println(" /* static SESE names */");
1846 Iterator<SESEandAgePair> pItr = callerSESEplaceholder.getNeededStaticNames().iterator();
1847 while( pItr.hasNext() ) {
1848 SESEandAgePair pair = pItr.next();
1849 output.println(" void* "+pair+";");
1852 // declare variables for tracking dynamic sources
1853 output.println(" /* dynamic variable sources */");
1854 Iterator<TempDescriptor> dynSrcItr = callerSESEplaceholder.getDynamicVarSet().iterator();
1855 while( dynSrcItr.hasNext() ) {
1856 TempDescriptor dynSrcVar = dynSrcItr.next();
1857 output.println(" void* "+dynSrcVar+"_srcSESE;");
1858 output.println(" INTPTR "+dynSrcVar+"_srcOffset;");
1863 // set up related allocation sites's waiting queues
1866 ConflictGraph graph = null;
1867 graph = mlpa.getConflictGraphResults().get(fm);
1868 if (graph != null && graph.hasConflictEdge()) {
1869 output.println(" /* set up waiting queues */");
1870 output.println(" int numMemoryQueue=0;");
1871 output.println(" int memoryQueueItemID=0;");
1872 HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
1874 System.out.println("#lockSet="+lockSet.hashCode());
1875 System.out.println("lockset="+lockSet);
1876 for (Iterator iterator = lockSet.iterator(); iterator.hasNext();) {
1877 SESELock seseLock = (SESELock) iterator.next();
1878 System.out.println("id="+seseLock.getID());
1879 System.out.println("#="+seseLock);
1881 System.out.println("size="+lockSet.size());
1882 if (lockSet.size() > 0) {
1883 output.println(" numMemoryQueue=" + lockSet.size() + ";");
1885 .println(" seseCaller->numMemoryQueue=numMemoryQueue;");
1887 .println(" seseCaller->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
1892 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
1893 if(callerSESEplaceholder!= oooa.getMainSESE()){
1894 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(callerSESEplaceholder);
1895 if (graph != null && graph.hasConflictEdge()) {
1896 output.println(" // set up waiting queues ");
1897 output.println(" int numMemoryQueue=0;");
1898 output.println(" int memoryQueueItemID=0;");
1899 Set<Analysis.OoOJava.SESELock> lockSet = oooa.getLockMappings(graph);
1900 System.out.println("#lockSet="+lockSet.hashCode());
1901 System.out.println("lockset="+lockSet);
1902 for (Iterator iterator = lockSet.iterator(); iterator.hasNext();) {
1903 Analysis.OoOJava.SESELock seseLock = (Analysis.OoOJava.SESELock) iterator.next();
1904 System.out.println("id="+seseLock.getID());
1905 System.out.println("#="+seseLock);
1907 System.out.println("size="+lockSet.size());
1908 if (lockSet.size() > 0) {
1909 output.println(" numMemoryQueue=" + lockSet.size() + ";");
1911 .println(" seseCaller->numMemoryQueue=numMemoryQueue;");
1913 .println(" seseCaller->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
1923 /* Check to see if we need to do a GC if this is a
1924 * multi-threaded program...*/
1926 if (((state.MLP||state.OOOJAVA||state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
1927 || this.state.MULTICOREGC) {
1928 //Don't bother if we aren't in recursive methods...The loops case will catch it
1929 if (callgraph.getAllMethods(md).contains(md)) {
1930 if (state.DSM&&lb.isAtomic())
1931 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
1932 else if (this.state.MULTICOREGC) {
1933 output.println("if(gcflag) gc("+localsprefixaddr+");");
1935 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
1940 generateCode(fm.getNext(0), fm, lb, null, output, true);
1942 output.println("}\n\n");
1946 protected void initializeSESE( FlatSESEEnterNode fsen ) {
1948 FlatMethod fm = fsen.getfmEnclosing();
1949 MethodDescriptor md = fm.getMethod();
1950 ClassDescriptor cn = md.getClassDesc();
1953 // Creates bogus method descriptor to index into tables
1954 Modifiers modBogus = new Modifiers();
1955 MethodDescriptor mdBogus =
1956 new MethodDescriptor( modBogus,
1957 new TypeDescriptor( TypeDescriptor.VOID ),
1958 "sese_"+fsen.getPrettyIdentifier()+fsen.getIdentifier()
1961 mdBogus.setClassDesc( fsen.getcdEnclosing() );
1962 FlatMethod fmBogus = new FlatMethod( mdBogus, null );
1963 fsen.setfmBogus( fmBogus );
1964 fsen.setmdBogus( mdBogus );
1966 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1967 inSetAndOutSet.addAll( fsen.getInVarSet() );
1968 inSetAndOutSet.addAll( fsen.getOutVarSet() );
1970 // Build paramsobj for bogus method descriptor
1971 ParamsObject objectparams = new ParamsObject( mdBogus, tag++ );
1972 paramstable.put( mdBogus, objectparams );
1974 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1975 while( itr.hasNext() ) {
1976 TempDescriptor temp = itr.next();
1977 TypeDescriptor type = temp.getType();
1978 if( type.isPtr() ) {
1979 objectparams.addPtr( temp );
1981 objectparams.addPrim( temp );
1985 // Build normal temp object for bogus method descriptor
1986 TempObject objecttemps = new TempObject( objectparams, mdBogus, tag++ );
1987 tempstable.put( mdBogus, objecttemps );
1989 for( Iterator nodeit = fsen.getNodeSet().iterator(); nodeit.hasNext(); ) {
1990 FlatNode fn = (FlatNode)nodeit.next();
1991 TempDescriptor[] writes = fn.writesTemps();
1993 for( int i = 0; i < writes.length; i++ ) {
1994 TempDescriptor temp = writes[i];
1995 TypeDescriptor type = temp.getType();
1997 if( type.isPtr() ) {
1998 objecttemps.addPtr( temp );
2000 objecttemps.addPrim( temp );
2006 // used when generating the specific SESE record struct
2007 // to remember the FIRST field name of sese records
2008 // that the current SESE depends on--we need to know the
2009 // offset to the first one for garbage collection
2010 protected void addingDepRecField( FlatSESEEnterNode fsen,
2012 if( fsen.getFirstDepRecField() == null ) {
2013 fsen.setFirstDepRecField( field );
2015 fsen.incNumDepRecs();
2018 protected void generateMethodSESE(FlatSESEEnterNode fsen,
2020 PrintWriter outputStructs,
2021 PrintWriter outputMethHead,
2022 PrintWriter outputMethods
2025 ParamsObject objectparams = (ParamsObject) paramstable.get( fsen.getmdBogus() );
2026 TempObject objecttemps = (TempObject) tempstable .get( fsen.getmdBogus() );
2028 // generate locals structure
2029 outputStructs.println("struct "+
2030 fsen.getcdEnclosing().getSafeSymbol()+
2031 fsen.getmdBogus().getSafeSymbol()+"_"+
2032 fsen.getmdBogus().getSafeMethodDescriptor()+
2034 outputStructs.println(" int size;");
2035 outputStructs.println(" void * next;");
2036 for(int i=0; i<objecttemps.numPointers(); i++) {
2037 TempDescriptor temp=objecttemps.getPointer(i);
2039 if (temp.getType().isNull())
2040 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
2042 outputStructs.println(" struct "+
2043 temp.getType().getSafeSymbol()+" * "+
2044 temp.getSafeSymbol()+";");
2046 outputStructs.println("};\n");
2049 // divide in-set and out-set into objects and primitives to prep
2050 // for the record generation just below
2051 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
2052 inSetAndOutSet.addAll( fsen.getInVarSet() );
2053 inSetAndOutSet.addAll( fsen.getOutVarSet() );
2055 Set<TempDescriptor> inSetAndOutSetObjs = new HashSet<TempDescriptor>();
2056 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
2058 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
2059 while( itr.hasNext() ) {
2060 TempDescriptor temp = itr.next();
2061 TypeDescriptor type = temp.getType();
2062 if( type.isPtr() ) {
2063 inSetAndOutSetObjs.add( temp );
2065 inSetAndOutSetPrims.add( temp );
2070 // generate the SESE record structure
2071 outputStructs.println(fsen.getSESErecordName()+" {");
2073 // data common to any SESE, and it must be placed first so
2074 // a module that doesn't know what kind of SESE record this
2075 // is can cast the pointer to a common struct
2076 outputStructs.println(" SESEcommon common;");
2078 // then garbage list stuff
2079 outputStructs.println(" /* next is in-set and out-set objects that look like a garbage list */");
2080 outputStructs.println(" int size;");
2081 outputStructs.println(" void * next;");
2083 // I think that the set of TempDescriptors inSetAndOutSetObjs
2084 // calculated above should match the pointer object params
2085 // used in the following code, but let's just leave the working
2086 // implementation unless there is actually a problem...
2087 for(int i=0; i<objectparams.numPointers(); i++) {
2088 TempDescriptor temp=objectparams.getPointer(i);
2089 if (temp.getType().isNull())
2090 outputStructs.println(" void * "+temp.getSafeSymbol()+
2091 "; /* in-or-out-set obj in gl */");
2093 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+
2094 temp.getSafeSymbol()+"; /* in-or-out-set obj in gl */");
2097 outputStructs.println(" /* next is primitives for in-set and out-set and dynamic tracking */");
2099 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
2100 while( itrPrims.hasNext() ) {
2101 TempDescriptor temp = itrPrims.next();
2102 TypeDescriptor type = temp.getType();
2103 if(type.isPrimitive()){
2104 outputStructs.println(" "+temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol()+"; /* in-set or out-set primitive */");
2108 // note that the sese record pointer will be added below, just primitive part of tracking here
2109 Iterator<TempDescriptor> itrDynInVars = fsen.getDynamicInVarSet().iterator();
2110 while( itrDynInVars.hasNext() ) {
2111 TempDescriptor dynInVar = itrDynInVars.next();
2112 outputStructs.println(" INTPTR "+dynInVar+"_srcOffset; /* dynamic tracking primitive */");
2116 outputStructs.println(" /* everything after this should be pointers to an SESE record */" );
2118 // other half of info for dynamic tracking, the SESE record pointer
2119 itrDynInVars = fsen.getDynamicInVarSet().iterator();
2120 while( itrDynInVars.hasNext() ) {
2121 TempDescriptor dynInVar = itrDynInVars.next();
2122 String depRecField = dynInVar+"_srcSESE";
2123 outputStructs.println(" void* "+depRecField+";");
2124 addingDepRecField( fsen, depRecField );
2127 // statically known sese sources are record pointers, too
2128 Iterator<SESEandAgePair> itrStaticInVarSrcs = fsen.getStaticInVarSrcs().iterator();
2129 while( itrStaticInVarSrcs.hasNext() ) {
2130 SESEandAgePair srcPair = itrStaticInVarSrcs.next();
2131 outputStructs.println(" "+srcPair.getSESE().getSESErecordName()+"* "+srcPair+";");
2132 addingDepRecField( fsen, srcPair.toString() );
2135 if( fsen.getFirstDepRecField() != null ) {
2136 outputStructs.println(" /* compiler believes first dependent SESE record field above is: "+
2137 fsen.getFirstDepRecField()+" */" );
2140 outputStructs.println("};\n");
2143 // write method declaration to header file
2144 outputMethHead.print("void ");
2145 outputMethHead.print(fsen.getSESEmethodName()+"(");
2146 outputMethHead.print(fsen.getSESErecordName()+"* "+paramsprefix);
2147 outputMethHead.println(");\n");
2150 generateFlatMethodSESE( fsen.getfmBogus(),
2151 fsen.getcdEnclosing(),
2157 private void generateFlatMethodSESE(FlatMethod fm,
2159 FlatSESEEnterNode fsen,
2160 FlatSESEExitNode seseExit,
2164 MethodDescriptor md=fm.getMethod();
2166 output.print("void ");
2167 output.print(fsen.getSESEmethodName()+"(");
2168 output.print(fsen.getSESErecordName()+"* "+paramsprefix);
2169 output.println("){\n");
2171 TempObject objecttemp=(TempObject) tempstable.get(md);
2173 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2174 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
2175 output.print(objecttemp.numPointers()+",");
2176 output.print("&(((SESEcommon*)(___params___))[1])");
2177 for(int j=0; j<objecttemp.numPointers(); j++)
2178 output.print(", NULL");
2179 output.println("};");
2182 output.println(" /* regular local primitives */");
2183 for(int i=0; i<objecttemp.numPrimitives(); i++) {
2184 TempDescriptor td=objecttemp.getPrimitive(i);
2185 TypeDescriptor type=td.getType();
2187 output.println(" void * "+td.getSafeSymbol()+";");
2188 else if (type.isClass()||type.isArray())
2189 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
2191 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
2195 // declare variables for naming static SESE's
2196 output.println(" /* static SESE names */");
2197 Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
2198 while( pItr.hasNext() ) {
2199 SESEandAgePair pair = pItr.next();
2200 output.println(" void* "+pair+";");
2203 // declare variables for tracking dynamic sources
2204 output.println(" /* dynamic variable sources */");
2205 Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
2206 while( dynSrcItr.hasNext() ) {
2207 TempDescriptor dynSrcVar = dynSrcItr.next();
2208 output.println(" void* "+dynSrcVar+"_srcSESE;");
2209 output.println(" INTPTR "+dynSrcVar+"_srcOffset;");
2212 // declare local temps for in-set primitives, and if it is
2213 // a ready-source variable, get the value from the record
2214 output.println(" /* local temps for in-set primitives */");
2215 Iterator<TempDescriptor> itrInSet = fsen.getInVarSet().iterator();
2216 while( itrInSet.hasNext() ) {
2217 TempDescriptor temp = itrInSet.next();
2218 TypeDescriptor type = temp.getType();
2219 if( !type.isPtr() ) {
2220 if( fsen.getReadyInVarSet().contains( temp ) ) {
2221 output.println(" "+type+" "+temp+" = "+paramsprefix+"->"+temp+";");
2223 output.println(" "+type+" "+temp+";");
2228 // declare local temps for out-set primitives if its not already
2229 // in the in-set, and it's value will get written so no problem
2230 output.println(" /* local temp for out-set prim, not already in the in-set */");
2231 Iterator<TempDescriptor> itrOutSet = fsen.getOutVarSet().iterator();
2232 while( itrOutSet.hasNext() ) {
2233 TempDescriptor temp = itrOutSet.next();
2234 TypeDescriptor type = temp.getType();
2235 if( !type.isPtr() && !fsen.getInVarSet().contains( temp ) ) {
2236 output.println(" "+type+" "+temp+";");
2240 // setup memory queue
2243 output.println(" // set up memory queues ");
2244 output.println(" int numMemoryQueue=0;");
2245 output.println(" int memoryQueueItemID=0;");
2246 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(fsen);
2247 if (graph != null && graph.hasConflictEdge()) {
2248 output.println(" {");
2250 .println(" SESEcommon* parentCommon = &(___params___->common);");
2251 Set<Analysis.OoOJava.SESELock> lockSet = oooa.getLockMappings(graph);
2252 System.out.println("#lockSet="+lockSet);
2253 if (lockSet.size() > 0) {
2254 output.println(" numMemoryQueue=" + lockSet.size() + ";");
2256 .println(" parentCommon->numMemoryQueue=numMemoryQueue;");
2258 .println(" parentCommon->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2261 output.println(" }");
2264 output.println(" // set up memory queues ");
2265 output.println(" int numMemoryQueue=0;");
2266 output.println(" int memoryQueueItemID=0;");
2267 ConflictGraph graph = null;
2268 graph = mlpa.getConflictGraphResults().get(fsen);
2269 if (graph != null && graph.hasConflictEdge()) {
2270 output.println(" {");
2272 .println(" SESEcommon* parentCommon = &(___params___->common);");
2273 HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
2275 System.out.println("#lockSet="+lockSet);
2277 if (lockSet.size() > 0) {
2278 output.println(" numMemoryQueue=" + lockSet.size() + "; ");
2280 .println(" parentCommon->numMemoryQueue=numMemoryQueue;");
2282 .println(" parentCommon->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2285 output.println(" }");
2291 // copy in-set into place, ready vars were already
2292 // copied when the SESE was issued
2293 Iterator<TempDescriptor> tempItr;
2295 // static vars are from a known SESE
2296 tempItr = fsen.getStaticInVarSet().iterator();
2297 while( tempItr.hasNext() ) {
2298 TempDescriptor temp = tempItr.next();
2299 VariableSourceToken vst = fsen.getStaticInVarSrc( temp );
2300 SESEandAgePair srcPair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2302 // can't grab something from this source until it is done
2303 output.println(" {");
2305 If we are running, everything is done. This check is redundant.
2307 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+srcPair+";" );
2308 output.println(" pthread_mutex_lock( &(com->lock) );");
2309 output.println(" while( com->doneExecuting == FALSE ) {");
2310 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
2311 output.println(" }");
2312 output.println(" pthread_mutex_unlock( &(com->lock) );");
2314 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2315 " = "+paramsprefix+"->"+srcPair+"->"+vst.getAddrVar()+";");
2317 output.println(" }");
2320 // dynamic vars come from an SESE and src
2321 tempItr = fsen.getDynamicInVarSet().iterator();
2322 while( tempItr.hasNext() ) {
2323 TempDescriptor temp = tempItr.next();
2324 TypeDescriptor type = temp.getType();
2326 // go grab it from the SESE source
2327 output.println(" if( "+paramsprefix+"->"+temp+"_srcSESE != NULL ) {");
2329 // gotta wait until the source is done
2330 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+temp+"_srcSESE;" );
2332 If we are running, everything is done!
2333 output.println(" pthread_mutex_lock( &(com->lock) );");
2334 output.println(" while( com->doneExecuting == FALSE ) {");
2335 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
2336 output.println(" }");
2337 output.println(" pthread_mutex_unlock( &(com->lock) );");
2341 if( type.isNull() ) {
2343 } else if( type.isClass() || type.isArray() ) {
2344 typeStr = "struct "+type.getSafeSymbol()+"*";
2346 typeStr = type.getSafeSymbol();
2349 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2350 " = *(("+typeStr+"*) ("+
2351 paramsprefix+"->"+temp+"_srcSESE + "+
2352 paramsprefix+"->"+temp+"_srcOffset));");
2354 // or if the source was our parent, its in the record to grab
2355 output.println(" } else {");
2356 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2357 " = "+paramsprefix+"->"+temp+";");
2358 output.println(" }");
2361 // Check to see if we need to do a GC if this is a
2362 // multi-threaded program...
2363 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2364 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2365 //Don't bother if we aren't in recursive methods...The loops case will catch it
2366 // if (callgraph.getAllMethods(md).contains(md)) {
2367 // if(this.state.MULTICOREGC) {
2368 // output.println("if(gcflag) gc("+localsprefixaddr+");");
2370 // output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2375 // initialize thread-local var to a non-zero, invalid address
2376 output.println(" seseCaller = (SESEcommon*) 0x2;");
2377 HashSet<FlatNode> exitset=new HashSet<FlatNode>();
2378 exitset.add(seseExit);
2379 generateCode(fsen.getNext(0), fm, null, exitset, output, true);
2380 output.println("}\n\n");
2385 // when a new mlp thread is created for an issued SESE, it is started
2386 // by running this method which blocks on a cond variable until
2387 // it is allowed to transition to execute. Then a case statement
2388 // allows it to invoke the method with the proper SESE body, and after
2389 // exiting the SESE method, executes proper SESE exit code before the
2390 // thread can be destroyed
2391 private void generateSESEinvocationMethod(PrintWriter outmethodheader,
2392 PrintWriter outmethod
2395 outmethodheader.println("void* invokeSESEmethod( void* seseRecord );");
2396 outmethod.println( "void* invokeSESEmethod( void* seseRecord ) {");
2397 outmethod.println( " int status;");
2398 outmethod.println( " char errmsg[128];");
2400 // generate a case for each SESE class that can be invoked
2401 outmethod.println( " switch( *((int*)seseRecord) ) {");
2402 outmethod.println( " ");
2403 Iterator<FlatSESEEnterNode> seseit;
2405 seseit=mlpa.getAllSESEs().iterator();
2407 seseit=oooa.getAllSESEs().iterator();
2409 while(seseit.hasNext()){
2410 FlatSESEEnterNode fsen = seseit.next();
2412 outmethod.println( " /* "+fsen.getPrettyIdentifier()+" */");
2413 outmethod.println( " case "+fsen.getIdentifier()+":");
2414 outmethod.println( " "+fsen.getSESEmethodName()+"( seseRecord );");
2416 if( (state.MLP && fsen.equals( mlpa.getMainSESE() )) ||
2417 (state.OOOJAVA && fsen.equals( oooa.getMainSESE() ))
2419 outmethod.println( " /* work scheduler works forever, explicitly exit */");
2420 if (state.COREPROF) {
2421 outmethod.println("CP_EXIT();");
2422 outmethod.println("CP_DUMP();");
2424 outmethod.println( " exit( 0 );");
2427 outmethod.println( " break;");
2428 outmethod.println( "");
2431 // default case should never be taken, error out
2432 outmethod.println( " default:");
2433 outmethod.println( " printf(\"Error: unknown SESE class ID in invoke method.\\n\");");
2434 outmethod.println( " exit(-30);");
2435 outmethod.println( " break;");
2436 outmethod.println( " }");
2437 outmethod.println( " return NULL;");
2438 outmethod.println( "}\n\n");
2442 protected void generateCode(FlatNode first,
2445 Set<FlatNode> stopset,
2446 PrintWriter output, boolean firstpass) {
2448 /* Assign labels to FlatNode's if necessary.*/
2450 Hashtable<FlatNode, Integer> nodetolabel;
2452 if (state.DELAYCOMP&&!firstpass)
2453 nodetolabel=dcassignLabels(first, stopset);
2455 nodetolabel=assignLabels(first, stopset);
2457 Set<FlatNode> storeset=null;
2458 HashSet<FlatNode> genset=null;
2459 HashSet<FlatNode> refset=null;
2460 Set<FlatNode> unionset=null;
2462 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
2463 storeset=delaycomp.livecode(lb);
2464 genset=new HashSet<FlatNode>();
2465 if (state.STMARRAY&&!state.DUALVIEW) {
2466 refset=new HashSet<FlatNode>();
2467 refset.addAll(delaycomp.getDeref(lb));
2468 refset.removeAll(delaycomp.getCannotDelay(lb));
2469 refset.removeAll(delaycomp.getOther(lb));
2472 genset.addAll(delaycomp.getCannotDelay(lb));
2473 genset.addAll(delaycomp.getOther(lb));
2475 genset.addAll(delaycomp.getNotReady(lb));
2476 if (state.STMARRAY&&!state.DUALVIEW) {
2477 genset.removeAll(refset);
2480 unionset=new HashSet<FlatNode>();
2481 unionset.addAll(storeset);
2482 unionset.addAll(genset);
2483 if (state.STMARRAY&&!state.DUALVIEW)
2484 unionset.addAll(refset);
2487 /* Do the actual code generation */
2488 FlatNode current_node=null;
2489 HashSet tovisit=new HashSet();
2490 HashSet visited=new HashSet();
2492 tovisit.add(first.getNext(0));
2495 while(current_node!=null||!tovisit.isEmpty()) {
2496 if (current_node==null) {
2497 current_node=(FlatNode)tovisit.iterator().next();
2498 tovisit.remove(current_node);
2499 } else if (tovisit.contains(current_node)) {
2500 tovisit.remove(current_node);
2502 visited.add(current_node);
2503 if (nodetolabel.containsKey(current_node)) {
2504 output.println("L"+nodetolabel.get(current_node)+":");
2506 if (state.INSTRUCTIONFAILURE) {
2507 if (state.THREAD||state.DSM||state.SINGLETM) {
2508 output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
2510 output.println("if ((--instructioncount)==0) injectinstructionfailure();");
2512 if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
2514 if (!state.DELAYCOMP||firstpass) {
2515 generateFlatNode(fm, lb, current_node, output);
2517 //store primitive variables in out set
2518 AtomicRecord ar=atomicmethodmap.get((FlatAtomicEnterNode)first);
2519 Set<TempDescriptor> liveout=ar.liveout;
2520 for(Iterator<TempDescriptor> tmpit=liveout.iterator();tmpit.hasNext();) {
2521 TempDescriptor tmp=tmpit.next();
2522 output.println("primitives->"+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2525 if ((state.MLP || state.OOOJAVA) && stopset!=null) {
2526 assert first.getPrev( 0 ) instanceof FlatSESEEnterNode;
2527 assert current_node instanceof FlatSESEExitNode;
2528 FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev( 0 );
2529 FlatSESEExitNode fsxn = (FlatSESEExitNode) current_node;
2530 assert fsen.getFlatExit().equals( fsxn );
2531 assert fsxn.getFlatEnter().equals( fsen );
2533 if (current_node.kind()!=FKind.FlatReturnNode) {
2534 output.println(" return;");
2537 } else if(current_node.numNext()==1) {
2539 if ((state.MLP|| state.OOOJAVA) &&
2540 current_node.kind()==FKind.FlatSESEEnterNode &&
2541 !((FlatSESEEnterNode)current_node).getIsCallerSESEplaceholder()
2543 FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
2544 generateFlatNode(fm, lb, current_node, output);
2545 nextnode=fsen.getFlatExit().getNext(0);
2546 } else if (state.DELAYCOMP) {
2547 boolean specialprimitive=false;
2548 //skip literals...no need to add extra overhead
2549 if (storeset!=null&&storeset.contains(current_node)&¤t_node.kind()==FKind.FlatLiteralNode) {
2550 TypeDescriptor typedesc=((FlatLiteralNode)current_node).getType();
2551 if (!typedesc.isClass()&&!typedesc.isArray()) {
2552 specialprimitive=true;
2556 if (genset==null||genset.contains(current_node)||specialprimitive)
2557 generateFlatNode(fm, lb, current_node, output);
2558 if (state.STMARRAY&&!state.DUALVIEW&&refset!=null&&refset.contains(current_node)) {
2559 //need to acquire lock
2560 handleArrayDeref(fm, lb, current_node, output, firstpass);
2562 if (storeset!=null&&storeset.contains(current_node)&&!specialprimitive) {
2563 TempDescriptor wrtmp=current_node.writesTemps()[0];
2565 //need to store value written by previous node
2566 if (wrtmp.getType().isPtr()) {
2567 //only lock the objects that may actually need locking
2568 if (recorddc.getNeedTrans(lb, current_node)&&
2569 (!state.STMARRAY||state.DUALVIEW||!wrtmp.getType().isArray()||
2570 wrtmp.getType().getSymbol().equals(TypeUtil.ObjectClass))) {
2571 output.println("STOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2573 output.println("STOREPTRNOLOCK("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2576 output.println("STORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");/* "+current_node.nodeid+" */");
2579 //need to read value read by previous node
2580 if (wrtmp.getType().isPtr()) {
2581 output.println("RESTOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2583 output.println("RESTORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+"); /* "+current_node.nodeid+" */");
2587 nextnode=current_node.getNext(0);
2590 generateFlatNode(fm, lb, current_node, output);
2591 nextnode=current_node.getNext(0);
2593 if (visited.contains(nextnode)) {
2594 output.println("goto L"+nodetolabel.get(nextnode)+";");
2597 current_node=nextnode;
2598 } else if (current_node.numNext()==2) {
2600 if (state.DELAYCOMP) {
2601 boolean computeside=false;
2603 //need to record which way it should go
2604 if (genset==null||genset.contains(current_node)) {
2605 if (storeset!=null&&storeset.contains(current_node)) {
2606 //need to store which way branch goes
2607 generateStoreFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2609 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2611 //which side to execute
2615 if (genset.contains(current_node)) {
2616 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2617 } else if (storeset.contains(current_node)) {
2619 branchanalysis.generateGroupCode(current_node, output, nodetolabel);
2621 //which side to execute
2626 Set<FlatNode> leftset=DelayComputation.getNext(current_node, 0, unionset, lb,locality, true);
2628 if (leftset.size()==0)
2630 if (visited.contains(current_node.getNext(branch))) {
2631 //already visited -- build jump
2632 output.println("goto L"+nodetolabel.get(current_node.getNext(branch))+";");
2635 current_node=current_node.getNext(branch);
2638 if (!visited.contains(current_node.getNext(1)))
2639 tovisit.add(current_node.getNext(1));
2640 if (visited.contains(current_node.getNext(0))) {
2641 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2644 current_node=current_node.getNext(0);
2648 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2649 if (!visited.contains(current_node.getNext(1)))
2650 tovisit.add(current_node.getNext(1));
2651 if (visited.contains(current_node.getNext(0))) {
2652 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2655 current_node=current_node.getNext(0);
2657 } else throw new Error();
2661 protected void handleArrayDeref(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output, boolean firstpass) {
2662 if (fn.kind()==FKind.FlatSetElementNode) {
2663 FlatSetElementNode fsen=(FlatSetElementNode) fn;
2664 String dst=generateTemp(fm, fsen.getDst(), lb);
2665 String src=generateTemp(fm, fsen.getSrc(), lb);
2666 String index=generateTemp(fm, fsen.getIndex(), lb);
2667 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
2669 if (elementtype.isArray()||elementtype.isClass())
2672 type=elementtype.getSafeSymbol()+" ";
2674 output.println("STOREARRAY("+dst+","+index+","+type+")");
2676 output.println("{");
2677 output.println(" struct ArrayObject *array;");
2678 output.println(" int index;");
2679 output.println(" RESTOREARRAY(array,index);");
2680 output.println(" (("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index]="+src+";");
2681 output.println("}");
2683 } else if (fn.kind()==FKind.FlatElementNode) {
2684 FlatElementNode fen=(FlatElementNode) fn;
2685 String src=generateTemp(fm, fen.getSrc(), lb);
2686 String index=generateTemp(fm, fen.getIndex(), lb);
2687 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
2688 String dst=generateTemp(fm, fen.getDst(), lb);
2690 if (elementtype.isArray()||elementtype.isClass())
2693 type=elementtype.getSafeSymbol()+" ";
2695 output.println("STOREARRAY("+src+","+index+","+type+")");
2697 output.println("{");
2698 output.println(" struct ArrayObject *array;");
2699 output.println(" int index;");
2700 output.println(" RESTOREARRAY(array,index);");
2701 output.println(" "+dst+"=(("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index];");
2702 output.println("}");
2706 /** Special label assignment for delaycomputation */
2707 protected Hashtable<FlatNode, Integer> dcassignLabels(FlatNode first, Set<FlatNode> lastset) {
2708 HashSet tovisit=new HashSet();
2709 HashSet visited=new HashSet();
2711 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2713 //Label targets of branches
2714 Set<FlatNode> targets=branchanalysis.getTargets();
2715 for(Iterator<FlatNode> it=targets.iterator();it.hasNext();) {
2716 nodetolabel.put(it.next(), new Integer(labelindex++));
2721 /*Assign labels first. A node needs a label if the previous
2722 * node has two exits or this node is a join point. */
2724 while(!tovisit.isEmpty()) {
2725 FlatNode fn=(FlatNode)tovisit.iterator().next();
2730 if(lastset!=null&&lastset.contains(fn)) {
2731 // if last is not null and matches, don't go
2732 // any further for assigning labels
2736 for(int i=0; i<fn.numNext(); i++) {
2737 FlatNode nn=fn.getNext(i);
2740 //1) Edge >1 of node
2741 nodetolabel.put(nn,new Integer(labelindex++));
2743 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2747 nodetolabel.put(nn,new Integer(labelindex++));
2755 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first) {
2756 return assignLabels(first, null);
2759 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
2760 HashSet tovisit=new HashSet();
2761 HashSet visited=new HashSet();
2763 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2766 /*Assign labels first. A node needs a label if the previous
2767 * node has two exits or this node is a join point. */
2769 while(!tovisit.isEmpty()) {
2770 FlatNode fn=(FlatNode)tovisit.iterator().next();
2775 if(lastset!=null&&lastset.contains(fn)) {
2776 // if last is not null and matches, don't go
2777 // any further for assigning labels
2781 for(int i=0; i<fn.numNext(); i++) {
2782 FlatNode nn=fn.getNext(i);
2785 //1) Edge >1 of node
2786 nodetolabel.put(nn,new Integer(labelindex++));
2788 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2792 nodetolabel.put(nn,new Integer(labelindex++));
2800 /** Generate text string that corresponds to the TempDescriptor td. */
2801 protected String generateTemp(FlatMethod fm, TempDescriptor td, LocalityBinding lb) {
2802 MethodDescriptor md=fm.getMethod();
2803 TaskDescriptor task=fm.getTask();
2804 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
2806 if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
2807 return td.getSafeSymbol();
2810 if (objecttemps.isLocalPtr(td)) {
2811 return localsprefixderef+td.getSafeSymbol();
2814 if (objecttemps.isParamPtr(td)) {
2815 return paramsprefix+"->"+td.getSafeSymbol();
2821 protected void generateFlatNode(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output) {
2823 // insert pre-node actions from the code plan
2824 if( state.MLP|| state.OOOJAVA ) {
2828 cp = mlpa.getCodePlan( fn );
2830 cp = oooa.getCodePlan(fn);
2835 FlatSESEEnterNode currentSESE = cp.getCurrentSESE();
2837 // for each sese and age pair that this parent statement
2838 // must stall on, take that child's stall semaphore, the
2839 // copying of values comes after the statement
2840 Iterator<VariableSourceToken> vstItr = cp.getStallTokens().iterator();
2841 while( vstItr.hasNext() ) {
2842 VariableSourceToken vst = vstItr.next();
2844 SESEandAgePair pair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2846 output.println(" {");
2847 output.println(" SESEcommon* common = (SESEcommon*) "+pair+";");
2848 //output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_BEGIN );");
2849 output.println(" pthread_mutex_lock( &(common->lock) );");
2850 output.println(" while( common->doneExecuting == FALSE ) {");
2851 output.println(" pthread_cond_wait( &(common->doneCond), &(common->lock) );");
2852 output.println(" }");
2853 output.println(" pthread_mutex_unlock( &(common->lock) );");
2855 // copy things we might have stalled for
2856 output.println(" "+pair.getSESE().getSESErecordName()+"* child = ("+
2857 pair.getSESE().getSESErecordName()+"*) "+pair+";");
2859 Iterator<TempDescriptor> tdItr = cp.getCopySet( vst ).iterator();
2860 while( tdItr.hasNext() ) {
2861 TempDescriptor td = tdItr.next();
2862 FlatMethod fmContext;
2863 if( currentSESE.getIsCallerSESEplaceholder() ) {
2864 fmContext = currentSESE.getfmEnclosing();
2866 fmContext = currentSESE.getfmBogus();
2868 output.println(" "+generateTemp( fmContext, td, null )+
2869 " = child->"+vst.getAddrVar().getSafeSymbol()+";");
2872 //output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_END );");
2873 output.println(" }");
2876 // for each variable with a dynamic source, stall just for that variable
2877 Iterator<TempDescriptor> dynItr = cp.getDynamicStallSet().iterator();
2878 while( dynItr.hasNext() ) {
2879 TempDescriptor dynVar = dynItr.next();
2881 // only stall if the dynamic source is not yourself, denoted by src==NULL
2882 // otherwise the dynamic write nodes will have the local var up-to-date
2883 output.println(" {");
2884 output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
2885 //output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_BEGIN );");
2886 output.println(" SESEcommon* common = (SESEcommon*) "+dynVar+"_srcSESE;");
2887 output.println(" psem_take( &(common->stallSem) );");
2889 FlatMethod fmContext;
2890 if( currentSESE.getIsCallerSESEplaceholder() ) {
2891 fmContext = currentSESE.getfmEnclosing();
2893 fmContext = currentSESE.getfmBogus();
2896 TypeDescriptor type=dynVar.getType();
2898 if( type.isNull() ) {
2900 } else if( type.isClass() || type.isArray() ) {
2901 typeStr = "struct "+type.getSafeSymbol()+"*";
2903 typeStr = type.getSafeSymbol();
2906 output.println(" "+generateTemp( fmContext, dynVar, null )+
2907 " = *(("+typeStr+"*) ("+
2908 dynVar+"_srcSESE + "+dynVar+"_srcOffset));");
2909 //output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_END );");
2910 output.println(" }");
2911 output.println(" }");
2914 // for each assignment of a variable to rhs that has a dynamic source,
2915 // copy the dynamic sources
2916 Iterator dynAssignItr = cp.getDynAssigns().entrySet().iterator();
2917 while( dynAssignItr.hasNext() ) {
2918 Map.Entry me = (Map.Entry) dynAssignItr.next();
2919 TempDescriptor lhs = (TempDescriptor) me.getKey();
2920 TempDescriptor rhs = (TempDescriptor) me.getValue();
2921 output.println(" "+lhs+"_srcSESE = "+rhs+"_srcSESE;");
2922 output.println(" "+lhs+"_srcOffset = "+rhs+"_srcOffset;");
2925 // for each lhs that is dynamic from a non-dynamic source, set the
2926 // dynamic source vars to the current SESE
2927 dynItr = cp.getDynAssignCurr().iterator();
2928 while( dynItr.hasNext() ) {
2929 TempDescriptor dynVar = dynItr.next();
2930 assert currentSESE.getDynamicVarSet().contains( dynVar );
2931 output.println(" "+dynVar+"_srcSESE = NULL;");
2935 // handling stall site
2936 if (state.OOOJAVA) {
2937 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(currentSESE);
2939 Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
2940 Set<Analysis.OoOJava.WaitingElement> waitingElementSet =
2941 graph.getStallSiteWaitingElementSet(fn, seseLockSet);
2943 if(waitingElementSet.size()>0){
2944 output.println("// stall on parent's stall sites ");
2945 output.println(" {");
2946 output.println(" REntry* rentry;");
2948 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
2949 Analysis.OoOJava.WaitingElement waitingElement = (Analysis.OoOJava.WaitingElement) iterator.next();
2951 if( waitingElement.getStatus() >= ConflictNode.COARSE ){
2952 output.println(" rentry=mlpCreateREntry("+ waitingElement.getStatus()+ ", seseCaller);");
2954 output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", seseCaller, (void*)&" +generateTemp(fm,waitingElement.getTempDesc(),lb)+ ");");
2956 output.println(" psem_init( &(rentry->parentStallSem) );");
2957 output.println(" rentry->queue=seseCaller->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
2959 .println(" if(ADDRENTRY(seseCaller->memoryQueueArray["+ waitingElement.getQueueID()
2960 + "],rentry)==NOTREADY){");
2961 //output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_BEGIN );");
2962 output.println(" psem_take( &(rentry->parentStallSem) );");
2963 //output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_END );");
2964 output.println(" } ");
2966 output.println(" }");
2970 ParentChildConflictsMap conflictsMap = mlpa.getConflictsResults().get(fn);
2971 if (conflictsMap != null) {
2972 Set<Long> allocSet = conflictsMap.getAllocationSiteIDSetofStallSite();
2973 if (allocSet.size() > 0) {
2974 FlatNode enclosingFlatNode=null;
2975 if( currentSESE.getIsCallerSESEplaceholder() && currentSESE.getParent()==null){
2976 enclosingFlatNode=currentSESE.getfmEnclosing();
2978 enclosingFlatNode=currentSESE;
2980 ConflictGraph graph=mlpa.getConflictGraphResults().get(enclosingFlatNode);
2981 HashSet<SESELock> seseLockSet=mlpa.getConflictGraphLockMap().get(graph);
2982 Set<WaitingElement> waitingElementSet=graph.getStallSiteWaitingElementSet(conflictsMap, seseLockSet);
2984 if(waitingElementSet.size()>0){
2985 output.println("// stall on parent's stall sites ");
2986 output.println(" {");
2987 output.println(" REntry* rentry;");
2989 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
2990 WaitingElement waitingElement = (WaitingElement) iterator.next();
2992 if( waitingElement.getStatus() >= ConflictNode.COARSE ){
2993 // HERE! a parent might conflict with a child
2994 output.println(" rentry=mlpCreateREntry("+ waitingElement.getStatus()+ ", seseCaller);");
2996 output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", seseCaller, (void*)&___locals___."+ waitingElement.getDynID() + ");");
2997 // output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", seseCaller, ___locals___."+ waitingElement.getDynID() + "->oid);");
2999 output.println(" psem_init( &(rentry->parentStallSem) );");
3000 output.println(" rentry->queue=seseCaller->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
3002 .println(" if(ADDRENTRY(seseCaller->memoryQueueArray["+ waitingElement.getQueueID()
3003 + "],rentry)==NOTREADY){");
3004 //output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_BEGIN );");
3005 output.println(" psem_take( &(rentry->parentStallSem) );");
3006 //output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_END );");
3007 output.println(" } ");
3009 output.println(" }");
3018 case FKind.FlatAtomicEnterNode:
3019 generateFlatAtomicEnterNode(fm, lb, (FlatAtomicEnterNode) fn, output);
3022 case FKind.FlatAtomicExitNode:
3023 generateFlatAtomicExitNode(fm, lb, (FlatAtomicExitNode) fn, output);
3026 case FKind.FlatInstanceOfNode:
3027 generateFlatInstanceOfNode(fm, lb, (FlatInstanceOfNode)fn, output);
3030 case FKind.FlatSESEEnterNode:
3031 generateFlatSESEEnterNode(fm, lb, (FlatSESEEnterNode)fn, output);
3034 case FKind.FlatSESEExitNode:
3035 generateFlatSESEExitNode(fm, lb, (FlatSESEExitNode)fn, output);
3038 case FKind.FlatWriteDynamicVarNode:
3039 generateFlatWriteDynamicVarNode(fm, lb, (FlatWriteDynamicVarNode)fn, output);
3042 case FKind.FlatGlobalConvNode:
3043 generateFlatGlobalConvNode(fm, lb, (FlatGlobalConvNode) fn, output);
3046 case FKind.FlatTagDeclaration:
3047 generateFlatTagDeclaration(fm, lb, (FlatTagDeclaration) fn,output);
3050 case FKind.FlatCall:
3051 generateFlatCall(fm, lb, (FlatCall) fn,output);
3054 case FKind.FlatFieldNode:
3055 generateFlatFieldNode(fm, lb, (FlatFieldNode) fn,output);
3058 case FKind.FlatElementNode:
3059 generateFlatElementNode(fm, lb, (FlatElementNode) fn,output);
3062 case FKind.FlatSetElementNode:
3063 generateFlatSetElementNode(fm, lb, (FlatSetElementNode) fn,output);
3066 case FKind.FlatSetFieldNode:
3067 generateFlatSetFieldNode(fm, lb, (FlatSetFieldNode) fn,output);
3071 generateFlatNew(fm, lb, (FlatNew) fn,output);
3074 case FKind.FlatOpNode:
3075 generateFlatOpNode(fm, lb, (FlatOpNode) fn,output);
3078 case FKind.FlatCastNode:
3079 generateFlatCastNode(fm, lb, (FlatCastNode) fn,output);
3082 case FKind.FlatLiteralNode:
3083 generateFlatLiteralNode(fm, lb, (FlatLiteralNode) fn,output);
3086 case FKind.FlatReturnNode:
3087 generateFlatReturnNode(fm, lb, (FlatReturnNode) fn,output);
3091 output.println("/* nop */");
3094 case FKind.FlatExit:
3095 output.println("/* exit */");
3098 case FKind.FlatBackEdge:
3099 if (state.SINGLETM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
3100 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
3102 if(state.DSM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
3103 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
3105 if (((state.MLP|| state.OOOJAVA||state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
3106 || (this.state.MULTICOREGC)) {
3107 if(state.DSM&&locality.getAtomic(lb).get(fn).intValue()>0) {
3108 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
3109 } else if(this.state.MULTICOREGC) {
3110 output.println("if (gcflag) gc("+localsprefixaddr+");");
3112 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3115 output.println("/* nop */");
3118 case FKind.FlatCheckNode:
3119 generateFlatCheckNode(fm, lb, (FlatCheckNode) fn, output);
3122 case FKind.FlatFlagActionNode:
3123 generateFlatFlagActionNode(fm, lb, (FlatFlagActionNode) fn, output);
3126 case FKind.FlatPrefetchNode:
3127 generateFlatPrefetchNode(fm,lb, (FlatPrefetchNode) fn, output);
3130 case FKind.FlatOffsetNode:
3131 generateFlatOffsetNode(fm, lb, (FlatOffsetNode)fn, output);
3138 // insert post-node actions from the code-plan
3141 CodePlan cp = mlpa.getCodePlan( fn );
3149 public void generateFlatOffsetNode(FlatMethod fm, LocalityBinding lb, FlatOffsetNode fofn, PrintWriter output) {
3150 output.println("/* FlatOffsetNode */");
3151 FieldDescriptor fd=fofn.getField();
3152 output.println(generateTemp(fm, fofn.getDst(),lb)+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+ fd.getSafeSymbol()+");");
3153 output.println("/* offset */");
3156 public void generateFlatPrefetchNode(FlatMethod fm, LocalityBinding lb, FlatPrefetchNode fpn, PrintWriter output) {
3157 if (state.PREFETCH) {
3158 Vector oids = new Vector();
3159 Vector fieldoffset = new Vector();
3160 Vector endoffset = new Vector();
3161 int tuplecount = 0; //Keeps track of number of prefetch tuples that need to be generated
3162 for(Iterator it = fpn.hspp.iterator(); it.hasNext();) {
3163 PrefetchPair pp = (PrefetchPair) it.next();
3164 Integer statusbase = locality.getNodePreTempInfo(lb,fpn).get(pp.base);
3165 /* Find prefetches that can generate oid */
3166 if(statusbase == LocalityAnalysis.GLOBAL) {
3167 generateTransCode(fm, lb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(lb).get(fpn).intValue()>0, false);
3169 } else if (statusbase == LocalityAnalysis.LOCAL) {
3170 generateTransCode(fm,lb,pp,oids,fieldoffset,endoffset,tuplecount,false,true);
3177 System.out.println("Adding prefetch "+fpn+ " to method:" +fm);
3178 output.println("{");
3179 output.println("/* prefetch */");
3180 output.println("/* prefetchid_" + fpn.siteid + " */");
3181 output.println("void * prefptr;");
3182 output.println("int tmpindex;");
3184 output.println("if((evalPrefetch["+fpn.siteid+"].operMode) || (evalPrefetch["+fpn.siteid+"].retrycount <= 0)) {");
3185 /*Create C code for oid array */
3186 output.print(" unsigned int oidarray_[] = {");
3187 boolean needcomma=false;
3188 for (Iterator it = oids.iterator(); it.hasNext();) {
3191 output.print(it.next());
3194 output.println("};");
3196 /*Create C code for endoffset values */
3197 output.print(" unsigned short endoffsetarry_[] = {");
3199 for (Iterator it = endoffset.iterator(); it.hasNext();) {
3202 output.print(it.next());
3205 output.println("};");
3207 /*Create C code for Field Offset Values */
3208 output.print(" short fieldarry_[] = {");
3210 for (Iterator it = fieldoffset.iterator(); it.hasNext();) {
3213 output.print(it.next());
3216 output.println("};");
3217 /* make the prefetch call to Runtime */
3218 output.println(" if(!evalPrefetch["+fpn.siteid+"].operMode) {");
3219 output.println(" evalPrefetch["+fpn.siteid+"].retrycount = RETRYINTERVAL;");
3220 output.println(" }");
3221 output.println(" prefetch("+fpn.siteid+" ,"+tuplecount+", oidarray_, endoffsetarry_, fieldarry_);");
3222 output.println(" } else {");
3223 output.println(" evalPrefetch["+fpn.siteid+"].retrycount--;");
3224 output.println(" }");
3225 output.println("}");
3229 public void generateTransCode(FlatMethod fm, LocalityBinding lb,PrefetchPair pp, Vector oids, Vector fieldoffset, Vector endoffset, int tuplecount, boolean inside, boolean localbase) {
3230 short offsetcount = 0;
3234 } else if (localbase) {
3235 for(; breakindex<pp.desc.size(); breakindex++) {
3236 Descriptor desc=pp.getDescAt(breakindex);
3237 if (desc instanceof FieldDescriptor) {
3238 FieldDescriptor fd=(FieldDescriptor)desc;
3239 if (fd.isGlobal()) {
3247 if (breakindex>pp.desc.size()) //all local
3250 TypeDescriptor lasttype=pp.base.getType();
3251 String basestr=generateTemp(fm, pp.base, lb);
3253 boolean maybenull=fm.getMethod().isStatic()||
3254 !pp.base.equals(fm.getParameter(0));
3256 for(int i=0; i<breakindex; i++) {
3257 String indexcheck="";
3259 Descriptor desc=pp.getDescAt(i);
3260 if (desc instanceof FieldDescriptor) {
3261 FieldDescriptor fd=(FieldDescriptor)desc;
3263 if (!teststr.equals(""))
3265 teststr+="((prefptr="+basestr+")!=NULL)";
3266 basestr="((struct "+lasttype.getSafeSymbol()+" *)prefptr)->"+fd.getSafeSymbol();
3268 basestr=basestr+"->"+fd.getSafeSymbol();
3271 lasttype=fd.getType();
3273 IndexDescriptor id=(IndexDescriptor)desc;
3274 indexcheck="((tmpindex=";
3275 for(int j=0; j<id.tddesc.size(); j++) {
3276 indexcheck+=generateTemp(fm, id.getTempDescAt(j), lb)+"+";
3278 indexcheck+=id.offset+")>=0)&(tmpindex<((struct ArrayObject *)prefptr)->___length___)";
3280 if (!teststr.equals(""))
3282 teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck;
3283 basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]";
3285 lasttype=lasttype.dereference();
3290 if (teststr.equals("")) {
3291 oid="((unsigned int)"+basestr+")";
3293 oid="((unsigned int)(("+teststr+")?"+basestr+":NULL))";
3297 for(int i = breakindex; i < pp.desc.size(); i++) {
3298 String newfieldoffset;
3299 Object desc = pp.getDescAt(i);
3300 if(desc instanceof FieldDescriptor) {
3301 FieldDescriptor fd=(FieldDescriptor)desc;
3302 newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))");
3303 lasttype=fd.getType();
3305 newfieldoffset = "";
3306 IndexDescriptor id=(IndexDescriptor)desc;
3307 for(int j = 0; j < id.tddesc.size(); j++) {
3308 newfieldoffset += generateTemp(fm, id.getTempDescAt(j), lb) + "+";
3310 newfieldoffset += id.offset.toString();
3311 lasttype=lasttype.dereference();
3313 fieldoffset.add(newfieldoffset);
3316 int base=(tuplecount>0) ? ((Short)endoffset.get(tuplecount-1)).intValue() : 0;
3317 base+=pp.desc.size()-breakindex;
3318 endoffset.add(new Short((short)base));
3323 public void generateFlatGlobalConvNode(FlatMethod fm, LocalityBinding lb, FlatGlobalConvNode fgcn, PrintWriter output) {
3324 if (lb!=fgcn.getLocality())
3326 /* Have to generate flat globalconv */
3327 if (fgcn.getMakePtr()) {
3329 //DEBUG: output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+",\" "+fm+":"+fgcn+"\");");
3330 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3332 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fgcn)||state.READSET&&dc.getNeedWriteTrans(lb, fgcn)) {
3333 //need to do translation
3334 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+", (void *)("+localsprefixaddr+"));");
3335 } else if (state.READSET&&dc.getNeedTrans(lb, fgcn)) {
3336 if (state.HYBRID&&delaycomp.getConv(lb).contains(fgcn)) {
3337 output.println("TRANSREADRDFISSION("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3339 output.println("TRANSREADRD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3343 /* Need to convert to OID */
3344 if ((dc==null)||dc.getNeedSrcTrans(lb,fgcn)) {
3345 if (fgcn.doConvert()||(delaycomp!=null&&delaycomp.needsFission(lb, fgcn.getAtomicEnter())&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) {
3346 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc(),lb)+");");
3348 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=NULL;");
3354 public void generateFlatInstanceOfNode(FlatMethod fm, LocalityBinding lb, FlatInstanceOfNode fion, PrintWriter output) {
3356 if (fion.getType().isArray()) {
3357 type=state.getArrayNumber(fion.getType())+state.numClasses();
3359 type=fion.getType().getClassDesc().getId();
3362 if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
3363 output.println(generateTemp(fm, fion.getDst(), lb)+"=1;");
3365 output.println(generateTemp(fm, fion.getDst(), lb)+"=instanceof("+generateTemp(fm,fion.getSrc(),lb)+","+type+");");
3368 int sandboxcounter=0;
3369 public void generateFlatAtomicEnterNode(FlatMethod fm, LocalityBinding lb, FlatAtomicEnterNode faen, PrintWriter output) {
3370 /* Check to see if we need to generate code for this atomic */
3371 if (locality==null) {
3372 if (GENERATEPRECISEGC) {
3373 output.println("if (pthread_mutex_trylock(&atomiclock)!=0) {");
3374 output.println("stopforgc((struct garbagelist *) &___locals___);");
3375 output.println("pthread_mutex_lock(&atomiclock);");
3376 output.println("restartaftergc();");
3377 output.println("}");
3379 output.println("pthread_mutex_lock(&atomiclock);");
3384 if (locality.getAtomic(lb).get(faen.getPrev(0)).intValue()>0)
3388 if (state.SANDBOX) {
3389 outsandbox.println("int atomiccounter"+sandboxcounter+"=LOW_CHECK_FREQUENCY;");
3390 output.println("counter_reset_pointer=&atomiccounter"+sandboxcounter+";");
3393 if (state.DELAYCOMP&&delaycomp.needsFission(lb, faen)) {
3394 AtomicRecord ar=atomicmethodmap.get(faen);
3396 for(Iterator<TempDescriptor> tmpit=ar.livein.iterator();tmpit.hasNext();) {
3397 TempDescriptor tmp=tmpit.next();
3398 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3401 //copy outs that depend on path
3402 for(Iterator<TempDescriptor> tmpit=ar.liveoutvirtualread.iterator();tmpit.hasNext();) {
3403 TempDescriptor tmp=tmpit.next();
3404 if (!ar.livein.contains(tmp))
3405 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3409 /* Backup the temps. */
3410 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3411 TempDescriptor tmp=tmpit.next();
3412 output.println(generateTemp(fm, backuptable.get(lb).get(tmp),lb)+"="+generateTemp(fm,tmp,lb)+";");
3415 output.println("goto transstart"+faen.getIdentifier()+";");
3417 /******* Print code to retry aborted transaction *******/
3418 output.println("transretry"+faen.getIdentifier()+":");
3421 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3422 TempDescriptor tmp=tmpit.next();
3423 output.println(generateTemp(fm, tmp,lb)+"="+generateTemp(fm,backuptable.get(lb).get(tmp),lb)+";");
3427 /********* Need to revert local object store ********/
3428 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3430 output.println("while ("+revertptr+") {");
3431 output.println("struct ___Object___ * tmpptr;");
3432 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3433 output.println("REVERT_OBJ("+revertptr+");");
3434 output.println(revertptr+"=tmpptr;");
3435 output.println("}");
3437 /******* Tell the runtime to start the transaction *******/
3439 output.println("transstart"+faen.getIdentifier()+":");
3440 if (state.SANDBOX) {
3441 output.println("transaction_check_counter=*counter_reset_pointer;");
3444 output.println("transStart();");
3446 if (state.ABORTREADERS||state.SANDBOX) {
3448 output.println("abortenabled=1;");
3449 output.println("if (_setjmp(aborttrans)) {");
3450 output.println(" goto transretry"+faen.getIdentifier()+"; }");
3454 public void generateFlatAtomicExitNode(FlatMethod fm, LocalityBinding lb, FlatAtomicExitNode faen, PrintWriter output) {
3455 /* Check to see if we need to generate code for this atomic */
3456 if (locality==null) {
3457 output.println("pthread_mutex_unlock(&atomiclock);");
3460 if (locality.getAtomic(lb).get(faen).intValue()>0)
3462 //store the revert list before we lose the transaction object
3465 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3466 output.println(revertptr+"=revertlist;");
3467 output.println("if (transCommit()) {");
3468 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3469 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3470 output.println("} else {");
3471 /* Need to commit local object store */
3472 output.println("while ("+revertptr+") {");
3473 output.println("struct ___Object___ * tmpptr;");
3474 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3475 output.println("COMMIT_OBJ("+revertptr+");");
3476 output.println(revertptr+"=tmpptr;");
3477 output.println("}");
3478 output.println("}");
3482 if (!state.DELAYCOMP) {
3484 output.println("if (transCommit()) {");
3485 /* Transaction aborts if it returns true */
3486 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3487 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3488 output.println("}");
3490 if (delaycomp.optimizeTrans(lb, faen.getAtomicEnter())&&(!state.STMARRAY||state.DUALVIEW)) {
3491 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3492 output.println("LIGHTWEIGHTCOMMIT("+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+", transretry"+faen.getAtomicEnter().getIdentifier()+");");
3494 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3495 TempDescriptor tmp=tmpit.next();
3496 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3498 } else if (delaycomp.needsFission(lb, faen.getAtomicEnter())) {
3499 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3501 output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {");
3502 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3503 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3504 output.println("}");
3506 output.println("else {");
3507 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3508 TempDescriptor tmp=tmpit.next();
3509 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3511 output.println("}");
3513 output.println("if (transCommit(NULL, NULL, NULL, NULL)) {");
3514 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3515 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3516 output.println("}");
3521 public void generateFlatSESEEnterNode( FlatMethod fm,
3523 FlatSESEEnterNode fsen,
3526 // if MLP flag is off, okay that SESE nodes are in IR graph,
3527 // just skip over them and code generates exactly the same
3528 if( !(state.MLP || state.OOOJAVA) ) {
3531 // there may be an SESE in an unreachable method, skip over
3532 if( (state.MLP && !mlpa.getAllSESEs().contains( fsen )) ||
3533 (state.OOOJAVA && !oooa.getAllSESEs().contains(fsen))
3538 // also, if we have encountered a placeholder, just skip it
3539 if( fsen.getIsCallerSESEplaceholder() ) {
3543 output.println(" {");
3546 //output.println("CP_LOGEVENT( CP_EVENTID_TASKDISPATCH, CP_EVENTTYPE_BEGIN );");
3548 // set up the parent
3549 if( (state.MLP && fsen == mlpa.getMainSESE()) ||
3550 (state.OOOJAVA && fsen == oooa.getMainSESE())
3552 output.println(" SESEcommon* parentCommon = NULL;");
3554 if( fsen.getParent() == null ) {
3555 System.out.println( "in "+fm+", "+fsen+" has null parent" );
3557 assert fsen.getParent() != null;
3558 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3559 output.println(" SESEcommon* parentCommon = &("+paramsprefix+"->common);");
3561 //output.println(" SESEcommon* parentCommon = (SESEcommon*) peekItem( seseCallStack );");
3562 output.println(" SESEcommon* parentCommon = seseCaller;");
3566 // before doing anything, lock your own record and increment the running children
3567 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3568 (state.OOOJAVA && fsen != oooa.getMainSESE())
3570 output.println(" atomic_inc(&parentCommon->numRunningChildren);");
3573 // allocate the space for this record
3575 fsen.getSESErecordName()+"* seseToIssue = ("+
3576 fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
3577 fsen.getSESErecordName()+" ) );");
3579 // set up the SESE in-set and out-set objects, which look
3580 // like a garbage list
3581 output.println(" struct garbagelist * gl= (struct garbagelist *)&(((SESEcommon*)(seseToIssue))[1]);");
3582 output.println(" gl->size="+calculateSizeOfSESEParamList(fsen)+";");
3583 output.println(" gl->next = NULL;");
3585 // there are pointers to SESE records the newly-issued SESE
3586 // will use to get values it depends on them for--how many
3587 // are there, and what is the offset from the total SESE
3588 // record to the first dependent record pointer?
3589 output.println(" seseToIssue->common.numDependentSESErecords="+
3590 fsen.getNumDepRecs()+";");
3592 // we only need this (and it will only compile) when the number of dependent
3593 // SESE records is non-zero
3594 if( fsen.getFirstDepRecField() != null ) {
3595 output.println(" seseToIssue->common.offsetToDepSESErecords=(INTPTR)sizeof("+
3596 fsen.getSESErecordName()+") - (INTPTR)&((("+
3597 fsen.getSESErecordName()+"*)0)->"+fsen.getFirstDepRecField()+");"
3602 // and keep the thread-local sese stack up to date (jjenista--this still relevant??)
3603 //output.println(" addNewItem( seseCallStack, (void*) seseToIssue);");
3605 // fill in common data
3606 output.println(" int localCount=0;");
3607 output.println(" seseToIssue->common.classID = "+fsen.getIdentifier()+";");
3608 output.println(" psem_init( &(seseToIssue->common.stallSem) );");
3610 output.println(" seseToIssue->common.forwardList = createQueue();");
3611 output.println(" seseToIssue->common.unresolvedDependencies = 10000;");
3612 output.println(" pthread_cond_init( &(seseToIssue->common.doneCond), NULL );");
3613 output.println(" seseToIssue->common.doneExecuting = FALSE;");
3614 output.println(" pthread_cond_init( &(seseToIssue->common.runningChildrenCond), NULL );");
3615 output.println(" seseToIssue->common.numRunningChildren = 0;");
3616 output.println(" seseToIssue->common.parent = parentCommon;");
3618 // all READY in-vars should be copied now and be done with it
3619 Iterator<TempDescriptor> tempItr = fsen.getReadyInVarSet().iterator();
3620 while( tempItr.hasNext() ) {
3621 TempDescriptor temp = tempItr.next();
3623 // when we are issuing the main SESE or an SESE with placeholder
3624 // caller SESE as parent, generate temp child child's eclosing method,
3625 // otherwise use the parent's enclosing method as the context
3626 boolean useParentContext = false;
3628 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3629 (state.OOOJAVA && fsen != oooa.getMainSESE())
3631 assert fsen.getParent() != null;
3632 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3633 useParentContext = true;
3637 if( useParentContext ) {
3638 output.println(" seseToIssue->"+temp+" = "+
3639 generateTemp( fsen.getParent().getfmBogus(), temp, null )+";");
3641 output.println(" seseToIssue->"+temp+" = "+
3642 generateTemp( fsen.getfmEnclosing(), temp, null )+";");
3646 // before potentially adding this SESE to other forwarding lists,
3647 // create it's lock and take it immediately
3648 output.println(" pthread_mutex_init( &(seseToIssue->common.lock), NULL );");
3649 // output.println(" pthread_mutex_lock( &(seseToIssue->common.lock) );");
3651 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3652 (state.OOOJAVA && fsen != oooa.getMainSESE())
3654 // count up outstanding dependencies, static first, then dynamic
3655 Iterator<SESEandAgePair> staticSrcsItr = fsen.getStaticInVarSrcs().iterator();
3656 while( staticSrcsItr.hasNext() ) {
3657 SESEandAgePair srcPair = staticSrcsItr.next();
3658 output.println(" {");
3659 output.println(" SESEcommon* src = (SESEcommon*)"+srcPair+";");
3661 if(GENERATEPRECISEGC){
3662 output.println(" stopforgc((struct garbagelist *)&___locals___);");
3664 output.println(" pthread_mutex_lock( &(src->lock) );");
3665 if(GENERATEPRECISEGC){
3666 output.println(" restartaftergc();");
3668 output.println(" if( !isEmpty( src->forwardList ) &&");
3669 output.println(" seseToIssue == peekItem( src->forwardList ) ) {");
3670 output.println(" printf( \"This shouldnt already be here\\n\");");
3671 output.println(" exit( -1 );");
3672 output.println(" }");
3673 output.println(" if( !src->doneExecuting ) {");
3674 output.println(" addNewItem( src->forwardList, seseToIssue );");
3675 // output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3676 output.println(" ++(localCount);");
3677 output.println(" }");
3678 output.println(" pthread_mutex_unlock( &(src->lock) );");
3679 output.println(" }");
3681 // whether or not it is an outstanding dependency, make sure
3682 // to pass the static name to the child's record
3683 output.println(" seseToIssue->"+srcPair+" = "+srcPair+";");
3686 // dynamic sources might already be accounted for in the static list,
3687 // so only add them to forwarding lists if they're not already there
3688 Iterator<TempDescriptor> dynVarsItr = fsen.getDynamicInVarSet().iterator();
3689 while( dynVarsItr.hasNext() ) {
3690 TempDescriptor dynInVar = dynVarsItr.next();
3691 output.println(" {");
3692 output.println(" SESEcommon* src = (SESEcommon*)"+dynInVar+"_srcSESE;");
3694 // the dynamic source is NULL if it comes from your own space--you can't pass
3695 // the address off to the new child, because you're not done executing and
3696 // might change the variable, so copy it right now
3697 output.println(" if( src != NULL ) {");
3699 if(GENERATEPRECISEGC){
3700 output.println(" stopforgc((struct garbagelist *)&___locals___);");
3702 output.println(" pthread_mutex_lock( &(src->lock) );");
3703 if(GENERATEPRECISEGC){
3704 output.println(" restartaftergc();");
3706 output.println(" if( isEmpty( src->forwardList ) ||");
3707 output.println(" seseToIssue != peekItem( src->forwardList ) ) {");
3708 output.println(" if( !src->doneExecuting ) {");
3709 output.println(" addNewItem( src->forwardList, seseToIssue );");
3710 // output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3711 output.println(" ++(localCount);");
3712 output.println(" }");
3713 output.println(" }");
3714 output.println(" pthread_mutex_unlock( &(src->lock) );");
3715 output.println(" seseToIssue->"+dynInVar+"_srcOffset = "+dynInVar+"_srcOffset;");
3716 output.println(" } else {");
3718 boolean useParentContext = false;
3719 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3720 (state.OOOJAVA && fsen != oooa.getMainSESE())
3722 assert fsen.getParent() != null;
3723 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3724 useParentContext = true;
3727 if( useParentContext ) {
3728 output.println(" seseToIssue->"+dynInVar+" = "+
3729 generateTemp( fsen.getParent().getfmBogus(), dynInVar, null )+";");
3731 output.println(" seseToIssue->"+dynInVar+" = "+
3732 generateTemp( fsen.getfmEnclosing(), dynInVar, null )+";");
3735 output.println(" }");
3736 output.println(" }");
3738 // even if the value is already copied, make sure your NULL source
3739 // gets passed so child knows it already has the dynamic value
3740 output.println(" seseToIssue->"+dynInVar+"_srcSESE = "+dynInVar+"_srcSESE;");
3743 // maintain pointers for finding dynamic SESE
3744 // instances from static names
3745 SESEandAgePair pair = new SESEandAgePair( fsen, 0 );
3746 if( fsen.getParent() != null &&
3747 //!fsen.getParent().getIsCallerSESEplaceholder() &&
3748 fsen.getParent().getNeededStaticNames().contains( pair )
3751 for( int i = fsen.getOldestAgeToTrack(); i > 0; --i ) {
3752 SESEandAgePair pair1 = new SESEandAgePair( fsen, i );
3753 SESEandAgePair pair2 = new SESEandAgePair( fsen, i-1 );
3754 output.println(" "+pair1+" = "+pair2+";");
3756 output.println(" "+pair+" = seseToIssue;");
3760 // count up memory conflict dependencies,
3764 FlatSESEEnterNode parent = fsen.getParent();
3765 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(parent);
3766 if (graph != null && graph.hasConflictEdge()) {
3767 Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
3769 output.println(" //add memory queue element");
3770 Analysis.OoOJava.SESEWaitingQueue seseWaitingQueue=
3771 graph.getWaitingElementSetBySESEID(fsen.getIdentifier(), seseLockSet);
3772 if(seseWaitingQueue.getWaitingElementSize()>0){
3773 output.println(" {");
3774 output.println(" REntry* rentry=NULL;");
3775 output.println(" INTPTR* pointer=NULL;");
3776 output.println(" seseToIssue->common.rentryIdx=0;");
3778 Set<Integer> queueIDSet=seseWaitingQueue.getQueueIDSet();
3779 for (Iterator iterator = queueIDSet.iterator(); iterator
3781 Integer key = (Integer) iterator.next();
3782 int queueID=key.intValue();
3783 Set<Analysis.OoOJava.WaitingElement> waitingQueueSet =
3784 seseWaitingQueue.getWaitingElementSet(queueID);
3785 int enqueueType=seseWaitingQueue.getType(queueID);
3786 if(enqueueType==SESEWaitingQueue.EXCEPTION){
3787 output.println(" INITIALIZEBUF(parentCommon->memoryQueueArray["
3790 for (Iterator iterator2 = waitingQueueSet.iterator(); iterator2
3792 Analysis.OoOJava.WaitingElement waitingElement
3793 = (Analysis.OoOJava.WaitingElement) iterator2.next();
3794 if (waitingElement.getStatus() >= ConflictNode.COARSE) {
3795 output.println(" rentry=mlpCreateREntry("
3796 + waitingElement.getStatus()
3797 + ", seseToIssue);");
3799 TempDescriptor td = waitingElement
3801 // decide whether waiting element is dynamic or static
3802 if (fsen.getDynamicInVarSet().contains(td)) {
3803 // dynamic in-var case
3804 output.println(" pointer=seseToIssue->"
3805 + waitingElement.getDynID()
3806 + "_srcSESE+seseToIssue->"
3807 + waitingElement.getDynID()
3810 .println(" rentry=mlpCreateFineREntry("
3813 + ", seseToIssue, pointer );");
3814 } else if (fsen.getStaticInVarSet()
3816 // static in-var case
3817 VariableSourceToken vst = fsen
3818 .getStaticInVarSrc(td);
3821 String srcId = "SESE_"
3823 .getPrettyIdentifier()
3824 + vst.getSESE().getIdentifier()
3825 + "_" + vst.getAge();
3827 .println(" pointer=(void*)&seseToIssue->"
3834 .println(" rentry=mlpCreateFineREntry("
3837 + ", seseToIssue, pointer );");
3842 .println(" rentry=mlpCreateFineREntry("
3845 + ", seseToIssue, (void*)&seseToIssue->"
3846 + waitingElement.getDynID()
3851 .println(" rentry->queue=parentCommon->memoryQueueArray["
3852 + waitingElement.getQueueID()
3855 if(enqueueType==SESEWaitingQueue.NORMAL){
3857 .println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
3859 .println(" if(ADDRENTRY(parentCommon->memoryQueueArray["
3860 + waitingElement.getQueueID()
3861 + "],rentry)==NOTREADY){");
3862 output.println(" ++(localCount);");
3863 output.println(" }");
3865 // Trying to execute the dynamic coarse grain conflict strategy...
3866 if(state.RCR && rcr != null) {
3867 boolean useParentContext = false;
3869 if( (state.MLP &&fsen != mlpa.getMainSESE()) ||
3870 (state.OOOJAVA &&fsen != oooa.getMainSESE())) {
3871 assert fsen.getParent() != null;
3872 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3873 useParentContext = true;
3877 //TODO fix this workaround later by invoking it only once in the lifetime of the program
3878 output.println(" initializeStructsRCR();");
3880 for (TempDescriptor invar : fsen.getInVarsForDynamicCoarseConflictResolution()) {
3882 if( useParentContext ) {
3883 varString = generateTemp( fsen.getParent().getfmBogus(), invar, null );
3885 varString = generateTemp( fsen.getfmEnclosing(), invar, null );
3887 output.println(" "+rcr.getTraverserInvocation(invar, varString, fsen));
3892 .println(" ADDRENTRYTOBUF(parentCommon->memoryQueueArray["
3893 + waitingElement.getQueueID()
3897 if(enqueueType!=SESEWaitingQueue.NORMAL){
3898 output.println(" localCount+=RESOLVEBUF(parentCommon->memoryQueueArray["
3899 + queueID+ "],&seseToIssue->common);");
3902 output.println(" }");
3908 ConflictGraph graph = null;
3909 FlatSESEEnterNode parent = fsen.getParent();
3910 if (parent != null) {
3911 if (parent.isCallerSESEplaceholder) {
3912 graph = mlpa.getConflictGraphResults().get(parent.getfmEnclosing());
3914 graph = mlpa.getConflictGraphResults().get(parent);
3917 if (graph != null && graph.hasConflictEdge()) {
3918 HashSet<SESELock> seseLockSet = mlpa.getConflictGraphLockMap()
3921 output.println(" //add memory queue element");
3922 SESEWaitingQueue seseWaitingQueue=graph.getWaitingElementSetBySESEID(fsen.getIdentifier(),
3924 if(seseWaitingQueue.getWaitingElementSize()>0){
3925 output.println(" {");
3926 output.println(" REntry* rentry=NULL;");
3927 output.println(" INTPTR* pointer=NULL;");
3928 output.println(" seseToIssue->common.rentryIdx=0;");
3930 Set<Integer> queueIDSet=seseWaitingQueue.getQueueIDSet();
3931 for (Iterator iterator = queueIDSet.iterator(); iterator
3933 Integer key = (Integer) iterator.next();
3934 int queueID=key.intValue();
3935 Set<WaitingElement> waitingQueueSet = seseWaitingQueue.getWaitingElementSet(queueID);
3936 int enqueueType=seseWaitingQueue.getType(queueID);
3937 if(enqueueType==SESEWaitingQueue.EXCEPTION){
3938 output.println(" INITIALIZEBUF(parentCommon->memoryQueueArray["
3941 for (Iterator iterator2 = waitingQueueSet.iterator(); iterator2
3943 WaitingElement waitingElement = (WaitingElement) iterator2
3945 if (waitingElement.getStatus() >= ConflictNode.COARSE) {
3946 output.println(" rentry=mlpCreateREntry("
3947 + waitingElement.getStatus()
3948 + ", seseToIssue);");
3950 TempDescriptor td = waitingElement
3952 // decide whether waiting element is dynamic or
3954 if (fsen.getDynamicInVarSet().contains(td)) {
3955 // dynamic in-var case
3956 output.println(" pointer=seseToIssue->"
3957 + waitingElement.getDynID()
3958 + "_srcSESE+seseToIssue->"
3959 + waitingElement.getDynID()
3962 .println(" rentry=mlpCreateFineREntry("
3965 + ", seseToIssue, pointer );");
3966 } else if (fsen.getStaticInVarSet()
3968 // static in-var case
3969 VariableSourceToken vst = fsen
3970 .getStaticInVarSrc(td);
3973 String srcId = "SESE_"
3975 .getPrettyIdentifier()
3976 + vst.getSESE().getIdentifier()
3977 + "_" + vst.getAge();
3979 .println(" pointer=(void*)&seseToIssue->"
3986 .println(" rentry=mlpCreateFineREntry("
3989 + ", seseToIssue, pointer );");
3994 .println(" rentry=mlpCreateFineREntry("
3997 + ", seseToIssue, (void*)&seseToIssue->"
3998 + waitingElement.getDynID()
4003 .println(" rentry->queue=parentCommon->memoryQueueArray["
4004 + waitingElement.getQueueID()
4007 if(enqueueType==SESEWaitingQueue.NORMAL){
4009 .println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
4011 .println(" if(ADDRENTRY(parentCommon->memoryQueueArray["
4012 + waitingElement.getQueueID()
4013 + "],rentry)==NOTREADY){");
4014 output.println(" ++(localCount);");
4015 output.println(" } ");
4018 .println(" ADDRENTRYTOBUF(parentCommon->memoryQueueArray["
4019 + waitingElement.getQueueID()
4023 if(enqueueType!=SESEWaitingQueue.NORMAL){
4024 output.println(" localCount+=RESOLVEBUF(parentCommon->memoryQueueArray["
4025 + queueID+ "],&seseToIssue->common);");
4028 output.println(" }");
4036 // release this SESE for siblings to update its dependencies or,
4037 // eventually, for it to mark itself finished
4038 // output.println(" pthread_mutex_unlock( &(seseToIssue->common.lock) );");
4040 // if there were no outstanding dependencies, issue here
4041 output.println(" if( atomic_sub_and_test(10000-localCount,&(seseToIssue->common.unresolvedDependencies) ) ) {");
4042 output.println(" workScheduleSubmit( (void*)seseToIssue );");
4043 output.println(" }");
4045 output.println(" if( seseToIssue->common.unresolvedDependencies == 0 ) {");
4046 output.println(" workScheduleSubmit( (void*)seseToIssue );");
4047 output.println(" }");
4049 // release this SESE for siblings to update its dependencies or,
4050 // eventually, for it to mark itself finished
4051 // output.println(" pthread_mutex_unlock( &(seseToIssue->common.lock) );");
4054 //output.println("CP_LOGEVENT( CP_EVENTID_TASKDISPATCH, CP_EVENTTYPE_END );");
4056 output.println(" }");
4060 public void generateFlatSESEExitNode( FlatMethod fm,
4062 FlatSESEExitNode fsexn,
4066 // if MLP flag is off, okay that SESE nodes are in IR graph,
4067 // just skip over them and code generates exactly the same
4068 if( ! (state.MLP || state.OOOJAVA) ) {
4072 //output.println("CP_LOGEVENT( CP_EVENTID_TASKRETIRE, CP_EVENTTYPE_BEGIN );");
4074 // get the enter node for this exit that has meta data embedded
4075 FlatSESEEnterNode fsen = fsexn.getFlatEnter();
4077 // there may be an SESE in an unreachable method, skip over
4078 if( (state.MLP && !mlpa.getAllSESEs().contains( fsen )) ||
4079 (state.OOOJAVA && !oooa.getAllSESEs().contains( fsen ))
4084 // also, if we have encountered a placeholder, just jump it
4085 if( fsen.getIsCallerSESEplaceholder() ) {
4089 output.println(" /* SESE exiting */");
4091 String com = paramsprefix+"->common";
4093 // this SESE cannot be done until all of its children are done
4094 // so grab your own lock with the condition variable for watching
4095 // that the number of your running children is greater than zero
4096 if (GENERATEPRECISEGC){
4097 output.println(" stopforgc((struct garbagelist *)&___locals___);");
4099 output.println(" pthread_mutex_lock( &("+com+".lock) );");
4100 if (GENERATEPRECISEGC){
4101 output.println(" restartaftergc();");
4103 output.println(" while( "+com+".numRunningChildren > 0 ) {");
4104 if (GENERATEPRECISEGC){
4105 // output.println(" stopforgc((struct garbagelist *)&(((SESEcommon*)(___params___))[1]));");
4106 output.println(" stopforgc((struct garbagelist *)&___locals___);");
4108 output.println(" pthread_cond_wait( &("+com+".runningChildrenCond), &("+com+".lock) );");
4109 if (GENERATEPRECISEGC){
4110 output.println(" restartaftergc();");
4112 output.println(" }");
4115 // copy out-set from local temps into the sese record
4116 Iterator<TempDescriptor> itr = fsen.getOutVarSet().iterator();
4117 while( itr.hasNext() ) {
4118 TempDescriptor temp = itr.next();
4120 // only have to do this for primitives non-arrays
4122 temp.getType().isPrimitive() && !temp.getType().isArray()
4128 // have to determine the context enclosing this sese
4129 boolean useParentContext = false;
4131 if( (state.MLP &&fsen != mlpa.getMainSESE()) ||
4132 (state.OOOJAVA &&fsen != oooa.getMainSESE())
4134 assert fsen.getParent() != null;
4135 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
4136 useParentContext = true;
4141 if( useParentContext ) {
4142 from = generateTemp( fsen.getParent().getfmBogus(), temp, null );
4144 from = generateTemp( fsen.getfmEnclosing(), temp, null );
4147 output.println(" "+paramsprefix+
4148 "->"+temp.getSafeSymbol()+
4152 // mark yourself done, your SESE data is now read-only
4153 output.println(" "+com+".doneExecuting = TRUE;");
4154 output.println(" pthread_cond_signal( &("+com+".doneCond) );");
4155 output.println(" pthread_mutex_unlock( &("+com+".lock) );");
4157 // decrement dependency count for all SESE's on your forwarding list
4158 output.println(" while( !isEmpty( "+com+".forwardList ) ) {");
4159 output.println(" SESEcommon* consumer = (SESEcommon*) getItem( "+com+".forwardList );");
4162 output.println(" if(consumer->rentryIdx>0){");
4163 output.println(" // resolved null pointer");
4164 output.println(" int idx;");
4165 output.println(" for(idx=0;idx<consumer->rentryIdx;idx++){");
4166 output.println(" resolvePointer(consumer->rentryArray[idx]);");
4167 output.println(" }");
4168 output.println(" }");
4171 // output.println(" pthread_mutex_lock( &(consumer->lock) );");
4172 // output.println(" --(consumer->unresolvedDependencies);");
4173 // output.println(" if( consumer->unresolvedDependencies == 0 ) {");
4174 output.println(" if( atomic_sub_and_test(1, &(consumer->unresolvedDependencies)) ){");
4175 output.println(" workScheduleSubmit( (void*)consumer );");
4176 output.println(" }");
4177 // output.println(" pthread_mutex_unlock( &(consumer->lock) );");
4178 output.println(" }");
4182 // clean up its lock element from waiting queue, and decrement dependency count for next SESE block
4183 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
4184 (state.OOOJAVA && fsen != oooa.getMainSESE())
4188 output.println(" /* check memory dependency*/");
4189 output.println(" {");
4190 output.println(" int idx;");
4191 output.println(" for(idx=0;idx<___params___->common.rentryIdx;idx++){");
4192 output.println(" REntry* re=___params___->common.rentryArray[idx];");
4193 output.println(" RETIRERENTRY(re->queue,re);");
4194 output.println(" }");
4195 output.println(" }");
4199 // if parent is stalling on you, let them know you're done
4200 if( (state.MLP && fsexn.getFlatEnter() != mlpa.getMainSESE()) ||
4201 (state.OOOJAVA && fsexn.getFlatEnter() != oooa.getMainSESE())
4203 output.println(" psem_give( &("+paramsprefix+"->common.stallSem) );");
4206 // last of all, decrement your parent's number of running children
4207 output.println(" if( "+paramsprefix+"->common.parent != NULL ) {");
4208 output.println(" if (atomic_sub_and_test(1, &"+paramsprefix+"->common.parent->numRunningChildren)) {");
4209 if (GENERATEPRECISEGC){
4210 output.println(" stopforgc((struct garbagelist *)&___locals___);");
4212 output.println(" pthread_mutex_lock( &("+paramsprefix+"->common.parent->lock) );");
4213 if (GENERATEPRECISEGC){
4214 output.println(" restartaftergc();");
4216 output.println(" pthread_cond_signal( &("+paramsprefix+"->common.parent->runningChildrenCond) );");
4217 output.println(" pthread_mutex_unlock( &("+paramsprefix+"->common.parent->lock) );");
4218 output.println(" }");
4219 output.println(" }");
4221 // this is a thread-only variable that can be handled when critical sese-to-sese
4222 // data has been taken care of--set sese pointer to remember self over method
4223 // calls to a non-zero, invalid address
4224 output.println(" seseCaller = (SESEcommon*) 0x1;");
4227 //output.println("CP_LOGEVENT( CP_EVENTID_TASKRETIRE, CP_EVENTTYPE_END );");
4230 public void generateFlatWriteDynamicVarNode( FlatMethod fm,
4232 FlatWriteDynamicVarNode fwdvn,
4235 if( !(state.MLP || state.OOOJAVA) ) {
4236 // should node should not be in an IR graph if the
4237 // MLP flag is not set
4238 throw new Error("Unexpected presence of FlatWriteDynamicVarNode");
4241 Hashtable<TempDescriptor, VSTWrapper> writeDynamic = fwdvn.getVar2src();
4243 assert writeDynamic != null;
4245 Iterator wdItr = writeDynamic.entrySet().iterator();
4246 while( wdItr.hasNext() ) {
4247 Map.Entry me = (Map.Entry) wdItr.next();
4248 TempDescriptor refVar = (TempDescriptor) me.getKey();
4249 VSTWrapper vstW = (VSTWrapper) me.getValue();
4250 VariableSourceToken vst = vstW.vst;
4253 // only do this if the variable in question should be tracked,
4254 // meaning that it was explicitly added to the dynamic var set
4255 if( !current.getDynamicVarSet().contains( vst.getAddrVar() ) ) {
4261 // if there is no given source, this variable is ready so
4262 // mark src pointer NULL to signify that the var is up-to-date
4263 output.println(" "+refVar+"_srcSESE = NULL;");
4267 // otherwise we track where it will come from
4268 SESEandAgePair instance = new SESEandAgePair( vst.getSESE(), vst.getAge() );
4269 output.println(" "+refVar+"_srcSESE = "+instance+";");
4270 output.println(" "+refVar+"_srcOffset = (INTPTR) &((("+
4271 vst.getSESE().getSESErecordName()+"*)0)->"+vst.getAddrVar()+");");
4276 private void generateFlatCheckNode(FlatMethod fm, LocalityBinding lb, FlatCheckNode fcn, PrintWriter output) {
4277 if (state.CONSCHECK) {
4278 String specname=fcn.getSpec();
4279 String varname="repairstate___";
4280 output.println("{");
4281 output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
4283 TempDescriptor[] temps=fcn.getTemps();
4284 String[] vars=fcn.getVars();
4285 for(int i=0; i<temps.length; i++) {
4286 output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i],lb)+";");
4289 output.println("if (doanalysis"+specname+"("+varname+")) {");
4290 output.println("free"+specname+"_state("+varname+");");
4291 output.println("} else {");
4292 output.println("/* Bad invariant */");
4293 output.println("free"+specname+"_state("+varname+");");
4294 output.println("abort_task();");
4295 output.println("}");
4296 output.println("}");
4300 private void generateFlatCall(FlatMethod fm, LocalityBinding lb, FlatCall fc, PrintWriter output) {
4302 if( (state.MLP && !nonSESEpass) ||
4303 (state.OOOJAVA && !nonSESEpass)
4305 output.println(" seseCaller = (SESEcommon*)"+paramsprefix+";");
4308 MethodDescriptor md=fc.getMethod();
4309 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? locality.getBinding(lb, fc) : md);
4310 ClassDescriptor cn=md.getClassDesc();
4311 output.println("{");
4312 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4314 LocalityBinding fclb=locality.getBinding(lb, fc);
4315 output.print(" struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
4317 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
4318 output.print(objectparams.numPointers());
4319 output.print(", "+localsprefixaddr);
4320 if (md.getThis()!=null) {
4322 output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis(),lb));
4324 if (fc.getThis()!=null&&md.getThis()==null) {
4325 System.out.println("WARNING!!!!!!!!!!!!");
4326 System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
4330 for(int i=0; i<fc.numArgs(); i++) {
4331 Descriptor var=md.getParameter(i);
4332 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
4333 if (objectparams.isParamPtr(paramtemp)) {
4334 TempDescriptor targ=fc.getArg(i);
4336 TypeDescriptor td=md.getParamType(i);
4338 output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
4340 output.print("(struct "+md.getParamType(i).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
4343 output.println("};");
4348 if (fc.getReturnTemp()!=null)
4349 output.print(generateTemp(fm,fc.getReturnTemp(),lb)+"=");
4351 /* Do we need to do virtual dispatch? */
4352 if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
4355 LocalityBinding fclb=locality.getBinding(lb, fc);
4356 output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
4358 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
4363 if (md.getReturnType().isClass()||md.getReturnType().isArray())
4364 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
4366 output.print(md.getReturnType().getSafeSymbol()+" ");
4367 output.print("(*)(");
4369 boolean printcomma=false;
4370 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4372 LocalityBinding fclb=locality.getBinding(lb, fc);
4373 output.print("struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
4375 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
4379 for(int i=0; i<objectparams.numPrimitives(); i++) {
4380 TempDescriptor temp=objectparams.getPrimitive(i);
4384 if (temp.getType().isClass()||temp.getType().isArray())
4385 output.print("struct " + temp.getType().getSafeSymbol()+" * ");
4387 output.print(temp.getType().getSafeSymbol());
4392 LocalityBinding fclb=locality.getBinding(lb, fc);
4393 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])");
4395 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
4399 boolean needcomma=false;
4400 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4401 output.print("&__parameterlist__");
4405 if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
4406 if (fc.getThis()!=null) {
4407 TypeDescriptor ptd=md.getThis().getType();
4410 if (ptd.isClass()&&!ptd.isArray())
4411 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
4412 output.print(generateTemp(fm,fc.getThis(),lb));
4417 for(int i=0; i<fc.numArgs(); i++) {
4418 Descriptor var=md.getParameter(i);
4419 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
4420 if (objectparams.isParamPrim(paramtemp)) {
4421 TempDescriptor targ=fc.getArg(i);
4425 TypeDescriptor ptd=md.getParamType(i);
4426 if (ptd.isClass()&&!ptd.isArray())
4427 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
4428 output.print(generateTemp(fm, targ,lb));
4432 output.println(");");
4433 output.println(" }");
4436 private boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
4437 Set subclasses=typeutil.getSubClasses(thiscd);
4438 if (subclasses==null)
4440 for(Iterator classit=subclasses.iterator(); classit.hasNext();) {
4441 ClassDescriptor cd=(ClassDescriptor)classit.next();
4442 Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol());
4443 for(Iterator matchit=possiblematches.iterator(); matchit.hasNext();) {
4444 MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
4445 if (md.matches(matchmd))
4452 private void generateFlatFieldNode(FlatMethod fm, LocalityBinding lb, FlatFieldNode ffn, PrintWriter output) {
4453 if (state.SINGLETM) {
4454 //single machine transactional memory case
4455 String field=ffn.getField().getSafeSymbol();
4456 String src=generateTemp(fm, ffn.getSrc(),lb);
4457 String dst=generateTemp(fm, ffn.getDst(),lb);
4459 output.println(dst+"="+ src +"->"+field+ ";");
4460 if (ffn.getField().getType().isPtr()&&locality.getAtomic(lb).get(ffn).intValue()>0&&
4461 locality.getNodePreTempInfo(lb, ffn).get(ffn.getSrc())!=LocalityAnalysis.SCRATCH) {
4462 if ((dc==null)||(!state.READSET&&dc.getNeedTrans(lb, ffn))||
4463 (state.READSET&&dc.getNeedWriteTrans(lb, ffn))) {
4464 output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));");
4465 } else if (state.READSET&&dc.getNeedTrans(lb, ffn)) {
4466 if (state.HYBRID&&delaycomp.getConv(lb).contains(ffn)) {
4467 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4469 output.println("TRANSREADRD("+dst+", "+dst+");");
4472 } else if (state.DSM) {
4473 Integer status=locality.getNodePreTempInfo(lb,ffn).get(ffn.getSrc());
4474 if (status==LocalityAnalysis.GLOBAL) {
4475 String field=ffn.getField().getSafeSymbol();
4476 String src=generateTemp(fm, ffn.getSrc(),lb);
4477 String dst=generateTemp(fm, ffn.getDst(),lb);
4479 if (ffn.getField().getType().isPtr()) {
4481 //TODO: Uncomment this when we have runtime support
4482 //if (ffn.getSrc()==ffn.getDst()) {
4483 //output.println("{");
4484 //output.println("void * temp="+src+";");
4485 //output.println("if (temp&0x1) {");
4486 //output.println("temp=(void *) transRead(trans, (unsigned int) temp);");
4487 //output.println(src+"->"+field+"="+temp+";");
4488 //output.println("}");
4489 //output.println(dst+"=temp;");
4490 //output.println("}");
4492 output.println(dst+"="+ src +"->"+field+ ";");
4493 //output.println("if ("+dst+"&0x1) {");
4494 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
4495 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
4496 //output.println(src+"->"+field+"="+src+"->"+field+";");
4497 //output.println("}");
4500 output.println(dst+"="+ src+"->"+field+";");
4502 } else if (status==LocalityAnalysis.LOCAL) {
4503 if (ffn.getField().getType().isPtr()&&
4504 ffn.getField().isGlobal()) {
4505 String field=ffn.getField().getSafeSymbol();
4506 String src=generateTemp(fm, ffn.getSrc(),lb);
4507 String dst=generateTemp(fm, ffn.getDst(),lb);
4508 output.println(dst+"="+ src +"->"+field+ ";");
4509 if (locality.getAtomic(lb).get(ffn).intValue()>0)
4510 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
4511 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
4513 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4514 } else if (status==LocalityAnalysis.EITHER) {
4515 //Code is reading from a null pointer
4516 output.println("if ("+generateTemp(fm, ffn.getSrc(),lb)+") {");
4517 output.println("#ifndef RAW");
4518 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4519 output.println("#endif");
4520 //This should throw a suitable null pointer error
4521 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4523 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4525 // DEBUG if(!ffn.getDst().getType().isPrimitive()){
4526 // DEBUG output.println("within((void*)"+generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+");");
4528 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4533 private void generateFlatSetFieldNode(FlatMethod fm, LocalityBinding lb, FlatSetFieldNode fsfn, PrintWriter output) {
4534 if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
4535 throw new Error("Can't set array length");
4536 if (state.SINGLETM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
4537 //Single Machine Transaction Case
4538 boolean srcptr=fsfn.getSrc().getType().isPtr();
4539 String src=generateTemp(fm,fsfn.getSrc(),lb);
4540 String dst=generateTemp(fm,fsfn.getDst(),lb);
4541 output.println("//"+srcptr+" "+fsfn.getSrc().getType().isNull());
4542 if (srcptr&&!fsfn.getSrc().getType().isNull()) {
4543 output.println("{");
4544 if ((dc==null)||dc.getNeedSrcTrans(lb, fsfn)&&
4545 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) {
4546 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4548 output.println("INTPTR srcoid=(INTPTR)"+src+";");
4551 if (wb.needBarrier(fsfn)&&
4552 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getDst())!=LocalityAnalysis.SCRATCH) {
4553 if (state.EVENTMONITOR) {
4554 output.println("if ("+dst+"->___objstatus___&DIRTY) EVLOGEVENTOBJ(EV_WRITE,"+dst+"->objuid)");
4556 output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;");
4558 if (srcptr&!fsfn.getSrc().getType().isNull()) {
4559 output.println("*((unsigned INTPTR *)&("+dst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4560 output.println("}");
4562 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4564 } else if (state.DSM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
4565 Integer statussrc=locality.getNodePreTempInfo(lb,fsfn).get(fsfn.getSrc());
4566 Integer statusdst=locality.getNodeTempInfo(lb).get(fsfn).get(fsfn.getDst());
4567 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4569 String src=generateTemp(fm,fsfn.getSrc(),lb);
4570 String dst=generateTemp(fm,fsfn.getDst(),lb);
4572 output.println("{");
4573 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4575 if (statusdst.equals(LocalityAnalysis.GLOBAL)) {
4578 if (wb.needBarrier(fsfn))
4579 output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;");
4581 output.println("*((unsigned INTPTR *)&("+glbdst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4583 output.println(glbdst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4584 } else if (statusdst.equals(LocalityAnalysis.LOCAL)) {
4585 /** Check if we need to copy */
4586 output.println("if(!"+dst+"->"+localcopystr+") {");
4587 /* Link object into list */
4588 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4589 output.println(revertptr+"=revertlist;");
4590 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4591 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4593 output.println("COPY_OBJ("+dst+");");
4594 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4595 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4596 output.println("}");
4598 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4600 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4601 } else if (statusdst.equals(LocalityAnalysis.EITHER)) {
4602 //writing to a null...bad
4603 output.println("if ("+dst+") {");
4604 output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}");
4606 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4608 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4611 output.println("}");
4614 if (state.FASTCHECK) {
4615 String dst=generateTemp(fm, fsfn.getDst(),lb);
4616 output.println("if(!"+dst+"->"+localcopystr+") {");
4617 /* Link object into list */
4618 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4619 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4621 output.println("COPY_OBJ("+dst+");");
4622 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4623 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4624 output.println("}");
4627 // DEBUG if(!fsfn.getField().getType().isPrimitive()){
4628 // DEBUG output.println("within((void*)"+generateTemp(fm,fsfn.getSrc(),lb)+");");
4630 output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
4634 private void generateFlatElementNode(FlatMethod fm, LocalityBinding lb, FlatElementNode fen, PrintWriter output) {
4635 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
4638 if (elementtype.isArray()||elementtype.isClass())
4641 type=elementtype.getSafeSymbol()+" ";
4643 if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
4644 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fen.getIndex(),lb)+") >= "+generateTemp(fm,fen.getSrc(),lb) + "->___length___))");
4645 output.println("failedboundschk();");
4647 if (state.SINGLETM) {
4648 //Single machine transaction case
4649 String dst=generateTemp(fm, fen.getDst(),lb);
4650 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))) {
4651 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4653 output.println("STMGETARRAY("+dst+", "+ generateTemp(fm,fen.getSrc(),lb)+", "+generateTemp(fm, fen.getIndex(),lb)+", "+type+");");
4656 if (elementtype.isPtr()&&locality.getAtomic(lb).get(fen).intValue()>0&&
4657 locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())!=LocalityAnalysis.SCRATCH) {
4658 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fen)||state.READSET&&dc.getNeedWriteTrans(lb, fen)) {
4659 output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));");
4660 } else if (state.READSET&&dc.getNeedTrans(lb, fen)) {
4661 if (state.HYBRID&&delaycomp.getConv(lb).contains(fen)) {
4662 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4664 output.println("TRANSREADRD("+dst+", "+dst+");");
4667 } else if (state.DSM) {
4668 Integer status=locality.getNodePreTempInfo(lb,fen).get(fen.getSrc());
4669 if (status==LocalityAnalysis.GLOBAL) {
4670 String dst=generateTemp(fm, fen.getDst(),lb);
4671 if (elementtype.isPtr()) {
4672 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4673 //DEBUG: output.println("TRANSREAD("+dst+", "+dst+",\""+fm+":"+fen+"\");");
4674 output.println("TRANSREAD("+dst+", "+dst+");");
4676 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4678 } else if (status==LocalityAnalysis.LOCAL) {
4679 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4680 } else if (status==LocalityAnalysis.EITHER) {
4681 //Code is reading from a null pointer
4682 output.println("if ("+generateTemp(fm, fen.getSrc(),lb)+") {");
4683 output.println("#ifndef RAW");
4684 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4685 output.println("#endif");
4686 //This should throw a suitable null pointer error
4687 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4689 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4691 // DEBUG output.println("within((void*)"+generateTemp(fm,fen.getSrc(),lb)+");");
4692 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4696 private void generateFlatSetElementNode(FlatMethod fm, LocalityBinding lb, FlatSetElementNode fsen, PrintWriter output) {
4697 //TODO: need dynamic check to make sure this assignment is actually legal
4698 //Because Object[] could actually be something more specific...ie. Integer[]
4700 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
4703 if (elementtype.isArray()||elementtype.isClass())
4706 type=elementtype.getSafeSymbol()+" ";
4708 if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
4709 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fsen.getIndex(),lb)+") >= "+generateTemp(fm,fsen.getDst(),lb) + "->___length___))");
4710 output.println("failedboundschk();");
4713 if (state.SINGLETM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4714 //Transaction set element case
4715 if (wb.needBarrier(fsen)&&
4716 locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH) {
4717 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___objstatus___))|=DIRTY;");
4719 if (fsen.getSrc().getType().isPtr()&&!fsen.getSrc().getType().isNull()) {
4720 output.println("{");
4721 String src=generateTemp(fm, fsen.getSrc(), lb);
4722 if ((dc==null)||dc.getNeedSrcTrans(lb, fsen)&&
4723 locality.getNodePreTempInfo(lb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) {
4724 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4726 output.println("INTPTR srcoid=(INTPTR)"+src+";");
4728 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
4729 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", srcoid, INTPTR);");
4731 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
4733 output.println("}");
4735 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
4736 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", "+ generateTemp(fm, fsen.getSrc(), lb) +", "+type+");");
4738 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4741 } else if (state.DSM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4742 Integer statussrc=locality.getNodePreTempInfo(lb,fsen).get(fsen.getSrc());
4743 Integer statusdst=locality.getNodePreTempInfo(lb,fsen).get(fsen.getDst());
4744 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4745 boolean dstglobal=statusdst==LocalityAnalysis.GLOBAL;
4746 boolean dstlocal=(statusdst==LocalityAnalysis.LOCAL)||(statusdst==LocalityAnalysis.EITHER);
4749 if (wb.needBarrier(fsen))
4750 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___localcopy___))|=DIRTY;");
4751 } else if (dstlocal) {
4752 /** Check if we need to copy */
4753 String dst=generateTemp(fm, fsen.getDst(),lb);
4754 output.println("if(!"+dst+"->"+localcopystr+") {");
4755 /* Link object into list */
4756 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4757 output.println(revertptr+"=revertlist;");
4758 if ((GENERATEPRECISEGC) || this.state.MULTICOREGC)
4759 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4761 output.println("COPY_OBJ("+dst+");");
4762 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4763 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4764 output.println("}");
4766 System.out.println("Node: "+fsen);
4767 System.out.println(lb);
4768 System.out.println("statusdst="+statusdst);
4769 System.out.println(fm.printMethod());
4770 throw new Error("Unknown array type");
4773 output.println("{");
4774 String src=generateTemp(fm, fsen.getSrc(), lb);
4775 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4776 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
4777 output.println("}");
4779 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4782 if (state.FASTCHECK) {
4783 String dst=generateTemp(fm, fsen.getDst(),lb);
4784 output.println("if(!"+dst+"->"+localcopystr+") {");
4785 /* Link object into list */
4786 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4787 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4789 output.println("COPY_OBJ("+dst+");");
4790 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4791 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4792 output.println("}");
4794 // DEBUG output.println("within((void*)"+generateTemp(fm,fsen.getDst(),lb)+");");
4795 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4799 protected void generateFlatNew(FlatMethod fm, LocalityBinding lb, FlatNew fn, PrintWriter output) {
4800 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
4801 //Stash pointer in case of GC
4802 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4803 output.println(revertptr+"=revertlist;");
4805 if (state.SINGLETM) {
4806 if (fn.getType().isArray()) {
4807 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4808 if (locality.getAtomic(lb).get(fn).intValue()>0) {
4809 //inside transaction
4810 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4812 //outside transaction
4813 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4816 if (locality.getAtomic(lb).get(fn).intValue()>0) {
4817 //inside transaction
4818 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4820 //outside transaction
4821 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4824 } else if (fn.getType().isArray()) {
4825 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4826 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4827 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4828 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4829 if(this.state.MLP || state.OOOJAVA){
4830 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray_mlp("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+", oid, "+oooa.getDisjointAnalysis().getAllocationSiteFromFlatNew(fn).getUniqueAllocSiteID()+");");
4831 output.println(" oid += numWorkers;");
4833 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4836 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4839 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4840 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");");
4841 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4842 if (this.state.MLP || state.OOOJAVA){
4843 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new_mlp("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+", oid, "+oooa.getDisjointAnalysis().getAllocationSiteFromFlatNew(fn).getUniqueAllocSiteID()+");");
4844 output.println(" oid += numWorkers;");
4846 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4849 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
4852 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
4853 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4854 String dst=generateTemp(fm,fn.getDst(),lb);
4855 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
4856 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4857 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4859 if (state.FASTCHECK) {
4860 String dst=generateTemp(fm,fn.getDst(),lb);
4861 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
4862 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4863 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4867 private void generateFlatTagDeclaration(FlatMethod fm, LocalityBinding lb, FlatTagDeclaration fn, PrintWriter output) {
4868 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4869 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
4871 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+state.getTagId(fn.getType())+");");
4875 private void generateFlatOpNode(FlatMethod fm, LocalityBinding lb, FlatOpNode fon, PrintWriter output) {
4876 if (fon.getRight()!=null) {
4877 if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
4878 if (fon.getLeft().getType().isLong())
4879 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
4881 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned int)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
4883 } else if (dc!=null) {
4884 output.print(generateTemp(fm, fon.getDest(),lb)+" = (");
4885 if (fon.getLeft().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
4886 output.print("(void *)");
4887 if (dc.getNeedLeftSrcTrans(lb, fon))
4888 output.print("("+generateTemp(fm, fon.getLeft(),lb)+"!=NULL?"+generateTemp(fm, fon.getLeft(),lb)+"->"+oidstr+":NULL)");
4890 output.print(generateTemp(fm, fon.getLeft(),lb));
4891 output.print(")"+fon.getOp().toString()+"(");
4892 if (fon.getRight().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
4893 output.print("(void *)");
4894 if (dc.getNeedRightSrcTrans(lb, fon))
4895 output.println("("+generateTemp(fm, fon.getRight(),lb)+"!=NULL?"+generateTemp(fm, fon.getRight(),lb)+"->"+oidstr+":NULL));");
4897 output.println(generateTemp(fm,fon.getRight(),lb)+");");
4899 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+fon.getOp().toString()+generateTemp(fm,fon.getRight(),lb)+";");
4900 } else if (fon.getOp().getOp()==Operation.ASSIGN)
4901 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
4902 else if (fon.getOp().getOp()==Operation.UNARYPLUS)
4903 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
4904 else if (fon.getOp().getOp()==Operation.UNARYMINUS)
4905 output.println(generateTemp(fm, fon.getDest(),lb)+" = -"+generateTemp(fm, fon.getLeft(),lb)+";");
4906 else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
4907 output.println(generateTemp(fm, fon.getDest(),lb)+" = !"+generateTemp(fm, fon.getLeft(),lb)+";");
4908 else if (fon.getOp().getOp()==Operation.COMP)
4909 output.println(generateTemp(fm, fon.getDest(),lb)+" = ~"+generateTemp(fm, fon.getLeft(),lb)+";");
4910 else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
4911 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+"->fses==NULL;");
4913 output.println(generateTemp(fm, fon.getDest(),lb)+fon.getOp().toString()+generateTemp(fm, fon.getLeft(),lb)+";");
4916 private void generateFlatCastNode(FlatMethod fm, LocalityBinding lb, FlatCastNode fcn, PrintWriter output) {
4917 /* TODO: Do type check here */
4918 if (fcn.getType().isArray()) {
4919 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
4920 } else if (fcn.getType().isClass())
4921 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
4923 output.println(generateTemp(fm,fcn.getDst(),lb)+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc(),lb)+";");
4926 private void generateFlatLiteralNode(FlatMethod fm, LocalityBinding lb, FlatLiteralNode fln, PrintWriter output) {
4927 if (fln.getValue()==null)
4928 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
4929 else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
4930 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4931 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
4932 //Stash pointer in case of GC
4933 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4934 output.println(revertptr+"=revertlist;");
4936 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
4937 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
4938 //Stash pointer in case of GC
4939 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4940 output.println("revertlist="+revertptr+";");
4943 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
4945 } else if (fln.getType().isBoolean()) {
4946 if (((Boolean)fln.getValue()).booleanValue())
4947 output.println(generateTemp(fm, fln.getDst(),lb)+"=1;");
4949 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
4950 } else if (fln.getType().isChar()) {
4951 String st=FlatLiteralNode.escapeString(fln.getValue().toString());
4952 output.println(generateTemp(fm, fln.getDst(),lb)+"='"+st+"';");
4953 } else if (fln.getType().isLong()) {
4954 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+"LL;");
4956 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+";");
4959 protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) {
4960 if (frn.getReturnTemp()!=null) {
4961 if (frn.getReturnTemp().getType().isPtr())
4962 output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";");
4964 output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";");
4966 output.println("return;");
4970 protected void generateStoreFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
4973 //only record if this group has more than one exit
4974 if (branchanalysis.numJumps(fcb)>1) {
4975 left=branchanalysis.jumpValue(fcb, 0);
4976 right=branchanalysis.jumpValue(fcb, 1);
4978 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") {");
4980 output.println("STOREBRANCH("+right+");");
4981 output.println("goto "+label+";");
4982 output.println("}");
4984 output.println("STOREBRANCH("+left+");");
4987 protected void generateFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
4988 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") goto "+label+";");
4991 /** This method generates header information for the method or
4992 * task referenced by the Descriptor des. */
4993 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) {
4994 generateHeader(fm, lb, des, output, false);
4997 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output, boolean addSESErecord) {
4999 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : des);
5000 MethodDescriptor md=null;
5001 TaskDescriptor task=null;
5002 if (des instanceof MethodDescriptor)
5003 md=(MethodDescriptor) des;
5005 task=(TaskDescriptor) des;
5007 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
5009 if (md!=null&&md.getReturnType()!=null) {
5010 if (md.getReturnType().isClass()||md.getReturnType().isArray())
5011 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
5013 output.print(md.getReturnType().getSafeSymbol()+" ");
5015 //catch the constructor case
5016 output.print("void ");
5018 if (state.DSM||state.SINGLETM) {
5019 output.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
5021 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
5023 output.print(task.getSafeSymbol()+"(");
5025 boolean printcomma=false;
5026 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5028 if (state.DSM||state.SINGLETM) {
5029 output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
5031 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
5033 output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
5039 for(int i=0; i<objectparams.numPrimitives(); i++) {
5040 TempDescriptor temp=objectparams.getPrimitive(i);
5044 if (temp.getType().isClass()||temp.getType().isArray())
5045 output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
5047 output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
5049 output.println(") {");
5050 } else if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
5051 /* Imprecise Task */
5052 output.println("void * parameterarray[]) {");
5053 /* Unpack variables */
5054 for(int i=0; i<objectparams.numPrimitives(); i++) {
5055 TempDescriptor temp=objectparams.getPrimitive(i);
5056 output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
5058 for(int i=0; i<fm.numTags(); i++) {
5059 TempDescriptor temp=fm.getTag(i);
5060 int offset=i+objectparams.numPrimitives();
5061 output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
5064 if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
5065 maxtaskparams=objectparams.numPrimitives()+fm.numTags();
5066 } else output.println(") {");
5069 public void generateFlatFlagActionNode(FlatMethod fm, LocalityBinding lb, FlatFlagActionNode ffan, PrintWriter output) {
5070 output.println("/* FlatFlagActionNode */");
5073 /* Process tag changes */
5074 Relation tagsettable=new Relation();
5075 Relation tagcleartable=new Relation();
5077 Iterator tagsit=ffan.getTempTagPairs();
5078 while (tagsit.hasNext()) {
5079 TempTagPair ttp=(TempTagPair) tagsit.next();
5080 TempDescriptor objtmp=ttp.getTemp();
5081 TagDescriptor tag=ttp.getTag();
5082 TempDescriptor tagtmp=ttp.getTagTemp();
5083 boolean tagstatus=ffan.getTagChange(ttp);
5085 tagsettable.put(objtmp, tagtmp);
5087 tagcleartable.put(objtmp, tagtmp);
5092 Hashtable flagandtable=new Hashtable();
5093 Hashtable flagortable=new Hashtable();
5095 /* Process flag changes */
5096 Iterator flagsit=ffan.getTempFlagPairs();
5097 while(flagsit.hasNext()) {
5098 TempFlagPair tfp=(TempFlagPair)flagsit.next();
5099 TempDescriptor temp=tfp.getTemp();
5100 Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
5101 FlagDescriptor flag=tfp.getFlag();
5103 //Newly allocate objects that don't set any flags case
5104 if (flagortable.containsKey(temp)) {
5108 flagortable.put(temp,new Integer(mask));
5110 int flagid=1<<((Integer)flagtable.get(flag)).intValue();
5111 boolean flagstatus=ffan.getFlagChange(tfp);
5114 if (flagortable.containsKey(temp)) {
5115 mask=((Integer)flagortable.get(temp)).intValue();
5118 flagortable.put(temp,new Integer(mask));
5120 int mask=0xFFFFFFFF;
5121 if (flagandtable.containsKey(temp)) {
5122 mask=((Integer)flagandtable.get(temp)).intValue();
5124 mask&=(0xFFFFFFFF^flagid);
5125 flagandtable.put(temp,new Integer(mask));
5131 HashSet flagtagset=new HashSet();
5132 flagtagset.addAll(flagortable.keySet());
5133 flagtagset.addAll(flagandtable.keySet());
5134 flagtagset.addAll(tagsettable.keySet());
5135 flagtagset.addAll(tagcleartable.keySet());
5137 Iterator ftit=flagtagset.iterator();
5138 while(ftit.hasNext()) {
5139 TempDescriptor temp=(TempDescriptor)ftit.next();
5142 Set tagtmps=tagcleartable.get(temp);
5143 if (tagtmps!=null) {
5144 Iterator tagit=tagtmps.iterator();
5145 while(tagit.hasNext()) {
5146 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
5147 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
5148 output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5150 output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5154 tagtmps=tagsettable.get(temp);
5155 if (tagtmps!=null) {
5156 Iterator tagit=tagtmps.iterator();
5157 while(tagit.hasNext()) {
5158 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
5159 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
5160 output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5162 output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp, lb)+", "+generateTemp(fm,tagtmp, lb)+");");
5167 int andmask=0xFFFFFFF;
5169 if (flagortable.containsKey(temp))
5170 ormask=((Integer)flagortable.get(temp)).intValue();
5171 if (flagandtable.containsKey(temp))
5172 andmask=((Integer)flagandtable.get(temp)).intValue();
5173 generateFlagOrAnd(ffan, fm, lb, temp, output, ormask, andmask);
5174 generateObjectDistribute(ffan, fm, lb, temp, output);
5178 protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp,
5179 PrintWriter output, int ormask, int andmask) {
5180 if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
5181 output.println("flagorandinit("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
5183 output.println("flagorand("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
5187 protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, PrintWriter output) {
5188 output.println("enqueueObject("+generateTemp(fm, temp, lb)+");");
5191 void generateOptionalHeader(PrintWriter headers) {
5194 headers.println("#include \"task.h\"\n\n");
5195 headers.println("#ifndef _OPTIONAL_STRUCT_");
5196 headers.println("#define _OPTIONAL_STRUCT_");
5198 //STRUCT PREDICATEMEMBER
5199 headers.println("struct predicatemember{");
5200 headers.println("int type;");
5201 headers.println("int numdnfterms;");
5202 headers.println("int * flags;");
5203 headers.println("int numtags;");
5204 headers.println("int * tags;\n};\n\n");
5206 //STRUCT OPTIONALTASKDESCRIPTOR
5207 headers.println("struct optionaltaskdescriptor{");
5208 headers.println("struct taskdescriptor * task;");
5209 headers.println("int index;");
5210 headers.println("int numenterflags;");
5211 headers.println("int * enterflags;");
5212 headers.println("int numpredicatemembers;");
5213 headers.println("struct predicatemember ** predicatememberarray;");
5214 headers.println("};\n\n");
5216 //STRUCT TASKFAILURE
5217 headers.println("struct taskfailure {");
5218 headers.println("struct taskdescriptor * task;");
5219 headers.println("int index;");
5220 headers.println("int numoptionaltaskdescriptors;");
5221 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
5223 //STRUCT FSANALYSISWRAPPER
5224 headers.println("struct fsanalysiswrapper{");
5225 headers.println("int flags;");
5226 headers.println("int numtags;");
5227 headers.println("int * tags;");
5228 headers.println("int numtaskfailures;");
5229 headers.println("struct taskfailure ** taskfailurearray;");
5230 headers.println("int numoptionaltaskdescriptors;");
5231 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
5233 //STRUCT CLASSANALYSISWRAPPER
5234 headers.println("struct classanalysiswrapper{");
5235 headers.println("int type;");
5236 headers.println("int numotd;");
5237 headers.println("struct optionaltaskdescriptor ** otdarray;");
5238 headers.println("int numfsanalysiswrappers;");
5239 headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
5241 headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
5243 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
5244 while(taskit.hasNext()) {
5245 TaskDescriptor td=(TaskDescriptor)taskit.next();
5246 headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
5251 //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
5252 int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
5253 int predicateindex = 0;
5254 //iterate through the classes concerned by the predicate
5255 Set c_vard = predicate.vardescriptors;
5256 Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
5259 for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext();) {
5260 VarDescriptor vard = (VarDescriptor)vard_it.next();
5261 TypeDescriptor typed = vard.getType();
5263 //generate for flags
5264 HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
5265 output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5267 if (fen_hashset!=null) {
5268 for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext();) {
5269 FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
5271 DNFFlag dflag=fen.getDNF();
5272 numberterms+=dflag.size();
5274 Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
5276 for(int j=0; j<dflag.size(); j++) {
5278 output.println(",");
5279 Vector term=dflag.get(j);
5282 for(int k=0; k<term.size(); k++) {
5283 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
5284 FlagDescriptor fd=dfa.getFlag();
5285 boolean negated=dfa.getNegated();
5286 int flagid=1<<((Integer)flags.get(fd)).intValue();
5291 output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
5296 output.println("};\n");
5299 TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
5300 output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5303 for(int j=0; j<tagel.numTags(); j++) {
5305 output.println(",");
5306 TempDescriptor tmp=tagel.getTemp(j);
5307 if (!slotnumber.containsKey(tmp)) {
5308 Integer slotint=new Integer(current_slot++);
5309 slotnumber.put(tmp,slotint);
5311 int slot=slotnumber.get(tmp).intValue();
5312 output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
5314 numtags = tagel.numTags();
5316 output.println("};");
5318 //store the result into a predicatemember struct
5319 output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
5320 output.println("/*type*/"+typed.getClassDesc().getId()+",");
5321 output.println("/* number of dnf terms */"+numberterms+",");
5322 output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5323 output.println("/* number of tag */"+numtags+",");
5324 output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5325 output.println("};\n");
5330 //generate an array that stores the entire predicate
5331 output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5332 for( int j = 0; j<predicateindex; j++) {
5333 if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5334 else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5336 output.println("};\n");
5337 return predicateindex;
5341 void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
5342 generateOptionalHeader(headers);
5344 output.println("#include \"optionalstruct.h\"\n\n");
5345 output.println("#include \"stdlib.h\"\n");
5347 HashSet processedcd = new HashSet();
5349 Enumeration e = safeexecution.keys();
5350 while (e.hasMoreElements()) {
5353 ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
5354 Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp); //will be used several times
5356 //Generate the struct of optionals
5357 Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
5358 numotd = c_otd.size();
5359 if(maxotd<numotd) maxotd = numotd;
5360 if( !c_otd.isEmpty() ) {
5361 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
5362 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
5364 //generate the int arrays for the predicate
5365 Predicate predicate = otd.predicate;
5366 int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
5367 TreeSet<Integer> fsset=new TreeSet<Integer>();
5368 //iterate through possible FSes corresponding to
5369 //the state when entering
5371 for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext();) {
5372 FlagState fs = (FlagState)fses.next();
5374 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
5375 FlagDescriptor flagd = (FlagDescriptor)flags.next();
5376 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
5379 fsset.add(new Integer(flagid));
5380 //tag information not needed because tag
5381 //changes are not tolerated.
5384 output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5385 boolean needcomma=false;
5386 for(Iterator<Integer> it=fsset.iterator(); it.hasNext();) {
5389 output.println(it.next());
5392 output.println("};\n");
5395 //generate optionaltaskdescriptor that actually
5396 //includes exit fses, predicate and the task
5398 output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
5399 output.println("&task_"+otd.td.getSafeSymbol()+",");
5400 output.println("/*index*/"+otd.getIndex()+",");
5401 output.println("/*number of enter flags*/"+fsset.size()+",");
5402 output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5403 output.println("/*number of members */"+predicateindex+",");
5404 output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5405 output.println("};\n");
5409 // if there are no optionals, there is no need to build the rest of the struct
5411 output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
5412 c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
5413 if( !c_otd.isEmpty() ) {
5414 boolean needcomma=false;
5415 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
5416 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
5418 output.println(",");
5420 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5423 output.println("};\n");
5425 //get all the possible flagstates reachable by an object
5426 Hashtable hashtbtemp = safeexecution.get(cdtemp);
5428 TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
5429 fsts.addAll(hashtbtemp.keySet());
5430 for(Iterator fsit=fsts.iterator(); fsit.hasNext();) {
5431 FlagState fs = (FlagState)fsit.next();
5434 //get the set of OptionalTaskDescriptors corresponding
5435 HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
5436 //iterate through the OptionalTaskDescriptors and
5437 //store the pointers to the optionals struct (see on
5438 //top) into an array
5440 output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
5441 for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext();) {
5442 OptionalTaskDescriptor mm = mos.next();
5444 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
5446 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5449 output.println("};\n");
5451 //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
5454 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
5455 FlagDescriptor flagd = (FlagDescriptor)flags.next();
5456 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
5460 //process tag information
5463 boolean first = true;
5464 Enumeration tag_enum = fs.getTags();
5465 output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
5466 while(tag_enum.hasMoreElements()) {
5468 TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
5472 output.println(", ");
5473 output.println("/*tagid*/"+state.getTagId(tagd));
5475 output.println("};");
5477 Set<TaskIndex> tiset=sa.getTaskIndex(fs);
5478 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
5479 TaskIndex ti=itti.next();
5483 Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
5485 output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
5486 boolean needcomma=false;
5487 for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext();) {
5488 OptionalTaskDescriptor otd=otdit.next();
5492 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5494 output.println("};");
5496 output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
5497 output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
5498 output.print(ti.getIndex()+", ");
5499 output.print(otdset.size()+", ");
5500 output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
5501 output.println("};");
5504 tiset=sa.getTaskIndex(fs);
5505 boolean needcomma=false;
5507 output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
5508 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
5509 TaskIndex ti=itti.next();
5510 if (ti.isRuntime()) {
5517 output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
5519 output.println("};\n");
5521 //Store the result in fsanalysiswrapper
5523 output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
5524 output.println("/*flag*/"+flagid+",");
5525 output.println("/* number of tags*/"+tagcounter+",");
5526 output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
5527 output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
5528 output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
5529 output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
5530 output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
5531 output.println("};\n");
5535 //Build the array of fsanalysiswrappers
5536 output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
5537 boolean needcomma=false;
5538 for(int i = 0; i<fscounter; i++) {
5539 if (needcomma) output.print(",");
5540 output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
5543 output.println("};");
5545 //Build the classanalysiswrapper referring to the previous array
5546 output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
5547 output.println("/*type*/"+cdtemp.getId()+",");
5548 output.println("/*numotd*/"+numotd+",");
5549 output.println("otdarray"+cdtemp.getSafeSymbol()+",");
5550 output.println("/* number of fsanalysiswrappers */"+fscounter+",");
5551 output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
5552 processedcd.add(cdtemp);
5555 //build an array containing every classes for which code has been build
5556 output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
5557 for(int i=0; i<state.numClasses(); i++) {
5558 ClassDescriptor cn=cdarray[i];
5561 if ((cn != null) && (processedcd.contains(cn)))
5562 output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
5564 output.print("NULL");
5566 output.println("};");
5568 output.println("#define MAXOTD "+maxotd);
5569 headers.println("#endif");
5572 public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
5573 Relation r=new Relation();
5574 for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext();) {
5575 OptionalTaskDescriptor otd=otdit.next();
5576 TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
5580 LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
5581 for(Iterator it=r.keySet().iterator(); it.hasNext();) {
5582 Set s=r.get(it.next());
5583 for(Iterator it2=s.iterator(); it2.hasNext();) {
5584 OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
5592 protected void outputTransCode(PrintWriter output) {
5595 private int calculateSizeOfSESEParamList(FlatSESEEnterNode fsen){
5597 Set<TempDescriptor> tdSet=new HashSet<TempDescriptor>();
5599 for (Iterator iterator = fsen.getInVarSet().iterator(); iterator.hasNext();) {
5600 TempDescriptor tempDescriptor = (TempDescriptor) iterator.next();
5601 if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()){
5602 tdSet.add(tempDescriptor);
5606 for (Iterator iterator = fsen.getOutVarSet().iterator(); iterator.hasNext();) {
5607 TempDescriptor tempDescriptor = (TempDescriptor) iterator.next();
5608 if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()){
5609 tdSet.add(tempDescriptor);
5613 return tdSet.size();
5616 private String calculateSizeOfSESEParamSize(FlatSESEEnterNode fsen){
5617 HashMap <String,Integer> map=new HashMap();
5618 HashSet <TempDescriptor> processed=new HashSet<TempDescriptor>();
5621 // space for all in and out set primitives
5622 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
5623 inSetAndOutSet.addAll( fsen.getInVarSet() );
5624 inSetAndOutSet.addAll( fsen.getOutVarSet() );
5626 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
5628 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
5629 while( itr.hasNext() ) {
5630 TempDescriptor temp = itr.next();
5631 TypeDescriptor type = temp.getType();
5632 if( !type.isPtr() ) {
5633 inSetAndOutSetPrims.add( temp );
5637 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
5638 while( itrPrims.hasNext() ) {
5639 TempDescriptor temp = itrPrims.next();
5640 TypeDescriptor type = temp.getType();
5641 if(type.isPrimitive()){
5642 Integer count=map.get(type.getSymbol());
5644 count=new Integer(1);
5645 map.put(type.getSymbol(), count);
5647 map.put(type.getSymbol(), new Integer(count.intValue()+1));
5652 Set<String> keySet=map.keySet();
5653 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
5654 String key = (String) iterator.next();
5655 rtr+="+sizeof("+key+")*"+map.get(key);