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);
171 outglobaldefs=new PrintWriter(new FileOutputStream(PREFIX+"globaldefs.h"), true);
172 outmethod=new PrintWriter(new FileOutputStream(PREFIX+"methods.c"), true);
173 outvirtual=new PrintWriter(new FileOutputStream(PREFIX+"virtualtable.h"), true);
175 outtask=new PrintWriter(new FileOutputStream(PREFIX+"task.h"), true);
176 outtaskdefs=new PrintWriter(new FileOutputStream(PREFIX+"taskdefs.c"), true);
177 if (state.OPTIONAL) {
178 outoptionalarrays=new PrintWriter(new FileOutputStream(PREFIX+"optionalarrays.c"), true);
179 optionalheaders=new PrintWriter(new FileOutputStream(PREFIX+"optionalstruct.h"), true);
182 if (state.structfile!=null) {
183 outrepairstructs=new PrintWriter(new FileOutputStream(PREFIX+state.structfile+".struct"), true);
185 } catch (Exception e) {
190 /* Build the virtual dispatch tables */
191 buildVirtualTables(outvirtual);
193 /* Output includes */
194 outmethodheader.println("#ifndef METHODHEADERS_H");
195 outmethodheader.println("#define METHODHEADERS_H");
196 outmethodheader.println("#include \"structdefs.h\"");
198 outmethodheader.println("#include \"dstm.h\"");
200 outmethodheader.println("#include \"sandbox.h\"");
202 if (state.EVENTMONITOR) {
203 outmethodheader.println("#include \"monitor.h\"");
205 if (state.SINGLETM) {
206 outmethodheader.println("#include \"tm.h\"");
207 outmethodheader.println("#include \"delaycomp.h\"");
208 outmethodheader.println("#include \"inlinestm.h\"");
210 if (state.ABORTREADERS) {
211 outmethodheader.println("#include \"abortreaders.h\"");
212 outmethodheader.println("#include <setjmp.h>");
214 if (state.MLP || state.OOOJAVA) {
215 outmethodheader.println("#include <stdlib.h>");
216 outmethodheader.println("#include <stdio.h>");
217 outmethodheader.println("#include <string.h>");
218 outmethodheader.println("#include \"mlp_runtime.h\"");
219 outmethodheader.println("#include \"psemaphore.h\"");
220 outmethodheader.println("#include \"memPool.h\"");
223 outmethodheader.println("#include \"rcr_runtime.h\"");
225 // spit out a global to inform all worker threads with
226 // the maximum size is for any task record
227 outmethodheader.println("extern int "+maxTaskRecSizeStr+";");
230 /* Output Structures */
231 outputStructs(outstructs);
233 // Output the C class declarations
234 // These could mutually reference each other
236 outglobaldefs.println("#ifndef __GLOBALDEF_H_");
237 outglobaldefs.println("#define __GLOBALDEF_H_");
238 outglobaldefs.println("");
239 outglobaldefs.println("struct global_defs_t {");
241 outclassdefs.println("#ifndef __CLASSDEF_H_");
242 outclassdefs.println("#define __CLASSDEF_H_");
243 outputClassDeclarations(outclassdefs, outglobaldefs);
245 // Output function prototypes and structures for parameters
246 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
247 while(it.hasNext()) {
248 ClassDescriptor cn=(ClassDescriptor)it.next();
249 generateCallStructs(cn, outclassdefs, outstructs, outmethodheader, outglobaldefs);
251 outclassdefs.println("#endif");
252 outclassdefs.close();
253 outglobaldefs.println("};");
254 outglobaldefs.println("");
255 outglobaldefs.println("extern struct global_defs_t * global_defs_p;");
256 outglobaldefs.println("#endif");
257 outglobaldefs.flush();
258 outglobaldefs.close();
261 /* Map flags to integers */
262 /* The runtime keeps track of flags using these integers */
263 it=state.getClassSymbolTable().getDescriptorsIterator();
264 while(it.hasNext()) {
265 ClassDescriptor cn=(ClassDescriptor)it.next();
269 generateTaskStructs(outstructs, outmethodheader);
271 /* Outputs generic task structures if this is a task
273 outputTaskTypes(outtask);
276 if( state.MLP || state.OOOJAVA) {
277 // have to initialize some SESE compiler data before
278 // analyzing normal methods, which must happen before
279 // generating SESE internal code
281 Iterator<FlatSESEEnterNode> seseit;
283 seseit=mlpa.getAllSESEs().iterator();
285 seseit=oooa.getAllSESEs().iterator();
288 //TODO signal the object that will report errors
291 rcr = new RuntimeConflictResolver(PREFIX, oooa);
292 rcr.setGlobalEffects(oooa.getDisjointAnalysis().getEffectsAnalysis().getAllEffects());
293 } catch (FileNotFoundException e) {
294 System.out.println("Runtime Conflict Resolver could not create output file.");
299 while(seseit.hasNext()){
300 FlatSESEEnterNode fsen = seseit.next();
301 initializeSESE( fsen );
305 /* Build the actual methods */
306 outputMethods(outmethod);
308 // Output function prototypes and structures for SESE's and code
309 if( state.MLP || state.OOOJAVA ) {
311 // spit out a global to inform all worker threads with
312 // the maximum size is for any task record
313 outmethod.println("int "+maxTaskRecSizeStr+" = 0;");
315 // used to differentiate, during code generation, whether we are
316 // passing over SESE body code, or non-SESE code
319 // first generate code for each sese's internals
320 Iterator<FlatSESEEnterNode> seseit;
322 seseit=mlpa.getAllSESEs().iterator();
324 seseit=oooa.getAllSESEs().iterator();
327 while(seseit.hasNext()) {
328 FlatSESEEnterNode fsen = seseit.next();
329 generateMethodSESE(fsen, null, outstructs, outmethodheader, outmethod);
332 // then write the invokeSESE switch to decouple scheduler
333 // from having to do unique details of sese invocation
334 generateSESEinvocationMethod(outmethodheader, outmethod);
338 /* Output code for tasks */
339 outputTaskCode(outtaskdefs, outmethod);
341 /* Record maximum number of task parameters */
342 outstructs.println("#define MAXTASKPARAMS "+maxtaskparams);
343 } else if (state.main!=null) {
344 /* Generate main method */
345 outputMainMethod(outmethod);
348 /* Generate information for task with optional parameters */
349 if (state.TASK&&state.OPTIONAL) {
350 generateOptionalArrays(outoptionalarrays, optionalheaders, state.getAnalysisResult(), state.getOptionalTaskDescriptors());
351 outoptionalarrays.close();
354 /* Output structure definitions for repair tool */
355 if (state.structfile!=null) {
356 buildRepairStructs(outrepairstructs);
357 outrepairstructs.close();
361 outmethodheader.println("#endif");
362 outmethodheader.close();
364 outstructs.println("#endif");
368 System.out.println("Runtime Conflict Resolver Done.");
373 /* This code just generates the main C method for java programs.
374 * The main C method packs up the arguments into a string array
375 * and passes it to the java main method. */
377 protected void outputMainMethod(PrintWriter outmethod) {
378 outmethod.println("int main(int argc, const char *argv[]) {");
379 outmethod.println(" int i;");
381 if (state.MLP || state.OOOJAVA) {
383 // do a calculation to determine which task record
384 // is the largest, store that as a global value for
385 // allocating records
386 Iterator<FlatSESEEnterNode> seseit;
388 seseit=mlpa.getAllSESEs().iterator();
390 seseit=oooa.getAllSESEs().iterator();
392 while(seseit.hasNext()){
393 FlatSESEEnterNode fsen = seseit.next();
394 outmethod.println("if( sizeof( "+fsen.getSESErecordName()+
395 " ) > "+maxTaskRecSizeStr+
396 " ) { "+maxTaskRecSizeStr+
397 " = sizeof( "+fsen.getSESErecordName()+
401 outmethod.println(" runningSESE = NULL;");
403 outmethod.println(" workScheduleInit( "+state.MLP_NUMCORES+", invokeSESEmethod );");
405 //initializes data structures needed for the RCR traverser
406 if(state.RCR && rcr != null) {
407 outmethod.println(" initializeStructsRCR();");
412 if (state.DSMRECOVERYSTATS) {
413 outmethod.println("#ifdef RECOVERYSTATS \n");
414 outmethod.println("handle();\n");
415 outmethod.println("#endif\n");
417 outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n");
418 outmethod.println("handle();\n");
419 outmethod.println("#endif\n");
423 if (state.THREAD||state.DSM||state.SINGLETM) {
424 outmethod.println("initializethreads();");
427 outmethod.println("if (dstmStartup(argv[1])) {");
428 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
429 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-2);");
431 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-2);");
434 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
435 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1);");
437 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1);");
441 outmethod.println(" for(i=2;i<argc;i++) {");
443 outmethod.println(" for(i=1;i<argc;i++) {");
444 outmethod.println(" int length=strlen(argv[i]);");
445 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
446 outmethod.println(" struct ___String___ *newstring=NewString(NULL, argv[i], length);");
448 outmethod.println(" struct ___String___ *newstring=NewString(argv[i], length);");
451 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-2]=newstring;");
453 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-1]=newstring;");
454 outmethod.println(" }");
456 MethodDescriptor md=typeutil.getMain();
457 ClassDescriptor cd=typeutil.getMainClass();
459 outmethod.println(" {");
460 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
461 if (state.DSM||state.SINGLETM) {
462 outmethod.print(" struct "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
464 outmethod.print(" struct "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
465 outmethod.println("1, NULL,"+"stringarray};");
466 if (state.DSM||state.SINGLETM)
467 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
469 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
471 if (state.DSM||state.SINGLETM)
472 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
474 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
476 outmethod.println(" }");
479 outmethod.println("}");
482 if (state.THREAD||state.DSM||state.SINGLETM) {
483 outmethod.println("pthread_mutex_lock(&gclistlock);");
484 outmethod.println("threadcount--;");
485 outmethod.println("pthread_cond_signal(&gccond);");
486 outmethod.println("pthread_mutex_unlock(&gclistlock);");
489 if (state.DSM||state.SINGLETM) {
490 //outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n");
491 outmethod.println("#if defined(TRANSSTATS) \n");
492 outmethod.println("printf(\"****** Transaction Stats ******\\n\");");
493 outmethod.println("printf(\"numTransCommit= %d\\n\", numTransCommit);");
494 outmethod.println("printf(\"numTransAbort= %d\\n\", numTransAbort);");
495 outmethod.println("printf(\"nSoftAbort= %d\\n\", nSoftAbort);");
497 outmethod.println("printf(\"nchashSearch= %d\\n\", nchashSearch);");
498 outmethod.println("printf(\"nmhashSearch= %d\\n\", nmhashSearch);");
499 outmethod.println("printf(\"nprehashSearch= %d\\n\", nprehashSearch);");
500 outmethod.println("printf(\"ndirtyCacheObj= %d\\n\", ndirtyCacheObj);");
501 outmethod.println("printf(\"nRemoteReadSend= %d\\n\", nRemoteSend);");
502 outmethod.println("printf(\"bytesSent= %d\\n\", bytesSent);");
503 outmethod.println("printf(\"bytesRecv= %d\\n\", bytesRecv);");
504 outmethod.println("printf(\"totalObjSize= %d\\n\", totalObjSize);");
505 outmethod.println("printf(\"sendRemoteReq= %d\\n\", sendRemoteReq);");
506 outmethod.println("printf(\"getResponse= %d\\n\", getResponse);");
507 } else if (state.SINGLETM) {
508 outmethod.println("printf(\"nSoftAbortAbort= %d\\n\", nSoftAbortAbort);");
509 outmethod.println("printf(\"nSoftAbortCommit= %d\\n\", nSoftAbortCommit);");
510 outmethod.println("#ifdef STMSTATS\n");
511 outmethod.println("for(i=0; i<TOTALNUMCLASSANDARRAY; i++) {\n");
512 outmethod.println(" printf(\"typesCausingAbort[%2d] numaccess= %5d numabort= %3d\\n\", i, typesCausingAbort[i].numaccess, typesCausingAbort[i].numabort);\n");
513 outmethod.println("}\n");
514 outmethod.println("#endif\n");
515 outmethod.println("fflush(stdout);");
517 outmethod.println("#endif\n");
520 if (state.EVENTMONITOR) {
521 outmethod.println("dumpdata();");
524 if (state.THREAD||state.SINGLETM)
525 outmethod.println("pthread_exit(NULL);");
527 if (state.MLP || state.OOOJAVA ) {
528 outmethod.println(" workScheduleBegin();");
531 outmethod.println("}");
534 /* This method outputs code for each task. */
536 private void outputTaskCode(PrintWriter outtaskdefs, PrintWriter outmethod) {
537 /* Compile task based program */
538 outtaskdefs.println("#include \"task.h\"");
539 outtaskdefs.println("#include \"methodheaders.h\"");
540 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
541 while(taskit.hasNext()) {
542 TaskDescriptor td=(TaskDescriptor)taskit.next();
543 FlatMethod fm=state.getMethodFlat(td);
544 generateFlatMethod(fm, null, outmethod);
545 generateTaskDescriptor(outtaskdefs, fm, td);
548 //Output task descriptors
549 taskit=state.getTaskSymbolTable().getDescriptorsIterator();
550 outtaskdefs.println("struct taskdescriptor * taskarray[]= {");
552 while(taskit.hasNext()) {
553 TaskDescriptor td=(TaskDescriptor)taskit.next();
557 outtaskdefs.println(",");
558 outtaskdefs.print("&task_"+td.getSafeSymbol());
560 outtaskdefs.println("};");
562 outtaskdefs.println("int numtasks="+state.getTaskSymbolTable().getValueSet().size()+";");
565 /* This method outputs most of the methods.c file. This includes
566 * some standard includes and then an array with the sizes of
567 * objets and array that stores supertype and then the code for
568 * the Java methods.. */
570 protected void outputMethods(PrintWriter outmethod) {
571 outmethod.println("#include \"methodheaders.h\"");
572 outmethod.println("#include \"virtualtable.h\"");
573 outmethod.println("#include \"runtime.h\"");
575 // always include: compiler directives will leave out
576 // instrumentation when option is not set
577 outmethod.println("#include \"coreprof/coreprof.h\"");
580 outmethod.println("#include \"sandboxdefs.c\"");
583 outmethod.println("#include \"addPrefetchEnhance.h\"");
584 outmethod.println("#include \"localobjects.h\"");
586 if (state.FASTCHECK) {
587 outmethod.println("#include \"localobjects.h\"");
589 if(state.MULTICORE) {
591 outmethod.println("#include \"task.h\"");
593 outmethod.println("#include \"multicoreruntime.h\"");
594 outmethod.println("#include \"runtime_arch.h\"");
596 if (state.THREAD||state.DSM||state.SINGLETM)
597 outmethod.println("#include <thread.h>");
598 if (state.main!=null) {
599 outmethod.println("#include <string.h>");
601 if (state.CONSCHECK) {
602 outmethod.println("#include \"checkers.h\"");
604 if (state.MLP || state.OOOJAVA ) {
605 outmethod.println("#include <stdlib.h>");
606 outmethod.println("#include <stdio.h>");
607 outmethod.println("#include \"mlp_runtime.h\"");
608 outmethod.println("#include \"psemaphore.h\"");
611 outmethod.println("#include \"trqueue.h\"");
612 outmethod.println("#include \"RuntimeConflictResolver.h\"");
613 outmethod.println("#include \"rcr_runtime.h\"");
617 outmethod.println("struct global_defs_t * global_defs_p;");
618 //Store the sizes of classes & array elements
619 generateSizeArray(outmethod);
621 //Store table of supertypes
622 generateSuperTypeTable(outmethod);
624 //Store the layout of classes
625 generateLayoutStructs(outmethod);
627 /* Generate code for methods */
628 if (state.DSM||state.SINGLETM) {
629 for(Iterator<LocalityBinding> lbit=locality.getLocalityBindings().iterator(); lbit.hasNext();) {
630 LocalityBinding lb=lbit.next();
631 MethodDescriptor md=lb.getMethod();
632 FlatMethod fm=state.getMethodFlat(md);
634 if (!md.getModifiers().isNative()) {
635 generateFlatMethod(fm, lb, outmethod);
636 //System.out.println("fm= " + fm + " md= " + md);
640 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
641 while(classit.hasNext()) {
642 ClassDescriptor cn=(ClassDescriptor)classit.next();
643 Iterator methodit=cn.getMethods();
644 while(methodit.hasNext()) {
645 /* Classify parameters */
646 MethodDescriptor md=(MethodDescriptor)methodit.next();
647 FlatMethod fm=state.getMethodFlat(md);
648 if (!md.getModifiers().isNative()) {
649 generateFlatMethod(fm, null, outmethod);
656 protected void outputStructs(PrintWriter outstructs) {
657 outstructs.println("#ifndef STRUCTDEFS_H");
658 outstructs.println("#define STRUCTDEFS_H");
659 outstructs.println("#include \"classdefs.h\"");
660 outstructs.println("#ifndef INTPTR");
661 outstructs.println("#ifdef BIT64");
662 outstructs.println("#define INTPTR long");
663 outstructs.println("#else");
664 outstructs.println("#define INTPTR int");
665 outstructs.println("#endif");
666 outstructs.println("#endif");
667 if( state.MLP || state.OOOJAVA ) {
668 outstructs.println("#include \"mlp_runtime.h\"");
669 outstructs.println("#include \"psemaphore.h\"");
672 outstructs.println("#include \"rcr_runtime.h\"");
676 /* Output #defines that the runtime uses to determine type
677 * numbers for various objects it needs */
678 outstructs.println("#define MAXCOUNT "+maxcount);
679 if (state.DSM||state.SINGLETM) {
680 LocalityBinding lbrun=new LocalityBinding(typeutil.getRun(), false);
682 lbrun.setGlobalThis(LocalityAnalysis.GLOBAL);
684 else if (state.SINGLETM) {
685 lbrun.setGlobalThis(LocalityAnalysis.NORMAL);
687 outstructs.println("#define RUNMETHOD "+virtualcalls.getLocalityNumber(lbrun));
691 LocalityBinding lbexecute = new LocalityBinding(typeutil.getExecute(), false);
693 lbexecute.setGlobalThis(LocalityAnalysis.GLOBAL);
694 else if( state.SINGLETM)
695 lbexecute.setGlobalThis(LocalityAnalysis.NORMAL);
696 outstructs.println("#define EXECUTEMETHOD " + virtualcalls.getLocalityNumber(lbexecute));
699 outstructs.println("#define STRINGARRAYTYPE "+
700 (state.getArrayNumber(
701 (new TypeDescriptor(typeutil.getClass(TypeUtil.StringClass))).makeArray(state))+state.numClasses()));
703 outstructs.println("#define OBJECTARRAYTYPE "+
704 (state.getArrayNumber(
705 (new TypeDescriptor(typeutil.getClass(TypeUtil.ObjectClass))).makeArray(state))+state.numClasses()));
708 outstructs.println("#define STRINGTYPE "+typeutil.getClass(TypeUtil.StringClass).getId());
709 outstructs.println("#define CHARARRAYTYPE "+
710 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.CHAR)).makeArray(state))+state.numClasses()));
712 outstructs.println("#define BYTEARRAYTYPE "+
713 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state))+state.numClasses()));
715 outstructs.println("#define BYTEARRAYARRAYTYPE "+
716 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state).makeArray(state))+state.numClasses()));
718 outstructs.println("#define NUMCLASSES "+state.numClasses());
719 int totalClassSize = state.numClasses() + state.numArrays();
720 outstructs.println("#define TOTALNUMCLASSANDARRAY "+ totalClassSize);
722 outstructs.println("#define STARTUPTYPE "+typeutil.getClass(TypeUtil.StartupClass).getId());
723 outstructs.println("#define TAGTYPE "+typeutil.getClass(TypeUtil.TagClass).getId());
724 outstructs.println("#define TAGARRAYTYPE "+
725 (state.getArrayNumber(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)).makeArray(state))+state.numClasses()));
729 protected void outputClassDeclarations(PrintWriter outclassdefs, PrintWriter outglobaldefs) {
730 if (state.THREAD||state.DSM||state.SINGLETM)
731 outclassdefs.println("#include <pthread.h>");
732 outclassdefs.println("#ifndef INTPTR");
733 outclassdefs.println("#ifdef BIT64");
734 outclassdefs.println("#define INTPTR long");
735 outclassdefs.println("#else");
736 outclassdefs.println("#define INTPTR int");
737 outclassdefs.println("#endif");
738 outclassdefs.println("#endif");
740 outclassdefs.println("#include \"optionalstruct.h\"");
741 outclassdefs.println("struct "+arraytype+";");
742 /* Start by declaring all structs */
743 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
744 while(it.hasNext()) {
745 ClassDescriptor cn=(ClassDescriptor)it.next();
746 outclassdefs.println("struct "+cn.getSafeSymbol()+";");
748 outclassdefs.println("");
749 //Print out definition for array type
750 outclassdefs.println("struct "+arraytype+" {");
751 outclassdefs.println(" int type;");
752 if(state.MLP || state.OOOJAVA ){
753 outclassdefs.println(" int oid;");
754 outclassdefs.println(" int allocsite;");
756 if (state.EVENTMONITOR) {
757 outclassdefs.println(" int objuid;");
760 outclassdefs.println(" pthread_t tid;");
761 outclassdefs.println(" void * lockentry;");
762 outclassdefs.println(" int lockcount;");
765 outclassdefs.println(" int mutex;");
766 outclassdefs.println(" int objlock;");
767 if(state.MULTICOREGC) {
768 outclassdefs.println(" int marked;");
772 outclassdefs.println(" int flag;");
773 if(!state.MULTICORE) {
774 outclassdefs.println(" void * flagptr;");
776 outclassdefs.println(" int version;");
777 outclassdefs.println(" int * lock;"); // lock entry for this obj
778 outclassdefs.println(" int mutex;");
779 outclassdefs.println(" int lockcount;");
780 if(state.MULTICOREGC) {
781 outclassdefs.println(" int marked;");
785 outclassdefs.println(" int numfses;");
786 outclassdefs.println(" int * fses;");
789 printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs, outglobaldefs);
791 if (state.STMARRAY) {
792 outclassdefs.println(" int lowindex;");
793 outclassdefs.println(" int highindex;");
796 outclassdefs.println(" int paddingforarray;");
797 if (state.DUALVIEW) {
798 outclassdefs.println(" int arrayversion;");
801 outclassdefs.println(" int ___length___;");
802 outclassdefs.println("};\n");
803 outclassdefs.println("extern int classsize[];");
804 outclassdefs.println("extern int hasflags[];");
805 outclassdefs.println("extern unsigned INTPTR * pointerarray[];");
806 outclassdefs.println("extern int supertypes[];");
807 outclassdefs.println("#include \"globaldefs.h\"");
808 outclassdefs.println("");
811 /** Prints out definitions for generic task structures */
813 private void outputTaskTypes(PrintWriter outtask) {
814 outtask.println("#ifndef _TASK_H");
815 outtask.println("#define _TASK_H");
816 outtask.println("struct parameterdescriptor {");
817 outtask.println("int type;");
818 outtask.println("int numberterms;");
819 outtask.println("int *intarray;");
820 outtask.println("void * queue;");
821 outtask.println("int numbertags;");
822 outtask.println("int *tagarray;");
823 outtask.println("};");
825 outtask.println("struct taskdescriptor {");
826 outtask.println("void * taskptr;");
827 outtask.println("int numParameters;");
828 outtask.println(" int numTotal;");
829 outtask.println("struct parameterdescriptor **descriptorarray;");
830 outtask.println("char * name;");
831 outtask.println("};");
832 outtask.println("extern struct taskdescriptor * taskarray[];");
833 outtask.println("extern numtasks;");
834 outtask.println("#endif");
838 private void buildRepairStructs(PrintWriter outrepairstructs) {
839 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
840 while(classit.hasNext()) {
841 ClassDescriptor cn=(ClassDescriptor)classit.next();
842 outrepairstructs.println("structure "+cn.getSymbol()+" {");
843 outrepairstructs.println(" int __type__;");
845 outrepairstructs.println(" int __flag__;");
846 if(!state.MULTICORE) {
847 outrepairstructs.println(" int __flagptr__;");
850 printRepairStruct(cn, outrepairstructs);
851 outrepairstructs.println("}\n");
854 for(int i=0; i<state.numArrays(); i++) {
855 TypeDescriptor tdarray=arraytable[i];
856 TypeDescriptor tdelement=tdarray.dereference();
857 outrepairstructs.println("structure "+arraytype+"_"+state.getArrayNumber(tdarray)+" {");
858 outrepairstructs.println(" int __type__;");
859 printRepairStruct(typeutil.getClass(TypeUtil.ObjectClass), outrepairstructs);
860 outrepairstructs.println(" int length;");
862 // Need to add support to repair tool for this
863 if (tdelement.isClass()||tdelement.isArray())
864 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" * elem[this.length];");
866 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" elem[this.length];");
868 outrepairstructs.println("}\n");
872 private void printRepairStruct(ClassDescriptor cn, PrintWriter output) {
873 ClassDescriptor sp=cn.getSuperDesc();
875 printRepairStruct(sp, output);
877 Vector fields=(Vector)fieldorder.get(cn);
879 for(int i=0; i<fields.size(); i++) {
880 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
881 if (fd.getType().isArray()) {
882 output.println(" "+arraytype+"_"+ state.getArrayNumber(fd.getType()) +" * "+fd.getSymbol()+";");
883 } else if (fd.getType().isClass())
884 output.println(" "+fd.getType().getRepairSymbol()+" * "+fd.getSymbol()+";");
885 else if (fd.getType().isFloat())
886 output.println(" int "+fd.getSymbol()+"; /* really float */");
888 output.println(" "+fd.getType().getRepairSymbol()+" "+fd.getSymbol()+";");
892 /** This method outputs TaskDescriptor information */
893 private void generateTaskDescriptor(PrintWriter output, FlatMethod fm, TaskDescriptor task) {
894 for (int i=0; i<task.numParameters(); i++) {
895 VarDescriptor param_var=task.getParameter(i);
896 TypeDescriptor param_type=task.getParamType(i);
897 FlagExpressionNode param_flag=task.getFlag(param_var);
898 TagExpressionList param_tag=task.getTag(param_var);
901 if (param_flag==null) {
902 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
903 output.println("0x0, 0x0 };");
906 DNFFlag dflag=param_flag.getDNF();
907 dnfterms=dflag.size();
909 Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
910 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
911 for(int j=0; j<dflag.size(); j++) {
914 Vector term=dflag.get(j);
917 for(int k=0; k<term.size(); k++) {
918 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
919 FlagDescriptor fd=dfa.getFlag();
920 boolean negated=dfa.getNegated();
921 int flagid=1<<((Integer)flags.get(fd)).intValue();
926 output.print("0x"+Integer.toHexString(andmask)+", 0x"+Integer.toHexString(checkmask));
928 output.println("};");
931 output.println("int parametertag_"+i+"_"+task.getSafeSymbol()+"[]={");
932 //BUG...added next line to fix, test with any task program
934 for(int j=0; j<param_tag.numTags(); j++) {
937 /* for each tag we need */
938 /* which slot it is */
939 /* what type it is */
940 TagVarDescriptor tvd=(TagVarDescriptor)task.getParameterTable().get(param_tag.getName(j));
941 TempDescriptor tmp=param_tag.getTemp(j);
942 int slot=fm.getTagInt(tmp);
943 output.println(slot+", "+state.getTagId(tvd.getTag()));
945 output.println("};");
947 output.println("struct parameterdescriptor parameter_"+i+"_"+task.getSafeSymbol()+"={");
948 output.println("/* type */"+param_type.getClassDesc().getId()+",");
949 output.println("/* number of DNF terms */"+dnfterms+",");
950 output.println("parameterdnf_"+i+"_"+task.getSafeSymbol()+",");
951 output.println("0,");
952 //BUG, added next line to fix and else statement...test
953 //with any task program
955 output.println("/* number of tags */"+param_tag.numTags()+",");
957 output.println("/* number of tags */ 0,");
958 output.println("parametertag_"+i+"_"+task.getSafeSymbol());
959 output.println("};");
963 output.println("struct parameterdescriptor * parameterdescriptors_"+task.getSafeSymbol()+"[] = {");
964 for (int i=0; i<task.numParameters(); i++) {
967 output.print("¶meter_"+i+"_"+task.getSafeSymbol());
969 output.println("};");
971 output.println("struct taskdescriptor task_"+task.getSafeSymbol()+"={");
972 output.println("&"+task.getSafeSymbol()+",");
973 output.println("/* number of parameters */" +task.numParameters() + ",");
974 int numtotal=task.numParameters()+fm.numTags();
975 output.println("/* number total parameters */" +numtotal + ",");
976 output.println("parameterdescriptors_"+task.getSafeSymbol()+",");
977 output.println("\""+task.getSymbol()+"\"");
978 output.println("};");
982 /** The buildVirtualTables method outputs the virtual dispatch
983 * tables for methods. */
985 protected void buildVirtualTables(PrintWriter outvirtual) {
986 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
987 while(classit.hasNext()) {
988 ClassDescriptor cd=(ClassDescriptor)classit.next();
989 if (virtualcalls.getMethodCount(cd)>maxcount)
990 maxcount=virtualcalls.getMethodCount(cd);
992 MethodDescriptor[][] virtualtable=null;
993 LocalityBinding[][] lbvirtualtable=null;
994 if (state.DSM||state.SINGLETM)
995 lbvirtualtable=new LocalityBinding[state.numClasses()+state.numArrays()][maxcount];
997 virtualtable=new MethodDescriptor[state.numClasses()+state.numArrays()][maxcount];
999 /* Fill in virtual table */
1000 classit=state.getClassSymbolTable().getDescriptorsIterator();
1001 while(classit.hasNext()) {
1002 ClassDescriptor cd=(ClassDescriptor)classit.next();
1003 if (state.DSM||state.SINGLETM)
1004 fillinRow(cd, lbvirtualtable, cd.getId());
1006 fillinRow(cd, virtualtable, cd.getId());
1009 ClassDescriptor objectcd=typeutil.getClass(TypeUtil.ObjectClass);
1010 Iterator arrayit=state.getArrayIterator();
1011 while(arrayit.hasNext()) {
1012 TypeDescriptor td=(TypeDescriptor)arrayit.next();
1013 int id=state.getArrayNumber(td);
1014 if (state.DSM||state.SINGLETM)
1015 fillinRow(objectcd, lbvirtualtable, id+state.numClasses());
1017 fillinRow(objectcd, virtualtable, id+state.numClasses());
1020 outvirtual.print("void * virtualtable[]={");
1021 boolean needcomma=false;
1022 for(int i=0; i<state.numClasses()+state.numArrays(); i++) {
1023 for(int j=0; j<maxcount; j++) {
1025 outvirtual.print(", ");
1026 if ((state.DSM||state.SINGLETM)&&lbvirtualtable[i][j]!=null) {
1027 LocalityBinding lb=lbvirtualtable[i][j];
1028 MethodDescriptor md=lb.getMethod();
1029 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
1030 } else if (!(state.DSM||state.SINGLETM)&&virtualtable[i][j]!=null) {
1031 MethodDescriptor md=virtualtable[i][j];
1032 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
1034 outvirtual.print("0");
1038 outvirtual.println("");
1040 outvirtual.println("};");
1044 private void fillinRow(ClassDescriptor cd, MethodDescriptor[][] virtualtable, int rownum) {
1045 /* Get inherited methods */
1046 if (cd.getSuperDesc()!=null)
1047 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
1048 /* Override them with our methods */
1049 for(Iterator it=cd.getMethods(); it.hasNext();) {
1050 MethodDescriptor md=(MethodDescriptor)it.next();
1051 if (md.isStatic()||md.getReturnType()==null)
1053 int methodnum=virtualcalls.getMethodNumber(md);
1054 virtualtable[rownum][methodnum]=md;
1058 private void fillinRow(ClassDescriptor cd, LocalityBinding[][] virtualtable, int rownum) {
1059 /* Get inherited methods */
1060 if (cd.getSuperDesc()!=null)
1061 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
1062 /* Override them with our methods */
1063 if (locality.getClassBindings(cd)!=null)
1064 for(Iterator<LocalityBinding> lbit=locality.getClassBindings(cd).iterator(); lbit.hasNext();) {
1065 LocalityBinding lb=lbit.next();
1066 MethodDescriptor md=lb.getMethod();
1067 //Is the method static or a constructor
1068 if (md.isStatic()||md.getReturnType()==null)
1070 int methodnum=virtualcalls.getLocalityNumber(lb);
1071 virtualtable[rownum][methodnum]=lb;
1075 /** Generate array that contains the sizes of class objects. The
1076 * object allocation functions in the runtime use this
1079 private void generateSizeArray(PrintWriter outclassdefs) {
1080 outclassdefs.print("extern struct prefetchCountStats * evalPrefetch;\n");
1081 outclassdefs.print("#ifdef TRANSSTATS \n");
1082 outclassdefs.print("extern int numTransAbort;\n");
1083 outclassdefs.print("extern int numTransCommit;\n");
1084 outclassdefs.print("extern int nSoftAbort;\n");
1086 outclassdefs.print("extern int nchashSearch;\n");
1087 outclassdefs.print("extern int nmhashSearch;\n");
1088 outclassdefs.print("extern int nprehashSearch;\n");
1089 outclassdefs.print("extern int ndirtyCacheObj;\n");
1090 outclassdefs.print("extern int nRemoteSend;\n");
1091 outclassdefs.print("extern int sendRemoteReq;\n");
1092 outclassdefs.print("extern int getResponse;\n");
1093 outclassdefs.print("extern int bytesSent;\n");
1094 outclassdefs.print("extern int bytesRecv;\n");
1095 outclassdefs.print("extern int totalObjSize;\n");
1096 outclassdefs.print("extern void handle();\n");
1097 } else if (state.SINGLETM) {
1098 outclassdefs.println("extern int nSoftAbortAbort;");
1099 outclassdefs.println("extern int nSoftAbortCommit;");
1100 outclassdefs.println("#ifdef STMSTATS\n");
1101 outclassdefs.println("extern objtypestat_t typesCausingAbort[];");
1102 outclassdefs.println("#endif\n");
1104 outclassdefs.print("#endif\n");
1106 outclassdefs.print("int numprefetchsites = " + pa.prefetchsiteid + ";\n");
1107 if(this.state.MLP || state.OOOJAVA ){
1108 outclassdefs.print("extern __thread int oid;\n");
1109 outclassdefs.print("extern int numWorkers;\n");
1112 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1113 cdarray=new ClassDescriptor[state.numClasses()];
1115 while(it.hasNext()) {
1116 ClassDescriptor cd=(ClassDescriptor)it.next();
1117 cdarray[cd.getId()]=cd;
1120 arraytable=new TypeDescriptor[state.numArrays()];
1122 Iterator arrayit=state.getArrayIterator();
1123 while(arrayit.hasNext()) {
1124 TypeDescriptor td=(TypeDescriptor)arrayit.next();
1125 int id=state.getArrayNumber(td);
1131 /* Print out types */
1132 outclassdefs.println("/* ");
1133 for(int i=0; i<state.numClasses(); i++) {
1134 ClassDescriptor cd=cdarray[i];
1136 outclassdefs.println("NULL " + i);
1138 outclassdefs.println(cd +" "+i);
1142 for(int i=0; i<state.numArrays(); i++) {
1143 TypeDescriptor arraytd=arraytable[i];
1144 outclassdefs.println(arraytd.toPrettyString() +" "+(i+state.numClasses()));
1147 outclassdefs.println("*/");
1150 outclassdefs.print("int classsize[]={");
1152 boolean needcomma=false;
1153 for(int i=0; i<state.numClasses(); i++) {
1155 outclassdefs.print(", ");
1157 outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")");
1159 outclassdefs.print("0");
1165 for(int i=0; i<state.numArrays(); i++) {
1167 outclassdefs.print(", ");
1168 TypeDescriptor tdelement=arraytable[i].dereference();
1169 if (tdelement.isArray()||tdelement.isClass())
1170 outclassdefs.print("sizeof(void *)");
1172 outclassdefs.print("sizeof("+tdelement.getSafeSymbol()+")");
1176 outclassdefs.println("};");
1178 ClassDescriptor objectclass=typeutil.getClass(TypeUtil.ObjectClass);
1180 outclassdefs.print("int typearray[]={");
1181 for(int i=0; i<state.numClasses(); i++) {
1182 ClassDescriptor cd=cdarray[i];
1183 ClassDescriptor supercd=i>0?cd.getSuperDesc():null;
1185 outclassdefs.print(", ");
1187 outclassdefs.print("-1");
1189 outclassdefs.print(supercd.getId());
1193 for(int i=0; i<state.numArrays(); i++) {
1194 TypeDescriptor arraytd=arraytable[i];
1195 ClassDescriptor arraycd=arraytd.getClassDesc();
1196 if (arraycd==null) {
1198 outclassdefs.print(", ");
1199 outclassdefs.print(objectclass.getId());
1203 ClassDescriptor cd=arraycd.getSuperDesc();
1206 TypeDescriptor supertd=new TypeDescriptor(cd);
1207 supertd.setArrayCount(arraytd.getArrayCount());
1208 type=state.getArrayNumber(supertd);
1210 type+=state.numClasses();
1213 cd=cd.getSuperDesc();
1216 outclassdefs.print(", ");
1217 outclassdefs.print(type);
1221 outclassdefs.println("};");
1226 outclassdefs.print("int typearray2[]={");
1227 for(int i=0; i<state.numArrays(); i++) {
1228 TypeDescriptor arraytd=arraytable[i];
1229 ClassDescriptor arraycd=arraytd.getClassDesc();
1230 if (arraycd==null) {
1232 outclassdefs.print(", ");
1233 outclassdefs.print("-1");
1237 ClassDescriptor cd=arraycd.getSuperDesc();
1238 int level=arraytd.getArrayCount()-1;
1240 for(; level>0; level--) {
1241 TypeDescriptor supertd=new TypeDescriptor(objectclass);
1242 supertd.setArrayCount(level);
1243 type=state.getArrayNumber(supertd);
1245 type+=state.numClasses();
1250 outclassdefs.print(", ");
1251 outclassdefs.print(type);
1255 outclassdefs.println("};");
1258 /** Constructs params and temp objects for each method or task.
1259 * These objects tell the compiler which temps need to be
1262 protected void generateTempStructs(FlatMethod fm, LocalityBinding lb) {
1263 MethodDescriptor md=fm.getMethod();
1264 TaskDescriptor task=fm.getTask();
1265 Set<TempDescriptor> saveset=lb!=null ? locality.getTempSet(lb) : null;
1266 ParamsObject objectparams=md!=null ? new ParamsObject(md,tag++) : new ParamsObject(task, tag++);
1268 paramstable.put(lb, objectparams);
1269 backuptable.put(lb, new Hashtable<TempDescriptor, TempDescriptor>());
1270 } else if (md!=null)
1271 paramstable.put(md, objectparams);
1273 paramstable.put(task, objectparams);
1275 for(int i=0; i<fm.numParameters(); i++) {
1276 TempDescriptor temp=fm.getParameter(i);
1277 TypeDescriptor type=temp.getType();
1278 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1279 objectparams.addPtr(temp);
1281 objectparams.addPrim(temp);
1282 if(lb!=null&&saveset.contains(temp)) {
1283 backuptable.get(lb).put(temp, temp.createNew());
1287 for(int i=0; i<fm.numTags(); i++) {
1288 TempDescriptor temp=fm.getTag(i);
1289 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1290 objectparams.addPtr(temp);
1292 objectparams.addPrim(temp);
1295 TempObject objecttemps=md!=null ? new TempObject(objectparams,md,tag++) : new TempObject(objectparams, task, tag++);
1297 tempstable.put(lb, objecttemps);
1299 tempstable.put(md, objecttemps);
1301 tempstable.put(task, objecttemps);
1303 for(Iterator nodeit=fm.getNodeSet().iterator(); nodeit.hasNext();) {
1304 FlatNode fn=(FlatNode)nodeit.next();
1305 TempDescriptor[] writes=fn.writesTemps();
1306 for(int i=0; i<writes.length; i++) {
1307 TempDescriptor temp=writes[i];
1308 TypeDescriptor type=temp.getType();
1309 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1310 objecttemps.addPtr(temp);
1312 objecttemps.addPrim(temp);
1313 if(lb!=null&&saveset.contains(temp)&&
1314 !backuptable.get(lb).containsKey(temp))
1315 backuptable.get(lb).put(temp, temp.createNew());
1319 /* Create backup temps */
1321 for(Iterator<TempDescriptor> tmpit=backuptable.get(lb).values().iterator(); tmpit.hasNext();) {
1322 TempDescriptor tmp=tmpit.next();
1323 TypeDescriptor type=tmp.getType();
1324 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1325 objecttemps.addPtr(tmp);
1327 objecttemps.addPrim(tmp);
1329 /* Create temp to hold revert table */
1330 if (state.DSM&&(lb.getHasAtomic()||lb.isAtomic())) {
1331 TempDescriptor reverttmp=new TempDescriptor("revertlist", typeutil.getClass(TypeUtil.ObjectClass));
1332 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1333 objecttemps.addPtr(reverttmp);
1335 objecttemps.addPrim(reverttmp);
1336 reverttable.put(lb, reverttmp);
1341 /** This method outputs the following information about classes
1343 * (1) For classes, what are the locations of pointers.
1344 * (2) For arrays, does the array contain pointers or primitives.
1345 * (3) For classes, does the class contain flags.
1348 private void generateLayoutStructs(PrintWriter output) {
1349 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1350 while(it.hasNext()) {
1351 ClassDescriptor cn=(ClassDescriptor)it.next();
1352 output.println("unsigned INTPTR "+cn.getSafeSymbol()+"_pointers[]={");
1353 Iterator allit=cn.getFieldTable().getAllDescriptorsIterator();
1355 while(allit.hasNext()) {
1356 FieldDescriptor fd=(FieldDescriptor)allit.next();
1357 TypeDescriptor type=fd.getType();
1358 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1363 output.print(count);
1364 allit=cn.getFieldTable().getAllDescriptorsIterator();
1365 while(allit.hasNext()) {
1366 FieldDescriptor fd=(FieldDescriptor)allit.next();
1367 TypeDescriptor type=fd.getType();
1368 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1371 output.println(",");
1372 output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+fd.getSafeSymbol()+"))");
1375 output.println("};");
1377 output.println("unsigned INTPTR * pointerarray[]={");
1378 boolean needcomma=false;
1379 for(int i=0; i<state.numClasses(); i++) {
1380 ClassDescriptor cn=cdarray[i];
1382 output.println(",");
1385 output.print(cn.getSafeSymbol()+"_pointers");
1387 output.print("NULL");
1391 for(int i=0; i<state.numArrays(); i++) {
1393 output.println(", ");
1394 TypeDescriptor tdelement=arraytable[i].dereference();
1395 if (tdelement.isArray()||tdelement.isClass())
1396 output.print("((unsigned INTPTR *)1)");
1402 output.println("};");
1404 output.println("int hasflags[]={");
1405 for(int i=0; i<state.numClasses(); i++) {
1406 ClassDescriptor cn=cdarray[i];
1408 output.println(", ");
1410 if ((cn != null) && (cn.hasFlags()))
1415 output.println("};");
1418 /** Print out table to give us supertypes */
1419 private void generateSuperTypeTable(PrintWriter output) {
1420 output.println("int supertypes[]={");
1421 boolean needcomma=false;
1422 for(int i=0; i<state.numClasses(); i++) {
1423 ClassDescriptor cn=cdarray[i];
1425 output.println(",");
1427 if ((cn != null) && (cn.getSuperDesc()!=null)) {
1428 ClassDescriptor cdsuper=cn.getSuperDesc();
1429 output.print(cdsuper.getId());
1433 output.println("};");
1436 /** Force consistent field ordering between inherited classes. */
1438 private void printClassStruct(ClassDescriptor cn, PrintWriter classdefout, PrintWriter globaldefout) {
1440 ClassDescriptor sp=cn.getSuperDesc();
1442 printClassStruct(sp, classdefout, globaldefout);
1444 if (!fieldorder.containsKey(cn)) {
1445 Vector fields=new Vector();
1446 fieldorder.put(cn,fields);
1447 Vector fieldvec=cn.getFieldVec();
1448 for(int i=0;i<fieldvec.size();i++) {
1449 FieldDescriptor fd=(FieldDescriptor)fieldvec.get(i);
1450 if ((sp==null||!sp.getFieldTable().contains(fd.getSymbol())))
1454 Vector fields=(Vector)fieldorder.get(cn);
1456 for(int i=0; i<fields.size(); i++) {
1457 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
1458 if (fd.getType().isClass()||fd.getType().isArray())
1459 classdefout.println(" struct "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1460 else if(fd.isStatic()) {
1462 globaldefout.println(" "+fd.getType().getSafeSymbol()+ " "+cn.getSafeSymbol()+fd.getSafeSymbol()+";");
1463 classdefout.println(" "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1465 classdefout.println(" "+fd.getType().getSafeSymbol()+" "+fd.getSafeSymbol()+";");
1470 /* Map flags to integers consistently between inherited
1473 protected void mapFlags(ClassDescriptor cn) {
1474 ClassDescriptor sp=cn.getSuperDesc();
1478 if (!flagorder.containsKey(cn)) {
1479 Hashtable flags=new Hashtable();
1480 flagorder.put(cn,flags);
1482 Hashtable superflags=(Hashtable)flagorder.get(sp);
1483 Iterator superflagit=superflags.keySet().iterator();
1484 while(superflagit.hasNext()) {
1485 FlagDescriptor fd=(FlagDescriptor)superflagit.next();
1486 Integer number=(Integer)superflags.get(fd);
1487 flags.put(fd, number);
1488 if ((number.intValue()+1)>max)
1489 max=number.intValue()+1;
1493 Iterator flagit=cn.getFlags();
1494 while(flagit.hasNext()) {
1495 FlagDescriptor fd=(FlagDescriptor)flagit.next();
1496 if (sp==null||!sp.getFlagTable().contains(fd.getSymbol()))
1497 flags.put(fd, new Integer(max++));
1503 /** This function outputs (1) structures that parameters are
1504 * passed in (when PRECISE GC is enabled) and (2) function
1505 * prototypes for the methods */
1507 protected void generateCallStructs(ClassDescriptor cn, PrintWriter classdefout, PrintWriter output, PrintWriter headersout, PrintWriter globaldefout) {
1508 /* Output class structure */
1509 classdefout.println("struct "+cn.getSafeSymbol()+" {");
1510 classdefout.println(" int type;");
1511 if(state.MLP || state.OOOJAVA){
1512 classdefout.println(" int oid;");
1513 classdefout.println(" int allocsite;");
1515 if (state.EVENTMONITOR) {
1516 classdefout.println(" int objuid;");
1519 classdefout.println(" pthread_t tid;");
1520 classdefout.println(" void * lockentry;");
1521 classdefout.println(" int lockcount;");
1524 classdefout.println(" int mutex;");
1525 classdefout.println(" int objlock;");
1526 if(state.MULTICOREGC) {
1527 classdefout.println(" int marked;");
1531 classdefout.println(" int flag;");
1532 if((!state.MULTICORE) || (cn.getSymbol().equals("TagDescriptor"))) {
1533 classdefout.println(" void * flagptr;");
1534 } else if (state.MULTICORE) {
1535 classdefout.println(" int version;");
1536 classdefout.println(" int * lock;"); // lock entry for this obj
1537 classdefout.println(" int mutex;");
1538 classdefout.println(" int lockcount;");
1539 if(state.MULTICOREGC) {
1540 classdefout.println(" int marked;");
1543 if (state.OPTIONAL) {
1544 classdefout.println(" int numfses;");
1545 classdefout.println(" int * fses;");
1548 printClassStruct(cn, classdefout, globaldefout);
1549 classdefout.println("};\n");
1551 if (state.DSM||state.SINGLETM) {
1552 /* Cycle through LocalityBindings */
1553 HashSet<MethodDescriptor> nativemethods=new HashSet<MethodDescriptor>();
1554 Set<LocalityBinding> lbset=locality.getClassBindings(cn);
1556 for(Iterator<LocalityBinding> lbit=lbset.iterator(); lbit.hasNext();) {
1557 LocalityBinding lb=lbit.next();
1558 MethodDescriptor md=lb.getMethod();
1559 if (md.getModifiers().isNative()) {
1560 //make sure we only print a native method once
1561 if (nativemethods.contains(md)) {
1562 FlatMethod fm=state.getMethodFlat(md);
1563 generateTempStructs(fm, lb);
1566 nativemethods.add(md);
1568 generateMethod(cn, md, lb, headersout, output);
1571 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1572 MethodDescriptor md=(MethodDescriptor)methodit.next();
1573 if (md.getModifiers().isNative()&&!nativemethods.contains(md)) {
1574 //Need to build param structure for library code
1575 FlatMethod fm=state.getMethodFlat(md);
1576 generateTempStructs(fm, null);
1577 generateMethodParam(cn, md, null, output);
1582 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1583 MethodDescriptor md=(MethodDescriptor)methodit.next();
1584 generateMethod(cn, md, null, headersout, output);
1588 private void generateMethodParam(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter output) {
1589 /* Output parameter structure */
1590 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1591 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1592 if ((state.DSM||state.SINGLETM)&&lb!=null)
1593 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1595 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1596 output.println(" int size;");
1597 output.println(" void * next;");
1598 for(int i=0; i<objectparams.numPointers(); i++) {
1599 TempDescriptor temp=objectparams.getPointer(i);
1600 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1602 output.println("};\n");
1606 private void generateMethod(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter headersout, PrintWriter output) {
1607 FlatMethod fm=state.getMethodFlat(md);
1608 generateTempStructs(fm, lb);
1610 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1611 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md);
1613 generateMethodParam(cn, md, lb, output);
1615 /* Output temp structure */
1616 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1617 if (state.DSM||state.SINGLETM)
1618 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1620 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1621 output.println(" int size;");
1622 output.println(" void * next;");
1623 for(int i=0; i<objecttemps.numPointers(); i++) {
1624 TempDescriptor temp=objecttemps.getPointer(i);
1625 if (temp.getType().isNull())
1626 output.println(" void * "+temp.getSafeSymbol()+";");
1628 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1630 output.println("};\n");
1633 /********* Output method declaration ***********/
1634 if (state.DSM||state.SINGLETM) {
1635 headersout.println("#define D"+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1637 headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1639 /* First the return type */
1640 if (md.getReturnType()!=null) {
1641 if (md.getReturnType().isClass()||md.getReturnType().isArray())
1642 headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1644 headersout.print(md.getReturnType().getSafeSymbol()+" ");
1646 //catch the constructor case
1647 headersout.print("void ");
1649 /* Next the method name */
1650 if (state.DSM||state.SINGLETM) {
1651 headersout.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1653 headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1655 boolean printcomma=false;
1656 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1657 if (state.DSM||state.SINGLETM) {
1658 headersout.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1660 headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1664 /* Output parameter list*/
1665 for(int i=0; i<objectparams.numPrimitives(); i++) {
1666 TempDescriptor temp=objectparams.getPrimitive(i);
1668 headersout.print(", ");
1670 if (temp.getType().isClass()||temp.getType().isArray())
1671 headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1673 headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1675 headersout.println(");\n");
1679 /** This function outputs (1) structures that parameters are
1680 * passed in (when PRECISE GC is enabled) and (2) function
1681 * prototypes for the tasks */
1683 private void generateTaskStructs(PrintWriter output, PrintWriter headersout) {
1684 /* Cycle through tasks */
1685 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
1687 while(taskit.hasNext()) {
1688 /* Classify parameters */
1689 TaskDescriptor task=(TaskDescriptor)taskit.next();
1690 FlatMethod fm=state.getMethodFlat(task);
1691 generateTempStructs(fm, null);
1693 ParamsObject objectparams=(ParamsObject) paramstable.get(task);
1694 TempObject objecttemps=(TempObject) tempstable.get(task);
1696 /* Output parameter structure */
1697 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1698 output.println("struct "+task.getSafeSymbol()+"_params {");
1699 output.println(" int size;");
1700 output.println(" void * next;");
1701 for(int i=0; i<objectparams.numPointers(); i++) {
1702 TempDescriptor temp=objectparams.getPointer(i);
1703 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1706 output.println("};\n");
1707 if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
1708 maxtaskparams=objectparams.numPointers()+fm.numTags();
1712 /* Output temp structure */
1713 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1714 output.println("struct "+task.getSafeSymbol()+"_locals {");
1715 output.println(" int size;");
1716 output.println(" void * next;");
1717 for(int i=0; i<objecttemps.numPointers(); i++) {
1718 TempDescriptor temp=objecttemps.getPointer(i);
1719 if (temp.getType().isNull())
1720 output.println(" void * "+temp.getSafeSymbol()+";");
1721 else if(temp.getType().isTag())
1722 output.println(" struct "+
1723 (new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1725 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1727 output.println("};\n");
1730 /* Output task declaration */
1731 headersout.print("void " + task.getSafeSymbol()+"(");
1733 boolean printcomma=false;
1734 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1735 headersout.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
1737 headersout.print("void * parameterarray[]");
1738 headersout.println(");\n");
1742 /***** Generate code for FlatMethod fm. *****/
1744 Hashtable<FlatAtomicEnterNode, AtomicRecord> atomicmethodmap;
1745 static int atomicmethodcount=0;
1748 BranchAnalysis branchanalysis;
1749 private void generateFlatMethod(FlatMethod fm, LocalityBinding lb, PrintWriter output) {
1750 if (State.PRINTFLAT)
1751 System.out.println(fm.printMethod());
1752 MethodDescriptor md=fm.getMethod();
1753 TaskDescriptor task=fm.getTask();
1754 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
1755 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : md!=null ? md : task);
1757 HashSet<AtomicRecord> arset=null;
1758 branchanalysis=null;
1760 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1762 if (atomicmethodmap==null)
1763 atomicmethodmap=new Hashtable<FlatAtomicEnterNode, AtomicRecord>();
1765 //fix these so we get right strings for local variables
1766 localsprefixaddr=localsprefix;
1767 localsprefixderef=localsprefix+"->";
1768 arset=new HashSet<AtomicRecord>();
1770 //build branchanalysis
1771 branchanalysis=new BranchAnalysis(locality, lb, delaycomp.getNotReady(lb), delaycomp.livecode(lb), state);
1773 //Generate commit methods here
1774 for(Iterator<FlatNode> fnit=fm.getNodeSet().iterator();fnit.hasNext();) {
1775 FlatNode fn=fnit.next();
1776 if (fn.kind()==FKind.FlatAtomicEnterNode&&
1777 locality.getAtomic(lb).get(fn.getPrev(0)).intValue()==0&&
1778 delaycomp.needsFission(lb, (FlatAtomicEnterNode) fn)) {
1779 //We have an atomic enter
1780 FlatAtomicEnterNode faen=(FlatAtomicEnterNode) fn;
1781 Set<FlatNode> exitset=faen.getExits();
1783 String methodname=md.getSymbol()+(atomicmethodcount++);
1784 AtomicRecord ar=new AtomicRecord();
1788 atomicmethodmap.put(faen, ar);
1790 //build data structure declaration
1791 output.println("struct atomicprimitives_"+methodname+" {");
1793 Set<FlatNode> recordset=delaycomp.livecode(lb);
1794 Set<TempDescriptor> liveinto=delaycomp.liveinto(lb, faen, recordset);
1795 Set<TempDescriptor> liveout=delaycomp.liveout(lb, faen);
1796 Set<TempDescriptor> liveoutvirtualread=delaycomp.liveoutvirtualread(lb, faen);
1798 ar.reallivein=new HashSet(liveinto);
1800 ar.liveoutvirtualread=liveoutvirtualread;
1803 for(Iterator<TempDescriptor> it=liveinto.iterator(); it.hasNext();) {
1804 TempDescriptor tmp=it.next();
1805 //remove the pointers
1806 if (tmp.getType().isPtr()) {
1809 //let's print it here
1810 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1813 for(Iterator<TempDescriptor> it=liveout.iterator(); it.hasNext();) {
1814 TempDescriptor tmp=it.next();
1815 //remove the pointers
1816 if (tmp.getType().isPtr()) {
1818 } else if (!liveinto.contains(tmp)) {
1819 //let's print it here
1820 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1823 output.println("};");
1825 //print out method name
1826 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) {");
1827 //build code for commit method
1829 //first define local primitives
1830 Set<TempDescriptor> alltemps=delaycomp.alltemps(lb, faen, recordset);
1831 for(Iterator<TempDescriptor> tmpit=alltemps.iterator();tmpit.hasNext();) {
1832 TempDescriptor tmp=tmpit.next();
1833 if (!tmp.getType().isPtr()) {
1834 if (liveinto.contains(tmp)||liveoutvirtualread.contains(tmp)) {
1835 //read from live into set
1836 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+"=primitives->"+tmp.getSafeSymbol()+";");
1839 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1843 //turn off write barrier generation
1845 state.SINGLETM=false;
1846 generateCode(faen, fm, lb, exitset, output, false);
1847 state.SINGLETM=true;
1848 //turn on write barrier generation
1850 output.println("}\n\n");
1854 //redefine these back to normal
1856 localsprefixaddr="&"+localsprefix;
1857 localsprefixderef=localsprefix+".";
1859 generateHeader(fm, lb, md!=null ? md : task,output);
1860 TempObject objecttemp=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
1862 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1863 for(Iterator<AtomicRecord> arit=arset.iterator();arit.hasNext();) {
1864 AtomicRecord ar=arit.next();
1865 output.println("struct atomicprimitives_"+ar.name+" primitives_"+ar.name+";");
1869 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1870 if (md!=null&&(state.DSM||state.SINGLETM))
1871 output.print(" struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1872 else if (md!=null&&!(state.DSM||state.SINGLETM))
1873 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1875 output.print(" struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={");
1876 output.print(objecttemp.numPointers()+",");
1877 output.print(paramsprefix);
1878 for(int j=0; j<objecttemp.numPointers(); j++)
1879 output.print(", NULL");
1880 output.println("};");
1883 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1884 TempDescriptor td=objecttemp.getPrimitive(i);
1885 TypeDescriptor type=td.getType();
1887 output.println(" void * "+td.getSafeSymbol()+";");
1888 else if (type.isClass()||type.isArray())
1889 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1891 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1895 if( state.MLP || state.OOOJAVA ) {
1896 if( fm.getNext(0) instanceof FlatSESEEnterNode ) {
1897 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
1898 if( (state.MLP && callerSESEplaceholder != mlpa.getMainSESE()) ||
1899 (state.OOOJAVA && callerSESEplaceholder != oooa.getMainSESE())
1901 // declare variables for naming static SESE's
1902 output.println(" /* static SESE names */");
1903 Iterator<SESEandAgePair> pItr = callerSESEplaceholder.getNeededStaticNames().iterator();
1904 while( pItr.hasNext() ) {
1905 SESEandAgePair pair = pItr.next();
1906 output.println(" void* "+pair+" = NULL;");
1909 // declare variables for tracking dynamic sources
1910 output.println(" /* dynamic variable sources */");
1911 Iterator<TempDescriptor> dynSrcItr = callerSESEplaceholder.getDynamicVarSet().iterator();
1912 while( dynSrcItr.hasNext() ) {
1913 TempDescriptor dynSrcVar = dynSrcItr.next();
1914 output.println(" SESEcommon* "+dynSrcVar+"_srcSESE = NULL;");
1915 output.println(" INTPTR "+dynSrcVar+"_srcOffset = 0x1;");
1920 // set up related allocation sites's waiting queues
1923 ConflictGraph graph = null;
1924 graph = mlpa.getConflictGraphResults().get(fm);
1925 if (graph != null && graph.hasConflictEdge()) {
1926 output.println(" /* set up waiting queues */");
1927 output.println(" int numMemoryQueue=0;");
1928 output.println(" int memoryQueueItemID=0;");
1929 HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
1931 System.out.println("#lockSet="+lockSet.hashCode());
1932 System.out.println("lockset="+lockSet);
1933 for (Iterator iterator = lockSet.iterator(); iterator.hasNext();) {
1934 SESELock seseLock = (SESELock) iterator.next();
1935 System.out.println("id="+seseLock.getID());
1936 System.out.println("#="+seseLock);
1938 System.out.println("size="+lockSet.size());
1939 if (lockSet.size() > 0) {
1940 output.println(" numMemoryQueue=" + lockSet.size() + ";");
1941 output.println(" runningSESE->numMemoryQueue=numMemoryQueue;");
1942 output.println(" runningSESE->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
1947 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
1948 if(callerSESEplaceholder!= oooa.getMainSESE()){
1949 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(callerSESEplaceholder);
1950 if (graph != null && graph.hasConflictEdge()) {
1951 output.println(" // set up waiting queues ");
1952 output.println(" int numMemoryQueue=0;");
1953 output.println(" int memoryQueueItemID=0;");
1954 Set<Analysis.OoOJava.SESELock> lockSet = oooa.getLockMappings(graph);
1955 System.out.println("#lockSet="+lockSet.hashCode());
1956 System.out.println("lockset="+lockSet);
1957 for (Iterator iterator = lockSet.iterator(); iterator.hasNext();) {
1958 Analysis.OoOJava.SESELock seseLock = (Analysis.OoOJava.SESELock) iterator.next();
1959 System.out.println("id="+seseLock.getID());
1960 System.out.println("#="+seseLock);
1962 System.out.println("size="+lockSet.size());
1963 if (lockSet.size() > 0) {
1964 output.println(" numMemoryQueue=" + lockSet.size() + ";");
1965 output.println(" runningSESE->numMemoryQueue=numMemoryQueue;");
1966 output.println(" runningSESE->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
1976 /* Check to see if we need to do a GC if this is a
1977 * multi-threaded program...*/
1979 if (((state.MLP||state.OOOJAVA||state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
1980 || this.state.MULTICOREGC) {
1981 //Don't bother if we aren't in recursive methods...The loops case will catch it
1982 if (callgraph.getAllMethods(md).contains(md)) {
1983 if (state.DSM&&lb.isAtomic())
1984 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
1985 else if (this.state.MULTICOREGC) {
1986 output.println("if(gcflag) gc("+localsprefixaddr+");");
1988 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
1993 if(fm.getMethod().isStaticBlock()) {
1995 } else if((fm.getMethod().getReturnType() == null) && (cn != null)){
1996 // is a constructor, check and output initialization of the static fields
1997 Vector fields=(Vector)fieldorder.get(cn);
1999 for(int i=0; i<fields.size(); i++) {
2000 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
2003 output.println(generateTemp(fm,fm.getParameter(0),lb)+"->"+fd.getSafeSymbol()+"=&(global_defs_p->"+cn.getSafeSymbol()+fd.getSafeSymbol()+");");
2008 generateCode(fm.getNext(0), fm, lb, null, output, true);
2010 output.println("}\n\n");
2014 protected void initializeSESE( FlatSESEEnterNode fsen ) {
2016 FlatMethod fm = fsen.getfmEnclosing();
2017 MethodDescriptor md = fm.getMethod();
2018 ClassDescriptor cn = md.getClassDesc();
2021 // Creates bogus method descriptor to index into tables
2022 Modifiers modBogus = new Modifiers();
2023 MethodDescriptor mdBogus =
2024 new MethodDescriptor( modBogus,
2025 new TypeDescriptor( TypeDescriptor.VOID ),
2026 "sese_"+fsen.getPrettyIdentifier()+fsen.getIdentifier()
2029 mdBogus.setClassDesc( fsen.getcdEnclosing() );
2030 FlatMethod fmBogus = new FlatMethod( mdBogus, null );
2031 fsen.setfmBogus( fmBogus );
2032 fsen.setmdBogus( mdBogus );
2034 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
2035 inSetAndOutSet.addAll( fsen.getInVarSet() );
2036 inSetAndOutSet.addAll( fsen.getOutVarSet() );
2038 // Build paramsobj for bogus method descriptor
2039 ParamsObject objectparams = new ParamsObject( mdBogus, tag++ );
2040 paramstable.put( mdBogus, objectparams );
2042 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
2043 while( itr.hasNext() ) {
2044 TempDescriptor temp = itr.next();
2045 TypeDescriptor type = temp.getType();
2046 if( type.isPtr() ) {
2047 objectparams.addPtr( temp );
2049 objectparams.addPrim( temp );
2053 // Build normal temp object for bogus method descriptor
2054 TempObject objecttemps = new TempObject( objectparams, mdBogus, tag++ );
2055 tempstable.put( mdBogus, objecttemps );
2057 for( Iterator nodeit = fsen.getNodeSet().iterator(); nodeit.hasNext(); ) {
2058 FlatNode fn = (FlatNode)nodeit.next();
2059 TempDescriptor[] writes = fn.writesTemps();
2061 for( int i = 0; i < writes.length; i++ ) {
2062 TempDescriptor temp = writes[i];
2063 TypeDescriptor type = temp.getType();
2065 if( type.isPtr() ) {
2066 objecttemps.addPtr( temp );
2068 objecttemps.addPrim( temp );
2074 // used when generating the specific SESE record struct
2075 // to remember the FIRST field name of sese records
2076 // that the current SESE depends on--we need to know the
2077 // offset to the first one for garbage collection
2078 protected void addingDepRecField( FlatSESEEnterNode fsen,
2080 if( fsen.getFirstDepRecField() == null ) {
2081 fsen.setFirstDepRecField( field );
2083 fsen.incNumDepRecs();
2086 protected void generateMethodSESE(FlatSESEEnterNode fsen,
2088 PrintWriter outputStructs,
2089 PrintWriter outputMethHead,
2090 PrintWriter outputMethods
2093 ParamsObject objectparams = (ParamsObject) paramstable.get( fsen.getmdBogus() );
2094 TempObject objecttemps = (TempObject) tempstable .get( fsen.getmdBogus() );
2096 // generate locals structure
2097 outputStructs.println("struct "+
2098 fsen.getcdEnclosing().getSafeSymbol()+
2099 fsen.getmdBogus().getSafeSymbol()+"_"+
2100 fsen.getmdBogus().getSafeMethodDescriptor()+
2102 outputStructs.println(" int size;");
2103 outputStructs.println(" void * next;");
2104 for(int i=0; i<objecttemps.numPointers(); i++) {
2105 TempDescriptor temp=objecttemps.getPointer(i);
2107 if (temp.getType().isNull())
2108 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
2110 outputStructs.println(" struct "+
2111 temp.getType().getSafeSymbol()+" * "+
2112 temp.getSafeSymbol()+";");
2114 outputStructs.println("};\n");
2117 // divide in-set and out-set into objects and primitives to prep
2118 // for the record generation just below
2119 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
2120 inSetAndOutSet.addAll( fsen.getInVarSet() );
2121 inSetAndOutSet.addAll( fsen.getOutVarSet() );
2123 Set<TempDescriptor> inSetAndOutSetObjs = new HashSet<TempDescriptor>();
2124 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
2126 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
2127 while( itr.hasNext() ) {
2128 TempDescriptor temp = itr.next();
2129 TypeDescriptor type = temp.getType();
2130 if( type.isPtr() ) {
2131 inSetAndOutSetObjs.add( temp );
2133 inSetAndOutSetPrims.add( temp );
2138 // generate the SESE record structure
2139 outputStructs.println(fsen.getSESErecordName()+" {");
2141 // data common to any SESE, and it must be placed first so
2142 // a module that doesn't know what kind of SESE record this
2143 // is can cast the pointer to a common struct
2144 outputStructs.println(" SESEcommon common;");
2146 // then garbage list stuff
2147 outputStructs.println(" /* next is in-set and out-set objects that look like a garbage list */");
2148 outputStructs.println(" int size;");
2149 outputStructs.println(" void * next;");
2151 // I think that the set of TempDescriptors inSetAndOutSetObjs
2152 // calculated above should match the pointer object params
2153 // used in the following code, but let's just leave the working
2154 // implementation unless there is actually a problem...
2156 Vector<TempDescriptor> inset=fsen.getInVarsForDynamicCoarseConflictResolution();
2157 for(int i=0; i<inset.size();i++) {
2158 TempDescriptor temp=inset.get(i);
2159 if (temp.getType().isNull())
2160 outputStructs.println(" void * "+temp.getSafeSymbol()+
2161 "; /* in-or-out-set obj in gl */");
2163 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+
2164 temp.getSafeSymbol()+"; /* in-or-out-set obj in gl */");
2167 for(int i=0; i<objectparams.numPointers(); i++) {
2168 TempDescriptor temp=objectparams.getPointer(i);
2169 if (!inset.contains(temp)) {
2170 if (temp.getType().isNull())
2171 outputStructs.println(" void * "+temp.getSafeSymbol()+
2172 "; /* in-or-out-set obj in gl */");
2174 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+
2175 temp.getSafeSymbol()+"; /* in-or-out-set obj in gl */");
2179 outputStructs.println(" /* next is primitives for in-set and out-set and dynamic tracking */");
2181 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
2182 while( itrPrims.hasNext() ) {
2183 TempDescriptor temp = itrPrims.next();
2184 TypeDescriptor type = temp.getType();
2185 if(type.isPrimitive()){
2186 outputStructs.println(" "+temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol()+"; /* in-set or out-set primitive */");
2190 // note that the sese record pointer will be added below, just primitive part of tracking here
2191 Iterator<TempDescriptor> itrDynInVars = fsen.getDynamicInVarSet().iterator();
2192 while( itrDynInVars.hasNext() ) {
2193 TempDescriptor dynInVar = itrDynInVars.next();
2194 outputStructs.println(" INTPTR "+dynInVar+"_srcOffset; /* dynamic tracking primitive */");
2198 outputStructs.println(" /* everything after this should be pointers to an SESE record */" );
2200 // other half of info for dynamic tracking, the SESE record pointer
2201 itrDynInVars = fsen.getDynamicInVarSet().iterator();
2202 while( itrDynInVars.hasNext() ) {
2203 TempDescriptor dynInVar = itrDynInVars.next();
2204 String depRecField = dynInVar+"_srcSESE";
2205 outputStructs.println(" SESEcommon* "+depRecField+";");
2206 addingDepRecField( fsen, depRecField );
2209 // statically known sese sources are record pointers, too
2210 Iterator<SESEandAgePair> itrStaticInVarSrcs = fsen.getStaticInVarSrcs().iterator();
2211 while( itrStaticInVarSrcs.hasNext() ) {
2212 SESEandAgePair srcPair = itrStaticInVarSrcs.next();
2213 outputStructs.println(" "+srcPair.getSESE().getSESErecordName()+"* "+srcPair+";");
2214 addingDepRecField(fsen, srcPair.toString());
2218 if (inset.size()!=0)
2219 outputStructs.println("struct rcrRecord rcrRecords["+inset.size()+"];");
2222 if( fsen.getFirstDepRecField() != null ) {
2223 outputStructs.println(" /* compiler believes first dependent SESE record field above is: "+
2224 fsen.getFirstDepRecField()+" */" );
2226 outputStructs.println("};\n");
2229 // write method declaration to header file
2230 outputMethHead.print("void ");
2231 outputMethHead.print(fsen.getSESEmethodName()+"(");
2232 outputMethHead.print(fsen.getSESErecordName()+"* "+paramsprefix);
2233 outputMethHead.println(");\n");
2236 generateFlatMethodSESE( fsen.getfmBogus(),
2237 fsen.getcdEnclosing(),
2243 private void generateFlatMethodSESE(FlatMethod fm,
2245 FlatSESEEnterNode fsen,
2246 FlatSESEExitNode seseExit,
2250 MethodDescriptor md=fm.getMethod();
2252 output.print("void ");
2253 output.print(fsen.getSESEmethodName()+"(");
2254 output.print(fsen.getSESErecordName()+"* "+paramsprefix);
2255 output.println("){\n");
2258 TempObject objecttemp=(TempObject) tempstable.get(md);
2260 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2261 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
2262 output.print(objecttemp.numPointers()+",");
2263 output.print("&(((SESEcommon*)(___params___))[1])");
2264 for(int j=0; j<objecttemp.numPointers(); j++)
2265 output.print(", NULL");
2266 output.println("};");
2269 output.println(" /* regular local primitives */");
2270 for(int i=0; i<objecttemp.numPrimitives(); i++) {
2271 TempDescriptor td=objecttemp.getPrimitive(i);
2272 TypeDescriptor type=td.getType();
2274 output.println(" void * "+td.getSafeSymbol()+";");
2275 else if (type.isClass()||type.isArray())
2276 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
2278 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
2282 // declare variables for naming static SESE's
2283 output.println(" /* static SESE names */");
2284 Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
2285 while( pItr.hasNext() ) {
2286 SESEandAgePair pair = pItr.next();
2287 output.println(" SESEcommon* "+pair+" = NULL;");
2290 // declare variables for tracking dynamic sources
2291 output.println(" /* dynamic variable sources */");
2292 Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
2293 while( dynSrcItr.hasNext() ) {
2294 TempDescriptor dynSrcVar = dynSrcItr.next();
2295 output.println(" SESEcommon* "+dynSrcVar+"_srcSESE = NULL;");
2296 output.println(" INTPTR "+dynSrcVar+"_srcOffset = 0x1;");
2299 // declare local temps for in-set primitives, and if it is
2300 // a ready-source variable, get the value from the record
2301 output.println(" /* local temps for in-set primitives */");
2302 Iterator<TempDescriptor> itrInSet = fsen.getInVarSet().iterator();
2303 while( itrInSet.hasNext() ) {
2304 TempDescriptor temp = itrInSet.next();
2305 TypeDescriptor type = temp.getType();
2306 if( !type.isPtr() ) {
2307 if( fsen.getReadyInVarSet().contains( temp ) ) {
2308 output.println(" "+type+" "+temp+" = "+paramsprefix+"->"+temp+";");
2310 output.println(" "+type+" "+temp+";");
2315 // declare local temps for out-set primitives if its not already
2316 // in the in-set, and it's value will get written so no problem
2317 output.println(" /* local temp for out-set prim, not already in the in-set */");
2318 Iterator<TempDescriptor> itrOutSet = fsen.getOutVarSet().iterator();
2319 while( itrOutSet.hasNext() ) {
2320 TempDescriptor temp = itrOutSet.next();
2321 TypeDescriptor type = temp.getType();
2322 if( !type.isPtr() && !fsen.getInVarSet().contains( temp ) ) {
2323 output.println(" "+type+" "+temp+";");
2328 // initialize thread-local var to a the task's record, which is fused
2329 // with the param list
2330 output.println(" ");
2331 output.println(" // code of this task's body should use this to access the running task record");
2332 output.println(" runningSESE = &(___params___->common);");
2333 output.println(" ");
2335 // setup memory queue
2338 output.println(" // set up memory queues ");
2339 output.println(" int numMemoryQueue=0;");
2340 output.println(" int memoryQueueItemID=0;");
2341 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(fsen);
2342 if (graph != null && graph.hasConflictEdge()) {
2343 output.println(" {");
2344 Set<Analysis.OoOJava.SESELock> lockSet = oooa.getLockMappings(graph);
2345 System.out.println("#lockSet="+lockSet);
2346 if (lockSet.size() > 0) {
2347 output.println(" numMemoryQueue=" + lockSet.size() + ";");
2348 output.println(" runningSESE->numMemoryQueue=numMemoryQueue;");
2349 output.println(" runningSESE->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2352 output.println(" }");
2355 output.println(" // set up memory queues ");
2356 output.println(" int numMemoryQueue=0;");
2357 output.println(" int memoryQueueItemID=0;");
2358 ConflictGraph graph = null;
2359 graph = mlpa.getConflictGraphResults().get(fsen);
2360 if (graph != null && graph.hasConflictEdge()) {
2361 output.println(" {");
2362 HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
2364 System.out.println("#lockSet="+lockSet);
2366 if (lockSet.size() > 0) {
2367 output.println(" numMemoryQueue=" + lockSet.size() + "; ");
2368 output.println(" runningSESE->numMemoryQueue=numMemoryQueue;");
2369 output.println(" runningSESE->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2372 output.println(" }");
2377 // set up a task's mem pool to recycle the allocation of children tasks
2378 // don't bother if the task never has children (a leaf task)
2379 output.println( "#ifndef OOO_DISABLE_TASKMEMPOOL" );
2380 if( !fsen.getIsLeafSESE() ) {
2381 output.println(" runningSESE->taskRecordMemPool = poolcreate( "+
2382 maxTaskRecSizeStr+" );");
2384 // make it clear we purposefully did not initialize this
2385 output.println(" runningSESE->taskRecordMemPool = (MemPool*)0x1;");
2387 output.println( "#endif // OOO_DISABLE_TASKMEMPOOL" );
2390 // copy in-set into place, ready vars were already
2391 // copied when the SESE was issued
2392 Iterator<TempDescriptor> tempItr;
2394 // static vars are from a known SESE
2395 output.println(" // copy variables from static sources");
2396 tempItr = fsen.getStaticInVarSet().iterator();
2397 while( tempItr.hasNext() ) {
2398 TempDescriptor temp = tempItr.next();
2399 VariableSourceToken vst = fsen.getStaticInVarSrc( temp );
2400 SESEandAgePair srcPair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2401 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2402 " = "+paramsprefix+"->"+srcPair+"->"+vst.getAddrVar()+";");
2405 output.println(" // decrement references to static sources");
2406 for( Iterator<SESEandAgePair> pairItr = fsen.getStaticInVarSrcs().iterator(); pairItr.hasNext(); ) {
2407 SESEandAgePair srcPair = pairItr.next();
2408 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
2409 output.println(" {");
2410 output.println(" SESEcommon* src = &("+paramsprefix+"->"+srcPair+"->common);");
2411 output.println(" RELEASE_REFERENCE_TO( src );");
2412 output.println(" }");
2413 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
2417 // dynamic vars come from an SESE and src
2418 output.println(" // copy variables from dynamic sources");
2419 tempItr = fsen.getDynamicInVarSet().iterator();
2420 while( tempItr.hasNext() ) {
2421 TempDescriptor temp = tempItr.next();
2422 TypeDescriptor type = temp.getType();
2424 // go grab it from the SESE source
2425 output.println(" if( "+paramsprefix+"->"+temp+"_srcSESE != NULL ) {");
2428 if( type.isNull() ) {
2430 } else if( type.isClass() || type.isArray() ) {
2431 typeStr = "struct "+type.getSafeSymbol()+"*";
2433 typeStr = type.getSafeSymbol();
2436 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2437 " = *(("+typeStr+"*) ((void*)"+
2438 paramsprefix+"->"+temp+"_srcSESE + "+
2439 paramsprefix+"->"+temp+"_srcOffset));");
2441 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
2442 output.println(" SESEcommon* src = "+paramsprefix+"->"+temp+"_srcSESE;");
2443 output.println(" RELEASE_REFERENCE_TO( src );");
2444 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
2446 // or if the source was our parent, its already in our record to grab
2447 output.println(" } else {");
2448 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2449 " = "+paramsprefix+"->"+temp+";");
2450 output.println(" }");
2453 // Check to see if we need to do a GC if this is a
2454 // multi-threaded program...
2455 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2456 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2457 //Don't bother if we aren't in recursive methods...The loops case will catch it
2458 // if (callgraph.getAllMethods(md).contains(md)) {
2459 // if(this.state.MULTICOREGC) {
2460 // output.println("if(gcflag) gc("+localsprefixaddr+");");
2462 // output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2467 if( state.COREPROF ) {
2468 output.println("#ifdef CP_EVENTID_TASKEXECUTE");
2469 output.println(" CP_LOGEVENT( CP_EVENTID_TASKEXECUTE, CP_EVENTTYPE_BEGIN );");
2470 output.println("#endif");
2473 HashSet<FlatNode> exitset=new HashSet<FlatNode>();
2474 exitset.add(seseExit);
2475 generateCode(fsen.getNext(0), fm, null, exitset, output, true);
2476 output.println("}\n\n");
2481 // when a new mlp thread is created for an issued SESE, it is started
2482 // by running this method which blocks on a cond variable until
2483 // it is allowed to transition to execute. Then a case statement
2484 // allows it to invoke the method with the proper SESE body, and after
2485 // exiting the SESE method, executes proper SESE exit code before the
2486 // thread can be destroyed
2487 private void generateSESEinvocationMethod(PrintWriter outmethodheader,
2488 PrintWriter outmethod
2491 outmethodheader.println("void* invokeSESEmethod( void* seseRecord );");
2492 outmethod.println( "void* invokeSESEmethod( void* seseRecord ) {");
2493 outmethod.println( " int status;");
2494 outmethod.println( " char errmsg[128];");
2496 // generate a case for each SESE class that can be invoked
2497 outmethod.println( " switch( *((int*)seseRecord) ) {");
2498 outmethod.println( " ");
2499 Iterator<FlatSESEEnterNode> seseit;
2501 seseit=mlpa.getAllSESEs().iterator();
2503 seseit=oooa.getAllSESEs().iterator();
2505 while(seseit.hasNext()){
2506 FlatSESEEnterNode fsen = seseit.next();
2508 outmethod.println( " /* "+fsen.getPrettyIdentifier()+" */");
2509 outmethod.println( " case "+fsen.getIdentifier()+":");
2510 outmethod.println( " "+fsen.getSESEmethodName()+"( seseRecord );");
2512 if( (state.MLP && fsen.equals( mlpa.getMainSESE() )) ||
2513 (state.OOOJAVA && fsen.equals( oooa.getMainSESE() ))
2515 outmethod.println( " /* work scheduler works forever, explicitly exit */");
2516 outmethod.println( " CP_EXIT();");
2517 outmethod.println( " CP_DUMP();");
2518 outmethod.println( " workScheduleExit();");
2519 outmethod.println( " exit( 0 );");
2522 outmethod.println( " break;");
2523 outmethod.println( "");
2526 // default case should never be taken, error out
2527 outmethod.println( " default:");
2528 outmethod.println( " printf(\"Error: unknown SESE class ID in invoke method.\\n\");");
2529 outmethod.println( " exit(-30);");
2530 outmethod.println( " break;");
2531 outmethod.println( " }");
2532 outmethod.println( " return NULL;");
2533 outmethod.println( "}\n\n");
2537 protected void generateCode(FlatNode first,
2540 Set<FlatNode> stopset,
2541 PrintWriter output, boolean firstpass) {
2543 /* Assign labels to FlatNode's if necessary.*/
2545 Hashtable<FlatNode, Integer> nodetolabel;
2547 if (state.DELAYCOMP&&!firstpass)
2548 nodetolabel=dcassignLabels(first, stopset);
2550 nodetolabel=assignLabels(first, stopset);
2552 Set<FlatNode> storeset=null;
2553 HashSet<FlatNode> genset=null;
2554 HashSet<FlatNode> refset=null;
2555 Set<FlatNode> unionset=null;
2557 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
2558 storeset=delaycomp.livecode(lb);
2559 genset=new HashSet<FlatNode>();
2560 if (state.STMARRAY&&!state.DUALVIEW) {
2561 refset=new HashSet<FlatNode>();
2562 refset.addAll(delaycomp.getDeref(lb));
2563 refset.removeAll(delaycomp.getCannotDelay(lb));
2564 refset.removeAll(delaycomp.getOther(lb));
2567 genset.addAll(delaycomp.getCannotDelay(lb));
2568 genset.addAll(delaycomp.getOther(lb));
2570 genset.addAll(delaycomp.getNotReady(lb));
2571 if (state.STMARRAY&&!state.DUALVIEW) {
2572 genset.removeAll(refset);
2575 unionset=new HashSet<FlatNode>();
2576 unionset.addAll(storeset);
2577 unionset.addAll(genset);
2578 if (state.STMARRAY&&!state.DUALVIEW)
2579 unionset.addAll(refset);
2582 /* Do the actual code generation */
2583 FlatNode current_node=null;
2584 HashSet tovisit=new HashSet();
2585 HashSet visited=new HashSet();
2587 tovisit.add(first.getNext(0));
2590 while(current_node!=null||!tovisit.isEmpty()) {
2591 if (current_node==null) {
2592 current_node=(FlatNode)tovisit.iterator().next();
2593 tovisit.remove(current_node);
2594 } else if (tovisit.contains(current_node)) {
2595 tovisit.remove(current_node);
2597 visited.add(current_node);
2598 if (nodetolabel.containsKey(current_node)) {
2599 output.println("L"+nodetolabel.get(current_node)+":");
2601 if (state.INSTRUCTIONFAILURE) {
2602 if (state.THREAD||state.DSM||state.SINGLETM) {
2603 output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
2605 output.println("if ((--instructioncount)==0) injectinstructionfailure();");
2607 if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
2609 if (!state.DELAYCOMP||firstpass) {
2610 generateFlatNode(fm, lb, current_node, output);
2612 //store primitive variables in out set
2613 AtomicRecord ar=atomicmethodmap.get((FlatAtomicEnterNode)first);
2614 Set<TempDescriptor> liveout=ar.liveout;
2615 for(Iterator<TempDescriptor> tmpit=liveout.iterator();tmpit.hasNext();) {
2616 TempDescriptor tmp=tmpit.next();
2617 output.println("primitives->"+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2620 if ((state.MLP || state.OOOJAVA) && stopset!=null) {
2621 assert first.getPrev( 0 ) instanceof FlatSESEEnterNode;
2622 assert current_node instanceof FlatSESEExitNode;
2623 FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev( 0 );
2624 FlatSESEExitNode fsxn = (FlatSESEExitNode) current_node;
2625 assert fsen.getFlatExit().equals( fsxn );
2626 assert fsxn.getFlatEnter().equals( fsen );
2628 if (current_node.kind()!=FKind.FlatReturnNode) {
2629 output.println(" return;");
2632 } else if(current_node.numNext()==1) {
2634 if ((state.MLP|| state.OOOJAVA) &&
2635 current_node.kind()==FKind.FlatSESEEnterNode &&
2636 !((FlatSESEEnterNode)current_node).getIsCallerSESEplaceholder()
2638 FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
2639 generateFlatNode(fm, lb, current_node, output);
2640 nextnode=fsen.getFlatExit().getNext(0);
2641 } else if (state.DELAYCOMP) {
2642 boolean specialprimitive=false;
2643 //skip literals...no need to add extra overhead
2644 if (storeset!=null&&storeset.contains(current_node)&¤t_node.kind()==FKind.FlatLiteralNode) {
2645 TypeDescriptor typedesc=((FlatLiteralNode)current_node).getType();
2646 if (!typedesc.isClass()&&!typedesc.isArray()) {
2647 specialprimitive=true;
2651 if (genset==null||genset.contains(current_node)||specialprimitive)
2652 generateFlatNode(fm, lb, current_node, output);
2653 if (state.STMARRAY&&!state.DUALVIEW&&refset!=null&&refset.contains(current_node)) {
2654 //need to acquire lock
2655 handleArrayDeref(fm, lb, current_node, output, firstpass);
2657 if (storeset!=null&&storeset.contains(current_node)&&!specialprimitive) {
2658 TempDescriptor wrtmp=current_node.writesTemps()[0];
2660 //need to store value written by previous node
2661 if (wrtmp.getType().isPtr()) {
2662 //only lock the objects that may actually need locking
2663 if (recorddc.getNeedTrans(lb, current_node)&&
2664 (!state.STMARRAY||state.DUALVIEW||!wrtmp.getType().isArray()||
2665 wrtmp.getType().getSymbol().equals(TypeUtil.ObjectClass))) {
2666 output.println("STOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2668 output.println("STOREPTRNOLOCK("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2671 output.println("STORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");/* "+current_node.nodeid+" */");
2674 //need to read value read by previous node
2675 if (wrtmp.getType().isPtr()) {
2676 output.println("RESTOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2678 output.println("RESTORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+"); /* "+current_node.nodeid+" */");
2682 nextnode=current_node.getNext(0);
2685 generateFlatNode(fm, lb, current_node, output);
2686 nextnode=current_node.getNext(0);
2688 if (visited.contains(nextnode)) {
2689 output.println("goto L"+nodetolabel.get(nextnode)+";");
2692 current_node=nextnode;
2693 } else if (current_node.numNext()==2) {
2695 if (state.DELAYCOMP) {
2696 boolean computeside=false;
2698 //need to record which way it should go
2699 if (genset==null||genset.contains(current_node)) {
2700 if (storeset!=null&&storeset.contains(current_node)) {
2701 //need to store which way branch goes
2702 generateStoreFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2704 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2706 //which side to execute
2710 if (genset.contains(current_node)) {
2711 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2712 } else if (storeset.contains(current_node)) {
2714 branchanalysis.generateGroupCode(current_node, output, nodetolabel);
2716 //which side to execute
2721 Set<FlatNode> leftset=DelayComputation.getNext(current_node, 0, unionset, lb,locality, true);
2723 if (leftset.size()==0)
2725 if (visited.contains(current_node.getNext(branch))) {
2726 //already visited -- build jump
2727 output.println("goto L"+nodetolabel.get(current_node.getNext(branch))+";");
2730 current_node=current_node.getNext(branch);
2733 if (!visited.contains(current_node.getNext(1)))
2734 tovisit.add(current_node.getNext(1));
2735 if (visited.contains(current_node.getNext(0))) {
2736 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2739 current_node=current_node.getNext(0);
2743 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2744 if (!visited.contains(current_node.getNext(1)))
2745 tovisit.add(current_node.getNext(1));
2746 if (visited.contains(current_node.getNext(0))) {
2747 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2750 current_node=current_node.getNext(0);
2752 } else throw new Error();
2756 protected void handleArrayDeref(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output, boolean firstpass) {
2757 if (fn.kind()==FKind.FlatSetElementNode) {
2758 FlatSetElementNode fsen=(FlatSetElementNode) fn;
2759 String dst=generateTemp(fm, fsen.getDst(), lb);
2760 String src=generateTemp(fm, fsen.getSrc(), lb);
2761 String index=generateTemp(fm, fsen.getIndex(), lb);
2762 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
2764 if (elementtype.isArray()||elementtype.isClass())
2767 type=elementtype.getSafeSymbol()+" ";
2769 output.println("STOREARRAY("+dst+","+index+","+type+")");
2771 output.println("{");
2772 output.println(" struct ArrayObject *array;");
2773 output.println(" int index;");
2774 output.println(" RESTOREARRAY(array,index);");
2775 output.println(" (("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index]="+src+";");
2776 output.println("}");
2778 } else if (fn.kind()==FKind.FlatElementNode) {
2779 FlatElementNode fen=(FlatElementNode) fn;
2780 String src=generateTemp(fm, fen.getSrc(), lb);
2781 String index=generateTemp(fm, fen.getIndex(), lb);
2782 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
2783 String dst=generateTemp(fm, fen.getDst(), lb);
2785 if (elementtype.isArray()||elementtype.isClass())
2788 type=elementtype.getSafeSymbol()+" ";
2790 output.println("STOREARRAY("+src+","+index+","+type+")");
2792 output.println("{");
2793 output.println(" struct ArrayObject *array;");
2794 output.println(" int index;");
2795 output.println(" RESTOREARRAY(array,index);");
2796 output.println(" "+dst+"=(("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index];");
2797 output.println("}");
2801 /** Special label assignment for delaycomputation */
2802 protected Hashtable<FlatNode, Integer> dcassignLabels(FlatNode first, Set<FlatNode> lastset) {
2803 HashSet tovisit=new HashSet();
2804 HashSet visited=new HashSet();
2806 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2808 //Label targets of branches
2809 Set<FlatNode> targets=branchanalysis.getTargets();
2810 for(Iterator<FlatNode> it=targets.iterator();it.hasNext();) {
2811 nodetolabel.put(it.next(), new Integer(labelindex++));
2816 /*Assign labels first. A node needs a label if the previous
2817 * node has two exits or this node is a join point. */
2819 while(!tovisit.isEmpty()) {
2820 FlatNode fn=(FlatNode)tovisit.iterator().next();
2825 if(lastset!=null&&lastset.contains(fn)) {
2826 // if last is not null and matches, don't go
2827 // any further for assigning labels
2831 for(int i=0; i<fn.numNext(); i++) {
2832 FlatNode nn=fn.getNext(i);
2835 //1) Edge >1 of node
2836 nodetolabel.put(nn,new Integer(labelindex++));
2838 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2842 nodetolabel.put(nn,new Integer(labelindex++));
2850 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first) {
2851 return assignLabels(first, null);
2854 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
2855 HashSet tovisit=new HashSet();
2856 HashSet visited=new HashSet();
2858 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2861 /*Assign labels first. A node needs a label if the previous
2862 * node has two exits or this node is a join point. */
2864 while(!tovisit.isEmpty()) {
2865 FlatNode fn=(FlatNode)tovisit.iterator().next();
2870 if(lastset!=null&&lastset.contains(fn)) {
2871 // if last is not null and matches, don't go
2872 // any further for assigning labels
2876 for(int i=0; i<fn.numNext(); i++) {
2877 FlatNode nn=fn.getNext(i);
2880 //1) Edge >1 of node
2881 nodetolabel.put(nn,new Integer(labelindex++));
2883 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2887 nodetolabel.put(nn,new Integer(labelindex++));
2895 /** Generate text string that corresponds to the TempDescriptor td. */
2896 protected String generateTemp(FlatMethod fm, TempDescriptor td, LocalityBinding lb) {
2897 MethodDescriptor md=fm.getMethod();
2898 TaskDescriptor task=fm.getTask();
2899 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
2901 if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
2902 return td.getSafeSymbol();
2905 if (objecttemps.isLocalPtr(td)) {
2906 return localsprefixderef+td.getSafeSymbol();
2909 if (objecttemps.isParamPtr(td)) {
2910 return paramsprefix+"->"+td.getSafeSymbol();
2916 protected void generateFlatNode(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output) {
2918 // insert pre-node actions from the code plan
2919 if( state.MLP|| state.OOOJAVA ) {
2923 cp = mlpa.getCodePlan( fn );
2925 cp = oooa.getCodePlan(fn);
2930 FlatSESEEnterNode currentSESE = cp.getCurrentSESE();
2932 // for each sese and age pair that this parent statement
2933 // must stall on, take that child's stall semaphore, the
2934 // copying of values comes after the statement
2935 Iterator<VariableSourceToken> vstItr = cp.getStallTokens().iterator();
2936 while( vstItr.hasNext() ) {
2937 VariableSourceToken vst = vstItr.next();
2939 SESEandAgePair pair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2941 output.println(" {");
2942 output.println(" "+pair.getSESE().getSESErecordName()+"* child = ("+
2943 pair.getSESE().getSESErecordName()+"*) "+pair+";");
2945 output.println(" SESEcommon* childCom = (SESEcommon*) "+pair+";");
2947 if( state.COREPROF ) {
2948 output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
2949 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_BEGIN );");
2950 output.println("#endif");
2953 output.println(" pthread_mutex_lock( &(childCom->lock) );");
2954 output.println(" if( childCom->doneExecuting == FALSE ) {");
2955 output.println(" psem_reset( &runningSESEstallSem );");
2956 output.println(" childCom->parentsStallSem = &runningSESEstallSem;");
2957 output.println(" pthread_mutex_unlock( &(childCom->lock) );");
2958 output.println(" psem_take( &runningSESEstallSem, (struct garbagelist *)&___locals___ );");
2959 output.println(" } else {");
2960 output.println(" pthread_mutex_unlock( &(childCom->lock) );");
2961 output.println(" }");
2963 // copy things we might have stalled for
2964 Iterator<TempDescriptor> tdItr = cp.getCopySet( vst ).iterator();
2965 while( tdItr.hasNext() ) {
2966 TempDescriptor td = tdItr.next();
2967 FlatMethod fmContext;
2968 if( currentSESE.getIsCallerSESEplaceholder() ) {
2969 fmContext = currentSESE.getfmEnclosing();
2971 fmContext = currentSESE.getfmBogus();
2973 output.println(" "+generateTemp( fmContext, td, null )+
2974 " = child->"+vst.getAddrVar().getSafeSymbol()+";");
2977 if( state.COREPROF ) {
2978 output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
2979 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_END );");
2980 output.println("#endif");
2983 output.println(" }");
2986 // for each variable with a dynamic source, stall just for that variable
2987 Iterator<TempDescriptor> dynItr = cp.getDynamicStallSet().iterator();
2988 while( dynItr.hasNext() ) {
2989 TempDescriptor dynVar = dynItr.next();
2991 // only stall if the dynamic source is not yourself, denoted by src==NULL
2992 // otherwise the dynamic write nodes will have the local var up-to-date
2993 output.println(" {");
2994 output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
2996 output.println(" SESEcommon* childCom = (SESEcommon*) "+dynVar+"_srcSESE;");
2998 if( state.COREPROF ) {
2999 output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
3000 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_BEGIN );");
3001 output.println("#endif");
3004 output.println(" pthread_mutex_lock( &(childCom->lock) );");
3005 output.println(" if( childCom->doneExecuting == FALSE ) {");
3006 output.println(" psem_reset( &runningSESEstallSem );");
3007 output.println(" childCom->parentsStallSem = &runningSESEstallSem;");
3008 output.println(" pthread_mutex_unlock( &(childCom->lock) );");
3009 output.println(" psem_take( &runningSESEstallSem, (struct garbagelist *)&___locals___ );");
3010 output.println(" } else {");
3011 output.println(" pthread_mutex_unlock( &(childCom->lock) );");
3012 output.println(" }");
3014 FlatMethod fmContext;
3015 if( currentSESE.getIsCallerSESEplaceholder() ) {
3016 fmContext = currentSESE.getfmEnclosing();
3018 fmContext = currentSESE.getfmBogus();
3021 TypeDescriptor type = dynVar.getType();
3023 if( type.isNull() ) {
3025 } else if( type.isClass() || type.isArray() ) {
3026 typeStr = "struct "+type.getSafeSymbol()+"*";
3028 typeStr = type.getSafeSymbol();
3031 output.println(" "+generateTemp( fmContext, dynVar, null )+
3032 " = *(("+typeStr+"*) ((void*)"+
3033 dynVar+"_srcSESE + "+dynVar+"_srcOffset));");
3035 if( state.COREPROF ) {
3036 output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
3037 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_END );");
3038 output.println("#endif");
3041 output.println(" }");
3042 output.println(" }");
3045 // for each assignment of a variable to rhs that has a dynamic source,
3046 // copy the dynamic sources
3047 Iterator dynAssignItr = cp.getDynAssigns().entrySet().iterator();
3048 while( dynAssignItr.hasNext() ) {
3049 Map.Entry me = (Map.Entry) dynAssignItr.next();
3050 TempDescriptor lhs = (TempDescriptor) me.getKey();
3051 TempDescriptor rhs = (TempDescriptor) me.getValue();
3053 output.println(" {");
3054 output.println(" SESEcommon* oldSrc = "+lhs+"_srcSESE;");
3056 output.println(" "+lhs+"_srcSESE = "+rhs+"_srcSESE;");
3057 output.println(" "+lhs+"_srcOffset = "+rhs+"_srcOffset;");
3059 // no matter what we did above, track reference count of whatever
3060 // this variable pointed to, do release last in case we're just
3061 // copying the same value in because 1->2->1 is safe but ref count
3062 // 1->0->1 has a window where it looks like it should be free'd
3063 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
3064 output.println(" if( "+rhs+"_srcSESE != NULL ) {");
3065 output.println(" ADD_REFERENCE_TO( "+rhs+"_srcSESE );");
3066 output.println(" }");
3067 output.println(" if( oldSrc != NULL ) {");
3068 output.println(" RELEASE_REFERENCE_TO( oldSrc );");
3069 output.println(" }");
3070 output.println(" }");
3071 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
3074 // for each lhs that is dynamic from a non-dynamic source, set the
3075 // dynamic source vars to the current SESE
3076 dynItr = cp.getDynAssignCurr().iterator();
3077 while( dynItr.hasNext() ) {
3078 TempDescriptor dynVar = dynItr.next();
3079 assert currentSESE.getDynamicVarSet().contains( dynVar );
3081 // first release a reference to current record
3082 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
3083 output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
3084 output.println(" RELEASE_REFERENCE_TO( oldSrc );");
3085 output.println(" }");
3086 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
3088 output.println(" "+dynVar+"_srcSESE = NULL;");
3092 // handling stall site
3093 if (state.OOOJAVA) {
3094 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(currentSESE);
3096 Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
3097 Set<Analysis.OoOJava.WaitingElement> waitingElementSet =
3098 graph.getStallSiteWaitingElementSet(fn, seseLockSet);
3100 if(waitingElementSet.size()>0){
3101 output.println("// stall on parent's stall sites ");
3102 output.println(" {");
3103 output.println(" REntry* rentry;");
3105 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
3106 Analysis.OoOJava.WaitingElement waitingElement = (Analysis.OoOJava.WaitingElement) iterator.next();
3107 if( waitingElement.getStatus() >= ConflictNode.COARSE ){
3108 output.println(" rentry=mlpCreateREntry("+ waitingElement.getStatus()+ ", runningSESE);");
3110 output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", runningSESE, (void*)&" +generateTemp(fm,waitingElement.getTempDesc(),lb)+ ");");
3112 output.println(" psem_init( &(rentry->parentStallSem) );");
3113 output.println(" rentry->queue=runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
3114 output.println(" if(ADDRENTRY(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()
3115 + "],rentry)==NOTREADY){");
3116 if( state.COREPROF ) {
3117 output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3118 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_BEGIN );");
3119 output.println("#endif");
3121 output.println(" psem_take( &(rentry->parentStallSem), (struct garbagelist *)&___locals___ );");
3122 if( state.COREPROF ) {
3123 output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3124 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_END );");
3125 output.println("#endif");
3127 output.println(" } ");
3130 output.println(" "+rcr.getTraverserInvocation(waitingElement.getTempDesc(),
3131 generateTemp(fm, waitingElement.getTempDesc(), null), fn));
3134 output.println(" }");
3138 ParentChildConflictsMap conflictsMap = mlpa.getConflictsResults().get(fn);
3139 if (conflictsMap != null) {
3140 Set<Long> allocSet = conflictsMap.getAllocationSiteIDSetofStallSite();
3141 if (allocSet.size() > 0) {
3142 FlatNode enclosingFlatNode=null;
3143 if( currentSESE.getIsCallerSESEplaceholder() && currentSESE.getParent()==null){
3144 enclosingFlatNode=currentSESE.getfmEnclosing();
3146 enclosingFlatNode=currentSESE;
3148 ConflictGraph graph=mlpa.getConflictGraphResults().get(enclosingFlatNode);
3149 HashSet<SESELock> seseLockSet=mlpa.getConflictGraphLockMap().get(graph);
3150 Set<WaitingElement> waitingElementSet=graph.getStallSiteWaitingElementSet(conflictsMap, seseLockSet);
3152 if(waitingElementSet.size()>0){
3153 output.println("// stall on parent's stall sites ");
3154 output.println(" {");
3155 output.println(" REntry* rentry;");
3157 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
3158 WaitingElement waitingElement = (WaitingElement) iterator.next();
3160 if( waitingElement.getStatus() >= ConflictNode.COARSE ){
3161 // HERE! a parent might conflict with a child
3162 output.println(" rentry=mlpCreateREntry("+ waitingElement.getStatus()+ ", runningSESE);");
3164 output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", runningSESE, (void*)&___locals___."+ waitingElement.getDynID() + ");");
3166 output.println(" psem_init( &(rentry->parentStallSem) );");
3167 output.println(" rentry->queue=runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
3169 .println(" if(ADDRENTRY(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()
3170 + "],rentry)==NOTREADY){");
3171 if( state.COREPROF ) {
3172 output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3173 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_BEGIN );");
3174 output.println("#endif");
3176 output.println(" psem_take( &(rentry->parentStallSem), (struct garbagelist *)&___locals___ );");
3177 if( state.COREPROF ) {
3178 output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3179 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_END );");
3180 output.println("#endif");
3182 output.println(" } ");
3184 output.println(" }");
3193 case FKind.FlatAtomicEnterNode:
3194 generateFlatAtomicEnterNode(fm, lb, (FlatAtomicEnterNode) fn, output);
3197 case FKind.FlatAtomicExitNode:
3198 generateFlatAtomicExitNode(fm, lb, (FlatAtomicExitNode) fn, output);
3201 case FKind.FlatInstanceOfNode:
3202 generateFlatInstanceOfNode(fm, lb, (FlatInstanceOfNode)fn, output);
3205 case FKind.FlatSESEEnterNode:
3206 generateFlatSESEEnterNode(fm, lb, (FlatSESEEnterNode)fn, output);
3209 case FKind.FlatSESEExitNode:
3210 generateFlatSESEExitNode(fm, lb, (FlatSESEExitNode)fn, output);
3213 case FKind.FlatWriteDynamicVarNode:
3214 generateFlatWriteDynamicVarNode(fm, lb, (FlatWriteDynamicVarNode)fn, output);
3217 case FKind.FlatGlobalConvNode:
3218 generateFlatGlobalConvNode(fm, lb, (FlatGlobalConvNode) fn, output);
3221 case FKind.FlatTagDeclaration:
3222 generateFlatTagDeclaration(fm, lb, (FlatTagDeclaration) fn,output);
3225 case FKind.FlatCall:
3226 generateFlatCall(fm, lb, (FlatCall) fn,output);
3229 case FKind.FlatFieldNode:
3230 generateFlatFieldNode(fm, lb, (FlatFieldNode) fn,output);
3233 case FKind.FlatElementNode:
3234 generateFlatElementNode(fm, lb, (FlatElementNode) fn,output);
3237 case FKind.FlatSetElementNode:
3238 generateFlatSetElementNode(fm, lb, (FlatSetElementNode) fn,output);
3241 case FKind.FlatSetFieldNode:
3242 generateFlatSetFieldNode(fm, lb, (FlatSetFieldNode) fn,output);
3246 generateFlatNew(fm, lb, (FlatNew) fn,output);
3249 case FKind.FlatOpNode:
3250 generateFlatOpNode(fm, lb, (FlatOpNode) fn,output);
3253 case FKind.FlatCastNode:
3254 generateFlatCastNode(fm, lb, (FlatCastNode) fn,output);
3257 case FKind.FlatLiteralNode:
3258 generateFlatLiteralNode(fm, lb, (FlatLiteralNode) fn,output);
3261 case FKind.FlatReturnNode:
3262 generateFlatReturnNode(fm, lb, (FlatReturnNode) fn,output);
3266 output.println("/* nop */");
3269 case FKind.FlatGenReachNode:
3270 // this node is just for generating a reach graph
3271 // in disjointness analysis at a particular program point
3274 case FKind.FlatExit:
3275 output.println("/* exit */");
3278 case FKind.FlatBackEdge:
3279 if (state.SINGLETM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
3280 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
3282 if(state.DSM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
3283 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
3285 if (((state.MLP|| state.OOOJAVA||state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
3286 || (this.state.MULTICOREGC)) {
3287 if(state.DSM&&locality.getAtomic(lb).get(fn).intValue()>0) {
3288 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
3289 } else if(this.state.MULTICOREGC) {
3290 output.println("if (gcflag) gc("+localsprefixaddr+");");
3292 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3295 output.println("/* nop */");
3298 case FKind.FlatCheckNode:
3299 generateFlatCheckNode(fm, lb, (FlatCheckNode) fn, output);
3302 case FKind.FlatFlagActionNode:
3303 generateFlatFlagActionNode(fm, lb, (FlatFlagActionNode) fn, output);
3306 case FKind.FlatPrefetchNode:
3307 generateFlatPrefetchNode(fm,lb, (FlatPrefetchNode) fn, output);
3310 case FKind.FlatOffsetNode:
3311 generateFlatOffsetNode(fm, lb, (FlatOffsetNode)fn, output);
3318 // insert post-node actions from the code-plan
3321 CodePlan cp = mlpa.getCodePlan( fn );
3329 public void generateFlatOffsetNode(FlatMethod fm, LocalityBinding lb, FlatOffsetNode fofn, PrintWriter output) {
3330 output.println("/* FlatOffsetNode */");
3331 FieldDescriptor fd=fofn.getField();
3332 output.println(generateTemp(fm, fofn.getDst(),lb)+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+ fd.getSafeSymbol()+");");
3333 output.println("/* offset */");
3336 public void generateFlatPrefetchNode(FlatMethod fm, LocalityBinding lb, FlatPrefetchNode fpn, PrintWriter output) {
3337 if (state.PREFETCH) {
3338 Vector oids = new Vector();
3339 Vector fieldoffset = new Vector();
3340 Vector endoffset = new Vector();
3341 int tuplecount = 0; //Keeps track of number of prefetch tuples that need to be generated
3342 for(Iterator it = fpn.hspp.iterator(); it.hasNext();) {
3343 PrefetchPair pp = (PrefetchPair) it.next();
3344 Integer statusbase = locality.getNodePreTempInfo(lb,fpn).get(pp.base);
3345 /* Find prefetches that can generate oid */
3346 if(statusbase == LocalityAnalysis.GLOBAL) {
3347 generateTransCode(fm, lb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(lb).get(fpn).intValue()>0, false);
3349 } else if (statusbase == LocalityAnalysis.LOCAL) {
3350 generateTransCode(fm,lb,pp,oids,fieldoffset,endoffset,tuplecount,false,true);
3357 System.out.println("Adding prefetch "+fpn+ " to method:" +fm);
3358 output.println("{");
3359 output.println("/* prefetch */");
3360 output.println("/* prefetchid_" + fpn.siteid + " */");
3361 output.println("void * prefptr;");
3362 output.println("int tmpindex;");
3364 output.println("if((evalPrefetch["+fpn.siteid+"].operMode) || (evalPrefetch["+fpn.siteid+"].retrycount <= 0)) {");
3365 /*Create C code for oid array */
3366 output.print(" unsigned int oidarray_[] = {");
3367 boolean needcomma=false;
3368 for (Iterator it = oids.iterator(); it.hasNext();) {
3371 output.print(it.next());
3374 output.println("};");
3376 /*Create C code for endoffset values */
3377 output.print(" unsigned short endoffsetarry_[] = {");
3379 for (Iterator it = endoffset.iterator(); it.hasNext();) {
3382 output.print(it.next());
3385 output.println("};");
3387 /*Create C code for Field Offset Values */
3388 output.print(" short fieldarry_[] = {");
3390 for (Iterator it = fieldoffset.iterator(); it.hasNext();) {
3393 output.print(it.next());
3396 output.println("};");
3397 /* make the prefetch call to Runtime */
3398 output.println(" if(!evalPrefetch["+fpn.siteid+"].operMode) {");
3399 output.println(" evalPrefetch["+fpn.siteid+"].retrycount = RETRYINTERVAL;");
3400 output.println(" }");
3401 output.println(" prefetch("+fpn.siteid+" ,"+tuplecount+", oidarray_, endoffsetarry_, fieldarry_);");
3402 output.println(" } else {");
3403 output.println(" evalPrefetch["+fpn.siteid+"].retrycount--;");
3404 output.println(" }");
3405 output.println("}");
3409 public void generateTransCode(FlatMethod fm, LocalityBinding lb,PrefetchPair pp, Vector oids, Vector fieldoffset, Vector endoffset, int tuplecount, boolean inside, boolean localbase) {
3410 short offsetcount = 0;
3414 } else if (localbase) {
3415 for(; breakindex<pp.desc.size(); breakindex++) {
3416 Descriptor desc=pp.getDescAt(breakindex);
3417 if (desc instanceof FieldDescriptor) {
3418 FieldDescriptor fd=(FieldDescriptor)desc;
3419 if (fd.isGlobal()) {
3427 if (breakindex>pp.desc.size()) //all local
3430 TypeDescriptor lasttype=pp.base.getType();
3431 String basestr=generateTemp(fm, pp.base, lb);
3433 boolean maybenull=fm.getMethod().isStatic()||
3434 !pp.base.equals(fm.getParameter(0));
3436 for(int i=0; i<breakindex; i++) {
3437 String indexcheck="";
3439 Descriptor desc=pp.getDescAt(i);
3440 if (desc instanceof FieldDescriptor) {
3441 FieldDescriptor fd=(FieldDescriptor)desc;
3443 if (!teststr.equals(""))
3445 teststr+="((prefptr="+basestr+")!=NULL)";
3446 basestr="((struct "+lasttype.getSafeSymbol()+" *)prefptr)->"+fd.getSafeSymbol();
3448 basestr=basestr+"->"+fd.getSafeSymbol();
3451 lasttype=fd.getType();
3453 IndexDescriptor id=(IndexDescriptor)desc;
3454 indexcheck="((tmpindex=";
3455 for(int j=0; j<id.tddesc.size(); j++) {
3456 indexcheck+=generateTemp(fm, id.getTempDescAt(j), lb)+"+";
3458 indexcheck+=id.offset+")>=0)&(tmpindex<((struct ArrayObject *)prefptr)->___length___)";
3460 if (!teststr.equals(""))
3462 teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck;
3463 basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]";
3465 lasttype=lasttype.dereference();
3470 if (teststr.equals("")) {
3471 oid="((unsigned int)"+basestr+")";
3473 oid="((unsigned int)(("+teststr+")?"+basestr+":NULL))";
3477 for(int i = breakindex; i < pp.desc.size(); i++) {
3478 String newfieldoffset;
3479 Object desc = pp.getDescAt(i);
3480 if(desc instanceof FieldDescriptor) {
3481 FieldDescriptor fd=(FieldDescriptor)desc;
3482 newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))");
3483 lasttype=fd.getType();
3485 newfieldoffset = "";
3486 IndexDescriptor id=(IndexDescriptor)desc;
3487 for(int j = 0; j < id.tddesc.size(); j++) {
3488 newfieldoffset += generateTemp(fm, id.getTempDescAt(j), lb) + "+";
3490 newfieldoffset += id.offset.toString();
3491 lasttype=lasttype.dereference();
3493 fieldoffset.add(newfieldoffset);
3496 int base=(tuplecount>0) ? ((Short)endoffset.get(tuplecount-1)).intValue() : 0;
3497 base+=pp.desc.size()-breakindex;
3498 endoffset.add(new Short((short)base));
3503 public void generateFlatGlobalConvNode(FlatMethod fm, LocalityBinding lb, FlatGlobalConvNode fgcn, PrintWriter output) {
3504 if (lb!=fgcn.getLocality())
3506 /* Have to generate flat globalconv */
3507 if (fgcn.getMakePtr()) {
3509 //DEBUG: output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+",\" "+fm+":"+fgcn+"\");");
3510 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3512 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fgcn)||state.READSET&&dc.getNeedWriteTrans(lb, fgcn)) {
3513 //need to do translation
3514 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+", (void *)("+localsprefixaddr+"));");
3515 } else if (state.READSET&&dc.getNeedTrans(lb, fgcn)) {
3516 if (state.HYBRID&&delaycomp.getConv(lb).contains(fgcn)) {
3517 output.println("TRANSREADRDFISSION("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3519 output.println("TRANSREADRD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3523 /* Need to convert to OID */
3524 if ((dc==null)||dc.getNeedSrcTrans(lb,fgcn)) {
3525 if (fgcn.doConvert()||(delaycomp!=null&&delaycomp.needsFission(lb, fgcn.getAtomicEnter())&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) {
3526 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc(),lb)+");");
3528 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=NULL;");
3534 public void generateFlatInstanceOfNode(FlatMethod fm, LocalityBinding lb, FlatInstanceOfNode fion, PrintWriter output) {
3536 if (fion.getType().isArray()) {
3537 type=state.getArrayNumber(fion.getType())+state.numClasses();
3539 type=fion.getType().getClassDesc().getId();
3542 if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
3543 output.println(generateTemp(fm, fion.getDst(), lb)+"=1;");
3545 output.println(generateTemp(fm, fion.getDst(), lb)+"=instanceof("+generateTemp(fm,fion.getSrc(),lb)+","+type+");");
3548 int sandboxcounter=0;
3549 public void generateFlatAtomicEnterNode(FlatMethod fm, LocalityBinding lb, FlatAtomicEnterNode faen, PrintWriter output) {
3550 /* Check to see if we need to generate code for this atomic */
3551 if (locality==null) {
3552 if (GENERATEPRECISEGC) {
3553 output.println("if (pthread_mutex_trylock(&atomiclock)!=0) {");
3554 output.println("stopforgc((struct garbagelist *) &___locals___);");
3555 output.println("pthread_mutex_lock(&atomiclock);");
3556 output.println("restartaftergc();");
3557 output.println("}");
3559 output.println("pthread_mutex_lock(&atomiclock);");
3564 if (locality.getAtomic(lb).get(faen.getPrev(0)).intValue()>0)
3568 if (state.SANDBOX) {
3569 outsandbox.println("int atomiccounter"+sandboxcounter+"=LOW_CHECK_FREQUENCY;");
3570 output.println("counter_reset_pointer=&atomiccounter"+sandboxcounter+";");
3573 if (state.DELAYCOMP&&delaycomp.needsFission(lb, faen)) {
3574 AtomicRecord ar=atomicmethodmap.get(faen);
3576 for(Iterator<TempDescriptor> tmpit=ar.livein.iterator();tmpit.hasNext();) {
3577 TempDescriptor tmp=tmpit.next();
3578 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3581 //copy outs that depend on path
3582 for(Iterator<TempDescriptor> tmpit=ar.liveoutvirtualread.iterator();tmpit.hasNext();) {
3583 TempDescriptor tmp=tmpit.next();
3584 if (!ar.livein.contains(tmp))
3585 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3589 /* Backup the temps. */
3590 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3591 TempDescriptor tmp=tmpit.next();
3592 output.println(generateTemp(fm, backuptable.get(lb).get(tmp),lb)+"="+generateTemp(fm,tmp,lb)+";");
3595 output.println("goto transstart"+faen.getIdentifier()+";");
3597 /******* Print code to retry aborted transaction *******/
3598 output.println("transretry"+faen.getIdentifier()+":");
3601 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3602 TempDescriptor tmp=tmpit.next();
3603 output.println(generateTemp(fm, tmp,lb)+"="+generateTemp(fm,backuptable.get(lb).get(tmp),lb)+";");
3607 /********* Need to revert local object store ********/
3608 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3610 output.println("while ("+revertptr+") {");
3611 output.println("struct ___Object___ * tmpptr;");
3612 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3613 output.println("REVERT_OBJ("+revertptr+");");
3614 output.println(revertptr+"=tmpptr;");
3615 output.println("}");
3617 /******* Tell the runtime to start the transaction *******/
3619 output.println("transstart"+faen.getIdentifier()+":");
3620 if (state.SANDBOX) {
3621 output.println("transaction_check_counter=*counter_reset_pointer;");
3624 output.println("transStart();");
3626 if (state.ABORTREADERS||state.SANDBOX) {
3628 output.println("abortenabled=1;");
3629 output.println("if (_setjmp(aborttrans)) {");
3630 output.println(" goto transretry"+faen.getIdentifier()+"; }");
3634 public void generateFlatAtomicExitNode(FlatMethod fm, LocalityBinding lb, FlatAtomicExitNode faen, PrintWriter output) {
3635 /* Check to see if we need to generate code for this atomic */
3636 if (locality==null) {
3637 output.println("pthread_mutex_unlock(&atomiclock);");
3640 if (locality.getAtomic(lb).get(faen).intValue()>0)
3642 //store the revert list before we lose the transaction object
3645 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3646 output.println(revertptr+"=revertlist;");
3647 output.println("if (transCommit()) {");
3648 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3649 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3650 output.println("} else {");
3651 /* Need to commit local object store */
3652 output.println("while ("+revertptr+") {");
3653 output.println("struct ___Object___ * tmpptr;");
3654 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3655 output.println("COMMIT_OBJ("+revertptr+");");
3656 output.println(revertptr+"=tmpptr;");
3657 output.println("}");
3658 output.println("}");
3662 if (!state.DELAYCOMP) {
3664 output.println("if (transCommit()) {");
3665 /* Transaction aborts if it returns true */
3666 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3667 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3668 output.println("}");
3670 if (delaycomp.optimizeTrans(lb, faen.getAtomicEnter())&&(!state.STMARRAY||state.DUALVIEW)) {
3671 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3672 output.println("LIGHTWEIGHTCOMMIT("+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+", transretry"+faen.getAtomicEnter().getIdentifier()+");");
3674 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3675 TempDescriptor tmp=tmpit.next();
3676 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3678 } else if (delaycomp.needsFission(lb, faen.getAtomicEnter())) {
3679 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3681 output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {");
3682 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3683 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3684 output.println("}");
3686 output.println("else {");
3687 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3688 TempDescriptor tmp=tmpit.next();
3689 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3691 output.println("}");
3693 output.println("if (transCommit(NULL, NULL, NULL, NULL)) {");
3694 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3695 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3696 output.println("}");
3701 public void generateFlatSESEEnterNode( FlatMethod fm,
3703 FlatSESEEnterNode fsen,
3704 PrintWriter output) {
3705 // if MLP flag is off, okay that SESE nodes are in IR graph,
3706 // just skip over them and code generates exactly the same
3707 if( !(state.MLP || state.OOOJAVA) ) {
3710 // there may be an SESE in an unreachable method, skip over
3711 if( (state.MLP && !mlpa.getAllSESEs().contains( fsen )) ||
3712 (state.OOOJAVA && !oooa.getAllSESEs().contains(fsen))
3717 // also, if we have encountered a placeholder, just skip it
3718 if( fsen.getIsCallerSESEplaceholder() ) {
3722 output.println(" {");
3724 if( state.COREPROF ) {
3725 output.println("#ifdef CP_EVENTID_TASKDISPATCH");
3726 output.println(" CP_LOGEVENT( CP_EVENTID_TASKDISPATCH, CP_EVENTTYPE_BEGIN );");
3727 output.println("#endif");
3731 // before doing anything, lock your own record and increment the running children
3732 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3733 (state.OOOJAVA && fsen != oooa.getMainSESE())
3735 output.println(" atomic_inc(&(runningSESE->numRunningChildren));");
3738 // allocate the space for this record
3739 output.println( "#ifndef OOO_DISABLE_TASKMEMPOOL" );
3741 output.println( "#ifdef CP_EVENTID_POOLALLOC");
3742 output.println( " CP_LOGEVENT( CP_EVENTID_POOLALLOC, CP_EVENTTYPE_BEGIN );");
3743 output.println( "#endif");
3744 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3745 (state.OOOJAVA && fsen != oooa.getMainSESE())
3748 fsen.getSESErecordName()+"* seseToIssue = ("+
3749 fsen.getSESErecordName()+"*) poolalloc( runningSESE->taskRecordMemPool );");
3752 fsen.getSESErecordName()+"* seseToIssue = ("+
3753 fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
3754 fsen.getSESErecordName()+" ) );");
3756 output.println( "#ifdef CP_EVENTID_POOLALLOC");
3757 output.println( " CP_LOGEVENT( CP_EVENTID_POOLALLOC, CP_EVENTTYPE_END );");
3758 output.println( "#endif");
3760 output.println( "#else // OOO_DISABLE_TASKMEMPOOL" );
3762 fsen.getSESErecordName()+"* seseToIssue = ("+
3763 fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
3764 fsen.getSESErecordName()+" ) );");
3765 output.println( "#endif // OOO_DISABLE_TASKMEMPOOL" );
3768 // set up the SESE in-set and out-set objects, which look
3769 // like a garbage list
3770 output.println(" struct garbagelist * gl= (struct garbagelist *)&(((SESEcommon*)(seseToIssue))[1]);");
3771 output.println(" gl->size="+calculateSizeOfSESEParamList(fsen)+";");
3772 output.println(" gl->next = NULL;");
3774 // there are pointers to SESE records the newly-issued SESE
3775 // will use to get values it depends on them for--how many
3776 // are there, and what is the offset from the total SESE
3777 // record to the first dependent record pointer?
3778 output.println(" seseToIssue->common.numDependentSESErecords="+
3779 fsen.getNumDepRecs()+";");
3781 // we only need this (and it will only compile) when the number of dependent
3782 // SESE records is non-zero
3783 if( fsen.getFirstDepRecField() != null ) {
3784 output.println(" seseToIssue->common.offsetToDepSESErecords=(INTPTR)sizeof("+
3785 fsen.getSESErecordName()+") - (INTPTR)&((("+
3786 fsen.getSESErecordName()+"*)0)->"+fsen.getFirstDepRecField()+");"
3790 if (state.RCR&&fsen.getInVarsForDynamicCoarseConflictResolution().size()>0) {
3791 output.println(" seseToIssue->common.offsetToParamRecords=(INTPTR)sizeof("+fsen.getSESErecordName()+") - (INTPTR) & ((("+fsen.getSESErecordName()+"*)0)->rcrRecords);");
3794 // fill in common data
3795 output.println(" int localCount=0;");
3796 output.println(" seseToIssue->common.classID = "+fsen.getIdentifier()+";");
3797 output.println(" seseToIssue->common.parentsStallSem = NULL;");
3798 output.println(" seseToIssue->common.forwardList = createQueue();");
3799 output.println(" seseToIssue->common.unresolvedDependencies = 10000;");
3800 output.println(" seseToIssue->common.doneExecuting = FALSE;");
3801 output.println(" pthread_cond_init( &(seseToIssue->common.runningChildrenCond), NULL );");
3802 output.println(" seseToIssue->common.numRunningChildren = 0;");
3803 output.println(" seseToIssue->common.parent = runningSESE;");
3804 // start with refCount = 2, one being the count that the child itself
3805 // will decrement when it retires, to say it is done using its own
3806 // record, and the other count is for the parent that will remember
3807 // the static name of this new child below
3808 output.println(" seseToIssue->common.refCount = 2;");
3810 // all READY in-vars should be copied now and be done with it
3811 Iterator<TempDescriptor> tempItr = fsen.getReadyInVarSet().iterator();
3812 while( tempItr.hasNext() ) {
3813 TempDescriptor temp = tempItr.next();
3815 // when we are issuing the main SESE or an SESE with placeholder
3816 // caller SESE as parent, generate temp child child's eclosing method,
3817 // otherwise use the parent's enclosing method as the context
3818 boolean useParentContext = false;
3820 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3821 (state.OOOJAVA && fsen != oooa.getMainSESE())
3823 assert fsen.getParent() != null;
3824 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3825 useParentContext = true;
3829 if( useParentContext ) {
3830 output.println(" seseToIssue->"+temp+" = "+
3831 generateTemp( fsen.getParent().getfmBogus(), temp, null )+";");
3833 output.println(" seseToIssue->"+temp+" = "+
3834 generateTemp( fsen.getfmEnclosing(), temp, null )+";");
3838 // before potentially adding this SESE to other forwarding lists,
3840 output.println(" pthread_mutex_init( &(seseToIssue->common.lock), NULL );");
3843 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3844 (state.OOOJAVA && fsen != oooa.getMainSESE())
3846 // count up outstanding dependencies, static first, then dynamic
3847 Iterator<SESEandAgePair> staticSrcsItr = fsen.getStaticInVarSrcs().iterator();
3848 while( staticSrcsItr.hasNext() ) {
3849 SESEandAgePair srcPair = staticSrcsItr.next();
3850 output.println(" {");
3851 output.println(" SESEcommon* src = (SESEcommon*)"+srcPair+";");
3852 output.println(" pthread_mutex_lock( &(src->lock) );");
3854 output.println(" if( !src->doneExecuting ) {");
3855 output.println(" addNewItem( src->forwardList, seseToIssue );");
3856 output.println(" ++(localCount);");
3857 output.println(" }");
3858 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
3859 output.println(" ADD_REFERENCE_TO( src );");
3860 output.println("#endif" );
3861 output.println(" pthread_mutex_unlock( &(src->lock) );");
3862 output.println(" }");
3864 // whether or not it is an outstanding dependency, make sure
3865 // to pass the static name to the child's record
3866 output.println(" seseToIssue->"+srcPair+" = "+
3867 "("+srcPair.getSESE().getSESErecordName()+"*)"+
3871 // dynamic sources might already be accounted for in the static list,
3872 // so only add them to forwarding lists if they're not already there
3873 Iterator<TempDescriptor> dynVarsItr = fsen.getDynamicInVarSet().iterator();
3874 while( dynVarsItr.hasNext() ) {
3875 TempDescriptor dynInVar = dynVarsItr.next();
3876 output.println(" {");
3877 output.println(" SESEcommon* src = (SESEcommon*)"+dynInVar+"_srcSESE;");
3879 // the dynamic source is NULL if it comes from your own space--you can't pass
3880 // the address off to the new child, because you're not done executing and
3881 // might change the variable, so copy it right now
3882 output.println(" if( src != NULL ) {");
3883 output.println(" pthread_mutex_lock( &(src->lock) );");
3887 output.println(" if( isEmpty( src->forwardList ) ||");
3888 output.println(" seseToIssue != peekItem( src->forwardList ) ) {");
3889 output.println(" if( !src->doneExecuting ) {");
3890 output.println(" addNewItem( src->forwardList, seseToIssue );");
3891 output.println(" ++(localCount);");
3892 output.println(" }");
3893 output.println(" }");
3894 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
3895 output.println(" ADD_REFERENCE_TO( src );");
3896 output.println("#endif" );
3897 output.println(" pthread_mutex_unlock( &(src->lock) );");
3898 output.println(" seseToIssue->"+dynInVar+"_srcOffset = "+dynInVar+"_srcOffset;");
3899 output.println(" } else {");
3901 boolean useParentContext = false;
3902 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3903 (state.OOOJAVA && fsen != oooa.getMainSESE())
3905 assert fsen.getParent() != null;
3906 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3907 useParentContext = true;
3910 if( useParentContext ) {
3911 output.println(" seseToIssue->"+dynInVar+" = "+
3912 generateTemp( fsen.getParent().getfmBogus(), dynInVar, null )+";");
3914 output.println(" seseToIssue->"+dynInVar+" = "+
3915 generateTemp( fsen.getfmEnclosing(), dynInVar, null )+";");
3918 output.println(" }");
3919 output.println(" }");
3921 // even if the value is already copied, make sure your NULL source
3922 // gets passed so child knows it already has the dynamic value
3923 output.println(" seseToIssue->"+dynInVar+"_srcSESE = "+dynInVar+"_srcSESE;");
3929 // maintain pointers for finding dynamic SESE
3930 // instances from static names
3931 SESEandAgePair pairNewest = new SESEandAgePair( fsen, 0 );
3932 SESEandAgePair pairOldest = new SESEandAgePair( fsen, fsen.getOldestAgeToTrack() );
3933 if( fsen.getParent() != null &&
3934 fsen.getParent().getNeededStaticNames().contains( pairNewest )
3936 output.println(" {");
3937 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
3938 output.println(" SESEcommon* oldest = "+pairOldest+";");
3939 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
3941 for( int i = fsen.getOldestAgeToTrack(); i > 0; --i ) {
3942 SESEandAgePair pair1 = new SESEandAgePair( fsen, i );
3943 SESEandAgePair pair2 = new SESEandAgePair( fsen, i-1 );
3944 output.println(" "+pair1+" = "+pair2+";");
3946 output.println(" "+pairNewest+" = &(seseToIssue->common);");
3948 // no need to add a reference to whatever is the newest record, because
3949 // we initialized seseToIssue->refCount to *2*
3950 // but release a reference to whatever was the oldest BEFORE the shift
3951 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
3952 output.println(" if( oldest != NULL ) {");
3953 output.println(" RELEASE_REFERENCE_TO( oldest );");
3954 output.println(" }");
3955 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
3956 output.println(" }");
3961 if( state.COREPROF ) {
3962 output.println("#ifdef CP_EVENTID_PREPAREMEMQ");
3963 output.println(" CP_LOGEVENT( CP_EVENTID_PREPAREMEMQ, CP_EVENTTYPE_BEGIN );");
3964 output.println("#endif");
3969 // count up memory conflict dependencies,
3971 dispatchMEMRC(fm, lb, fsen, output);
3972 } else if(state.OOOJAVA){
3973 FlatSESEEnterNode parent = fsen.getParent();
3974 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(parent);
3975 if (graph != null && graph.hasConflictEdge()) {
3976 Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
3978 output.println(" //add memory queue element");
3979 Analysis.OoOJava.SESEWaitingQueue seseWaitingQueue=
3980 graph.getWaitingElementSetBySESEID(fsen.getIdentifier(), seseLockSet);
3981 if(seseWaitingQueue.getWaitingElementSize()>0) {
3982 output.println(" {");
3983 output.println(" REntry* rentry=NULL;");
3984 output.println(" INTPTR* pointer=NULL;");
3985 output.println(" seseToIssue->common.rentryIdx=0;");
3987 Set<Integer> queueIDSet=seseWaitingQueue.getQueueIDSet();
3988 for (Iterator iterator = queueIDSet.iterator(); iterator.hasNext();) {
3989 Integer key = (Integer) iterator.next();
3990 int queueID=key.intValue();
3991 Set<Analysis.OoOJava.WaitingElement> waitingQueueSet =
3992 seseWaitingQueue.getWaitingElementSet(queueID);
3993 int enqueueType=seseWaitingQueue.getType(queueID);
3994 if(enqueueType==SESEWaitingQueue.EXCEPTION) {
3995 output.println(" INITIALIZEBUF(runningSESE->memoryQueueArray[" + queueID+ "]);");
3997 for (Iterator iterator2 = waitingQueueSet.iterator(); iterator2.hasNext();) {
3998 Analysis.OoOJava.WaitingElement waitingElement
3999 = (Analysis.OoOJava.WaitingElement) iterator2.next();
4000 if (waitingElement.getStatus() >= ConflictNode.COARSE) {
4001 output.println(" rentry=mlpCreateREntry("
4002 + waitingElement.getStatus()
4003 + ", &(seseToIssue->common));");
4005 TempDescriptor td = waitingElement.getTempDesc();
4006 // decide whether waiting element is dynamic or static
4007 if (fsen.getDynamicInVarSet().contains(td)) {
4008 // dynamic in-var case
4009 output.println(" pointer=seseToIssue->"
4010 + waitingElement.getDynID()
4011 + "_srcSESE+seseToIssue->"
4012 + waitingElement.getDynID()
4014 output.println(" rentry=mlpCreateFineREntry("
4015 + waitingElement.getStatus()
4016 + ", &(seseToIssue->common), pointer );");
4017 } else if (fsen.getStaticInVarSet().contains(td)) {
4018 // static in-var case
4019 VariableSourceToken vst = fsen.getStaticInVarSrc(td);
4022 String srcId = "SESE_" + vst.getSESE().getPrettyIdentifier()
4023 + vst.getSESE().getIdentifier()
4024 + "_" + vst.getAge();
4025 output.println(" pointer=(void*)&seseToIssue->"
4031 output.println(" rentry=mlpCreateFineREntry("
4032 + waitingElement.getStatus()
4033 + ", &(seseToIssue->common), pointer );");
4036 output.println(" rentry=mlpCreateFineREntry("
4037 + waitingElement.getStatus()
4038 + ", &(seseToIssue->common), (void*)&seseToIssue->"
4039 + waitingElement.getDynID()
4043 output.println(" rentry->queue=runningSESE->memoryQueueArray["
4044 + waitingElement.getQueueID()
4047 if(enqueueType==SESEWaitingQueue.NORMAL){
4048 output.println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
4049 output.println(" if(ADDRENTRY(runningSESE->memoryQueueArray["
4050 + waitingElement.getQueueID()
4051 + "],rentry)==NOTREADY) {");
4052 output.println(" localCount++;");
4053 output.println(" }");
4055 output.println(" ADDRENTRYTOBUF(runningSESE->memoryQueueArray[" + waitingElement.getQueueID() + "],rentry);");
4058 if(enqueueType!=SESEWaitingQueue.NORMAL){
4059 output.println(" localCount+=RESOLVEBUF(runningSESE->memoryQueueArray["
4060 + queueID+ "],&seseToIssue->common);");
4063 output.println(" }");
4068 ConflictGraph graph = null;
4069 FlatSESEEnterNode parent = fsen.getParent();
4070 if (parent != null) {
4071 if (parent.isCallerSESEplaceholder) {
4072 graph = mlpa.getConflictGraphResults().get(parent.getfmEnclosing());
4074 graph = mlpa.getConflictGraphResults().get(parent);
4077 if (graph != null && graph.hasConflictEdge()) {
4078 HashSet<SESELock> seseLockSet = mlpa.getConflictGraphLockMap()
4081 output.println(" //add memory queue element");
4082 SESEWaitingQueue seseWaitingQueue=graph.getWaitingElementSetBySESEID(fsen.getIdentifier(),
4084 if(seseWaitingQueue.getWaitingElementSize()>0){
4085 output.println(" {");
4086 output.println(" REntry* rentry=NULL;");
4087 output.println(" INTPTR* pointer=NULL;");
4088 output.println(" seseToIssue->common.rentryIdx=0;");
4090 Set<Integer> queueIDSet=seseWaitingQueue.getQueueIDSet();
4091 for (Iterator iterator = queueIDSet.iterator(); iterator
4093 Integer key = (Integer) iterator.next();
4094 int queueID=key.intValue();
4095 Set<WaitingElement> waitingQueueSet = seseWaitingQueue.getWaitingElementSet(queueID);
4096 int enqueueType=seseWaitingQueue.getType(queueID);
4097 if(enqueueType==SESEWaitingQueue.EXCEPTION){
4098 output.println(" INITIALIZEBUF(runningSESE->memoryQueueArray["
4101 for (Iterator iterator2 = waitingQueueSet.iterator(); iterator2
4103 WaitingElement waitingElement = (WaitingElement) iterator2
4105 if (waitingElement.getStatus() >= ConflictNode.COARSE) {
4106 output.println(" rentry=mlpCreateREntry("
4107 + waitingElement.getStatus()
4108 + ", &(seseToIssue->common));");
4110 TempDescriptor td = waitingElement
4112 // decide whether waiting element is dynamic or
4114 if (fsen.getDynamicInVarSet().contains(td)) {
4115 // dynamic in-var case
4116 output.println(" pointer=seseToIssue->"
4117 + waitingElement.getDynID()
4118 + "_srcSESE+seseToIssue->"
4119 + waitingElement.getDynID()
4122 .println(" rentry=mlpCreateFineREntry("
4125 + ", &(seseToIssue->common), pointer );");
4126 } else if (fsen.getStaticInVarSet()
4128 // static in-var case
4129 VariableSourceToken vst = fsen
4130 .getStaticInVarSrc(td);
4133 String srcId = "SESE_"
4135 .getPrettyIdentifier()
4136 + vst.getSESE().getIdentifier()
4137 + "_" + vst.getAge();
4139 .println(" pointer=(void*)&seseToIssue->"
4146 .println(" rentry=mlpCreateFineREntry("
4149 + ", &(seseToIssue->common), pointer );");
4154 .println(" rentry=mlpCreateFineREntry("
4157 + ", &(seseToIssue->common), (void*)&seseToIssue->"
4158 + waitingElement.getDynID()
4163 .println(" rentry->queue=runningSESE->memoryQueueArray["
4164 + waitingElement.getQueueID()
4167 if(enqueueType==SESEWaitingQueue.NORMAL){
4169 .println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
4171 .println(" if(ADDRENTRY(runningSESE->memoryQueueArray["
4172 + waitingElement.getQueueID()
4173 + "],rentry)==NOTREADY){");
4174 output.println(" ++(localCount);");
4175 output.println(" } ");
4178 .println(" ADDRENTRYTOBUF(runningSESE->memoryQueueArray["
4179 + waitingElement.getQueueID()
4183 if(enqueueType!=SESEWaitingQueue.NORMAL){
4184 output.println(" localCount+=RESOLVEBUF(runningSESE->memoryQueueArray["
4185 + queueID+ "],&seseToIssue->common);");
4188 output.println(" }");
4195 if( state.COREPROF ) {
4196 output.println("#ifdef CP_EVENTID_PREPAREMEMQ");
4197 output.println(" CP_LOGEVENT( CP_EVENTID_PREPAREMEMQ, CP_EVENTTYPE_END );");
4198 output.println("#endif");
4201 // Enqueue Task Record
4203 output.println(" enqueueTR(TRqueue, (void *)seseToIssue);");
4206 // if there were no outstanding dependencies, issue here
4207 output.println(" if( atomic_sub_and_test(10000-localCount,&(seseToIssue->common.unresolvedDependencies) ) ) {");
4208 output.println(" workScheduleSubmit( (void*)seseToIssue );");
4209 output.println(" }");
4213 if( state.COREPROF ) {
4214 output.println("#ifdef CP_EVENTID_TASKDISPATCH");
4215 output.println(" CP_LOGEVENT( CP_EVENTID_TASKDISPATCH, CP_EVENTTYPE_END );");
4216 output.println("#endif");
4219 output.println(" }");
4223 void dispatchMEMRC(FlatMethod fm, LocalityBinding lb, FlatSESEEnterNode fsen, PrintWriter output) {
4224 FlatSESEEnterNode parent = fsen.getParent();
4225 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(parent);
4226 if (graph != null && graph.hasConflictEdge()) {
4227 Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
4228 Analysis.OoOJava.SESEWaitingQueue seseWaitingQueue=graph.getWaitingElementSetBySESEID(fsen.getIdentifier(), seseLockSet);
4229 if(seseWaitingQueue.getWaitingElementSize()>0) {
4230 output.println(" {");
4231 output.println(" REntry* rentry=NULL;");
4232 output.println(" INTPTR* pointer=NULL;");
4233 output.println(" seseToIssue->common.rentryIdx=0;");
4234 output.println(" int dispCount;");
4235 Vector<TempDescriptor> invars=fsen.getInVarsForDynamicCoarseConflictResolution();
4236 for(int i=0;i<invars.size();i++) {
4237 TempDescriptor td=invars.get(i);
4238 Set<Analysis.OoOJava.WaitingElement> weset=seseWaitingQueue.getWaitingElementSet(td);
4239 int numqueues=weset.size();
4240 output.println(" seseToIssue->rcrRecords["+i+"].flag="+numqueues+";");
4241 output.println(" dispCount=0;");
4242 for(Iterator<Analysis.OoOJava.WaitingElement> wtit=weset.iterator();wtit.hasNext();) {
4243 Analysis.OoOJava.WaitingElement waitingElement=wtit.next();
4244 int queueID=waitingElement.getQueueID();
4245 assert(waitingElement.getStatus()>=ConflictNode.COARSE);
4246 output.println(" rentry=mlpCreateREntry(" + waitingElement.getStatus() + ", &(seseToIssue->common));");
4247 output.println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
4248 output.println(" if(ADDRENTRY(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "],rentry)==READY) {");
4249 output.println(" dispCount++;");
4250 output.println(" }");
4252 output.println(" if(!dispCount || !atomic_sub_and_test(dispCount,&(seseToIssue->rcrRecords["+i+"].flag)))");
4253 output.println(" localCount++;");
4254 if (fsen.getDynamicInVarSet().contains(td)) {
4255 // dynamic in-var case
4256 //output.println(" pointer=seseToIssue->" + waitingElement.getDynID()+ "_srcSESE+seseToIssue->"+ waitingElement.getDynID()+ "_srcOffset;");
4257 //output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", &(seseToIssue->common), pointer );");
4260 output.println(" }");
4265 public void generateFlatSESEExitNode( FlatMethod fm,
4267 FlatSESEExitNode fsexn,
4268 PrintWriter output) {
4270 // if MLP flag is off, okay that SESE nodes are in IR graph,
4271 // just skip over them and code generates exactly the same
4272 if( ! (state.MLP || state.OOOJAVA) ) {
4276 // get the enter node for this exit that has meta data embedded
4277 FlatSESEEnterNode fsen = fsexn.getFlatEnter();
4279 // there may be an SESE in an unreachable method, skip over
4280 if( (state.MLP && !mlpa.getAllSESEs().contains( fsen )) ||
4281 (state.OOOJAVA && !oooa.getAllSESEs().contains( fsen ))
4286 // also, if we have encountered a placeholder, just jump it
4287 if( fsen.getIsCallerSESEplaceholder() ) {
4291 if( state.COREPROF ) {
4292 output.println("#ifdef CP_EVENTID_TASKEXECUTE");
4293 output.println(" CP_LOGEVENT( CP_EVENTID_TASKEXECUTE, CP_EVENTTYPE_END );");
4294 output.println("#endif");
4297 output.println(" /* SESE exiting */");
4299 if( state.COREPROF ) {
4300 output.println("#ifdef CP_EVENTID_TASKRETIRE");
4301 output.println(" CP_LOGEVENT( CP_EVENTID_TASKRETIRE, CP_EVENTTYPE_BEGIN );");
4302 output.println("#endif");
4306 // this SESE cannot be done until all of its children are done
4307 // so grab your own lock with the condition variable for watching
4308 // that the number of your running children is greater than zero
4309 output.println(" pthread_mutex_lock( &(runningSESE->lock) );");
4310 output.println(" if( runningSESE->numRunningChildren > 0 ) {");
4311 output.println(" stopforgc( (struct garbagelist *)&___locals___ );");
4312 output.println(" do {");
4313 output.println(" pthread_cond_wait( &(runningSESE->runningChildrenCond), &(runningSESE->lock) );");
4314 output.println(" } while( runningSESE->numRunningChildren > 0 );");
4315 output.println(" restartaftergc();");
4316 output.println(" }");
4319 // copy out-set from local temps into the sese record
4320 Iterator<TempDescriptor> itr = fsen.getOutVarSet().iterator();
4321 while( itr.hasNext() ) {
4322 TempDescriptor temp = itr.next();
4324 // only have to do this for primitives non-arrays
4326 temp.getType().isPrimitive() && !temp.getType().isArray()
4332 // have to determine the context enclosing this sese
4333 boolean useParentContext = false;
4335 if( (state.MLP &&fsen != mlpa.getMainSESE()) ||
4336 (state.OOOJAVA &&fsen != oooa.getMainSESE())
4338 assert fsen.getParent() != null;
4339 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
4340 useParentContext = true;
4345 if( useParentContext ) {
4346 from = generateTemp( fsen.getParent().getfmBogus(), temp, null );
4348 from = generateTemp( fsen.getfmEnclosing(), temp, null );
4351 output.println(" "+paramsprefix+
4352 "->"+temp.getSafeSymbol()+
4356 // mark yourself done, your task data is now read-only
4357 output.println(" runningSESE->doneExecuting = TRUE;");
4359 // if parent is stalling on you, let them know you're done
4360 if( (state.MLP && fsexn.getFlatEnter() != mlpa.getMainSESE()) ||
4361 (state.OOOJAVA && fsexn.getFlatEnter() != oooa.getMainSESE())
4363 output.println(" if( runningSESE->parentsStallSem != NULL ) {");
4364 output.println(" psem_give( runningSESE->parentsStallSem );");
4365 output.println(" }");
4368 output.println(" pthread_mutex_unlock( &(runningSESE->lock) );");
4370 // decrement dependency count for all SESE's on your forwarding list
4373 output.println(" while( !isEmpty( runningSESE->forwardList ) ) {");
4374 output.println(" SESEcommon* consumer = (SESEcommon*) getItem( runningSESE->forwardList );");
4377 output.println(" if(consumer->rentryIdx>0){");
4378 output.println(" // resolved null pointer");
4379 output.println(" int idx;");
4380 output.println(" for(idx=0;idx<consumer->rentryIdx;idx++){");
4381 output.println(" resolvePointer(consumer->rentryArray[idx]);");
4382 output.println(" }");
4383 output.println(" }");
4386 output.println(" if( atomic_sub_and_test( 1, &(consumer->unresolvedDependencies) ) ){");
4387 output.println(" workScheduleSubmit( (void*)consumer );");
4388 output.println(" }");
4389 output.println(" }");
4393 // clean up its lock element from waiting queue, and decrement dependency count for next SESE block
4394 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
4395 (state.OOOJAVA && fsen != oooa.getMainSESE())
4399 output.println(" /* check memory dependency*/");
4400 output.println(" {");
4401 output.println(" int idx;");
4402 output.println(" for(idx=0;idx<___params___->common.rentryIdx;idx++){");
4403 output.println(" REntry* re=___params___->common.rentryArray[idx];");
4404 output.println(" RETIRERENTRY(re->queue,re);");
4405 output.println(" }");
4406 output.println(" }");
4411 // last of all, decrement your parent's number of running children
4412 output.println(" if( runningSESE->parent != NULL ) {");
4413 output.println(" if( atomic_sub_and_test( 1, &(runningSESE->parent->numRunningChildren) ) ) {");
4414 output.println(" pthread_mutex_lock ( &(runningSESE->parent->lock) );");
4415 output.println(" pthread_cond_signal ( &(runningSESE->parent->runningChildrenCond) );");
4416 output.println(" pthread_mutex_unlock( &(runningSESE->parent->lock) );");
4417 output.println(" }");
4418 output.println(" }");
4420 // a task has variables to track static/dynamic instances
4421 // that serve as sources, release the parent's ref of each
4422 // non-null var of these types
4423 output.println(" // releasing static SESEs");
4424 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
4425 Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
4426 while( pItr.hasNext() ) {
4427 SESEandAgePair pair = pItr.next();
4428 output.println(" if( "+pair+" != NULL ) {");
4429 output.println(" RELEASE_REFERENCE_TO( "+pair+" );");
4430 output.println(" }");
4432 output.println(" // releasing dynamic variable sources");
4433 Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
4434 while( dynSrcItr.hasNext() ) {
4435 TempDescriptor dynSrcVar = dynSrcItr.next();
4436 output.println(" if( "+dynSrcVar+"_srcSESE != NULL ) {");
4437 output.println(" RELEASE_REFERENCE_TO( "+dynSrcVar+"_srcSESE );");
4438 output.println(" }");
4440 // destroy this task's mempool if it is not a leaf task
4441 if( !fsen.getIsLeafSESE() ) {
4442 output.println(" pooldestroy( runningSESE->taskRecordMemPool );");
4444 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
4447 // if this is not the Main sese (which has no parent) then return
4448 // THIS task's record to the PARENT'S task record pool, and only if
4449 // the reference count is now zero
4450 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
4451 (state.OOOJAVA && fsen != oooa.getMainSESE())
4453 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
4454 output.println(" RELEASE_REFERENCE_TO( runningSESE );");
4455 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
4457 // the main task has no parent, just free its record
4458 output.println(" mlpFreeSESErecord( runningSESE );");
4461 // as this thread is wrapping up the task, make sure the thread-local var
4462 // for the currently running task record references an invalid task
4463 output.println(" runningSESE = (SESEcommon*) 0x1;");
4465 if( state.COREPROF ) {
4466 output.println("#ifdef CP_EVENTID_TASKRETIRE");
4467 output.println(" CP_LOGEVENT( CP_EVENTID_TASKRETIRE, CP_EVENTTYPE_END );");
4468 output.println("#endif");
4472 public void generateFlatWriteDynamicVarNode( FlatMethod fm,
4474 FlatWriteDynamicVarNode fwdvn,
4477 if( !(state.MLP || state.OOOJAVA) ) {
4478 // should node should not be in an IR graph if the
4479 // MLP flag is not set
4480 throw new Error("Unexpected presence of FlatWriteDynamicVarNode");
4483 Hashtable<TempDescriptor, VSTWrapper> writeDynamic = fwdvn.getVar2src();
4485 assert writeDynamic != null;
4487 Iterator wdItr = writeDynamic.entrySet().iterator();
4488 while( wdItr.hasNext() ) {
4489 Map.Entry me = (Map.Entry) wdItr.next();
4490 TempDescriptor refVar = (TempDescriptor) me.getKey();
4491 VSTWrapper vstW = (VSTWrapper) me.getValue();
4492 VariableSourceToken vst = vstW.vst;
4494 output.println(" {");
4495 output.println(" SESEcommon* oldSrc = "+refVar+"_srcSESE;");
4498 // if there is no given source, this variable is ready so
4499 // mark src pointer NULL to signify that the var is up-to-date
4500 output.println(" "+refVar+"_srcSESE = NULL;");
4502 // otherwise we track where it will come from
4503 SESEandAgePair instance = new SESEandAgePair( vst.getSESE(), vst.getAge() );
4504 output.println(" "+refVar+"_srcSESE = "+instance+";");
4505 output.println(" "+refVar+"_srcOffset = (INTPTR) &((("+
4506 vst.getSESE().getSESErecordName()+"*)0)->"+vst.getAddrVar()+");");
4509 // no matter what we did above, track reference count of whatever
4510 // this variable pointed to, do release last in case we're just
4511 // copying the same value in because 1->2->1 is safe but ref count
4512 // 1->0->1 has a window where it looks like it should be free'd
4513 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
4514 output.println(" if( "+refVar+"_srcSESE != NULL ) {");
4515 output.println(" ADD_REFERENCE_TO( "+refVar+"_srcSESE );");
4516 output.println(" }");
4517 output.println(" if( oldSrc != NULL ) {");
4518 output.println(" RELEASE_REFERENCE_TO( oldSrc );");
4519 output.println(" }");
4520 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
4522 output.println(" }");
4527 private void generateFlatCheckNode(FlatMethod fm, LocalityBinding lb, FlatCheckNode fcn, PrintWriter output) {
4528 if (state.CONSCHECK) {
4529 String specname=fcn.getSpec();
4530 String varname="repairstate___";
4531 output.println("{");
4532 output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
4534 TempDescriptor[] temps=fcn.getTemps();
4535 String[] vars=fcn.getVars();
4536 for(int i=0; i<temps.length; i++) {
4537 output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i],lb)+";");
4540 output.println("if (doanalysis"+specname+"("+varname+")) {");
4541 output.println("free"+specname+"_state("+varname+");");
4542 output.println("} else {");
4543 output.println("/* Bad invariant */");
4544 output.println("free"+specname+"_state("+varname+");");
4545 output.println("abort_task();");
4546 output.println("}");
4547 output.println("}");
4551 private void generateFlatCall(FlatMethod fm, LocalityBinding lb, FlatCall fc, PrintWriter output) {
4553 MethodDescriptor md=fc.getMethod();
4554 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? locality.getBinding(lb, fc) : md);
4555 ClassDescriptor cn=md.getClassDesc();
4556 output.println("{");
4557 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4559 LocalityBinding fclb=locality.getBinding(lb, fc);
4560 output.print(" struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
4562 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
4563 output.print(objectparams.numPointers());
4564 output.print(", "+localsprefixaddr);
4565 if (md.getThis()!=null) {
4567 output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis(),lb));
4569 if (fc.getThis()!=null&&md.getThis()==null) {
4570 System.out.println("WARNING!!!!!!!!!!!!");
4571 System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
4575 for(int i=0; i<fc.numArgs(); i++) {
4576 Descriptor var=md.getParameter(i);
4577 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
4578 if (objectparams.isParamPtr(paramtemp)) {
4579 TempDescriptor targ=fc.getArg(i);
4581 TypeDescriptor td=md.getParamType(i);
4583 output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
4585 output.print("(struct "+md.getParamType(i).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
4588 output.println("};");
4593 if (fc.getReturnTemp()!=null)
4594 output.print(generateTemp(fm,fc.getReturnTemp(),lb)+"=");
4596 /* Do we need to do virtual dispatch? */
4597 if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
4600 LocalityBinding fclb=locality.getBinding(lb, fc);
4601 output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
4603 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
4608 if (md.getReturnType().isClass()||md.getReturnType().isArray())
4609 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
4611 output.print(md.getReturnType().getSafeSymbol()+" ");
4612 output.print("(*)(");
4614 boolean printcomma=false;
4615 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4617 LocalityBinding fclb=locality.getBinding(lb, fc);
4618 output.print("struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
4620 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
4624 for(int i=0; i<objectparams.numPrimitives(); i++) {
4625 TempDescriptor temp=objectparams.getPrimitive(i);
4629 if (temp.getType().isClass()||temp.getType().isArray())
4630 output.print("struct " + temp.getType().getSafeSymbol()+" * ");
4632 output.print(temp.getType().getSafeSymbol());
4637 LocalityBinding fclb=locality.getBinding(lb, fc);
4638 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])");
4640 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
4644 boolean needcomma=false;
4645 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4646 output.print("&__parameterlist__");
4650 if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
4651 if (fc.getThis()!=null) {
4652 TypeDescriptor ptd=null;
4653 if(md.getThis() != null) {
4654 ptd = md.getThis().getType();
4656 ptd = fc.getThis().getType();
4660 if (ptd.isClass()&&!ptd.isArray())
4661 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
4662 output.print(generateTemp(fm,fc.getThis(),lb));
4667 for(int i=0; i<fc.numArgs(); i++) {
4668 Descriptor var=md.getParameter(i);
4669 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
4670 if (objectparams.isParamPrim(paramtemp)) {
4671 TempDescriptor targ=fc.getArg(i);
4675 TypeDescriptor ptd=md.getParamType(i);
4676 if (ptd.isClass()&&!ptd.isArray())
4677 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
4678 output.print(generateTemp(fm, targ,lb));
4682 output.println(");");
4683 output.println(" }");
4686 private boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
4687 Set subclasses=typeutil.getSubClasses(thiscd);
4688 if (subclasses==null)
4690 for(Iterator classit=subclasses.iterator(); classit.hasNext();) {
4691 ClassDescriptor cd=(ClassDescriptor)classit.next();
4692 Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol());
4693 for(Iterator matchit=possiblematches.iterator(); matchit.hasNext();) {
4694 MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
4695 if (md.matches(matchmd))
4702 private void generateFlatFieldNode(FlatMethod fm, LocalityBinding lb, FlatFieldNode ffn, PrintWriter output) {
4703 if (state.SINGLETM) {
4704 //single machine transactional memory case
4705 String field=ffn.getField().getSafeSymbol();
4706 String src=generateTemp(fm, ffn.getSrc(),lb);
4707 String dst=generateTemp(fm, ffn.getDst(),lb);
4709 output.println(dst+"="+ src +"->"+field+ ";");
4710 if (ffn.getField().getType().isPtr()&&locality.getAtomic(lb).get(ffn).intValue()>0&&
4711 locality.getNodePreTempInfo(lb, ffn).get(ffn.getSrc())!=LocalityAnalysis.SCRATCH) {
4712 if ((dc==null)||(!state.READSET&&dc.getNeedTrans(lb, ffn))||
4713 (state.READSET&&dc.getNeedWriteTrans(lb, ffn))) {
4714 output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));");
4715 } else if (state.READSET&&dc.getNeedTrans(lb, ffn)) {
4716 if (state.HYBRID&&delaycomp.getConv(lb).contains(ffn)) {
4717 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4719 output.println("TRANSREADRD("+dst+", "+dst+");");
4722 } else if (state.DSM) {
4723 Integer status=locality.getNodePreTempInfo(lb,ffn).get(ffn.getSrc());
4724 if (status==LocalityAnalysis.GLOBAL) {
4725 String field=ffn.getField().getSafeSymbol();
4726 String src=generateTemp(fm, ffn.getSrc(),lb);
4727 String dst=generateTemp(fm, ffn.getDst(),lb);
4729 if (ffn.getField().getType().isPtr()) {
4731 //TODO: Uncomment this when we have runtime support
4732 //if (ffn.getSrc()==ffn.getDst()) {
4733 //output.println("{");
4734 //output.println("void * temp="+src+";");
4735 //output.println("if (temp&0x1) {");
4736 //output.println("temp=(void *) transRead(trans, (unsigned int) temp);");
4737 //output.println(src+"->"+field+"="+temp+";");
4738 //output.println("}");
4739 //output.println(dst+"=temp;");
4740 //output.println("}");
4742 output.println(dst+"="+ src +"->"+field+ ";");
4743 //output.println("if ("+dst+"&0x1) {");
4744 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
4745 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
4746 //output.println(src+"->"+field+"="+src+"->"+field+";");
4747 //output.println("}");
4750 output.println(dst+"="+ src+"->"+field+";");
4752 } else if (status==LocalityAnalysis.LOCAL) {
4753 if (ffn.getField().getType().isPtr()&&
4754 ffn.getField().isGlobal()) {
4755 String field=ffn.getField().getSafeSymbol();
4756 String src=generateTemp(fm, ffn.getSrc(),lb);
4757 String dst=generateTemp(fm, ffn.getDst(),lb);
4758 output.println(dst+"="+ src +"->"+field+ ";");
4759 if (locality.getAtomic(lb).get(ffn).intValue()>0)
4760 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
4761 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
4763 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4764 } else if (status==LocalityAnalysis.EITHER) {
4765 //Code is reading from a null pointer
4766 output.println("if ("+generateTemp(fm, ffn.getSrc(),lb)+") {");
4767 output.println("#ifndef RAW");
4768 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4769 output.println("#endif");
4770 //This should throw a suitable null pointer error
4771 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4773 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4775 // DEBUG if(!ffn.getDst().getType().isPrimitive()){
4776 // DEBUG output.println("within((void*)"+generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+");");
4778 if(ffn.getField().isStatic()) {
4779 // static field, redirect to the global_defs_p structure
4780 if(ffn.getSrc().getType().isStatic()) {
4781 // reference to the static field with Class name
4782 output.println(generateTemp(fm, ffn.getDst(),lb)+"=global_defs_p->"+ ffn.getSrc().getType().getClassDesc().getSafeSymbol()+ffn.getField().getSafeSymbol()+";");
4784 output.println(generateTemp(fm, ffn.getDst(),lb)+"=*"+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4786 //output.println(generateTemp(fm, ffn.getDst(),lb)+"=global_defs_p->"+ffn.getSrc().getType().getClassDesc().getSafeSymbol()+"->"+ ffn.getField().getSafeSymbol()+";");
4788 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4794 private void generateFlatSetFieldNode(FlatMethod fm, LocalityBinding lb, FlatSetFieldNode fsfn, PrintWriter output) {
4795 if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
4796 throw new Error("Can't set array length");
4797 if (state.SINGLETM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
4798 //Single Machine Transaction Case
4799 boolean srcptr=fsfn.getSrc().getType().isPtr();
4800 String src=generateTemp(fm,fsfn.getSrc(),lb);
4801 String dst=generateTemp(fm,fsfn.getDst(),lb);
4802 output.println("//"+srcptr+" "+fsfn.getSrc().getType().isNull());
4803 if (srcptr&&!fsfn.getSrc().getType().isNull()) {
4804 output.println("{");
4805 if ((dc==null)||dc.getNeedSrcTrans(lb, fsfn)&&
4806 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) {
4807 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4809 output.println("INTPTR srcoid=(INTPTR)"+src+";");
4812 if (wb.needBarrier(fsfn)&&
4813 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getDst())!=LocalityAnalysis.SCRATCH) {
4814 if (state.EVENTMONITOR) {
4815 output.println("if ("+dst+"->___objstatus___&DIRTY) EVLOGEVENTOBJ(EV_WRITE,"+dst+"->objuid)");
4817 output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;");
4819 if (srcptr&!fsfn.getSrc().getType().isNull()) {
4820 output.println("*((unsigned INTPTR *)&("+dst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4821 output.println("}");
4823 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4825 } else if (state.DSM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
4826 Integer statussrc=locality.getNodePreTempInfo(lb,fsfn).get(fsfn.getSrc());
4827 Integer statusdst=locality.getNodeTempInfo(lb).get(fsfn).get(fsfn.getDst());
4828 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4830 String src=generateTemp(fm,fsfn.getSrc(),lb);
4831 String dst=generateTemp(fm,fsfn.getDst(),lb);
4833 output.println("{");
4834 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4836 if (statusdst.equals(LocalityAnalysis.GLOBAL)) {
4839 if (wb.needBarrier(fsfn))
4840 output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;");
4842 output.println("*((unsigned INTPTR *)&("+glbdst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4844 output.println(glbdst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4845 } else if (statusdst.equals(LocalityAnalysis.LOCAL)) {
4846 /** Check if we need to copy */
4847 output.println("if(!"+dst+"->"+localcopystr+") {");
4848 /* Link object into list */
4849 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4850 output.println(revertptr+"=revertlist;");
4851 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4852 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4854 output.println("COPY_OBJ("+dst+");");
4855 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4856 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4857 output.println("}");
4859 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4861 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4862 } else if (statusdst.equals(LocalityAnalysis.EITHER)) {
4863 //writing to a null...bad
4864 output.println("if ("+dst+") {");
4865 output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}");
4867 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4869 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4872 output.println("}");
4875 if (state.FASTCHECK) {
4876 String dst=generateTemp(fm, fsfn.getDst(),lb);
4877 output.println("if(!"+dst+"->"+localcopystr+") {");
4878 /* Link object into list */
4879 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4880 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4882 output.println("COPY_OBJ("+dst+");");
4883 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4884 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4885 output.println("}");
4888 // DEBUG if(!fsfn.getField().getType().isPrimitive()){
4889 // DEBUG output.println("within((void*)"+generateTemp(fm,fsfn.getSrc(),lb)+");");
4891 if(fsfn.getField().isStatic()) {
4892 // static field, redirect to the global_defs_p structure
4893 if(fsfn.getDst().getType().isStatic()) {
4894 // reference to the static field with Class name
4895 output.println("global_defs_p->" + fsfn.getDst().getType().getClassDesc().getSafeSymbol() + fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
4897 output.println("*"+generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
4900 output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
4905 private void generateFlatElementNode(FlatMethod fm, LocalityBinding lb, FlatElementNode fen, PrintWriter output) {
4906 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
4909 if (elementtype.isArray()||elementtype.isClass())
4912 type=elementtype.getSafeSymbol()+" ";
4914 if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
4915 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fen.getIndex(),lb)+") >= "+generateTemp(fm,fen.getSrc(),lb) + "->___length___))");
4916 output.println("failedboundschk();");
4918 if (state.SINGLETM) {
4919 //Single machine transaction case
4920 String dst=generateTemp(fm, fen.getDst(),lb);
4921 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))) {
4922 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4924 output.println("STMGETARRAY("+dst+", "+ generateTemp(fm,fen.getSrc(),lb)+", "+generateTemp(fm, fen.getIndex(),lb)+", "+type+");");
4927 if (elementtype.isPtr()&&locality.getAtomic(lb).get(fen).intValue()>0&&
4928 locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())!=LocalityAnalysis.SCRATCH) {
4929 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fen)||state.READSET&&dc.getNeedWriteTrans(lb, fen)) {
4930 output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));");
4931 } else if (state.READSET&&dc.getNeedTrans(lb, fen)) {
4932 if (state.HYBRID&&delaycomp.getConv(lb).contains(fen)) {
4933 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4935 output.println("TRANSREADRD("+dst+", "+dst+");");
4938 } else if (state.DSM) {
4939 Integer status=locality.getNodePreTempInfo(lb,fen).get(fen.getSrc());
4940 if (status==LocalityAnalysis.GLOBAL) {
4941 String dst=generateTemp(fm, fen.getDst(),lb);
4942 if (elementtype.isPtr()) {
4943 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4944 //DEBUG: output.println("TRANSREAD("+dst+", "+dst+",\""+fm+":"+fen+"\");");
4945 output.println("TRANSREAD("+dst+", "+dst+");");
4947 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4949 } else if (status==LocalityAnalysis.LOCAL) {
4950 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4951 } else if (status==LocalityAnalysis.EITHER) {
4952 //Code is reading from a null pointer
4953 output.println("if ("+generateTemp(fm, fen.getSrc(),lb)+") {");
4954 output.println("#ifndef RAW");
4955 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4956 output.println("#endif");
4957 //This should throw a suitable null pointer error
4958 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4960 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4962 // DEBUG output.println("within((void*)"+generateTemp(fm,fen.getSrc(),lb)+");");
4963 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4967 private void generateFlatSetElementNode(FlatMethod fm, LocalityBinding lb, FlatSetElementNode fsen, PrintWriter output) {
4968 //TODO: need dynamic check to make sure this assignment is actually legal
4969 //Because Object[] could actually be something more specific...ie. Integer[]
4971 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
4974 if (elementtype.isArray()||elementtype.isClass())
4977 type=elementtype.getSafeSymbol()+" ";
4979 if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
4980 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fsen.getIndex(),lb)+") >= "+generateTemp(fm,fsen.getDst(),lb) + "->___length___))");
4981 output.println("failedboundschk();");
4984 if (state.SINGLETM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4985 //Transaction set element case
4986 if (wb.needBarrier(fsen)&&
4987 locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH) {
4988 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___objstatus___))|=DIRTY;");
4990 if (fsen.getSrc().getType().isPtr()&&!fsen.getSrc().getType().isNull()) {
4991 output.println("{");
4992 String src=generateTemp(fm, fsen.getSrc(), lb);
4993 if ((dc==null)||dc.getNeedSrcTrans(lb, fsen)&&
4994 locality.getNodePreTempInfo(lb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) {
4995 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4997 output.println("INTPTR srcoid=(INTPTR)"+src+";");
4999 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
5000 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", srcoid, INTPTR);");
5002 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
5004 output.println("}");
5006 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
5007 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", "+ generateTemp(fm, fsen.getSrc(), lb) +", "+type+");");
5009 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
5012 } else if (state.DSM && locality.getAtomic(lb).get(fsen).intValue()>0) {
5013 Integer statussrc=locality.getNodePreTempInfo(lb,fsen).get(fsen.getSrc());
5014 Integer statusdst=locality.getNodePreTempInfo(lb,fsen).get(fsen.getDst());
5015 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
5016 boolean dstglobal=statusdst==LocalityAnalysis.GLOBAL;
5017 boolean dstlocal=(statusdst==LocalityAnalysis.LOCAL)||(statusdst==LocalityAnalysis.EITHER);
5020 if (wb.needBarrier(fsen))
5021 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___localcopy___))|=DIRTY;");
5022 } else if (dstlocal) {
5023 /** Check if we need to copy */
5024 String dst=generateTemp(fm, fsen.getDst(),lb);
5025 output.println("if(!"+dst+"->"+localcopystr+") {");
5026 /* Link object into list */
5027 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5028 output.println(revertptr+"=revertlist;");
5029 if ((GENERATEPRECISEGC) || this.state.MULTICOREGC)
5030 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
5032 output.println("COPY_OBJ("+dst+");");
5033 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
5034 output.println("revertlist=(struct ___Object___ *)"+dst+";");
5035 output.println("}");
5037 System.out.println("Node: "+fsen);
5038 System.out.println(lb);
5039 System.out.println("statusdst="+statusdst);
5040 System.out.println(fm.printMethod());
5041 throw new Error("Unknown array type");
5044 output.println("{");
5045 String src=generateTemp(fm, fsen.getSrc(), lb);
5046 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
5047 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
5048 output.println("}");
5050 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
5053 if (state.FASTCHECK) {
5054 String dst=generateTemp(fm, fsen.getDst(),lb);
5055 output.println("if(!"+dst+"->"+localcopystr+") {");
5056 /* Link object into list */
5057 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
5058 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
5060 output.println("COPY_OBJ("+dst+");");
5061 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
5062 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
5063 output.println("}");
5065 // DEBUG output.println("within((void*)"+generateTemp(fm,fsen.getDst(),lb)+");");
5066 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
5070 protected void generateFlatNew(FlatMethod fm, LocalityBinding lb, FlatNew fn, PrintWriter output) {
5071 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
5072 //Stash pointer in case of GC
5073 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5074 output.println(revertptr+"=revertlist;");
5076 if (state.SINGLETM) {
5077 if (fn.getType().isArray()) {
5078 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
5079 if (locality.getAtomic(lb).get(fn).intValue()>0) {
5080 //inside transaction
5081 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
5083 //outside transaction
5084 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
5087 if (locality.getAtomic(lb).get(fn).intValue()>0) {
5088 //inside transaction
5089 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
5091 //outside transaction
5092 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
5095 } else if (fn.getType().isArray()) {
5096 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
5097 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
5098 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
5099 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5100 if(this.state.MLP || state.OOOJAVA){
5101 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray_mlp("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+", oid, "+oooa.getDisjointAnalysis().getAllocationSiteFromFlatNew(fn).getUniqueAllocSiteID()+");");
5102 output.println(" oid += numWorkers;");
5104 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
5107 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
5110 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
5111 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");");
5112 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5113 if (this.state.MLP || state.OOOJAVA){
5114 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new_mlp("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+", oid, "+oooa.getDisjointAnalysis().getAllocationSiteFromFlatNew(fn).getUniqueAllocSiteID()+");");
5115 output.println(" oid += numWorkers;");
5117 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
5120 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
5123 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
5124 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5125 String dst=generateTemp(fm,fn.getDst(),lb);
5126 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
5127 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
5128 output.println("revertlist=(struct ___Object___ *)"+dst+";");
5130 if (state.FASTCHECK) {
5131 String dst=generateTemp(fm,fn.getDst(),lb);
5132 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
5133 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
5134 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
5138 private void generateFlatTagDeclaration(FlatMethod fm, LocalityBinding lb, FlatTagDeclaration fn, PrintWriter output) {
5139 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5140 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
5142 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+state.getTagId(fn.getType())+");");
5146 private void generateFlatOpNode(FlatMethod fm, LocalityBinding lb, FlatOpNode fon, PrintWriter output) {
5147 if (fon.getRight()!=null) {
5148 if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
5149 if (fon.getLeft().getType().isLong())
5150 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
5152 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned int)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
5154 } else if (dc!=null) {
5155 output.print(generateTemp(fm, fon.getDest(),lb)+" = (");
5156 if (fon.getLeft().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
5157 output.print("(void *)");
5158 if (dc.getNeedLeftSrcTrans(lb, fon))
5159 output.print("("+generateTemp(fm, fon.getLeft(),lb)+"!=NULL?"+generateTemp(fm, fon.getLeft(),lb)+"->"+oidstr+":NULL)");
5161 output.print(generateTemp(fm, fon.getLeft(),lb));
5162 output.print(")"+fon.getOp().toString()+"(");
5163 if (fon.getRight().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
5164 output.print("(void *)");
5165 if (dc.getNeedRightSrcTrans(lb, fon))
5166 output.println("("+generateTemp(fm, fon.getRight(),lb)+"!=NULL?"+generateTemp(fm, fon.getRight(),lb)+"->"+oidstr+":NULL));");
5168 output.println(generateTemp(fm,fon.getRight(),lb)+");");
5170 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+fon.getOp().toString()+generateTemp(fm,fon.getRight(),lb)+";");
5171 } else if (fon.getOp().getOp()==Operation.ASSIGN)
5172 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
5173 else if (fon.getOp().getOp()==Operation.UNARYPLUS)
5174 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
5175 else if (fon.getOp().getOp()==Operation.UNARYMINUS)
5176 output.println(generateTemp(fm, fon.getDest(),lb)+" = -"+generateTemp(fm, fon.getLeft(),lb)+";");
5177 else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
5178 output.println(generateTemp(fm, fon.getDest(),lb)+" = !"+generateTemp(fm, fon.getLeft(),lb)+";");
5179 else if (fon.getOp().getOp()==Operation.COMP)
5180 output.println(generateTemp(fm, fon.getDest(),lb)+" = ~"+generateTemp(fm, fon.getLeft(),lb)+";");
5181 else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
5182 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+"->fses==NULL;");
5184 output.println(generateTemp(fm, fon.getDest(),lb)+fon.getOp().toString()+generateTemp(fm, fon.getLeft(),lb)+";");
5187 private void generateFlatCastNode(FlatMethod fm, LocalityBinding lb, FlatCastNode fcn, PrintWriter output) {
5188 /* TODO: Do type check here */
5189 if (fcn.getType().isArray()) {
5190 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
5191 } else if (fcn.getType().isClass())
5192 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
5194 output.println(generateTemp(fm,fcn.getDst(),lb)+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc(),lb)+";");
5197 private void generateFlatLiteralNode(FlatMethod fm, LocalityBinding lb, FlatLiteralNode fln, PrintWriter output) {
5198 if (fln.getValue()==null)
5199 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
5200 else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
5201 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5202 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
5203 //Stash pointer in case of GC
5204 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5205 output.println(revertptr+"=revertlist;");
5207 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
5208 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
5209 //Stash pointer in case of GC
5210 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5211 output.println("revertlist="+revertptr+";");
5214 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
5216 } else if (fln.getType().isBoolean()) {
5217 if (((Boolean)fln.getValue()).booleanValue())
5218 output.println(generateTemp(fm, fln.getDst(),lb)+"=1;");
5220 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
5221 } else if (fln.getType().isChar()) {
5222 String st=FlatLiteralNode.escapeString(fln.getValue().toString());
5223 output.println(generateTemp(fm, fln.getDst(),lb)+"='"+st+"';");
5224 } else if (fln.getType().isLong()) {
5225 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+"LL;");
5227 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+";");
5230 protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) {
5231 if (frn.getReturnTemp()!=null) {
5232 if (frn.getReturnTemp().getType().isPtr())
5233 output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";");
5235 output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";");
5237 output.println("return;");
5241 protected void generateStoreFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
5244 //only record if this group has more than one exit
5245 if (branchanalysis.numJumps(fcb)>1) {
5246 left=branchanalysis.jumpValue(fcb, 0);
5247 right=branchanalysis.jumpValue(fcb, 1);
5249 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") {");
5251 output.println("STOREBRANCH("+right+");");
5252 output.println("goto "+label+";");
5253 output.println("}");
5255 output.println("STOREBRANCH("+left+");");
5258 protected void generateFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
5259 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") goto "+label+";");
5262 /** This method generates header information for the method or
5263 * task referenced by the Descriptor des. */
5264 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) {
5265 generateHeader(fm, lb, des, output, false);
5268 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output, boolean addSESErecord) {
5270 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : des);
5271 MethodDescriptor md=null;
5272 TaskDescriptor task=null;
5273 if (des instanceof MethodDescriptor)
5274 md=(MethodDescriptor) des;
5276 task=(TaskDescriptor) des;
5278 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
5280 if (md!=null&&md.getReturnType()!=null) {
5281 if (md.getReturnType().isClass()||md.getReturnType().isArray())
5282 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
5284 output.print(md.getReturnType().getSafeSymbol()+" ");
5286 //catch the constructor case
5287 output.print("void ");
5289 if (state.DSM||state.SINGLETM) {
5290 output.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
5292 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
5294 output.print(task.getSafeSymbol()+"(");
5296 boolean printcomma=false;
5297 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5299 if (state.DSM||state.SINGLETM) {
5300 output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
5302 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
5304 output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
5310 for(int i=0; i<objectparams.numPrimitives(); i++) {
5311 TempDescriptor temp=objectparams.getPrimitive(i);
5315 if (temp.getType().isClass()||temp.getType().isArray())
5316 output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
5318 output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
5320 output.println(") {");
5321 } else if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
5322 /* Imprecise Task */
5323 output.println("void * parameterarray[]) {");
5324 /* Unpack variables */
5325 for(int i=0; i<objectparams.numPrimitives(); i++) {
5326 TempDescriptor temp=objectparams.getPrimitive(i);
5327 output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
5329 for(int i=0; i<fm.numTags(); i++) {
5330 TempDescriptor temp=fm.getTag(i);
5331 int offset=i+objectparams.numPrimitives();
5332 output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
5335 if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
5336 maxtaskparams=objectparams.numPrimitives()+fm.numTags();
5337 } else output.println(") {");
5340 public void generateFlatFlagActionNode(FlatMethod fm, LocalityBinding lb, FlatFlagActionNode ffan, PrintWriter output) {
5341 output.println("/* FlatFlagActionNode */");
5344 /* Process tag changes */
5345 Relation tagsettable=new Relation();
5346 Relation tagcleartable=new Relation();
5348 Iterator tagsit=ffan.getTempTagPairs();
5349 while (tagsit.hasNext()) {
5350 TempTagPair ttp=(TempTagPair) tagsit.next();
5351 TempDescriptor objtmp=ttp.getTemp();
5352 TagDescriptor tag=ttp.getTag();
5353 TempDescriptor tagtmp=ttp.getTagTemp();
5354 boolean tagstatus=ffan.getTagChange(ttp);
5356 tagsettable.put(objtmp, tagtmp);
5358 tagcleartable.put(objtmp, tagtmp);
5363 Hashtable flagandtable=new Hashtable();
5364 Hashtable flagortable=new Hashtable();
5366 /* Process flag changes */
5367 Iterator flagsit=ffan.getTempFlagPairs();
5368 while(flagsit.hasNext()) {
5369 TempFlagPair tfp=(TempFlagPair)flagsit.next();
5370 TempDescriptor temp=tfp.getTemp();
5371 Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
5372 FlagDescriptor flag=tfp.getFlag();
5374 //Newly allocate objects that don't set any flags case
5375 if (flagortable.containsKey(temp)) {
5379 flagortable.put(temp,new Integer(mask));
5381 int flagid=1<<((Integer)flagtable.get(flag)).intValue();
5382 boolean flagstatus=ffan.getFlagChange(tfp);
5385 if (flagortable.containsKey(temp)) {
5386 mask=((Integer)flagortable.get(temp)).intValue();
5389 flagortable.put(temp,new Integer(mask));
5391 int mask=0xFFFFFFFF;
5392 if (flagandtable.containsKey(temp)) {
5393 mask=((Integer)flagandtable.get(temp)).intValue();
5395 mask&=(0xFFFFFFFF^flagid);
5396 flagandtable.put(temp,new Integer(mask));
5402 HashSet flagtagset=new HashSet();
5403 flagtagset.addAll(flagortable.keySet());
5404 flagtagset.addAll(flagandtable.keySet());
5405 flagtagset.addAll(tagsettable.keySet());
5406 flagtagset.addAll(tagcleartable.keySet());
5408 Iterator ftit=flagtagset.iterator();
5409 while(ftit.hasNext()) {
5410 TempDescriptor temp=(TempDescriptor)ftit.next();
5413 Set tagtmps=tagcleartable.get(temp);
5414 if (tagtmps!=null) {
5415 Iterator tagit=tagtmps.iterator();
5416 while(tagit.hasNext()) {
5417 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
5418 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
5419 output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5421 output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5425 tagtmps=tagsettable.get(temp);
5426 if (tagtmps!=null) {
5427 Iterator tagit=tagtmps.iterator();
5428 while(tagit.hasNext()) {
5429 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
5430 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
5431 output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5433 output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp, lb)+", "+generateTemp(fm,tagtmp, lb)+");");
5438 int andmask=0xFFFFFFF;
5440 if (flagortable.containsKey(temp))
5441 ormask=((Integer)flagortable.get(temp)).intValue();
5442 if (flagandtable.containsKey(temp))
5443 andmask=((Integer)flagandtable.get(temp)).intValue();
5444 generateFlagOrAnd(ffan, fm, lb, temp, output, ormask, andmask);
5445 generateObjectDistribute(ffan, fm, lb, temp, output);
5449 protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp,
5450 PrintWriter output, int ormask, int andmask) {
5451 if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
5452 output.println("flagorandinit("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
5454 output.println("flagorand("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
5458 protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, PrintWriter output) {
5459 output.println("enqueueObject("+generateTemp(fm, temp, lb)+");");
5462 void generateOptionalHeader(PrintWriter headers) {
5465 headers.println("#include \"task.h\"\n\n");
5466 headers.println("#ifndef _OPTIONAL_STRUCT_");
5467 headers.println("#define _OPTIONAL_STRUCT_");
5469 //STRUCT PREDICATEMEMBER
5470 headers.println("struct predicatemember{");
5471 headers.println("int type;");
5472 headers.println("int numdnfterms;");
5473 headers.println("int * flags;");
5474 headers.println("int numtags;");
5475 headers.println("int * tags;\n};\n\n");
5477 //STRUCT OPTIONALTASKDESCRIPTOR
5478 headers.println("struct optionaltaskdescriptor{");
5479 headers.println("struct taskdescriptor * task;");
5480 headers.println("int index;");
5481 headers.println("int numenterflags;");
5482 headers.println("int * enterflags;");
5483 headers.println("int numpredicatemembers;");
5484 headers.println("struct predicatemember ** predicatememberarray;");
5485 headers.println("};\n\n");
5487 //STRUCT TASKFAILURE
5488 headers.println("struct taskfailure {");
5489 headers.println("struct taskdescriptor * task;");
5490 headers.println("int index;");
5491 headers.println("int numoptionaltaskdescriptors;");
5492 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
5494 //STRUCT FSANALYSISWRAPPER
5495 headers.println("struct fsanalysiswrapper{");
5496 headers.println("int flags;");
5497 headers.println("int numtags;");
5498 headers.println("int * tags;");
5499 headers.println("int numtaskfailures;");
5500 headers.println("struct taskfailure ** taskfailurearray;");
5501 headers.println("int numoptionaltaskdescriptors;");
5502 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
5504 //STRUCT CLASSANALYSISWRAPPER
5505 headers.println("struct classanalysiswrapper{");
5506 headers.println("int type;");
5507 headers.println("int numotd;");
5508 headers.println("struct optionaltaskdescriptor ** otdarray;");
5509 headers.println("int numfsanalysiswrappers;");
5510 headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
5512 headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
5514 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
5515 while(taskit.hasNext()) {
5516 TaskDescriptor td=(TaskDescriptor)taskit.next();
5517 headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
5522 //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
5523 int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
5524 int predicateindex = 0;
5525 //iterate through the classes concerned by the predicate
5526 Set c_vard = predicate.vardescriptors;
5527 Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
5530 for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext();) {
5531 VarDescriptor vard = (VarDescriptor)vard_it.next();
5532 TypeDescriptor typed = vard.getType();
5534 //generate for flags
5535 HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
5536 output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5538 if (fen_hashset!=null) {
5539 for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext();) {
5540 FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
5542 DNFFlag dflag=fen.getDNF();
5543 numberterms+=dflag.size();
5545 Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
5547 for(int j=0; j<dflag.size(); j++) {
5549 output.println(",");
5550 Vector term=dflag.get(j);
5553 for(int k=0; k<term.size(); k++) {
5554 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
5555 FlagDescriptor fd=dfa.getFlag();
5556 boolean negated=dfa.getNegated();
5557 int flagid=1<<((Integer)flags.get(fd)).intValue();
5562 output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
5567 output.println("};\n");
5570 TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
5571 output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5574 for(int j=0; j<tagel.numTags(); j++) {
5576 output.println(",");
5577 TempDescriptor tmp=tagel.getTemp(j);
5578 if (!slotnumber.containsKey(tmp)) {
5579 Integer slotint=new Integer(current_slot++);
5580 slotnumber.put(tmp,slotint);
5582 int slot=slotnumber.get(tmp).intValue();
5583 output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
5585 numtags = tagel.numTags();
5587 output.println("};");
5589 //store the result into a predicatemember struct
5590 output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
5591 output.println("/*type*/"+typed.getClassDesc().getId()+",");
5592 output.println("/* number of dnf terms */"+numberterms+",");
5593 output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5594 output.println("/* number of tag */"+numtags+",");
5595 output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5596 output.println("};\n");
5601 //generate an array that stores the entire predicate
5602 output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5603 for( int j = 0; j<predicateindex; j++) {
5604 if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5605 else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5607 output.println("};\n");
5608 return predicateindex;
5612 void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
5613 generateOptionalHeader(headers);
5615 output.println("#include \"optionalstruct.h\"\n\n");
5616 output.println("#include \"stdlib.h\"\n");
5618 HashSet processedcd = new HashSet();
5620 Enumeration e = safeexecution.keys();
5621 while (e.hasMoreElements()) {
5624 ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
5625 Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp); //will be used several times
5627 //Generate the struct of optionals
5628 Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
5629 numotd = c_otd.size();
5630 if(maxotd<numotd) maxotd = numotd;
5631 if( !c_otd.isEmpty() ) {
5632 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
5633 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
5635 //generate the int arrays for the predicate
5636 Predicate predicate = otd.predicate;
5637 int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
5638 TreeSet<Integer> fsset=new TreeSet<Integer>();
5639 //iterate through possible FSes corresponding to
5640 //the state when entering
5642 for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext();) {
5643 FlagState fs = (FlagState)fses.next();
5645 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
5646 FlagDescriptor flagd = (FlagDescriptor)flags.next();
5647 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
5650 fsset.add(new Integer(flagid));
5651 //tag information not needed because tag
5652 //changes are not tolerated.
5655 output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5656 boolean needcomma=false;
5657 for(Iterator<Integer> it=fsset.iterator(); it.hasNext();) {
5660 output.println(it.next());
5663 output.println("};\n");
5666 //generate optionaltaskdescriptor that actually
5667 //includes exit fses, predicate and the task
5669 output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
5670 output.println("&task_"+otd.td.getSafeSymbol()+",");
5671 output.println("/*index*/"+otd.getIndex()+",");
5672 output.println("/*number of enter flags*/"+fsset.size()+",");
5673 output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5674 output.println("/*number of members */"+predicateindex+",");
5675 output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5676 output.println("};\n");
5680 // if there are no optionals, there is no need to build the rest of the struct
5682 output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
5683 c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
5684 if( !c_otd.isEmpty() ) {
5685 boolean needcomma=false;
5686 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
5687 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
5689 output.println(",");
5691 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5694 output.println("};\n");
5696 //get all the possible flagstates reachable by an object
5697 Hashtable hashtbtemp = safeexecution.get(cdtemp);
5699 TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
5700 fsts.addAll(hashtbtemp.keySet());
5701 for(Iterator fsit=fsts.iterator(); fsit.hasNext();) {
5702 FlagState fs = (FlagState)fsit.next();
5705 //get the set of OptionalTaskDescriptors corresponding
5706 HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
5707 //iterate through the OptionalTaskDescriptors and
5708 //store the pointers to the optionals struct (see on
5709 //top) into an array
5711 output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
5712 for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext();) {
5713 OptionalTaskDescriptor mm = mos.next();
5715 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
5717 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5720 output.println("};\n");
5722 //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
5725 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
5726 FlagDescriptor flagd = (FlagDescriptor)flags.next();
5727 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
5731 //process tag information
5734 boolean first = true;
5735 Enumeration tag_enum = fs.getTags();
5736 output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
5737 while(tag_enum.hasMoreElements()) {
5739 TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
5743 output.println(", ");
5744 output.println("/*tagid*/"+state.getTagId(tagd));
5746 output.println("};");
5748 Set<TaskIndex> tiset=sa.getTaskIndex(fs);
5749 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
5750 TaskIndex ti=itti.next();
5754 Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
5756 output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
5757 boolean needcomma=false;
5758 for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext();) {
5759 OptionalTaskDescriptor otd=otdit.next();
5763 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5765 output.println("};");
5767 output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
5768 output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
5769 output.print(ti.getIndex()+", ");
5770 output.print(otdset.size()+", ");
5771 output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
5772 output.println("};");
5775 tiset=sa.getTaskIndex(fs);
5776 boolean needcomma=false;
5778 output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
5779 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
5780 TaskIndex ti=itti.next();
5781 if (ti.isRuntime()) {
5788 output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
5790 output.println("};\n");
5792 //Store the result in fsanalysiswrapper
5794 output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
5795 output.println("/*flag*/"+flagid+",");
5796 output.println("/* number of tags*/"+tagcounter+",");
5797 output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
5798 output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
5799 output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
5800 output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
5801 output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
5802 output.println("};\n");
5806 //Build the array of fsanalysiswrappers
5807 output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
5808 boolean needcomma=false;
5809 for(int i = 0; i<fscounter; i++) {
5810 if (needcomma) output.print(",");
5811 output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
5814 output.println("};");
5816 //Build the classanalysiswrapper referring to the previous array
5817 output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
5818 output.println("/*type*/"+cdtemp.getId()+",");
5819 output.println("/*numotd*/"+numotd+",");
5820 output.println("otdarray"+cdtemp.getSafeSymbol()+",");
5821 output.println("/* number of fsanalysiswrappers */"+fscounter+",");
5822 output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
5823 processedcd.add(cdtemp);
5826 //build an array containing every classes for which code has been build
5827 output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
5828 for(int i=0; i<state.numClasses(); i++) {
5829 ClassDescriptor cn=cdarray[i];
5832 if ((cn != null) && (processedcd.contains(cn)))
5833 output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
5835 output.print("NULL");
5837 output.println("};");
5839 output.println("#define MAXOTD "+maxotd);
5840 headers.println("#endif");
5843 public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
5844 Relation r=new Relation();
5845 for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext();) {
5846 OptionalTaskDescriptor otd=otdit.next();
5847 TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
5851 LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
5852 for(Iterator it=r.keySet().iterator(); it.hasNext();) {
5853 Set s=r.get(it.next());
5854 for(Iterator it2=s.iterator(); it2.hasNext();) {
5855 OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
5863 protected void outputTransCode(PrintWriter output) {
5866 private int calculateSizeOfSESEParamList(FlatSESEEnterNode fsen){
5868 Set<TempDescriptor> tdSet=new HashSet<TempDescriptor>();
5870 for (Iterator iterator = fsen.getInVarSet().iterator(); iterator.hasNext();) {
5871 TempDescriptor tempDescriptor = (TempDescriptor) iterator.next();
5872 if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()){
5873 tdSet.add(tempDescriptor);
5877 for (Iterator iterator = fsen.getOutVarSet().iterator(); iterator.hasNext();) {
5878 TempDescriptor tempDescriptor = (TempDescriptor) iterator.next();
5879 if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()){
5880 tdSet.add(tempDescriptor);
5884 return tdSet.size();
5887 private String calculateSizeOfSESEParamSize(FlatSESEEnterNode fsen){
5888 HashMap <String,Integer> map=new HashMap();
5889 HashSet <TempDescriptor> processed=new HashSet<TempDescriptor>();
5892 // space for all in and out set primitives
5893 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
5894 inSetAndOutSet.addAll( fsen.getInVarSet() );
5895 inSetAndOutSet.addAll( fsen.getOutVarSet() );
5897 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
5899 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
5900 while( itr.hasNext() ) {
5901 TempDescriptor temp = itr.next();
5902 TypeDescriptor type = temp.getType();
5903 if( !type.isPtr() ) {
5904 inSetAndOutSetPrims.add( temp );
5908 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
5909 while( itrPrims.hasNext() ) {
5910 TempDescriptor temp = itrPrims.next();
5911 TypeDescriptor type = temp.getType();
5912 if(type.isPrimitive()){
5913 Integer count=map.get(type.getSymbol());
5915 count=new Integer(1);
5916 map.put(type.getSymbol(), count);
5918 map.put(type.getSymbol(), new Integer(count.intValue()+1));
5923 Set<String> keySet=map.keySet();
5924 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
5925 String key = (String) iterator.next();
5926 rtr+="+sizeof("+key+")*"+map.get(key);