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;
162 PrintWriter outglobaldefs=null;
166 outsandbox=new PrintWriter(new FileOutputStream(PREFIX+"sandboxdefs.c"), true);
168 outstructs=new PrintWriter(new FileOutputStream(PREFIX+"structdefs.h"), true);
169 outmethodheader=new PrintWriter(new FileOutputStream(PREFIX+"methodheaders.h"), true);
170 outclassdefs=new PrintWriter(new FileOutputStream(PREFIX+"classdefs.h"), true);
172 // TODO add version for normal Java later
173 outglobaldefs=new PrintWriter(new FileOutputStream(PREFIX+"globaldefs.h"), true);
175 outmethod=new PrintWriter(new FileOutputStream(PREFIX+"methods.c"), true);
176 outvirtual=new PrintWriter(new FileOutputStream(PREFIX+"virtualtable.h"), true);
178 outtask=new PrintWriter(new FileOutputStream(PREFIX+"task.h"), true);
179 outtaskdefs=new PrintWriter(new FileOutputStream(PREFIX+"taskdefs.c"), true);
180 if (state.OPTIONAL) {
181 outoptionalarrays=new PrintWriter(new FileOutputStream(PREFIX+"optionalarrays.c"), true);
182 optionalheaders=new PrintWriter(new FileOutputStream(PREFIX+"optionalstruct.h"), true);
185 if (state.structfile!=null) {
186 outrepairstructs=new PrintWriter(new FileOutputStream(PREFIX+state.structfile+".struct"), true);
188 } catch (Exception e) {
193 /* Build the virtual dispatch tables */
194 buildVirtualTables(outvirtual);
196 /* Tag the methods that are invoked by static blocks */
197 tagMethodInvokedByStaticBlock();
199 /* Output includes */
200 outmethodheader.println("#ifndef METHODHEADERS_H");
201 outmethodheader.println("#define METHODHEADERS_H");
202 outmethodheader.println("#include \"structdefs.h\"");
204 outmethodheader.println("#include \"dstm.h\"");
206 outmethodheader.println("#include \"sandbox.h\"");
208 if (state.EVENTMONITOR) {
209 outmethodheader.println("#include \"monitor.h\"");
211 if (state.SINGLETM) {
212 outmethodheader.println("#include \"tm.h\"");
213 outmethodheader.println("#include \"delaycomp.h\"");
214 outmethodheader.println("#include \"inlinestm.h\"");
216 if (state.ABORTREADERS) {
217 outmethodheader.println("#include \"abortreaders.h\"");
218 outmethodheader.println("#include <setjmp.h>");
220 if (state.MLP || state.OOOJAVA) {
221 outmethodheader.println("#include <stdlib.h>");
222 outmethodheader.println("#include <stdio.h>");
223 outmethodheader.println("#include <string.h>");
224 outmethodheader.println("#include \"mlp_runtime.h\"");
225 outmethodheader.println("#include \"psemaphore.h\"");
226 outmethodheader.println("#include \"memPool.h\"");
229 outmethodheader.println("#include \"rcr_runtime.h\"");
230 outmethodheader.println("#include \"oooJava/hashStructure.h\"");
233 // spit out a global to inform all worker threads with
234 // the maximum size is for any task record
235 outmethodheader.println("extern int "+maxTaskRecSizeStr+";");
238 /* Output Structures */
239 outputStructs(outstructs);
241 // Output the C class declarations
242 // These could mutually reference each other
245 // TODO add version for normal Java later
246 outglobaldefs.println("#ifndef __GLOBALDEF_H_");
247 outglobaldefs.println("#define __GLOBALDEF_H_");
248 outglobaldefs.println("");
249 outglobaldefs.println("struct global_defs_t {");
252 outclassdefs.println("#ifndef __CLASSDEF_H_");
253 outclassdefs.println("#define __CLASSDEF_H_");
254 outputClassDeclarations(outclassdefs, outglobaldefs);
256 // Output function prototypes and structures for parameters
257 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
258 while(it.hasNext()) {
259 ClassDescriptor cn=(ClassDescriptor)it.next();
260 generateCallStructs(cn, outclassdefs, outstructs, outmethodheader, outglobaldefs);
262 outclassdefs.println("#endif");
263 outclassdefs.close();
265 // TODO add version for normal Java later
266 outglobaldefs.println("};");
267 outglobaldefs.println("");
268 outglobaldefs.println("extern struct global_defs_t * global_defs_p;");
269 outglobaldefs.println("#endif");
270 outglobaldefs.flush();
271 outglobaldefs.close();
275 /* Map flags to integers */
276 /* The runtime keeps track of flags using these integers */
277 it=state.getClassSymbolTable().getDescriptorsIterator();
278 while(it.hasNext()) {
279 ClassDescriptor cn=(ClassDescriptor)it.next();
283 generateTaskStructs(outstructs, outmethodheader);
285 /* Outputs generic task structures if this is a task
287 outputTaskTypes(outtask);
290 if( state.MLP || state.OOOJAVA) {
291 // have to initialize some SESE compiler data before
292 // analyzing normal methods, which must happen before
293 // generating SESE internal code
295 Iterator<FlatSESEEnterNode> seseit;
297 seseit=mlpa.getAllSESEs().iterator();
299 seseit=oooa.getAllSESEs().iterator();
302 //TODO signal the object that will report errors
305 rcr = new RuntimeConflictResolver(PREFIX, oooa);
306 rcr.setGlobalEffects(oooa.getDisjointAnalysis().getEffectsAnalysis().getAllEffects());
307 } catch (FileNotFoundException e) {
308 System.out.println("Runtime Conflict Resolver could not create output file.");
313 while(seseit.hasNext()){
314 FlatSESEEnterNode fsen = seseit.next();
315 initializeSESE( fsen );
319 /* Build the actual methods */
320 outputMethods(outmethod);
322 // Output function prototypes and structures for SESE's and code
323 if( state.MLP || state.OOOJAVA ) {
325 // spit out a global to inform all worker threads with
326 // the maximum size is for any task record
327 outmethod.println("int "+maxTaskRecSizeStr+" = 0;");
329 // used to differentiate, during code generation, whether we are
330 // passing over SESE body code, or non-SESE code
333 // first generate code for each sese's internals
334 Iterator<FlatSESEEnterNode> seseit;
336 seseit=mlpa.getAllSESEs().iterator();
338 seseit=oooa.getAllSESEs().iterator();
341 while(seseit.hasNext()) {
342 FlatSESEEnterNode fsen = seseit.next();
343 generateMethodSESE(fsen, null, outstructs, outmethodheader, outmethod);
346 // then write the invokeSESE switch to decouple scheduler
347 // from having to do unique details of sese invocation
348 generateSESEinvocationMethod(outmethodheader, outmethod);
352 /* Output code for tasks */
353 outputTaskCode(outtaskdefs, outmethod);
355 /* Record maximum number of task parameters */
356 outstructs.println("#define MAXTASKPARAMS "+maxtaskparams);
357 } else if (state.main!=null) {
358 /* Generate main method */
359 outputMainMethod(outmethod);
362 /* Generate information for task with optional parameters */
363 if (state.TASK&&state.OPTIONAL) {
364 generateOptionalArrays(outoptionalarrays, optionalheaders, state.getAnalysisResult(), state.getOptionalTaskDescriptors());
365 outoptionalarrays.close();
368 /* Output structure definitions for repair tool */
369 if (state.structfile!=null) {
370 buildRepairStructs(outrepairstructs);
371 outrepairstructs.close();
375 outmethodheader.println("#endif");
376 outmethodheader.close();
378 outstructs.println("#endif");
382 System.out.println("Runtime Conflict Resolver Done.");
386 /* This method goes though the call graph and tag those methods that are
387 * invoked inside static blocks
389 protected void tagMethodInvokedByStaticBlock() {
391 Iterator it_sclasses = this.state.getSClassSymbolTable().getDescriptorsIterator();
392 MethodDescriptor current_md=null;
393 HashSet tovisit=new HashSet();
394 HashSet visited=new HashSet();
396 while(it_sclasses.hasNext()) {
397 ClassDescriptor cd = (ClassDescriptor)it_sclasses.next();
398 MethodDescriptor md = (MethodDescriptor)cd.getMethodTable().get("staticblocks");
404 while(!tovisit.isEmpty()) {
405 current_md=(MethodDescriptor)tovisit.iterator().next();
406 tovisit.remove(current_md);
407 visited.add(current_md);
408 Iterator it_callee = this.callgraph.getCalleeSet(current_md).iterator();
409 while(it_callee.hasNext()) {
410 Descriptor d = (Descriptor)it_callee.next();
411 if(d instanceof MethodDescriptor) {
412 if(!visited.contains(d)) {
413 ((MethodDescriptor)d).setIsInvokedByStatic(true);
419 } // TODO for normal Java version
422 /* This code generates code for each static block and static field
424 protected void outputStaticBlocks(PrintWriter outmethod) {
425 // execute all the static blocks and all the static field initializations
429 /* This code generates code to create a Class object for each class for
432 protected void outputClassObjects(PrintWriter outmethod) {
433 // for each class, initialize its Class object
435 SymbolTable ctbl = this.state.getClassSymbolTable();
436 Iterator it_classes = ctbl.getDescriptorsIterator();
437 while(it_classes.hasNext()) {
438 ClassDescriptor t_cd = (ClassDescriptor)it_classes.next();
439 outmethod.println(" {");
440 outmethod.println(" global_defs_p->"+t_cd.getSafeSymbol()+"classobj.type="+t_cd.getId()+";");
441 outmethod.println(" initlock((struct ___Object___ *)(&(global_defs_p->"+t_cd.getSafeSymbol()+"classobj)));");
442 outmethod.println(" }");
444 } // else TODO normal java version
447 /* This code just generates the main C method for java programs.
448 * The main C method packs up the arguments into a string array
449 * and passes it to the java main method. */
451 protected void outputMainMethod(PrintWriter outmethod) {
452 outmethod.println("int main(int argc, const char *argv[]) {");
453 outmethod.println(" int i;");
455 outputStaticBlocks(outmethod);
456 outputClassObjects(outmethod);
458 if (state.MLP || state.OOOJAVA) {
460 // do a calculation to determine which task record
461 // is the largest, store that as a global value for
462 // allocating records
463 Iterator<FlatSESEEnterNode> seseit;
465 seseit=mlpa.getAllSESEs().iterator();
467 seseit=oooa.getAllSESEs().iterator();
469 while(seseit.hasNext()){
470 FlatSESEEnterNode fsen = seseit.next();
471 outmethod.println("if( sizeof( "+fsen.getSESErecordName()+
472 " ) > "+maxTaskRecSizeStr+
473 " ) { "+maxTaskRecSizeStr+
474 " = sizeof( "+fsen.getSESErecordName()+
478 outmethod.println(" runningSESE = NULL;");
480 outmethod.println(" workScheduleInit( "+state.MLP_NUMCORES+", invokeSESEmethod );");
482 //initializes data structures needed for the RCR traverser
483 if(state.RCR && rcr != null) {
484 outmethod.println(" initializeStructsRCR();");
485 outmethod.println(" createAndFillMasterHashStructureArray();");
490 if (state.DSMRECOVERYSTATS) {
491 outmethod.println("#ifdef RECOVERYSTATS \n");
492 outmethod.println("handle();\n");
493 outmethod.println("#endif\n");
495 outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n");
496 outmethod.println("handle();\n");
497 outmethod.println("#endif\n");
501 if (state.THREAD||state.DSM||state.SINGLETM) {
502 outmethod.println("initializethreads();");
505 outmethod.println("if (dstmStartup(argv[1])) {");
506 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
507 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-2);");
509 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-2);");
512 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
513 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1);");
515 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1);");
519 outmethod.println(" for(i=2;i<argc;i++) {");
521 outmethod.println(" for(i=1;i<argc;i++) {");
522 outmethod.println(" int length=strlen(argv[i]);");
523 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
524 outmethod.println(" struct ___String___ *newstring=NewString(NULL, argv[i], length);");
526 outmethod.println(" struct ___String___ *newstring=NewString(argv[i], length);");
529 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-2]=newstring;");
531 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-1]=newstring;");
532 outmethod.println(" }");
534 MethodDescriptor md=typeutil.getMain();
535 ClassDescriptor cd=typeutil.getMainClass();
537 outmethod.println(" {");
538 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
539 if (state.DSM||state.SINGLETM) {
540 outmethod.print(" struct "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
542 outmethod.print(" struct "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
543 outmethod.println("1, NULL,"+"stringarray};");
544 if (state.DSM||state.SINGLETM)
545 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
547 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
549 if (state.DSM||state.SINGLETM)
550 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
552 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
554 outmethod.println(" }");
557 outmethod.println("}");
560 if (state.THREAD||state.DSM||state.SINGLETM) {
561 outmethod.println("pthread_mutex_lock(&gclistlock);");
562 outmethod.println("threadcount--;");
563 outmethod.println("pthread_cond_signal(&gccond);");
564 outmethod.println("pthread_mutex_unlock(&gclistlock);");
567 if (state.DSM||state.SINGLETM) {
568 //outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n");
569 outmethod.println("#if defined(TRANSSTATS) \n");
570 outmethod.println("printf(\"****** Transaction Stats ******\\n\");");
571 outmethod.println("printf(\"numTransCommit= %d\\n\", numTransCommit);");
572 outmethod.println("printf(\"numTransAbort= %d\\n\", numTransAbort);");
573 outmethod.println("printf(\"nSoftAbort= %d\\n\", nSoftAbort);");
575 outmethod.println("printf(\"nchashSearch= %d\\n\", nchashSearch);");
576 outmethod.println("printf(\"nmhashSearch= %d\\n\", nmhashSearch);");
577 outmethod.println("printf(\"nprehashSearch= %d\\n\", nprehashSearch);");
578 outmethod.println("printf(\"ndirtyCacheObj= %d\\n\", ndirtyCacheObj);");
579 outmethod.println("printf(\"nRemoteReadSend= %d\\n\", nRemoteSend);");
580 outmethod.println("printf(\"bytesSent= %d\\n\", bytesSent);");
581 outmethod.println("printf(\"bytesRecv= %d\\n\", bytesRecv);");
582 outmethod.println("printf(\"totalObjSize= %d\\n\", totalObjSize);");
583 outmethod.println("printf(\"sendRemoteReq= %d\\n\", sendRemoteReq);");
584 outmethod.println("printf(\"getResponse= %d\\n\", getResponse);");
585 } else if (state.SINGLETM) {
586 outmethod.println("printf(\"nSoftAbortAbort= %d\\n\", nSoftAbortAbort);");
587 outmethod.println("printf(\"nSoftAbortCommit= %d\\n\", nSoftAbortCommit);");
588 outmethod.println("#ifdef STMSTATS\n");
589 outmethod.println("for(i=0; i<TOTALNUMCLASSANDARRAY; i++) {\n");
590 outmethod.println(" printf(\"typesCausingAbort[%2d] numaccess= %5d numabort= %3d\\n\", i, typesCausingAbort[i].numaccess, typesCausingAbort[i].numabort);\n");
591 outmethod.println("}\n");
592 outmethod.println("#endif\n");
593 outmethod.println("fflush(stdout);");
595 outmethod.println("#endif\n");
598 if (state.EVENTMONITOR) {
599 outmethod.println("dumpdata();");
602 if (state.THREAD||state.SINGLETM)
603 outmethod.println("pthread_exit(NULL);");
605 if (state.MLP || state.OOOJAVA ) {
606 outmethod.println(" workScheduleBegin();");
609 outmethod.println("}");
612 /* This method outputs code for each task. */
614 private void outputTaskCode(PrintWriter outtaskdefs, PrintWriter outmethod) {
615 /* Compile task based program */
616 outtaskdefs.println("#include \"task.h\"");
617 outtaskdefs.println("#include \"methodheaders.h\"");
618 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
619 while(taskit.hasNext()) {
620 TaskDescriptor td=(TaskDescriptor)taskit.next();
621 FlatMethod fm=state.getMethodFlat(td);
622 generateFlatMethod(fm, null, outmethod);
623 generateTaskDescriptor(outtaskdefs, fm, td);
626 //Output task descriptors
627 taskit=state.getTaskSymbolTable().getDescriptorsIterator();
628 outtaskdefs.println("struct taskdescriptor * taskarray[]= {");
630 while(taskit.hasNext()) {
631 TaskDescriptor td=(TaskDescriptor)taskit.next();
635 outtaskdefs.println(",");
636 outtaskdefs.print("&task_"+td.getSafeSymbol());
638 outtaskdefs.println("};");
640 outtaskdefs.println("int numtasks="+state.getTaskSymbolTable().getValueSet().size()+";");
643 /* This method outputs most of the methods.c file. This includes
644 * some standard includes and then an array with the sizes of
645 * objets and array that stores supertype and then the code for
646 * the Java methods.. */
648 protected void outputMethods(PrintWriter outmethod) {
649 outmethod.println("#include \"methodheaders.h\"");
650 outmethod.println("#include \"virtualtable.h\"");
651 outmethod.println("#include \"runtime.h\"");
653 // always include: compiler directives will leave out
654 // instrumentation when option is not set
655 outmethod.println("#include \"coreprof/coreprof.h\"");
658 outmethod.println("#include \"sandboxdefs.c\"");
661 outmethod.println("#include \"addPrefetchEnhance.h\"");
662 outmethod.println("#include \"localobjects.h\"");
664 if (state.FASTCHECK) {
665 outmethod.println("#include \"localobjects.h\"");
667 if(state.MULTICORE) {
669 outmethod.println("#include \"task.h\"");
671 outmethod.println("#include \"multicoreruntime.h\"");
672 outmethod.println("#include \"runtime_arch.h\"");
674 if (state.THREAD||state.DSM||state.SINGLETM) {
675 outmethod.println("#include <thread.h>");
678 outmethod.println("#include \"thread.h\"");
680 if (state.main!=null) {
681 outmethod.println("#include <string.h>");
683 if (state.CONSCHECK) {
684 outmethod.println("#include \"checkers.h\"");
686 if (state.MLP || state.OOOJAVA ) {
687 outmethod.println("#include <stdlib.h>");
688 outmethod.println("#include <stdio.h>");
689 outmethod.println("#include \"mlp_runtime.h\"");
690 outmethod.println("#include \"psemaphore.h\"");
693 outmethod.println("#include \"trqueue.h\"");
694 outmethod.println("#include \"RuntimeConflictResolver.h\"");
695 outmethod.println("#include \"rcr_runtime.h\"");
700 // TODO add version for normal Java later
701 outmethod.println("struct global_defs_t * global_defs_p;");
703 //Store the sizes of classes & array elements
704 generateSizeArray(outmethod);
706 //Store table of supertypes
707 generateSuperTypeTable(outmethod);
709 //Store the layout of classes
710 generateLayoutStructs(outmethod);
712 /* Generate code for methods */
713 if (state.DSM||state.SINGLETM) {
714 for(Iterator<LocalityBinding> lbit=locality.getLocalityBindings().iterator(); lbit.hasNext();) {
715 LocalityBinding lb=lbit.next();
716 MethodDescriptor md=lb.getMethod();
717 FlatMethod fm=state.getMethodFlat(md);
719 if (!md.getModifiers().isNative()) {
720 generateFlatMethod(fm, lb, outmethod);
721 //System.out.println("fm= " + fm + " md= " + md);
725 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
726 while(classit.hasNext()) {
727 ClassDescriptor cn=(ClassDescriptor)classit.next();
728 Iterator methodit=cn.getMethods();
729 while(methodit.hasNext()) {
730 /* Classify parameters */
731 MethodDescriptor md=(MethodDescriptor)methodit.next();
732 FlatMethod fm=state.getMethodFlat(md);
733 if (!md.getModifiers().isNative()) {
734 generateFlatMethod(fm, null, outmethod);
741 protected void outputStructs(PrintWriter outstructs) {
742 outstructs.println("#ifndef STRUCTDEFS_H");
743 outstructs.println("#define STRUCTDEFS_H");
744 outstructs.println("#include \"classdefs.h\"");
745 outstructs.println("#ifndef INTPTR");
746 outstructs.println("#ifdef BIT64");
747 outstructs.println("#define INTPTR long");
748 outstructs.println("#else");
749 outstructs.println("#define INTPTR int");
750 outstructs.println("#endif");
751 outstructs.println("#endif");
752 if( state.MLP || state.OOOJAVA ) {
753 outstructs.println("#include \"mlp_runtime.h\"");
754 outstructs.println("#include \"psemaphore.h\"");
757 outstructs.println("#include \"rcr_runtime.h\"");
761 /* Output #defines that the runtime uses to determine type
762 * numbers for various objects it needs */
763 outstructs.println("#define MAXCOUNT "+maxcount);
764 if (state.DSM||state.SINGLETM) {
765 LocalityBinding lbrun=new LocalityBinding(typeutil.getRun(), false);
767 lbrun.setGlobalThis(LocalityAnalysis.GLOBAL);
769 else if (state.SINGLETM) {
770 lbrun.setGlobalThis(LocalityAnalysis.NORMAL);
772 outstructs.println("#define RUNMETHOD "+virtualcalls.getLocalityNumber(lbrun));
776 LocalityBinding lbexecute = new LocalityBinding(typeutil.getExecute(), false);
778 lbexecute.setGlobalThis(LocalityAnalysis.GLOBAL);
779 else if( state.SINGLETM)
780 lbexecute.setGlobalThis(LocalityAnalysis.NORMAL);
781 outstructs.println("#define EXECUTEMETHOD " + virtualcalls.getLocalityNumber(lbexecute));
784 outstructs.println("#define STRINGARRAYTYPE "+
785 (state.getArrayNumber(
786 (new TypeDescriptor(typeutil.getClass(TypeUtil.StringClass))).makeArray(state))+state.numClasses()));
788 outstructs.println("#define OBJECTARRAYTYPE "+
789 (state.getArrayNumber(
790 (new TypeDescriptor(typeutil.getClass(TypeUtil.ObjectClass))).makeArray(state))+state.numClasses()));
793 outstructs.println("#define STRINGTYPE "+typeutil.getClass(TypeUtil.StringClass).getId());
794 outstructs.println("#define CHARARRAYTYPE "+
795 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.CHAR)).makeArray(state))+state.numClasses()));
797 outstructs.println("#define BYTEARRAYTYPE "+
798 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state))+state.numClasses()));
800 outstructs.println("#define BYTEARRAYARRAYTYPE "+
801 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state).makeArray(state))+state.numClasses()));
803 outstructs.println("#define NUMCLASSES "+state.numClasses());
804 int totalClassSize = state.numClasses() + state.numArrays();
805 outstructs.println("#define TOTALNUMCLASSANDARRAY "+ totalClassSize);
807 outstructs.println("#define STARTUPTYPE "+typeutil.getClass(TypeUtil.StartupClass).getId());
808 outstructs.println("#define TAGTYPE "+typeutil.getClass(TypeUtil.TagClass).getId());
809 outstructs.println("#define TAGARRAYTYPE "+
810 (state.getArrayNumber(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)).makeArray(state))+state.numClasses()));
814 protected void outputClassDeclarations(PrintWriter outclassdefs, PrintWriter outglobaldefs) {
815 if (state.THREAD||state.DSM||state.SINGLETM)
816 outclassdefs.println("#include <pthread.h>");
817 outclassdefs.println("#ifndef INTPTR");
818 outclassdefs.println("#ifdef BIT64");
819 outclassdefs.println("#define INTPTR long");
820 outclassdefs.println("#else");
821 outclassdefs.println("#define INTPTR int");
822 outclassdefs.println("#endif");
823 outclassdefs.println("#endif");
825 outclassdefs.println("#include \"optionalstruct.h\"");
826 outclassdefs.println("struct "+arraytype+";");
827 /* Start by declaring all structs */
828 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
829 while(it.hasNext()) {
830 ClassDescriptor cn=(ClassDescriptor)it.next();
831 outclassdefs.println("struct "+cn.getSafeSymbol()+";");
834 // TODO add version for normal Java later
835 if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) {
836 // this class has static fields/blocks, need to add a global flag to
837 // indicate if its static fields have been initialized and/or if its
838 // static blocks have been executed
839 outglobaldefs.println(" int "+cn.getSafeSymbol()+"static_block_exe_flag;");
842 // for each class, create a global object
843 outglobaldefs.println(" struct Class "+cn.getSafeSymbol()+"classobj;");
846 outclassdefs.println("");
847 //Print out definition for array type
848 outclassdefs.println("struct "+arraytype+" {");
849 outclassdefs.println(" int type;");
850 if(state.MLP || state.OOOJAVA ){
851 outclassdefs.println(" int oid;");
852 outclassdefs.println(" int allocsite;");
854 if (state.EVENTMONITOR) {
855 outclassdefs.println(" int objuid;");
858 outclassdefs.println(" pthread_t tid;");
859 outclassdefs.println(" void * lockentry;");
860 outclassdefs.println(" int lockcount;");
863 outclassdefs.println(" int mutex;");
864 outclassdefs.println(" int objlock;");
865 if(state.MULTICOREGC) {
866 outclassdefs.println(" int marked;");
870 outclassdefs.println(" int flag;");
871 if(!state.MULTICORE) {
872 outclassdefs.println(" void * flagptr;");
874 outclassdefs.println(" int version;");
875 outclassdefs.println(" int * lock;"); // lock entry for this obj
876 outclassdefs.println(" int mutex;");
877 outclassdefs.println(" int lockcount;");
878 if(state.MULTICOREGC) {
879 outclassdefs.println(" int marked;");
883 outclassdefs.println(" int numfses;");
884 outclassdefs.println(" int * fses;");
887 printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs, outglobaldefs);
889 if (state.STMARRAY) {
890 outclassdefs.println(" int lowindex;");
891 outclassdefs.println(" int highindex;");
894 outclassdefs.println(" int paddingforarray;");
895 if (state.DUALVIEW) {
896 outclassdefs.println(" int arrayversion;");
899 outclassdefs.println(" int ___length___;");
900 outclassdefs.println("};\n");
903 // TODO add version for normal Java later
904 outclassdefs.println("");
905 //Print out definition for Class type
906 outclassdefs.println("struct Class {");
907 outclassdefs.println(" int type;");
908 if(state.MLP || state.OOOJAVA ){
909 outclassdefs.println(" int oid;");
910 outclassdefs.println(" int allocsite;");
912 if (state.EVENTMONITOR) {
913 outclassdefs.println(" int objuid;");
916 outclassdefs.println(" pthread_t tid;");
917 outclassdefs.println(" void * lockentry;");
918 outclassdefs.println(" int lockcount;");
921 outclassdefs.println(" int mutex;");
922 outclassdefs.println(" int objlock;");
923 if(state.MULTICOREGC) {
924 outclassdefs.println(" int marked;");
928 outclassdefs.println(" int flag;");
929 if(!state.MULTICORE) {
930 outclassdefs.println(" void * flagptr;");
932 outclassdefs.println(" int version;");
933 outclassdefs.println(" int * lock;"); // lock entry for this obj
934 outclassdefs.println(" int mutex;");
935 outclassdefs.println(" int lockcount;");
936 if(state.MULTICOREGC) {
937 outclassdefs.println(" int marked;");
941 outclassdefs.println(" int numfses;");
942 outclassdefs.println(" int * fses;");
945 printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs, outglobaldefs);
946 outclassdefs.println("};\n");
949 outclassdefs.println("");
950 outclassdefs.println("extern int classsize[];");
951 outclassdefs.println("extern int hasflags[];");
952 outclassdefs.println("extern unsigned INTPTR * pointerarray[];");
953 outclassdefs.println("extern int supertypes[];");
955 // TODO add version for normal Java later
956 outclassdefs.println("#include \"globaldefs.h\"");
958 outclassdefs.println("");
961 /** Prints out definitions for generic task structures */
963 private void outputTaskTypes(PrintWriter outtask) {
964 outtask.println("#ifndef _TASK_H");
965 outtask.println("#define _TASK_H");
966 outtask.println("struct parameterdescriptor {");
967 outtask.println("int type;");
968 outtask.println("int numberterms;");
969 outtask.println("int *intarray;");
970 outtask.println("void * queue;");
971 outtask.println("int numbertags;");
972 outtask.println("int *tagarray;");
973 outtask.println("};");
975 outtask.println("struct taskdescriptor {");
976 outtask.println("void * taskptr;");
977 outtask.println("int numParameters;");
978 outtask.println(" int numTotal;");
979 outtask.println("struct parameterdescriptor **descriptorarray;");
980 outtask.println("char * name;");
981 outtask.println("};");
982 outtask.println("extern struct taskdescriptor * taskarray[];");
983 outtask.println("extern numtasks;");
984 outtask.println("#endif");
988 private void buildRepairStructs(PrintWriter outrepairstructs) {
989 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
990 while(classit.hasNext()) {
991 ClassDescriptor cn=(ClassDescriptor)classit.next();
992 outrepairstructs.println("structure "+cn.getSymbol()+" {");
993 outrepairstructs.println(" int __type__;");
995 outrepairstructs.println(" int __flag__;");
996 if(!state.MULTICORE) {
997 outrepairstructs.println(" int __flagptr__;");
1000 printRepairStruct(cn, outrepairstructs);
1001 outrepairstructs.println("}\n");
1004 for(int i=0; i<state.numArrays(); i++) {
1005 TypeDescriptor tdarray=arraytable[i];
1006 TypeDescriptor tdelement=tdarray.dereference();
1007 outrepairstructs.println("structure "+arraytype+"_"+state.getArrayNumber(tdarray)+" {");
1008 outrepairstructs.println(" int __type__;");
1009 printRepairStruct(typeutil.getClass(TypeUtil.ObjectClass), outrepairstructs);
1010 outrepairstructs.println(" int length;");
1012 // Need to add support to repair tool for this
1013 if (tdelement.isClass()||tdelement.isArray())
1014 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" * elem[this.length];");
1016 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" elem[this.length];");
1018 outrepairstructs.println("}\n");
1022 private void printRepairStruct(ClassDescriptor cn, PrintWriter output) {
1023 ClassDescriptor sp=cn.getSuperDesc();
1025 printRepairStruct(sp, output);
1027 Vector fields=(Vector)fieldorder.get(cn);
1029 for(int i=0; i<fields.size(); i++) {
1030 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
1031 if (fd.getType().isArray()) {
1032 output.println(" "+arraytype+"_"+ state.getArrayNumber(fd.getType()) +" * "+fd.getSymbol()+";");
1033 } else if (fd.getType().isClass())
1034 output.println(" "+fd.getType().getRepairSymbol()+" * "+fd.getSymbol()+";");
1035 else if (fd.getType().isFloat())
1036 output.println(" int "+fd.getSymbol()+"; /* really float */");
1038 output.println(" "+fd.getType().getRepairSymbol()+" "+fd.getSymbol()+";");
1042 /** This method outputs TaskDescriptor information */
1043 private void generateTaskDescriptor(PrintWriter output, FlatMethod fm, TaskDescriptor task) {
1044 for (int i=0; i<task.numParameters(); i++) {
1045 VarDescriptor param_var=task.getParameter(i);
1046 TypeDescriptor param_type=task.getParamType(i);
1047 FlagExpressionNode param_flag=task.getFlag(param_var);
1048 TagExpressionList param_tag=task.getTag(param_var);
1051 if (param_flag==null) {
1052 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
1053 output.println("0x0, 0x0 };");
1056 DNFFlag dflag=param_flag.getDNF();
1057 dnfterms=dflag.size();
1059 Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
1060 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
1061 for(int j=0; j<dflag.size(); j++) {
1063 output.println(",");
1064 Vector term=dflag.get(j);
1067 for(int k=0; k<term.size(); k++) {
1068 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
1069 FlagDescriptor fd=dfa.getFlag();
1070 boolean negated=dfa.getNegated();
1071 int flagid=1<<((Integer)flags.get(fd)).intValue();
1076 output.print("0x"+Integer.toHexString(andmask)+", 0x"+Integer.toHexString(checkmask));
1078 output.println("};");
1081 output.println("int parametertag_"+i+"_"+task.getSafeSymbol()+"[]={");
1082 //BUG...added next line to fix, test with any task program
1083 if (param_tag!=null)
1084 for(int j=0; j<param_tag.numTags(); j++) {
1086 output.println(",");
1087 /* for each tag we need */
1088 /* which slot it is */
1089 /* what type it is */
1090 TagVarDescriptor tvd=(TagVarDescriptor)task.getParameterTable().get(param_tag.getName(j));
1091 TempDescriptor tmp=param_tag.getTemp(j);
1092 int slot=fm.getTagInt(tmp);
1093 output.println(slot+", "+state.getTagId(tvd.getTag()));
1095 output.println("};");
1097 output.println("struct parameterdescriptor parameter_"+i+"_"+task.getSafeSymbol()+"={");
1098 output.println("/* type */"+param_type.getClassDesc().getId()+",");
1099 output.println("/* number of DNF terms */"+dnfterms+",");
1100 output.println("parameterdnf_"+i+"_"+task.getSafeSymbol()+",");
1101 output.println("0,");
1102 //BUG, added next line to fix and else statement...test
1103 //with any task program
1104 if (param_tag!=null)
1105 output.println("/* number of tags */"+param_tag.numTags()+",");
1107 output.println("/* number of tags */ 0,");
1108 output.println("parametertag_"+i+"_"+task.getSafeSymbol());
1109 output.println("};");
1113 output.println("struct parameterdescriptor * parameterdescriptors_"+task.getSafeSymbol()+"[] = {");
1114 for (int i=0; i<task.numParameters(); i++) {
1116 output.println(",");
1117 output.print("¶meter_"+i+"_"+task.getSafeSymbol());
1119 output.println("};");
1121 output.println("struct taskdescriptor task_"+task.getSafeSymbol()+"={");
1122 output.println("&"+task.getSafeSymbol()+",");
1123 output.println("/* number of parameters */" +task.numParameters() + ",");
1124 int numtotal=task.numParameters()+fm.numTags();
1125 output.println("/* number total parameters */" +numtotal + ",");
1126 output.println("parameterdescriptors_"+task.getSafeSymbol()+",");
1127 output.println("\""+task.getSymbol()+"\"");
1128 output.println("};");
1132 /** The buildVirtualTables method outputs the virtual dispatch
1133 * tables for methods. */
1135 protected void buildVirtualTables(PrintWriter outvirtual) {
1136 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
1137 while(classit.hasNext()) {
1138 ClassDescriptor cd=(ClassDescriptor)classit.next();
1139 if (virtualcalls.getMethodCount(cd)>maxcount)
1140 maxcount=virtualcalls.getMethodCount(cd);
1142 MethodDescriptor[][] virtualtable=null;
1143 LocalityBinding[][] lbvirtualtable=null;
1144 if (state.DSM||state.SINGLETM)
1145 lbvirtualtable=new LocalityBinding[state.numClasses()+state.numArrays()][maxcount];
1147 virtualtable=new MethodDescriptor[state.numClasses()+state.numArrays()][maxcount];
1149 /* Fill in virtual table */
1150 classit=state.getClassSymbolTable().getDescriptorsIterator();
1151 while(classit.hasNext()) {
1152 ClassDescriptor cd=(ClassDescriptor)classit.next();
1153 if (state.DSM||state.SINGLETM)
1154 fillinRow(cd, lbvirtualtable, cd.getId());
1156 fillinRow(cd, virtualtable, cd.getId());
1159 ClassDescriptor objectcd=typeutil.getClass(TypeUtil.ObjectClass);
1160 Iterator arrayit=state.getArrayIterator();
1161 while(arrayit.hasNext()) {
1162 TypeDescriptor td=(TypeDescriptor)arrayit.next();
1163 int id=state.getArrayNumber(td);
1164 if (state.DSM||state.SINGLETM)
1165 fillinRow(objectcd, lbvirtualtable, id+state.numClasses());
1167 fillinRow(objectcd, virtualtable, id+state.numClasses());
1170 outvirtual.print("void * virtualtable[]={");
1171 boolean needcomma=false;
1172 for(int i=0; i<state.numClasses()+state.numArrays(); i++) {
1173 for(int j=0; j<maxcount; j++) {
1175 outvirtual.print(", ");
1176 if ((state.DSM||state.SINGLETM)&&lbvirtualtable[i][j]!=null) {
1177 LocalityBinding lb=lbvirtualtable[i][j];
1178 MethodDescriptor md=lb.getMethod();
1179 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
1180 } else if (!(state.DSM||state.SINGLETM)&&virtualtable[i][j]!=null) {
1181 MethodDescriptor md=virtualtable[i][j];
1182 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
1184 outvirtual.print("0");
1188 outvirtual.println("");
1190 outvirtual.println("};");
1194 private void fillinRow(ClassDescriptor cd, MethodDescriptor[][] virtualtable, int rownum) {
1195 /* Get inherited methods */
1196 if (cd.getSuperDesc()!=null)
1197 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
1199 // TODO add version for normal Java later
1200 Iterator it_sifs = cd.getSuperInterfaces();
1201 while(it_sifs.hasNext()) {
1202 ClassDescriptor superif = (ClassDescriptor)it_sifs.next();
1203 fillinRow(superif, virtualtable, rownum);
1206 /* Override them with our methods */
1207 for(Iterator it=cd.getMethods(); it.hasNext();) {
1208 MethodDescriptor md=(MethodDescriptor)it.next();
1209 if (md.isStatic()||md.getReturnType()==null)
1211 int methodnum=virtualcalls.getMethodNumber(md);
1212 virtualtable[rownum][methodnum]=md;
1216 private void fillinRow(ClassDescriptor cd, LocalityBinding[][] virtualtable, int rownum) {
1217 /* Get inherited methods */
1218 if (cd.getSuperDesc()!=null)
1219 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
1220 /* Override them with our methods */
1221 if (locality.getClassBindings(cd)!=null)
1222 for(Iterator<LocalityBinding> lbit=locality.getClassBindings(cd).iterator(); lbit.hasNext();) {
1223 LocalityBinding lb=lbit.next();
1224 MethodDescriptor md=lb.getMethod();
1225 //Is the method static or a constructor
1226 if (md.isStatic()||md.getReturnType()==null)
1228 int methodnum=virtualcalls.getLocalityNumber(lb);
1229 virtualtable[rownum][methodnum]=lb;
1233 /** Generate array that contains the sizes of class objects. The
1234 * object allocation functions in the runtime use this
1237 private void generateSizeArray(PrintWriter outclassdefs) {
1238 outclassdefs.print("extern struct prefetchCountStats * evalPrefetch;\n");
1239 outclassdefs.print("#ifdef TRANSSTATS \n");
1240 outclassdefs.print("extern int numTransAbort;\n");
1241 outclassdefs.print("extern int numTransCommit;\n");
1242 outclassdefs.print("extern int nSoftAbort;\n");
1244 outclassdefs.print("extern int nchashSearch;\n");
1245 outclassdefs.print("extern int nmhashSearch;\n");
1246 outclassdefs.print("extern int nprehashSearch;\n");
1247 outclassdefs.print("extern int ndirtyCacheObj;\n");
1248 outclassdefs.print("extern int nRemoteSend;\n");
1249 outclassdefs.print("extern int sendRemoteReq;\n");
1250 outclassdefs.print("extern int getResponse;\n");
1251 outclassdefs.print("extern int bytesSent;\n");
1252 outclassdefs.print("extern int bytesRecv;\n");
1253 outclassdefs.print("extern int totalObjSize;\n");
1254 outclassdefs.print("extern void handle();\n");
1255 } else if (state.SINGLETM) {
1256 outclassdefs.println("extern int nSoftAbortAbort;");
1257 outclassdefs.println("extern int nSoftAbortCommit;");
1258 outclassdefs.println("#ifdef STMSTATS\n");
1259 outclassdefs.println("extern objtypestat_t typesCausingAbort[];");
1260 outclassdefs.println("#endif\n");
1262 outclassdefs.print("#endif\n");
1264 outclassdefs.print("int numprefetchsites = " + pa.prefetchsiteid + ";\n");
1265 if(this.state.MLP || state.OOOJAVA ){
1266 outclassdefs.print("extern __thread int oid;\n");
1267 outclassdefs.print("extern int numWorkSchedWorkers;\n");
1270 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1271 cdarray=new ClassDescriptor[state.numClasses()];
1273 while(it.hasNext()) {
1274 ClassDescriptor cd=(ClassDescriptor)it.next();
1275 cdarray[cd.getId()]=cd;
1278 arraytable=new TypeDescriptor[state.numArrays()];
1280 Iterator arrayit=state.getArrayIterator();
1281 while(arrayit.hasNext()) {
1282 TypeDescriptor td=(TypeDescriptor)arrayit.next();
1283 int id=state.getArrayNumber(td);
1289 /* Print out types */
1290 outclassdefs.println("/* ");
1291 for(int i=0; i<state.numClasses(); i++) {
1292 ClassDescriptor cd=cdarray[i];
1294 outclassdefs.println("NULL " + i);
1296 outclassdefs.println(cd +" "+i);
1300 for(int i=0; i<state.numArrays(); i++) {
1301 TypeDescriptor arraytd=arraytable[i];
1302 outclassdefs.println(arraytd.toPrettyString() +" "+(i+state.numClasses()));
1305 outclassdefs.println("*/");
1308 outclassdefs.print("int classsize[]={");
1310 boolean needcomma=false;
1311 for(int i=0; i<state.numClasses(); i++) {
1313 outclassdefs.print(", ");
1315 outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")");
1317 outclassdefs.print("0");
1323 for(int i=0; i<state.numArrays(); i++) {
1325 outclassdefs.print(", ");
1326 TypeDescriptor tdelement=arraytable[i].dereference();
1327 if (tdelement.isArray()||tdelement.isClass())
1328 outclassdefs.print("sizeof(void *)");
1330 outclassdefs.print("sizeof("+tdelement.getSafeSymbol()+")");
1334 outclassdefs.println("};");
1336 ClassDescriptor objectclass=typeutil.getClass(TypeUtil.ObjectClass);
1338 outclassdefs.print("int typearray[]={");
1339 for(int i=0; i<state.numClasses(); i++) {
1340 ClassDescriptor cd=cdarray[i];
1341 ClassDescriptor supercd=i>0?cd.getSuperDesc():null;
1343 outclassdefs.print(", ");
1345 outclassdefs.print("-1");
1347 outclassdefs.print(supercd.getId());
1351 for(int i=0; i<state.numArrays(); i++) {
1352 TypeDescriptor arraytd=arraytable[i];
1353 ClassDescriptor arraycd=arraytd.getClassDesc();
1354 if (arraycd==null) {
1356 outclassdefs.print(", ");
1357 outclassdefs.print(objectclass.getId());
1361 ClassDescriptor cd=arraycd.getSuperDesc();
1364 TypeDescriptor supertd=new TypeDescriptor(cd);
1365 supertd.setArrayCount(arraytd.getArrayCount());
1366 type=state.getArrayNumber(supertd);
1368 type+=state.numClasses();
1371 cd=cd.getSuperDesc();
1374 outclassdefs.print(", ");
1375 outclassdefs.print(type);
1379 outclassdefs.println("};");
1384 outclassdefs.print("int typearray2[]={");
1385 for(int i=0; i<state.numArrays(); i++) {
1386 TypeDescriptor arraytd=arraytable[i];
1387 ClassDescriptor arraycd=arraytd.getClassDesc();
1388 if (arraycd==null) {
1390 outclassdefs.print(", ");
1391 outclassdefs.print("-1");
1395 ClassDescriptor cd=arraycd.getSuperDesc();
1396 int level=arraytd.getArrayCount()-1;
1398 for(; level>0; level--) {
1399 TypeDescriptor supertd=new TypeDescriptor(objectclass);
1400 supertd.setArrayCount(level);
1401 type=state.getArrayNumber(supertd);
1403 type+=state.numClasses();
1408 outclassdefs.print(", ");
1409 outclassdefs.print(type);
1413 outclassdefs.println("};");
1416 /** Constructs params and temp objects for each method or task.
1417 * These objects tell the compiler which temps need to be
1420 protected void generateTempStructs(FlatMethod fm, LocalityBinding lb) {
1421 MethodDescriptor md=fm.getMethod();
1422 TaskDescriptor task=fm.getTask();
1423 Set<TempDescriptor> saveset=lb!=null ? locality.getTempSet(lb) : null;
1424 ParamsObject objectparams=md!=null ? new ParamsObject(md,tag++) : new ParamsObject(task, tag++);
1426 paramstable.put(lb, objectparams);
1427 backuptable.put(lb, new Hashtable<TempDescriptor, TempDescriptor>());
1428 } else if (md!=null)
1429 paramstable.put(md, objectparams);
1431 paramstable.put(task, objectparams);
1433 for(int i=0; i<fm.numParameters(); i++) {
1434 TempDescriptor temp=fm.getParameter(i);
1435 TypeDescriptor type=temp.getType();
1436 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1437 objectparams.addPtr(temp);
1439 objectparams.addPrim(temp);
1440 if(lb!=null&&saveset.contains(temp)) {
1441 backuptable.get(lb).put(temp, temp.createNew());
1445 for(int i=0; i<fm.numTags(); i++) {
1446 TempDescriptor temp=fm.getTag(i);
1447 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1448 objectparams.addPtr(temp);
1450 objectparams.addPrim(temp);
1453 TempObject objecttemps=md!=null ? new TempObject(objectparams,md,tag++) : new TempObject(objectparams, task, tag++);
1455 tempstable.put(lb, objecttemps);
1457 tempstable.put(md, objecttemps);
1459 tempstable.put(task, objecttemps);
1461 for(Iterator nodeit=fm.getNodeSet().iterator(); nodeit.hasNext();) {
1462 FlatNode fn=(FlatNode)nodeit.next();
1463 TempDescriptor[] writes=fn.writesTemps();
1464 for(int i=0; i<writes.length; i++) {
1465 TempDescriptor temp=writes[i];
1466 TypeDescriptor type=temp.getType();
1467 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1468 objecttemps.addPtr(temp);
1470 objecttemps.addPrim(temp);
1471 if(lb!=null&&saveset.contains(temp)&&
1472 !backuptable.get(lb).containsKey(temp))
1473 backuptable.get(lb).put(temp, temp.createNew());
1477 /* Create backup temps */
1479 for(Iterator<TempDescriptor> tmpit=backuptable.get(lb).values().iterator(); tmpit.hasNext();) {
1480 TempDescriptor tmp=tmpit.next();
1481 TypeDescriptor type=tmp.getType();
1482 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1483 objecttemps.addPtr(tmp);
1485 objecttemps.addPrim(tmp);
1487 /* Create temp to hold revert table */
1488 if (state.DSM&&(lb.getHasAtomic()||lb.isAtomic())) {
1489 TempDescriptor reverttmp=new TempDescriptor("revertlist", typeutil.getClass(TypeUtil.ObjectClass));
1490 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1491 objecttemps.addPtr(reverttmp);
1493 objecttemps.addPrim(reverttmp);
1494 reverttable.put(lb, reverttmp);
1499 /** This method outputs the following information about classes
1501 * (1) For classes, what are the locations of pointers.
1502 * (2) For arrays, does the array contain pointers or primitives.
1503 * (3) For classes, does the class contain flags.
1506 private void generateLayoutStructs(PrintWriter output) {
1507 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1508 while(it.hasNext()) {
1509 ClassDescriptor cn=(ClassDescriptor)it.next();
1510 output.println("unsigned INTPTR "+cn.getSafeSymbol()+"_pointers[]={");
1511 Iterator allit=cn.getFieldTable().getAllDescriptorsIterator();
1513 while(allit.hasNext()) {
1514 FieldDescriptor fd=(FieldDescriptor)allit.next();
1515 TypeDescriptor type=fd.getType();
1516 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1521 output.print(count);
1522 allit=cn.getFieldTable().getAllDescriptorsIterator();
1523 while(allit.hasNext()) {
1524 FieldDescriptor fd=(FieldDescriptor)allit.next();
1525 TypeDescriptor type=fd.getType();
1526 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1529 output.println(",");
1530 output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+fd.getSafeSymbol()+"))");
1533 output.println("};");
1535 output.println("unsigned INTPTR * pointerarray[]={");
1536 boolean needcomma=false;
1537 for(int i=0; i<state.numClasses(); i++) {
1538 ClassDescriptor cn=cdarray[i];
1540 output.println(",");
1543 output.print(cn.getSafeSymbol()+"_pointers");
1545 output.print("NULL");
1549 for(int i=0; i<state.numArrays(); i++) {
1551 output.println(", ");
1552 TypeDescriptor tdelement=arraytable[i].dereference();
1553 if (tdelement.isArray()||tdelement.isClass())
1554 output.print("((unsigned INTPTR *)1)");
1560 output.println("};");
1562 output.println("int hasflags[]={");
1563 for(int i=0; i<state.numClasses(); i++) {
1564 ClassDescriptor cn=cdarray[i];
1566 output.println(", ");
1568 if ((cn != null) && (cn.hasFlags()))
1573 output.println("};");
1576 /** Print out table to give us supertypes */
1577 private void generateSuperTypeTable(PrintWriter output) {
1578 output.println("int supertypes[]={");
1579 boolean needcomma=false;
1580 for(int i=0; i<state.numClasses(); i++) {
1581 ClassDescriptor cn=cdarray[i];
1583 output.println(",");
1585 if ((cn != null) && (cn.getSuperDesc()!=null)) {
1586 ClassDescriptor cdsuper=cn.getSuperDesc();
1587 output.print(cdsuper.getId());
1591 output.println("};");
1594 /** Force consistent field ordering between inherited classes. */
1596 private void printClassStruct(ClassDescriptor cn, PrintWriter classdefout, PrintWriter globaldefout) {
1598 ClassDescriptor sp=cn.getSuperDesc();
1600 printClassStruct(sp, classdefout, globaldefout);
1602 if (!fieldorder.containsKey(cn)) {
1603 Vector fields=new Vector();
1604 fieldorder.put(cn,fields);
1605 Vector fieldvec=cn.getFieldVec();
1606 for(int i=0;i<fieldvec.size();i++) {
1607 FieldDescriptor fd=(FieldDescriptor)fieldvec.get(i);
1608 if ((sp==null||!sp.getFieldTable().contains(fd.getSymbol())))
1612 Vector fields=(Vector)fieldorder.get(cn);
1614 for(int i=0; i<fields.size(); i++) {
1615 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
1616 if (fd.getType().isClass()||fd.getType().isArray())
1617 classdefout.println(" struct "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1618 else if ((state.MGC) && (fd.isStatic())) {
1619 // TODO add version for normal Java later
1621 globaldefout.println(" "+fd.getType().getSafeSymbol()+ " "+cn.getSafeSymbol()+fd.getSafeSymbol()+";");
1622 classdefout.println(" "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1624 classdefout.println(" "+fd.getType().getSafeSymbol()+" "+fd.getSafeSymbol()+";");
1629 /* Map flags to integers consistently between inherited
1632 protected void mapFlags(ClassDescriptor cn) {
1633 ClassDescriptor sp=cn.getSuperDesc();
1637 if (!flagorder.containsKey(cn)) {
1638 Hashtable flags=new Hashtable();
1639 flagorder.put(cn,flags);
1641 Hashtable superflags=(Hashtable)flagorder.get(sp);
1642 Iterator superflagit=superflags.keySet().iterator();
1643 while(superflagit.hasNext()) {
1644 FlagDescriptor fd=(FlagDescriptor)superflagit.next();
1645 Integer number=(Integer)superflags.get(fd);
1646 flags.put(fd, number);
1647 if ((number.intValue()+1)>max)
1648 max=number.intValue()+1;
1652 Iterator flagit=cn.getFlags();
1653 while(flagit.hasNext()) {
1654 FlagDescriptor fd=(FlagDescriptor)flagit.next();
1655 if (sp==null||!sp.getFlagTable().contains(fd.getSymbol()))
1656 flags.put(fd, new Integer(max++));
1662 /** This function outputs (1) structures that parameters are
1663 * passed in (when PRECISE GC is enabled) and (2) function
1664 * prototypes for the methods */
1666 protected void generateCallStructs(ClassDescriptor cn, PrintWriter classdefout, PrintWriter output, PrintWriter headersout, PrintWriter globaldefout) {
1667 /* Output class structure */
1668 classdefout.println("struct "+cn.getSafeSymbol()+" {");
1669 classdefout.println(" int type;");
1670 if(state.MLP || state.OOOJAVA){
1671 classdefout.println(" int oid;");
1672 classdefout.println(" int allocsite;");
1674 if (state.EVENTMONITOR) {
1675 classdefout.println(" int objuid;");
1678 classdefout.println(" pthread_t tid;");
1679 classdefout.println(" void * lockentry;");
1680 classdefout.println(" int lockcount;");
1683 classdefout.println(" int mutex;");
1684 classdefout.println(" int objlock;");
1685 if(state.MULTICOREGC) {
1686 classdefout.println(" int marked;");
1690 classdefout.println(" int flag;");
1691 if((!state.MULTICORE) || (cn.getSymbol().equals("TagDescriptor"))) {
1692 classdefout.println(" void * flagptr;");
1693 } else if (state.MULTICORE) {
1694 classdefout.println(" int version;");
1695 classdefout.println(" int * lock;"); // lock entry for this obj
1696 classdefout.println(" int mutex;");
1697 classdefout.println(" int lockcount;");
1698 if(state.MULTICOREGC) {
1699 classdefout.println(" int marked;");
1702 if (state.OPTIONAL) {
1703 classdefout.println(" int numfses;");
1704 classdefout.println(" int * fses;");
1707 printClassStruct(cn, classdefout, globaldefout);
1708 classdefout.println("};\n");
1710 if (state.DSM||state.SINGLETM) {
1711 /* Cycle through LocalityBindings */
1712 HashSet<MethodDescriptor> nativemethods=new HashSet<MethodDescriptor>();
1713 Set<LocalityBinding> lbset=locality.getClassBindings(cn);
1715 for(Iterator<LocalityBinding> lbit=lbset.iterator(); lbit.hasNext();) {
1716 LocalityBinding lb=lbit.next();
1717 MethodDescriptor md=lb.getMethod();
1718 if (md.getModifiers().isNative()) {
1719 //make sure we only print a native method once
1720 if (nativemethods.contains(md)) {
1721 FlatMethod fm=state.getMethodFlat(md);
1722 generateTempStructs(fm, lb);
1725 nativemethods.add(md);
1727 generateMethod(cn, md, lb, headersout, output);
1730 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1731 MethodDescriptor md=(MethodDescriptor)methodit.next();
1732 if (md.getModifiers().isNative()&&!nativemethods.contains(md)) {
1733 //Need to build param structure for library code
1734 FlatMethod fm=state.getMethodFlat(md);
1735 generateTempStructs(fm, null);
1736 generateMethodParam(cn, md, null, output);
1741 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1742 MethodDescriptor md=(MethodDescriptor)methodit.next();
1743 generateMethod(cn, md, null, headersout, output);
1747 private void generateMethodParam(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter output) {
1748 /* Output parameter structure */
1749 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1750 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1751 if ((state.DSM||state.SINGLETM)&&lb!=null)
1752 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1754 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1755 output.println(" int size;");
1756 output.println(" void * next;");
1757 for(int i=0; i<objectparams.numPointers(); i++) {
1758 TempDescriptor temp=objectparams.getPointer(i);
1759 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1761 output.println("};\n");
1765 private void generateMethod(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter headersout, PrintWriter output) {
1766 FlatMethod fm=state.getMethodFlat(md);
1767 generateTempStructs(fm, lb);
1769 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1770 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md);
1772 generateMethodParam(cn, md, lb, output);
1774 /* Output temp structure */
1775 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1776 if (state.DSM||state.SINGLETM)
1777 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1779 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1780 output.println(" int size;");
1781 output.println(" void * next;");
1782 for(int i=0; i<objecttemps.numPointers(); i++) {
1783 TempDescriptor temp=objecttemps.getPointer(i);
1784 if (temp.getType().isNull())
1785 output.println(" void * "+temp.getSafeSymbol()+";");
1787 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1789 output.println("};\n");
1792 /********* Output method declaration ***********/
1793 if (state.DSM||state.SINGLETM) {
1794 headersout.println("#define D"+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1796 headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1798 /* First the return type */
1799 if (md.getReturnType()!=null) {
1800 if (md.getReturnType().isClass()||md.getReturnType().isArray())
1801 headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1803 headersout.print(md.getReturnType().getSafeSymbol()+" ");
1805 //catch the constructor case
1806 headersout.print("void ");
1808 /* Next the method name */
1809 if (state.DSM||state.SINGLETM) {
1810 headersout.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1812 headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1814 boolean printcomma=false;
1815 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1816 if (state.DSM||state.SINGLETM) {
1817 headersout.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1819 headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1823 /* Output parameter list*/
1824 for(int i=0; i<objectparams.numPrimitives(); i++) {
1825 TempDescriptor temp=objectparams.getPrimitive(i);
1827 headersout.print(", ");
1829 if (temp.getType().isClass()||temp.getType().isArray())
1830 headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1832 headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1834 headersout.println(");\n");
1838 /** This function outputs (1) structures that parameters are
1839 * passed in (when PRECISE GC is enabled) and (2) function
1840 * prototypes for the tasks */
1842 private void generateTaskStructs(PrintWriter output, PrintWriter headersout) {
1843 /* Cycle through tasks */
1844 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
1846 while(taskit.hasNext()) {
1847 /* Classify parameters */
1848 TaskDescriptor task=(TaskDescriptor)taskit.next();
1849 FlatMethod fm=state.getMethodFlat(task);
1850 generateTempStructs(fm, null);
1852 ParamsObject objectparams=(ParamsObject) paramstable.get(task);
1853 TempObject objecttemps=(TempObject) tempstable.get(task);
1855 /* Output parameter structure */
1856 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1857 output.println("struct "+task.getSafeSymbol()+"_params {");
1858 output.println(" int size;");
1859 output.println(" void * next;");
1860 for(int i=0; i<objectparams.numPointers(); i++) {
1861 TempDescriptor temp=objectparams.getPointer(i);
1862 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1865 output.println("};\n");
1866 if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
1867 maxtaskparams=objectparams.numPointers()+fm.numTags();
1871 /* Output temp structure */
1872 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1873 output.println("struct "+task.getSafeSymbol()+"_locals {");
1874 output.println(" int size;");
1875 output.println(" void * next;");
1876 for(int i=0; i<objecttemps.numPointers(); i++) {
1877 TempDescriptor temp=objecttemps.getPointer(i);
1878 if (temp.getType().isNull())
1879 output.println(" void * "+temp.getSafeSymbol()+";");
1880 else if(temp.getType().isTag())
1881 output.println(" struct "+
1882 (new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1884 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1886 output.println("};\n");
1889 /* Output task declaration */
1890 headersout.print("void " + task.getSafeSymbol()+"(");
1892 boolean printcomma=false;
1893 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1894 headersout.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
1896 headersout.print("void * parameterarray[]");
1897 headersout.println(");\n");
1901 /***** Generate code for FlatMethod fm. *****/
1903 Hashtable<FlatAtomicEnterNode, AtomicRecord> atomicmethodmap;
1904 static int atomicmethodcount=0;
1907 BranchAnalysis branchanalysis;
1908 private void generateFlatMethod(FlatMethod fm, LocalityBinding lb, PrintWriter output) {
1909 if (State.PRINTFLAT)
1910 System.out.println(fm.printMethod());
1911 MethodDescriptor md=fm.getMethod();
1912 TaskDescriptor task=fm.getTask();
1913 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
1914 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : md!=null ? md : task);
1916 HashSet<AtomicRecord> arset=null;
1917 branchanalysis=null;
1919 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1921 if (atomicmethodmap==null)
1922 atomicmethodmap=new Hashtable<FlatAtomicEnterNode, AtomicRecord>();
1924 //fix these so we get right strings for local variables
1925 localsprefixaddr=localsprefix;
1926 localsprefixderef=localsprefix+"->";
1927 arset=new HashSet<AtomicRecord>();
1929 //build branchanalysis
1930 branchanalysis=new BranchAnalysis(locality, lb, delaycomp.getNotReady(lb), delaycomp.livecode(lb), state);
1932 //Generate commit methods here
1933 for(Iterator<FlatNode> fnit=fm.getNodeSet().iterator();fnit.hasNext();) {
1934 FlatNode fn=fnit.next();
1935 if (fn.kind()==FKind.FlatAtomicEnterNode&&
1936 locality.getAtomic(lb).get(fn.getPrev(0)).intValue()==0&&
1937 delaycomp.needsFission(lb, (FlatAtomicEnterNode) fn)) {
1938 //We have an atomic enter
1939 FlatAtomicEnterNode faen=(FlatAtomicEnterNode) fn;
1940 Set<FlatNode> exitset=faen.getExits();
1942 String methodname=md.getSymbol()+(atomicmethodcount++);
1943 AtomicRecord ar=new AtomicRecord();
1947 atomicmethodmap.put(faen, ar);
1949 //build data structure declaration
1950 output.println("struct atomicprimitives_"+methodname+" {");
1952 Set<FlatNode> recordset=delaycomp.livecode(lb);
1953 Set<TempDescriptor> liveinto=delaycomp.liveinto(lb, faen, recordset);
1954 Set<TempDescriptor> liveout=delaycomp.liveout(lb, faen);
1955 Set<TempDescriptor> liveoutvirtualread=delaycomp.liveoutvirtualread(lb, faen);
1957 ar.reallivein=new HashSet(liveinto);
1959 ar.liveoutvirtualread=liveoutvirtualread;
1962 for(Iterator<TempDescriptor> it=liveinto.iterator(); it.hasNext();) {
1963 TempDescriptor tmp=it.next();
1964 //remove the pointers
1965 if (tmp.getType().isPtr()) {
1968 //let's print it here
1969 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1972 for(Iterator<TempDescriptor> it=liveout.iterator(); it.hasNext();) {
1973 TempDescriptor tmp=it.next();
1974 //remove the pointers
1975 if (tmp.getType().isPtr()) {
1977 } else if (!liveinto.contains(tmp)) {
1978 //let's print it here
1979 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1982 output.println("};");
1984 //print out method name
1985 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) {");
1986 //build code for commit method
1988 //first define local primitives
1989 Set<TempDescriptor> alltemps=delaycomp.alltemps(lb, faen, recordset);
1990 for(Iterator<TempDescriptor> tmpit=alltemps.iterator();tmpit.hasNext();) {
1991 TempDescriptor tmp=tmpit.next();
1992 if (!tmp.getType().isPtr()) {
1993 if (liveinto.contains(tmp)||liveoutvirtualread.contains(tmp)) {
1994 //read from live into set
1995 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+"=primitives->"+tmp.getSafeSymbol()+";");
1998 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
2002 //turn off write barrier generation
2004 state.SINGLETM=false;
2005 generateCode(faen, fm, lb, exitset, output, false);
2006 state.SINGLETM=true;
2007 //turn on write barrier generation
2009 output.println("}\n\n");
2013 //redefine these back to normal
2015 localsprefixaddr="&"+localsprefix;
2016 localsprefixderef=localsprefix+".";
2018 generateHeader(fm, lb, md!=null ? md : task,output);
2019 TempObject objecttemp=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
2021 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
2022 for(Iterator<AtomicRecord> arit=arset.iterator();arit.hasNext();) {
2023 AtomicRecord ar=arit.next();
2024 output.println("struct atomicprimitives_"+ar.name+" primitives_"+ar.name+";");
2028 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2029 if (md!=null&&(state.DSM||state.SINGLETM))
2030 output.print(" struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
2031 else if (md!=null&&!(state.DSM||state.SINGLETM))
2032 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
2034 output.print(" struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={");
2035 output.print(objecttemp.numPointers()+",");
2036 output.print(paramsprefix);
2037 for(int j=0; j<objecttemp.numPointers(); j++)
2038 output.print(", NULL");
2039 output.println("};");
2042 for(int i=0; i<objecttemp.numPrimitives(); i++) {
2043 TempDescriptor td=objecttemp.getPrimitive(i);
2044 TypeDescriptor type=td.getType();
2046 output.println(" void * "+td.getSafeSymbol()+";");
2047 else if (type.isClass()||type.isArray())
2048 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
2050 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
2054 if( state.MLP || state.OOOJAVA ) {
2055 if( fm.getNext(0) instanceof FlatSESEEnterNode ) {
2056 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
2057 if( (state.MLP && callerSESEplaceholder != mlpa.getMainSESE()) ||
2058 (state.OOOJAVA && callerSESEplaceholder != oooa.getMainSESE())
2060 // declare variables for naming static SESE's
2061 output.println(" /* static SESE names */");
2062 Iterator<SESEandAgePair> pItr = callerSESEplaceholder.getNeededStaticNames().iterator();
2063 while( pItr.hasNext() ) {
2064 SESEandAgePair pair = pItr.next();
2065 output.println(" void* "+pair+" = NULL;");
2068 // declare variables for tracking dynamic sources
2069 output.println(" /* dynamic variable sources */");
2070 Iterator<TempDescriptor> dynSrcItr = callerSESEplaceholder.getDynamicVarSet().iterator();
2071 while( dynSrcItr.hasNext() ) {
2072 TempDescriptor dynSrcVar = dynSrcItr.next();
2073 output.println(" SESEcommon* "+dynSrcVar+"_srcSESE = NULL;");
2074 output.println(" INTPTR "+dynSrcVar+"_srcOffset = 0x1;");
2079 // set up related allocation sites's waiting queues
2082 ConflictGraph graph = null;
2083 graph = mlpa.getConflictGraphResults().get(fm);
2084 if (graph != null && graph.hasConflictEdge()) {
2085 output.println(" /* set up waiting queues */");
2086 output.println(" int numMemoryQueue=0;");
2087 output.println(" int memoryQueueItemID=0;");
2088 HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
2090 System.out.println("#lockSet="+lockSet.hashCode());
2091 System.out.println("lockset="+lockSet);
2092 for (Iterator iterator = lockSet.iterator(); iterator.hasNext();) {
2093 SESELock seseLock = (SESELock) iterator.next();
2094 System.out.println("id="+seseLock.getID());
2095 System.out.println("#="+seseLock);
2097 System.out.println("size="+lockSet.size());
2098 if (lockSet.size() > 0) {
2099 output.println(" numMemoryQueue=" + lockSet.size() + ";");
2100 output.println(" runningSESE->numMemoryQueue=numMemoryQueue;");
2101 output.println(" runningSESE->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2106 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
2107 if(callerSESEplaceholder!= oooa.getMainSESE()){
2108 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(callerSESEplaceholder);
2109 if (graph != null && graph.hasConflictEdge()) {
2110 output.println(" // set up waiting queues ");
2111 output.println(" int numMemoryQueue=0;");
2112 output.println(" int memoryQueueItemID=0;");
2113 Set<Analysis.OoOJava.SESELock> lockSet = oooa.getLockMappings(graph);
2114 System.out.println("#lockSet="+lockSet.hashCode());
2115 System.out.println("lockset="+lockSet);
2116 for (Iterator iterator = lockSet.iterator(); iterator.hasNext();) {
2117 Analysis.OoOJava.SESELock seseLock = (Analysis.OoOJava.SESELock) iterator.next();
2118 System.out.println("id="+seseLock.getID());
2119 System.out.println("#="+seseLock);
2121 System.out.println("size="+lockSet.size());
2122 if (lockSet.size() > 0) {
2123 output.println(" numMemoryQueue=" + lockSet.size() + ";");
2124 output.println(" runningSESE->numMemoryQueue=numMemoryQueue;");
2125 output.println(" runningSESE->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2135 /* Check to see if we need to do a GC if this is a
2136 * multi-threaded program...*/
2138 if (((state.MLP||state.OOOJAVA||state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
2139 || this.state.MULTICOREGC) {
2140 //Don't bother if we aren't in recursive methods...The loops case will catch it
2141 if (callgraph.getAllMethods(md).contains(md)) {
2142 if (state.DSM&&lb.isAtomic())
2143 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
2144 else if (this.state.MULTICOREGC) {
2145 output.println("if(gcflag) gc("+localsprefixaddr+");");
2147 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2153 // TODO add version for normal Java later
2154 if(fm.getMethod().isStaticBlock()) {
2155 // a static block, check if it has been executed
2156 output.println(" if(global_defs_p->" + cn.getSafeSymbol()+"static_block_exe_flag != 0) {");
2157 output.println(" return;");
2158 output.println(" }");
2161 if((!fm.getMethod().isStaticBlock()) && (fm.getMethod().getReturnType() == null) && (cn != null)){
2162 // is a constructor, check and output initialization of the static fields
2163 // here does not initialize the static fields of the class, instead it
2164 // redirect the corresponding fields in the object to the global_defs_p
2165 Vector fields=(Vector)fieldorder.get(cn);
2167 for(int i=0; i<fields.size(); i++) {
2168 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
2171 output.println(generateTemp(fm,fm.getParameter(0),lb)+"->"+fd.getSafeSymbol()+"=&(global_defs_p->"+cn.getSafeSymbol()+fd.getSafeSymbol()+");");
2177 generateCode(fm.getNext(0), fm, lb, null, output, true);
2179 output.println("}\n\n");
2183 protected void initializeSESE( FlatSESEEnterNode fsen ) {
2185 FlatMethod fm = fsen.getfmEnclosing();
2186 MethodDescriptor md = fm.getMethod();
2187 ClassDescriptor cn = md.getClassDesc();
2190 // Creates bogus method descriptor to index into tables
2191 Modifiers modBogus = new Modifiers();
2192 MethodDescriptor mdBogus =
2193 new MethodDescriptor( modBogus,
2194 new TypeDescriptor( TypeDescriptor.VOID ),
2195 "sese_"+fsen.getPrettyIdentifier()+fsen.getIdentifier()
2198 mdBogus.setClassDesc( fsen.getcdEnclosing() );
2199 FlatMethod fmBogus = new FlatMethod( mdBogus, null );
2200 fsen.setfmBogus( fmBogus );
2201 fsen.setmdBogus( mdBogus );
2203 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
2204 inSetAndOutSet.addAll( fsen.getInVarSet() );
2205 inSetAndOutSet.addAll( fsen.getOutVarSet() );
2207 // Build paramsobj for bogus method descriptor
2208 ParamsObject objectparams = new ParamsObject( mdBogus, tag++ );
2209 paramstable.put( mdBogus, objectparams );
2211 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
2212 while( itr.hasNext() ) {
2213 TempDescriptor temp = itr.next();
2214 TypeDescriptor type = temp.getType();
2215 if( type.isPtr() ) {
2216 objectparams.addPtr( temp );
2218 objectparams.addPrim( temp );
2222 // Build normal temp object for bogus method descriptor
2223 TempObject objecttemps = new TempObject( objectparams, mdBogus, tag++ );
2224 tempstable.put( mdBogus, objecttemps );
2226 for( Iterator nodeit = fsen.getNodeSet().iterator(); nodeit.hasNext(); ) {
2227 FlatNode fn = (FlatNode)nodeit.next();
2228 TempDescriptor[] writes = fn.writesTemps();
2230 for( int i = 0; i < writes.length; i++ ) {
2231 TempDescriptor temp = writes[i];
2232 TypeDescriptor type = temp.getType();
2234 if( type.isPtr() ) {
2235 objecttemps.addPtr( temp );
2237 objecttemps.addPrim( temp );
2243 // used when generating the specific SESE record struct
2244 // to remember the FIRST field name of sese records
2245 // that the current SESE depends on--we need to know the
2246 // offset to the first one for garbage collection
2247 protected void addingDepRecField( FlatSESEEnterNode fsen,
2249 if( fsen.getFirstDepRecField() == null ) {
2250 fsen.setFirstDepRecField( field );
2252 fsen.incNumDepRecs();
2255 protected void generateMethodSESE(FlatSESEEnterNode fsen,
2257 PrintWriter outputStructs,
2258 PrintWriter outputMethHead,
2259 PrintWriter outputMethods
2262 ParamsObject objectparams = (ParamsObject) paramstable.get( fsen.getmdBogus() );
2263 TempObject objecttemps = (TempObject) tempstable .get( fsen.getmdBogus() );
2265 // generate locals structure
2266 outputStructs.println("struct "+
2267 fsen.getcdEnclosing().getSafeSymbol()+
2268 fsen.getmdBogus().getSafeSymbol()+"_"+
2269 fsen.getmdBogus().getSafeMethodDescriptor()+
2271 outputStructs.println(" int size;");
2272 outputStructs.println(" void * next;");
2273 for(int i=0; i<objecttemps.numPointers(); i++) {
2274 TempDescriptor temp=objecttemps.getPointer(i);
2276 if (temp.getType().isNull())
2277 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
2279 outputStructs.println(" struct "+
2280 temp.getType().getSafeSymbol()+" * "+
2281 temp.getSafeSymbol()+";");
2283 outputStructs.println("};\n");
2286 // divide in-set and out-set into objects and primitives to prep
2287 // for the record generation just below
2288 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
2289 inSetAndOutSet.addAll( fsen.getInVarSet() );
2290 inSetAndOutSet.addAll( fsen.getOutVarSet() );
2292 Set<TempDescriptor> inSetAndOutSetObjs = new HashSet<TempDescriptor>();
2293 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
2295 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
2296 while( itr.hasNext() ) {
2297 TempDescriptor temp = itr.next();
2298 TypeDescriptor type = temp.getType();
2299 if( type.isPtr() ) {
2300 inSetAndOutSetObjs.add( temp );
2302 inSetAndOutSetPrims.add( temp );
2307 // generate the SESE record structure
2308 outputStructs.println(fsen.getSESErecordName()+" {");
2310 // data common to any SESE, and it must be placed first so
2311 // a module that doesn't know what kind of SESE record this
2312 // is can cast the pointer to a common struct
2313 outputStructs.println(" SESEcommon common;");
2315 // then garbage list stuff
2316 outputStructs.println(" /* next is in-set and out-set objects that look like a garbage list */");
2317 outputStructs.println(" int size;");
2318 outputStructs.println(" void * next;");
2320 // I think that the set of TempDescriptors inSetAndOutSetObjs
2321 // calculated above should match the pointer object params
2322 // used in the following code, but let's just leave the working
2323 // implementation unless there is actually a problem...
2325 Vector<TempDescriptor> inset=fsen.getInVarsForDynamicCoarseConflictResolution();
2326 for(int i=0; i<inset.size();i++) {
2327 TempDescriptor temp=inset.get(i);
2328 if (temp.getType().isNull())
2329 outputStructs.println(" void * "+temp.getSafeSymbol()+
2330 "; /* in-or-out-set obj in gl */");
2332 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+
2333 temp.getSafeSymbol()+"; /* in-or-out-set obj in gl */");
2336 for(int i=0; i<objectparams.numPointers(); i++) {
2337 TempDescriptor temp=objectparams.getPointer(i);
2338 if (!inset.contains(temp)) {
2339 if (temp.getType().isNull())
2340 outputStructs.println(" void * "+temp.getSafeSymbol()+
2341 "; /* in-or-out-set obj in gl */");
2343 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+
2344 temp.getSafeSymbol()+"; /* in-or-out-set obj in gl */");
2348 outputStructs.println(" /* next is primitives for in-set and out-set and dynamic tracking */");
2350 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
2351 while( itrPrims.hasNext() ) {
2352 TempDescriptor temp = itrPrims.next();
2353 TypeDescriptor type = temp.getType();
2354 if(type.isPrimitive()){
2355 outputStructs.println(" "+temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol()+"; /* in-set or out-set primitive */");
2359 // note that the sese record pointer will be added below, just primitive part of tracking here
2360 Iterator<TempDescriptor> itrDynInVars = fsen.getDynamicInVarSet().iterator();
2361 while( itrDynInVars.hasNext() ) {
2362 TempDescriptor dynInVar = itrDynInVars.next();
2363 outputStructs.println(" INTPTR "+dynInVar+"_srcOffset; /* dynamic tracking primitive */");
2367 outputStructs.println(" /* everything after this should be pointers to an SESE record */" );
2369 // other half of info for dynamic tracking, the SESE record pointer
2370 itrDynInVars = fsen.getDynamicInVarSet().iterator();
2371 while( itrDynInVars.hasNext() ) {
2372 TempDescriptor dynInVar = itrDynInVars.next();
2373 String depRecField = dynInVar+"_srcSESE";
2374 outputStructs.println(" SESEcommon* "+depRecField+";");
2375 addingDepRecField( fsen, depRecField );
2378 // statically known sese sources are record pointers, too
2379 Iterator<SESEandAgePair> itrStaticInVarSrcs = fsen.getStaticInVarSrcs().iterator();
2380 while( itrStaticInVarSrcs.hasNext() ) {
2381 SESEandAgePair srcPair = itrStaticInVarSrcs.next();
2382 outputStructs.println(" "+srcPair.getSESE().getSESErecordName()+"* "+srcPair+";");
2383 addingDepRecField(fsen, srcPair.toString());
2387 if (inset.size()!=0)
2388 outputStructs.println("struct rcrRecord rcrRecords["+inset.size()+"];");
2391 if( fsen.getFirstDepRecField() != null ) {
2392 outputStructs.println(" /* compiler believes first dependent SESE record field above is: "+
2393 fsen.getFirstDepRecField()+" */" );
2395 outputStructs.println("};\n");
2398 // write method declaration to header file
2399 outputMethHead.print("void ");
2400 outputMethHead.print(fsen.getSESEmethodName()+"(");
2401 outputMethHead.print(fsen.getSESErecordName()+"* "+paramsprefix);
2402 outputMethHead.println(");\n");
2405 generateFlatMethodSESE( fsen.getfmBogus(),
2406 fsen.getcdEnclosing(),
2412 private void generateFlatMethodSESE(FlatMethod fm,
2414 FlatSESEEnterNode fsen,
2415 FlatSESEExitNode seseExit,
2419 MethodDescriptor md=fm.getMethod();
2421 output.print("void ");
2422 output.print(fsen.getSESEmethodName()+"(");
2423 output.print(fsen.getSESErecordName()+"* "+paramsprefix);
2424 output.println("){\n");
2427 TempObject objecttemp=(TempObject) tempstable.get(md);
2429 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2430 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
2431 output.print(objecttemp.numPointers()+",");
2432 output.print("&(((SESEcommon*)(___params___))[1])");
2433 for(int j=0; j<objecttemp.numPointers(); j++)
2434 output.print(", NULL");
2435 output.println("};");
2438 output.println(" /* regular local primitives */");
2439 for(int i=0; i<objecttemp.numPrimitives(); i++) {
2440 TempDescriptor td=objecttemp.getPrimitive(i);
2441 TypeDescriptor type=td.getType();
2443 output.println(" void * "+td.getSafeSymbol()+";");
2444 else if (type.isClass()||type.isArray())
2445 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
2447 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
2451 // declare variables for naming static SESE's
2452 output.println(" /* static SESE names */");
2453 Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
2454 while( pItr.hasNext() ) {
2455 SESEandAgePair pair = pItr.next();
2456 output.println(" SESEcommon* "+pair+" = NULL;");
2459 // declare variables for tracking dynamic sources
2460 output.println(" /* dynamic variable sources */");
2461 Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
2462 while( dynSrcItr.hasNext() ) {
2463 TempDescriptor dynSrcVar = dynSrcItr.next();
2464 output.println(" SESEcommon* "+dynSrcVar+"_srcSESE = NULL;");
2465 output.println(" INTPTR "+dynSrcVar+"_srcOffset = 0x1;");
2468 // declare local temps for in-set primitives, and if it is
2469 // a ready-source variable, get the value from the record
2470 output.println(" /* local temps for in-set primitives */");
2471 Iterator<TempDescriptor> itrInSet = fsen.getInVarSet().iterator();
2472 while( itrInSet.hasNext() ) {
2473 TempDescriptor temp = itrInSet.next();
2474 TypeDescriptor type = temp.getType();
2475 if( !type.isPtr() ) {
2476 if( fsen.getReadyInVarSet().contains( temp ) ) {
2477 output.println(" "+type+" "+temp+" = "+paramsprefix+"->"+temp+";");
2479 output.println(" "+type+" "+temp+";");
2484 // declare local temps for out-set primitives if its not already
2485 // in the in-set, and it's value will get written so no problem
2486 output.println(" /* local temp for out-set prim, not already in the in-set */");
2487 Iterator<TempDescriptor> itrOutSet = fsen.getOutVarSet().iterator();
2488 while( itrOutSet.hasNext() ) {
2489 TempDescriptor temp = itrOutSet.next();
2490 TypeDescriptor type = temp.getType();
2491 if( !type.isPtr() && !fsen.getInVarSet().contains( temp ) ) {
2492 output.println(" "+type+" "+temp+";");
2497 // initialize thread-local var to a the task's record, which is fused
2498 // with the param list
2499 output.println(" ");
2500 output.println(" // code of this task's body should use this to access the running task record");
2501 output.println(" runningSESE = &(___params___->common);");
2502 output.println(" childSESE = 0;");
2503 output.println(" ");
2505 // setup memory queue
2508 output.println(" // set up memory queues ");
2509 output.println(" int numMemoryQueue=0;");
2510 output.println(" int memoryQueueItemID=0;");
2511 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(fsen);
2512 if (graph != null && graph.hasConflictEdge()) {
2513 output.println(" {");
2514 Set<Analysis.OoOJava.SESELock> lockSet = oooa.getLockMappings(graph);
2515 System.out.println("#lockSet="+lockSet);
2516 if (lockSet.size() > 0) {
2517 output.println(" numMemoryQueue=" + lockSet.size() + ";");
2518 output.println(" runningSESE->numMemoryQueue=numMemoryQueue;");
2519 output.println(" runningSESE->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2522 output.println(" }");
2525 output.println(" // set up memory queues ");
2526 output.println(" int numMemoryQueue=0;");
2527 output.println(" int memoryQueueItemID=0;");
2528 ConflictGraph graph = null;
2529 graph = mlpa.getConflictGraphResults().get(fsen);
2530 if (graph != null && graph.hasConflictEdge()) {
2531 output.println(" {");
2532 HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
2534 System.out.println("#lockSet="+lockSet);
2536 if (lockSet.size() > 0) {
2537 output.println(" numMemoryQueue=" + lockSet.size() + "; ");
2538 output.println(" runningSESE->numMemoryQueue=numMemoryQueue;");
2539 output.println(" runningSESE->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2542 output.println(" }");
2547 // set up a task's mem pool to recycle the allocation of children tasks
2548 // don't bother if the task never has children (a leaf task)
2549 output.println( "#ifndef OOO_DISABLE_TASKMEMPOOL" );
2550 if( !fsen.getIsLeafSESE() ) {
2551 output.println(" runningSESE->taskRecordMemPool = taskpoolcreate( "+
2552 maxTaskRecSizeStr+" );");
2554 // make it clear we purposefully did not initialize this
2555 output.println(" runningSESE->taskRecordMemPool = (MemPool*)0x7;");
2557 output.println( "#endif // OOO_DISABLE_TASKMEMPOOL" );
2560 // copy in-set into place, ready vars were already
2561 // copied when the SESE was issued
2562 Iterator<TempDescriptor> tempItr;
2564 // static vars are from a known SESE
2565 output.println(" // copy variables from static sources");
2566 tempItr = fsen.getStaticInVarSet().iterator();
2567 while( tempItr.hasNext() ) {
2568 TempDescriptor temp = tempItr.next();
2569 VariableSourceToken vst = fsen.getStaticInVarSrc( temp );
2570 SESEandAgePair srcPair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2571 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2572 " = "+paramsprefix+"->"+srcPair+"->"+vst.getAddrVar()+";");
2575 output.println(" // decrement references to static sources");
2576 for( Iterator<SESEandAgePair> pairItr = fsen.getStaticInVarSrcs().iterator(); pairItr.hasNext(); ) {
2577 SESEandAgePair srcPair = pairItr.next();
2578 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
2579 output.println(" {");
2580 output.println(" SESEcommon* src = &("+paramsprefix+"->"+srcPair+"->common);");
2581 output.println(" RELEASE_REFERENCE_TO( src );");
2582 output.println(" }");
2583 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
2587 // dynamic vars come from an SESE and src
2588 output.println(" // copy variables from dynamic sources");
2589 tempItr = fsen.getDynamicInVarSet().iterator();
2590 while( tempItr.hasNext() ) {
2591 TempDescriptor temp = tempItr.next();
2592 TypeDescriptor type = temp.getType();
2594 // go grab it from the SESE source
2595 output.println(" if( "+paramsprefix+"->"+temp+"_srcSESE != NULL ) {");
2598 if( type.isNull() ) {
2600 } else if( type.isClass() || type.isArray() ) {
2601 typeStr = "struct "+type.getSafeSymbol()+"*";
2603 typeStr = type.getSafeSymbol();
2606 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2607 " = *(("+typeStr+"*) ((void*)"+
2608 paramsprefix+"->"+temp+"_srcSESE + "+
2609 paramsprefix+"->"+temp+"_srcOffset));");
2611 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
2612 output.println(" SESEcommon* src = "+paramsprefix+"->"+temp+"_srcSESE;");
2613 output.println(" RELEASE_REFERENCE_TO( src );");
2614 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
2616 // or if the source was our parent, its already in our record to grab
2617 output.println(" } else {");
2618 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2619 " = "+paramsprefix+"->"+temp+";");
2620 output.println(" }");
2623 // Check to see if we need to do a GC if this is a
2624 // multi-threaded program...
2625 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2626 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2627 //Don't bother if we aren't in recursive methods...The loops case will catch it
2628 // if (callgraph.getAllMethods(md).contains(md)) {
2629 // if(this.state.MULTICOREGC) {
2630 // output.println("if(gcflag) gc("+localsprefixaddr+");");
2632 // output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2637 if( state.COREPROF ) {
2638 output.println("#ifdef CP_EVENTID_TASKEXECUTE");
2639 output.println(" CP_LOGEVENT( CP_EVENTID_TASKEXECUTE, CP_EVENTTYPE_BEGIN );");
2640 output.println("#endif");
2643 HashSet<FlatNode> exitset=new HashSet<FlatNode>();
2644 exitset.add(seseExit);
2645 generateCode(fsen.getNext(0), fm, null, exitset, output, true);
2646 output.println("}\n\n");
2651 // when a new mlp thread is created for an issued SESE, it is started
2652 // by running this method which blocks on a cond variable until
2653 // it is allowed to transition to execute. Then a case statement
2654 // allows it to invoke the method with the proper SESE body, and after
2655 // exiting the SESE method, executes proper SESE exit code before the
2656 // thread can be destroyed
2657 private void generateSESEinvocationMethod(PrintWriter outmethodheader,
2658 PrintWriter outmethod
2661 outmethodheader.println("void* invokeSESEmethod( void* seseRecord );");
2662 outmethod.println( "void* invokeSESEmethod( void* seseRecord ) {");
2663 outmethod.println( " int status;");
2664 outmethod.println( " char errmsg[128];");
2666 // generate a case for each SESE class that can be invoked
2667 outmethod.println( " switch( ((SESEcommon*)seseRecord)->classID ) {");
2668 outmethod.println( " ");
2669 Iterator<FlatSESEEnterNode> seseit;
2671 seseit=mlpa.getAllSESEs().iterator();
2673 seseit=oooa.getAllSESEs().iterator();
2675 while(seseit.hasNext()){
2676 FlatSESEEnterNode fsen = seseit.next();
2678 outmethod.println( " /* "+fsen.getPrettyIdentifier()+" */");
2679 outmethod.println( " case "+fsen.getIdentifier()+":");
2680 outmethod.println( " "+fsen.getSESEmethodName()+"( seseRecord );");
2682 if( (state.MLP && fsen.equals( mlpa.getMainSESE() )) ||
2683 (state.OOOJAVA && fsen.equals( oooa.getMainSESE() ))
2685 outmethod.println( " workScheduleExit();");
2688 outmethod.println( " break;");
2689 outmethod.println( "");
2692 // default case should never be taken, error out
2693 outmethod.println( " default:");
2694 outmethod.println( " printf(\"Error: unknown SESE class ID in invoke method.\\n\");");
2695 outmethod.println( " exit(-30);");
2696 outmethod.println( " break;");
2697 outmethod.println( " }");
2698 outmethod.println( " return NULL;");
2699 outmethod.println( "}\n\n");
2703 protected void generateCode(FlatNode first,
2706 Set<FlatNode> stopset,
2708 boolean firstpass) {
2710 /* Assign labels to FlatNode's if necessary.*/
2712 Hashtable<FlatNode, Integer> nodetolabel;
2714 if (state.DELAYCOMP&&!firstpass)
2715 nodetolabel=dcassignLabels(first, stopset);
2717 nodetolabel=assignLabels(first, stopset);
2719 Set<FlatNode> storeset=null;
2720 HashSet<FlatNode> genset=null;
2721 HashSet<FlatNode> refset=null;
2722 Set<FlatNode> unionset=null;
2724 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
2725 storeset=delaycomp.livecode(lb);
2726 genset=new HashSet<FlatNode>();
2727 if (state.STMARRAY&&!state.DUALVIEW) {
2728 refset=new HashSet<FlatNode>();
2729 refset.addAll(delaycomp.getDeref(lb));
2730 refset.removeAll(delaycomp.getCannotDelay(lb));
2731 refset.removeAll(delaycomp.getOther(lb));
2734 genset.addAll(delaycomp.getCannotDelay(lb));
2735 genset.addAll(delaycomp.getOther(lb));
2737 genset.addAll(delaycomp.getNotReady(lb));
2738 if (state.STMARRAY&&!state.DUALVIEW) {
2739 genset.removeAll(refset);
2742 unionset=new HashSet<FlatNode>();
2743 unionset.addAll(storeset);
2744 unionset.addAll(genset);
2745 if (state.STMARRAY&&!state.DUALVIEW)
2746 unionset.addAll(refset);
2749 /* Do the actual code generation */
2750 FlatNode current_node=null;
2751 HashSet tovisit=new HashSet();
2752 HashSet visited=new HashSet();
2754 tovisit.add(first.getNext(0));
2757 while(current_node!=null||!tovisit.isEmpty()) {
2758 if (current_node==null) {
2759 current_node=(FlatNode)tovisit.iterator().next();
2760 tovisit.remove(current_node);
2761 } else if (tovisit.contains(current_node)) {
2762 tovisit.remove(current_node);
2764 visited.add(current_node);
2765 if (nodetolabel.containsKey(current_node)) {
2766 output.println("L"+nodetolabel.get(current_node)+":");
2768 if (state.INSTRUCTIONFAILURE) {
2769 if (state.THREAD||state.DSM||state.SINGLETM) {
2770 output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
2772 output.println("if ((--instructioncount)==0) injectinstructionfailure();");
2774 if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
2776 if (!state.DELAYCOMP||firstpass) {
2777 generateFlatNode(fm, lb, current_node, output);
2779 //store primitive variables in out set
2780 AtomicRecord ar=atomicmethodmap.get((FlatAtomicEnterNode)first);
2781 Set<TempDescriptor> liveout=ar.liveout;
2782 for(Iterator<TempDescriptor> tmpit=liveout.iterator();tmpit.hasNext();) {
2783 TempDescriptor tmp=tmpit.next();
2784 output.println("primitives->"+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2787 if ((state.MLP || state.OOOJAVA) && stopset!=null) {
2788 assert first.getPrev( 0 ) instanceof FlatSESEEnterNode;
2789 assert current_node instanceof FlatSESEExitNode;
2790 FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev( 0 );
2791 FlatSESEExitNode fsxn = (FlatSESEExitNode) current_node;
2792 assert fsen.getFlatExit().equals( fsxn );
2793 assert fsxn.getFlatEnter().equals( fsen );
2795 if (current_node.kind()!=FKind.FlatReturnNode) {
2797 // TODO add version for normal Java later
2798 if((fm.getMethod() != null) && (fm.getMethod().isStaticBlock())) {
2799 // a static block, check if it has been executed
2800 output.println(" global_defs_p->" + fm.getMethod().getClassDesc().getSafeSymbol()+"static_block_exe_flag = 1;");
2804 output.println(" return;");
2807 } else if(current_node.numNext()==1) {
2809 if ((state.MLP|| state.OOOJAVA) &&
2810 current_node.kind()==FKind.FlatSESEEnterNode &&
2811 !((FlatSESEEnterNode)current_node).getIsCallerSESEplaceholder()
2813 FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
2814 generateFlatNode(fm, lb, current_node, output);
2815 nextnode=fsen.getFlatExit().getNext(0);
2816 } else if (state.DELAYCOMP) {
2817 boolean specialprimitive=false;
2818 //skip literals...no need to add extra overhead
2819 if (storeset!=null&&storeset.contains(current_node)&¤t_node.kind()==FKind.FlatLiteralNode) {
2820 TypeDescriptor typedesc=((FlatLiteralNode)current_node).getType();
2821 if (!typedesc.isClass()&&!typedesc.isArray()) {
2822 specialprimitive=true;
2826 if (genset==null||genset.contains(current_node)||specialprimitive)
2827 generateFlatNode(fm, lb, current_node, output);
2828 if (state.STMARRAY&&!state.DUALVIEW&&refset!=null&&refset.contains(current_node)) {
2829 //need to acquire lock
2830 handleArrayDeref(fm, lb, current_node, output, firstpass);
2832 if (storeset!=null&&storeset.contains(current_node)&&!specialprimitive) {
2833 TempDescriptor wrtmp=current_node.writesTemps()[0];
2835 //need to store value written by previous node
2836 if (wrtmp.getType().isPtr()) {
2837 //only lock the objects that may actually need locking
2838 if (recorddc.getNeedTrans(lb, current_node)&&
2839 (!state.STMARRAY||state.DUALVIEW||!wrtmp.getType().isArray()||
2840 wrtmp.getType().getSymbol().equals(TypeUtil.ObjectClass))) {
2841 output.println("STOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2843 output.println("STOREPTRNOLOCK("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2846 output.println("STORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");/* "+current_node.nodeid+" */");
2849 //need to read value read by previous node
2850 if (wrtmp.getType().isPtr()) {
2851 output.println("RESTOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2853 output.println("RESTORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+"); /* "+current_node.nodeid+" */");
2857 nextnode=current_node.getNext(0);
2860 generateFlatNode(fm, lb, current_node, output);
2861 nextnode=current_node.getNext(0);
2863 if (visited.contains(nextnode)) {
2864 output.println("goto L"+nodetolabel.get(nextnode)+";");
2867 current_node=nextnode;
2868 } else if (current_node.numNext()==2) {
2870 if (state.DELAYCOMP) {
2871 boolean computeside=false;
2873 //need to record which way it should go
2874 if (genset==null||genset.contains(current_node)) {
2875 if (storeset!=null&&storeset.contains(current_node)) {
2876 //need to store which way branch goes
2877 generateStoreFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2879 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2881 //which side to execute
2885 if (genset.contains(current_node)) {
2886 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2887 } else if (storeset.contains(current_node)) {
2889 branchanalysis.generateGroupCode(current_node, output, nodetolabel);
2891 //which side to execute
2896 Set<FlatNode> leftset=DelayComputation.getNext(current_node, 0, unionset, lb,locality, true);
2898 if (leftset.size()==0)
2900 if (visited.contains(current_node.getNext(branch))) {
2901 //already visited -- build jump
2902 output.println("goto L"+nodetolabel.get(current_node.getNext(branch))+";");
2905 current_node=current_node.getNext(branch);
2908 if (!visited.contains(current_node.getNext(1)))
2909 tovisit.add(current_node.getNext(1));
2910 if (visited.contains(current_node.getNext(0))) {
2911 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2914 current_node=current_node.getNext(0);
2918 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2919 if (!visited.contains(current_node.getNext(1)))
2920 tovisit.add(current_node.getNext(1));
2921 if (visited.contains(current_node.getNext(0))) {
2922 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2925 current_node=current_node.getNext(0);
2927 } else throw new Error();
2931 protected void handleArrayDeref(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output, boolean firstpass) {
2932 if (fn.kind()==FKind.FlatSetElementNode) {
2933 FlatSetElementNode fsen=(FlatSetElementNode) fn;
2934 String dst=generateTemp(fm, fsen.getDst(), lb);
2935 String src=generateTemp(fm, fsen.getSrc(), lb);
2936 String index=generateTemp(fm, fsen.getIndex(), lb);
2937 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
2939 if (elementtype.isArray()||elementtype.isClass())
2942 type=elementtype.getSafeSymbol()+" ";
2944 output.println("STOREARRAY("+dst+","+index+","+type+")");
2946 output.println("{");
2947 output.println(" struct ArrayObject *array;");
2948 output.println(" int index;");
2949 output.println(" RESTOREARRAY(array,index);");
2950 output.println(" (("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index]="+src+";");
2951 output.println("}");
2953 } else if (fn.kind()==FKind.FlatElementNode) {
2954 FlatElementNode fen=(FlatElementNode) fn;
2955 String src=generateTemp(fm, fen.getSrc(), lb);
2956 String index=generateTemp(fm, fen.getIndex(), lb);
2957 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
2958 String dst=generateTemp(fm, fen.getDst(), lb);
2960 if (elementtype.isArray()||elementtype.isClass())
2963 type=elementtype.getSafeSymbol()+" ";
2965 output.println("STOREARRAY("+src+","+index+","+type+")");
2967 output.println("{");
2968 output.println(" struct ArrayObject *array;");
2969 output.println(" int index;");
2970 output.println(" RESTOREARRAY(array,index);");
2971 output.println(" "+dst+"=(("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index];");
2972 output.println("}");
2976 /** Special label assignment for delaycomputation */
2977 protected Hashtable<FlatNode, Integer> dcassignLabels(FlatNode first, Set<FlatNode> lastset) {
2978 HashSet tovisit=new HashSet();
2979 HashSet visited=new HashSet();
2981 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2983 //Label targets of branches
2984 Set<FlatNode> targets=branchanalysis.getTargets();
2985 for(Iterator<FlatNode> it=targets.iterator();it.hasNext();) {
2986 nodetolabel.put(it.next(), new Integer(labelindex++));
2991 /*Assign labels first. A node needs a label if the previous
2992 * node has two exits or this node is a join point. */
2994 while(!tovisit.isEmpty()) {
2995 FlatNode fn=(FlatNode)tovisit.iterator().next();
3000 if(lastset!=null&&lastset.contains(fn)) {
3001 // if last is not null and matches, don't go
3002 // any further for assigning labels
3006 for(int i=0; i<fn.numNext(); i++) {
3007 FlatNode nn=fn.getNext(i);
3010 //1) Edge >1 of node
3011 nodetolabel.put(nn,new Integer(labelindex++));
3013 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
3017 nodetolabel.put(nn,new Integer(labelindex++));
3025 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first) {
3026 return assignLabels(first, null);
3029 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
3030 HashSet tovisit=new HashSet();
3031 HashSet visited=new HashSet();
3033 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
3036 /*Assign labels first. A node needs a label if the previous
3037 * node has two exits or this node is a join point. */
3039 while(!tovisit.isEmpty()) {
3040 FlatNode fn=(FlatNode)tovisit.iterator().next();
3045 if(lastset!=null&&lastset.contains(fn)) {
3046 // if last is not null and matches, don't go
3047 // any further for assigning labels
3051 for(int i=0; i<fn.numNext(); i++) {
3052 FlatNode nn=fn.getNext(i);
3055 //1) Edge >1 of node
3056 nodetolabel.put(nn,new Integer(labelindex++));
3058 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
3062 nodetolabel.put(nn,new Integer(labelindex++));
3070 /** Generate text string that corresponds to the TempDescriptor td. */
3071 protected String generateTemp(FlatMethod fm, TempDescriptor td, LocalityBinding lb) {
3072 MethodDescriptor md=fm.getMethod();
3073 TaskDescriptor task=fm.getTask();
3074 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
3076 if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
3077 return td.getSafeSymbol();
3080 if (objecttemps.isLocalPtr(td)) {
3081 return localsprefixderef+td.getSafeSymbol();
3084 if (objecttemps.isParamPtr(td)) {
3085 return paramsprefix+"->"+td.getSafeSymbol();
3091 protected void generateFlatNode(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output) {
3093 // insert pre-node actions from the code plan
3094 if( state.MLP|| state.OOOJAVA ) {
3098 cp = mlpa.getCodePlan( fn );
3100 cp = oooa.getCodePlan(fn);
3105 FlatSESEEnterNode currentSESE = cp.getCurrentSESE();
3107 // for each sese and age pair that this parent statement
3108 // must stall on, take that child's stall semaphore, the
3109 // copying of values comes after the statement
3110 Iterator<VariableSourceToken> vstItr = cp.getStallTokens().iterator();
3111 while( vstItr.hasNext() ) {
3112 VariableSourceToken vst = vstItr.next();
3114 SESEandAgePair pair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
3116 output.println(" {");
3117 output.println(" "+pair.getSESE().getSESErecordName()+"* child = ("+
3118 pair.getSESE().getSESErecordName()+"*) "+pair+";");
3120 output.println(" SESEcommon* childCom = (SESEcommon*) "+pair+";");
3122 if( state.COREPROF ) {
3123 output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
3124 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_BEGIN );");
3125 output.println("#endif");
3128 output.println(" pthread_mutex_lock( &(childCom->lock) );");
3129 output.println(" if( childCom->doneExecuting == FALSE ) {");
3130 output.println(" psem_reset( &runningSESEstallSem );");
3131 output.println(" childCom->parentsStallSem = &runningSESEstallSem;");
3132 output.println(" pthread_mutex_unlock( &(childCom->lock) );");
3133 output.println(" psem_take( &runningSESEstallSem, (struct garbagelist *)&___locals___ );");
3134 output.println(" } else {");
3135 output.println(" pthread_mutex_unlock( &(childCom->lock) );");
3136 output.println(" }");
3138 // copy things we might have stalled for
3139 Iterator<TempDescriptor> tdItr = cp.getCopySet( vst ).iterator();
3140 while( tdItr.hasNext() ) {
3141 TempDescriptor td = tdItr.next();
3142 FlatMethod fmContext;
3143 if( currentSESE.getIsCallerSESEplaceholder() ) {
3144 fmContext = currentSESE.getfmEnclosing();
3146 fmContext = currentSESE.getfmBogus();
3148 output.println(" "+generateTemp( fmContext, td, null )+
3149 " = child->"+vst.getAddrVar().getSafeSymbol()+";");
3152 if( state.COREPROF ) {
3153 output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
3154 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_END );");
3155 output.println("#endif");
3158 output.println(" }");
3161 // for each variable with a dynamic source, stall just for that variable
3162 Iterator<TempDescriptor> dynItr = cp.getDynamicStallSet().iterator();
3163 while( dynItr.hasNext() ) {
3164 TempDescriptor dynVar = dynItr.next();
3166 // only stall if the dynamic source is not yourself, denoted by src==NULL
3167 // otherwise the dynamic write nodes will have the local var up-to-date
3168 output.println(" {");
3169 output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
3171 output.println(" SESEcommon* childCom = (SESEcommon*) "+dynVar+"_srcSESE;");
3173 if( state.COREPROF ) {
3174 output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
3175 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_BEGIN );");
3176 output.println("#endif");
3179 output.println(" pthread_mutex_lock( &(childCom->lock) );");
3180 output.println(" if( childCom->doneExecuting == FALSE ) {");
3181 output.println(" psem_reset( &runningSESEstallSem );");
3182 output.println(" childCom->parentsStallSem = &runningSESEstallSem;");
3183 output.println(" pthread_mutex_unlock( &(childCom->lock) );");
3184 output.println(" psem_take( &runningSESEstallSem, (struct garbagelist *)&___locals___ );");
3185 output.println(" } else {");
3186 output.println(" pthread_mutex_unlock( &(childCom->lock) );");
3187 output.println(" }");
3189 FlatMethod fmContext;
3190 if( currentSESE.getIsCallerSESEplaceholder() ) {
3191 fmContext = currentSESE.getfmEnclosing();
3193 fmContext = currentSESE.getfmBogus();
3196 TypeDescriptor type = dynVar.getType();
3198 if( type.isNull() ) {
3200 } else if( type.isClass() || type.isArray() ) {
3201 typeStr = "struct "+type.getSafeSymbol()+"*";
3203 typeStr = type.getSafeSymbol();
3206 output.println(" "+generateTemp( fmContext, dynVar, null )+
3207 " = *(("+typeStr+"*) ((void*)"+
3208 dynVar+"_srcSESE + "+dynVar+"_srcOffset));");
3210 if( state.COREPROF ) {
3211 output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
3212 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_END );");
3213 output.println("#endif");
3216 output.println(" }");
3217 output.println(" }");
3220 // for each assignment of a variable to rhs that has a dynamic source,
3221 // copy the dynamic sources
3222 Iterator dynAssignItr = cp.getDynAssigns().entrySet().iterator();
3223 while( dynAssignItr.hasNext() ) {
3224 Map.Entry me = (Map.Entry) dynAssignItr.next();
3225 TempDescriptor lhs = (TempDescriptor) me.getKey();
3226 TempDescriptor rhs = (TempDescriptor) me.getValue();
3228 output.println(" {");
3229 output.println(" SESEcommon* oldSrc = "+lhs+"_srcSESE;");
3231 output.println(" "+lhs+"_srcSESE = "+rhs+"_srcSESE;");
3232 output.println(" "+lhs+"_srcOffset = "+rhs+"_srcOffset;");
3234 // no matter what we did above, track reference count of whatever
3235 // this variable pointed to, do release last in case we're just
3236 // copying the same value in because 1->2->1 is safe but ref count
3237 // 1->0->1 has a window where it looks like it should be free'd
3238 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
3239 output.println(" if( "+rhs+"_srcSESE != NULL ) {");
3240 output.println(" ADD_REFERENCE_TO( "+rhs+"_srcSESE );");
3241 output.println(" }");
3242 output.println(" if( oldSrc != NULL ) {");
3243 output.println(" RELEASE_REFERENCE_TO( oldSrc );");
3244 output.println(" }");
3245 output.println(" }");
3246 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
3249 // for each lhs that is dynamic from a non-dynamic source, set the
3250 // dynamic source vars to the current SESE
3251 dynItr = cp.getDynAssignCurr().iterator();
3252 while( dynItr.hasNext() ) {
3253 TempDescriptor dynVar = dynItr.next();
3254 assert currentSESE.getDynamicVarSet().contains( dynVar );
3256 // first release a reference to current record
3257 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
3258 output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
3259 output.println(" RELEASE_REFERENCE_TO( oldSrc );");
3260 output.println(" }");
3261 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
3263 output.println(" "+dynVar+"_srcSESE = NULL;");
3267 // handling stall site
3268 if (state.OOOJAVA) {
3269 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(currentSESE);
3271 Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
3272 Set<Analysis.OoOJava.WaitingElement> waitingElementSet = graph.getStallSiteWaitingElementSet(fn, seseLockSet);
3274 if(waitingElementSet.size()>0){
3275 output.println("// stall on parent's stall sites ");
3276 output.println(" {");
3277 output.println(" REntry* rentry;");
3279 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
3280 Analysis.OoOJava.WaitingElement waitingElement = (Analysis.OoOJava.WaitingElement) iterator.next();
3281 if( waitingElement.getStatus() >= ConflictNode.COARSE ){
3282 output.println(" rentry=mlpCreateREntry(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "],"+waitingElement.getStatus()+ ", runningSESE);");
3284 output.println(" rentry=mlpCreateFineREntry(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "],"+ waitingElement.getStatus()+ ", runningSESE, (void*)&" +generateTemp(fm,waitingElement.getTempDesc(),lb)+ ");");
3286 output.println(" rentry->parentStallSem=&runningSESEstallSem;");
3287 output.println(" psem_reset( &runningSESEstallSem);");
3288 output.println(" rentry->tag=runningSESEstallSem.tag;");
3289 output.println(" rentry->queue=runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
3290 output.println(" if(ADDRENTRY(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "],rentry)==NOTREADY){");
3291 if( state.COREPROF ) {
3292 output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3293 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_BEGIN );");
3294 output.println("#endif");
3297 //no need to enqueue parent effect if coarse grained conflict clears us
3298 output.println(" while(stallrecord.common.rcrstatus) ;");
3299 output.println(" BARRIER();");
3300 output.println(" stallrecord.common.parentsStallSem=&runningSESEstallSem;");
3301 output.println(" stallrecord.tag=rentry->tag;");
3302 output.println(" stallrecord.___obj___=(struct ___Object___ *)"+generateTemp(fm, waitingElement.getTempDesc(), null)+";");
3303 output.println(" stallrecord.common.classID=-"+rcr.getTraverserID(waitingElement.getTempDesc(), fn)+";");
3304 //mark the record used..so we won't use it again until it is free
3305 output.println(" stallrecord.common.rcrstatus=1;");
3306 output.println(" enqueueTR(TRqueue, (void *)&stallrecord);");
3308 output.println(" psem_take( &runningSESEstallSem, (struct garbagelist *)&___locals___ );");
3309 if( state.COREPROF ) {
3310 output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3311 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_END );");
3312 output.println("#endif");
3314 output.println(" } ");
3316 output.println(" }");
3320 ParentChildConflictsMap conflictsMap = mlpa.getConflictsResults().get(fn);
3321 if (conflictsMap != null) {
3322 Set<Long> allocSet = conflictsMap.getAllocationSiteIDSetofStallSite();
3323 if (allocSet.size() > 0) {
3324 FlatNode enclosingFlatNode=null;
3325 if( currentSESE.getIsCallerSESEplaceholder() && currentSESE.getParent()==null){
3326 enclosingFlatNode=currentSESE.getfmEnclosing();
3328 enclosingFlatNode=currentSESE;
3330 ConflictGraph graph=mlpa.getConflictGraphResults().get(enclosingFlatNode);
3331 HashSet<SESELock> seseLockSet=mlpa.getConflictGraphLockMap().get(graph);
3332 Set<WaitingElement> waitingElementSet=graph.getStallSiteWaitingElementSet(conflictsMap, seseLockSet);
3334 if(waitingElementSet.size()>0){
3335 output.println("// stall on parent's stall sites ");
3336 output.println(" {");
3337 output.println(" REntry* rentry;");
3339 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
3340 WaitingElement waitingElement = (WaitingElement) iterator.next();
3342 if( waitingElement.getStatus() >= ConflictNode.COARSE ){
3343 // HERE! a parent might conflict with a child
3344 output.println(" rentry=mlpCreateREntry(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "],"+ waitingElement.getStatus()+ ", runningSESE);");
3346 output.println(" rentry=mlpCreateFineREntry(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "],"+ waitingElement.getStatus()+ ", runningSESE, (void*)&___locals___."+ waitingElement.getDynID() + ");");
3348 output.println(" rentry->parentStallSem=&runningSESEstallSem;");
3349 output.println(" psem_reset( &runningSESEstallSem);");
3350 output.println(" rentry->tag=runningSESEstallSem.tag;");
3351 output.println(" rentry->queue=runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
3352 output.println(" if(ADDRENTRY(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+"],rentry)==NOTREADY) {");
3353 if( state.COREPROF ) {
3354 output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3355 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_BEGIN );");
3356 output.println("#endif");
3358 output.println(" psem_take( &runningSESEstallSem, (struct garbagelist *)&___locals___ );");
3359 if( state.COREPROF ) {
3360 output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3361 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_END );");
3362 output.println("#endif");
3364 output.println(" } ");
3366 output.println(" }");
3375 case FKind.FlatAtomicEnterNode:
3376 generateFlatAtomicEnterNode(fm, lb, (FlatAtomicEnterNode) fn, output);
3379 case FKind.FlatAtomicExitNode:
3380 generateFlatAtomicExitNode(fm, lb, (FlatAtomicExitNode) fn, output);
3383 case FKind.FlatInstanceOfNode:
3384 generateFlatInstanceOfNode(fm, lb, (FlatInstanceOfNode)fn, output);
3387 case FKind.FlatSESEEnterNode:
3388 generateFlatSESEEnterNode(fm, lb, (FlatSESEEnterNode)fn, output);
3391 case FKind.FlatSESEExitNode:
3392 generateFlatSESEExitNode(fm, lb, (FlatSESEExitNode)fn, output);
3395 case FKind.FlatWriteDynamicVarNode:
3396 generateFlatWriteDynamicVarNode(fm, lb, (FlatWriteDynamicVarNode)fn, output);
3399 case FKind.FlatGlobalConvNode:
3400 generateFlatGlobalConvNode(fm, lb, (FlatGlobalConvNode) fn, output);
3403 case FKind.FlatTagDeclaration:
3404 generateFlatTagDeclaration(fm, lb, (FlatTagDeclaration) fn,output);
3407 case FKind.FlatCall:
3408 generateFlatCall(fm, lb, (FlatCall) fn,output);
3411 case FKind.FlatFieldNode:
3412 generateFlatFieldNode(fm, lb, (FlatFieldNode) fn,output);
3415 case FKind.FlatElementNode:
3416 generateFlatElementNode(fm, lb, (FlatElementNode) fn,output);
3419 case FKind.FlatSetElementNode:
3420 generateFlatSetElementNode(fm, lb, (FlatSetElementNode) fn,output);
3423 case FKind.FlatSetFieldNode:
3424 generateFlatSetFieldNode(fm, lb, (FlatSetFieldNode) fn,output);
3428 generateFlatNew(fm, lb, (FlatNew) fn,output);
3431 case FKind.FlatOpNode:
3432 generateFlatOpNode(fm, lb, (FlatOpNode) fn,output);
3435 case FKind.FlatCastNode:
3436 generateFlatCastNode(fm, lb, (FlatCastNode) fn,output);
3439 case FKind.FlatLiteralNode:
3440 generateFlatLiteralNode(fm, lb, (FlatLiteralNode) fn,output);
3443 case FKind.FlatReturnNode:
3444 generateFlatReturnNode(fm, lb, (FlatReturnNode) fn,output);
3448 output.println("/* nop */");
3451 case FKind.FlatGenReachNode:
3452 // this node is just for generating a reach graph
3453 // in disjointness analysis at a particular program point
3456 case FKind.FlatExit:
3457 output.println("/* exit */");
3460 case FKind.FlatBackEdge:
3461 if (state.SINGLETM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
3462 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
3464 if(state.DSM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
3465 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
3467 if (((state.MLP|| state.OOOJAVA||state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
3468 || (this.state.MULTICOREGC)) {
3469 if(state.DSM&&locality.getAtomic(lb).get(fn).intValue()>0) {
3470 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
3471 } else if(this.state.MULTICOREGC) {
3472 output.println("if (gcflag) gc("+localsprefixaddr+");");
3474 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3477 output.println("/* nop */");
3480 case FKind.FlatCheckNode:
3481 generateFlatCheckNode(fm, lb, (FlatCheckNode) fn, output);
3484 case FKind.FlatFlagActionNode:
3485 generateFlatFlagActionNode(fm, lb, (FlatFlagActionNode) fn, output);
3488 case FKind.FlatPrefetchNode:
3489 generateFlatPrefetchNode(fm,lb, (FlatPrefetchNode) fn, output);
3492 case FKind.FlatOffsetNode:
3493 generateFlatOffsetNode(fm, lb, (FlatOffsetNode)fn, output);
3500 // insert post-node actions from the code-plan
3503 CodePlan cp = mlpa.getCodePlan( fn );
3511 public void generateFlatOffsetNode(FlatMethod fm, LocalityBinding lb, FlatOffsetNode fofn, PrintWriter output) {
3512 output.println("/* FlatOffsetNode */");
3513 FieldDescriptor fd=fofn.getField();
3514 output.println(generateTemp(fm, fofn.getDst(),lb)+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+ fd.getSafeSymbol()+");");
3515 output.println("/* offset */");
3518 public void generateFlatPrefetchNode(FlatMethod fm, LocalityBinding lb, FlatPrefetchNode fpn, PrintWriter output) {
3519 if (state.PREFETCH) {
3520 Vector oids = new Vector();
3521 Vector fieldoffset = new Vector();
3522 Vector endoffset = new Vector();
3523 int tuplecount = 0; //Keeps track of number of prefetch tuples that need to be generated
3524 for(Iterator it = fpn.hspp.iterator(); it.hasNext();) {
3525 PrefetchPair pp = (PrefetchPair) it.next();
3526 Integer statusbase = locality.getNodePreTempInfo(lb,fpn).get(pp.base);
3527 /* Find prefetches that can generate oid */
3528 if(statusbase == LocalityAnalysis.GLOBAL) {
3529 generateTransCode(fm, lb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(lb).get(fpn).intValue()>0, false);
3531 } else if (statusbase == LocalityAnalysis.LOCAL) {
3532 generateTransCode(fm,lb,pp,oids,fieldoffset,endoffset,tuplecount,false,true);
3539 System.out.println("Adding prefetch "+fpn+ " to method:" +fm);
3540 output.println("{");
3541 output.println("/* prefetch */");
3542 output.println("/* prefetchid_" + fpn.siteid + " */");
3543 output.println("void * prefptr;");
3544 output.println("int tmpindex;");
3546 output.println("if((evalPrefetch["+fpn.siteid+"].operMode) || (evalPrefetch["+fpn.siteid+"].retrycount <= 0)) {");
3547 /*Create C code for oid array */
3548 output.print(" unsigned int oidarray_[] = {");
3549 boolean needcomma=false;
3550 for (Iterator it = oids.iterator(); it.hasNext();) {
3553 output.print(it.next());
3556 output.println("};");
3558 /*Create C code for endoffset values */
3559 output.print(" unsigned short endoffsetarry_[] = {");
3561 for (Iterator it = endoffset.iterator(); it.hasNext();) {
3564 output.print(it.next());
3567 output.println("};");
3569 /*Create C code for Field Offset Values */
3570 output.print(" short fieldarry_[] = {");
3572 for (Iterator it = fieldoffset.iterator(); it.hasNext();) {
3575 output.print(it.next());
3578 output.println("};");
3579 /* make the prefetch call to Runtime */
3580 output.println(" if(!evalPrefetch["+fpn.siteid+"].operMode) {");
3581 output.println(" evalPrefetch["+fpn.siteid+"].retrycount = RETRYINTERVAL;");
3582 output.println(" }");
3583 output.println(" prefetch("+fpn.siteid+" ,"+tuplecount+", oidarray_, endoffsetarry_, fieldarry_);");
3584 output.println(" } else {");
3585 output.println(" evalPrefetch["+fpn.siteid+"].retrycount--;");
3586 output.println(" }");
3587 output.println("}");
3591 public void generateTransCode(FlatMethod fm, LocalityBinding lb,PrefetchPair pp, Vector oids, Vector fieldoffset, Vector endoffset, int tuplecount, boolean inside, boolean localbase) {
3592 short offsetcount = 0;
3596 } else if (localbase) {
3597 for(; breakindex<pp.desc.size(); breakindex++) {
3598 Descriptor desc=pp.getDescAt(breakindex);
3599 if (desc instanceof FieldDescriptor) {
3600 FieldDescriptor fd=(FieldDescriptor)desc;
3601 if (fd.isGlobal()) {
3609 if (breakindex>pp.desc.size()) //all local
3612 TypeDescriptor lasttype=pp.base.getType();
3613 String basestr=generateTemp(fm, pp.base, lb);
3615 boolean maybenull=fm.getMethod().isStatic()||
3616 !pp.base.equals(fm.getParameter(0));
3618 for(int i=0; i<breakindex; i++) {
3619 String indexcheck="";
3621 Descriptor desc=pp.getDescAt(i);
3622 if (desc instanceof FieldDescriptor) {
3623 FieldDescriptor fd=(FieldDescriptor)desc;
3625 if (!teststr.equals(""))
3627 teststr+="((prefptr="+basestr+")!=NULL)";
3628 basestr="((struct "+lasttype.getSafeSymbol()+" *)prefptr)->"+fd.getSafeSymbol();
3630 basestr=basestr+"->"+fd.getSafeSymbol();
3633 lasttype=fd.getType();
3635 IndexDescriptor id=(IndexDescriptor)desc;
3636 indexcheck="((tmpindex=";
3637 for(int j=0; j<id.tddesc.size(); j++) {
3638 indexcheck+=generateTemp(fm, id.getTempDescAt(j), lb)+"+";
3640 indexcheck+=id.offset+")>=0)&(tmpindex<((struct ArrayObject *)prefptr)->___length___)";
3642 if (!teststr.equals(""))
3644 teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck;
3645 basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]";
3647 lasttype=lasttype.dereference();
3652 if (teststr.equals("")) {
3653 oid="((unsigned int)"+basestr+")";
3655 oid="((unsigned int)(("+teststr+")?"+basestr+":NULL))";
3659 for(int i = breakindex; i < pp.desc.size(); i++) {
3660 String newfieldoffset;
3661 Object desc = pp.getDescAt(i);
3662 if(desc instanceof FieldDescriptor) {
3663 FieldDescriptor fd=(FieldDescriptor)desc;
3664 newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))");
3665 lasttype=fd.getType();
3667 newfieldoffset = "";
3668 IndexDescriptor id=(IndexDescriptor)desc;
3669 for(int j = 0; j < id.tddesc.size(); j++) {
3670 newfieldoffset += generateTemp(fm, id.getTempDescAt(j), lb) + "+";
3672 newfieldoffset += id.offset.toString();
3673 lasttype=lasttype.dereference();
3675 fieldoffset.add(newfieldoffset);
3678 int base=(tuplecount>0) ? ((Short)endoffset.get(tuplecount-1)).intValue() : 0;
3679 base+=pp.desc.size()-breakindex;
3680 endoffset.add(new Short((short)base));
3685 public void generateFlatGlobalConvNode(FlatMethod fm, LocalityBinding lb, FlatGlobalConvNode fgcn, PrintWriter output) {
3686 if (lb!=fgcn.getLocality())
3688 /* Have to generate flat globalconv */
3689 if (fgcn.getMakePtr()) {
3691 //DEBUG: output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+",\" "+fm+":"+fgcn+"\");");
3692 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3694 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fgcn)||state.READSET&&dc.getNeedWriteTrans(lb, fgcn)) {
3695 //need to do translation
3696 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+", (void *)("+localsprefixaddr+"));");
3697 } else if (state.READSET&&dc.getNeedTrans(lb, fgcn)) {
3698 if (state.HYBRID&&delaycomp.getConv(lb).contains(fgcn)) {
3699 output.println("TRANSREADRDFISSION("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3701 output.println("TRANSREADRD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3705 /* Need to convert to OID */
3706 if ((dc==null)||dc.getNeedSrcTrans(lb,fgcn)) {
3707 if (fgcn.doConvert()||(delaycomp!=null&&delaycomp.needsFission(lb, fgcn.getAtomicEnter())&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) {
3708 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc(),lb)+");");
3710 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=NULL;");
3716 public void generateFlatInstanceOfNode(FlatMethod fm, LocalityBinding lb, FlatInstanceOfNode fion, PrintWriter output) {
3718 if (fion.getType().isArray()) {
3719 type=state.getArrayNumber(fion.getType())+state.numClasses();
3721 type=fion.getType().getClassDesc().getId();
3724 if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
3725 output.println(generateTemp(fm, fion.getDst(), lb)+"=1;");
3727 output.println(generateTemp(fm, fion.getDst(), lb)+"=instanceof("+generateTemp(fm,fion.getSrc(),lb)+","+type+");");
3730 int sandboxcounter=0;
3731 public void generateFlatAtomicEnterNode(FlatMethod fm, LocalityBinding lb, FlatAtomicEnterNode faen, PrintWriter output) {
3732 /* Check to see if we need to generate code for this atomic */
3733 if (locality==null) {
3734 if (GENERATEPRECISEGC) {
3735 output.println("if (pthread_mutex_trylock(&atomiclock)!=0) {");
3736 output.println("stopforgc((struct garbagelist *) &___locals___);");
3737 output.println("pthread_mutex_lock(&atomiclock);");
3738 output.println("restartaftergc();");
3739 output.println("}");
3741 output.println("pthread_mutex_lock(&atomiclock);");
3746 if (locality.getAtomic(lb).get(faen.getPrev(0)).intValue()>0)
3750 if (state.SANDBOX) {
3751 outsandbox.println("int atomiccounter"+sandboxcounter+"=LOW_CHECK_FREQUENCY;");
3752 output.println("counter_reset_pointer=&atomiccounter"+sandboxcounter+";");
3755 if (state.DELAYCOMP&&delaycomp.needsFission(lb, faen)) {
3756 AtomicRecord ar=atomicmethodmap.get(faen);
3758 for(Iterator<TempDescriptor> tmpit=ar.livein.iterator();tmpit.hasNext();) {
3759 TempDescriptor tmp=tmpit.next();
3760 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3763 //copy outs that depend on path
3764 for(Iterator<TempDescriptor> tmpit=ar.liveoutvirtualread.iterator();tmpit.hasNext();) {
3765 TempDescriptor tmp=tmpit.next();
3766 if (!ar.livein.contains(tmp))
3767 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3771 /* Backup the temps. */
3772 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3773 TempDescriptor tmp=tmpit.next();
3774 output.println(generateTemp(fm, backuptable.get(lb).get(tmp),lb)+"="+generateTemp(fm,tmp,lb)+";");
3777 output.println("goto transstart"+faen.getIdentifier()+";");
3779 /******* Print code to retry aborted transaction *******/
3780 output.println("transretry"+faen.getIdentifier()+":");
3783 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3784 TempDescriptor tmp=tmpit.next();
3785 output.println(generateTemp(fm, tmp,lb)+"="+generateTemp(fm,backuptable.get(lb).get(tmp),lb)+";");
3789 /********* Need to revert local object store ********/
3790 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3792 output.println("while ("+revertptr+") {");
3793 output.println("struct ___Object___ * tmpptr;");
3794 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3795 output.println("REVERT_OBJ("+revertptr+");");
3796 output.println(revertptr+"=tmpptr;");
3797 output.println("}");
3799 /******* Tell the runtime to start the transaction *******/
3801 output.println("transstart"+faen.getIdentifier()+":");
3802 if (state.SANDBOX) {
3803 output.println("transaction_check_counter=*counter_reset_pointer;");
3806 output.println("transStart();");
3808 if (state.ABORTREADERS||state.SANDBOX) {
3810 output.println("abortenabled=1;");
3811 output.println("if (_setjmp(aborttrans)) {");
3812 output.println(" goto transretry"+faen.getIdentifier()+"; }");
3816 public void generateFlatAtomicExitNode(FlatMethod fm, LocalityBinding lb, FlatAtomicExitNode faen, PrintWriter output) {
3817 /* Check to see if we need to generate code for this atomic */
3818 if (locality==null) {
3819 output.println("pthread_mutex_unlock(&atomiclock);");
3822 if (locality.getAtomic(lb).get(faen).intValue()>0)
3824 //store the revert list before we lose the transaction object
3827 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3828 output.println(revertptr+"=revertlist;");
3829 output.println("if (transCommit()) {");
3830 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3831 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3832 output.println("} else {");
3833 /* Need to commit local object store */
3834 output.println("while ("+revertptr+") {");
3835 output.println("struct ___Object___ * tmpptr;");
3836 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3837 output.println("COMMIT_OBJ("+revertptr+");");
3838 output.println(revertptr+"=tmpptr;");
3839 output.println("}");
3840 output.println("}");
3844 if (!state.DELAYCOMP) {
3846 output.println("if (transCommit()) {");
3847 /* Transaction aborts if it returns true */
3848 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3849 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3850 output.println("}");
3852 if (delaycomp.optimizeTrans(lb, faen.getAtomicEnter())&&(!state.STMARRAY||state.DUALVIEW)) {
3853 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3854 output.println("LIGHTWEIGHTCOMMIT("+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+", transretry"+faen.getAtomicEnter().getIdentifier()+");");
3856 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3857 TempDescriptor tmp=tmpit.next();
3858 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3860 } else if (delaycomp.needsFission(lb, faen.getAtomicEnter())) {
3861 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3863 output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {");
3864 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3865 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3866 output.println("}");
3868 output.println("else {");
3869 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3870 TempDescriptor tmp=tmpit.next();
3871 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3873 output.println("}");
3875 output.println("if (transCommit(NULL, NULL, NULL, NULL)) {");
3876 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3877 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3878 output.println("}");
3883 public void generateFlatSESEEnterNode( FlatMethod fm,
3885 FlatSESEEnterNode fsen,
3886 PrintWriter output) {
3887 // if MLP flag is off, okay that SESE nodes are in IR graph,
3888 // just skip over them and code generates exactly the same
3889 if( !(state.MLP || state.OOOJAVA) ) {
3892 // there may be an SESE in an unreachable method, skip over
3893 if( (state.MLP && !mlpa.getAllSESEs().contains( fsen )) ||
3894 (state.OOOJAVA && !oooa.getAllSESEs().contains(fsen))
3899 // also, if we have encountered a placeholder, just skip it
3900 if( fsen.getIsCallerSESEplaceholder() ) {
3904 output.println(" {");
3906 if( state.COREPROF ) {
3907 output.println("#ifdef CP_EVENTID_TASKDISPATCH");
3908 output.println(" CP_LOGEVENT( CP_EVENTID_TASKDISPATCH, CP_EVENTTYPE_BEGIN );");
3909 output.println("#endif");
3913 // before doing anything, lock your own record and increment the running children
3914 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3915 (state.OOOJAVA && fsen != oooa.getMainSESE())
3917 output.println(" childSESE++;");
3920 // allocate the space for this record
3921 output.println( "#ifndef OOO_DISABLE_TASKMEMPOOL" );
3923 output.println( "#ifdef CP_EVENTID_POOLALLOC");
3924 output.println( " CP_LOGEVENT( CP_EVENTID_POOLALLOC, CP_EVENTTYPE_BEGIN );");
3925 output.println( "#endif");
3926 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3927 (state.OOOJAVA && fsen != oooa.getMainSESE())
3930 fsen.getSESErecordName()+"* seseToIssue = ("+
3931 fsen.getSESErecordName()+"*) taskpoolalloc( runningSESE->taskRecordMemPool );");
3934 fsen.getSESErecordName()+"* seseToIssue = ("+
3935 fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
3936 fsen.getSESErecordName()+" ) );");
3938 output.println( "#ifdef CP_EVENTID_POOLALLOC");
3939 output.println( " CP_LOGEVENT( CP_EVENTID_POOLALLOC, CP_EVENTTYPE_END );");
3940 output.println( "#endif");
3942 output.println( "#else // OOO_DISABLE_TASKMEMPOOL" );
3944 fsen.getSESErecordName()+"* seseToIssue = ("+
3945 fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
3946 fsen.getSESErecordName()+" ) );");
3947 output.println( "#endif // OOO_DISABLE_TASKMEMPOOL" );
3950 // set up the SESE in-set and out-set objects, which look
3951 // like a garbage list
3952 output.println(" struct garbagelist * gl= (struct garbagelist *)&(((SESEcommon*)(seseToIssue))[1]);");
3953 output.println(" gl->size="+calculateSizeOfSESEParamList(fsen)+";");
3954 output.println(" gl->next = NULL;");
3957 //flag the SESE status as 1...it will be reset
3958 output.println(" seseToIssue->common.rcrstatus=1;");
3961 // there are pointers to SESE records the newly-issued SESE
3962 // will use to get values it depends on them for--how many
3963 // are there, and what is the offset from the total SESE
3964 // record to the first dependent record pointer?
3965 output.println(" seseToIssue->common.numDependentSESErecords="+
3966 fsen.getNumDepRecs()+";");
3968 // we only need this (and it will only compile) when the number of dependent
3969 // SESE records is non-zero
3970 if( fsen.getFirstDepRecField() != null ) {
3971 output.println(" seseToIssue->common.offsetToDepSESErecords=(INTPTR)sizeof("+
3972 fsen.getSESErecordName()+") - (INTPTR)&((("+
3973 fsen.getSESErecordName()+"*)0)->"+fsen.getFirstDepRecField()+");"
3977 if (state.RCR&&fsen.getInVarsForDynamicCoarseConflictResolution().size()>0) {
3978 output.println(" seseToIssue->common.offsetToParamRecords=(INTPTR) & ((("+fsen.getSESErecordName()+"*)0)->rcrRecords);");
3981 // fill in common data
3982 output.println(" int localCount=0;");
3983 output.println(" seseToIssue->common.classID = "+fsen.getIdentifier()+";");
3984 output.println(" seseToIssue->common.unresolvedDependencies = 10000;");
3985 output.println(" seseToIssue->common.parentsStallSem = NULL;");
3986 output.println(" initQueue(&seseToIssue->common.forwardList);");
3987 output.println(" seseToIssue->common.doneExecuting = FALSE;");
3988 output.println(" seseToIssue->common.numRunningChildren = 0;");
3989 output.println( "#ifdef OOO_DISABLE_TASKMEMPOOL" );
3990 output.println(" pthread_cond_init( &(seseToIssue->common.runningChildrenCond), NULL );");
3991 output.println("#endif");
3992 output.println(" seseToIssue->common.parent = runningSESE;");
3993 // start with refCount = 2, one being the count that the child itself
3994 // will decrement when it retires, to say it is done using its own
3995 // record, and the other count is for the parent that will remember
3996 // the static name of this new child below
3998 // if we're using RCR, ref count is 3 because the traverser has
4000 output.println(" seseToIssue->common.refCount = 3;");
4002 output.println(" seseToIssue->common.refCount = 2;");
4005 // all READY in-vars should be copied now and be done with it
4006 Iterator<TempDescriptor> tempItr = fsen.getReadyInVarSet().iterator();
4007 while( tempItr.hasNext() ) {
4008 TempDescriptor temp = tempItr.next();
4010 // when we are issuing the main SESE or an SESE with placeholder
4011 // caller SESE as parent, generate temp child child's eclosing method,
4012 // otherwise use the parent's enclosing method as the context
4013 boolean useParentContext = false;
4015 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
4016 (state.OOOJAVA && fsen != oooa.getMainSESE())
4018 assert fsen.getParent() != null;
4019 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
4020 useParentContext = true;
4024 if( useParentContext ) {
4025 output.println(" seseToIssue->"+temp+" = "+
4026 generateTemp( fsen.getParent().getfmBogus(), temp, null )+";");
4028 output.println(" seseToIssue->"+temp+" = "+
4029 generateTemp( fsen.getfmEnclosing(), temp, null )+";");
4033 // before potentially adding this SESE to other forwarding lists,
4035 output.println( "#ifdef OOO_DISABLE_TASKMEMPOOL" );
4036 output.println(" pthread_mutex_init( &(seseToIssue->common.lock), NULL );");
4037 output.println("#endif");
4039 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
4040 (state.OOOJAVA && fsen != oooa.getMainSESE())
4042 // count up outstanding dependencies, static first, then dynamic
4043 Iterator<SESEandAgePair> staticSrcsItr = fsen.getStaticInVarSrcs().iterator();
4044 while( staticSrcsItr.hasNext() ) {
4045 SESEandAgePair srcPair = staticSrcsItr.next();
4046 output.println(" {");
4047 output.println(" SESEcommon* src = (SESEcommon*)"+srcPair+";");
4048 output.println(" pthread_mutex_lock( &(src->lock) );");
4050 output.println(" if( !src->doneExecuting ) {");
4051 output.println(" addNewItem( &src->forwardList, seseToIssue );");
4052 output.println(" ++(localCount);");
4053 output.println(" }");
4054 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
4055 output.println(" ADD_REFERENCE_TO( src );");
4056 output.println("#endif" );
4057 output.println(" pthread_mutex_unlock( &(src->lock) );");
4058 output.println(" }");
4060 // whether or not it is an outstanding dependency, make sure
4061 // to pass the static name to the child's record
4062 output.println(" seseToIssue->"+srcPair+" = "+
4063 "("+srcPair.getSESE().getSESErecordName()+"*)"+
4067 // dynamic sources might already be accounted for in the static list,
4068 // so only add them to forwarding lists if they're not already there
4069 Iterator<TempDescriptor> dynVarsItr = fsen.getDynamicInVarSet().iterator();
4070 while( dynVarsItr.hasNext() ) {
4071 TempDescriptor dynInVar = dynVarsItr.next();
4072 output.println(" {");
4073 output.println(" SESEcommon* src = (SESEcommon*)"+dynInVar+"_srcSESE;");
4075 // the dynamic source is NULL if it comes from your own space--you can't pass
4076 // the address off to the new child, because you're not done executing and
4077 // might change the variable, so copy it right now
4078 output.println(" if( src != NULL ) {");
4079 output.println(" pthread_mutex_lock( &(src->lock) );");
4083 output.println(" if( isEmpty( &src->forwardList ) ||");
4084 output.println(" seseToIssue != peekItem( &src->forwardList ) ) {");
4085 output.println(" if( !src->doneExecuting ) {");
4086 output.println(" addNewItem( &src->forwardList, seseToIssue );");
4087 output.println(" ++(localCount);");
4088 output.println(" }");
4089 output.println(" }");
4090 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
4091 output.println(" ADD_REFERENCE_TO( src );");
4092 output.println("#endif" );
4093 output.println(" pthread_mutex_unlock( &(src->lock) );");
4094 output.println(" seseToIssue->"+dynInVar+"_srcOffset = "+dynInVar+"_srcOffset;");
4095 output.println(" } else {");
4097 boolean useParentContext = false;
4098 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
4099 (state.OOOJAVA && fsen != oooa.getMainSESE())
4101 assert fsen.getParent() != null;
4102 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
4103 useParentContext = true;
4106 if( useParentContext ) {
4107 output.println(" seseToIssue->"+dynInVar+" = "+
4108 generateTemp( fsen.getParent().getfmBogus(), dynInVar, null )+";");
4110 output.println(" seseToIssue->"+dynInVar+" = "+
4111 generateTemp( fsen.getfmEnclosing(), dynInVar, null )+";");
4114 output.println(" }");
4115 output.println(" }");
4117 // even if the value is already copied, make sure your NULL source
4118 // gets passed so child knows it already has the dynamic value
4119 output.println(" seseToIssue->"+dynInVar+"_srcSESE = "+dynInVar+"_srcSESE;");
4125 // maintain pointers for finding dynamic SESE
4126 // instances from static names
4127 SESEandAgePair pairNewest = new SESEandAgePair( fsen, 0 );
4128 SESEandAgePair pairOldest = new SESEandAgePair( fsen, fsen.getOldestAgeToTrack() );
4129 if( fsen.getParent() != null &&
4130 fsen.getParent().getNeededStaticNames().contains( pairNewest )
4132 output.println(" {");
4133 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
4134 output.println(" SESEcommon* oldest = "+pairOldest+";");
4135 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
4137 for( int i = fsen.getOldestAgeToTrack(); i > 0; --i ) {
4138 SESEandAgePair pair1 = new SESEandAgePair( fsen, i );
4139 SESEandAgePair pair2 = new SESEandAgePair( fsen, i-1 );
4140 output.println(" "+pair1+" = "+pair2+";");
4142 output.println(" "+pairNewest+" = &(seseToIssue->common);");
4144 // no need to add a reference to whatever is the newest record, because
4145 // we initialized seseToIssue->refCount to *2*
4146 // but release a reference to whatever was the oldest BEFORE the shift
4147 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
4148 output.println(" if( oldest != NULL ) {");
4149 output.println(" RELEASE_REFERENCE_TO( oldest );");
4150 output.println(" }");
4151 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
4152 output.println(" }");
4157 if( state.COREPROF ) {
4158 output.println("#ifdef CP_EVENTID_PREPAREMEMQ");
4159 output.println(" CP_LOGEVENT( CP_EVENTID_PREPAREMEMQ, CP_EVENTTYPE_BEGIN );");
4160 output.println("#endif");
4165 // count up memory conflict dependencies,
4167 dispatchMEMRC(fm, lb, fsen, output);
4168 } else if(state.OOOJAVA){
4169 FlatSESEEnterNode parent = fsen.getParent();
4170 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(parent);
4171 if (graph != null && graph.hasConflictEdge()) {
4172 Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
4174 output.println(" //add memory queue element");
4175 Analysis.OoOJava.SESEWaitingQueue seseWaitingQueue=
4176 graph.getWaitingElementSetBySESEID(fsen.getIdentifier(), seseLockSet);
4177 if(seseWaitingQueue.getWaitingElementSize()>0) {
4178 output.println(" {");
4179 output.println(" REntry* rentry=NULL;");
4180 output.println(" INTPTR* pointer=NULL;");
4181 output.println(" seseToIssue->common.rentryIdx=0;");
4183 Set<Integer> queueIDSet=seseWaitingQueue.getQueueIDSet();
4184 for (Iterator iterator = queueIDSet.iterator(); iterator.hasNext();) {
4185 Integer key = (Integer) iterator.next();
4186 int queueID=key.intValue();
4187 Set<Analysis.OoOJava.WaitingElement> waitingQueueSet =
4188 seseWaitingQueue.getWaitingElementSet(queueID);
4189 int enqueueType=seseWaitingQueue.getType(queueID);
4190 if(enqueueType==SESEWaitingQueue.EXCEPTION) {
4191 output.println(" INITIALIZEBUF(runningSESE->memoryQueueArray[" + queueID+ "]);");
4193 for (Iterator iterator2 = waitingQueueSet.iterator(); iterator2.hasNext();) {
4194 Analysis.OoOJava.WaitingElement waitingElement
4195 = (Analysis.OoOJava.WaitingElement) iterator2.next();
4196 if (waitingElement.getStatus() >= ConflictNode.COARSE) {
4197 output.println(" rentry=mlpCreateREntry(runningSESE->memoryQueueArray["+ queueID+ "],"
4198 + waitingElement.getStatus()
4199 + ", &(seseToIssue->common));");
4201 TempDescriptor td = waitingElement.getTempDesc();
4202 // decide whether waiting element is dynamic or static
4203 if (fsen.getDynamicInVarSet().contains(td)) {
4204 // dynamic in-var case
4205 output.println(" pointer=seseToIssue->"
4206 + waitingElement.getDynID()
4207 + "_srcSESE+seseToIssue->"
4208 + waitingElement.getDynID()
4210 output.println(" rentry=mlpCreateFineREntry(runningSESE->memoryQueueArray["+ queueID+ "],"
4211 + waitingElement.getStatus()
4212 + ", &(seseToIssue->common), pointer );");
4213 } else if (fsen.getStaticInVarSet().contains(td)) {
4214 // static in-var case
4215 VariableSourceToken vst = fsen.getStaticInVarSrc(td);
4218 String srcId = "SESE_" + vst.getSESE().getPrettyIdentifier()
4219 + vst.getSESE().getIdentifier()
4220 + "_" + vst.getAge();
4221 output.println(" pointer=(void*)&seseToIssue->"
4227 output.println(" rentry=mlpCreateFineREntry(runningSESE->memoryQueueArray["+ queueID+ "],"
4228 + waitingElement.getStatus()
4229 + ", &(seseToIssue->common), pointer );");
4232 output.println(" rentry=mlpCreateFineREntry(runningSESE->memoryQueueArray["+ queueID+ "],"
4233 + waitingElement.getStatus()
4234 + ", &(seseToIssue->common), (void*)&seseToIssue->"
4235 + waitingElement.getDynID()
4239 output.println(" rentry->queue=runningSESE->memoryQueueArray["
4240 + waitingElement.getQueueID()
4243 if(enqueueType==SESEWaitingQueue.NORMAL){
4244 output.println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
4245 output.println(" if(ADDRENTRY(runningSESE->memoryQueueArray["
4246 + waitingElement.getQueueID()
4247 + "],rentry)==NOTREADY) {");
4248 output.println(" localCount++;");
4249 output.println(" }");
4251 output.println(" ADDRENTRYTOBUF(runningSESE->memoryQueueArray[" + waitingElement.getQueueID() + "],rentry);");
4254 if(enqueueType!=SESEWaitingQueue.NORMAL){
4255 output.println(" localCount+=RESOLVEBUF(runningSESE->memoryQueueArray["
4256 + queueID+ "],&seseToIssue->common);");
4259 output.println(" }");
4264 ConflictGraph graph = null;
4265 FlatSESEEnterNode parent = fsen.getParent();
4266 if (parent != null) {
4267 if (parent.isCallerSESEplaceholder) {
4268 graph = mlpa.getConflictGraphResults().get(parent.getfmEnclosing());
4270 graph = mlpa.getConflictGraphResults().get(parent);
4273 if (graph != null && graph.hasConflictEdge()) {
4274 HashSet<SESELock> seseLockSet = mlpa.getConflictGraphLockMap()
4277 output.println(" //add memory queue element");
4278 SESEWaitingQueue seseWaitingQueue=graph.getWaitingElementSetBySESEID(fsen.getIdentifier(),
4280 if(seseWaitingQueue.getWaitingElementSize()>0){
4281 output.println(" {");
4282 output.println(" REntry* rentry=NULL;");
4283 output.println(" INTPTR* pointer=NULL;");
4284 output.println(" seseToIssue->common.rentryIdx=0;");
4286 Set<Integer> queueIDSet=seseWaitingQueue.getQueueIDSet();
4287 for (Iterator iterator = queueIDSet.iterator(); iterator
4289 Integer key = (Integer) iterator.next();
4290 int queueID=key.intValue();
4291 Set<WaitingElement> waitingQueueSet = seseWaitingQueue.getWaitingElementSet(queueID);
4292 int enqueueType=seseWaitingQueue.getType(queueID);
4293 if(enqueueType==SESEWaitingQueue.EXCEPTION){
4294 output.println(" INITIALIZEBUF(runningSESE->memoryQueueArray["
4297 for (Iterator iterator2 = waitingQueueSet.iterator(); iterator2
4299 WaitingElement waitingElement = (WaitingElement) iterator2
4301 if (waitingElement.getStatus() >= ConflictNode.COARSE) {
4302 output.println(" rentry=mlpCreateREntry(runningSESE->memoryQueueArray["+ queueID+ "],"
4303 + waitingElement.getStatus()
4304 + ", &(seseToIssue->common));");
4306 TempDescriptor td = waitingElement
4308 // decide whether waiting element is dynamic or
4310 if (fsen.getDynamicInVarSet().contains(td)) {
4311 // dynamic in-var case
4312 output.println(" pointer=seseToIssue->"
4313 + waitingElement.getDynID()
4314 + "_srcSESE+seseToIssue->"
4315 + waitingElement.getDynID()
4318 .println(" rentry=mlpCreateFineREntry(runningSESE->memoryQueueArray["+ queueID+ "],"
4321 + ", &(seseToIssue->common), pointer );");
4322 } else if (fsen.getStaticInVarSet()
4324 // static in-var case
4325 VariableSourceToken vst = fsen
4326 .getStaticInVarSrc(td);
4329 String srcId = "SESE_"
4331 .getPrettyIdentifier()
4332 + vst.getSESE().getIdentifier()
4333 + "_" + vst.getAge();
4335 .println(" pointer=(void*)&seseToIssue->"
4342 .println(" rentry=mlpCreateFineREntry(runningSESE->memoryQueueArray["+ queueID+ "],"
4345 + ", &(seseToIssue->common), pointer );");
4350 .println(" rentry=mlpCreateFineREntry(runningSESE->memoryQueueArray["+ queueID+ "],"
4353 + ", &(seseToIssue->common), (void*)&seseToIssue->"
4354 + waitingElement.getDynID()
4359 .println(" rentry->queue=runningSESE->memoryQueueArray["
4360 + waitingElement.getQueueID()
4363 if(enqueueType==SESEWaitingQueue.NORMAL){
4365 .println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
4367 .println(" if(ADDRENTRY(runningSESE->memoryQueueArray["
4368 + waitingElement.getQueueID()
4369 + "],rentry)==NOTREADY){");
4370 output.println(" ++(localCount);");
4371 output.println(" } ");
4374 .println(" ADDRENTRYTOBUF(runningSESE->memoryQueueArray["
4375 + waitingElement.getQueueID()
4379 if(enqueueType!=SESEWaitingQueue.NORMAL){
4380 output.println(" localCount+=RESOLVEBUF(runningSESE->memoryQueueArray["
4381 + queueID+ "],&seseToIssue->common);");
4384 output.println(" }");
4391 if( state.COREPROF ) {
4392 output.println("#ifdef CP_EVENTID_PREPAREMEMQ");
4393 output.println(" CP_LOGEVENT( CP_EVENTID_PREPAREMEMQ, CP_EVENTTYPE_END );");
4394 output.println("#endif");
4397 // Enqueue Task Record
4399 output.println(" enqueueTR(TRqueue, (void *)seseToIssue);");
4402 // if there were no outstanding dependencies, issue here
4403 output.println(" if( atomic_sub_and_test(10000-localCount,&(seseToIssue->common.unresolvedDependencies) ) ) {");
4404 output.println(" workScheduleSubmit( (void*)seseToIssue );");
4405 output.println(" }");
4409 if( state.COREPROF ) {
4410 output.println("#ifdef CP_EVENTID_TASKDISPATCH");
4411 output.println(" CP_LOGEVENT( CP_EVENTID_TASKDISPATCH, CP_EVENTTYPE_END );");
4412 output.println("#endif");
4415 output.println(" }");
4419 void dispatchMEMRC(FlatMethod fm, LocalityBinding lb, FlatSESEEnterNode fsen, PrintWriter output) {
4420 FlatSESEEnterNode parent = fsen.getParent();
4421 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(parent);
4422 if (graph != null && graph.hasConflictEdge()) {
4423 Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
4424 Analysis.OoOJava.SESEWaitingQueue seseWaitingQueue=graph.getWaitingElementSetBySESEID(fsen.getIdentifier(), seseLockSet);
4425 if(seseWaitingQueue.getWaitingElementSize()>0) {
4426 output.println(" {");
4427 output.println(" REntry* rentry=NULL;");
4428 output.println(" INTPTR* pointer=NULL;");
4429 output.println(" seseToIssue->common.rentryIdx=0;");
4430 output.println(" int dispCount;");
4431 Vector<TempDescriptor> invars=fsen.getInVarsForDynamicCoarseConflictResolution();
4432 System.out.println(fm.getMethod()+"["+invars+"]");
4433 for(int i=0;i<invars.size();i++) {
4434 TempDescriptor td=invars.get(i);
4435 Set<Analysis.OoOJava.WaitingElement> weset=seseWaitingQueue.getWaitingElementSet(td);
4437 System.out.println("ERROR:"+td+" "+fsen+" "+fm.getMethod());
4438 int numqueues=weset.size();
4439 output.println(" seseToIssue->rcrRecords["+i+"].flag="+numqueues+";");
4440 output.println(" dispCount=0;");
4441 for(Iterator<Analysis.OoOJava.WaitingElement> wtit=weset.iterator();wtit.hasNext();) {
4442 Analysis.OoOJava.WaitingElement waitingElement=wtit.next();
4443 int queueID=waitingElement.getQueueID();
4444 assert(waitingElement.getStatus()>=ConflictNode.COARSE);
4445 output.println(" rentry=mlpCreateREntry(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "]," + waitingElement.getStatus() + ", &(seseToIssue->common));");
4446 output.println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
4447 output.println(" rentry->queue=runningSESE->memoryQueueArray[" + waitingElement.getQueueID()+"];");
4448 output.println(" if(ADDRENTRY(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "],rentry)==READY) {");
4449 output.println(" dispCount++;");
4450 output.println(" }");
4452 output.println(" if(!dispCount || !atomic_sub_and_test(dispCount,&(seseToIssue->rcrRecords["+i+"].flag)))");
4453 output.println(" localCount++;");
4454 if (fsen.getDynamicInVarSet().contains(td)) {
4455 // dynamic in-var case
4456 //output.println(" pointer=seseToIssue->" + waitingElement.getDynID()+ "_srcSESE+seseToIssue->"+ waitingElement.getDynID()+ "_srcOffset;");
4457 //output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", &(seseToIssue->common), pointer );");
4460 output.println(" }");
4465 public void generateFlatSESEExitNode( FlatMethod fm,
4467 FlatSESEExitNode fsexn,
4468 PrintWriter output) {
4470 // if MLP flag is off, okay that SESE nodes are in IR graph,
4471 // just skip over them and code generates exactly the same
4472 if( ! (state.MLP || state.OOOJAVA) ) {
4476 // get the enter node for this exit that has meta data embedded
4477 FlatSESEEnterNode fsen = fsexn.getFlatEnter();
4479 // there may be an SESE in an unreachable method, skip over
4480 if( (state.MLP && !mlpa.getAllSESEs().contains( fsen )) ||
4481 (state.OOOJAVA && !oooa.getAllSESEs().contains( fsen ))
4486 // also, if we have encountered a placeholder, just jump it
4487 if( fsen.getIsCallerSESEplaceholder() ) {
4491 if( state.COREPROF ) {
4492 output.println("#ifdef CP_EVENTID_TASKEXECUTE");
4493 output.println(" CP_LOGEVENT( CP_EVENTID_TASKEXECUTE, CP_EVENTTYPE_END );");
4494 output.println("#endif");
4497 output.println(" /* SESE exiting */");
4499 if( state.COREPROF ) {
4500 output.println("#ifdef CP_EVENTID_TASKRETIRE");
4501 output.println(" CP_LOGEVENT( CP_EVENTID_TASKRETIRE, CP_EVENTTYPE_BEGIN );");
4502 output.println("#endif");
4506 // this SESE cannot be done until all of its children are done
4507 // so grab your own lock with the condition variable for watching
4508 // that the number of your running children is greater than zero
4509 output.println(" atomic_add(childSESE, &runningSESE->numRunningChildren);");
4510 output.println(" pthread_mutex_lock( &(runningSESE->lock) );");
4511 output.println(" if( runningSESE->numRunningChildren > 0 ) {");
4512 output.println(" stopforgc( (struct garbagelist *)&___locals___ );");
4513 output.println(" do {");
4514 output.println(" pthread_cond_wait( &(runningSESE->runningChildrenCond), &(runningSESE->lock) );");
4515 output.println(" } while( runningSESE->numRunningChildren > 0 );");
4516 output.println(" restartaftergc();");
4517 output.println(" }");
4520 // copy out-set from local temps into the sese record
4521 Iterator<TempDescriptor> itr = fsen.getOutVarSet().iterator();
4522 while( itr.hasNext() ) {
4523 TempDescriptor temp = itr.next();
4525 // only have to do this for primitives non-arrays
4527 temp.getType().isPrimitive() && !temp.getType().isArray()
4533 // have to determine the context enclosing this sese
4534 boolean useParentContext = false;
4536 if( (state.MLP &&fsen != mlpa.getMainSESE()) ||
4537 (state.OOOJAVA &&fsen != oooa.getMainSESE())
4539 assert fsen.getParent() != null;
4540 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
4541 useParentContext = true;
4546 if( useParentContext ) {
4547 from = generateTemp( fsen.getParent().getfmBogus(), temp, null );
4549 from = generateTemp( fsen.getfmEnclosing(), temp, null );
4552 output.println(" "+paramsprefix+
4553 "->"+temp.getSafeSymbol()+
4557 // mark yourself done, your task data is now read-only
4558 output.println(" runningSESE->doneExecuting = TRUE;");
4560 // if parent is stalling on you, let them know you're done
4561 if( (state.MLP && fsexn.getFlatEnter() != mlpa.getMainSESE()) ||
4562 (state.OOOJAVA && fsexn.getFlatEnter() != oooa.getMainSESE())
4564 output.println(" if( runningSESE->parentsStallSem != NULL ) {");
4565 output.println(" psem_give( runningSESE->parentsStallSem );");
4566 output.println(" }");
4569 output.println(" pthread_mutex_unlock( &(runningSESE->lock) );");
4571 // decrement dependency count for all SESE's on your forwarding list
4574 output.println(" while( !isEmpty( &runningSESE->forwardList ) ) {");
4575 output.println(" SESEcommon* consumer = (SESEcommon*) getItem( &runningSESE->forwardList );");
4578 output.println(" if(consumer->rentryIdx>0){");
4579 output.println(" // resolved null pointer");
4580 output.println(" int idx;");
4581 output.println(" for(idx=0;idx<consumer->rentryIdx;idx++){");
4582 output.println(" resolvePointer(consumer->rentryArray[idx]);");
4583 output.println(" }");
4584 output.println(" }");
4586 output.println(" if( atomic_sub_and_test( 1, &(consumer->unresolvedDependencies) ) ){");
4587 output.println(" workScheduleSubmit( (void*)consumer );");
4588 output.println(" }");
4589 output.println(" }");
4593 // clean up its lock element from waiting queue, and decrement dependency count for next SESE block
4594 if((state.MLP && fsen != mlpa.getMainSESE()) ||
4595 (state.OOOJAVA && fsen != oooa.getMainSESE())) {
4597 output.println(" /* check memory dependency*/");
4598 output.println(" {");
4599 output.println(" int idx;");
4600 output.println(" for(idx=0;idx<___params___->common.rentryIdx;idx++){");
4601 output.println(" REntry* re=___params___->common.rentryArray[idx];");
4602 output.println(" RETIRERENTRY(re->queue,re);");
4603 output.println(" }");
4604 output.println(" }");
4608 if (state.RCR&&fsen.getDynamicInVarSet().size()>0) {
4609 /* Make sure the running SESE is finished */
4610 output.println(" if (unlikely(runningSESE->rcrstatus!=0)) {");
4611 output.println(" if(!CAS(&runningSESE->rcrstatus,1,0)) {");
4612 output.println(" while(runningSESE->rcrstatus) {");
4613 output.println(" BARRIER();");
4614 output.println(" sched_yield();");
4615 output.println(" }");
4616 output.println(" }");
4617 output.println(" }");
4618 output.println("{");
4619 output.println(" int idx,idx2;");
4620 if (fsen.getDynamicInVarSet().size()==1) {
4621 output.println(" idx=0; {");
4623 output.println(" for(idx=0;idx<"+fsen.getDynamicInVarSet().size()+";idx++){");
4625 output.println(" struct rcrRecord *rec="+paramsprefix+"->rcrRecords[idx];");
4626 output.println(" while(rec!=NULL) {");
4627 output.println(" for(idx2=0;idx2<rec->index;idx2++) {");
4628 output.println(" rcr_RETIREHASHTABLE(allHashStructures[0],rec,rec->array[idx2], (BinItem_rcr *) rcr->ptrarray[idx2]);");
4629 output.println(" }");//exit idx2 for loop
4630 output.println(" rec=rec->next;");
4631 output.println(" }");//exit rec while loop
4632 output.println(" }");//exit idx for loop
4633 output.println("}");
4637 // a task has variables to track static/dynamic instances
4638 // that serve as sources, release the parent's ref of each
4639 // non-null var of these types
4640 output.println(" // releasing static SESEs");
4641 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
4642 Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
4643 while( pItr.hasNext() ) {
4644 SESEandAgePair pair = pItr.next();
4645 output.println(" if( "+pair+" != NULL ) {");
4646 output.println(" RELEASE_REFERENCE_TO( "+pair+" );");
4647 output.println(" }");
4649 output.println(" // releasing dynamic variable sources");
4650 Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
4651 while( dynSrcItr.hasNext() ) {
4652 TempDescriptor dynSrcVar = dynSrcItr.next();
4653 output.println(" if( "+dynSrcVar+"_srcSESE != NULL ) {");
4654 output.println(" RELEASE_REFERENCE_TO( "+dynSrcVar+"_srcSESE );");
4655 output.println(" }");
4657 // destroy this task's mempool if it is not a leaf task
4658 if( !fsen.getIsLeafSESE() ) {
4659 output.println(" pooldestroy( runningSESE->taskRecordMemPool );");
4661 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
4664 output.println("{");
4665 output.println("SESEcommon *myparent=runningSESE->parent;");
4667 // if this is not the Main sese (which has no parent) then return
4668 // THIS task's record to the PARENT'S task record pool, and only if
4669 // the reference count is now zero
4670 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
4671 (state.OOOJAVA && fsen != oooa.getMainSESE())
4673 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
4674 output.println(" RELEASE_REFERENCE_TO( runningSESE );");
4675 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
4677 // the main task has no parent, just free its record
4678 output.println(" mlpFreeSESErecord( runningSESE );");
4682 // last of all, decrement your parent's number of running children
4683 output.println(" if( myparent != NULL ) {");
4684 output.println(" if( atomic_sub_and_test( 1, &(myparent->numRunningChildren) ) ) {");
4685 output.println(" pthread_mutex_lock ( &(myparent->lock) );");
4686 output.println(" pthread_cond_signal ( &(myparent->runningChildrenCond) );");
4687 output.println(" pthread_mutex_unlock( &(myparent->lock) );");
4688 output.println(" }");
4689 output.println(" }");
4691 output.println("}");
4693 // as this thread is wrapping up the task, make sure the thread-local var
4694 // for the currently running task record references an invalid task
4695 output.println(" runningSESE = (SESEcommon*) 0x1;");
4697 if( state.COREPROF ) {
4698 output.println("#ifdef CP_EVENTID_TASKRETIRE");
4699 output.println(" CP_LOGEVENT( CP_EVENTID_TASKRETIRE, CP_EVENTTYPE_END );");
4700 output.println("#endif");
4704 public void generateFlatWriteDynamicVarNode( FlatMethod fm,
4706 FlatWriteDynamicVarNode fwdvn,
4709 if( !(state.MLP || state.OOOJAVA) ) {
4710 // should node should not be in an IR graph if the
4711 // MLP flag is not set
4712 throw new Error("Unexpected presence of FlatWriteDynamicVarNode");
4715 Hashtable<TempDescriptor, VSTWrapper> writeDynamic = fwdvn.getVar2src();
4717 assert writeDynamic != null;
4719 Iterator wdItr = writeDynamic.entrySet().iterator();
4720 while( wdItr.hasNext() ) {
4721 Map.Entry me = (Map.Entry) wdItr.next();
4722 TempDescriptor refVar = (TempDescriptor) me.getKey();
4723 VSTWrapper vstW = (VSTWrapper) me.getValue();
4724 VariableSourceToken vst = vstW.vst;
4726 output.println(" {");
4727 output.println(" SESEcommon* oldSrc = "+refVar+"_srcSESE;");
4730 // if there is no given source, this variable is ready so
4731 // mark src pointer NULL to signify that the var is up-to-date
4732 output.println(" "+refVar+"_srcSESE = NULL;");
4734 // otherwise we track where it will come from
4735 SESEandAgePair instance = new SESEandAgePair( vst.getSESE(), vst.getAge() );
4736 output.println(" "+refVar+"_srcSESE = "+instance+";");
4737 output.println(" "+refVar+"_srcOffset = (INTPTR) &((("+
4738 vst.getSESE().getSESErecordName()+"*)0)->"+vst.getAddrVar()+");");
4741 // no matter what we did above, track reference count of whatever
4742 // this variable pointed to, do release last in case we're just
4743 // copying the same value in because 1->2->1 is safe but ref count
4744 // 1->0->1 has a window where it looks like it should be free'd
4745 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
4746 output.println(" if( "+refVar+"_srcSESE != NULL ) {");
4747 output.println(" ADD_REFERENCE_TO( "+refVar+"_srcSESE );");
4748 output.println(" }");
4749 output.println(" if( oldSrc != NULL ) {");
4750 output.println(" RELEASE_REFERENCE_TO( oldSrc );");
4751 output.println(" }");
4752 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
4754 output.println(" }");
4759 private void generateFlatCheckNode(FlatMethod fm, LocalityBinding lb, FlatCheckNode fcn, PrintWriter output) {
4760 if (state.CONSCHECK) {
4761 String specname=fcn.getSpec();
4762 String varname="repairstate___";
4763 output.println("{");
4764 output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
4766 TempDescriptor[] temps=fcn.getTemps();
4767 String[] vars=fcn.getVars();
4768 for(int i=0; i<temps.length; i++) {
4769 output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i],lb)+";");
4772 output.println("if (doanalysis"+specname+"("+varname+")) {");
4773 output.println("free"+specname+"_state("+varname+");");
4774 output.println("} else {");
4775 output.println("/* Bad invariant */");
4776 output.println("free"+specname+"_state("+varname+");");
4777 output.println("abort_task();");
4778 output.println("}");
4779 output.println("}");
4783 private void generateFlatCall(FlatMethod fm, LocalityBinding lb, FlatCall fc, PrintWriter output) {
4785 MethodDescriptor md=fc.getMethod();
4786 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? locality.getBinding(lb, fc) : md);
4787 ClassDescriptor cn=md.getClassDesc();
4789 // if the called method is a static block or a static method or a constructor
4790 // need to check if it can be invoked inside some static block
4792 // TODO add version for normal Java later
4793 if((md.isStatic() || md.isStaticBlock() || md.isConstructor()) &&
4794 ((fm.getMethod().isStaticBlock()) || (fm.getMethod().isInvokedByStatic()))) {
4795 if(!md.isInvokedByStatic()) {
4796 System.err.println("Error: a method that is invoked inside a static block is not tagged!");
4798 // is a static block or is invoked in some static block
4799 ClassDescriptor cd = fm.getMethod().getClassDesc();
4801 // the same class, do nothing
4802 // TODO may want to invoke static field initialization here
4804 if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) {
4805 // need to check if the class' static fields have been initialized and/or
4806 // its static blocks have been executed
4807 output.println("#ifdef MGC_STATIC_INIT_CHECK");
4808 output.println("if(global_defs_p->" + cn.getSafeSymbol()+"static_block_exe_flag == 0) {");
4809 if(cn.getNumStaticFields() != 0) {
4810 // TODO add static field initialization here
4812 if(cn.getNumStaticBlocks() != 0) {
4813 MethodDescriptor t_md = (MethodDescriptor)cn.getMethodTable().get("staticblocks");
4814 output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();");
4816 output.println(" global_defs_p->" + cn.getSafeSymbol()+"static_block_exe_flag = 1;");
4818 output.println("}");
4819 output.println("#endif // MGC_STATIC_INIT_CHECK");
4825 output.println("{");
4826 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4828 LocalityBinding fclb=locality.getBinding(lb, fc);
4829 output.print(" struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
4831 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
4832 output.print(objectparams.numPointers());
4833 output.print(", "+localsprefixaddr);
4834 if (md.getThis()!=null) {
4836 output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis(),lb));
4838 if (fc.getThis()!=null&&md.getThis()==null) {
4839 System.out.println("WARNING!!!!!!!!!!!!");
4840 System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
4844 for(int i=0; i<fc.numArgs(); i++) {
4845 Descriptor var=md.getParameter(i);
4846 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
4847 if (objectparams.isParamPtr(paramtemp)) {
4848 TempDescriptor targ=fc.getArg(i);
4850 TypeDescriptor td=md.getParamType(i);
4852 output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
4854 output.print("(struct "+md.getParamType(i).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
4857 output.println("};");
4862 if (fc.getReturnTemp()!=null)
4863 output.print(generateTemp(fm,fc.getReturnTemp(),lb)+"=");
4865 /* Do we need to do virtual dispatch? */
4866 if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
4869 LocalityBinding fclb=locality.getBinding(lb, fc);
4870 output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
4872 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
4877 if (md.getReturnType().isClass()||md.getReturnType().isArray())
4878 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
4880 output.print(md.getReturnType().getSafeSymbol()+" ");
4881 output.print("(*)(");
4883 boolean printcomma=false;
4884 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4886 LocalityBinding fclb=locality.getBinding(lb, fc);
4887 output.print("struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
4889 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
4893 for(int i=0; i<objectparams.numPrimitives(); i++) {
4894 TempDescriptor temp=objectparams.getPrimitive(i);
4898 if (temp.getType().isClass()||temp.getType().isArray())
4899 output.print("struct " + temp.getType().getSafeSymbol()+" * ");
4901 output.print(temp.getType().getSafeSymbol());
4906 LocalityBinding fclb=locality.getBinding(lb, fc);
4907 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])");
4909 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
4913 boolean needcomma=false;
4914 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4915 output.print("&__parameterlist__");
4919 if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
4920 if (fc.getThis()!=null) {
4921 TypeDescriptor ptd=null;
4922 if(md.getThis() != null) {
4923 ptd = md.getThis().getType();
4925 ptd = fc.getThis().getType();
4929 if (ptd.isClass()&&!ptd.isArray())
4930 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
4931 output.print(generateTemp(fm,fc.getThis(),lb));
4936 for(int i=0; i<fc.numArgs(); i++) {
4937 Descriptor var=md.getParameter(i);
4938 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
4939 if (objectparams.isParamPrim(paramtemp)) {
4940 TempDescriptor targ=fc.getArg(i);
4944 TypeDescriptor ptd=md.getParamType(i);
4945 if (ptd.isClass()&&!ptd.isArray())
4946 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
4947 output.print(generateTemp(fm, targ,lb));
4951 output.println(");");
4952 output.println(" }");
4955 private boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
4956 Set subclasses=typeutil.getSubClasses(thiscd);
4957 if (subclasses==null)
4959 for(Iterator classit=subclasses.iterator(); classit.hasNext();) {
4960 ClassDescriptor cd=(ClassDescriptor)classit.next();
4961 Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol());
4962 for(Iterator matchit=possiblematches.iterator(); matchit.hasNext();) {
4963 MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
4964 if (md.matches(matchmd))
4971 private void generateFlatFieldNode(FlatMethod fm, LocalityBinding lb, FlatFieldNode ffn, PrintWriter output) {
4972 if (state.SINGLETM) {
4973 //single machine transactional memory case
4974 String field=ffn.getField().getSafeSymbol();
4975 String src=generateTemp(fm, ffn.getSrc(),lb);
4976 String dst=generateTemp(fm, ffn.getDst(),lb);
4978 output.println(dst+"="+ src +"->"+field+ ";");
4979 if (ffn.getField().getType().isPtr()&&locality.getAtomic(lb).get(ffn).intValue()>0&&
4980 locality.getNodePreTempInfo(lb, ffn).get(ffn.getSrc())!=LocalityAnalysis.SCRATCH) {
4981 if ((dc==null)||(!state.READSET&&dc.getNeedTrans(lb, ffn))||
4982 (state.READSET&&dc.getNeedWriteTrans(lb, ffn))) {
4983 output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));");
4984 } else if (state.READSET&&dc.getNeedTrans(lb, ffn)) {
4985 if (state.HYBRID&&delaycomp.getConv(lb).contains(ffn)) {
4986 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4988 output.println("TRANSREADRD("+dst+", "+dst+");");
4991 } else if (state.DSM) {
4992 Integer status=locality.getNodePreTempInfo(lb,ffn).get(ffn.getSrc());
4993 if (status==LocalityAnalysis.GLOBAL) {
4994 String field=ffn.getField().getSafeSymbol();
4995 String src=generateTemp(fm, ffn.getSrc(),lb);
4996 String dst=generateTemp(fm, ffn.getDst(),lb);
4998 if (ffn.getField().getType().isPtr()) {
5000 //TODO: Uncomment this when we have runtime support
5001 //if (ffn.getSrc()==ffn.getDst()) {
5002 //output.println("{");
5003 //output.println("void * temp="+src+";");
5004 //output.println("if (temp&0x1) {");
5005 //output.println("temp=(void *) transRead(trans, (unsigned int) temp);");
5006 //output.println(src+"->"+field+"="+temp+";");
5007 //output.println("}");
5008 //output.println(dst+"=temp;");
5009 //output.println("}");
5011 output.println(dst+"="+ src +"->"+field+ ";");
5012 //output.println("if ("+dst+"&0x1) {");
5013 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
5014 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
5015 //output.println(src+"->"+field+"="+src+"->"+field+";");
5016 //output.println("}");
5019 output.println(dst+"="+ src+"->"+field+";");
5021 } else if (status==LocalityAnalysis.LOCAL) {
5022 if (ffn.getField().getType().isPtr()&&
5023 ffn.getField().isGlobal()) {
5024 String field=ffn.getField().getSafeSymbol();
5025 String src=generateTemp(fm, ffn.getSrc(),lb);
5026 String dst=generateTemp(fm, ffn.getDst(),lb);
5027 output.println(dst+"="+ src +"->"+field+ ";");
5028 if (locality.getAtomic(lb).get(ffn).intValue()>0)
5029 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
5030 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
5032 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
5033 } else if (status==LocalityAnalysis.EITHER) {
5034 //Code is reading from a null pointer
5035 output.println("if ("+generateTemp(fm, ffn.getSrc(),lb)+") {");
5036 output.println("#ifndef RAW");
5037 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
5038 output.println("#endif");
5039 //This should throw a suitable null pointer error
5040 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
5042 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
5044 // DEBUG if(!ffn.getDst().getType().isPrimitive()){
5045 // DEBUG output.println("within((void*)"+generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+");");
5048 // TODO add version for normal Java later
5049 if(ffn.getField().isStatic()) {
5051 if((fm.getMethod().isStaticBlock()) || (fm.getMethod().isInvokedByStatic())) {
5052 // is a static block or is invoked in some static block
5053 ClassDescriptor cd = fm.getMethod().getClassDesc();
5054 ClassDescriptor cn = ffn.getSrc().getType().getClassDesc();
5056 // the same class, do nothing
5057 // TODO may want to invoke static field initialization here
5059 if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) {
5060 // need to check if the class' static fields have been initialized and/or
5061 // its static blocks have been executed
5062 output.println("#ifdef MGC_STATIC_INIT_CHECK");
5063 output.println("if(global_defs_p->" + cn.getSafeSymbol()+"static_block_exe_flag == 0) {");
5064 if(cn.getNumStaticFields() != 0) {
5065 // TODO add static field initialization here
5067 if(cn.getNumStaticBlocks() != 0) {
5068 MethodDescriptor t_md = (MethodDescriptor)cn.getMethodTable().get("staticblocks");
5069 output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();");
5071 output.println(" global_defs_p->" + cn.getSafeSymbol()+"static_block_exe_flag = 1;");
5073 output.println("}");
5074 output.println("#endif // MGC_STATIC_INIT_CHECK");
5078 // redirect to the global_defs_p structure
5079 if(ffn.getSrc().getType().isStatic()) {
5080 // reference to the static field with Class name
5081 output.println(generateTemp(fm, ffn.getDst(),lb)+"=global_defs_p->"+ ffn.getSrc().getType().getClassDesc().getSafeSymbol()+ffn.getField().getSafeSymbol()+";");
5083 output.println(generateTemp(fm, ffn.getDst(),lb)+"=*"+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
5085 //output.println(generateTemp(fm, ffn.getDst(),lb)+"=global_defs_p->"+ffn.getSrc().getType().getClassDesc().getSafeSymbol()+"->"+ ffn.getField().getSafeSymbol()+";");
5087 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
5090 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
5096 private void generateFlatSetFieldNode(FlatMethod fm, LocalityBinding lb, FlatSetFieldNode fsfn, PrintWriter output) {
5097 if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
5098 throw new Error("Can't set array length");
5099 if (state.SINGLETM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
5100 //Single Machine Transaction Case
5101 boolean srcptr=fsfn.getSrc().getType().isPtr();
5102 String src=generateTemp(fm,fsfn.getSrc(),lb);
5103 String dst=generateTemp(fm,fsfn.getDst(),lb);
5104 output.println("//"+srcptr+" "+fsfn.getSrc().getType().isNull());
5105 if (srcptr&&!fsfn.getSrc().getType().isNull()) {
5106 output.println("{");
5107 if ((dc==null)||dc.getNeedSrcTrans(lb, fsfn)&&
5108 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) {
5109 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
5111 output.println("INTPTR srcoid=(INTPTR)"+src+";");
5114 if (wb.needBarrier(fsfn)&&
5115 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getDst())!=LocalityAnalysis.SCRATCH) {
5116 if (state.EVENTMONITOR) {
5117 output.println("if ("+dst+"->___objstatus___&DIRTY) EVLOGEVENTOBJ(EV_WRITE,"+dst+"->objuid)");
5119 output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;");
5121 if (srcptr&!fsfn.getSrc().getType().isNull()) {
5122 output.println("*((unsigned INTPTR *)&("+dst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
5123 output.println("}");
5125 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
5127 } else if (state.DSM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
5128 Integer statussrc=locality.getNodePreTempInfo(lb,fsfn).get(fsfn.getSrc());
5129 Integer statusdst=locality.getNodeTempInfo(lb).get(fsfn).get(fsfn.getDst());
5130 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
5132 String src=generateTemp(fm,fsfn.getSrc(),lb);
5133 String dst=generateTemp(fm,fsfn.getDst(),lb);
5135 output.println("{");
5136 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
5138 if (statusdst.equals(LocalityAnalysis.GLOBAL)) {
5141 if (wb.needBarrier(fsfn))
5142 output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;");
5144 output.println("*((unsigned INTPTR *)&("+glbdst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
5146 output.println(glbdst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
5147 } else if (statusdst.equals(LocalityAnalysis.LOCAL)) {
5148 /** Check if we need to copy */
5149 output.println("if(!"+dst+"->"+localcopystr+") {");
5150 /* Link object into list */
5151 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5152 output.println(revertptr+"=revertlist;");
5153 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
5154 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
5156 output.println("COPY_OBJ("+dst+");");
5157 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
5158 output.println("revertlist=(struct ___Object___ *)"+dst+";");
5159 output.println("}");
5161 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
5163 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
5164 } else if (statusdst.equals(LocalityAnalysis.EITHER)) {
5165 //writing to a null...bad
5166 output.println("if ("+dst+") {");
5167 output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}");
5169 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
5171 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
5174 output.println("}");
5177 if (state.FASTCHECK) {
5178 String dst=generateTemp(fm, fsfn.getDst(),lb);
5179 output.println("if(!"+dst+"->"+localcopystr+") {");
5180 /* Link object into list */
5181 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
5182 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
5184 output.println("COPY_OBJ("+dst+");");
5185 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
5186 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
5187 output.println("}");
5190 // DEBUG if(!fsfn.getField().getType().isPrimitive()){
5191 // DEBUG output.println("within((void*)"+generateTemp(fm,fsfn.getSrc(),lb)+");");
5194 // TODO add version for normal Java later
5195 if(fsfn.getField().isStatic()) {
5197 if((fm.getMethod().isStaticBlock()) || (fm.getMethod().isInvokedByStatic())) {
5198 // is a static block or is invoked in some static block
5199 ClassDescriptor cd = fm.getMethod().getClassDesc();
5200 ClassDescriptor cn = fsfn.getDst().getType().getClassDesc();
5202 // the same class, do nothing
5203 // TODO may want to invoke static field initialization here
5205 if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) {
5206 // need to check if the class' static fields have been initialized and/or
5207 // its static blocks have been executed
5208 output.println("#ifdef MGC_STATIC_INIT_CHECK");
5209 output.println("if(global_defs_p->" + cn.getSafeSymbol()+"static_block_exe_flag == 0) {");
5210 if(cn.getNumStaticFields() != 0) {
5211 // TODO add static field initialization here
5213 if(cn.getNumStaticBlocks() != 0) {
5214 MethodDescriptor t_md = (MethodDescriptor)cn.getMethodTable().get("staticblocks");
5215 output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();");
5217 output.println(" global_defs_p->" + cn.getSafeSymbol()+"static_block_exe_flag = 1;");
5219 output.println("}");
5220 output.println("#endif // MGC_STATIC_INIT_CHECK");
5224 // redirect to the global_defs_p structure
5225 if(fsfn.getDst().getType().isStatic()) {
5226 // reference to the static field with Class name
5227 output.println("global_defs_p->" + fsfn.getDst().getType().getClassDesc().getSafeSymbol() + fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
5229 output.println("*"+generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
5232 output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
5235 output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
5240 private void generateFlatElementNode(FlatMethod fm, LocalityBinding lb, FlatElementNode fen, PrintWriter output) {
5241 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
5244 if (elementtype.isArray()||elementtype.isClass())
5247 type=elementtype.getSafeSymbol()+" ";
5249 if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
5250 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fen.getIndex(),lb)+") >= "+generateTemp(fm,fen.getSrc(),lb) + "->___length___))");
5251 output.println("failedboundschk();");
5253 if (state.SINGLETM) {
5254 //Single machine transaction case
5255 String dst=generateTemp(fm, fen.getDst(),lb);
5256 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))) {
5257 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
5259 output.println("STMGETARRAY("+dst+", "+ generateTemp(fm,fen.getSrc(),lb)+", "+generateTemp(fm, fen.getIndex(),lb)+", "+type+");");
5262 if (elementtype.isPtr()&&locality.getAtomic(lb).get(fen).intValue()>0&&
5263 locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())!=LocalityAnalysis.SCRATCH) {
5264 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fen)||state.READSET&&dc.getNeedWriteTrans(lb, fen)) {
5265 output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));");
5266 } else if (state.READSET&&dc.getNeedTrans(lb, fen)) {
5267 if (state.HYBRID&&delaycomp.getConv(lb).contains(fen)) {
5268 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
5270 output.println("TRANSREADRD("+dst+", "+dst+");");
5273 } else if (state.DSM) {
5274 Integer status=locality.getNodePreTempInfo(lb,fen).get(fen.getSrc());
5275 if (status==LocalityAnalysis.GLOBAL) {
5276 String dst=generateTemp(fm, fen.getDst(),lb);
5277 if (elementtype.isPtr()) {
5278 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
5279 //DEBUG: output.println("TRANSREAD("+dst+", "+dst+",\""+fm+":"+fen+"\");");
5280 output.println("TRANSREAD("+dst+", "+dst+");");
5282 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
5284 } else if (status==LocalityAnalysis.LOCAL) {
5285 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
5286 } else if (status==LocalityAnalysis.EITHER) {
5287 //Code is reading from a null pointer
5288 output.println("if ("+generateTemp(fm, fen.getSrc(),lb)+") {");
5289 output.println("#ifndef RAW");
5290 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
5291 output.println("#endif");
5292 //This should throw a suitable null pointer error
5293 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
5295 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
5297 // DEBUG output.println("within((void*)"+generateTemp(fm,fen.getSrc(),lb)+");");
5298 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
5302 private void generateFlatSetElementNode(FlatMethod fm, LocalityBinding lb, FlatSetElementNode fsen, PrintWriter output) {
5303 //TODO: need dynamic check to make sure this assignment is actually legal
5304 //Because Object[] could actually be something more specific...ie. Integer[]
5306 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
5309 if (elementtype.isArray()||elementtype.isClass())
5312 type=elementtype.getSafeSymbol()+" ";
5314 if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
5315 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fsen.getIndex(),lb)+") >= "+generateTemp(fm,fsen.getDst(),lb) + "->___length___))");
5316 output.println("failedboundschk();");
5319 if (state.SINGLETM && locality.getAtomic(lb).get(fsen).intValue()>0) {
5320 //Transaction set element case
5321 if (wb.needBarrier(fsen)&&
5322 locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH) {
5323 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___objstatus___))|=DIRTY;");
5325 if (fsen.getSrc().getType().isPtr()&&!fsen.getSrc().getType().isNull()) {
5326 output.println("{");
5327 String src=generateTemp(fm, fsen.getSrc(), lb);
5328 if ((dc==null)||dc.getNeedSrcTrans(lb, fsen)&&
5329 locality.getNodePreTempInfo(lb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) {
5330 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
5332 output.println("INTPTR srcoid=(INTPTR)"+src+";");
5334 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
5335 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", srcoid, INTPTR);");
5337 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
5339 output.println("}");
5341 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
5342 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", "+ generateTemp(fm, fsen.getSrc(), lb) +", "+type+");");
5344 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
5347 } else if (state.DSM && locality.getAtomic(lb).get(fsen).intValue()>0) {
5348 Integer statussrc=locality.getNodePreTempInfo(lb,fsen).get(fsen.getSrc());
5349 Integer statusdst=locality.getNodePreTempInfo(lb,fsen).get(fsen.getDst());
5350 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
5351 boolean dstglobal=statusdst==LocalityAnalysis.GLOBAL;
5352 boolean dstlocal=(statusdst==LocalityAnalysis.LOCAL)||(statusdst==LocalityAnalysis.EITHER);
5355 if (wb.needBarrier(fsen))
5356 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___localcopy___))|=DIRTY;");
5357 } else if (dstlocal) {
5358 /** Check if we need to copy */
5359 String dst=generateTemp(fm, fsen.getDst(),lb);
5360 output.println("if(!"+dst+"->"+localcopystr+") {");
5361 /* Link object into list */
5362 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5363 output.println(revertptr+"=revertlist;");
5364 if ((GENERATEPRECISEGC) || this.state.MULTICOREGC)
5365 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
5367 output.println("COPY_OBJ("+dst+");");
5368 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
5369 output.println("revertlist=(struct ___Object___ *)"+dst+";");
5370 output.println("}");
5372 System.out.println("Node: "+fsen);
5373 System.out.println(lb);
5374 System.out.println("statusdst="+statusdst);
5375 System.out.println(fm.printMethod());
5376 throw new Error("Unknown array type");
5379 output.println("{");
5380 String src=generateTemp(fm, fsen.getSrc(), lb);
5381 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
5382 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
5383 output.println("}");
5385 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
5388 if (state.FASTCHECK) {
5389 String dst=generateTemp(fm, fsen.getDst(),lb);
5390 output.println("if(!"+dst+"->"+localcopystr+") {");
5391 /* Link object into list */
5392 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
5393 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
5395 output.println("COPY_OBJ("+dst+");");
5396 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
5397 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
5398 output.println("}");
5400 // DEBUG output.println("within((void*)"+generateTemp(fm,fsen.getDst(),lb)+");");
5401 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
5405 protected void generateFlatNew(FlatMethod fm, LocalityBinding lb, FlatNew fn, PrintWriter output) {
5406 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
5407 //Stash pointer in case of GC
5408 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5409 output.println(revertptr+"=revertlist;");
5411 if (state.SINGLETM) {
5412 if (fn.getType().isArray()) {
5413 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
5414 if (locality.getAtomic(lb).get(fn).intValue()>0) {
5415 //inside transaction
5416 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
5418 //outside transaction
5419 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
5422 if (locality.getAtomic(lb).get(fn).intValue()>0) {
5423 //inside transaction
5424 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
5426 //outside transaction
5427 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
5430 } else if (fn.getType().isArray()) {
5431 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
5432 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
5433 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
5434 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5435 if(this.state.MLP || state.OOOJAVA){
5436 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray_mlp("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+", oid, "+oooa.getDisjointAnalysis().getAllocationSiteFromFlatNew(fn).getUniqueAllocSiteID()+");");
5437 output.println(" oid += numWorkSchedWorkers;");
5439 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
5442 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
5445 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
5446 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");");
5447 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5448 if (this.state.MLP || state.OOOJAVA){
5449 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new_mlp("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+", oid, "+oooa.getDisjointAnalysis().getAllocationSiteFromFlatNew(fn).getUniqueAllocSiteID()+");");
5450 output.println(" oid += numWorkSchedWorkers;");
5452 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
5455 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
5458 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
5459 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5460 String dst=generateTemp(fm,fn.getDst(),lb);
5461 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
5462 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
5463 output.println("revertlist=(struct ___Object___ *)"+dst+";");
5465 if (state.FASTCHECK) {
5466 String dst=generateTemp(fm,fn.getDst(),lb);
5467 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
5468 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
5469 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
5473 private void generateFlatTagDeclaration(FlatMethod fm, LocalityBinding lb, FlatTagDeclaration fn, PrintWriter output) {
5474 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5475 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
5477 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+state.getTagId(fn.getType())+");");
5481 private void generateFlatOpNode(FlatMethod fm, LocalityBinding lb, FlatOpNode fon, PrintWriter output) {
5482 if (fon.getRight()!=null) {
5483 if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
5484 if (fon.getLeft().getType().isLong())
5485 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
5487 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned int)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
5489 } else if (dc!=null) {
5490 output.print(generateTemp(fm, fon.getDest(),lb)+" = (");
5491 if (fon.getLeft().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
5492 output.print("(void *)");
5493 if (dc.getNeedLeftSrcTrans(lb, fon))
5494 output.print("("+generateTemp(fm, fon.getLeft(),lb)+"!=NULL?"+generateTemp(fm, fon.getLeft(),lb)+"->"+oidstr+":NULL)");
5496 output.print(generateTemp(fm, fon.getLeft(),lb));
5497 output.print(")"+fon.getOp().toString()+"(");
5498 if (fon.getRight().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
5499 output.print("(void *)");
5500 if (dc.getNeedRightSrcTrans(lb, fon))
5501 output.println("("+generateTemp(fm, fon.getRight(),lb)+"!=NULL?"+generateTemp(fm, fon.getRight(),lb)+"->"+oidstr+":NULL));");
5503 output.println(generateTemp(fm,fon.getRight(),lb)+");");
5505 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+fon.getOp().toString()+generateTemp(fm,fon.getRight(),lb)+";");
5506 } else if (fon.getOp().getOp()==Operation.ASSIGN)
5507 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
5508 else if (fon.getOp().getOp()==Operation.UNARYPLUS)
5509 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
5510 else if (fon.getOp().getOp()==Operation.UNARYMINUS)
5511 output.println(generateTemp(fm, fon.getDest(),lb)+" = -"+generateTemp(fm, fon.getLeft(),lb)+";");
5512 else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
5513 output.println(generateTemp(fm, fon.getDest(),lb)+" = !"+generateTemp(fm, fon.getLeft(),lb)+";");
5514 else if (fon.getOp().getOp()==Operation.COMP)
5515 output.println(generateTemp(fm, fon.getDest(),lb)+" = ~"+generateTemp(fm, fon.getLeft(),lb)+";");
5516 else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
5517 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+"->fses==NULL;");
5519 output.println(generateTemp(fm, fon.getDest(),lb)+fon.getOp().toString()+generateTemp(fm, fon.getLeft(),lb)+";");
5522 private void generateFlatCastNode(FlatMethod fm, LocalityBinding lb, FlatCastNode fcn, PrintWriter output) {
5523 /* TODO: Do type check here */
5524 if (fcn.getType().isArray()) {
5525 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
5526 } else if (fcn.getType().isClass())
5527 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
5529 output.println(generateTemp(fm,fcn.getDst(),lb)+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc(),lb)+";");
5532 private void generateFlatLiteralNode(FlatMethod fm, LocalityBinding lb, FlatLiteralNode fln, PrintWriter output) {
5533 if (fln.getValue()==null)
5534 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
5535 else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
5536 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5537 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
5538 //Stash pointer in case of GC
5539 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5540 output.println(revertptr+"=revertlist;");
5542 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
5543 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
5544 //Stash pointer in case of GC
5545 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5546 output.println("revertlist="+revertptr+";");
5549 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
5551 } else if (fln.getType().isBoolean()) {
5552 if (((Boolean)fln.getValue()).booleanValue())
5553 output.println(generateTemp(fm, fln.getDst(),lb)+"=1;");
5555 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
5556 } else if (fln.getType().isChar()) {
5557 String st=FlatLiteralNode.escapeString(fln.getValue().toString());
5558 output.println(generateTemp(fm, fln.getDst(),lb)+"='"+st+"';");
5559 } else if (fln.getType().isLong()) {
5560 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+"LL;");
5562 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+";");
5565 protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) {
5567 // TODO add version for normal Java later
5568 if((fm.getMethod() != null) && (fm.getMethod().isStaticBlock())) {
5569 // a static block, check if it has been executed
5570 output.println(" global_defs_p->" + fm.getMethod().getClassDesc().getSafeSymbol()+"static_block_exe_flag = 1;");
5574 if (frn.getReturnTemp()!=null) {
5575 if (frn.getReturnTemp().getType().isPtr())
5576 output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";");
5578 output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";");
5580 output.println("return;");
5584 protected void generateStoreFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
5587 //only record if this group has more than one exit
5588 if (branchanalysis.numJumps(fcb)>1) {
5589 left=branchanalysis.jumpValue(fcb, 0);
5590 right=branchanalysis.jumpValue(fcb, 1);
5592 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") {");
5594 output.println("STOREBRANCH("+right+");");
5595 output.println("goto "+label+";");
5596 output.println("}");
5598 output.println("STOREBRANCH("+left+");");
5601 protected void generateFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
5602 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") goto "+label+";");
5605 /** This method generates header information for the method or
5606 * task referenced by the Descriptor des. */
5607 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) {
5608 generateHeader(fm, lb, des, output, false);
5611 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output, boolean addSESErecord) {
5613 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : des);
5614 MethodDescriptor md=null;
5615 TaskDescriptor task=null;
5616 if (des instanceof MethodDescriptor)
5617 md=(MethodDescriptor) des;
5619 task=(TaskDescriptor) des;
5621 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
5623 if (md!=null&&md.getReturnType()!=null) {
5624 if (md.getReturnType().isClass()||md.getReturnType().isArray())
5625 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
5627 output.print(md.getReturnType().getSafeSymbol()+" ");
5629 //catch the constructor case
5630 output.print("void ");
5632 if (state.DSM||state.SINGLETM) {
5633 output.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
5635 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
5637 output.print(task.getSafeSymbol()+"(");
5639 boolean printcomma=false;
5640 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5642 if (state.DSM||state.SINGLETM) {
5643 output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
5645 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
5647 output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
5653 for(int i=0; i<objectparams.numPrimitives(); i++) {
5654 TempDescriptor temp=objectparams.getPrimitive(i);
5658 if (temp.getType().isClass()||temp.getType().isArray())
5659 output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
5661 output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
5663 output.println(") {");
5664 } else if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
5665 /* Imprecise Task */
5666 output.println("void * parameterarray[]) {");
5667 /* Unpack variables */
5668 for(int i=0; i<objectparams.numPrimitives(); i++) {
5669 TempDescriptor temp=objectparams.getPrimitive(i);
5670 output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
5672 for(int i=0; i<fm.numTags(); i++) {
5673 TempDescriptor temp=fm.getTag(i);
5674 int offset=i+objectparams.numPrimitives();
5675 output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
5678 if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
5679 maxtaskparams=objectparams.numPrimitives()+fm.numTags();
5680 } else output.println(") {");
5683 public void generateFlatFlagActionNode(FlatMethod fm, LocalityBinding lb, FlatFlagActionNode ffan, PrintWriter output) {
5684 output.println("/* FlatFlagActionNode */");
5687 /* Process tag changes */
5688 Relation tagsettable=new Relation();
5689 Relation tagcleartable=new Relation();
5691 Iterator tagsit=ffan.getTempTagPairs();
5692 while (tagsit.hasNext()) {
5693 TempTagPair ttp=(TempTagPair) tagsit.next();
5694 TempDescriptor objtmp=ttp.getTemp();
5695 TagDescriptor tag=ttp.getTag();
5696 TempDescriptor tagtmp=ttp.getTagTemp();
5697 boolean tagstatus=ffan.getTagChange(ttp);
5699 tagsettable.put(objtmp, tagtmp);
5701 tagcleartable.put(objtmp, tagtmp);
5706 Hashtable flagandtable=new Hashtable();
5707 Hashtable flagortable=new Hashtable();
5709 /* Process flag changes */
5710 Iterator flagsit=ffan.getTempFlagPairs();
5711 while(flagsit.hasNext()) {
5712 TempFlagPair tfp=(TempFlagPair)flagsit.next();
5713 TempDescriptor temp=tfp.getTemp();
5714 Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
5715 FlagDescriptor flag=tfp.getFlag();
5717 //Newly allocate objects that don't set any flags case
5718 if (flagortable.containsKey(temp)) {
5722 flagortable.put(temp,new Integer(mask));
5724 int flagid=1<<((Integer)flagtable.get(flag)).intValue();
5725 boolean flagstatus=ffan.getFlagChange(tfp);
5728 if (flagortable.containsKey(temp)) {
5729 mask=((Integer)flagortable.get(temp)).intValue();
5732 flagortable.put(temp,new Integer(mask));
5734 int mask=0xFFFFFFFF;
5735 if (flagandtable.containsKey(temp)) {
5736 mask=((Integer)flagandtable.get(temp)).intValue();
5738 mask&=(0xFFFFFFFF^flagid);
5739 flagandtable.put(temp,new Integer(mask));
5745 HashSet flagtagset=new HashSet();
5746 flagtagset.addAll(flagortable.keySet());
5747 flagtagset.addAll(flagandtable.keySet());
5748 flagtagset.addAll(tagsettable.keySet());
5749 flagtagset.addAll(tagcleartable.keySet());
5751 Iterator ftit=flagtagset.iterator();
5752 while(ftit.hasNext()) {
5753 TempDescriptor temp=(TempDescriptor)ftit.next();
5756 Set tagtmps=tagcleartable.get(temp);
5757 if (tagtmps!=null) {
5758 Iterator tagit=tagtmps.iterator();
5759 while(tagit.hasNext()) {
5760 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
5761 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
5762 output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5764 output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5768 tagtmps=tagsettable.get(temp);
5769 if (tagtmps!=null) {
5770 Iterator tagit=tagtmps.iterator();
5771 while(tagit.hasNext()) {
5772 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
5773 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
5774 output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5776 output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp, lb)+", "+generateTemp(fm,tagtmp, lb)+");");
5781 int andmask=0xFFFFFFF;
5783 if (flagortable.containsKey(temp))
5784 ormask=((Integer)flagortable.get(temp)).intValue();
5785 if (flagandtable.containsKey(temp))
5786 andmask=((Integer)flagandtable.get(temp)).intValue();
5787 generateFlagOrAnd(ffan, fm, lb, temp, output, ormask, andmask);
5788 generateObjectDistribute(ffan, fm, lb, temp, output);
5792 protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp,
5793 PrintWriter output, int ormask, int andmask) {
5794 if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
5795 output.println("flagorandinit("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
5797 output.println("flagorand("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
5801 protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, PrintWriter output) {
5802 output.println("enqueueObject("+generateTemp(fm, temp, lb)+");");
5805 void generateOptionalHeader(PrintWriter headers) {
5808 headers.println("#include \"task.h\"\n\n");
5809 headers.println("#ifndef _OPTIONAL_STRUCT_");
5810 headers.println("#define _OPTIONAL_STRUCT_");
5812 //STRUCT PREDICATEMEMBER
5813 headers.println("struct predicatemember{");
5814 headers.println("int type;");
5815 headers.println("int numdnfterms;");
5816 headers.println("int * flags;");
5817 headers.println("int numtags;");
5818 headers.println("int * tags;\n};\n\n");
5820 //STRUCT OPTIONALTASKDESCRIPTOR
5821 headers.println("struct optionaltaskdescriptor{");
5822 headers.println("struct taskdescriptor * task;");
5823 headers.println("int index;");
5824 headers.println("int numenterflags;");
5825 headers.println("int * enterflags;");
5826 headers.println("int numpredicatemembers;");
5827 headers.println("struct predicatemember ** predicatememberarray;");
5828 headers.println("};\n\n");
5830 //STRUCT TASKFAILURE
5831 headers.println("struct taskfailure {");
5832 headers.println("struct taskdescriptor * task;");
5833 headers.println("int index;");
5834 headers.println("int numoptionaltaskdescriptors;");
5835 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
5837 //STRUCT FSANALYSISWRAPPER
5838 headers.println("struct fsanalysiswrapper{");
5839 headers.println("int flags;");
5840 headers.println("int numtags;");
5841 headers.println("int * tags;");
5842 headers.println("int numtaskfailures;");
5843 headers.println("struct taskfailure ** taskfailurearray;");
5844 headers.println("int numoptionaltaskdescriptors;");
5845 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
5847 //STRUCT CLASSANALYSISWRAPPER
5848 headers.println("struct classanalysiswrapper{");
5849 headers.println("int type;");
5850 headers.println("int numotd;");
5851 headers.println("struct optionaltaskdescriptor ** otdarray;");
5852 headers.println("int numfsanalysiswrappers;");
5853 headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
5855 headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
5857 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
5858 while(taskit.hasNext()) {
5859 TaskDescriptor td=(TaskDescriptor)taskit.next();
5860 headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
5865 //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
5866 int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
5867 int predicateindex = 0;
5868 //iterate through the classes concerned by the predicate
5869 Set c_vard = predicate.vardescriptors;
5870 Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
5873 for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext();) {
5874 VarDescriptor vard = (VarDescriptor)vard_it.next();
5875 TypeDescriptor typed = vard.getType();
5877 //generate for flags
5878 HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
5879 output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5881 if (fen_hashset!=null) {
5882 for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext();) {
5883 FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
5885 DNFFlag dflag=fen.getDNF();
5886 numberterms+=dflag.size();
5888 Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
5890 for(int j=0; j<dflag.size(); j++) {
5892 output.println(",");
5893 Vector term=dflag.get(j);
5896 for(int k=0; k<term.size(); k++) {
5897 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
5898 FlagDescriptor fd=dfa.getFlag();
5899 boolean negated=dfa.getNegated();
5900 int flagid=1<<((Integer)flags.get(fd)).intValue();
5905 output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
5910 output.println("};\n");
5913 TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
5914 output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5917 for(int j=0; j<tagel.numTags(); j++) {
5919 output.println(",");
5920 TempDescriptor tmp=tagel.getTemp(j);
5921 if (!slotnumber.containsKey(tmp)) {
5922 Integer slotint=new Integer(current_slot++);
5923 slotnumber.put(tmp,slotint);
5925 int slot=slotnumber.get(tmp).intValue();
5926 output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
5928 numtags = tagel.numTags();
5930 output.println("};");
5932 //store the result into a predicatemember struct
5933 output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
5934 output.println("/*type*/"+typed.getClassDesc().getId()+",");
5935 output.println("/* number of dnf terms */"+numberterms+",");
5936 output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5937 output.println("/* number of tag */"+numtags+",");
5938 output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5939 output.println("};\n");
5944 //generate an array that stores the entire predicate
5945 output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5946 for( int j = 0; j<predicateindex; j++) {
5947 if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5948 else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5950 output.println("};\n");
5951 return predicateindex;
5955 void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
5956 generateOptionalHeader(headers);
5958 output.println("#include \"optionalstruct.h\"\n\n");
5959 output.println("#include \"stdlib.h\"\n");
5961 HashSet processedcd = new HashSet();
5963 Enumeration e = safeexecution.keys();
5964 while (e.hasMoreElements()) {
5967 ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
5968 Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp); //will be used several times
5970 //Generate the struct of optionals
5971 Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
5972 numotd = c_otd.size();
5973 if(maxotd<numotd) maxotd = numotd;
5974 if( !c_otd.isEmpty() ) {
5975 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
5976 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
5978 //generate the int arrays for the predicate
5979 Predicate predicate = otd.predicate;
5980 int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
5981 TreeSet<Integer> fsset=new TreeSet<Integer>();
5982 //iterate through possible FSes corresponding to
5983 //the state when entering
5985 for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext();) {
5986 FlagState fs = (FlagState)fses.next();
5988 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
5989 FlagDescriptor flagd = (FlagDescriptor)flags.next();
5990 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
5993 fsset.add(new Integer(flagid));
5994 //tag information not needed because tag
5995 //changes are not tolerated.
5998 output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5999 boolean needcomma=false;
6000 for(Iterator<Integer> it=fsset.iterator(); it.hasNext();) {
6003 output.println(it.next());
6006 output.println("};\n");
6009 //generate optionaltaskdescriptor that actually
6010 //includes exit fses, predicate and the task
6012 output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
6013 output.println("&task_"+otd.td.getSafeSymbol()+",");
6014 output.println("/*index*/"+otd.getIndex()+",");
6015 output.println("/*number of enter flags*/"+fsset.size()+",");
6016 output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
6017 output.println("/*number of members */"+predicateindex+",");
6018 output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
6019 output.println("};\n");
6023 // if there are no optionals, there is no need to build the rest of the struct
6025 output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
6026 c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
6027 if( !c_otd.isEmpty() ) {
6028 boolean needcomma=false;
6029 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
6030 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
6032 output.println(",");
6034 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
6037 output.println("};\n");
6039 //get all the possible flagstates reachable by an object
6040 Hashtable hashtbtemp = safeexecution.get(cdtemp);
6042 TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
6043 fsts.addAll(hashtbtemp.keySet());
6044 for(Iterator fsit=fsts.iterator(); fsit.hasNext();) {
6045 FlagState fs = (FlagState)fsit.next();
6048 //get the set of OptionalTaskDescriptors corresponding
6049 HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
6050 //iterate through the OptionalTaskDescriptors and
6051 //store the pointers to the optionals struct (see on
6052 //top) into an array
6054 output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
6055 for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext();) {
6056 OptionalTaskDescriptor mm = mos.next();
6058 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
6060 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
6063 output.println("};\n");
6065 //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
6068 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
6069 FlagDescriptor flagd = (FlagDescriptor)flags.next();
6070 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
6074 //process tag information
6077 boolean first = true;
6078 Enumeration tag_enum = fs.getTags();
6079 output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
6080 while(tag_enum.hasMoreElements()) {
6082 TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
6086 output.println(", ");
6087 output.println("/*tagid*/"+state.getTagId(tagd));
6089 output.println("};");
6091 Set<TaskIndex> tiset=sa.getTaskIndex(fs);
6092 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
6093 TaskIndex ti=itti.next();
6097 Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
6099 output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
6100 boolean needcomma=false;
6101 for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext();) {
6102 OptionalTaskDescriptor otd=otdit.next();
6106 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
6108 output.println("};");
6110 output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
6111 output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
6112 output.print(ti.getIndex()+", ");
6113 output.print(otdset.size()+", ");
6114 output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
6115 output.println("};");
6118 tiset=sa.getTaskIndex(fs);
6119 boolean needcomma=false;
6121 output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
6122 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
6123 TaskIndex ti=itti.next();
6124 if (ti.isRuntime()) {
6131 output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
6133 output.println("};\n");
6135 //Store the result in fsanalysiswrapper
6137 output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
6138 output.println("/*flag*/"+flagid+",");
6139 output.println("/* number of tags*/"+tagcounter+",");
6140 output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
6141 output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
6142 output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
6143 output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
6144 output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
6145 output.println("};\n");
6149 //Build the array of fsanalysiswrappers
6150 output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
6151 boolean needcomma=false;
6152 for(int i = 0; i<fscounter; i++) {
6153 if (needcomma) output.print(",");
6154 output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
6157 output.println("};");
6159 //Build the classanalysiswrapper referring to the previous array
6160 output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
6161 output.println("/*type*/"+cdtemp.getId()+",");
6162 output.println("/*numotd*/"+numotd+",");
6163 output.println("otdarray"+cdtemp.getSafeSymbol()+",");
6164 output.println("/* number of fsanalysiswrappers */"+fscounter+",");
6165 output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
6166 processedcd.add(cdtemp);
6169 //build an array containing every classes for which code has been build
6170 output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
6171 for(int i=0; i<state.numClasses(); i++) {
6172 ClassDescriptor cn=cdarray[i];
6175 if ((cn != null) && (processedcd.contains(cn)))
6176 output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
6178 output.print("NULL");
6180 output.println("};");
6182 output.println("#define MAXOTD "+maxotd);
6183 headers.println("#endif");
6186 public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
6187 Relation r=new Relation();
6188 for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext();) {
6189 OptionalTaskDescriptor otd=otdit.next();
6190 TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
6194 LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
6195 for(Iterator it=r.keySet().iterator(); it.hasNext();) {
6196 Set s=r.get(it.next());
6197 for(Iterator it2=s.iterator(); it2.hasNext();) {
6198 OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
6206 protected void outputTransCode(PrintWriter output) {
6209 private int calculateSizeOfSESEParamList(FlatSESEEnterNode fsen){
6211 Set<TempDescriptor> tdSet=new HashSet<TempDescriptor>();
6213 for (Iterator iterator = fsen.getInVarSet().iterator(); iterator.hasNext();) {
6214 TempDescriptor tempDescriptor = (TempDescriptor) iterator.next();
6215 if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()){
6216 tdSet.add(tempDescriptor);
6220 for (Iterator iterator = fsen.getOutVarSet().iterator(); iterator.hasNext();) {
6221 TempDescriptor tempDescriptor = (TempDescriptor) iterator.next();
6222 if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()){
6223 tdSet.add(tempDescriptor);
6227 return tdSet.size();
6230 private String calculateSizeOfSESEParamSize(FlatSESEEnterNode fsen){
6231 HashMap <String,Integer> map=new HashMap();
6232 HashSet <TempDescriptor> processed=new HashSet<TempDescriptor>();
6235 // space for all in and out set primitives
6236 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
6237 inSetAndOutSet.addAll( fsen.getInVarSet() );
6238 inSetAndOutSet.addAll( fsen.getOutVarSet() );
6240 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
6242 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
6243 while( itr.hasNext() ) {
6244 TempDescriptor temp = itr.next();
6245 TypeDescriptor type = temp.getType();
6246 if( !type.isPtr() ) {
6247 inSetAndOutSetPrims.add( temp );
6251 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
6252 while( itrPrims.hasNext() ) {
6253 TempDescriptor temp = itrPrims.next();
6254 TypeDescriptor type = temp.getType();
6255 if(type.isPrimitive()){
6256 Integer count=map.get(type.getSymbol());
6258 count=new Integer(1);
6259 map.put(type.getSymbol(), count);
6261 map.put(type.getSymbol(), new Integer(count.intValue()+1));
6266 Set<String> keySet=map.keySet();
6267 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
6268 String key = (String) iterator.next();
6269 rtr+="+sizeof("+key+")*"+map.get(key);