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 maxTaskRecSizeStr="__maxTaskRecSize___";
82 String mlperrstr = "if(status != 0) { "+
83 "sprintf(errmsg, \"MLP error at %s:%d\", __FILE__, __LINE__); "+
84 "perror(errmsg); exit(-1); }";
85 boolean nonSESEpass=true;
86 RuntimeConflictResolver rcr = null;
89 DiscoverConflicts recorddc;
94 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa) {
95 this(st, temptovar, typeutil, null, sa, pa, null, null);
98 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa, OoOJavaAnalysis oooa) {
99 this(st, temptovar, typeutil, null, sa, pa, mlpa, oooa);
102 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, PrefetchAnalysis pa, MLPAnalysis mlpa, OoOJavaAnalysis oooa) {
103 this(st, temptovar, typeutil, locality, null, pa, mlpa, oooa);
106 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa, OoOJavaAnalysis oooa) {
112 callgraph=new CallGraph(state);
114 oidstr="___objlocation___";
115 this.temptovar=temptovar;
116 paramstable=new Hashtable();
117 tempstable=new Hashtable();
118 fieldorder=new Hashtable();
119 flagorder=new Hashtable();
120 this.typeutil=typeutil;
121 virtualcalls=new Virtual(state,locality);
122 if (locality!=null) {
123 this.locality=locality;
124 this.reverttable=new Hashtable<LocalityBinding, TempDescriptor>();
125 this.backuptable=new Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>>();
126 this.wb=new WriteBarrier(locality, st);
128 if (state.SINGLETM&&state.DCOPTS) {
129 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
130 GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
131 this.dc=new DiscoverConflicts(locality, st, typeanalysis, gft);
134 if (state.DELAYCOMP) {
135 //TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
136 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
137 GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
138 delaycomp=new DCWrapper(locality, st, typeanalysis, gft);
139 dc=delaycomp.getConflicts();
140 recorddc=new DiscoverConflicts(locality, st, typeanalysis, delaycomp.getCannotDelayMap(), true, true, null);
141 recorddc.doAnalysis();
145 /** The buildCode method outputs C code for all the methods. The Flat
146 * versions of the methods must already be generated and stored in
147 * the State object. */
148 PrintWriter outsandbox=null;
150 public void buildCode() {
151 /* Create output streams to write to */
152 PrintWriter outclassdefs=null;
153 PrintWriter outstructs=null;
154 PrintWriter outrepairstructs=null;
155 PrintWriter outmethodheader=null;
156 PrintWriter outmethod=null;
157 PrintWriter outvirtual=null;
158 PrintWriter outtask=null;
159 PrintWriter outtaskdefs=null;
160 PrintWriter outoptionalarrays=null;
161 PrintWriter optionalheaders=null;
165 outsandbox=new PrintWriter(new FileOutputStream(PREFIX+"sandboxdefs.c"), true);
167 outstructs=new PrintWriter(new FileOutputStream(PREFIX+"structdefs.h"), true);
168 outmethodheader=new PrintWriter(new FileOutputStream(PREFIX+"methodheaders.h"), true);
169 outclassdefs=new PrintWriter(new FileOutputStream(PREFIX+"classdefs.h"), true);
170 outmethod=new PrintWriter(new FileOutputStream(PREFIX+"methods.c"), true);
171 outvirtual=new PrintWriter(new FileOutputStream(PREFIX+"virtualtable.h"), true);
173 outtask=new PrintWriter(new FileOutputStream(PREFIX+"task.h"), true);
174 outtaskdefs=new PrintWriter(new FileOutputStream(PREFIX+"taskdefs.c"), true);
175 if (state.OPTIONAL) {
176 outoptionalarrays=new PrintWriter(new FileOutputStream(PREFIX+"optionalarrays.c"), true);
177 optionalheaders=new PrintWriter(new FileOutputStream(PREFIX+"optionalstruct.h"), true);
180 if (state.structfile!=null) {
181 outrepairstructs=new PrintWriter(new FileOutputStream(PREFIX+state.structfile+".struct"), true);
183 } catch (Exception e) {
188 /* Build the virtual dispatch tables */
189 buildVirtualTables(outvirtual);
191 /* Output includes */
192 outmethodheader.println("#ifndef METHODHEADERS_H");
193 outmethodheader.println("#define METHODHEADERS_H");
194 outmethodheader.println("#include \"structdefs.h\"");
196 outmethodheader.println("#include \"dstm.h\"");
198 outmethodheader.println("#include \"sandbox.h\"");
200 if (state.EVENTMONITOR) {
201 outmethodheader.println("#include \"monitor.h\"");
203 if (state.SINGLETM) {
204 outmethodheader.println("#include \"tm.h\"");
205 outmethodheader.println("#include \"delaycomp.h\"");
206 outmethodheader.println("#include \"inlinestm.h\"");
208 if (state.ABORTREADERS) {
209 outmethodheader.println("#include \"abortreaders.h\"");
210 outmethodheader.println("#include <setjmp.h>");
212 if (state.MLP || state.OOOJAVA) {
213 outmethodheader.println("#include <stdlib.h>");
214 outmethodheader.println("#include <stdio.h>");
215 outmethodheader.println("#include <string.h>");
216 outmethodheader.println("#include \"mlp_runtime.h\"");
217 outmethodheader.println("#include \"psemaphore.h\"");
218 outmethodheader.println("#include \"memPool.h\"");
220 // spit out a global to inform all worker threads with
221 // the maximum size is for any task record
222 outmethodheader.println("extern int "+maxTaskRecSizeStr+";");
225 /* Output Structures */
226 outputStructs(outstructs);
228 // Output the C class declarations
229 // These could mutually reference each other
232 outclassdefs.println("#ifndef __CLASSDEF_H_");
233 outclassdefs.println("#define __CLASSDEF_H_");
234 outputClassDeclarations(outclassdefs);
236 // Output function prototypes and structures for parameters
237 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
238 while(it.hasNext()) {
239 ClassDescriptor cn=(ClassDescriptor)it.next();
240 generateCallStructs(cn, outclassdefs, outstructs, outmethodheader);
242 outclassdefs.println("#endif");
243 outclassdefs.close();
246 /* Map flags to integers */
247 /* The runtime keeps track of flags using these integers */
248 it=state.getClassSymbolTable().getDescriptorsIterator();
249 while(it.hasNext()) {
250 ClassDescriptor cn=(ClassDescriptor)it.next();
254 generateTaskStructs(outstructs, outmethodheader);
256 /* Outputs generic task structures if this is a task
258 outputTaskTypes(outtask);
261 if( state.MLP || state.OOOJAVA) {
262 // have to initialize some SESE compiler data before
263 // analyzing normal methods, which must happen before
264 // generating SESE internal code
266 Iterator<FlatSESEEnterNode> seseit;
268 seseit=mlpa.getAllSESEs().iterator();
270 seseit=oooa.getAllSESEs().iterator();
273 //TODO signal the object that will report errors
276 rcr = new RuntimeConflictResolver(PREFIX);
278 catch (FileNotFoundException e) {
279 System.out.println("Runtime Conflict Resolver could not create output file.");
283 while(seseit.hasNext()){
284 FlatSESEEnterNode fsen = seseit.next();
285 initializeSESE( fsen );
287 if(state.RCR && rcr != null){
288 Analysis.OoOJava.ConflictGraph conflictGraph;
289 Hashtable<Taint, Set<Effect>> conflicts;
290 if(!fsen.getIsCallerSESEplaceholder() && fsen.getParent()!=null &&
291 (conflictGraph = oooa.getConflictGraph(fsen.getParent())) != null &&
292 (conflicts = conflictGraph.getConflictEffectSet(fsen)) != null){
294 FlatMethod fm=fsen.getfmEnclosing();
297 ReachGraph rg=oooa.getDisjointAnalysis().getReachGraph(fm.getMethod());
300 rg.writeGraph("RCR_RG_SESE_DEBUG");
304 Hashtable<Taint, Set<Effect>> effects=oooa.getDisjointAnalysis().getEffectsAnalysis().get(fsen);
306 //rcr.traverseSESEBlock(fsen, effects, conflicts, rg);
312 /* Build the actual methods */
313 outputMethods(outmethod);
315 // Output function prototypes and structures for SESE's and code
316 if( state.MLP || state.OOOJAVA ) {
318 // spit out a global to inform all worker threads with
319 // the maximum size is for any task record
320 outmethod.println("int "+maxTaskRecSizeStr+" = 0;");
322 // used to differentiate, during code generation, whether we are
323 // passing over SESE body code, or non-SESE code
326 // first generate code for each sese's internals
327 Iterator<FlatSESEEnterNode> seseit;
329 seseit=mlpa.getAllSESEs().iterator();
331 seseit=oooa.getAllSESEs().iterator();
334 while(seseit.hasNext()) {
335 FlatSESEEnterNode fsen = seseit.next();
336 generateMethodSESE(fsen, null, outstructs, outmethodheader, outmethod);
339 // then write the invokeSESE switch to decouple scheduler
340 // from having to do unique details of sese invocation
341 generateSESEinvocationMethod(outmethodheader, outmethod);
345 /* Output code for tasks */
346 outputTaskCode(outtaskdefs, outmethod);
348 /* Record maximum number of task parameters */
349 outstructs.println("#define MAXTASKPARAMS "+maxtaskparams);
350 } else if (state.main!=null) {
351 /* Generate main method */
352 outputMainMethod(outmethod);
355 /* Generate information for task with optional parameters */
356 if (state.TASK&&state.OPTIONAL) {
357 generateOptionalArrays(outoptionalarrays, optionalheaders, state.getAnalysisResult(), state.getOptionalTaskDescriptors());
358 outoptionalarrays.close();
361 /* Output structure definitions for repair tool */
362 if (state.structfile!=null) {
363 buildRepairStructs(outrepairstructs);
364 outrepairstructs.close();
368 outmethodheader.println("#endif");
369 outmethodheader.close();
371 outstructs.println("#endif");
375 System.out.println("Runtime Conflict Resolver Done.");
380 /* This code just generates the main C method for java programs.
381 * The main C method packs up the arguments into a string array
382 * and passes it to the java main method. */
384 private void outputMainMethod(PrintWriter outmethod) {
385 outmethod.println("int main(int argc, const char *argv[]) {");
386 outmethod.println(" int i;");
388 if (state.MLP || state.OOOJAVA) {
390 // do a calculation to determine which task record
391 // is the largest, store that as a global value for
392 // allocating records
393 Iterator<FlatSESEEnterNode> seseit;
395 seseit=mlpa.getAllSESEs().iterator();
397 seseit=oooa.getAllSESEs().iterator();
399 while(seseit.hasNext()){
400 FlatSESEEnterNode fsen = seseit.next();
401 outmethod.println("if( sizeof( "+fsen.getSESErecordName()+
402 " ) > "+maxTaskRecSizeStr+
403 " ) { "+maxTaskRecSizeStr+
404 " = sizeof( "+fsen.getSESErecordName()+
409 outmethod.println(" workScheduleInit( "+state.MLP_NUMCORES+", invokeSESEmethod );");
411 //initializes data structures needed for the RCR traverser
413 outmethod.println(" initializeStructsRCR();");
418 if (state.DSMRECOVERYSTATS) {
419 outmethod.println("#ifdef RECOVERYSTATS \n");
420 outmethod.println("handle();\n");
421 outmethod.println("#endif\n");
423 outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n");
424 outmethod.println("handle();\n");
425 outmethod.println("#endif\n");
429 if (state.THREAD||state.DSM||state.SINGLETM) {
430 outmethod.println("initializethreads();");
433 outmethod.println("if (dstmStartup(argv[1])) {");
434 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
435 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-2);");
437 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-2);");
440 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
441 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1);");
443 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1);");
447 outmethod.println(" for(i=2;i<argc;i++) {");
449 outmethod.println(" for(i=1;i<argc;i++) {");
450 outmethod.println(" int length=strlen(argv[i]);");
451 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
452 outmethod.println(" struct ___String___ *newstring=NewString(NULL, argv[i], length);");
454 outmethod.println(" struct ___String___ *newstring=NewString(argv[i], length);");
457 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-2]=newstring;");
459 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-1]=newstring;");
460 outmethod.println(" }");
462 MethodDescriptor md=typeutil.getMain();
463 ClassDescriptor cd=typeutil.getMainClass();
465 outmethod.println(" {");
466 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
467 if (state.DSM||state.SINGLETM) {
468 outmethod.print(" struct "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
470 outmethod.print(" struct "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
471 outmethod.println("1, NULL,"+"stringarray};");
472 if (state.DSM||state.SINGLETM)
473 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
475 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
477 if (state.DSM||state.SINGLETM)
478 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
480 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
482 outmethod.println(" }");
485 outmethod.println("}");
488 if (state.THREAD||state.DSM||state.SINGLETM) {
489 outmethod.println("pthread_mutex_lock(&gclistlock);");
490 outmethod.println("threadcount--;");
491 outmethod.println("pthread_cond_signal(&gccond);");
492 outmethod.println("pthread_mutex_unlock(&gclistlock);");
495 if (state.DSM||state.SINGLETM) {
496 //outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n");
497 outmethod.println("#if defined(TRANSSTATS) \n");
498 outmethod.println("printf(\"****** Transaction Stats ******\\n\");");
499 outmethod.println("printf(\"numTransCommit= %d\\n\", numTransCommit);");
500 outmethod.println("printf(\"numTransAbort= %d\\n\", numTransAbort);");
501 outmethod.println("printf(\"nSoftAbort= %d\\n\", nSoftAbort);");
503 outmethod.println("printf(\"nchashSearch= %d\\n\", nchashSearch);");
504 outmethod.println("printf(\"nmhashSearch= %d\\n\", nmhashSearch);");
505 outmethod.println("printf(\"nprehashSearch= %d\\n\", nprehashSearch);");
506 outmethod.println("printf(\"ndirtyCacheObj= %d\\n\", ndirtyCacheObj);");
507 outmethod.println("printf(\"nRemoteReadSend= %d\\n\", nRemoteSend);");
508 outmethod.println("printf(\"bytesSent= %d\\n\", bytesSent);");
509 outmethod.println("printf(\"bytesRecv= %d\\n\", bytesRecv);");
510 outmethod.println("printf(\"totalObjSize= %d\\n\", totalObjSize);");
511 outmethod.println("printf(\"sendRemoteReq= %d\\n\", sendRemoteReq);");
512 outmethod.println("printf(\"getResponse= %d\\n\", getResponse);");
513 } else if (state.SINGLETM) {
514 outmethod.println("printf(\"nSoftAbortAbort= %d\\n\", nSoftAbortAbort);");
515 outmethod.println("printf(\"nSoftAbortCommit= %d\\n\", nSoftAbortCommit);");
516 outmethod.println("#ifdef STMSTATS\n");
517 outmethod.println("for(i=0; i<TOTALNUMCLASSANDARRAY; i++) {\n");
518 outmethod.println(" printf(\"typesCausingAbort[%2d] numaccess= %5d numabort= %3d\\n\", i, typesCausingAbort[i].numaccess, typesCausingAbort[i].numabort);\n");
519 outmethod.println("}\n");
520 outmethod.println("#endif\n");
521 outmethod.println("fflush(stdout);");
523 outmethod.println("#endif\n");
526 if (state.EVENTMONITOR) {
527 outmethod.println("dumpdata();");
530 if (state.THREAD||state.SINGLETM)
531 outmethod.println("pthread_exit(NULL);");
533 if (state.MLP || state.OOOJAVA ) {
534 outmethod.println(" workScheduleBegin();");
537 outmethod.println("}");
540 /* This method outputs code for each task. */
542 private void outputTaskCode(PrintWriter outtaskdefs, PrintWriter outmethod) {
543 /* Compile task based program */
544 outtaskdefs.println("#include \"task.h\"");
545 outtaskdefs.println("#include \"methodheaders.h\"");
546 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
547 while(taskit.hasNext()) {
548 TaskDescriptor td=(TaskDescriptor)taskit.next();
549 FlatMethod fm=state.getMethodFlat(td);
550 generateFlatMethod(fm, null, outmethod);
551 generateTaskDescriptor(outtaskdefs, fm, td);
554 //Output task descriptors
555 taskit=state.getTaskSymbolTable().getDescriptorsIterator();
556 outtaskdefs.println("struct taskdescriptor * taskarray[]= {");
558 while(taskit.hasNext()) {
559 TaskDescriptor td=(TaskDescriptor)taskit.next();
563 outtaskdefs.println(",");
564 outtaskdefs.print("&task_"+td.getSafeSymbol());
566 outtaskdefs.println("};");
568 outtaskdefs.println("int numtasks="+state.getTaskSymbolTable().getValueSet().size()+";");
571 /* This method outputs most of the methods.c file. This includes
572 * some standard includes and then an array with the sizes of
573 * objets and array that stores supertype and then the code for
574 * the Java methods.. */
576 protected void outputMethods(PrintWriter outmethod) {
577 outmethod.println("#include \"methodheaders.h\"");
578 outmethod.println("#include \"virtualtable.h\"");
579 outmethod.println("#include \"runtime.h\"");
581 // always include: compiler directives will leave out
582 // instrumentation when option is not set
583 outmethod.println("#include \"coreprof/coreprof.h\"");
586 outmethod.println("#include \"sandboxdefs.c\"");
589 outmethod.println("#include \"addPrefetchEnhance.h\"");
590 outmethod.println("#include \"localobjects.h\"");
592 if (state.FASTCHECK) {
593 outmethod.println("#include \"localobjects.h\"");
595 if(state.MULTICORE) {
596 outmethod.println("#include \"task.h\"");
597 outmethod.println("#include \"multicoreruntime.h\"");
598 outmethod.println("#include \"runtime_arch.h\"");
600 if (state.THREAD||state.DSM||state.SINGLETM)
601 outmethod.println("#include <thread.h>");
602 if (state.main!=null) {
603 outmethod.println("#include <string.h>");
605 if (state.CONSCHECK) {
606 outmethod.println("#include \"checkers.h\"");
608 if (state.MLP || state.OOOJAVA ) {
609 outmethod.println("#include <stdlib.h>");
610 outmethod.println("#include <stdio.h>");
611 outmethod.println("#include \"mlp_runtime.h\"");
612 outmethod.println("#include \"psemaphore.h\"");
615 outmethod.println("#include \"RuntimeConflictResolver.h\"");
619 //Store the sizes of classes & array elements
620 generateSizeArray(outmethod);
622 //Store table of supertypes
623 generateSuperTypeTable(outmethod);
625 //Store the layout of classes
626 generateLayoutStructs(outmethod);
628 /* Generate code for methods */
629 if (state.DSM||state.SINGLETM) {
630 for(Iterator<LocalityBinding> lbit=locality.getLocalityBindings().iterator(); lbit.hasNext();) {
631 LocalityBinding lb=lbit.next();
632 MethodDescriptor md=lb.getMethod();
633 FlatMethod fm=state.getMethodFlat(md);
635 if (!md.getModifiers().isNative()) {
636 generateFlatMethod(fm, lb, outmethod);
637 //System.out.println("fm= " + fm + " md= " + md);
641 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
642 while(classit.hasNext()) {
643 ClassDescriptor cn=(ClassDescriptor)classit.next();
644 Iterator methodit=cn.getMethods();
645 while(methodit.hasNext()) {
646 /* Classify parameters */
647 MethodDescriptor md=(MethodDescriptor)methodit.next();
648 FlatMethod fm=state.getMethodFlat(md);
649 if (!md.getModifiers().isNative()) {
650 generateFlatMethod(fm, null, outmethod);
657 protected void outputStructs(PrintWriter outstructs) {
658 outstructs.println("#ifndef STRUCTDEFS_H");
659 outstructs.println("#define STRUCTDEFS_H");
660 outstructs.println("#include \"classdefs.h\"");
661 outstructs.println("#ifndef INTPTR");
662 outstructs.println("#ifdef BIT64");
663 outstructs.println("#define INTPTR long");
664 outstructs.println("#else");
665 outstructs.println("#define INTPTR int");
666 outstructs.println("#endif");
667 outstructs.println("#endif");
668 if( state.MLP || state.OOOJAVA ) {
669 outstructs.println("#include \"mlp_runtime.h\"");
670 outstructs.println("#include \"psemaphore.h\"");
673 /* Output #defines that the runtime uses to determine type
674 * numbers for various objects it needs */
675 outstructs.println("#define MAXCOUNT "+maxcount);
676 if (state.DSM||state.SINGLETM) {
677 LocalityBinding lbrun=new LocalityBinding(typeutil.getRun(), false);
679 lbrun.setGlobalThis(LocalityAnalysis.GLOBAL);
681 else if (state.SINGLETM) {
682 lbrun.setGlobalThis(LocalityAnalysis.NORMAL);
684 outstructs.println("#define RUNMETHOD "+virtualcalls.getLocalityNumber(lbrun));
688 LocalityBinding lbexecute = new LocalityBinding(typeutil.getExecute(), false);
690 lbexecute.setGlobalThis(LocalityAnalysis.GLOBAL);
691 else if( state.SINGLETM)
692 lbexecute.setGlobalThis(LocalityAnalysis.NORMAL);
693 outstructs.println("#define EXECUTEMETHOD " + virtualcalls.getLocalityNumber(lbexecute));
696 outstructs.println("#define STRINGARRAYTYPE "+
697 (state.getArrayNumber(
698 (new TypeDescriptor(typeutil.getClass(TypeUtil.StringClass))).makeArray(state))+state.numClasses()));
700 outstructs.println("#define OBJECTARRAYTYPE "+
701 (state.getArrayNumber(
702 (new TypeDescriptor(typeutil.getClass(TypeUtil.ObjectClass))).makeArray(state))+state.numClasses()));
705 outstructs.println("#define STRINGTYPE "+typeutil.getClass(TypeUtil.StringClass).getId());
706 outstructs.println("#define CHARARRAYTYPE "+
707 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.CHAR)).makeArray(state))+state.numClasses()));
709 outstructs.println("#define BYTEARRAYTYPE "+
710 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state))+state.numClasses()));
712 outstructs.println("#define BYTEARRAYARRAYTYPE "+
713 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state).makeArray(state))+state.numClasses()));
715 outstructs.println("#define NUMCLASSES "+state.numClasses());
716 int totalClassSize = state.numClasses() + state.numArrays();
717 outstructs.println("#define TOTALNUMCLASSANDARRAY "+ totalClassSize);
719 outstructs.println("#define STARTUPTYPE "+typeutil.getClass(TypeUtil.StartupClass).getId());
720 outstructs.println("#define TAGTYPE "+typeutil.getClass(TypeUtil.TagClass).getId());
721 outstructs.println("#define TAGARRAYTYPE "+
722 (state.getArrayNumber(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)).makeArray(state))+state.numClasses()));
726 protected void outputClassDeclarations(PrintWriter outclassdefs) {
727 if (state.THREAD||state.DSM||state.SINGLETM)
728 outclassdefs.println("#include <pthread.h>");
729 outclassdefs.println("#ifndef INTPTR");
730 outclassdefs.println("#ifdef BIT64");
731 outclassdefs.println("#define INTPTR long");
732 outclassdefs.println("#else");
733 outclassdefs.println("#define INTPTR int");
734 outclassdefs.println("#endif");
735 outclassdefs.println("#endif");
737 outclassdefs.println("#include \"optionalstruct.h\"");
738 outclassdefs.println("struct "+arraytype+";");
739 /* Start by declaring all structs */
740 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
741 while(it.hasNext()) {
742 ClassDescriptor cn=(ClassDescriptor)it.next();
743 outclassdefs.println("struct "+cn.getSafeSymbol()+";");
745 outclassdefs.println("");
746 //Print out definition for array type
747 outclassdefs.println("struct "+arraytype+" {");
748 outclassdefs.println(" int type;");
749 if(state.MLP || state.OOOJAVA ){
750 outclassdefs.println(" int oid;");
751 outclassdefs.println(" int allocsite;");
753 if (state.EVENTMONITOR) {
754 outclassdefs.println(" int objuid;");
757 outclassdefs.println(" pthread_t tid;");
758 outclassdefs.println(" void * lockentry;");
759 outclassdefs.println(" int lockcount;");
762 outclassdefs.println(" int flag;");
763 if(!state.MULTICORE) {
764 outclassdefs.println(" void * flagptr;");
766 outclassdefs.println(" int version;");
767 outclassdefs.println(" int * lock;"); // lock entry for this obj
768 outclassdefs.println(" int mutex;");
769 outclassdefs.println(" int lockcount;");
770 if(state.MULTICOREGC) {
771 outclassdefs.println(" int marked;");
775 outclassdefs.println(" int numfses;");
776 outclassdefs.println(" int * fses;");
779 printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs);
781 if (state.STMARRAY) {
782 outclassdefs.println(" int lowindex;");
783 outclassdefs.println(" int highindex;");
786 outclassdefs.println(" int paddingforarray;");
787 if (state.DUALVIEW) {
788 outclassdefs.println(" int arrayversion;");
791 outclassdefs.println(" int ___length___;");
792 outclassdefs.println("};\n");
793 outclassdefs.println("extern int classsize[];");
794 outclassdefs.println("extern int hasflags[];");
795 outclassdefs.println("extern unsigned INTPTR * pointerarray[];");
796 outclassdefs.println("extern int supertypes[];");
799 /** Prints out definitions for generic task structures */
801 private void outputTaskTypes(PrintWriter outtask) {
802 outtask.println("#ifndef _TASK_H");
803 outtask.println("#define _TASK_H");
804 outtask.println("struct parameterdescriptor {");
805 outtask.println("int type;");
806 outtask.println("int numberterms;");
807 outtask.println("int *intarray;");
808 outtask.println("void * queue;");
809 outtask.println("int numbertags;");
810 outtask.println("int *tagarray;");
811 outtask.println("};");
813 outtask.println("struct taskdescriptor {");
814 outtask.println("void * taskptr;");
815 outtask.println("int numParameters;");
816 outtask.println(" int numTotal;");
817 outtask.println("struct parameterdescriptor **descriptorarray;");
818 outtask.println("char * name;");
819 outtask.println("};");
820 outtask.println("extern struct taskdescriptor * taskarray[];");
821 outtask.println("extern numtasks;");
822 outtask.println("#endif");
826 private void buildRepairStructs(PrintWriter outrepairstructs) {
827 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
828 while(classit.hasNext()) {
829 ClassDescriptor cn=(ClassDescriptor)classit.next();
830 outrepairstructs.println("structure "+cn.getSymbol()+" {");
831 outrepairstructs.println(" int __type__;");
833 outrepairstructs.println(" int __flag__;");
834 if(!state.MULTICORE) {
835 outrepairstructs.println(" int __flagptr__;");
838 printRepairStruct(cn, outrepairstructs);
839 outrepairstructs.println("}\n");
842 for(int i=0; i<state.numArrays(); i++) {
843 TypeDescriptor tdarray=arraytable[i];
844 TypeDescriptor tdelement=tdarray.dereference();
845 outrepairstructs.println("structure "+arraytype+"_"+state.getArrayNumber(tdarray)+" {");
846 outrepairstructs.println(" int __type__;");
847 printRepairStruct(typeutil.getClass(TypeUtil.ObjectClass), outrepairstructs);
848 outrepairstructs.println(" int length;");
850 // Need to add support to repair tool for this
851 if (tdelement.isClass()||tdelement.isArray())
852 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" * elem[this.length];");
854 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" elem[this.length];");
856 outrepairstructs.println("}\n");
860 private void printRepairStruct(ClassDescriptor cn, PrintWriter output) {
861 ClassDescriptor sp=cn.getSuperDesc();
863 printRepairStruct(sp, output);
865 Vector fields=(Vector)fieldorder.get(cn);
867 for(int i=0; i<fields.size(); i++) {
868 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
869 if (fd.getType().isArray()) {
870 output.println(" "+arraytype+"_"+ state.getArrayNumber(fd.getType()) +" * "+fd.getSymbol()+";");
871 } else if (fd.getType().isClass())
872 output.println(" "+fd.getType().getRepairSymbol()+" * "+fd.getSymbol()+";");
873 else if (fd.getType().isFloat())
874 output.println(" int "+fd.getSymbol()+"; /* really float */");
876 output.println(" "+fd.getType().getRepairSymbol()+" "+fd.getSymbol()+";");
880 /** This method outputs TaskDescriptor information */
881 private void generateTaskDescriptor(PrintWriter output, FlatMethod fm, TaskDescriptor task) {
882 for (int i=0; i<task.numParameters(); i++) {
883 VarDescriptor param_var=task.getParameter(i);
884 TypeDescriptor param_type=task.getParamType(i);
885 FlagExpressionNode param_flag=task.getFlag(param_var);
886 TagExpressionList param_tag=task.getTag(param_var);
889 if (param_flag==null) {
890 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
891 output.println("0x0, 0x0 };");
894 DNFFlag dflag=param_flag.getDNF();
895 dnfterms=dflag.size();
897 Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
898 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
899 for(int j=0; j<dflag.size(); j++) {
902 Vector term=dflag.get(j);
905 for(int k=0; k<term.size(); k++) {
906 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
907 FlagDescriptor fd=dfa.getFlag();
908 boolean negated=dfa.getNegated();
909 int flagid=1<<((Integer)flags.get(fd)).intValue();
914 output.print("0x"+Integer.toHexString(andmask)+", 0x"+Integer.toHexString(checkmask));
916 output.println("};");
919 output.println("int parametertag_"+i+"_"+task.getSafeSymbol()+"[]={");
920 //BUG...added next line to fix, test with any task program
922 for(int j=0; j<param_tag.numTags(); j++) {
925 /* for each tag we need */
926 /* which slot it is */
927 /* what type it is */
928 TagVarDescriptor tvd=(TagVarDescriptor)task.getParameterTable().get(param_tag.getName(j));
929 TempDescriptor tmp=param_tag.getTemp(j);
930 int slot=fm.getTagInt(tmp);
931 output.println(slot+", "+state.getTagId(tvd.getTag()));
933 output.println("};");
935 output.println("struct parameterdescriptor parameter_"+i+"_"+task.getSafeSymbol()+"={");
936 output.println("/* type */"+param_type.getClassDesc().getId()+",");
937 output.println("/* number of DNF terms */"+dnfterms+",");
938 output.println("parameterdnf_"+i+"_"+task.getSafeSymbol()+",");
939 output.println("0,");
940 //BUG, added next line to fix and else statement...test
941 //with any task program
943 output.println("/* number of tags */"+param_tag.numTags()+",");
945 output.println("/* number of tags */ 0,");
946 output.println("parametertag_"+i+"_"+task.getSafeSymbol());
947 output.println("};");
951 output.println("struct parameterdescriptor * parameterdescriptors_"+task.getSafeSymbol()+"[] = {");
952 for (int i=0; i<task.numParameters(); i++) {
955 output.print("¶meter_"+i+"_"+task.getSafeSymbol());
957 output.println("};");
959 output.println("struct taskdescriptor task_"+task.getSafeSymbol()+"={");
960 output.println("&"+task.getSafeSymbol()+",");
961 output.println("/* number of parameters */" +task.numParameters() + ",");
962 int numtotal=task.numParameters()+fm.numTags();
963 output.println("/* number total parameters */" +numtotal + ",");
964 output.println("parameterdescriptors_"+task.getSafeSymbol()+",");
965 output.println("\""+task.getSymbol()+"\"");
966 output.println("};");
970 /** The buildVirtualTables method outputs the virtual dispatch
971 * tables for methods. */
973 protected void buildVirtualTables(PrintWriter outvirtual) {
974 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
975 while(classit.hasNext()) {
976 ClassDescriptor cd=(ClassDescriptor)classit.next();
977 if (virtualcalls.getMethodCount(cd)>maxcount)
978 maxcount=virtualcalls.getMethodCount(cd);
980 MethodDescriptor[][] virtualtable=null;
981 LocalityBinding[][] lbvirtualtable=null;
982 if (state.DSM||state.SINGLETM)
983 lbvirtualtable=new LocalityBinding[state.numClasses()+state.numArrays()][maxcount];
985 virtualtable=new MethodDescriptor[state.numClasses()+state.numArrays()][maxcount];
987 /* Fill in virtual table */
988 classit=state.getClassSymbolTable().getDescriptorsIterator();
989 while(classit.hasNext()) {
990 ClassDescriptor cd=(ClassDescriptor)classit.next();
991 if (state.DSM||state.SINGLETM)
992 fillinRow(cd, lbvirtualtable, cd.getId());
994 fillinRow(cd, virtualtable, cd.getId());
997 ClassDescriptor objectcd=typeutil.getClass(TypeUtil.ObjectClass);
998 Iterator arrayit=state.getArrayIterator();
999 while(arrayit.hasNext()) {
1000 TypeDescriptor td=(TypeDescriptor)arrayit.next();
1001 int id=state.getArrayNumber(td);
1002 if (state.DSM||state.SINGLETM)
1003 fillinRow(objectcd, lbvirtualtable, id+state.numClasses());
1005 fillinRow(objectcd, virtualtable, id+state.numClasses());
1008 outvirtual.print("void * virtualtable[]={");
1009 boolean needcomma=false;
1010 for(int i=0; i<state.numClasses()+state.numArrays(); i++) {
1011 for(int j=0; j<maxcount; j++) {
1013 outvirtual.print(", ");
1014 if ((state.DSM||state.SINGLETM)&&lbvirtualtable[i][j]!=null) {
1015 LocalityBinding lb=lbvirtualtable[i][j];
1016 MethodDescriptor md=lb.getMethod();
1017 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
1018 } else if (!(state.DSM||state.SINGLETM)&&virtualtable[i][j]!=null) {
1019 MethodDescriptor md=virtualtable[i][j];
1020 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
1022 outvirtual.print("0");
1026 outvirtual.println("");
1028 outvirtual.println("};");
1032 private void fillinRow(ClassDescriptor cd, MethodDescriptor[][] virtualtable, int rownum) {
1033 /* Get inherited methods */
1034 if (cd.getSuperDesc()!=null)
1035 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
1036 /* Override them with our methods */
1037 for(Iterator it=cd.getMethods(); it.hasNext();) {
1038 MethodDescriptor md=(MethodDescriptor)it.next();
1039 if (md.isStatic()||md.getReturnType()==null)
1041 int methodnum=virtualcalls.getMethodNumber(md);
1042 virtualtable[rownum][methodnum]=md;
1046 private void fillinRow(ClassDescriptor cd, LocalityBinding[][] virtualtable, int rownum) {
1047 /* Get inherited methods */
1048 if (cd.getSuperDesc()!=null)
1049 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
1050 /* Override them with our methods */
1051 if (locality.getClassBindings(cd)!=null)
1052 for(Iterator<LocalityBinding> lbit=locality.getClassBindings(cd).iterator(); lbit.hasNext();) {
1053 LocalityBinding lb=lbit.next();
1054 MethodDescriptor md=lb.getMethod();
1055 //Is the method static or a constructor
1056 if (md.isStatic()||md.getReturnType()==null)
1058 int methodnum=virtualcalls.getLocalityNumber(lb);
1059 virtualtable[rownum][methodnum]=lb;
1063 /** Generate array that contains the sizes of class objects. The
1064 * object allocation functions in the runtime use this
1067 private void generateSizeArray(PrintWriter outclassdefs) {
1068 outclassdefs.print("extern struct prefetchCountStats * evalPrefetch;\n");
1069 outclassdefs.print("#ifdef TRANSSTATS \n");
1070 outclassdefs.print("extern int numTransAbort;\n");
1071 outclassdefs.print("extern int numTransCommit;\n");
1072 outclassdefs.print("extern int nSoftAbort;\n");
1074 outclassdefs.print("extern int nchashSearch;\n");
1075 outclassdefs.print("extern int nmhashSearch;\n");
1076 outclassdefs.print("extern int nprehashSearch;\n");
1077 outclassdefs.print("extern int ndirtyCacheObj;\n");
1078 outclassdefs.print("extern int nRemoteSend;\n");
1079 outclassdefs.print("extern int sendRemoteReq;\n");
1080 outclassdefs.print("extern int getResponse;\n");
1081 outclassdefs.print("extern int bytesSent;\n");
1082 outclassdefs.print("extern int bytesRecv;\n");
1083 outclassdefs.print("extern int totalObjSize;\n");
1084 outclassdefs.print("extern void handle();\n");
1085 } else if (state.SINGLETM) {
1086 outclassdefs.println("extern int nSoftAbortAbort;");
1087 outclassdefs.println("extern int nSoftAbortCommit;");
1088 outclassdefs.println("#ifdef STMSTATS\n");
1089 outclassdefs.println("extern objtypestat_t typesCausingAbort[];");
1090 outclassdefs.println("#endif\n");
1092 outclassdefs.print("#endif\n");
1094 outclassdefs.print("int numprefetchsites = " + pa.prefetchsiteid + ";\n");
1095 if(this.state.MLP || state.OOOJAVA ){
1096 outclassdefs.print("extern __thread int oid;\n");
1097 outclassdefs.print("extern int numWorkers;\n");
1100 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1101 cdarray=new ClassDescriptor[state.numClasses()];
1103 while(it.hasNext()) {
1104 ClassDescriptor cd=(ClassDescriptor)it.next();
1105 cdarray[cd.getId()]=cd;
1108 arraytable=new TypeDescriptor[state.numArrays()];
1110 Iterator arrayit=state.getArrayIterator();
1111 while(arrayit.hasNext()) {
1112 TypeDescriptor td=(TypeDescriptor)arrayit.next();
1113 int id=state.getArrayNumber(td);
1119 /* Print out types */
1120 outclassdefs.println("/* ");
1121 for(int i=0; i<state.numClasses(); i++) {
1122 ClassDescriptor cd=cdarray[i];
1124 outclassdefs.println("NULL " + i);
1126 outclassdefs.println(cd +" "+i);
1130 for(int i=0; i<state.numArrays(); i++) {
1131 TypeDescriptor arraytd=arraytable[i];
1132 outclassdefs.println(arraytd.toPrettyString() +" "+(i+state.numClasses()));
1135 outclassdefs.println("*/");
1138 outclassdefs.print("int classsize[]={");
1140 boolean needcomma=false;
1141 for(int i=0; i<state.numClasses(); i++) {
1143 outclassdefs.print(", ");
1145 outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")");
1147 outclassdefs.print("0");
1153 for(int i=0; i<state.numArrays(); i++) {
1155 outclassdefs.print(", ");
1156 TypeDescriptor tdelement=arraytable[i].dereference();
1157 if (tdelement.isArray()||tdelement.isClass())
1158 outclassdefs.print("sizeof(void *)");
1160 outclassdefs.print("sizeof("+tdelement.getSafeSymbol()+")");
1164 outclassdefs.println("};");
1166 ClassDescriptor objectclass=typeutil.getClass(TypeUtil.ObjectClass);
1168 outclassdefs.print("int typearray[]={");
1169 for(int i=0; i<state.numClasses(); i++) {
1170 ClassDescriptor cd=cdarray[i];
1171 ClassDescriptor supercd=i>0?cd.getSuperDesc():null;
1173 outclassdefs.print(", ");
1175 outclassdefs.print("-1");
1177 outclassdefs.print(supercd.getId());
1181 for(int i=0; i<state.numArrays(); i++) {
1182 TypeDescriptor arraytd=arraytable[i];
1183 ClassDescriptor arraycd=arraytd.getClassDesc();
1184 if (arraycd==null) {
1186 outclassdefs.print(", ");
1187 outclassdefs.print(objectclass.getId());
1191 ClassDescriptor cd=arraycd.getSuperDesc();
1194 TypeDescriptor supertd=new TypeDescriptor(cd);
1195 supertd.setArrayCount(arraytd.getArrayCount());
1196 type=state.getArrayNumber(supertd);
1198 type+=state.numClasses();
1201 cd=cd.getSuperDesc();
1204 outclassdefs.print(", ");
1205 outclassdefs.print(type);
1209 outclassdefs.println("};");
1214 outclassdefs.print("int typearray2[]={");
1215 for(int i=0; i<state.numArrays(); i++) {
1216 TypeDescriptor arraytd=arraytable[i];
1217 ClassDescriptor arraycd=arraytd.getClassDesc();
1218 if (arraycd==null) {
1220 outclassdefs.print(", ");
1221 outclassdefs.print("-1");
1225 ClassDescriptor cd=arraycd.getSuperDesc();
1226 int level=arraytd.getArrayCount()-1;
1228 for(; level>0; level--) {
1229 TypeDescriptor supertd=new TypeDescriptor(objectclass);
1230 supertd.setArrayCount(level);
1231 type=state.getArrayNumber(supertd);
1233 type+=state.numClasses();
1238 outclassdefs.print(", ");
1239 outclassdefs.print(type);
1243 outclassdefs.println("};");
1246 /** Constructs params and temp objects for each method or task.
1247 * These objects tell the compiler which temps need to be
1250 protected void generateTempStructs(FlatMethod fm, LocalityBinding lb) {
1251 MethodDescriptor md=fm.getMethod();
1252 TaskDescriptor task=fm.getTask();
1253 Set<TempDescriptor> saveset=lb!=null ? locality.getTempSet(lb) : null;
1254 ParamsObject objectparams=md!=null ? new ParamsObject(md,tag++) : new ParamsObject(task, tag++);
1256 paramstable.put(lb, objectparams);
1257 backuptable.put(lb, new Hashtable<TempDescriptor, TempDescriptor>());
1258 } else if (md!=null)
1259 paramstable.put(md, objectparams);
1261 paramstable.put(task, objectparams);
1263 for(int i=0; i<fm.numParameters(); i++) {
1264 TempDescriptor temp=fm.getParameter(i);
1265 TypeDescriptor type=temp.getType();
1266 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1267 objectparams.addPtr(temp);
1269 objectparams.addPrim(temp);
1270 if(lb!=null&&saveset.contains(temp)) {
1271 backuptable.get(lb).put(temp, temp.createNew());
1275 for(int i=0; i<fm.numTags(); i++) {
1276 TempDescriptor temp=fm.getTag(i);
1277 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1278 objectparams.addPtr(temp);
1280 objectparams.addPrim(temp);
1283 TempObject objecttemps=md!=null ? new TempObject(objectparams,md,tag++) : new TempObject(objectparams, task, tag++);
1285 tempstable.put(lb, objecttemps);
1287 tempstable.put(md, objecttemps);
1289 tempstable.put(task, objecttemps);
1291 for(Iterator nodeit=fm.getNodeSet().iterator(); nodeit.hasNext();) {
1292 FlatNode fn=(FlatNode)nodeit.next();
1293 TempDescriptor[] writes=fn.writesTemps();
1294 for(int i=0; i<writes.length; i++) {
1295 TempDescriptor temp=writes[i];
1296 TypeDescriptor type=temp.getType();
1297 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1298 objecttemps.addPtr(temp);
1300 objecttemps.addPrim(temp);
1301 if(lb!=null&&saveset.contains(temp)&&
1302 !backuptable.get(lb).containsKey(temp))
1303 backuptable.get(lb).put(temp, temp.createNew());
1307 /* Create backup temps */
1309 for(Iterator<TempDescriptor> tmpit=backuptable.get(lb).values().iterator(); tmpit.hasNext();) {
1310 TempDescriptor tmp=tmpit.next();
1311 TypeDescriptor type=tmp.getType();
1312 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1313 objecttemps.addPtr(tmp);
1315 objecttemps.addPrim(tmp);
1317 /* Create temp to hold revert table */
1318 if (state.DSM&&(lb.getHasAtomic()||lb.isAtomic())) {
1319 TempDescriptor reverttmp=new TempDescriptor("revertlist", typeutil.getClass(TypeUtil.ObjectClass));
1320 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1321 objecttemps.addPtr(reverttmp);
1323 objecttemps.addPrim(reverttmp);
1324 reverttable.put(lb, reverttmp);
1329 /** This method outputs the following information about classes
1331 * (1) For classes, what are the locations of pointers.
1332 * (2) For arrays, does the array contain pointers or primitives.
1333 * (3) For classes, does the class contain flags.
1336 private void generateLayoutStructs(PrintWriter output) {
1337 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1338 while(it.hasNext()) {
1339 ClassDescriptor cn=(ClassDescriptor)it.next();
1340 output.println("unsigned INTPTR "+cn.getSafeSymbol()+"_pointers[]={");
1341 Iterator allit=cn.getFieldTable().getAllDescriptorsIterator();
1343 while(allit.hasNext()) {
1344 FieldDescriptor fd=(FieldDescriptor)allit.next();
1345 TypeDescriptor type=fd.getType();
1346 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1351 output.print(count);
1352 allit=cn.getFieldTable().getAllDescriptorsIterator();
1353 while(allit.hasNext()) {
1354 FieldDescriptor fd=(FieldDescriptor)allit.next();
1355 TypeDescriptor type=fd.getType();
1356 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1359 output.println(",");
1360 output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+fd.getSafeSymbol()+"))");
1363 output.println("};");
1365 output.println("unsigned INTPTR * pointerarray[]={");
1366 boolean needcomma=false;
1367 for(int i=0; i<state.numClasses(); i++) {
1368 ClassDescriptor cn=cdarray[i];
1370 output.println(",");
1373 output.print(cn.getSafeSymbol()+"_pointers");
1375 output.print("NULL");
1379 for(int i=0; i<state.numArrays(); i++) {
1381 output.println(", ");
1382 TypeDescriptor tdelement=arraytable[i].dereference();
1383 if (tdelement.isArray()||tdelement.isClass())
1384 output.print("((unsigned INTPTR *)1)");
1390 output.println("};");
1392 output.println("int hasflags[]={");
1393 for(int i=0; i<state.numClasses(); i++) {
1394 ClassDescriptor cn=cdarray[i];
1396 output.println(", ");
1398 if ((cn != null) && (cn.hasFlags()))
1403 output.println("};");
1406 /** Print out table to give us supertypes */
1407 private void generateSuperTypeTable(PrintWriter output) {
1408 output.println("int supertypes[]={");
1409 boolean needcomma=false;
1410 for(int i=0; i<state.numClasses(); i++) {
1411 ClassDescriptor cn=cdarray[i];
1413 output.println(",");
1415 if ((cn != null) && (cn.getSuperDesc()!=null)) {
1416 ClassDescriptor cdsuper=cn.getSuperDesc();
1417 output.print(cdsuper.getId());
1421 output.println("};");
1424 /** Force consistent field ordering between inherited classes. */
1426 private void printClassStruct(ClassDescriptor cn, PrintWriter classdefout) {
1428 ClassDescriptor sp=cn.getSuperDesc();
1430 printClassStruct(sp, classdefout);
1432 if (!fieldorder.containsKey(cn)) {
1433 Vector fields=new Vector();
1434 fieldorder.put(cn,fields);
1435 Vector fieldvec=cn.getFieldVec();
1436 for(int i=0;i<fieldvec.size();i++) {
1437 FieldDescriptor fd=(FieldDescriptor)fieldvec.get(i);
1438 if ((sp==null||!sp.getFieldTable().contains(fd.getSymbol())))
1442 Vector fields=(Vector)fieldorder.get(cn);
1444 for(int i=0; i<fields.size(); i++) {
1445 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
1446 if (fd.getType().isClass()||fd.getType().isArray())
1447 classdefout.println(" struct "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1449 classdefout.println(" "+fd.getType().getSafeSymbol()+" "+fd.getSafeSymbol()+";");
1454 /* Map flags to integers consistently between inherited
1457 protected void mapFlags(ClassDescriptor cn) {
1458 ClassDescriptor sp=cn.getSuperDesc();
1462 if (!flagorder.containsKey(cn)) {
1463 Hashtable flags=new Hashtable();
1464 flagorder.put(cn,flags);
1466 Hashtable superflags=(Hashtable)flagorder.get(sp);
1467 Iterator superflagit=superflags.keySet().iterator();
1468 while(superflagit.hasNext()) {
1469 FlagDescriptor fd=(FlagDescriptor)superflagit.next();
1470 Integer number=(Integer)superflags.get(fd);
1471 flags.put(fd, number);
1472 if ((number.intValue()+1)>max)
1473 max=number.intValue()+1;
1477 Iterator flagit=cn.getFlags();
1478 while(flagit.hasNext()) {
1479 FlagDescriptor fd=(FlagDescriptor)flagit.next();
1480 if (sp==null||!sp.getFlagTable().contains(fd.getSymbol()))
1481 flags.put(fd, new Integer(max++));
1487 /** This function outputs (1) structures that parameters are
1488 * passed in (when PRECISE GC is enabled) and (2) function
1489 * prototypes for the methods */
1491 protected void generateCallStructs(ClassDescriptor cn, PrintWriter classdefout, PrintWriter output, PrintWriter headersout) {
1492 /* Output class structure */
1493 classdefout.println("struct "+cn.getSafeSymbol()+" {");
1494 classdefout.println(" int type;");
1495 if(state.MLP || state.OOOJAVA){
1496 classdefout.println(" int oid;");
1497 classdefout.println(" int allocsite;");
1499 if (state.EVENTMONITOR) {
1500 classdefout.println(" int objuid;");
1503 classdefout.println(" pthread_t tid;");
1504 classdefout.println(" void * lockentry;");
1505 classdefout.println(" int lockcount;");
1509 classdefout.println(" int flag;");
1510 if((!state.MULTICORE) || (cn.getSymbol().equals("TagDescriptor"))) {
1511 classdefout.println(" void * flagptr;");
1512 } else if (state.MULTICORE) {
1513 classdefout.println(" int version;");
1514 classdefout.println(" int * lock;"); // lock entry for this obj
1515 classdefout.println(" int mutex;");
1516 classdefout.println(" int lockcount;");
1517 if(state.MULTICOREGC) {
1518 classdefout.println(" int marked;");
1521 if (state.OPTIONAL) {
1522 classdefout.println(" int numfses;");
1523 classdefout.println(" int * fses;");
1526 printClassStruct(cn, classdefout);
1527 classdefout.println("};\n");
1529 if (state.DSM||state.SINGLETM) {
1530 /* Cycle through LocalityBindings */
1531 HashSet<MethodDescriptor> nativemethods=new HashSet<MethodDescriptor>();
1532 Set<LocalityBinding> lbset=locality.getClassBindings(cn);
1534 for(Iterator<LocalityBinding> lbit=lbset.iterator(); lbit.hasNext();) {
1535 LocalityBinding lb=lbit.next();
1536 MethodDescriptor md=lb.getMethod();
1537 if (md.getModifiers().isNative()) {
1538 //make sure we only print a native method once
1539 if (nativemethods.contains(md)) {
1540 FlatMethod fm=state.getMethodFlat(md);
1541 generateTempStructs(fm, lb);
1544 nativemethods.add(md);
1546 generateMethod(cn, md, lb, headersout, output);
1549 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1550 MethodDescriptor md=(MethodDescriptor)methodit.next();
1551 if (md.getModifiers().isNative()&&!nativemethods.contains(md)) {
1552 //Need to build param structure for library code
1553 FlatMethod fm=state.getMethodFlat(md);
1554 generateTempStructs(fm, null);
1555 generateMethodParam(cn, md, null, output);
1560 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1561 MethodDescriptor md=(MethodDescriptor)methodit.next();
1562 generateMethod(cn, md, null, headersout, output);
1566 private void generateMethodParam(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter output) {
1567 /* Output parameter structure */
1568 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1569 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1570 if ((state.DSM||state.SINGLETM)&&lb!=null)
1571 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1573 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1574 output.println(" int size;");
1575 output.println(" void * next;");
1576 for(int i=0; i<objectparams.numPointers(); i++) {
1577 TempDescriptor temp=objectparams.getPointer(i);
1578 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1580 output.println("};\n");
1584 private void generateMethod(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter headersout, PrintWriter output) {
1585 FlatMethod fm=state.getMethodFlat(md);
1586 generateTempStructs(fm, lb);
1588 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1589 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md);
1591 generateMethodParam(cn, md, lb, output);
1593 /* Output temp structure */
1594 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1595 if (state.DSM||state.SINGLETM)
1596 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1598 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1599 output.println(" int size;");
1600 output.println(" void * next;");
1601 for(int i=0; i<objecttemps.numPointers(); i++) {
1602 TempDescriptor temp=objecttemps.getPointer(i);
1603 if (temp.getType().isNull())
1604 output.println(" void * "+temp.getSafeSymbol()+";");
1606 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1608 output.println("};\n");
1611 /********* Output method declaration ***********/
1612 if (state.DSM||state.SINGLETM) {
1613 headersout.println("#define D"+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1615 headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1617 /* First the return type */
1618 if (md.getReturnType()!=null) {
1619 if (md.getReturnType().isClass()||md.getReturnType().isArray())
1620 headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1622 headersout.print(md.getReturnType().getSafeSymbol()+" ");
1624 //catch the constructor case
1625 headersout.print("void ");
1627 /* Next the method name */
1628 if (state.DSM||state.SINGLETM) {
1629 headersout.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1631 headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1633 boolean printcomma=false;
1634 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1635 if (state.DSM||state.SINGLETM) {
1636 headersout.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1638 headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1642 /* Output parameter list*/
1643 for(int i=0; i<objectparams.numPrimitives(); i++) {
1644 TempDescriptor temp=objectparams.getPrimitive(i);
1646 headersout.print(", ");
1648 if (temp.getType().isClass()||temp.getType().isArray())
1649 headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1651 headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1653 headersout.println(");\n");
1657 /** This function outputs (1) structures that parameters are
1658 * passed in (when PRECISE GC is enabled) and (2) function
1659 * prototypes for the tasks */
1661 private void generateTaskStructs(PrintWriter output, PrintWriter headersout) {
1662 /* Cycle through tasks */
1663 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
1665 while(taskit.hasNext()) {
1666 /* Classify parameters */
1667 TaskDescriptor task=(TaskDescriptor)taskit.next();
1668 FlatMethod fm=state.getMethodFlat(task);
1669 generateTempStructs(fm, null);
1671 ParamsObject objectparams=(ParamsObject) paramstable.get(task);
1672 TempObject objecttemps=(TempObject) tempstable.get(task);
1674 /* Output parameter structure */
1675 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1676 output.println("struct "+task.getSafeSymbol()+"_params {");
1677 output.println(" int size;");
1678 output.println(" void * next;");
1679 for(int i=0; i<objectparams.numPointers(); i++) {
1680 TempDescriptor temp=objectparams.getPointer(i);
1681 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1684 output.println("};\n");
1685 if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
1686 maxtaskparams=objectparams.numPointers()+fm.numTags();
1690 /* Output temp structure */
1691 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1692 output.println("struct "+task.getSafeSymbol()+"_locals {");
1693 output.println(" int size;");
1694 output.println(" void * next;");
1695 for(int i=0; i<objecttemps.numPointers(); i++) {
1696 TempDescriptor temp=objecttemps.getPointer(i);
1697 if (temp.getType().isNull())
1698 output.println(" void * "+temp.getSafeSymbol()+";");
1699 else if(temp.getType().isTag())
1700 output.println(" struct "+
1701 (new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1703 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1705 output.println("};\n");
1708 /* Output task declaration */
1709 headersout.print("void " + task.getSafeSymbol()+"(");
1711 boolean printcomma=false;
1712 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1713 headersout.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
1715 headersout.print("void * parameterarray[]");
1716 headersout.println(");\n");
1720 /***** Generate code for FlatMethod fm. *****/
1722 Hashtable<FlatAtomicEnterNode, AtomicRecord> atomicmethodmap;
1723 static int atomicmethodcount=0;
1726 BranchAnalysis branchanalysis;
1727 private void generateFlatMethod(FlatMethod fm, LocalityBinding lb, PrintWriter output) {
1728 if (State.PRINTFLAT)
1729 System.out.println(fm.printMethod());
1730 MethodDescriptor md=fm.getMethod();
1731 TaskDescriptor task=fm.getTask();
1732 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
1733 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : md!=null ? md : task);
1735 HashSet<AtomicRecord> arset=null;
1736 branchanalysis=null;
1738 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1740 if (atomicmethodmap==null)
1741 atomicmethodmap=new Hashtable<FlatAtomicEnterNode, AtomicRecord>();
1743 //fix these so we get right strings for local variables
1744 localsprefixaddr=localsprefix;
1745 localsprefixderef=localsprefix+"->";
1746 arset=new HashSet<AtomicRecord>();
1748 //build branchanalysis
1749 branchanalysis=new BranchAnalysis(locality, lb, delaycomp.getNotReady(lb), delaycomp.livecode(lb), state);
1751 //Generate commit methods here
1752 for(Iterator<FlatNode> fnit=fm.getNodeSet().iterator();fnit.hasNext();) {
1753 FlatNode fn=fnit.next();
1754 if (fn.kind()==FKind.FlatAtomicEnterNode&&
1755 locality.getAtomic(lb).get(fn.getPrev(0)).intValue()==0&&
1756 delaycomp.needsFission(lb, (FlatAtomicEnterNode) fn)) {
1757 //We have an atomic enter
1758 FlatAtomicEnterNode faen=(FlatAtomicEnterNode) fn;
1759 Set<FlatNode> exitset=faen.getExits();
1761 String methodname=md.getSymbol()+(atomicmethodcount++);
1762 AtomicRecord ar=new AtomicRecord();
1766 atomicmethodmap.put(faen, ar);
1768 //build data structure declaration
1769 output.println("struct atomicprimitives_"+methodname+" {");
1771 Set<FlatNode> recordset=delaycomp.livecode(lb);
1772 Set<TempDescriptor> liveinto=delaycomp.liveinto(lb, faen, recordset);
1773 Set<TempDescriptor> liveout=delaycomp.liveout(lb, faen);
1774 Set<TempDescriptor> liveoutvirtualread=delaycomp.liveoutvirtualread(lb, faen);
1776 ar.reallivein=new HashSet(liveinto);
1778 ar.liveoutvirtualread=liveoutvirtualread;
1781 for(Iterator<TempDescriptor> it=liveinto.iterator(); it.hasNext();) {
1782 TempDescriptor tmp=it.next();
1783 //remove the pointers
1784 if (tmp.getType().isPtr()) {
1787 //let's print it here
1788 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1791 for(Iterator<TempDescriptor> it=liveout.iterator(); it.hasNext();) {
1792 TempDescriptor tmp=it.next();
1793 //remove the pointers
1794 if (tmp.getType().isPtr()) {
1796 } else if (!liveinto.contains(tmp)) {
1797 //let's print it here
1798 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1801 output.println("};");
1803 //print out method name
1804 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) {");
1805 //build code for commit method
1807 //first define local primitives
1808 Set<TempDescriptor> alltemps=delaycomp.alltemps(lb, faen, recordset);
1809 for(Iterator<TempDescriptor> tmpit=alltemps.iterator();tmpit.hasNext();) {
1810 TempDescriptor tmp=tmpit.next();
1811 if (!tmp.getType().isPtr()) {
1812 if (liveinto.contains(tmp)||liveoutvirtualread.contains(tmp)) {
1813 //read from live into set
1814 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+"=primitives->"+tmp.getSafeSymbol()+";");
1817 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1821 //turn off write barrier generation
1823 state.SINGLETM=false;
1824 generateCode(faen, fm, lb, exitset, output, false);
1825 state.SINGLETM=true;
1826 //turn on write barrier generation
1828 output.println("}\n\n");
1832 //redefine these back to normal
1834 localsprefixaddr="&"+localsprefix;
1835 localsprefixderef=localsprefix+".";
1837 generateHeader(fm, lb, md!=null ? md : task,output);
1838 TempObject objecttemp=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
1840 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1841 for(Iterator<AtomicRecord> arit=arset.iterator();arit.hasNext();) {
1842 AtomicRecord ar=arit.next();
1843 output.println("struct atomicprimitives_"+ar.name+" primitives_"+ar.name+";");
1847 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1848 if (md!=null&&(state.DSM||state.SINGLETM))
1849 output.print(" struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1850 else if (md!=null&&!(state.DSM||state.SINGLETM))
1851 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1853 output.print(" struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={");
1854 output.print(objecttemp.numPointers()+",");
1855 output.print(paramsprefix);
1856 for(int j=0; j<objecttemp.numPointers(); j++)
1857 output.print(", NULL");
1858 output.println("};");
1861 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1862 TempDescriptor td=objecttemp.getPrimitive(i);
1863 TypeDescriptor type=td.getType();
1865 output.println(" void * "+td.getSafeSymbol()+";");
1866 else if (type.isClass()||type.isArray())
1867 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1869 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1873 if( state.MLP || state.OOOJAVA ) {
1874 if( fm.getNext(0) instanceof FlatSESEEnterNode ) {
1875 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
1876 if( (state.MLP && callerSESEplaceholder != mlpa.getMainSESE()) ||
1877 (state.OOOJAVA && callerSESEplaceholder != oooa.getMainSESE())
1879 // declare variables for naming static SESE's
1880 output.println(" /* static SESE names */");
1881 Iterator<SESEandAgePair> pItr = callerSESEplaceholder.getNeededStaticNames().iterator();
1882 while( pItr.hasNext() ) {
1883 SESEandAgePair pair = pItr.next();
1884 output.println(" void* "+pair+";");
1887 // declare variables for tracking dynamic sources
1888 output.println(" /* dynamic variable sources */");
1889 Iterator<TempDescriptor> dynSrcItr = callerSESEplaceholder.getDynamicVarSet().iterator();
1890 while( dynSrcItr.hasNext() ) {
1891 TempDescriptor dynSrcVar = dynSrcItr.next();
1892 output.println(" void* "+dynSrcVar+"_srcSESE;");
1893 output.println(" INTPTR "+dynSrcVar+"_srcOffset;");
1898 // set up related allocation sites's waiting queues
1901 ConflictGraph graph = null;
1902 graph = mlpa.getConflictGraphResults().get(fm);
1903 if (graph != null && graph.hasConflictEdge()) {
1904 output.println(" /* set up waiting queues */");
1905 output.println(" int numMemoryQueue=0;");
1906 output.println(" int memoryQueueItemID=0;");
1907 HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
1909 System.out.println("#lockSet="+lockSet.hashCode());
1910 System.out.println("lockset="+lockSet);
1911 for (Iterator iterator = lockSet.iterator(); iterator.hasNext();) {
1912 SESELock seseLock = (SESELock) iterator.next();
1913 System.out.println("id="+seseLock.getID());
1914 System.out.println("#="+seseLock);
1916 System.out.println("size="+lockSet.size());
1917 if (lockSet.size() > 0) {
1918 output.println(" numMemoryQueue=" + lockSet.size() + ";");
1920 .println(" seseCaller->numMemoryQueue=numMemoryQueue;");
1922 .println(" seseCaller->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
1927 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
1928 if(callerSESEplaceholder!= oooa.getMainSESE()){
1929 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(callerSESEplaceholder);
1930 if (graph != null && graph.hasConflictEdge()) {
1931 output.println(" // set up waiting queues ");
1932 output.println(" int numMemoryQueue=0;");
1933 output.println(" int memoryQueueItemID=0;");
1934 Set<Analysis.OoOJava.SESELock> lockSet = oooa.getLockMappings(graph);
1935 System.out.println("#lockSet="+lockSet.hashCode());
1936 System.out.println("lockset="+lockSet);
1937 for (Iterator iterator = lockSet.iterator(); iterator.hasNext();) {
1938 Analysis.OoOJava.SESELock seseLock = (Analysis.OoOJava.SESELock) iterator.next();
1939 System.out.println("id="+seseLock.getID());
1940 System.out.println("#="+seseLock);
1942 System.out.println("size="+lockSet.size());
1943 if (lockSet.size() > 0) {
1944 output.println(" numMemoryQueue=" + lockSet.size() + ";");
1946 .println(" seseCaller->numMemoryQueue=numMemoryQueue;");
1948 .println(" seseCaller->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
1958 /* Check to see if we need to do a GC if this is a
1959 * multi-threaded program...*/
1961 if (((state.MLP||state.OOOJAVA||state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
1962 || this.state.MULTICOREGC) {
1963 //Don't bother if we aren't in recursive methods...The loops case will catch it
1964 if (callgraph.getAllMethods(md).contains(md)) {
1965 if (state.DSM&&lb.isAtomic())
1966 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
1967 else if (this.state.MULTICOREGC) {
1968 output.println("if(gcflag) gc("+localsprefixaddr+");");
1970 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
1975 generateCode(fm.getNext(0), fm, lb, null, output, true);
1977 output.println("}\n\n");
1981 protected void initializeSESE( FlatSESEEnterNode fsen ) {
1983 FlatMethod fm = fsen.getfmEnclosing();
1984 MethodDescriptor md = fm.getMethod();
1985 ClassDescriptor cn = md.getClassDesc();
1988 // Creates bogus method descriptor to index into tables
1989 Modifiers modBogus = new Modifiers();
1990 MethodDescriptor mdBogus =
1991 new MethodDescriptor( modBogus,
1992 new TypeDescriptor( TypeDescriptor.VOID ),
1993 "sese_"+fsen.getPrettyIdentifier()+fsen.getIdentifier()
1996 mdBogus.setClassDesc( fsen.getcdEnclosing() );
1997 FlatMethod fmBogus = new FlatMethod( mdBogus, null );
1998 fsen.setfmBogus( fmBogus );
1999 fsen.setmdBogus( mdBogus );
2001 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
2002 inSetAndOutSet.addAll( fsen.getInVarSet() );
2003 inSetAndOutSet.addAll( fsen.getOutVarSet() );
2005 // Build paramsobj for bogus method descriptor
2006 ParamsObject objectparams = new ParamsObject( mdBogus, tag++ );
2007 paramstable.put( mdBogus, objectparams );
2009 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
2010 while( itr.hasNext() ) {
2011 TempDescriptor temp = itr.next();
2012 TypeDescriptor type = temp.getType();
2013 if( type.isPtr() ) {
2014 objectparams.addPtr( temp );
2016 objectparams.addPrim( temp );
2020 // Build normal temp object for bogus method descriptor
2021 TempObject objecttemps = new TempObject( objectparams, mdBogus, tag++ );
2022 tempstable.put( mdBogus, objecttemps );
2024 for( Iterator nodeit = fsen.getNodeSet().iterator(); nodeit.hasNext(); ) {
2025 FlatNode fn = (FlatNode)nodeit.next();
2026 TempDescriptor[] writes = fn.writesTemps();
2028 for( int i = 0; i < writes.length; i++ ) {
2029 TempDescriptor temp = writes[i];
2030 TypeDescriptor type = temp.getType();
2032 if( type.isPtr() ) {
2033 objecttemps.addPtr( temp );
2035 objecttemps.addPrim( temp );
2041 // used when generating the specific SESE record struct
2042 // to remember the FIRST field name of sese records
2043 // that the current SESE depends on--we need to know the
2044 // offset to the first one for garbage collection
2045 protected void addingDepRecField( FlatSESEEnterNode fsen,
2047 if( fsen.getFirstDepRecField() == null ) {
2048 fsen.setFirstDepRecField( field );
2050 fsen.incNumDepRecs();
2053 protected void generateMethodSESE(FlatSESEEnterNode fsen,
2055 PrintWriter outputStructs,
2056 PrintWriter outputMethHead,
2057 PrintWriter outputMethods
2060 ParamsObject objectparams = (ParamsObject) paramstable.get( fsen.getmdBogus() );
2061 TempObject objecttemps = (TempObject) tempstable .get( fsen.getmdBogus() );
2063 // generate locals structure
2064 outputStructs.println("struct "+
2065 fsen.getcdEnclosing().getSafeSymbol()+
2066 fsen.getmdBogus().getSafeSymbol()+"_"+
2067 fsen.getmdBogus().getSafeMethodDescriptor()+
2069 outputStructs.println(" int size;");
2070 outputStructs.println(" void * next;");
2071 for(int i=0; i<objecttemps.numPointers(); i++) {
2072 TempDescriptor temp=objecttemps.getPointer(i);
2074 if (temp.getType().isNull())
2075 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
2077 outputStructs.println(" struct "+
2078 temp.getType().getSafeSymbol()+" * "+
2079 temp.getSafeSymbol()+";");
2081 outputStructs.println("};\n");
2084 // divide in-set and out-set into objects and primitives to prep
2085 // for the record generation just below
2086 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
2087 inSetAndOutSet.addAll( fsen.getInVarSet() );
2088 inSetAndOutSet.addAll( fsen.getOutVarSet() );
2090 Set<TempDescriptor> inSetAndOutSetObjs = new HashSet<TempDescriptor>();
2091 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
2093 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
2094 while( itr.hasNext() ) {
2095 TempDescriptor temp = itr.next();
2096 TypeDescriptor type = temp.getType();
2097 if( type.isPtr() ) {
2098 inSetAndOutSetObjs.add( temp );
2100 inSetAndOutSetPrims.add( temp );
2105 // generate the SESE record structure
2106 outputStructs.println(fsen.getSESErecordName()+" {");
2108 // data common to any SESE, and it must be placed first so
2109 // a module that doesn't know what kind of SESE record this
2110 // is can cast the pointer to a common struct
2111 outputStructs.println(" SESEcommon common;");
2113 // then garbage list stuff
2114 outputStructs.println(" /* next is in-set and out-set objects that look like a garbage list */");
2115 outputStructs.println(" int size;");
2116 outputStructs.println(" void * next;");
2118 // I think that the set of TempDescriptors inSetAndOutSetObjs
2119 // calculated above should match the pointer object params
2120 // used in the following code, but let's just leave the working
2121 // implementation unless there is actually a problem...
2122 for(int i=0; i<objectparams.numPointers(); i++) {
2123 TempDescriptor temp=objectparams.getPointer(i);
2124 if (temp.getType().isNull())
2125 outputStructs.println(" void * "+temp.getSafeSymbol()+
2126 "; /* in-or-out-set obj in gl */");
2128 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+
2129 temp.getSafeSymbol()+"; /* in-or-out-set obj in gl */");
2132 outputStructs.println(" /* next is primitives for in-set and out-set and dynamic tracking */");
2134 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
2135 while( itrPrims.hasNext() ) {
2136 TempDescriptor temp = itrPrims.next();
2137 TypeDescriptor type = temp.getType();
2138 if(type.isPrimitive()){
2139 outputStructs.println(" "+temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol()+"; /* in-set or out-set primitive */");
2143 // note that the sese record pointer will be added below, just primitive part of tracking here
2144 Iterator<TempDescriptor> itrDynInVars = fsen.getDynamicInVarSet().iterator();
2145 while( itrDynInVars.hasNext() ) {
2146 TempDescriptor dynInVar = itrDynInVars.next();
2147 outputStructs.println(" INTPTR "+dynInVar+"_srcOffset; /* dynamic tracking primitive */");
2151 outputStructs.println(" /* everything after this should be pointers to an SESE record */" );
2153 // other half of info for dynamic tracking, the SESE record pointer
2154 itrDynInVars = fsen.getDynamicInVarSet().iterator();
2155 while( itrDynInVars.hasNext() ) {
2156 TempDescriptor dynInVar = itrDynInVars.next();
2157 String depRecField = dynInVar+"_srcSESE";
2158 outputStructs.println(" void* "+depRecField+";");
2159 addingDepRecField( fsen, depRecField );
2162 // statically known sese sources are record pointers, too
2163 Iterator<SESEandAgePair> itrStaticInVarSrcs = fsen.getStaticInVarSrcs().iterator();
2164 while( itrStaticInVarSrcs.hasNext() ) {
2165 SESEandAgePair srcPair = itrStaticInVarSrcs.next();
2166 outputStructs.println(" "+srcPair.getSESE().getSESErecordName()+"* "+srcPair+";");
2167 addingDepRecField( fsen, srcPair.toString() );
2170 if( fsen.getFirstDepRecField() != null ) {
2171 outputStructs.println(" /* compiler believes first dependent SESE record field above is: "+
2172 fsen.getFirstDepRecField()+" */" );
2175 outputStructs.println("};\n");
2178 // write method declaration to header file
2179 outputMethHead.print("void ");
2180 outputMethHead.print(fsen.getSESEmethodName()+"(");
2181 outputMethHead.print(fsen.getSESErecordName()+"* "+paramsprefix);
2182 outputMethHead.println(");\n");
2185 generateFlatMethodSESE( fsen.getfmBogus(),
2186 fsen.getcdEnclosing(),
2192 private void generateFlatMethodSESE(FlatMethod fm,
2194 FlatSESEEnterNode fsen,
2195 FlatSESEExitNode seseExit,
2199 MethodDescriptor md=fm.getMethod();
2201 output.print("void ");
2202 output.print(fsen.getSESEmethodName()+"(");
2203 output.print(fsen.getSESErecordName()+"* "+paramsprefix);
2204 output.println("){\n");
2206 TempObject objecttemp=(TempObject) tempstable.get(md);
2208 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2209 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
2210 output.print(objecttemp.numPointers()+",");
2211 output.print("&(((SESEcommon*)(___params___))[1])");
2212 for(int j=0; j<objecttemp.numPointers(); j++)
2213 output.print(", NULL");
2214 output.println("};");
2217 output.println(" /* regular local primitives */");
2218 for(int i=0; i<objecttemp.numPrimitives(); i++) {
2219 TempDescriptor td=objecttemp.getPrimitive(i);
2220 TypeDescriptor type=td.getType();
2222 output.println(" void * "+td.getSafeSymbol()+";");
2223 else if (type.isClass()||type.isArray())
2224 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
2226 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
2230 // declare variables for naming static SESE's
2231 output.println(" /* static SESE names */");
2232 Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
2233 while( pItr.hasNext() ) {
2234 SESEandAgePair pair = pItr.next();
2235 output.println(" void* "+pair+";");
2238 // declare variables for tracking dynamic sources
2239 output.println(" /* dynamic variable sources */");
2240 Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
2241 while( dynSrcItr.hasNext() ) {
2242 TempDescriptor dynSrcVar = dynSrcItr.next();
2243 output.println(" void* "+dynSrcVar+"_srcSESE;");
2244 output.println(" INTPTR "+dynSrcVar+"_srcOffset;");
2247 // declare local temps for in-set primitives, and if it is
2248 // a ready-source variable, get the value from the record
2249 output.println(" /* local temps for in-set primitives */");
2250 Iterator<TempDescriptor> itrInSet = fsen.getInVarSet().iterator();
2251 while( itrInSet.hasNext() ) {
2252 TempDescriptor temp = itrInSet.next();
2253 TypeDescriptor type = temp.getType();
2254 if( !type.isPtr() ) {
2255 if( fsen.getReadyInVarSet().contains( temp ) ) {
2256 output.println(" "+type+" "+temp+" = "+paramsprefix+"->"+temp+";");
2258 output.println(" "+type+" "+temp+";");
2263 // declare local temps for out-set primitives if its not already
2264 // in the in-set, and it's value will get written so no problem
2265 output.println(" /* local temp for out-set prim, not already in the in-set */");
2266 Iterator<TempDescriptor> itrOutSet = fsen.getOutVarSet().iterator();
2267 while( itrOutSet.hasNext() ) {
2268 TempDescriptor temp = itrOutSet.next();
2269 TypeDescriptor type = temp.getType();
2270 if( !type.isPtr() && !fsen.getInVarSet().contains( temp ) ) {
2271 output.println(" "+type+" "+temp+";");
2275 // setup memory queue
2278 output.println(" // set up memory queues ");
2279 output.println(" int numMemoryQueue=0;");
2280 output.println(" int memoryQueueItemID=0;");
2281 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(fsen);
2282 if (graph != null && graph.hasConflictEdge()) {
2283 output.println(" {");
2285 .println(" SESEcommon* parentCommon = &(___params___->common);");
2286 Set<Analysis.OoOJava.SESELock> lockSet = oooa.getLockMappings(graph);
2287 System.out.println("#lockSet="+lockSet);
2288 if (lockSet.size() > 0) {
2289 output.println(" numMemoryQueue=" + lockSet.size() + ";");
2291 .println(" parentCommon->numMemoryQueue=numMemoryQueue;");
2293 .println(" parentCommon->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2296 output.println(" }");
2299 output.println(" // set up memory queues ");
2300 output.println(" int numMemoryQueue=0;");
2301 output.println(" int memoryQueueItemID=0;");
2302 ConflictGraph graph = null;
2303 graph = mlpa.getConflictGraphResults().get(fsen);
2304 if (graph != null && graph.hasConflictEdge()) {
2305 output.println(" {");
2307 .println(" SESEcommon* parentCommon = &(___params___->common);");
2308 HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
2310 System.out.println("#lockSet="+lockSet);
2312 if (lockSet.size() > 0) {
2313 output.println(" numMemoryQueue=" + lockSet.size() + "; ");
2315 .println(" parentCommon->numMemoryQueue=numMemoryQueue;");
2317 .println(" parentCommon->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2320 output.println(" }");
2326 // copy in-set into place, ready vars were already
2327 // copied when the SESE was issued
2328 Iterator<TempDescriptor> tempItr;
2330 // static vars are from a known SESE
2331 tempItr = fsen.getStaticInVarSet().iterator();
2332 while( tempItr.hasNext() ) {
2333 TempDescriptor temp = tempItr.next();
2334 VariableSourceToken vst = fsen.getStaticInVarSrc( temp );
2335 SESEandAgePair srcPair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2337 // can't grab something from this source until it is done
2338 output.println(" {");
2340 If we are running, everything is done. This check is redundant.
2342 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+srcPair+";" );
2343 output.println(" pthread_mutex_lock( &(com->lock) );");
2344 output.println(" while( com->doneExecuting == FALSE ) {");
2345 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
2346 output.println(" }");
2347 output.println(" pthread_mutex_unlock( &(com->lock) );");
2349 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2350 " = "+paramsprefix+"->"+srcPair+"->"+vst.getAddrVar()+";");
2352 output.println(" }");
2355 // dynamic vars come from an SESE and src
2356 tempItr = fsen.getDynamicInVarSet().iterator();
2357 while( tempItr.hasNext() ) {
2358 TempDescriptor temp = tempItr.next();
2359 TypeDescriptor type = temp.getType();
2361 // go grab it from the SESE source
2362 output.println(" if( "+paramsprefix+"->"+temp+"_srcSESE != NULL ) {");
2364 // gotta wait until the source is done
2365 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+temp+"_srcSESE;" );
2367 If we are running, everything is done!
2368 output.println(" pthread_mutex_lock( &(com->lock) );");
2369 output.println(" while( com->doneExecuting == FALSE ) {");
2370 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
2371 output.println(" }");
2372 output.println(" pthread_mutex_unlock( &(com->lock) );");
2376 if( type.isNull() ) {
2378 } else if( type.isClass() || type.isArray() ) {
2379 typeStr = "struct "+type.getSafeSymbol()+"*";
2381 typeStr = type.getSafeSymbol();
2384 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2385 " = *(("+typeStr+"*) ("+
2386 paramsprefix+"->"+temp+"_srcSESE + "+
2387 paramsprefix+"->"+temp+"_srcOffset));");
2389 // or if the source was our parent, its in the record to grab
2390 output.println(" } else {");
2391 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2392 " = "+paramsprefix+"->"+temp+";");
2393 output.println(" }");
2396 // Check to see if we need to do a GC if this is a
2397 // multi-threaded program...
2398 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2399 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2400 //Don't bother if we aren't in recursive methods...The loops case will catch it
2401 // if (callgraph.getAllMethods(md).contains(md)) {
2402 // if(this.state.MULTICOREGC) {
2403 // output.println("if(gcflag) gc("+localsprefixaddr+");");
2405 // output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2410 // initialize thread-local var to a non-zero, invalid address
2411 output.println(" seseCaller = (SESEcommon*) 0x2;");
2413 if( state.COREPROF ) {
2414 output.println(" CP_LOGEVENT( CP_EVENTID_TASKEXECUTE, CP_EVENTTYPE_BEGIN );");
2417 HashSet<FlatNode> exitset=new HashSet<FlatNode>();
2418 exitset.add(seseExit);
2419 generateCode(fsen.getNext(0), fm, null, exitset, output, true);
2420 output.println("}\n\n");
2425 // when a new mlp thread is created for an issued SESE, it is started
2426 // by running this method which blocks on a cond variable until
2427 // it is allowed to transition to execute. Then a case statement
2428 // allows it to invoke the method with the proper SESE body, and after
2429 // exiting the SESE method, executes proper SESE exit code before the
2430 // thread can be destroyed
2431 private void generateSESEinvocationMethod(PrintWriter outmethodheader,
2432 PrintWriter outmethod
2435 outmethodheader.println("void* invokeSESEmethod( void* seseRecord );");
2436 outmethod.println( "void* invokeSESEmethod( void* seseRecord ) {");
2437 outmethod.println( " int status;");
2438 outmethod.println( " char errmsg[128];");
2440 // generate a case for each SESE class that can be invoked
2441 outmethod.println( " switch( *((int*)seseRecord) ) {");
2442 outmethod.println( " ");
2443 Iterator<FlatSESEEnterNode> seseit;
2445 seseit=mlpa.getAllSESEs().iterator();
2447 seseit=oooa.getAllSESEs().iterator();
2449 while(seseit.hasNext()){
2450 FlatSESEEnterNode fsen = seseit.next();
2452 outmethod.println( " /* "+fsen.getPrettyIdentifier()+" */");
2453 outmethod.println( " case "+fsen.getIdentifier()+":");
2454 outmethod.println( " "+fsen.getSESEmethodName()+"( seseRecord );");
2456 if( (state.MLP && fsen.equals( mlpa.getMainSESE() )) ||
2457 (state.OOOJAVA && fsen.equals( oooa.getMainSESE() ))
2459 outmethod.println( " /* work scheduler works forever, explicitly exit */");
2460 outmethod.println( " CP_EXIT();");
2461 outmethod.println( " CP_DUMP();");
2462 outmethod.println( " workScheduleExit();");
2463 outmethod.println( " exit( 0 );");
2466 outmethod.println( " break;");
2467 outmethod.println( "");
2470 // default case should never be taken, error out
2471 outmethod.println( " default:");
2472 outmethod.println( " printf(\"Error: unknown SESE class ID in invoke method.\\n\");");
2473 outmethod.println( " exit(-30);");
2474 outmethod.println( " break;");
2475 outmethod.println( " }");
2476 outmethod.println( " return NULL;");
2477 outmethod.println( "}\n\n");
2481 protected void generateCode(FlatNode first,
2484 Set<FlatNode> stopset,
2485 PrintWriter output, boolean firstpass) {
2487 /* Assign labels to FlatNode's if necessary.*/
2489 Hashtable<FlatNode, Integer> nodetolabel;
2491 if (state.DELAYCOMP&&!firstpass)
2492 nodetolabel=dcassignLabels(first, stopset);
2494 nodetolabel=assignLabels(first, stopset);
2496 Set<FlatNode> storeset=null;
2497 HashSet<FlatNode> genset=null;
2498 HashSet<FlatNode> refset=null;
2499 Set<FlatNode> unionset=null;
2501 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
2502 storeset=delaycomp.livecode(lb);
2503 genset=new HashSet<FlatNode>();
2504 if (state.STMARRAY&&!state.DUALVIEW) {
2505 refset=new HashSet<FlatNode>();
2506 refset.addAll(delaycomp.getDeref(lb));
2507 refset.removeAll(delaycomp.getCannotDelay(lb));
2508 refset.removeAll(delaycomp.getOther(lb));
2511 genset.addAll(delaycomp.getCannotDelay(lb));
2512 genset.addAll(delaycomp.getOther(lb));
2514 genset.addAll(delaycomp.getNotReady(lb));
2515 if (state.STMARRAY&&!state.DUALVIEW) {
2516 genset.removeAll(refset);
2519 unionset=new HashSet<FlatNode>();
2520 unionset.addAll(storeset);
2521 unionset.addAll(genset);
2522 if (state.STMARRAY&&!state.DUALVIEW)
2523 unionset.addAll(refset);
2526 /* Do the actual code generation */
2527 FlatNode current_node=null;
2528 HashSet tovisit=new HashSet();
2529 HashSet visited=new HashSet();
2531 tovisit.add(first.getNext(0));
2534 while(current_node!=null||!tovisit.isEmpty()) {
2535 if (current_node==null) {
2536 current_node=(FlatNode)tovisit.iterator().next();
2537 tovisit.remove(current_node);
2538 } else if (tovisit.contains(current_node)) {
2539 tovisit.remove(current_node);
2541 visited.add(current_node);
2542 if (nodetolabel.containsKey(current_node)) {
2543 output.println("L"+nodetolabel.get(current_node)+":");
2545 if (state.INSTRUCTIONFAILURE) {
2546 if (state.THREAD||state.DSM||state.SINGLETM) {
2547 output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
2549 output.println("if ((--instructioncount)==0) injectinstructionfailure();");
2551 if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
2553 if (!state.DELAYCOMP||firstpass) {
2554 generateFlatNode(fm, lb, current_node, output);
2556 //store primitive variables in out set
2557 AtomicRecord ar=atomicmethodmap.get((FlatAtomicEnterNode)first);
2558 Set<TempDescriptor> liveout=ar.liveout;
2559 for(Iterator<TempDescriptor> tmpit=liveout.iterator();tmpit.hasNext();) {
2560 TempDescriptor tmp=tmpit.next();
2561 output.println("primitives->"+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2564 if ((state.MLP || state.OOOJAVA) && stopset!=null) {
2565 assert first.getPrev( 0 ) instanceof FlatSESEEnterNode;
2566 assert current_node instanceof FlatSESEExitNode;
2567 FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev( 0 );
2568 FlatSESEExitNode fsxn = (FlatSESEExitNode) current_node;
2569 assert fsen.getFlatExit().equals( fsxn );
2570 assert fsxn.getFlatEnter().equals( fsen );
2572 if (current_node.kind()!=FKind.FlatReturnNode) {
2573 output.println(" return;");
2576 } else if(current_node.numNext()==1) {
2578 if ((state.MLP|| state.OOOJAVA) &&
2579 current_node.kind()==FKind.FlatSESEEnterNode &&
2580 !((FlatSESEEnterNode)current_node).getIsCallerSESEplaceholder()
2582 FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
2583 generateFlatNode(fm, lb, current_node, output);
2584 nextnode=fsen.getFlatExit().getNext(0);
2585 } else if (state.DELAYCOMP) {
2586 boolean specialprimitive=false;
2587 //skip literals...no need to add extra overhead
2588 if (storeset!=null&&storeset.contains(current_node)&¤t_node.kind()==FKind.FlatLiteralNode) {
2589 TypeDescriptor typedesc=((FlatLiteralNode)current_node).getType();
2590 if (!typedesc.isClass()&&!typedesc.isArray()) {
2591 specialprimitive=true;
2595 if (genset==null||genset.contains(current_node)||specialprimitive)
2596 generateFlatNode(fm, lb, current_node, output);
2597 if (state.STMARRAY&&!state.DUALVIEW&&refset!=null&&refset.contains(current_node)) {
2598 //need to acquire lock
2599 handleArrayDeref(fm, lb, current_node, output, firstpass);
2601 if (storeset!=null&&storeset.contains(current_node)&&!specialprimitive) {
2602 TempDescriptor wrtmp=current_node.writesTemps()[0];
2604 //need to store value written by previous node
2605 if (wrtmp.getType().isPtr()) {
2606 //only lock the objects that may actually need locking
2607 if (recorddc.getNeedTrans(lb, current_node)&&
2608 (!state.STMARRAY||state.DUALVIEW||!wrtmp.getType().isArray()||
2609 wrtmp.getType().getSymbol().equals(TypeUtil.ObjectClass))) {
2610 output.println("STOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2612 output.println("STOREPTRNOLOCK("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2615 output.println("STORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");/* "+current_node.nodeid+" */");
2618 //need to read value read by previous node
2619 if (wrtmp.getType().isPtr()) {
2620 output.println("RESTOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2622 output.println("RESTORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+"); /* "+current_node.nodeid+" */");
2626 nextnode=current_node.getNext(0);
2629 generateFlatNode(fm, lb, current_node, output);
2630 nextnode=current_node.getNext(0);
2632 if (visited.contains(nextnode)) {
2633 output.println("goto L"+nodetolabel.get(nextnode)+";");
2636 current_node=nextnode;
2637 } else if (current_node.numNext()==2) {
2639 if (state.DELAYCOMP) {
2640 boolean computeside=false;
2642 //need to record which way it should go
2643 if (genset==null||genset.contains(current_node)) {
2644 if (storeset!=null&&storeset.contains(current_node)) {
2645 //need to store which way branch goes
2646 generateStoreFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2648 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2650 //which side to execute
2654 if (genset.contains(current_node)) {
2655 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2656 } else if (storeset.contains(current_node)) {
2658 branchanalysis.generateGroupCode(current_node, output, nodetolabel);
2660 //which side to execute
2665 Set<FlatNode> leftset=DelayComputation.getNext(current_node, 0, unionset, lb,locality, true);
2667 if (leftset.size()==0)
2669 if (visited.contains(current_node.getNext(branch))) {
2670 //already visited -- build jump
2671 output.println("goto L"+nodetolabel.get(current_node.getNext(branch))+";");
2674 current_node=current_node.getNext(branch);
2677 if (!visited.contains(current_node.getNext(1)))
2678 tovisit.add(current_node.getNext(1));
2679 if (visited.contains(current_node.getNext(0))) {
2680 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2683 current_node=current_node.getNext(0);
2687 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2688 if (!visited.contains(current_node.getNext(1)))
2689 tovisit.add(current_node.getNext(1));
2690 if (visited.contains(current_node.getNext(0))) {
2691 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2694 current_node=current_node.getNext(0);
2696 } else throw new Error();
2700 protected void handleArrayDeref(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output, boolean firstpass) {
2701 if (fn.kind()==FKind.FlatSetElementNode) {
2702 FlatSetElementNode fsen=(FlatSetElementNode) fn;
2703 String dst=generateTemp(fm, fsen.getDst(), lb);
2704 String src=generateTemp(fm, fsen.getSrc(), lb);
2705 String index=generateTemp(fm, fsen.getIndex(), lb);
2706 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
2708 if (elementtype.isArray()||elementtype.isClass())
2711 type=elementtype.getSafeSymbol()+" ";
2713 output.println("STOREARRAY("+dst+","+index+","+type+")");
2715 output.println("{");
2716 output.println(" struct ArrayObject *array;");
2717 output.println(" int index;");
2718 output.println(" RESTOREARRAY(array,index);");
2719 output.println(" (("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index]="+src+";");
2720 output.println("}");
2722 } else if (fn.kind()==FKind.FlatElementNode) {
2723 FlatElementNode fen=(FlatElementNode) fn;
2724 String src=generateTemp(fm, fen.getSrc(), lb);
2725 String index=generateTemp(fm, fen.getIndex(), lb);
2726 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
2727 String dst=generateTemp(fm, fen.getDst(), lb);
2729 if (elementtype.isArray()||elementtype.isClass())
2732 type=elementtype.getSafeSymbol()+" ";
2734 output.println("STOREARRAY("+src+","+index+","+type+")");
2736 output.println("{");
2737 output.println(" struct ArrayObject *array;");
2738 output.println(" int index;");
2739 output.println(" RESTOREARRAY(array,index);");
2740 output.println(" "+dst+"=(("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index];");
2741 output.println("}");
2745 /** Special label assignment for delaycomputation */
2746 protected Hashtable<FlatNode, Integer> dcassignLabels(FlatNode first, Set<FlatNode> lastset) {
2747 HashSet tovisit=new HashSet();
2748 HashSet visited=new HashSet();
2750 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2752 //Label targets of branches
2753 Set<FlatNode> targets=branchanalysis.getTargets();
2754 for(Iterator<FlatNode> it=targets.iterator();it.hasNext();) {
2755 nodetolabel.put(it.next(), new Integer(labelindex++));
2760 /*Assign labels first. A node needs a label if the previous
2761 * node has two exits or this node is a join point. */
2763 while(!tovisit.isEmpty()) {
2764 FlatNode fn=(FlatNode)tovisit.iterator().next();
2769 if(lastset!=null&&lastset.contains(fn)) {
2770 // if last is not null and matches, don't go
2771 // any further for assigning labels
2775 for(int i=0; i<fn.numNext(); i++) {
2776 FlatNode nn=fn.getNext(i);
2779 //1) Edge >1 of node
2780 nodetolabel.put(nn,new Integer(labelindex++));
2782 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2786 nodetolabel.put(nn,new Integer(labelindex++));
2794 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first) {
2795 return assignLabels(first, null);
2798 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
2799 HashSet tovisit=new HashSet();
2800 HashSet visited=new HashSet();
2802 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2805 /*Assign labels first. A node needs a label if the previous
2806 * node has two exits or this node is a join point. */
2808 while(!tovisit.isEmpty()) {
2809 FlatNode fn=(FlatNode)tovisit.iterator().next();
2814 if(lastset!=null&&lastset.contains(fn)) {
2815 // if last is not null and matches, don't go
2816 // any further for assigning labels
2820 for(int i=0; i<fn.numNext(); i++) {
2821 FlatNode nn=fn.getNext(i);
2824 //1) Edge >1 of node
2825 nodetolabel.put(nn,new Integer(labelindex++));
2827 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2831 nodetolabel.put(nn,new Integer(labelindex++));
2839 /** Generate text string that corresponds to the TempDescriptor td. */
2840 protected String generateTemp(FlatMethod fm, TempDescriptor td, LocalityBinding lb) {
2841 MethodDescriptor md=fm.getMethod();
2842 TaskDescriptor task=fm.getTask();
2843 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
2845 if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
2846 return td.getSafeSymbol();
2849 if (objecttemps.isLocalPtr(td)) {
2850 return localsprefixderef+td.getSafeSymbol();
2853 if (objecttemps.isParamPtr(td)) {
2854 return paramsprefix+"->"+td.getSafeSymbol();
2860 protected void generateFlatNode(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output) {
2862 // insert pre-node actions from the code plan
2863 if( state.MLP|| state.OOOJAVA ) {
2867 cp = mlpa.getCodePlan( fn );
2869 cp = oooa.getCodePlan(fn);
2874 FlatSESEEnterNode currentSESE = cp.getCurrentSESE();
2876 // for each sese and age pair that this parent statement
2877 // must stall on, take that child's stall semaphore, the
2878 // copying of values comes after the statement
2879 Iterator<VariableSourceToken> vstItr = cp.getStallTokens().iterator();
2880 while( vstItr.hasNext() ) {
2881 VariableSourceToken vst = vstItr.next();
2883 SESEandAgePair pair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2885 output.println(" {");
2886 output.println(" SESEcommon* common = (SESEcommon*) "+pair+";");
2887 if( state.COREPROF ) {
2888 //output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_BEGIN );");
2890 output.println(" pthread_mutex_lock( &(common->lock) );");
2891 output.println(" while( common->doneExecuting == FALSE ) {");
2892 output.println(" pthread_cond_wait( &(common->doneCond), &(common->lock) );");
2893 output.println(" }");
2894 output.println(" pthread_mutex_unlock( &(common->lock) );");
2896 // copy things we might have stalled for
2897 output.println(" "+pair.getSESE().getSESErecordName()+"* child = ("+
2898 pair.getSESE().getSESErecordName()+"*) "+pair+";");
2900 Iterator<TempDescriptor> tdItr = cp.getCopySet( vst ).iterator();
2901 while( tdItr.hasNext() ) {
2902 TempDescriptor td = tdItr.next();
2903 FlatMethod fmContext;
2904 if( currentSESE.getIsCallerSESEplaceholder() ) {
2905 fmContext = currentSESE.getfmEnclosing();
2907 fmContext = currentSESE.getfmBogus();
2909 output.println(" "+generateTemp( fmContext, td, null )+
2910 " = child->"+vst.getAddrVar().getSafeSymbol()+";");
2912 if( state.COREPROF ) {
2913 //output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_END );");
2915 output.println(" }");
2918 // for each variable with a dynamic source, stall just for that variable
2919 Iterator<TempDescriptor> dynItr = cp.getDynamicStallSet().iterator();
2920 while( dynItr.hasNext() ) {
2921 TempDescriptor dynVar = dynItr.next();
2923 // only stall if the dynamic source is not yourself, denoted by src==NULL
2924 // otherwise the dynamic write nodes will have the local var up-to-date
2925 output.println(" {");
2926 output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
2927 if( state.COREPROF ) {
2928 //output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_BEGIN );");
2930 output.println(" SESEcommon* common = (SESEcommon*) "+dynVar+"_srcSESE;");
2931 output.println(" psem_take( &(common->stallSem) );");
2933 FlatMethod fmContext;
2934 if( currentSESE.getIsCallerSESEplaceholder() ) {
2935 fmContext = currentSESE.getfmEnclosing();
2937 fmContext = currentSESE.getfmBogus();
2940 TypeDescriptor type=dynVar.getType();
2942 if( type.isNull() ) {
2944 } else if( type.isClass() || type.isArray() ) {
2945 typeStr = "struct "+type.getSafeSymbol()+"*";
2947 typeStr = type.getSafeSymbol();
2950 output.println(" "+generateTemp( fmContext, dynVar, null )+
2951 " = *(("+typeStr+"*) ("+
2952 dynVar+"_srcSESE + "+dynVar+"_srcOffset));");
2953 if( state.COREPROF ) {
2954 //output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_END );");
2956 output.println(" }");
2957 output.println(" }");
2960 // for each assignment of a variable to rhs that has a dynamic source,
2961 // copy the dynamic sources
2962 Iterator dynAssignItr = cp.getDynAssigns().entrySet().iterator();
2963 while( dynAssignItr.hasNext() ) {
2964 Map.Entry me = (Map.Entry) dynAssignItr.next();
2965 TempDescriptor lhs = (TempDescriptor) me.getKey();
2966 TempDescriptor rhs = (TempDescriptor) me.getValue();
2967 output.println(" "+lhs+"_srcSESE = "+rhs+"_srcSESE;");
2968 output.println(" "+lhs+"_srcOffset = "+rhs+"_srcOffset;");
2971 // for each lhs that is dynamic from a non-dynamic source, set the
2972 // dynamic source vars to the current SESE
2973 dynItr = cp.getDynAssignCurr().iterator();
2974 while( dynItr.hasNext() ) {
2975 TempDescriptor dynVar = dynItr.next();
2976 assert currentSESE.getDynamicVarSet().contains( dynVar );
2977 output.println(" "+dynVar+"_srcSESE = NULL;");
2981 // handling stall site
2982 if (state.OOOJAVA) {
2983 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(currentSESE);
2985 Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
2986 Set<Analysis.OoOJava.WaitingElement> waitingElementSet =
2987 graph.getStallSiteWaitingElementSet(fn, seseLockSet);
2989 if(waitingElementSet.size()>0){
2990 output.println("// stall on parent's stall sites ");
2991 output.println(" {");
2992 output.println(" REntry* rentry;");
2994 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
2995 Analysis.OoOJava.WaitingElement waitingElement = (Analysis.OoOJava.WaitingElement) iterator.next();
2997 if(state.RCR && rcr != null){
2998 Analysis.OoOJava.ConflictGraph conflictGraph = graph;
2999 Hashtable<Taint, Set<Effect>> conflicts;
3000 ReachGraph rg = oooa.getDisjointAnalysis().getReachGraph(currentSESE.getmdEnclosing());
3001 if(rcr.cSideDebug) {
3002 rg.writeGraph("RCR_RG_STALLSITE_DEBUG");
3004 if((conflictGraph != null) &&
3005 (conflicts = graph.getConflictEffectSet(fn)) != null &&
3009 Hashtable<Taint, Set<Effect>> effects=oooa.getDisjointAnalysis().getEffectsAnalysis().get(fn);
3010 rcr.traverseStallSite(fn, waitingElement.getTempDesc(), effects, conflicts, rg);
3014 if( waitingElement.getStatus() >= ConflictNode.COARSE ){
3015 output.println(" rentry=mlpCreateREntry("+ waitingElement.getStatus()+ ", seseCaller);");
3017 output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", seseCaller, (void*)&" +generateTemp(fm,waitingElement.getTempDesc(),lb)+ ");");
3019 output.println(" psem_init( &(rentry->parentStallSem) );");
3020 output.println(" rentry->queue=seseCaller->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
3021 output.println(" if(ADDRENTRY(seseCaller->memoryQueueArray["+ waitingElement.getQueueID()
3022 + "],rentry)==NOTREADY){");
3023 if( state.COREPROF ) {
3024 //output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_BEGIN );");
3026 output.println(" psem_take( &(rentry->parentStallSem) );");
3027 if( state.COREPROF ) {
3028 //output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_END );");
3030 output.println(" } ");
3032 if(state.RCR && rcr != null) {
3033 output.println(" "+rcr.getTraverserInvocation(waitingElement.getTempDesc(),
3034 generateTemp(fm, waitingElement.getTempDesc(), null), fn));
3037 output.println(" }");
3041 ParentChildConflictsMap conflictsMap = mlpa.getConflictsResults().get(fn);
3042 if (conflictsMap != null) {
3043 Set<Long> allocSet = conflictsMap.getAllocationSiteIDSetofStallSite();
3044 if (allocSet.size() > 0) {
3045 FlatNode enclosingFlatNode=null;
3046 if( currentSESE.getIsCallerSESEplaceholder() && currentSESE.getParent()==null){
3047 enclosingFlatNode=currentSESE.getfmEnclosing();
3049 enclosingFlatNode=currentSESE;
3051 ConflictGraph graph=mlpa.getConflictGraphResults().get(enclosingFlatNode);
3052 HashSet<SESELock> seseLockSet=mlpa.getConflictGraphLockMap().get(graph);
3053 Set<WaitingElement> waitingElementSet=graph.getStallSiteWaitingElementSet(conflictsMap, seseLockSet);
3055 if(waitingElementSet.size()>0){
3056 output.println("// stall on parent's stall sites ");
3057 output.println(" {");
3058 output.println(" REntry* rentry;");
3060 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
3061 WaitingElement waitingElement = (WaitingElement) iterator.next();
3063 if( waitingElement.getStatus() >= ConflictNode.COARSE ){
3064 // HERE! a parent might conflict with a child
3065 output.println(" rentry=mlpCreateREntry("+ waitingElement.getStatus()+ ", seseCaller);");
3067 output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", seseCaller, (void*)&___locals___."+ waitingElement.getDynID() + ");");
3068 // output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", seseCaller, ___locals___."+ waitingElement.getDynID() + "->oid);");
3070 output.println(" psem_init( &(rentry->parentStallSem) );");
3071 output.println(" rentry->queue=seseCaller->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
3073 .println(" if(ADDRENTRY(seseCaller->memoryQueueArray["+ waitingElement.getQueueID()
3074 + "],rentry)==NOTREADY){");
3075 if( state.COREPROF ) {
3076 //output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_BEGIN );");
3078 output.println(" psem_take( &(rentry->parentStallSem) );");
3079 if( state.COREPROF ) {
3080 //output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_END );");
3082 output.println(" } ");
3084 output.println(" }");
3093 case FKind.FlatAtomicEnterNode:
3094 generateFlatAtomicEnterNode(fm, lb, (FlatAtomicEnterNode) fn, output);
3097 case FKind.FlatAtomicExitNode:
3098 generateFlatAtomicExitNode(fm, lb, (FlatAtomicExitNode) fn, output);
3101 case FKind.FlatInstanceOfNode:
3102 generateFlatInstanceOfNode(fm, lb, (FlatInstanceOfNode)fn, output);
3105 case FKind.FlatSESEEnterNode:
3106 generateFlatSESEEnterNode(fm, lb, (FlatSESEEnterNode)fn, output);
3109 case FKind.FlatSESEExitNode:
3110 generateFlatSESEExitNode(fm, lb, (FlatSESEExitNode)fn, output);
3113 case FKind.FlatWriteDynamicVarNode:
3114 generateFlatWriteDynamicVarNode(fm, lb, (FlatWriteDynamicVarNode)fn, output);
3117 case FKind.FlatGlobalConvNode:
3118 generateFlatGlobalConvNode(fm, lb, (FlatGlobalConvNode) fn, output);
3121 case FKind.FlatTagDeclaration:
3122 generateFlatTagDeclaration(fm, lb, (FlatTagDeclaration) fn,output);
3125 case FKind.FlatCall:
3126 generateFlatCall(fm, lb, (FlatCall) fn,output);
3129 case FKind.FlatFieldNode:
3130 generateFlatFieldNode(fm, lb, (FlatFieldNode) fn,output);
3133 case FKind.FlatElementNode:
3134 generateFlatElementNode(fm, lb, (FlatElementNode) fn,output);
3137 case FKind.FlatSetElementNode:
3138 generateFlatSetElementNode(fm, lb, (FlatSetElementNode) fn,output);
3141 case FKind.FlatSetFieldNode:
3142 generateFlatSetFieldNode(fm, lb, (FlatSetFieldNode) fn,output);
3146 generateFlatNew(fm, lb, (FlatNew) fn,output);
3149 case FKind.FlatOpNode:
3150 generateFlatOpNode(fm, lb, (FlatOpNode) fn,output);
3153 case FKind.FlatCastNode:
3154 generateFlatCastNode(fm, lb, (FlatCastNode) fn,output);
3157 case FKind.FlatLiteralNode:
3158 generateFlatLiteralNode(fm, lb, (FlatLiteralNode) fn,output);
3161 case FKind.FlatReturnNode:
3162 generateFlatReturnNode(fm, lb, (FlatReturnNode) fn,output);
3166 output.println("/* nop */");
3169 case FKind.FlatExit:
3170 output.println("/* exit */");
3173 case FKind.FlatBackEdge:
3174 if (state.SINGLETM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
3175 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
3177 if(state.DSM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
3178 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
3180 if (((state.MLP|| state.OOOJAVA||state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
3181 || (this.state.MULTICOREGC)) {
3182 if(state.DSM&&locality.getAtomic(lb).get(fn).intValue()>0) {
3183 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
3184 } else if(this.state.MULTICOREGC) {
3185 output.println("if (gcflag) gc("+localsprefixaddr+");");
3187 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3190 output.println("/* nop */");
3193 case FKind.FlatCheckNode:
3194 generateFlatCheckNode(fm, lb, (FlatCheckNode) fn, output);
3197 case FKind.FlatFlagActionNode:
3198 generateFlatFlagActionNode(fm, lb, (FlatFlagActionNode) fn, output);
3201 case FKind.FlatPrefetchNode:
3202 generateFlatPrefetchNode(fm,lb, (FlatPrefetchNode) fn, output);
3205 case FKind.FlatOffsetNode:
3206 generateFlatOffsetNode(fm, lb, (FlatOffsetNode)fn, output);
3213 // insert post-node actions from the code-plan
3216 CodePlan cp = mlpa.getCodePlan( fn );
3224 public void generateFlatOffsetNode(FlatMethod fm, LocalityBinding lb, FlatOffsetNode fofn, PrintWriter output) {
3225 output.println("/* FlatOffsetNode */");
3226 FieldDescriptor fd=fofn.getField();
3227 output.println(generateTemp(fm, fofn.getDst(),lb)+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+ fd.getSafeSymbol()+");");
3228 output.println("/* offset */");
3231 public void generateFlatPrefetchNode(FlatMethod fm, LocalityBinding lb, FlatPrefetchNode fpn, PrintWriter output) {
3232 if (state.PREFETCH) {
3233 Vector oids = new Vector();
3234 Vector fieldoffset = new Vector();
3235 Vector endoffset = new Vector();
3236 int tuplecount = 0; //Keeps track of number of prefetch tuples that need to be generated
3237 for(Iterator it = fpn.hspp.iterator(); it.hasNext();) {
3238 PrefetchPair pp = (PrefetchPair) it.next();
3239 Integer statusbase = locality.getNodePreTempInfo(lb,fpn).get(pp.base);
3240 /* Find prefetches that can generate oid */
3241 if(statusbase == LocalityAnalysis.GLOBAL) {
3242 generateTransCode(fm, lb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(lb).get(fpn).intValue()>0, false);
3244 } else if (statusbase == LocalityAnalysis.LOCAL) {
3245 generateTransCode(fm,lb,pp,oids,fieldoffset,endoffset,tuplecount,false,true);
3252 System.out.println("Adding prefetch "+fpn+ " to method:" +fm);
3253 output.println("{");
3254 output.println("/* prefetch */");
3255 output.println("/* prefetchid_" + fpn.siteid + " */");
3256 output.println("void * prefptr;");
3257 output.println("int tmpindex;");
3259 output.println("if((evalPrefetch["+fpn.siteid+"].operMode) || (evalPrefetch["+fpn.siteid+"].retrycount <= 0)) {");
3260 /*Create C code for oid array */
3261 output.print(" unsigned int oidarray_[] = {");
3262 boolean needcomma=false;
3263 for (Iterator it = oids.iterator(); it.hasNext();) {
3266 output.print(it.next());
3269 output.println("};");
3271 /*Create C code for endoffset values */
3272 output.print(" unsigned short endoffsetarry_[] = {");
3274 for (Iterator it = endoffset.iterator(); it.hasNext();) {
3277 output.print(it.next());
3280 output.println("};");
3282 /*Create C code for Field Offset Values */
3283 output.print(" short fieldarry_[] = {");
3285 for (Iterator it = fieldoffset.iterator(); it.hasNext();) {
3288 output.print(it.next());
3291 output.println("};");
3292 /* make the prefetch call to Runtime */
3293 output.println(" if(!evalPrefetch["+fpn.siteid+"].operMode) {");
3294 output.println(" evalPrefetch["+fpn.siteid+"].retrycount = RETRYINTERVAL;");
3295 output.println(" }");
3296 output.println(" prefetch("+fpn.siteid+" ,"+tuplecount+", oidarray_, endoffsetarry_, fieldarry_);");
3297 output.println(" } else {");
3298 output.println(" evalPrefetch["+fpn.siteid+"].retrycount--;");
3299 output.println(" }");
3300 output.println("}");
3304 public void generateTransCode(FlatMethod fm, LocalityBinding lb,PrefetchPair pp, Vector oids, Vector fieldoffset, Vector endoffset, int tuplecount, boolean inside, boolean localbase) {
3305 short offsetcount = 0;
3309 } else if (localbase) {
3310 for(; breakindex<pp.desc.size(); breakindex++) {
3311 Descriptor desc=pp.getDescAt(breakindex);
3312 if (desc instanceof FieldDescriptor) {
3313 FieldDescriptor fd=(FieldDescriptor)desc;
3314 if (fd.isGlobal()) {
3322 if (breakindex>pp.desc.size()) //all local
3325 TypeDescriptor lasttype=pp.base.getType();
3326 String basestr=generateTemp(fm, pp.base, lb);
3328 boolean maybenull=fm.getMethod().isStatic()||
3329 !pp.base.equals(fm.getParameter(0));
3331 for(int i=0; i<breakindex; i++) {
3332 String indexcheck="";
3334 Descriptor desc=pp.getDescAt(i);
3335 if (desc instanceof FieldDescriptor) {
3336 FieldDescriptor fd=(FieldDescriptor)desc;
3338 if (!teststr.equals(""))
3340 teststr+="((prefptr="+basestr+")!=NULL)";
3341 basestr="((struct "+lasttype.getSafeSymbol()+" *)prefptr)->"+fd.getSafeSymbol();
3343 basestr=basestr+"->"+fd.getSafeSymbol();
3346 lasttype=fd.getType();
3348 IndexDescriptor id=(IndexDescriptor)desc;
3349 indexcheck="((tmpindex=";
3350 for(int j=0; j<id.tddesc.size(); j++) {
3351 indexcheck+=generateTemp(fm, id.getTempDescAt(j), lb)+"+";
3353 indexcheck+=id.offset+")>=0)&(tmpindex<((struct ArrayObject *)prefptr)->___length___)";
3355 if (!teststr.equals(""))
3357 teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck;
3358 basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]";
3360 lasttype=lasttype.dereference();
3365 if (teststr.equals("")) {
3366 oid="((unsigned int)"+basestr+")";
3368 oid="((unsigned int)(("+teststr+")?"+basestr+":NULL))";
3372 for(int i = breakindex; i < pp.desc.size(); i++) {
3373 String newfieldoffset;
3374 Object desc = pp.getDescAt(i);
3375 if(desc instanceof FieldDescriptor) {
3376 FieldDescriptor fd=(FieldDescriptor)desc;
3377 newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))");
3378 lasttype=fd.getType();
3380 newfieldoffset = "";
3381 IndexDescriptor id=(IndexDescriptor)desc;
3382 for(int j = 0; j < id.tddesc.size(); j++) {
3383 newfieldoffset += generateTemp(fm, id.getTempDescAt(j), lb) + "+";
3385 newfieldoffset += id.offset.toString();
3386 lasttype=lasttype.dereference();
3388 fieldoffset.add(newfieldoffset);
3391 int base=(tuplecount>0) ? ((Short)endoffset.get(tuplecount-1)).intValue() : 0;
3392 base+=pp.desc.size()-breakindex;
3393 endoffset.add(new Short((short)base));
3398 public void generateFlatGlobalConvNode(FlatMethod fm, LocalityBinding lb, FlatGlobalConvNode fgcn, PrintWriter output) {
3399 if (lb!=fgcn.getLocality())
3401 /* Have to generate flat globalconv */
3402 if (fgcn.getMakePtr()) {
3404 //DEBUG: output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+",\" "+fm+":"+fgcn+"\");");
3405 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3407 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fgcn)||state.READSET&&dc.getNeedWriteTrans(lb, fgcn)) {
3408 //need to do translation
3409 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+", (void *)("+localsprefixaddr+"));");
3410 } else if (state.READSET&&dc.getNeedTrans(lb, fgcn)) {
3411 if (state.HYBRID&&delaycomp.getConv(lb).contains(fgcn)) {
3412 output.println("TRANSREADRDFISSION("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3414 output.println("TRANSREADRD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3418 /* Need to convert to OID */
3419 if ((dc==null)||dc.getNeedSrcTrans(lb,fgcn)) {
3420 if (fgcn.doConvert()||(delaycomp!=null&&delaycomp.needsFission(lb, fgcn.getAtomicEnter())&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) {
3421 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc(),lb)+");");
3423 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=NULL;");
3429 public void generateFlatInstanceOfNode(FlatMethod fm, LocalityBinding lb, FlatInstanceOfNode fion, PrintWriter output) {
3431 if (fion.getType().isArray()) {
3432 type=state.getArrayNumber(fion.getType())+state.numClasses();
3434 type=fion.getType().getClassDesc().getId();
3437 if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
3438 output.println(generateTemp(fm, fion.getDst(), lb)+"=1;");
3440 output.println(generateTemp(fm, fion.getDst(), lb)+"=instanceof("+generateTemp(fm,fion.getSrc(),lb)+","+type+");");
3443 int sandboxcounter=0;
3444 public void generateFlatAtomicEnterNode(FlatMethod fm, LocalityBinding lb, FlatAtomicEnterNode faen, PrintWriter output) {
3445 /* Check to see if we need to generate code for this atomic */
3446 if (locality==null) {
3447 if (GENERATEPRECISEGC) {
3448 output.println("if (pthread_mutex_trylock(&atomiclock)!=0) {");
3449 output.println("stopforgc((struct garbagelist *) &___locals___);");
3450 output.println("pthread_mutex_lock(&atomiclock);");
3451 output.println("restartaftergc();");
3452 output.println("}");
3454 output.println("pthread_mutex_lock(&atomiclock);");
3459 if (locality.getAtomic(lb).get(faen.getPrev(0)).intValue()>0)
3463 if (state.SANDBOX) {
3464 outsandbox.println("int atomiccounter"+sandboxcounter+"=LOW_CHECK_FREQUENCY;");
3465 output.println("counter_reset_pointer=&atomiccounter"+sandboxcounter+";");
3468 if (state.DELAYCOMP&&delaycomp.needsFission(lb, faen)) {
3469 AtomicRecord ar=atomicmethodmap.get(faen);
3471 for(Iterator<TempDescriptor> tmpit=ar.livein.iterator();tmpit.hasNext();) {
3472 TempDescriptor tmp=tmpit.next();
3473 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3476 //copy outs that depend on path
3477 for(Iterator<TempDescriptor> tmpit=ar.liveoutvirtualread.iterator();tmpit.hasNext();) {
3478 TempDescriptor tmp=tmpit.next();
3479 if (!ar.livein.contains(tmp))
3480 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3484 /* Backup the temps. */
3485 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3486 TempDescriptor tmp=tmpit.next();
3487 output.println(generateTemp(fm, backuptable.get(lb).get(tmp),lb)+"="+generateTemp(fm,tmp,lb)+";");
3490 output.println("goto transstart"+faen.getIdentifier()+";");
3492 /******* Print code to retry aborted transaction *******/
3493 output.println("transretry"+faen.getIdentifier()+":");
3496 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3497 TempDescriptor tmp=tmpit.next();
3498 output.println(generateTemp(fm, tmp,lb)+"="+generateTemp(fm,backuptable.get(lb).get(tmp),lb)+";");
3502 /********* Need to revert local object store ********/
3503 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3505 output.println("while ("+revertptr+") {");
3506 output.println("struct ___Object___ * tmpptr;");
3507 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3508 output.println("REVERT_OBJ("+revertptr+");");
3509 output.println(revertptr+"=tmpptr;");
3510 output.println("}");
3512 /******* Tell the runtime to start the transaction *******/
3514 output.println("transstart"+faen.getIdentifier()+":");
3515 if (state.SANDBOX) {
3516 output.println("transaction_check_counter=*counter_reset_pointer;");
3519 output.println("transStart();");
3521 if (state.ABORTREADERS||state.SANDBOX) {
3523 output.println("abortenabled=1;");
3524 output.println("if (_setjmp(aborttrans)) {");
3525 output.println(" goto transretry"+faen.getIdentifier()+"; }");
3529 public void generateFlatAtomicExitNode(FlatMethod fm, LocalityBinding lb, FlatAtomicExitNode faen, PrintWriter output) {
3530 /* Check to see if we need to generate code for this atomic */
3531 if (locality==null) {
3532 output.println("pthread_mutex_unlock(&atomiclock);");
3535 if (locality.getAtomic(lb).get(faen).intValue()>0)
3537 //store the revert list before we lose the transaction object
3540 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3541 output.println(revertptr+"=revertlist;");
3542 output.println("if (transCommit()) {");
3543 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3544 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3545 output.println("} else {");
3546 /* Need to commit local object store */
3547 output.println("while ("+revertptr+") {");
3548 output.println("struct ___Object___ * tmpptr;");
3549 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3550 output.println("COMMIT_OBJ("+revertptr+");");
3551 output.println(revertptr+"=tmpptr;");
3552 output.println("}");
3553 output.println("}");
3557 if (!state.DELAYCOMP) {
3559 output.println("if (transCommit()) {");
3560 /* Transaction aborts if it returns true */
3561 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3562 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3563 output.println("}");
3565 if (delaycomp.optimizeTrans(lb, faen.getAtomicEnter())&&(!state.STMARRAY||state.DUALVIEW)) {
3566 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3567 output.println("LIGHTWEIGHTCOMMIT("+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+", transretry"+faen.getAtomicEnter().getIdentifier()+");");
3569 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3570 TempDescriptor tmp=tmpit.next();
3571 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3573 } else if (delaycomp.needsFission(lb, faen.getAtomicEnter())) {
3574 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3576 output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {");
3577 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3578 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3579 output.println("}");
3581 output.println("else {");
3582 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3583 TempDescriptor tmp=tmpit.next();
3584 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3586 output.println("}");
3588 output.println("if (transCommit(NULL, NULL, NULL, NULL)) {");
3589 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3590 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3591 output.println("}");
3596 public void generateFlatSESEEnterNode( FlatMethod fm,
3598 FlatSESEEnterNode fsen,
3601 // if MLP flag is off, okay that SESE nodes are in IR graph,
3602 // just skip over them and code generates exactly the same
3603 if( !(state.MLP || state.OOOJAVA) ) {
3606 // there may be an SESE in an unreachable method, skip over
3607 if( (state.MLP && !mlpa.getAllSESEs().contains( fsen )) ||
3608 (state.OOOJAVA && !oooa.getAllSESEs().contains(fsen))
3613 // also, if we have encountered a placeholder, just skip it
3614 if( fsen.getIsCallerSESEplaceholder() ) {
3618 output.println(" {");
3620 if( state.COREPROF ) {
3621 output.println("CP_LOGEVENT( CP_EVENTID_TASKDISPATCH, CP_EVENTTYPE_BEGIN );");
3624 // set up the parent
3625 if( (state.MLP && fsen == mlpa.getMainSESE()) ||
3626 (state.OOOJAVA && fsen == oooa.getMainSESE())
3628 output.println(" SESEcommon* parentCommon = NULL;");
3630 if( fsen.getParent() == null ) {
3631 System.out.println( "in "+fm+", "+fsen+" has null parent" );
3633 assert fsen.getParent() != null;
3634 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3635 output.println(" SESEcommon* parentCommon = &("+paramsprefix+"->common);");
3637 //output.println(" SESEcommon* parentCommon = (SESEcommon*) peekItem( seseCallStack );");
3638 output.println(" SESEcommon* parentCommon = seseCaller;");
3642 // before doing anything, lock your own record and increment the running children
3643 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3644 (state.OOOJAVA && fsen != oooa.getMainSESE())
3646 output.println(" atomic_inc(&parentCommon->numRunningChildren);");
3649 // allocate the space for this record
3651 fsen.getSESErecordName()+"* seseToIssue = ("+
3652 fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
3653 fsen.getSESErecordName()+" ) );");
3655 // set up the SESE in-set and out-set objects, which look
3656 // like a garbage list
3657 output.println(" struct garbagelist * gl= (struct garbagelist *)&(((SESEcommon*)(seseToIssue))[1]);");
3658 output.println(" gl->size="+calculateSizeOfSESEParamList(fsen)+";");
3659 output.println(" gl->next = NULL;");
3661 // there are pointers to SESE records the newly-issued SESE
3662 // will use to get values it depends on them for--how many
3663 // are there, and what is the offset from the total SESE
3664 // record to the first dependent record pointer?
3665 output.println(" seseToIssue->common.numDependentSESErecords="+
3666 fsen.getNumDepRecs()+";");
3668 // we only need this (and it will only compile) when the number of dependent
3669 // SESE records is non-zero
3670 if( fsen.getFirstDepRecField() != null ) {
3671 output.println(" seseToIssue->common.offsetToDepSESErecords=(INTPTR)sizeof("+
3672 fsen.getSESErecordName()+") - (INTPTR)&((("+
3673 fsen.getSESErecordName()+"*)0)->"+fsen.getFirstDepRecField()+");"
3678 // and keep the thread-local sese stack up to date (jjenista--this still relevant??)
3679 //output.println(" addNewItem( seseCallStack, (void*) seseToIssue);");
3681 // fill in common data
3682 output.println(" int localCount=0;");
3683 output.println(" seseToIssue->common.classID = "+fsen.getIdentifier()+";");
3684 output.println(" psem_init( &(seseToIssue->common.stallSem) );");
3686 output.println(" seseToIssue->common.forwardList = createQueue();");
3687 output.println(" seseToIssue->common.unresolvedDependencies = 10000;");
3688 output.println(" pthread_cond_init( &(seseToIssue->common.doneCond), NULL );");
3689 output.println(" seseToIssue->common.doneExecuting = FALSE;");
3690 output.println(" pthread_cond_init( &(seseToIssue->common.runningChildrenCond), NULL );");
3691 output.println(" seseToIssue->common.numRunningChildren = 0;");
3692 output.println(" seseToIssue->common.parent = parentCommon;");
3694 // all READY in-vars should be copied now and be done with it
3695 Iterator<TempDescriptor> tempItr = fsen.getReadyInVarSet().iterator();
3696 while( tempItr.hasNext() ) {
3697 TempDescriptor temp = tempItr.next();
3699 // when we are issuing the main SESE or an SESE with placeholder
3700 // caller SESE as parent, generate temp child child's eclosing method,
3701 // otherwise use the parent's enclosing method as the context
3702 boolean useParentContext = false;
3704 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3705 (state.OOOJAVA && fsen != oooa.getMainSESE())
3707 assert fsen.getParent() != null;
3708 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3709 useParentContext = true;
3713 if( useParentContext ) {
3714 output.println(" seseToIssue->"+temp+" = "+
3715 generateTemp( fsen.getParent().getfmBogus(), temp, null )+";");
3717 output.println(" seseToIssue->"+temp+" = "+
3718 generateTemp( fsen.getfmEnclosing(), temp, null )+";");
3722 // before potentially adding this SESE to other forwarding lists,
3723 // create it's lock and take it immediately
3724 output.println(" pthread_mutex_init( &(seseToIssue->common.lock), NULL );");
3725 // output.println(" pthread_mutex_lock( &(seseToIssue->common.lock) );");
3727 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3728 (state.OOOJAVA && fsen != oooa.getMainSESE())
3730 // count up outstanding dependencies, static first, then dynamic
3731 Iterator<SESEandAgePair> staticSrcsItr = fsen.getStaticInVarSrcs().iterator();
3732 while( staticSrcsItr.hasNext() ) {
3733 SESEandAgePair srcPair = staticSrcsItr.next();
3734 output.println(" {");
3735 output.println(" SESEcommon* src = (SESEcommon*)"+srcPair+";");
3737 if(GENERATEPRECISEGC){
3738 output.println(" stopforgc((struct garbagelist *)&___locals___);");
3740 output.println(" pthread_mutex_lock( &(src->lock) );");
3741 if(GENERATEPRECISEGC){
3742 output.println(" restartaftergc();");
3744 output.println(" if( !isEmpty( src->forwardList ) &&");
3745 output.println(" seseToIssue == peekItem( src->forwardList ) ) {");
3746 output.println(" printf( \"This shouldnt already be here\\n\");");
3747 output.println(" exit( -1 );");
3748 output.println(" }");
3749 output.println(" if( !src->doneExecuting ) {");
3750 output.println(" addNewItem( src->forwardList, seseToIssue );");
3751 // output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3752 output.println(" ++(localCount);");
3753 output.println(" }");
3754 output.println(" pthread_mutex_unlock( &(src->lock) );");
3755 output.println(" }");
3757 // whether or not it is an outstanding dependency, make sure
3758 // to pass the static name to the child's record
3759 output.println(" seseToIssue->"+srcPair+" = "+srcPair+";");
3762 // dynamic sources might already be accounted for in the static list,
3763 // so only add them to forwarding lists if they're not already there
3764 Iterator<TempDescriptor> dynVarsItr = fsen.getDynamicInVarSet().iterator();
3765 while( dynVarsItr.hasNext() ) {
3766 TempDescriptor dynInVar = dynVarsItr.next();
3767 output.println(" {");
3768 output.println(" SESEcommon* src = (SESEcommon*)"+dynInVar+"_srcSESE;");
3770 // the dynamic source is NULL if it comes from your own space--you can't pass
3771 // the address off to the new child, because you're not done executing and
3772 // might change the variable, so copy it right now
3773 output.println(" if( src != NULL ) {");
3775 if(GENERATEPRECISEGC){
3776 output.println(" stopforgc((struct garbagelist *)&___locals___);");
3778 output.println(" pthread_mutex_lock( &(src->lock) );");
3779 if(GENERATEPRECISEGC){
3780 output.println(" restartaftergc();");
3782 output.println(" if( isEmpty( src->forwardList ) ||");
3783 output.println(" seseToIssue != peekItem( src->forwardList ) ) {");
3784 output.println(" if( !src->doneExecuting ) {");
3785 output.println(" addNewItem( src->forwardList, seseToIssue );");
3786 // output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3787 output.println(" ++(localCount);");
3788 output.println(" }");
3789 output.println(" }");
3790 output.println(" pthread_mutex_unlock( &(src->lock) );");
3791 output.println(" seseToIssue->"+dynInVar+"_srcOffset = "+dynInVar+"_srcOffset;");
3792 output.println(" } else {");
3794 boolean useParentContext = false;
3795 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3796 (state.OOOJAVA && fsen != oooa.getMainSESE())
3798 assert fsen.getParent() != null;
3799 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3800 useParentContext = true;
3803 if( useParentContext ) {
3804 output.println(" seseToIssue->"+dynInVar+" = "+
3805 generateTemp( fsen.getParent().getfmBogus(), dynInVar, null )+";");
3807 output.println(" seseToIssue->"+dynInVar+" = "+
3808 generateTemp( fsen.getfmEnclosing(), dynInVar, null )+";");
3811 output.println(" }");
3812 output.println(" }");
3814 // even if the value is already copied, make sure your NULL source
3815 // gets passed so child knows it already has the dynamic value
3816 output.println(" seseToIssue->"+dynInVar+"_srcSESE = "+dynInVar+"_srcSESE;");
3819 // maintain pointers for finding dynamic SESE
3820 // instances from static names
3821 SESEandAgePair pair = new SESEandAgePair( fsen, 0 );
3822 if( fsen.getParent() != null &&
3823 //!fsen.getParent().getIsCallerSESEplaceholder() &&
3824 fsen.getParent().getNeededStaticNames().contains( pair )
3827 for( int i = fsen.getOldestAgeToTrack(); i > 0; --i ) {
3828 SESEandAgePair pair1 = new SESEandAgePair( fsen, i );
3829 SESEandAgePair pair2 = new SESEandAgePair( fsen, i-1 );
3830 output.println(" "+pair1+" = "+pair2+";");
3832 output.println(" "+pair+" = seseToIssue;");
3836 // count up memory conflict dependencies,
3840 FlatSESEEnterNode parent = fsen.getParent();
3841 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(parent);
3842 if (graph != null && graph.hasConflictEdge()) {
3843 Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
3845 output.println(" //add memory queue element");
3846 Analysis.OoOJava.SESEWaitingQueue seseWaitingQueue=
3847 graph.getWaitingElementSetBySESEID(fsen.getIdentifier(), seseLockSet);
3848 if(seseWaitingQueue.getWaitingElementSize()>0){
3849 output.println(" {");
3850 output.println(" REntry* rentry=NULL;");
3851 output.println(" INTPTR* pointer=NULL;");
3852 output.println(" seseToIssue->common.rentryIdx=0;");
3854 Set<Integer> queueIDSet=seseWaitingQueue.getQueueIDSet();
3855 for (Iterator iterator = queueIDSet.iterator(); iterator
3857 Integer key = (Integer) iterator.next();
3858 int queueID=key.intValue();
3859 Set<Analysis.OoOJava.WaitingElement> waitingQueueSet =
3860 seseWaitingQueue.getWaitingElementSet(queueID);
3861 int enqueueType=seseWaitingQueue.getType(queueID);
3862 if(enqueueType==SESEWaitingQueue.EXCEPTION){
3863 output.println(" INITIALIZEBUF(parentCommon->memoryQueueArray["
3866 for (Iterator iterator2 = waitingQueueSet.iterator(); iterator2
3868 Analysis.OoOJava.WaitingElement waitingElement
3869 = (Analysis.OoOJava.WaitingElement) iterator2.next();
3870 if (waitingElement.getStatus() >= ConflictNode.COARSE) {
3871 output.println(" rentry=mlpCreateREntry("
3872 + waitingElement.getStatus()
3873 + ", seseToIssue);");
3875 TempDescriptor td = waitingElement
3877 // decide whether waiting element is dynamic or static
3878 if (fsen.getDynamicInVarSet().contains(td)) {
3879 // dynamic in-var case
3880 output.println(" pointer=seseToIssue->"
3881 + waitingElement.getDynID()
3882 + "_srcSESE+seseToIssue->"
3883 + waitingElement.getDynID()
3886 .println(" rentry=mlpCreateFineREntry("
3889 + ", seseToIssue, pointer );");
3890 } else if (fsen.getStaticInVarSet()
3892 // static in-var case
3893 VariableSourceToken vst = fsen
3894 .getStaticInVarSrc(td);
3897 String srcId = "SESE_"
3899 .getPrettyIdentifier()
3900 + vst.getSESE().getIdentifier()
3901 + "_" + vst.getAge();
3903 .println(" pointer=(void*)&seseToIssue->"
3910 .println(" rentry=mlpCreateFineREntry("
3913 + ", seseToIssue, pointer );");
3918 .println(" rentry=mlpCreateFineREntry("
3921 + ", seseToIssue, (void*)&seseToIssue->"
3922 + waitingElement.getDynID()
3927 .println(" rentry->queue=parentCommon->memoryQueueArray["
3928 + waitingElement.getQueueID()
3931 if(enqueueType==SESEWaitingQueue.NORMAL){
3933 .println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
3935 .println(" if(ADDRENTRY(parentCommon->memoryQueueArray["
3936 + waitingElement.getQueueID()
3937 + "],rentry)==NOTREADY){");
3938 output.println(" ++(localCount);");
3939 output.println(" }");
3941 // Trying to execute the dynamic coarse grain conflict strategy...
3942 if(state.RCR && rcr != null) {
3943 boolean useParentContext = false;
3945 if( (state.MLP &&fsen != mlpa.getMainSESE()) ||
3946 (state.OOOJAVA &&fsen != oooa.getMainSESE())) {
3947 assert fsen.getParent() != null;
3948 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3949 useParentContext = true;
3953 for (TempDescriptor invar : fsen.getInVarsForDynamicCoarseConflictResolution()) {
3955 if( useParentContext ) {
3956 varString = generateTemp( fsen.getParent().getfmBogus(), invar, null );
3958 varString = generateTemp( fsen.getfmEnclosing(), invar, null );
3960 output.println(" "+rcr.getTraverserInvocation(invar, varString, fsen));
3965 .println(" ADDRENTRYTOBUF(parentCommon->memoryQueueArray["
3966 + waitingElement.getQueueID()
3970 if(enqueueType!=SESEWaitingQueue.NORMAL){
3971 output.println(" localCount+=RESOLVEBUF(parentCommon->memoryQueueArray["
3972 + queueID+ "],&seseToIssue->common);");
3975 output.println(" }");
3981 ConflictGraph graph = null;
3982 FlatSESEEnterNode parent = fsen.getParent();
3983 if (parent != null) {
3984 if (parent.isCallerSESEplaceholder) {
3985 graph = mlpa.getConflictGraphResults().get(parent.getfmEnclosing());
3987 graph = mlpa.getConflictGraphResults().get(parent);
3990 if (graph != null && graph.hasConflictEdge()) {
3991 HashSet<SESELock> seseLockSet = mlpa.getConflictGraphLockMap()
3994 output.println(" //add memory queue element");
3995 SESEWaitingQueue seseWaitingQueue=graph.getWaitingElementSetBySESEID(fsen.getIdentifier(),
3997 if(seseWaitingQueue.getWaitingElementSize()>0){
3998 output.println(" {");
3999 output.println(" REntry* rentry=NULL;");
4000 output.println(" INTPTR* pointer=NULL;");
4001 output.println(" seseToIssue->common.rentryIdx=0;");
4003 Set<Integer> queueIDSet=seseWaitingQueue.getQueueIDSet();
4004 for (Iterator iterator = queueIDSet.iterator(); iterator
4006 Integer key = (Integer) iterator.next();
4007 int queueID=key.intValue();
4008 Set<WaitingElement> waitingQueueSet = seseWaitingQueue.getWaitingElementSet(queueID);
4009 int enqueueType=seseWaitingQueue.getType(queueID);
4010 if(enqueueType==SESEWaitingQueue.EXCEPTION){
4011 output.println(" INITIALIZEBUF(parentCommon->memoryQueueArray["
4014 for (Iterator iterator2 = waitingQueueSet.iterator(); iterator2
4016 WaitingElement waitingElement = (WaitingElement) iterator2
4018 if (waitingElement.getStatus() >= ConflictNode.COARSE) {
4019 output.println(" rentry=mlpCreateREntry("
4020 + waitingElement.getStatus()
4021 + ", seseToIssue);");
4023 TempDescriptor td = waitingElement
4025 // decide whether waiting element is dynamic or
4027 if (fsen.getDynamicInVarSet().contains(td)) {
4028 // dynamic in-var case
4029 output.println(" pointer=seseToIssue->"
4030 + waitingElement.getDynID()
4031 + "_srcSESE+seseToIssue->"
4032 + waitingElement.getDynID()
4035 .println(" rentry=mlpCreateFineREntry("
4038 + ", seseToIssue, pointer );");
4039 } else if (fsen.getStaticInVarSet()
4041 // static in-var case
4042 VariableSourceToken vst = fsen
4043 .getStaticInVarSrc(td);
4046 String srcId = "SESE_"
4048 .getPrettyIdentifier()
4049 + vst.getSESE().getIdentifier()
4050 + "_" + vst.getAge();
4052 .println(" pointer=(void*)&seseToIssue->"
4059 .println(" rentry=mlpCreateFineREntry("
4062 + ", seseToIssue, pointer );");
4067 .println(" rentry=mlpCreateFineREntry("
4070 + ", seseToIssue, (void*)&seseToIssue->"
4071 + waitingElement.getDynID()
4076 .println(" rentry->queue=parentCommon->memoryQueueArray["
4077 + waitingElement.getQueueID()
4080 if(enqueueType==SESEWaitingQueue.NORMAL){
4082 .println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
4084 .println(" if(ADDRENTRY(parentCommon->memoryQueueArray["
4085 + waitingElement.getQueueID()
4086 + "],rentry)==NOTREADY){");
4087 output.println(" ++(localCount);");
4088 output.println(" } ");
4091 .println(" ADDRENTRYTOBUF(parentCommon->memoryQueueArray["
4092 + waitingElement.getQueueID()
4096 if(enqueueType!=SESEWaitingQueue.NORMAL){
4097 output.println(" localCount+=RESOLVEBUF(parentCommon->memoryQueueArray["
4098 + queueID+ "],&seseToIssue->common);");
4101 output.println(" }");
4109 // release this SESE for siblings to update its dependencies or,
4110 // eventually, for it to mark itself finished
4111 // output.println(" pthread_mutex_unlock( &(seseToIssue->common.lock) );");
4113 // if there were no outstanding dependencies, issue here
4114 output.println(" if( atomic_sub_and_test(10000-localCount,&(seseToIssue->common.unresolvedDependencies) ) ) {");
4115 output.println(" workScheduleSubmit( (void*)seseToIssue );");
4116 output.println(" }");
4118 output.println(" if( seseToIssue->common.unresolvedDependencies == 0 ) {");
4119 output.println(" workScheduleSubmit( (void*)seseToIssue );");
4120 output.println(" }");
4122 // release this SESE for siblings to update its dependencies or,
4123 // eventually, for it to mark itself finished
4124 // output.println(" pthread_mutex_unlock( &(seseToIssue->common.lock) );");
4126 if( state.COREPROF ) {
4127 output.println("CP_LOGEVENT( CP_EVENTID_TASKDISPATCH, CP_EVENTTYPE_END );");
4130 output.println(" }");
4134 public void generateFlatSESEExitNode( FlatMethod fm,
4136 FlatSESEExitNode fsexn,
4140 // if MLP flag is off, okay that SESE nodes are in IR graph,
4141 // just skip over them and code generates exactly the same
4142 if( ! (state.MLP || state.OOOJAVA) ) {
4146 // get the enter node for this exit that has meta data embedded
4147 FlatSESEEnterNode fsen = fsexn.getFlatEnter();
4149 // there may be an SESE in an unreachable method, skip over
4150 if( (state.MLP && !mlpa.getAllSESEs().contains( fsen )) ||
4151 (state.OOOJAVA && !oooa.getAllSESEs().contains( fsen ))
4156 // also, if we have encountered a placeholder, just jump it
4157 if( fsen.getIsCallerSESEplaceholder() ) {
4161 if( state.COREPROF ) {
4162 output.println(" CP_LOGEVENT( CP_EVENTID_TASKEXECUTE, CP_EVENTTYPE_END );");
4165 output.println(" /* SESE exiting */");
4167 if( state.COREPROF ) {
4168 output.println(" CP_LOGEVENT( CP_EVENTID_TASKRETIRE, CP_EVENTTYPE_BEGIN );");
4171 String com = paramsprefix+"->common";
4173 // this SESE cannot be done until all of its children are done
4174 // so grab your own lock with the condition variable for watching
4175 // that the number of your running children is greater than zero
4176 if (GENERATEPRECISEGC){
4177 output.println(" stopforgc((struct garbagelist *)&___locals___);");
4179 output.println(" pthread_mutex_lock( &("+com+".lock) );");
4180 if (GENERATEPRECISEGC){
4181 output.println(" restartaftergc();");
4183 output.println(" while( "+com+".numRunningChildren > 0 ) {");
4184 if (GENERATEPRECISEGC){
4185 // output.println(" stopforgc((struct garbagelist *)&(((SESEcommon*)(___params___))[1]));");
4186 output.println(" stopforgc((struct garbagelist *)&___locals___);");
4188 output.println(" pthread_cond_wait( &("+com+".runningChildrenCond), &("+com+".lock) );");
4189 if (GENERATEPRECISEGC){
4190 output.println(" restartaftergc();");
4192 output.println(" }");
4195 // copy out-set from local temps into the sese record
4196 Iterator<TempDescriptor> itr = fsen.getOutVarSet().iterator();
4197 while( itr.hasNext() ) {
4198 TempDescriptor temp = itr.next();
4200 // only have to do this for primitives non-arrays
4202 temp.getType().isPrimitive() && !temp.getType().isArray()
4208 // have to determine the context enclosing this sese
4209 boolean useParentContext = false;
4211 if( (state.MLP &&fsen != mlpa.getMainSESE()) ||
4212 (state.OOOJAVA &&fsen != oooa.getMainSESE())
4214 assert fsen.getParent() != null;
4215 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
4216 useParentContext = true;
4221 if( useParentContext ) {
4222 from = generateTemp( fsen.getParent().getfmBogus(), temp, null );
4224 from = generateTemp( fsen.getfmEnclosing(), temp, null );
4227 output.println(" "+paramsprefix+
4228 "->"+temp.getSafeSymbol()+
4232 // mark yourself done, your SESE data is now read-only
4233 output.println(" "+com+".doneExecuting = TRUE;");
4234 output.println(" pthread_cond_signal( &("+com+".doneCond) );");
4235 output.println(" pthread_mutex_unlock( &("+com+".lock) );");
4237 // decrement dependency count for all SESE's on your forwarding list
4238 output.println(" while( !isEmpty( "+com+".forwardList ) ) {");
4239 output.println(" SESEcommon* consumer = (SESEcommon*) getItem( "+com+".forwardList );");
4242 output.println(" if(consumer->rentryIdx>0){");
4243 output.println(" // resolved null pointer");
4244 output.println(" int idx;");
4245 output.println(" for(idx=0;idx<consumer->rentryIdx;idx++){");
4246 output.println(" resolvePointer(consumer->rentryArray[idx]);");
4247 output.println(" }");
4248 output.println(" }");
4251 // output.println(" pthread_mutex_lock( &(consumer->lock) );");
4252 // output.println(" --(consumer->unresolvedDependencies);");
4253 // output.println(" if( consumer->unresolvedDependencies == 0 ) {");
4254 output.println(" if( atomic_sub_and_test(1, &(consumer->unresolvedDependencies)) ){");
4255 output.println(" workScheduleSubmit( (void*)consumer );");
4256 output.println(" }");
4257 // output.println(" pthread_mutex_unlock( &(consumer->lock) );");
4258 output.println(" }");
4262 // clean up its lock element from waiting queue, and decrement dependency count for next SESE block
4263 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
4264 (state.OOOJAVA && fsen != oooa.getMainSESE())
4268 output.println(" /* check memory dependency*/");
4269 output.println(" {");
4270 output.println(" int idx;");
4271 output.println(" for(idx=0;idx<___params___->common.rentryIdx;idx++){");
4272 output.println(" REntry* re=___params___->common.rentryArray[idx];");
4273 output.println(" RETIRERENTRY(re->queue,re);");
4274 output.println(" }");
4275 output.println(" }");
4279 // if parent is stalling on you, let them know you're done
4280 if( (state.MLP && fsexn.getFlatEnter() != mlpa.getMainSESE()) ||
4281 (state.OOOJAVA && fsexn.getFlatEnter() != oooa.getMainSESE())
4283 output.println(" psem_give( &("+paramsprefix+"->common.stallSem) );");
4286 // last of all, decrement your parent's number of running children
4287 output.println(" if( "+paramsprefix+"->common.parent != NULL ) {");
4288 output.println(" if (atomic_sub_and_test(1, &"+paramsprefix+"->common.parent->numRunningChildren)) {");
4289 if (GENERATEPRECISEGC){
4290 output.println(" stopforgc((struct garbagelist *)&___locals___);");
4292 output.println(" pthread_mutex_lock( &("+paramsprefix+"->common.parent->lock) );");
4293 if (GENERATEPRECISEGC){
4294 output.println(" restartaftergc();");
4296 output.println(" pthread_cond_signal( &("+paramsprefix+"->common.parent->runningChildrenCond) );");
4297 output.println(" pthread_mutex_unlock( &("+paramsprefix+"->common.parent->lock) );");
4298 output.println(" }");
4299 output.println(" }");
4301 // this is a thread-only variable that can be handled when critical sese-to-sese
4302 // data has been taken care of--set sese pointer to remember self over method
4303 // calls to a non-zero, invalid address
4304 output.println(" seseCaller = (SESEcommon*) 0x1;");
4306 if( state.COREPROF ) {
4307 output.println(" CP_LOGEVENT( CP_EVENTID_TASKRETIRE, CP_EVENTTYPE_END );");
4311 public void generateFlatWriteDynamicVarNode( FlatMethod fm,
4313 FlatWriteDynamicVarNode fwdvn,
4316 if( !(state.MLP || state.OOOJAVA) ) {
4317 // should node should not be in an IR graph if the
4318 // MLP flag is not set
4319 throw new Error("Unexpected presence of FlatWriteDynamicVarNode");
4322 Hashtable<TempDescriptor, VSTWrapper> writeDynamic = fwdvn.getVar2src();
4324 assert writeDynamic != null;
4326 Iterator wdItr = writeDynamic.entrySet().iterator();
4327 while( wdItr.hasNext() ) {
4328 Map.Entry me = (Map.Entry) wdItr.next();
4329 TempDescriptor refVar = (TempDescriptor) me.getKey();
4330 VSTWrapper vstW = (VSTWrapper) me.getValue();
4331 VariableSourceToken vst = vstW.vst;
4334 // only do this if the variable in question should be tracked,
4335 // meaning that it was explicitly added to the dynamic var set
4336 if( !current.getDynamicVarSet().contains( vst.getAddrVar() ) ) {
4342 // if there is no given source, this variable is ready so
4343 // mark src pointer NULL to signify that the var is up-to-date
4344 output.println(" "+refVar+"_srcSESE = NULL;");
4348 // otherwise we track where it will come from
4349 SESEandAgePair instance = new SESEandAgePair( vst.getSESE(), vst.getAge() );
4350 output.println(" "+refVar+"_srcSESE = "+instance+";");
4351 output.println(" "+refVar+"_srcOffset = (INTPTR) &((("+
4352 vst.getSESE().getSESErecordName()+"*)0)->"+vst.getAddrVar()+");");
4357 private void generateFlatCheckNode(FlatMethod fm, LocalityBinding lb, FlatCheckNode fcn, PrintWriter output) {
4358 if (state.CONSCHECK) {
4359 String specname=fcn.getSpec();
4360 String varname="repairstate___";
4361 output.println("{");
4362 output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
4364 TempDescriptor[] temps=fcn.getTemps();
4365 String[] vars=fcn.getVars();
4366 for(int i=0; i<temps.length; i++) {
4367 output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i],lb)+";");
4370 output.println("if (doanalysis"+specname+"("+varname+")) {");
4371 output.println("free"+specname+"_state("+varname+");");
4372 output.println("} else {");
4373 output.println("/* Bad invariant */");
4374 output.println("free"+specname+"_state("+varname+");");
4375 output.println("abort_task();");
4376 output.println("}");
4377 output.println("}");
4381 private void generateFlatCall(FlatMethod fm, LocalityBinding lb, FlatCall fc, PrintWriter output) {
4383 if( (state.MLP && !nonSESEpass) ||
4384 (state.OOOJAVA && !nonSESEpass)
4386 output.println(" seseCaller = (SESEcommon*)"+paramsprefix+";");
4389 MethodDescriptor md=fc.getMethod();
4390 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? locality.getBinding(lb, fc) : md);
4391 ClassDescriptor cn=md.getClassDesc();
4392 output.println("{");
4393 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4395 LocalityBinding fclb=locality.getBinding(lb, fc);
4396 output.print(" struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
4398 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
4399 output.print(objectparams.numPointers());
4400 output.print(", "+localsprefixaddr);
4401 if (md.getThis()!=null) {
4403 output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis(),lb));
4405 if (fc.getThis()!=null&&md.getThis()==null) {
4406 System.out.println("WARNING!!!!!!!!!!!!");
4407 System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
4411 for(int i=0; i<fc.numArgs(); i++) {
4412 Descriptor var=md.getParameter(i);
4413 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
4414 if (objectparams.isParamPtr(paramtemp)) {
4415 TempDescriptor targ=fc.getArg(i);
4417 TypeDescriptor td=md.getParamType(i);
4419 output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
4421 output.print("(struct "+md.getParamType(i).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
4424 output.println("};");
4429 if (fc.getReturnTemp()!=null)
4430 output.print(generateTemp(fm,fc.getReturnTemp(),lb)+"=");
4432 /* Do we need to do virtual dispatch? */
4433 if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
4436 LocalityBinding fclb=locality.getBinding(lb, fc);
4437 output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
4439 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
4444 if (md.getReturnType().isClass()||md.getReturnType().isArray())
4445 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
4447 output.print(md.getReturnType().getSafeSymbol()+" ");
4448 output.print("(*)(");
4450 boolean printcomma=false;
4451 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4453 LocalityBinding fclb=locality.getBinding(lb, fc);
4454 output.print("struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
4456 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
4460 for(int i=0; i<objectparams.numPrimitives(); i++) {
4461 TempDescriptor temp=objectparams.getPrimitive(i);
4465 if (temp.getType().isClass()||temp.getType().isArray())
4466 output.print("struct " + temp.getType().getSafeSymbol()+" * ");
4468 output.print(temp.getType().getSafeSymbol());
4473 LocalityBinding fclb=locality.getBinding(lb, fc);
4474 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])");
4476 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
4480 boolean needcomma=false;
4481 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4482 output.print("&__parameterlist__");
4486 if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
4487 if (fc.getThis()!=null) {
4488 TypeDescriptor ptd=md.getThis().getType();
4491 if (ptd.isClass()&&!ptd.isArray())
4492 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
4493 output.print(generateTemp(fm,fc.getThis(),lb));
4498 for(int i=0; i<fc.numArgs(); i++) {
4499 Descriptor var=md.getParameter(i);
4500 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
4501 if (objectparams.isParamPrim(paramtemp)) {
4502 TempDescriptor targ=fc.getArg(i);
4506 TypeDescriptor ptd=md.getParamType(i);
4507 if (ptd.isClass()&&!ptd.isArray())
4508 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
4509 output.print(generateTemp(fm, targ,lb));
4513 output.println(");");
4514 output.println(" }");
4517 private boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
4518 Set subclasses=typeutil.getSubClasses(thiscd);
4519 if (subclasses==null)
4521 for(Iterator classit=subclasses.iterator(); classit.hasNext();) {
4522 ClassDescriptor cd=(ClassDescriptor)classit.next();
4523 Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol());
4524 for(Iterator matchit=possiblematches.iterator(); matchit.hasNext();) {
4525 MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
4526 if (md.matches(matchmd))
4533 private void generateFlatFieldNode(FlatMethod fm, LocalityBinding lb, FlatFieldNode ffn, PrintWriter output) {
4534 if (state.SINGLETM) {
4535 //single machine transactional memory case
4536 String field=ffn.getField().getSafeSymbol();
4537 String src=generateTemp(fm, ffn.getSrc(),lb);
4538 String dst=generateTemp(fm, ffn.getDst(),lb);
4540 output.println(dst+"="+ src +"->"+field+ ";");
4541 if (ffn.getField().getType().isPtr()&&locality.getAtomic(lb).get(ffn).intValue()>0&&
4542 locality.getNodePreTempInfo(lb, ffn).get(ffn.getSrc())!=LocalityAnalysis.SCRATCH) {
4543 if ((dc==null)||(!state.READSET&&dc.getNeedTrans(lb, ffn))||
4544 (state.READSET&&dc.getNeedWriteTrans(lb, ffn))) {
4545 output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));");
4546 } else if (state.READSET&&dc.getNeedTrans(lb, ffn)) {
4547 if (state.HYBRID&&delaycomp.getConv(lb).contains(ffn)) {
4548 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4550 output.println("TRANSREADRD("+dst+", "+dst+");");
4553 } else if (state.DSM) {
4554 Integer status=locality.getNodePreTempInfo(lb,ffn).get(ffn.getSrc());
4555 if (status==LocalityAnalysis.GLOBAL) {
4556 String field=ffn.getField().getSafeSymbol();
4557 String src=generateTemp(fm, ffn.getSrc(),lb);
4558 String dst=generateTemp(fm, ffn.getDst(),lb);
4560 if (ffn.getField().getType().isPtr()) {
4562 //TODO: Uncomment this when we have runtime support
4563 //if (ffn.getSrc()==ffn.getDst()) {
4564 //output.println("{");
4565 //output.println("void * temp="+src+";");
4566 //output.println("if (temp&0x1) {");
4567 //output.println("temp=(void *) transRead(trans, (unsigned int) temp);");
4568 //output.println(src+"->"+field+"="+temp+";");
4569 //output.println("}");
4570 //output.println(dst+"=temp;");
4571 //output.println("}");
4573 output.println(dst+"="+ src +"->"+field+ ";");
4574 //output.println("if ("+dst+"&0x1) {");
4575 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
4576 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
4577 //output.println(src+"->"+field+"="+src+"->"+field+";");
4578 //output.println("}");
4581 output.println(dst+"="+ src+"->"+field+";");
4583 } else if (status==LocalityAnalysis.LOCAL) {
4584 if (ffn.getField().getType().isPtr()&&
4585 ffn.getField().isGlobal()) {
4586 String field=ffn.getField().getSafeSymbol();
4587 String src=generateTemp(fm, ffn.getSrc(),lb);
4588 String dst=generateTemp(fm, ffn.getDst(),lb);
4589 output.println(dst+"="+ src +"->"+field+ ";");
4590 if (locality.getAtomic(lb).get(ffn).intValue()>0)
4591 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
4592 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
4594 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4595 } else if (status==LocalityAnalysis.EITHER) {
4596 //Code is reading from a null pointer
4597 output.println("if ("+generateTemp(fm, ffn.getSrc(),lb)+") {");
4598 output.println("#ifndef RAW");
4599 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4600 output.println("#endif");
4601 //This should throw a suitable null pointer error
4602 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4604 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4606 // DEBUG if(!ffn.getDst().getType().isPrimitive()){
4607 // DEBUG output.println("within((void*)"+generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+");");
4609 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4614 private void generateFlatSetFieldNode(FlatMethod fm, LocalityBinding lb, FlatSetFieldNode fsfn, PrintWriter output) {
4615 if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
4616 throw new Error("Can't set array length");
4617 if (state.SINGLETM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
4618 //Single Machine Transaction Case
4619 boolean srcptr=fsfn.getSrc().getType().isPtr();
4620 String src=generateTemp(fm,fsfn.getSrc(),lb);
4621 String dst=generateTemp(fm,fsfn.getDst(),lb);
4622 output.println("//"+srcptr+" "+fsfn.getSrc().getType().isNull());
4623 if (srcptr&&!fsfn.getSrc().getType().isNull()) {
4624 output.println("{");
4625 if ((dc==null)||dc.getNeedSrcTrans(lb, fsfn)&&
4626 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) {
4627 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4629 output.println("INTPTR srcoid=(INTPTR)"+src+";");
4632 if (wb.needBarrier(fsfn)&&
4633 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getDst())!=LocalityAnalysis.SCRATCH) {
4634 if (state.EVENTMONITOR) {
4635 output.println("if ("+dst+"->___objstatus___&DIRTY) EVLOGEVENTOBJ(EV_WRITE,"+dst+"->objuid)");
4637 output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;");
4639 if (srcptr&!fsfn.getSrc().getType().isNull()) {
4640 output.println("*((unsigned INTPTR *)&("+dst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4641 output.println("}");
4643 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4645 } else if (state.DSM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
4646 Integer statussrc=locality.getNodePreTempInfo(lb,fsfn).get(fsfn.getSrc());
4647 Integer statusdst=locality.getNodeTempInfo(lb).get(fsfn).get(fsfn.getDst());
4648 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4650 String src=generateTemp(fm,fsfn.getSrc(),lb);
4651 String dst=generateTemp(fm,fsfn.getDst(),lb);
4653 output.println("{");
4654 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4656 if (statusdst.equals(LocalityAnalysis.GLOBAL)) {
4659 if (wb.needBarrier(fsfn))
4660 output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;");
4662 output.println("*((unsigned INTPTR *)&("+glbdst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4664 output.println(glbdst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4665 } else if (statusdst.equals(LocalityAnalysis.LOCAL)) {
4666 /** Check if we need to copy */
4667 output.println("if(!"+dst+"->"+localcopystr+") {");
4668 /* Link object into list */
4669 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4670 output.println(revertptr+"=revertlist;");
4671 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4672 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4674 output.println("COPY_OBJ("+dst+");");
4675 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4676 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4677 output.println("}");
4679 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4681 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4682 } else if (statusdst.equals(LocalityAnalysis.EITHER)) {
4683 //writing to a null...bad
4684 output.println("if ("+dst+") {");
4685 output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}");
4687 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4689 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4692 output.println("}");
4695 if (state.FASTCHECK) {
4696 String dst=generateTemp(fm, fsfn.getDst(),lb);
4697 output.println("if(!"+dst+"->"+localcopystr+") {");
4698 /* Link object into list */
4699 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4700 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4702 output.println("COPY_OBJ("+dst+");");
4703 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4704 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4705 output.println("}");
4708 // DEBUG if(!fsfn.getField().getType().isPrimitive()){
4709 // DEBUG output.println("within((void*)"+generateTemp(fm,fsfn.getSrc(),lb)+");");
4711 output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
4715 private void generateFlatElementNode(FlatMethod fm, LocalityBinding lb, FlatElementNode fen, PrintWriter output) {
4716 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
4719 if (elementtype.isArray()||elementtype.isClass())
4722 type=elementtype.getSafeSymbol()+" ";
4724 if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
4725 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fen.getIndex(),lb)+") >= "+generateTemp(fm,fen.getSrc(),lb) + "->___length___))");
4726 output.println("failedboundschk();");
4728 if (state.SINGLETM) {
4729 //Single machine transaction case
4730 String dst=generateTemp(fm, fen.getDst(),lb);
4731 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))) {
4732 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4734 output.println("STMGETARRAY("+dst+", "+ generateTemp(fm,fen.getSrc(),lb)+", "+generateTemp(fm, fen.getIndex(),lb)+", "+type+");");
4737 if (elementtype.isPtr()&&locality.getAtomic(lb).get(fen).intValue()>0&&
4738 locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())!=LocalityAnalysis.SCRATCH) {
4739 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fen)||state.READSET&&dc.getNeedWriteTrans(lb, fen)) {
4740 output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));");
4741 } else if (state.READSET&&dc.getNeedTrans(lb, fen)) {
4742 if (state.HYBRID&&delaycomp.getConv(lb).contains(fen)) {
4743 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4745 output.println("TRANSREADRD("+dst+", "+dst+");");
4748 } else if (state.DSM) {
4749 Integer status=locality.getNodePreTempInfo(lb,fen).get(fen.getSrc());
4750 if (status==LocalityAnalysis.GLOBAL) {
4751 String dst=generateTemp(fm, fen.getDst(),lb);
4752 if (elementtype.isPtr()) {
4753 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4754 //DEBUG: output.println("TRANSREAD("+dst+", "+dst+",\""+fm+":"+fen+"\");");
4755 output.println("TRANSREAD("+dst+", "+dst+");");
4757 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4759 } else if (status==LocalityAnalysis.LOCAL) {
4760 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4761 } else if (status==LocalityAnalysis.EITHER) {
4762 //Code is reading from a null pointer
4763 output.println("if ("+generateTemp(fm, fen.getSrc(),lb)+") {");
4764 output.println("#ifndef RAW");
4765 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4766 output.println("#endif");
4767 //This should throw a suitable null pointer error
4768 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4770 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4772 // DEBUG output.println("within((void*)"+generateTemp(fm,fen.getSrc(),lb)+");");
4773 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4777 private void generateFlatSetElementNode(FlatMethod fm, LocalityBinding lb, FlatSetElementNode fsen, PrintWriter output) {
4778 //TODO: need dynamic check to make sure this assignment is actually legal
4779 //Because Object[] could actually be something more specific...ie. Integer[]
4781 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
4784 if (elementtype.isArray()||elementtype.isClass())
4787 type=elementtype.getSafeSymbol()+" ";
4789 if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
4790 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fsen.getIndex(),lb)+") >= "+generateTemp(fm,fsen.getDst(),lb) + "->___length___))");
4791 output.println("failedboundschk();");
4794 if (state.SINGLETM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4795 //Transaction set element case
4796 if (wb.needBarrier(fsen)&&
4797 locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH) {
4798 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___objstatus___))|=DIRTY;");
4800 if (fsen.getSrc().getType().isPtr()&&!fsen.getSrc().getType().isNull()) {
4801 output.println("{");
4802 String src=generateTemp(fm, fsen.getSrc(), lb);
4803 if ((dc==null)||dc.getNeedSrcTrans(lb, fsen)&&
4804 locality.getNodePreTempInfo(lb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) {
4805 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4807 output.println("INTPTR srcoid=(INTPTR)"+src+";");
4809 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
4810 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", srcoid, INTPTR);");
4812 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
4814 output.println("}");
4816 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
4817 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", "+ generateTemp(fm, fsen.getSrc(), lb) +", "+type+");");
4819 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4822 } else if (state.DSM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4823 Integer statussrc=locality.getNodePreTempInfo(lb,fsen).get(fsen.getSrc());
4824 Integer statusdst=locality.getNodePreTempInfo(lb,fsen).get(fsen.getDst());
4825 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4826 boolean dstglobal=statusdst==LocalityAnalysis.GLOBAL;
4827 boolean dstlocal=(statusdst==LocalityAnalysis.LOCAL)||(statusdst==LocalityAnalysis.EITHER);
4830 if (wb.needBarrier(fsen))
4831 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___localcopy___))|=DIRTY;");
4832 } else if (dstlocal) {
4833 /** Check if we need to copy */
4834 String dst=generateTemp(fm, fsen.getDst(),lb);
4835 output.println("if(!"+dst+"->"+localcopystr+") {");
4836 /* Link object into list */
4837 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4838 output.println(revertptr+"=revertlist;");
4839 if ((GENERATEPRECISEGC) || this.state.MULTICOREGC)
4840 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4842 output.println("COPY_OBJ("+dst+");");
4843 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4844 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4845 output.println("}");
4847 System.out.println("Node: "+fsen);
4848 System.out.println(lb);
4849 System.out.println("statusdst="+statusdst);
4850 System.out.println(fm.printMethod());
4851 throw new Error("Unknown array type");
4854 output.println("{");
4855 String src=generateTemp(fm, fsen.getSrc(), lb);
4856 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4857 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
4858 output.println("}");
4860 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4863 if (state.FASTCHECK) {
4864 String dst=generateTemp(fm, fsen.getDst(),lb);
4865 output.println("if(!"+dst+"->"+localcopystr+") {");
4866 /* Link object into list */
4867 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4868 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4870 output.println("COPY_OBJ("+dst+");");
4871 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4872 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4873 output.println("}");
4875 // DEBUG output.println("within((void*)"+generateTemp(fm,fsen.getDst(),lb)+");");
4876 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4880 protected void generateFlatNew(FlatMethod fm, LocalityBinding lb, FlatNew fn, PrintWriter output) {
4881 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
4882 //Stash pointer in case of GC
4883 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4884 output.println(revertptr+"=revertlist;");
4886 if (state.SINGLETM) {
4887 if (fn.getType().isArray()) {
4888 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4889 if (locality.getAtomic(lb).get(fn).intValue()>0) {
4890 //inside transaction
4891 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4893 //outside transaction
4894 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4897 if (locality.getAtomic(lb).get(fn).intValue()>0) {
4898 //inside transaction
4899 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4901 //outside transaction
4902 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4905 } else if (fn.getType().isArray()) {
4906 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4907 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4908 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4909 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4910 if(this.state.MLP || state.OOOJAVA){
4911 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray_mlp("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+", oid, "+oooa.getDisjointAnalysis().getAllocationSiteFromFlatNew(fn).getUniqueAllocSiteID()+");");
4912 output.println(" oid += numWorkers;");
4914 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4917 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4920 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4921 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");");
4922 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4923 if (this.state.MLP || state.OOOJAVA){
4924 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new_mlp("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+", oid, "+oooa.getDisjointAnalysis().getAllocationSiteFromFlatNew(fn).getUniqueAllocSiteID()+");");
4925 output.println(" oid += numWorkers;");
4927 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4930 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
4933 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
4934 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4935 String dst=generateTemp(fm,fn.getDst(),lb);
4936 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
4937 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4938 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4940 if (state.FASTCHECK) {
4941 String dst=generateTemp(fm,fn.getDst(),lb);
4942 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
4943 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4944 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4948 private void generateFlatTagDeclaration(FlatMethod fm, LocalityBinding lb, FlatTagDeclaration fn, PrintWriter output) {
4949 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4950 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
4952 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+state.getTagId(fn.getType())+");");
4956 private void generateFlatOpNode(FlatMethod fm, LocalityBinding lb, FlatOpNode fon, PrintWriter output) {
4957 if (fon.getRight()!=null) {
4958 if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
4959 if (fon.getLeft().getType().isLong())
4960 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
4962 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned int)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
4964 } else if (dc!=null) {
4965 output.print(generateTemp(fm, fon.getDest(),lb)+" = (");
4966 if (fon.getLeft().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
4967 output.print("(void *)");
4968 if (dc.getNeedLeftSrcTrans(lb, fon))
4969 output.print("("+generateTemp(fm, fon.getLeft(),lb)+"!=NULL?"+generateTemp(fm, fon.getLeft(),lb)+"->"+oidstr+":NULL)");
4971 output.print(generateTemp(fm, fon.getLeft(),lb));
4972 output.print(")"+fon.getOp().toString()+"(");
4973 if (fon.getRight().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
4974 output.print("(void *)");
4975 if (dc.getNeedRightSrcTrans(lb, fon))
4976 output.println("("+generateTemp(fm, fon.getRight(),lb)+"!=NULL?"+generateTemp(fm, fon.getRight(),lb)+"->"+oidstr+":NULL));");
4978 output.println(generateTemp(fm,fon.getRight(),lb)+");");
4980 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+fon.getOp().toString()+generateTemp(fm,fon.getRight(),lb)+";");
4981 } else if (fon.getOp().getOp()==Operation.ASSIGN)
4982 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
4983 else if (fon.getOp().getOp()==Operation.UNARYPLUS)
4984 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
4985 else if (fon.getOp().getOp()==Operation.UNARYMINUS)
4986 output.println(generateTemp(fm, fon.getDest(),lb)+" = -"+generateTemp(fm, fon.getLeft(),lb)+";");
4987 else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
4988 output.println(generateTemp(fm, fon.getDest(),lb)+" = !"+generateTemp(fm, fon.getLeft(),lb)+";");
4989 else if (fon.getOp().getOp()==Operation.COMP)
4990 output.println(generateTemp(fm, fon.getDest(),lb)+" = ~"+generateTemp(fm, fon.getLeft(),lb)+";");
4991 else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
4992 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+"->fses==NULL;");
4994 output.println(generateTemp(fm, fon.getDest(),lb)+fon.getOp().toString()+generateTemp(fm, fon.getLeft(),lb)+";");
4997 private void generateFlatCastNode(FlatMethod fm, LocalityBinding lb, FlatCastNode fcn, PrintWriter output) {
4998 /* TODO: Do type check here */
4999 if (fcn.getType().isArray()) {
5000 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
5001 } else if (fcn.getType().isClass())
5002 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
5004 output.println(generateTemp(fm,fcn.getDst(),lb)+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc(),lb)+";");
5007 private void generateFlatLiteralNode(FlatMethod fm, LocalityBinding lb, FlatLiteralNode fln, PrintWriter output) {
5008 if (fln.getValue()==null)
5009 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
5010 else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
5011 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5012 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
5013 //Stash pointer in case of GC
5014 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5015 output.println(revertptr+"=revertlist;");
5017 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
5018 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
5019 //Stash pointer in case of GC
5020 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5021 output.println("revertlist="+revertptr+";");
5024 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
5026 } else if (fln.getType().isBoolean()) {
5027 if (((Boolean)fln.getValue()).booleanValue())
5028 output.println(generateTemp(fm, fln.getDst(),lb)+"=1;");
5030 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
5031 } else if (fln.getType().isChar()) {
5032 String st=FlatLiteralNode.escapeString(fln.getValue().toString());
5033 output.println(generateTemp(fm, fln.getDst(),lb)+"='"+st+"';");
5034 } else if (fln.getType().isLong()) {
5035 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+"LL;");
5037 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+";");
5040 protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) {
5041 if (frn.getReturnTemp()!=null) {
5042 if (frn.getReturnTemp().getType().isPtr())
5043 output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";");
5045 output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";");
5047 output.println("return;");
5051 protected void generateStoreFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
5054 //only record if this group has more than one exit
5055 if (branchanalysis.numJumps(fcb)>1) {
5056 left=branchanalysis.jumpValue(fcb, 0);
5057 right=branchanalysis.jumpValue(fcb, 1);
5059 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") {");
5061 output.println("STOREBRANCH("+right+");");
5062 output.println("goto "+label+";");
5063 output.println("}");
5065 output.println("STOREBRANCH("+left+");");
5068 protected void generateFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
5069 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") goto "+label+";");
5072 /** This method generates header information for the method or
5073 * task referenced by the Descriptor des. */
5074 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) {
5075 generateHeader(fm, lb, des, output, false);
5078 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output, boolean addSESErecord) {
5080 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : des);
5081 MethodDescriptor md=null;
5082 TaskDescriptor task=null;
5083 if (des instanceof MethodDescriptor)
5084 md=(MethodDescriptor) des;
5086 task=(TaskDescriptor) des;
5088 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
5090 if (md!=null&&md.getReturnType()!=null) {
5091 if (md.getReturnType().isClass()||md.getReturnType().isArray())
5092 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
5094 output.print(md.getReturnType().getSafeSymbol()+" ");
5096 //catch the constructor case
5097 output.print("void ");
5099 if (state.DSM||state.SINGLETM) {
5100 output.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
5102 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
5104 output.print(task.getSafeSymbol()+"(");
5106 boolean printcomma=false;
5107 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5109 if (state.DSM||state.SINGLETM) {
5110 output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
5112 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
5114 output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
5120 for(int i=0; i<objectparams.numPrimitives(); i++) {
5121 TempDescriptor temp=objectparams.getPrimitive(i);
5125 if (temp.getType().isClass()||temp.getType().isArray())
5126 output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
5128 output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
5130 output.println(") {");
5131 } else if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
5132 /* Imprecise Task */
5133 output.println("void * parameterarray[]) {");
5134 /* Unpack variables */
5135 for(int i=0; i<objectparams.numPrimitives(); i++) {
5136 TempDescriptor temp=objectparams.getPrimitive(i);
5137 output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
5139 for(int i=0; i<fm.numTags(); i++) {
5140 TempDescriptor temp=fm.getTag(i);
5141 int offset=i+objectparams.numPrimitives();
5142 output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
5145 if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
5146 maxtaskparams=objectparams.numPrimitives()+fm.numTags();
5147 } else output.println(") {");
5150 public void generateFlatFlagActionNode(FlatMethod fm, LocalityBinding lb, FlatFlagActionNode ffan, PrintWriter output) {
5151 output.println("/* FlatFlagActionNode */");
5154 /* Process tag changes */
5155 Relation tagsettable=new Relation();
5156 Relation tagcleartable=new Relation();
5158 Iterator tagsit=ffan.getTempTagPairs();
5159 while (tagsit.hasNext()) {
5160 TempTagPair ttp=(TempTagPair) tagsit.next();
5161 TempDescriptor objtmp=ttp.getTemp();
5162 TagDescriptor tag=ttp.getTag();
5163 TempDescriptor tagtmp=ttp.getTagTemp();
5164 boolean tagstatus=ffan.getTagChange(ttp);
5166 tagsettable.put(objtmp, tagtmp);
5168 tagcleartable.put(objtmp, tagtmp);
5173 Hashtable flagandtable=new Hashtable();
5174 Hashtable flagortable=new Hashtable();
5176 /* Process flag changes */
5177 Iterator flagsit=ffan.getTempFlagPairs();
5178 while(flagsit.hasNext()) {
5179 TempFlagPair tfp=(TempFlagPair)flagsit.next();
5180 TempDescriptor temp=tfp.getTemp();
5181 Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
5182 FlagDescriptor flag=tfp.getFlag();
5184 //Newly allocate objects that don't set any flags case
5185 if (flagortable.containsKey(temp)) {
5189 flagortable.put(temp,new Integer(mask));
5191 int flagid=1<<((Integer)flagtable.get(flag)).intValue();
5192 boolean flagstatus=ffan.getFlagChange(tfp);
5195 if (flagortable.containsKey(temp)) {
5196 mask=((Integer)flagortable.get(temp)).intValue();
5199 flagortable.put(temp,new Integer(mask));
5201 int mask=0xFFFFFFFF;
5202 if (flagandtable.containsKey(temp)) {
5203 mask=((Integer)flagandtable.get(temp)).intValue();
5205 mask&=(0xFFFFFFFF^flagid);
5206 flagandtable.put(temp,new Integer(mask));
5212 HashSet flagtagset=new HashSet();
5213 flagtagset.addAll(flagortable.keySet());
5214 flagtagset.addAll(flagandtable.keySet());
5215 flagtagset.addAll(tagsettable.keySet());
5216 flagtagset.addAll(tagcleartable.keySet());
5218 Iterator ftit=flagtagset.iterator();
5219 while(ftit.hasNext()) {
5220 TempDescriptor temp=(TempDescriptor)ftit.next();
5223 Set tagtmps=tagcleartable.get(temp);
5224 if (tagtmps!=null) {
5225 Iterator tagit=tagtmps.iterator();
5226 while(tagit.hasNext()) {
5227 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
5228 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
5229 output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5231 output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5235 tagtmps=tagsettable.get(temp);
5236 if (tagtmps!=null) {
5237 Iterator tagit=tagtmps.iterator();
5238 while(tagit.hasNext()) {
5239 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
5240 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
5241 output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5243 output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp, lb)+", "+generateTemp(fm,tagtmp, lb)+");");
5248 int andmask=0xFFFFFFF;
5250 if (flagortable.containsKey(temp))
5251 ormask=((Integer)flagortable.get(temp)).intValue();
5252 if (flagandtable.containsKey(temp))
5253 andmask=((Integer)flagandtable.get(temp)).intValue();
5254 generateFlagOrAnd(ffan, fm, lb, temp, output, ormask, andmask);
5255 generateObjectDistribute(ffan, fm, lb, temp, output);
5259 protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp,
5260 PrintWriter output, int ormask, int andmask) {
5261 if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
5262 output.println("flagorandinit("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
5264 output.println("flagorand("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
5268 protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, PrintWriter output) {
5269 output.println("enqueueObject("+generateTemp(fm, temp, lb)+");");
5272 void generateOptionalHeader(PrintWriter headers) {
5275 headers.println("#include \"task.h\"\n\n");
5276 headers.println("#ifndef _OPTIONAL_STRUCT_");
5277 headers.println("#define _OPTIONAL_STRUCT_");
5279 //STRUCT PREDICATEMEMBER
5280 headers.println("struct predicatemember{");
5281 headers.println("int type;");
5282 headers.println("int numdnfterms;");
5283 headers.println("int * flags;");
5284 headers.println("int numtags;");
5285 headers.println("int * tags;\n};\n\n");
5287 //STRUCT OPTIONALTASKDESCRIPTOR
5288 headers.println("struct optionaltaskdescriptor{");
5289 headers.println("struct taskdescriptor * task;");
5290 headers.println("int index;");
5291 headers.println("int numenterflags;");
5292 headers.println("int * enterflags;");
5293 headers.println("int numpredicatemembers;");
5294 headers.println("struct predicatemember ** predicatememberarray;");
5295 headers.println("};\n\n");
5297 //STRUCT TASKFAILURE
5298 headers.println("struct taskfailure {");
5299 headers.println("struct taskdescriptor * task;");
5300 headers.println("int index;");
5301 headers.println("int numoptionaltaskdescriptors;");
5302 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
5304 //STRUCT FSANALYSISWRAPPER
5305 headers.println("struct fsanalysiswrapper{");
5306 headers.println("int flags;");
5307 headers.println("int numtags;");
5308 headers.println("int * tags;");
5309 headers.println("int numtaskfailures;");
5310 headers.println("struct taskfailure ** taskfailurearray;");
5311 headers.println("int numoptionaltaskdescriptors;");
5312 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
5314 //STRUCT CLASSANALYSISWRAPPER
5315 headers.println("struct classanalysiswrapper{");
5316 headers.println("int type;");
5317 headers.println("int numotd;");
5318 headers.println("struct optionaltaskdescriptor ** otdarray;");
5319 headers.println("int numfsanalysiswrappers;");
5320 headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
5322 headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
5324 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
5325 while(taskit.hasNext()) {
5326 TaskDescriptor td=(TaskDescriptor)taskit.next();
5327 headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
5332 //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
5333 int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
5334 int predicateindex = 0;
5335 //iterate through the classes concerned by the predicate
5336 Set c_vard = predicate.vardescriptors;
5337 Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
5340 for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext();) {
5341 VarDescriptor vard = (VarDescriptor)vard_it.next();
5342 TypeDescriptor typed = vard.getType();
5344 //generate for flags
5345 HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
5346 output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5348 if (fen_hashset!=null) {
5349 for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext();) {
5350 FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
5352 DNFFlag dflag=fen.getDNF();
5353 numberterms+=dflag.size();
5355 Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
5357 for(int j=0; j<dflag.size(); j++) {
5359 output.println(",");
5360 Vector term=dflag.get(j);
5363 for(int k=0; k<term.size(); k++) {
5364 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
5365 FlagDescriptor fd=dfa.getFlag();
5366 boolean negated=dfa.getNegated();
5367 int flagid=1<<((Integer)flags.get(fd)).intValue();
5372 output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
5377 output.println("};\n");
5380 TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
5381 output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5384 for(int j=0; j<tagel.numTags(); j++) {
5386 output.println(",");
5387 TempDescriptor tmp=tagel.getTemp(j);
5388 if (!slotnumber.containsKey(tmp)) {
5389 Integer slotint=new Integer(current_slot++);
5390 slotnumber.put(tmp,slotint);
5392 int slot=slotnumber.get(tmp).intValue();
5393 output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
5395 numtags = tagel.numTags();
5397 output.println("};");
5399 //store the result into a predicatemember struct
5400 output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
5401 output.println("/*type*/"+typed.getClassDesc().getId()+",");
5402 output.println("/* number of dnf terms */"+numberterms+",");
5403 output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5404 output.println("/* number of tag */"+numtags+",");
5405 output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5406 output.println("};\n");
5411 //generate an array that stores the entire predicate
5412 output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5413 for( int j = 0; j<predicateindex; j++) {
5414 if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5415 else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5417 output.println("};\n");
5418 return predicateindex;
5422 void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
5423 generateOptionalHeader(headers);
5425 output.println("#include \"optionalstruct.h\"\n\n");
5426 output.println("#include \"stdlib.h\"\n");
5428 HashSet processedcd = new HashSet();
5430 Enumeration e = safeexecution.keys();
5431 while (e.hasMoreElements()) {
5434 ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
5435 Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp); //will be used several times
5437 //Generate the struct of optionals
5438 Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
5439 numotd = c_otd.size();
5440 if(maxotd<numotd) maxotd = numotd;
5441 if( !c_otd.isEmpty() ) {
5442 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
5443 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
5445 //generate the int arrays for the predicate
5446 Predicate predicate = otd.predicate;
5447 int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
5448 TreeSet<Integer> fsset=new TreeSet<Integer>();
5449 //iterate through possible FSes corresponding to
5450 //the state when entering
5452 for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext();) {
5453 FlagState fs = (FlagState)fses.next();
5455 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
5456 FlagDescriptor flagd = (FlagDescriptor)flags.next();
5457 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
5460 fsset.add(new Integer(flagid));
5461 //tag information not needed because tag
5462 //changes are not tolerated.
5465 output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5466 boolean needcomma=false;
5467 for(Iterator<Integer> it=fsset.iterator(); it.hasNext();) {
5470 output.println(it.next());
5473 output.println("};\n");
5476 //generate optionaltaskdescriptor that actually
5477 //includes exit fses, predicate and the task
5479 output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
5480 output.println("&task_"+otd.td.getSafeSymbol()+",");
5481 output.println("/*index*/"+otd.getIndex()+",");
5482 output.println("/*number of enter flags*/"+fsset.size()+",");
5483 output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5484 output.println("/*number of members */"+predicateindex+",");
5485 output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5486 output.println("};\n");
5490 // if there are no optionals, there is no need to build the rest of the struct
5492 output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
5493 c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
5494 if( !c_otd.isEmpty() ) {
5495 boolean needcomma=false;
5496 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
5497 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
5499 output.println(",");
5501 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5504 output.println("};\n");
5506 //get all the possible flagstates reachable by an object
5507 Hashtable hashtbtemp = safeexecution.get(cdtemp);
5509 TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
5510 fsts.addAll(hashtbtemp.keySet());
5511 for(Iterator fsit=fsts.iterator(); fsit.hasNext();) {
5512 FlagState fs = (FlagState)fsit.next();
5515 //get the set of OptionalTaskDescriptors corresponding
5516 HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
5517 //iterate through the OptionalTaskDescriptors and
5518 //store the pointers to the optionals struct (see on
5519 //top) into an array
5521 output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
5522 for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext();) {
5523 OptionalTaskDescriptor mm = mos.next();
5525 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
5527 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5530 output.println("};\n");
5532 //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
5535 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
5536 FlagDescriptor flagd = (FlagDescriptor)flags.next();
5537 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
5541 //process tag information
5544 boolean first = true;
5545 Enumeration tag_enum = fs.getTags();
5546 output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
5547 while(tag_enum.hasMoreElements()) {
5549 TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
5553 output.println(", ");
5554 output.println("/*tagid*/"+state.getTagId(tagd));
5556 output.println("};");
5558 Set<TaskIndex> tiset=sa.getTaskIndex(fs);
5559 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
5560 TaskIndex ti=itti.next();
5564 Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
5566 output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
5567 boolean needcomma=false;
5568 for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext();) {
5569 OptionalTaskDescriptor otd=otdit.next();
5573 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5575 output.println("};");
5577 output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
5578 output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
5579 output.print(ti.getIndex()+", ");
5580 output.print(otdset.size()+", ");
5581 output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
5582 output.println("};");
5585 tiset=sa.getTaskIndex(fs);
5586 boolean needcomma=false;
5588 output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
5589 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
5590 TaskIndex ti=itti.next();
5591 if (ti.isRuntime()) {
5598 output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
5600 output.println("};\n");
5602 //Store the result in fsanalysiswrapper
5604 output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
5605 output.println("/*flag*/"+flagid+",");
5606 output.println("/* number of tags*/"+tagcounter+",");
5607 output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
5608 output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
5609 output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
5610 output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
5611 output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
5612 output.println("};\n");
5616 //Build the array of fsanalysiswrappers
5617 output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
5618 boolean needcomma=false;
5619 for(int i = 0; i<fscounter; i++) {
5620 if (needcomma) output.print(",");
5621 output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
5624 output.println("};");
5626 //Build the classanalysiswrapper referring to the previous array
5627 output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
5628 output.println("/*type*/"+cdtemp.getId()+",");
5629 output.println("/*numotd*/"+numotd+",");
5630 output.println("otdarray"+cdtemp.getSafeSymbol()+",");
5631 output.println("/* number of fsanalysiswrappers */"+fscounter+",");
5632 output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
5633 processedcd.add(cdtemp);
5636 //build an array containing every classes for which code has been build
5637 output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
5638 for(int i=0; i<state.numClasses(); i++) {
5639 ClassDescriptor cn=cdarray[i];
5642 if ((cn != null) && (processedcd.contains(cn)))
5643 output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
5645 output.print("NULL");
5647 output.println("};");
5649 output.println("#define MAXOTD "+maxotd);
5650 headers.println("#endif");
5653 public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
5654 Relation r=new Relation();
5655 for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext();) {
5656 OptionalTaskDescriptor otd=otdit.next();
5657 TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
5661 LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
5662 for(Iterator it=r.keySet().iterator(); it.hasNext();) {
5663 Set s=r.get(it.next());
5664 for(Iterator it2=s.iterator(); it2.hasNext();) {
5665 OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
5673 protected void outputTransCode(PrintWriter output) {
5676 private int calculateSizeOfSESEParamList(FlatSESEEnterNode fsen){
5678 Set<TempDescriptor> tdSet=new HashSet<TempDescriptor>();
5680 for (Iterator iterator = fsen.getInVarSet().iterator(); iterator.hasNext();) {
5681 TempDescriptor tempDescriptor = (TempDescriptor) iterator.next();
5682 if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()){
5683 tdSet.add(tempDescriptor);
5687 for (Iterator iterator = fsen.getOutVarSet().iterator(); iterator.hasNext();) {
5688 TempDescriptor tempDescriptor = (TempDescriptor) iterator.next();
5689 if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()){
5690 tdSet.add(tempDescriptor);
5694 return tdSet.size();
5697 private String calculateSizeOfSESEParamSize(FlatSESEEnterNode fsen){
5698 HashMap <String,Integer> map=new HashMap();
5699 HashSet <TempDescriptor> processed=new HashSet<TempDescriptor>();
5702 // space for all in and out set primitives
5703 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
5704 inSetAndOutSet.addAll( fsen.getInVarSet() );
5705 inSetAndOutSet.addAll( fsen.getOutVarSet() );
5707 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
5709 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
5710 while( itr.hasNext() ) {
5711 TempDescriptor temp = itr.next();
5712 TypeDescriptor type = temp.getType();
5713 if( !type.isPtr() ) {
5714 inSetAndOutSetPrims.add( temp );
5718 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
5719 while( itrPrims.hasNext() ) {
5720 TempDescriptor temp = itrPrims.next();
5721 TypeDescriptor type = temp.getType();
5722 if(type.isPrimitive()){
5723 Integer count=map.get(type.getSymbol());
5725 count=new Integer(1);
5726 map.put(type.getSymbol(), count);
5728 map.put(type.getSymbol(), new Integer(count.intValue()+1));
5733 Set<String> keySet=map.keySet();
5734 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
5735 String key = (String) iterator.next();
5736 rtr+="+sizeof("+key+")*"+map.get(key);