2 import IR.Tree.Modifiers;
3 import IR.Tree.FlagExpressionNode;
4 import IR.Tree.DNFFlag;
5 import IR.Tree.DNFFlagAtom;
6 import IR.Tree.TagExpressionList;
7 import IR.Tree.OffsetNode;
14 import Analysis.TaskStateAnalysis.FlagState;
15 import Analysis.TaskStateAnalysis.FlagComparator;
16 import Analysis.TaskStateAnalysis.OptionalTaskDescriptor;
17 import Analysis.TaskStateAnalysis.Predicate;
18 import Analysis.TaskStateAnalysis.SafetyAnalysis;
19 import Analysis.TaskStateAnalysis.TaskIndex;
20 import Analysis.Locality.LocalityAnalysis;
21 import Analysis.Locality.LocalityBinding;
22 import Analysis.Locality.DiscoverConflicts;
23 import Analysis.Locality.DCWrapper;
24 import Analysis.Locality.DelayComputation;
25 import Analysis.Locality.BranchAnalysis;
26 import Analysis.CallGraph.CallGraph;
27 import Analysis.Disjoint.AllocSite;
28 import Analysis.Disjoint.Effect;
29 import Analysis.Disjoint.ReachGraph;
30 import Analysis.Disjoint.Taint;
31 import Analysis.OoOJava.OoOJavaAnalysis;
32 import Analysis.Prefetch.*;
33 import Analysis.Loops.WriteBarrier;
34 import Analysis.Loops.GlobalFieldType;
35 import Analysis.Locality.TypeAnalysis;
36 import Analysis.MLP.ConflictGraph;
37 import Analysis.MLP.ConflictNode;
38 import Analysis.MLP.MLPAnalysis;
39 import Analysis.MLP.ParentChildConflictsMap;
40 import Analysis.MLP.SESELock;
41 import Analysis.MLP.SESEWaitingQueue;
42 import Analysis.MLP.VariableSourceToken;
43 import Analysis.MLP.VSTWrapper;
44 import Analysis.MLP.CodePlan;
45 import Analysis.MLP.SESEandAgePair;
46 import Analysis.MLP.WaitingElement;
48 public class BuildCode {
51 Hashtable paramstable;
56 String localsprefix="___locals___";
57 String localsprefixaddr="&"+localsprefix;
58 String localsprefixderef=localsprefix+".";
59 String fcrevert="___fcrevert___";
60 String paramsprefix="___params___";
61 String oidstr="___nextobject___";
62 String nextobjstr="___nextobject___";
63 String localcopystr="___localcopy___";
64 public static boolean GENERATEPRECISEGC=false;
65 public static String PREFIX="";
66 public static String arraytype="ArrayObject";
67 public static int flagcount = 0;
70 protected int maxtaskparams=0;
71 private int maxcount=0;
72 ClassDescriptor[] cdarray;
73 TypeDescriptor[] arraytable;
74 LocalityAnalysis locality;
75 Hashtable<LocalityBinding, TempDescriptor> reverttable;
76 Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>> backuptable;
81 String maxTaskRecSizeStr="__maxTaskRecSize___";
82 String mlperrstr = "if(status != 0) { "+
83 "sprintf(errmsg, \"MLP error at %s:%d\", __FILE__, __LINE__); "+
84 "perror(errmsg); exit(-1); }";
85 boolean nonSESEpass=true;
86 RuntimeConflictResolver rcr = null;
89 DiscoverConflicts recorddc;
94 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa) {
95 this(st, temptovar, typeutil, null, sa, pa, null, null);
98 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa, OoOJavaAnalysis oooa) {
99 this(st, temptovar, typeutil, null, sa, pa, mlpa, oooa);
102 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, PrefetchAnalysis pa, MLPAnalysis mlpa, OoOJavaAnalysis oooa) {
103 this(st, temptovar, typeutil, locality, null, pa, mlpa, oooa);
106 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa, OoOJavaAnalysis oooa) {
112 callgraph=new CallGraph(state);
114 oidstr="___objlocation___";
115 this.temptovar=temptovar;
116 paramstable=new Hashtable();
117 tempstable=new Hashtable();
118 fieldorder=new Hashtable();
119 flagorder=new Hashtable();
120 this.typeutil=typeutil;
121 virtualcalls=new Virtual(state,locality);
122 if (locality!=null) {
123 this.locality=locality;
124 this.reverttable=new Hashtable<LocalityBinding, TempDescriptor>();
125 this.backuptable=new Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>>();
126 this.wb=new WriteBarrier(locality, st);
128 if (state.SINGLETM&&state.DCOPTS) {
129 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
130 GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
131 this.dc=new DiscoverConflicts(locality, st, typeanalysis, gft);
134 if (state.DELAYCOMP) {
135 //TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
136 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
137 GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
138 delaycomp=new DCWrapper(locality, st, typeanalysis, gft);
139 dc=delaycomp.getConflicts();
140 recorddc=new DiscoverConflicts(locality, st, typeanalysis, delaycomp.getCannotDelayMap(), true, true, null);
141 recorddc.doAnalysis();
145 /** The buildCode method outputs C code for all the methods. The Flat
146 * versions of the methods must already be generated and stored in
147 * the State object. */
148 PrintWriter outsandbox=null;
150 public void buildCode() {
151 /* Create output streams to write to */
152 PrintWriter outclassdefs=null;
153 PrintWriter outstructs=null;
154 PrintWriter outrepairstructs=null;
155 PrintWriter outmethodheader=null;
156 PrintWriter outmethod=null;
157 PrintWriter outvirtual=null;
158 PrintWriter outtask=null;
159 PrintWriter outtaskdefs=null;
160 PrintWriter outoptionalarrays=null;
161 PrintWriter optionalheaders=null;
165 outsandbox=new PrintWriter(new FileOutputStream(PREFIX+"sandboxdefs.c"), true);
167 outstructs=new PrintWriter(new FileOutputStream(PREFIX+"structdefs.h"), true);
168 outmethodheader=new PrintWriter(new FileOutputStream(PREFIX+"methodheaders.h"), true);
169 outclassdefs=new PrintWriter(new FileOutputStream(PREFIX+"classdefs.h"), true);
170 outmethod=new PrintWriter(new FileOutputStream(PREFIX+"methods.c"), true);
171 outvirtual=new PrintWriter(new FileOutputStream(PREFIX+"virtualtable.h"), true);
173 outtask=new PrintWriter(new FileOutputStream(PREFIX+"task.h"), true);
174 outtaskdefs=new PrintWriter(new FileOutputStream(PREFIX+"taskdefs.c"), true);
175 if (state.OPTIONAL) {
176 outoptionalarrays=new PrintWriter(new FileOutputStream(PREFIX+"optionalarrays.c"), true);
177 optionalheaders=new PrintWriter(new FileOutputStream(PREFIX+"optionalstruct.h"), true);
180 if (state.structfile!=null) {
181 outrepairstructs=new PrintWriter(new FileOutputStream(PREFIX+state.structfile+".struct"), true);
183 } catch (Exception e) {
188 /* Build the virtual dispatch tables */
189 buildVirtualTables(outvirtual);
191 /* Output includes */
192 outmethodheader.println("#ifndef METHODHEADERS_H");
193 outmethodheader.println("#define METHODHEADERS_H");
194 outmethodheader.println("#include \"structdefs.h\"");
196 outmethodheader.println("#include \"dstm.h\"");
198 outmethodheader.println("#include \"sandbox.h\"");
200 if (state.EVENTMONITOR) {
201 outmethodheader.println("#include \"monitor.h\"");
203 if (state.SINGLETM) {
204 outmethodheader.println("#include \"tm.h\"");
205 outmethodheader.println("#include \"delaycomp.h\"");
206 outmethodheader.println("#include \"inlinestm.h\"");
208 if (state.ABORTREADERS) {
209 outmethodheader.println("#include \"abortreaders.h\"");
210 outmethodheader.println("#include <setjmp.h>");
212 if (state.MLP || state.OOOJAVA) {
213 outmethodheader.println("#include <stdlib.h>");
214 outmethodheader.println("#include <stdio.h>");
215 outmethodheader.println("#include <string.h>");
216 outmethodheader.println("#include \"mlp_runtime.h\"");
217 outmethodheader.println("#include \"psemaphore.h\"");
218 outmethodheader.println("#include \"memPool.h\"");
220 // spit out a global to inform all worker threads with
221 // the maximum size is for any task record
222 outmethodheader.println("extern int "+maxTaskRecSizeStr+";");
225 /* Output Structures */
226 outputStructs(outstructs);
228 // Output the C class declarations
229 // These could mutually reference each other
232 outclassdefs.println("#ifndef __CLASSDEF_H_");
233 outclassdefs.println("#define __CLASSDEF_H_");
234 outputClassDeclarations(outclassdefs);
236 // Output function prototypes and structures for parameters
237 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
238 while(it.hasNext()) {
239 ClassDescriptor cn=(ClassDescriptor)it.next();
240 generateCallStructs(cn, outclassdefs, outstructs, outmethodheader);
242 outclassdefs.println("#endif");
243 outclassdefs.close();
246 /* Map flags to integers */
247 /* The runtime keeps track of flags using these integers */
248 it=state.getClassSymbolTable().getDescriptorsIterator();
249 while(it.hasNext()) {
250 ClassDescriptor cn=(ClassDescriptor)it.next();
254 generateTaskStructs(outstructs, outmethodheader);
256 /* Outputs generic task structures if this is a task
258 outputTaskTypes(outtask);
261 if( state.MLP || state.OOOJAVA) {
262 // have to initialize some SESE compiler data before
263 // analyzing normal methods, which must happen before
264 // generating SESE internal code
266 Iterator<FlatSESEEnterNode> seseit;
268 seseit=mlpa.getAllSESEs().iterator();
270 seseit=oooa.getAllSESEs().iterator();
273 //TODO signal the object that will report errors
276 rcr = new RuntimeConflictResolver(PREFIX);
278 catch (FileNotFoundException e) {
279 System.out.println("Runtime Conflict Resolver could not create output file.");
283 while(seseit.hasNext()){
284 FlatSESEEnterNode fsen = seseit.next();
285 initializeSESE( fsen );
287 if(state.RCR && rcr != null){
288 Analysis.OoOJava.ConflictGraph conflictGraph;
289 Hashtable<Taint, Set<Effect>> conflicts;
290 if(!fsen.getIsCallerSESEplaceholder() && fsen.getParent()!=null &&
291 (conflictGraph = oooa.getConflictGraph(fsen.getParent())) != null &&
292 (conflicts = conflictGraph.getConflictEffectSet(fsen)) != null){
294 FlatMethod fm=fsen.getfmEnclosing();
297 ReachGraph rg=oooa.getDisjointAnalysis().getReachGraph(fm.getMethod());
300 rg.writeGraph("RCR_RG_SESE_DEBUG");
304 Hashtable<Taint, Set<Effect>> effects=oooa.getDisjointAnalysis().getEffectsAnalysis().get(fsen);
306 //rcr.traverseSESEBlock(fsen, effects, conflicts, rg);
312 /* Build the actual methods */
313 outputMethods(outmethod);
315 // Output function prototypes and structures for SESE's and code
316 if( state.MLP || state.OOOJAVA ) {
318 // spit out a global to inform all worker threads with
319 // the maximum size is for any task record
320 outmethod.println("int "+maxTaskRecSizeStr+" = 0;");
322 // used to differentiate, during code generation, whether we are
323 // passing over SESE body code, or non-SESE code
326 // first generate code for each sese's internals
327 Iterator<FlatSESEEnterNode> seseit;
329 seseit=mlpa.getAllSESEs().iterator();
331 seseit=oooa.getAllSESEs().iterator();
334 while(seseit.hasNext()) {
335 FlatSESEEnterNode fsen = seseit.next();
336 generateMethodSESE(fsen, null, outstructs, outmethodheader, outmethod);
339 // then write the invokeSESE switch to decouple scheduler
340 // from having to do unique details of sese invocation
341 generateSESEinvocationMethod(outmethodheader, outmethod);
345 /* Output code for tasks */
346 outputTaskCode(outtaskdefs, outmethod);
348 /* Record maximum number of task parameters */
349 outstructs.println("#define MAXTASKPARAMS "+maxtaskparams);
350 } else if (state.main!=null) {
351 /* Generate main method */
352 outputMainMethod(outmethod);
355 /* Generate information for task with optional parameters */
356 if (state.TASK&&state.OPTIONAL) {
357 generateOptionalArrays(outoptionalarrays, optionalheaders, state.getAnalysisResult(), state.getOptionalTaskDescriptors());
358 outoptionalarrays.close();
361 /* Output structure definitions for repair tool */
362 if (state.structfile!=null) {
363 buildRepairStructs(outrepairstructs);
364 outrepairstructs.close();
368 outmethodheader.println("#endif");
369 outmethodheader.close();
371 outstructs.println("#endif");
375 System.out.println("Runtime Conflict Resolver Done.");
380 /* This code just generates the main C method for java programs.
381 * The main C method packs up the arguments into a string array
382 * and passes it to the java main method. */
384 private void outputMainMethod(PrintWriter outmethod) {
385 outmethod.println("int main(int argc, const char *argv[]) {");
386 outmethod.println(" int i;");
388 if (state.MLP || state.OOOJAVA) {
390 // do a calculation to determine which task record
391 // is the largest, store that as a global value for
392 // allocating records
393 Iterator<FlatSESEEnterNode> seseit;
395 seseit=mlpa.getAllSESEs().iterator();
397 seseit=oooa.getAllSESEs().iterator();
399 while(seseit.hasNext()){
400 FlatSESEEnterNode fsen = seseit.next();
401 outmethod.println("if( sizeof( "+fsen.getSESErecordName()+
402 " ) > "+maxTaskRecSizeStr+
403 " ) { "+maxTaskRecSizeStr+
404 " = sizeof( "+fsen.getSESErecordName()+
408 outmethod.println(" runningSESE = NULL;");
410 outmethod.println(" workScheduleInit( "+state.MLP_NUMCORES+", invokeSESEmethod );");
412 //initializes data structures needed for the RCR traverser
414 outmethod.println(" initializeStructsRCR();");
419 if (state.DSMRECOVERYSTATS) {
420 outmethod.println("#ifdef RECOVERYSTATS \n");
421 outmethod.println("handle();\n");
422 outmethod.println("#endif\n");
424 outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n");
425 outmethod.println("handle();\n");
426 outmethod.println("#endif\n");
430 if (state.THREAD||state.DSM||state.SINGLETM) {
431 outmethod.println("initializethreads();");
434 outmethod.println("if (dstmStartup(argv[1])) {");
435 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
436 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-2);");
438 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-2);");
441 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
442 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1);");
444 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1);");
448 outmethod.println(" for(i=2;i<argc;i++) {");
450 outmethod.println(" for(i=1;i<argc;i++) {");
451 outmethod.println(" int length=strlen(argv[i]);");
452 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
453 outmethod.println(" struct ___String___ *newstring=NewString(NULL, argv[i], length);");
455 outmethod.println(" struct ___String___ *newstring=NewString(argv[i], length);");
458 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-2]=newstring;");
460 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-1]=newstring;");
461 outmethod.println(" }");
463 MethodDescriptor md=typeutil.getMain();
464 ClassDescriptor cd=typeutil.getMainClass();
466 outmethod.println(" {");
467 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
468 if (state.DSM||state.SINGLETM) {
469 outmethod.print(" struct "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
471 outmethod.print(" struct "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
472 outmethod.println("1, NULL,"+"stringarray};");
473 if (state.DSM||state.SINGLETM)
474 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
476 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
478 if (state.DSM||state.SINGLETM)
479 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
481 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
483 outmethod.println(" }");
486 outmethod.println("}");
489 if (state.THREAD||state.DSM||state.SINGLETM) {
490 outmethod.println("pthread_mutex_lock(&gclistlock);");
491 outmethod.println("threadcount--;");
492 outmethod.println("pthread_cond_signal(&gccond);");
493 outmethod.println("pthread_mutex_unlock(&gclistlock);");
496 if (state.DSM||state.SINGLETM) {
497 //outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n");
498 outmethod.println("#if defined(TRANSSTATS) \n");
499 outmethod.println("printf(\"****** Transaction Stats ******\\n\");");
500 outmethod.println("printf(\"numTransCommit= %d\\n\", numTransCommit);");
501 outmethod.println("printf(\"numTransAbort= %d\\n\", numTransAbort);");
502 outmethod.println("printf(\"nSoftAbort= %d\\n\", nSoftAbort);");
504 outmethod.println("printf(\"nchashSearch= %d\\n\", nchashSearch);");
505 outmethod.println("printf(\"nmhashSearch= %d\\n\", nmhashSearch);");
506 outmethod.println("printf(\"nprehashSearch= %d\\n\", nprehashSearch);");
507 outmethod.println("printf(\"ndirtyCacheObj= %d\\n\", ndirtyCacheObj);");
508 outmethod.println("printf(\"nRemoteReadSend= %d\\n\", nRemoteSend);");
509 outmethod.println("printf(\"bytesSent= %d\\n\", bytesSent);");
510 outmethod.println("printf(\"bytesRecv= %d\\n\", bytesRecv);");
511 outmethod.println("printf(\"totalObjSize= %d\\n\", totalObjSize);");
512 outmethod.println("printf(\"sendRemoteReq= %d\\n\", sendRemoteReq);");
513 outmethod.println("printf(\"getResponse= %d\\n\", getResponse);");
514 } else if (state.SINGLETM) {
515 outmethod.println("printf(\"nSoftAbortAbort= %d\\n\", nSoftAbortAbort);");
516 outmethod.println("printf(\"nSoftAbortCommit= %d\\n\", nSoftAbortCommit);");
517 outmethod.println("#ifdef STMSTATS\n");
518 outmethod.println("for(i=0; i<TOTALNUMCLASSANDARRAY; i++) {\n");
519 outmethod.println(" printf(\"typesCausingAbort[%2d] numaccess= %5d numabort= %3d\\n\", i, typesCausingAbort[i].numaccess, typesCausingAbort[i].numabort);\n");
520 outmethod.println("}\n");
521 outmethod.println("#endif\n");
522 outmethod.println("fflush(stdout);");
524 outmethod.println("#endif\n");
527 if (state.EVENTMONITOR) {
528 outmethod.println("dumpdata();");
531 if (state.THREAD||state.SINGLETM)
532 outmethod.println("pthread_exit(NULL);");
534 if (state.MLP || state.OOOJAVA ) {
535 outmethod.println(" workScheduleBegin();");
538 outmethod.println("}");
541 /* This method outputs code for each task. */
543 private void outputTaskCode(PrintWriter outtaskdefs, PrintWriter outmethod) {
544 /* Compile task based program */
545 outtaskdefs.println("#include \"task.h\"");
546 outtaskdefs.println("#include \"methodheaders.h\"");
547 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
548 while(taskit.hasNext()) {
549 TaskDescriptor td=(TaskDescriptor)taskit.next();
550 FlatMethod fm=state.getMethodFlat(td);
551 generateFlatMethod(fm, null, outmethod);
552 generateTaskDescriptor(outtaskdefs, fm, td);
555 //Output task descriptors
556 taskit=state.getTaskSymbolTable().getDescriptorsIterator();
557 outtaskdefs.println("struct taskdescriptor * taskarray[]= {");
559 while(taskit.hasNext()) {
560 TaskDescriptor td=(TaskDescriptor)taskit.next();
564 outtaskdefs.println(",");
565 outtaskdefs.print("&task_"+td.getSafeSymbol());
567 outtaskdefs.println("};");
569 outtaskdefs.println("int numtasks="+state.getTaskSymbolTable().getValueSet().size()+";");
572 /* This method outputs most of the methods.c file. This includes
573 * some standard includes and then an array with the sizes of
574 * objets and array that stores supertype and then the code for
575 * the Java methods.. */
577 protected void outputMethods(PrintWriter outmethod) {
578 outmethod.println("#include \"methodheaders.h\"");
579 outmethod.println("#include \"virtualtable.h\"");
580 outmethod.println("#include \"runtime.h\"");
582 // always include: compiler directives will leave out
583 // instrumentation when option is not set
584 outmethod.println("#include \"coreprof/coreprof.h\"");
587 outmethod.println("#include \"sandboxdefs.c\"");
590 outmethod.println("#include \"addPrefetchEnhance.h\"");
591 outmethod.println("#include \"localobjects.h\"");
593 if (state.FASTCHECK) {
594 outmethod.println("#include \"localobjects.h\"");
596 if(state.MULTICORE) {
597 outmethod.println("#include \"task.h\"");
598 outmethod.println("#include \"multicoreruntime.h\"");
599 outmethod.println("#include \"runtime_arch.h\"");
601 if (state.THREAD||state.DSM||state.SINGLETM)
602 outmethod.println("#include <thread.h>");
603 if (state.main!=null) {
604 outmethod.println("#include <string.h>");
606 if (state.CONSCHECK) {
607 outmethod.println("#include \"checkers.h\"");
609 if (state.MLP || state.OOOJAVA ) {
610 outmethod.println("#include <stdlib.h>");
611 outmethod.println("#include <stdio.h>");
612 outmethod.println("#include \"mlp_runtime.h\"");
613 outmethod.println("#include \"psemaphore.h\"");
616 outmethod.println("#include \"RuntimeConflictResolver.h\"");
620 //Store the sizes of classes & array elements
621 generateSizeArray(outmethod);
623 //Store table of supertypes
624 generateSuperTypeTable(outmethod);
626 //Store the layout of classes
627 generateLayoutStructs(outmethod);
629 /* Generate code for methods */
630 if (state.DSM||state.SINGLETM) {
631 for(Iterator<LocalityBinding> lbit=locality.getLocalityBindings().iterator(); lbit.hasNext();) {
632 LocalityBinding lb=lbit.next();
633 MethodDescriptor md=lb.getMethod();
634 FlatMethod fm=state.getMethodFlat(md);
636 if (!md.getModifiers().isNative()) {
637 generateFlatMethod(fm, lb, outmethod);
638 //System.out.println("fm= " + fm + " md= " + md);
642 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
643 while(classit.hasNext()) {
644 ClassDescriptor cn=(ClassDescriptor)classit.next();
645 Iterator methodit=cn.getMethods();
646 while(methodit.hasNext()) {
647 /* Classify parameters */
648 MethodDescriptor md=(MethodDescriptor)methodit.next();
649 FlatMethod fm=state.getMethodFlat(md);
650 if (!md.getModifiers().isNative()) {
651 generateFlatMethod(fm, null, outmethod);
658 protected void outputStructs(PrintWriter outstructs) {
659 outstructs.println("#ifndef STRUCTDEFS_H");
660 outstructs.println("#define STRUCTDEFS_H");
661 outstructs.println("#include \"classdefs.h\"");
662 outstructs.println("#ifndef INTPTR");
663 outstructs.println("#ifdef BIT64");
664 outstructs.println("#define INTPTR long");
665 outstructs.println("#else");
666 outstructs.println("#define INTPTR int");
667 outstructs.println("#endif");
668 outstructs.println("#endif");
669 if( state.MLP || state.OOOJAVA ) {
670 outstructs.println("#include \"mlp_runtime.h\"");
671 outstructs.println("#include \"psemaphore.h\"");
674 /* Output #defines that the runtime uses to determine type
675 * numbers for various objects it needs */
676 outstructs.println("#define MAXCOUNT "+maxcount);
677 if (state.DSM||state.SINGLETM) {
678 LocalityBinding lbrun=new LocalityBinding(typeutil.getRun(), false);
680 lbrun.setGlobalThis(LocalityAnalysis.GLOBAL);
682 else if (state.SINGLETM) {
683 lbrun.setGlobalThis(LocalityAnalysis.NORMAL);
685 outstructs.println("#define RUNMETHOD "+virtualcalls.getLocalityNumber(lbrun));
689 LocalityBinding lbexecute = new LocalityBinding(typeutil.getExecute(), false);
691 lbexecute.setGlobalThis(LocalityAnalysis.GLOBAL);
692 else if( state.SINGLETM)
693 lbexecute.setGlobalThis(LocalityAnalysis.NORMAL);
694 outstructs.println("#define EXECUTEMETHOD " + virtualcalls.getLocalityNumber(lbexecute));
697 outstructs.println("#define STRINGARRAYTYPE "+
698 (state.getArrayNumber(
699 (new TypeDescriptor(typeutil.getClass(TypeUtil.StringClass))).makeArray(state))+state.numClasses()));
701 outstructs.println("#define OBJECTARRAYTYPE "+
702 (state.getArrayNumber(
703 (new TypeDescriptor(typeutil.getClass(TypeUtil.ObjectClass))).makeArray(state))+state.numClasses()));
706 outstructs.println("#define STRINGTYPE "+typeutil.getClass(TypeUtil.StringClass).getId());
707 outstructs.println("#define CHARARRAYTYPE "+
708 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.CHAR)).makeArray(state))+state.numClasses()));
710 outstructs.println("#define BYTEARRAYTYPE "+
711 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state))+state.numClasses()));
713 outstructs.println("#define BYTEARRAYARRAYTYPE "+
714 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state).makeArray(state))+state.numClasses()));
716 outstructs.println("#define NUMCLASSES "+state.numClasses());
717 int totalClassSize = state.numClasses() + state.numArrays();
718 outstructs.println("#define TOTALNUMCLASSANDARRAY "+ totalClassSize);
720 outstructs.println("#define STARTUPTYPE "+typeutil.getClass(TypeUtil.StartupClass).getId());
721 outstructs.println("#define TAGTYPE "+typeutil.getClass(TypeUtil.TagClass).getId());
722 outstructs.println("#define TAGARRAYTYPE "+
723 (state.getArrayNumber(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)).makeArray(state))+state.numClasses()));
727 protected void outputClassDeclarations(PrintWriter outclassdefs) {
728 if (state.THREAD||state.DSM||state.SINGLETM)
729 outclassdefs.println("#include <pthread.h>");
730 outclassdefs.println("#ifndef INTPTR");
731 outclassdefs.println("#ifdef BIT64");
732 outclassdefs.println("#define INTPTR long");
733 outclassdefs.println("#else");
734 outclassdefs.println("#define INTPTR int");
735 outclassdefs.println("#endif");
736 outclassdefs.println("#endif");
738 outclassdefs.println("#include \"optionalstruct.h\"");
739 outclassdefs.println("struct "+arraytype+";");
740 /* Start by declaring all structs */
741 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
742 while(it.hasNext()) {
743 ClassDescriptor cn=(ClassDescriptor)it.next();
744 outclassdefs.println("struct "+cn.getSafeSymbol()+";");
746 outclassdefs.println("");
747 //Print out definition for array type
748 outclassdefs.println("struct "+arraytype+" {");
749 outclassdefs.println(" int type;");
750 if(state.MLP || state.OOOJAVA ){
751 outclassdefs.println(" int oid;");
752 outclassdefs.println(" int allocsite;");
754 if (state.EVENTMONITOR) {
755 outclassdefs.println(" int objuid;");
758 outclassdefs.println(" pthread_t tid;");
759 outclassdefs.println(" void * lockentry;");
760 outclassdefs.println(" int lockcount;");
763 outclassdefs.println(" int flag;");
764 if(!state.MULTICORE) {
765 outclassdefs.println(" void * flagptr;");
767 outclassdefs.println(" int version;");
768 outclassdefs.println(" int * lock;"); // lock entry for this obj
769 outclassdefs.println(" int mutex;");
770 outclassdefs.println(" int lockcount;");
771 if(state.MULTICOREGC) {
772 outclassdefs.println(" int marked;");
776 outclassdefs.println(" int numfses;");
777 outclassdefs.println(" int * fses;");
780 printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs);
782 if (state.STMARRAY) {
783 outclassdefs.println(" int lowindex;");
784 outclassdefs.println(" int highindex;");
787 outclassdefs.println(" int paddingforarray;");
788 if (state.DUALVIEW) {
789 outclassdefs.println(" int arrayversion;");
792 outclassdefs.println(" int ___length___;");
793 outclassdefs.println("};\n");
794 outclassdefs.println("extern int classsize[];");
795 outclassdefs.println("extern int hasflags[];");
796 outclassdefs.println("extern unsigned INTPTR * pointerarray[];");
797 outclassdefs.println("extern int supertypes[];");
800 /** Prints out definitions for generic task structures */
802 private void outputTaskTypes(PrintWriter outtask) {
803 outtask.println("#ifndef _TASK_H");
804 outtask.println("#define _TASK_H");
805 outtask.println("struct parameterdescriptor {");
806 outtask.println("int type;");
807 outtask.println("int numberterms;");
808 outtask.println("int *intarray;");
809 outtask.println("void * queue;");
810 outtask.println("int numbertags;");
811 outtask.println("int *tagarray;");
812 outtask.println("};");
814 outtask.println("struct taskdescriptor {");
815 outtask.println("void * taskptr;");
816 outtask.println("int numParameters;");
817 outtask.println(" int numTotal;");
818 outtask.println("struct parameterdescriptor **descriptorarray;");
819 outtask.println("char * name;");
820 outtask.println("};");
821 outtask.println("extern struct taskdescriptor * taskarray[];");
822 outtask.println("extern numtasks;");
823 outtask.println("#endif");
827 private void buildRepairStructs(PrintWriter outrepairstructs) {
828 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
829 while(classit.hasNext()) {
830 ClassDescriptor cn=(ClassDescriptor)classit.next();
831 outrepairstructs.println("structure "+cn.getSymbol()+" {");
832 outrepairstructs.println(" int __type__;");
834 outrepairstructs.println(" int __flag__;");
835 if(!state.MULTICORE) {
836 outrepairstructs.println(" int __flagptr__;");
839 printRepairStruct(cn, outrepairstructs);
840 outrepairstructs.println("}\n");
843 for(int i=0; i<state.numArrays(); i++) {
844 TypeDescriptor tdarray=arraytable[i];
845 TypeDescriptor tdelement=tdarray.dereference();
846 outrepairstructs.println("structure "+arraytype+"_"+state.getArrayNumber(tdarray)+" {");
847 outrepairstructs.println(" int __type__;");
848 printRepairStruct(typeutil.getClass(TypeUtil.ObjectClass), outrepairstructs);
849 outrepairstructs.println(" int length;");
851 // Need to add support to repair tool for this
852 if (tdelement.isClass()||tdelement.isArray())
853 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" * elem[this.length];");
855 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" elem[this.length];");
857 outrepairstructs.println("}\n");
861 private void printRepairStruct(ClassDescriptor cn, PrintWriter output) {
862 ClassDescriptor sp=cn.getSuperDesc();
864 printRepairStruct(sp, output);
866 Vector fields=(Vector)fieldorder.get(cn);
868 for(int i=0; i<fields.size(); i++) {
869 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
870 if (fd.getType().isArray()) {
871 output.println(" "+arraytype+"_"+ state.getArrayNumber(fd.getType()) +" * "+fd.getSymbol()+";");
872 } else if (fd.getType().isClass())
873 output.println(" "+fd.getType().getRepairSymbol()+" * "+fd.getSymbol()+";");
874 else if (fd.getType().isFloat())
875 output.println(" int "+fd.getSymbol()+"; /* really float */");
877 output.println(" "+fd.getType().getRepairSymbol()+" "+fd.getSymbol()+";");
881 /** This method outputs TaskDescriptor information */
882 private void generateTaskDescriptor(PrintWriter output, FlatMethod fm, TaskDescriptor task) {
883 for (int i=0; i<task.numParameters(); i++) {
884 VarDescriptor param_var=task.getParameter(i);
885 TypeDescriptor param_type=task.getParamType(i);
886 FlagExpressionNode param_flag=task.getFlag(param_var);
887 TagExpressionList param_tag=task.getTag(param_var);
890 if (param_flag==null) {
891 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
892 output.println("0x0, 0x0 };");
895 DNFFlag dflag=param_flag.getDNF();
896 dnfterms=dflag.size();
898 Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
899 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
900 for(int j=0; j<dflag.size(); j++) {
903 Vector term=dflag.get(j);
906 for(int k=0; k<term.size(); k++) {
907 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
908 FlagDescriptor fd=dfa.getFlag();
909 boolean negated=dfa.getNegated();
910 int flagid=1<<((Integer)flags.get(fd)).intValue();
915 output.print("0x"+Integer.toHexString(andmask)+", 0x"+Integer.toHexString(checkmask));
917 output.println("};");
920 output.println("int parametertag_"+i+"_"+task.getSafeSymbol()+"[]={");
921 //BUG...added next line to fix, test with any task program
923 for(int j=0; j<param_tag.numTags(); j++) {
926 /* for each tag we need */
927 /* which slot it is */
928 /* what type it is */
929 TagVarDescriptor tvd=(TagVarDescriptor)task.getParameterTable().get(param_tag.getName(j));
930 TempDescriptor tmp=param_tag.getTemp(j);
931 int slot=fm.getTagInt(tmp);
932 output.println(slot+", "+state.getTagId(tvd.getTag()));
934 output.println("};");
936 output.println("struct parameterdescriptor parameter_"+i+"_"+task.getSafeSymbol()+"={");
937 output.println("/* type */"+param_type.getClassDesc().getId()+",");
938 output.println("/* number of DNF terms */"+dnfterms+",");
939 output.println("parameterdnf_"+i+"_"+task.getSafeSymbol()+",");
940 output.println("0,");
941 //BUG, added next line to fix and else statement...test
942 //with any task program
944 output.println("/* number of tags */"+param_tag.numTags()+",");
946 output.println("/* number of tags */ 0,");
947 output.println("parametertag_"+i+"_"+task.getSafeSymbol());
948 output.println("};");
952 output.println("struct parameterdescriptor * parameterdescriptors_"+task.getSafeSymbol()+"[] = {");
953 for (int i=0; i<task.numParameters(); i++) {
956 output.print("¶meter_"+i+"_"+task.getSafeSymbol());
958 output.println("};");
960 output.println("struct taskdescriptor task_"+task.getSafeSymbol()+"={");
961 output.println("&"+task.getSafeSymbol()+",");
962 output.println("/* number of parameters */" +task.numParameters() + ",");
963 int numtotal=task.numParameters()+fm.numTags();
964 output.println("/* number total parameters */" +numtotal + ",");
965 output.println("parameterdescriptors_"+task.getSafeSymbol()+",");
966 output.println("\""+task.getSymbol()+"\"");
967 output.println("};");
971 /** The buildVirtualTables method outputs the virtual dispatch
972 * tables for methods. */
974 protected void buildVirtualTables(PrintWriter outvirtual) {
975 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
976 while(classit.hasNext()) {
977 ClassDescriptor cd=(ClassDescriptor)classit.next();
978 if (virtualcalls.getMethodCount(cd)>maxcount)
979 maxcount=virtualcalls.getMethodCount(cd);
981 MethodDescriptor[][] virtualtable=null;
982 LocalityBinding[][] lbvirtualtable=null;
983 if (state.DSM||state.SINGLETM)
984 lbvirtualtable=new LocalityBinding[state.numClasses()+state.numArrays()][maxcount];
986 virtualtable=new MethodDescriptor[state.numClasses()+state.numArrays()][maxcount];
988 /* Fill in virtual table */
989 classit=state.getClassSymbolTable().getDescriptorsIterator();
990 while(classit.hasNext()) {
991 ClassDescriptor cd=(ClassDescriptor)classit.next();
992 if (state.DSM||state.SINGLETM)
993 fillinRow(cd, lbvirtualtable, cd.getId());
995 fillinRow(cd, virtualtable, cd.getId());
998 ClassDescriptor objectcd=typeutil.getClass(TypeUtil.ObjectClass);
999 Iterator arrayit=state.getArrayIterator();
1000 while(arrayit.hasNext()) {
1001 TypeDescriptor td=(TypeDescriptor)arrayit.next();
1002 int id=state.getArrayNumber(td);
1003 if (state.DSM||state.SINGLETM)
1004 fillinRow(objectcd, lbvirtualtable, id+state.numClasses());
1006 fillinRow(objectcd, virtualtable, id+state.numClasses());
1009 outvirtual.print("void * virtualtable[]={");
1010 boolean needcomma=false;
1011 for(int i=0; i<state.numClasses()+state.numArrays(); i++) {
1012 for(int j=0; j<maxcount; j++) {
1014 outvirtual.print(", ");
1015 if ((state.DSM||state.SINGLETM)&&lbvirtualtable[i][j]!=null) {
1016 LocalityBinding lb=lbvirtualtable[i][j];
1017 MethodDescriptor md=lb.getMethod();
1018 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
1019 } else if (!(state.DSM||state.SINGLETM)&&virtualtable[i][j]!=null) {
1020 MethodDescriptor md=virtualtable[i][j];
1021 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
1023 outvirtual.print("0");
1027 outvirtual.println("");
1029 outvirtual.println("};");
1033 private void fillinRow(ClassDescriptor cd, MethodDescriptor[][] virtualtable, int rownum) {
1034 /* Get inherited methods */
1035 if (cd.getSuperDesc()!=null)
1036 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
1037 /* Override them with our methods */
1038 for(Iterator it=cd.getMethods(); it.hasNext();) {
1039 MethodDescriptor md=(MethodDescriptor)it.next();
1040 if (md.isStatic()||md.getReturnType()==null)
1042 int methodnum=virtualcalls.getMethodNumber(md);
1043 virtualtable[rownum][methodnum]=md;
1047 private void fillinRow(ClassDescriptor cd, LocalityBinding[][] virtualtable, int rownum) {
1048 /* Get inherited methods */
1049 if (cd.getSuperDesc()!=null)
1050 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
1051 /* Override them with our methods */
1052 if (locality.getClassBindings(cd)!=null)
1053 for(Iterator<LocalityBinding> lbit=locality.getClassBindings(cd).iterator(); lbit.hasNext();) {
1054 LocalityBinding lb=lbit.next();
1055 MethodDescriptor md=lb.getMethod();
1056 //Is the method static or a constructor
1057 if (md.isStatic()||md.getReturnType()==null)
1059 int methodnum=virtualcalls.getLocalityNumber(lb);
1060 virtualtable[rownum][methodnum]=lb;
1064 /** Generate array that contains the sizes of class objects. The
1065 * object allocation functions in the runtime use this
1068 private void generateSizeArray(PrintWriter outclassdefs) {
1069 outclassdefs.print("extern struct prefetchCountStats * evalPrefetch;\n");
1070 outclassdefs.print("#ifdef TRANSSTATS \n");
1071 outclassdefs.print("extern int numTransAbort;\n");
1072 outclassdefs.print("extern int numTransCommit;\n");
1073 outclassdefs.print("extern int nSoftAbort;\n");
1075 outclassdefs.print("extern int nchashSearch;\n");
1076 outclassdefs.print("extern int nmhashSearch;\n");
1077 outclassdefs.print("extern int nprehashSearch;\n");
1078 outclassdefs.print("extern int ndirtyCacheObj;\n");
1079 outclassdefs.print("extern int nRemoteSend;\n");
1080 outclassdefs.print("extern int sendRemoteReq;\n");
1081 outclassdefs.print("extern int getResponse;\n");
1082 outclassdefs.print("extern int bytesSent;\n");
1083 outclassdefs.print("extern int bytesRecv;\n");
1084 outclassdefs.print("extern int totalObjSize;\n");
1085 outclassdefs.print("extern void handle();\n");
1086 } else if (state.SINGLETM) {
1087 outclassdefs.println("extern int nSoftAbortAbort;");
1088 outclassdefs.println("extern int nSoftAbortCommit;");
1089 outclassdefs.println("#ifdef STMSTATS\n");
1090 outclassdefs.println("extern objtypestat_t typesCausingAbort[];");
1091 outclassdefs.println("#endif\n");
1093 outclassdefs.print("#endif\n");
1095 outclassdefs.print("int numprefetchsites = " + pa.prefetchsiteid + ";\n");
1096 if(this.state.MLP || state.OOOJAVA ){
1097 outclassdefs.print("extern __thread int oid;\n");
1098 outclassdefs.print("extern int numWorkers;\n");
1101 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1102 cdarray=new ClassDescriptor[state.numClasses()];
1104 while(it.hasNext()) {
1105 ClassDescriptor cd=(ClassDescriptor)it.next();
1106 cdarray[cd.getId()]=cd;
1109 arraytable=new TypeDescriptor[state.numArrays()];
1111 Iterator arrayit=state.getArrayIterator();
1112 while(arrayit.hasNext()) {
1113 TypeDescriptor td=(TypeDescriptor)arrayit.next();
1114 int id=state.getArrayNumber(td);
1120 /* Print out types */
1121 outclassdefs.println("/* ");
1122 for(int i=0; i<state.numClasses(); i++) {
1123 ClassDescriptor cd=cdarray[i];
1125 outclassdefs.println("NULL " + i);
1127 outclassdefs.println(cd +" "+i);
1131 for(int i=0; i<state.numArrays(); i++) {
1132 TypeDescriptor arraytd=arraytable[i];
1133 outclassdefs.println(arraytd.toPrettyString() +" "+(i+state.numClasses()));
1136 outclassdefs.println("*/");
1139 outclassdefs.print("int classsize[]={");
1141 boolean needcomma=false;
1142 for(int i=0; i<state.numClasses(); i++) {
1144 outclassdefs.print(", ");
1146 outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")");
1148 outclassdefs.print("0");
1154 for(int i=0; i<state.numArrays(); i++) {
1156 outclassdefs.print(", ");
1157 TypeDescriptor tdelement=arraytable[i].dereference();
1158 if (tdelement.isArray()||tdelement.isClass())
1159 outclassdefs.print("sizeof(void *)");
1161 outclassdefs.print("sizeof("+tdelement.getSafeSymbol()+")");
1165 outclassdefs.println("};");
1167 ClassDescriptor objectclass=typeutil.getClass(TypeUtil.ObjectClass);
1169 outclassdefs.print("int typearray[]={");
1170 for(int i=0; i<state.numClasses(); i++) {
1171 ClassDescriptor cd=cdarray[i];
1172 ClassDescriptor supercd=i>0?cd.getSuperDesc():null;
1174 outclassdefs.print(", ");
1176 outclassdefs.print("-1");
1178 outclassdefs.print(supercd.getId());
1182 for(int i=0; i<state.numArrays(); i++) {
1183 TypeDescriptor arraytd=arraytable[i];
1184 ClassDescriptor arraycd=arraytd.getClassDesc();
1185 if (arraycd==null) {
1187 outclassdefs.print(", ");
1188 outclassdefs.print(objectclass.getId());
1192 ClassDescriptor cd=arraycd.getSuperDesc();
1195 TypeDescriptor supertd=new TypeDescriptor(cd);
1196 supertd.setArrayCount(arraytd.getArrayCount());
1197 type=state.getArrayNumber(supertd);
1199 type+=state.numClasses();
1202 cd=cd.getSuperDesc();
1205 outclassdefs.print(", ");
1206 outclassdefs.print(type);
1210 outclassdefs.println("};");
1215 outclassdefs.print("int typearray2[]={");
1216 for(int i=0; i<state.numArrays(); i++) {
1217 TypeDescriptor arraytd=arraytable[i];
1218 ClassDescriptor arraycd=arraytd.getClassDesc();
1219 if (arraycd==null) {
1221 outclassdefs.print(", ");
1222 outclassdefs.print("-1");
1226 ClassDescriptor cd=arraycd.getSuperDesc();
1227 int level=arraytd.getArrayCount()-1;
1229 for(; level>0; level--) {
1230 TypeDescriptor supertd=new TypeDescriptor(objectclass);
1231 supertd.setArrayCount(level);
1232 type=state.getArrayNumber(supertd);
1234 type+=state.numClasses();
1239 outclassdefs.print(", ");
1240 outclassdefs.print(type);
1244 outclassdefs.println("};");
1247 /** Constructs params and temp objects for each method or task.
1248 * These objects tell the compiler which temps need to be
1251 protected void generateTempStructs(FlatMethod fm, LocalityBinding lb) {
1252 MethodDescriptor md=fm.getMethod();
1253 TaskDescriptor task=fm.getTask();
1254 Set<TempDescriptor> saveset=lb!=null ? locality.getTempSet(lb) : null;
1255 ParamsObject objectparams=md!=null ? new ParamsObject(md,tag++) : new ParamsObject(task, tag++);
1257 paramstable.put(lb, objectparams);
1258 backuptable.put(lb, new Hashtable<TempDescriptor, TempDescriptor>());
1259 } else if (md!=null)
1260 paramstable.put(md, objectparams);
1262 paramstable.put(task, objectparams);
1264 for(int i=0; i<fm.numParameters(); i++) {
1265 TempDescriptor temp=fm.getParameter(i);
1266 TypeDescriptor type=temp.getType();
1267 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1268 objectparams.addPtr(temp);
1270 objectparams.addPrim(temp);
1271 if(lb!=null&&saveset.contains(temp)) {
1272 backuptable.get(lb).put(temp, temp.createNew());
1276 for(int i=0; i<fm.numTags(); i++) {
1277 TempDescriptor temp=fm.getTag(i);
1278 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1279 objectparams.addPtr(temp);
1281 objectparams.addPrim(temp);
1284 TempObject objecttemps=md!=null ? new TempObject(objectparams,md,tag++) : new TempObject(objectparams, task, tag++);
1286 tempstable.put(lb, objecttemps);
1288 tempstable.put(md, objecttemps);
1290 tempstable.put(task, objecttemps);
1292 for(Iterator nodeit=fm.getNodeSet().iterator(); nodeit.hasNext();) {
1293 FlatNode fn=(FlatNode)nodeit.next();
1294 TempDescriptor[] writes=fn.writesTemps();
1295 for(int i=0; i<writes.length; i++) {
1296 TempDescriptor temp=writes[i];
1297 TypeDescriptor type=temp.getType();
1298 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1299 objecttemps.addPtr(temp);
1301 objecttemps.addPrim(temp);
1302 if(lb!=null&&saveset.contains(temp)&&
1303 !backuptable.get(lb).containsKey(temp))
1304 backuptable.get(lb).put(temp, temp.createNew());
1308 /* Create backup temps */
1310 for(Iterator<TempDescriptor> tmpit=backuptable.get(lb).values().iterator(); tmpit.hasNext();) {
1311 TempDescriptor tmp=tmpit.next();
1312 TypeDescriptor type=tmp.getType();
1313 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1314 objecttemps.addPtr(tmp);
1316 objecttemps.addPrim(tmp);
1318 /* Create temp to hold revert table */
1319 if (state.DSM&&(lb.getHasAtomic()||lb.isAtomic())) {
1320 TempDescriptor reverttmp=new TempDescriptor("revertlist", typeutil.getClass(TypeUtil.ObjectClass));
1321 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1322 objecttemps.addPtr(reverttmp);
1324 objecttemps.addPrim(reverttmp);
1325 reverttable.put(lb, reverttmp);
1330 /** This method outputs the following information about classes
1332 * (1) For classes, what are the locations of pointers.
1333 * (2) For arrays, does the array contain pointers or primitives.
1334 * (3) For classes, does the class contain flags.
1337 private void generateLayoutStructs(PrintWriter output) {
1338 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1339 while(it.hasNext()) {
1340 ClassDescriptor cn=(ClassDescriptor)it.next();
1341 output.println("unsigned INTPTR "+cn.getSafeSymbol()+"_pointers[]={");
1342 Iterator allit=cn.getFieldTable().getAllDescriptorsIterator();
1344 while(allit.hasNext()) {
1345 FieldDescriptor fd=(FieldDescriptor)allit.next();
1346 TypeDescriptor type=fd.getType();
1347 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1352 output.print(count);
1353 allit=cn.getFieldTable().getAllDescriptorsIterator();
1354 while(allit.hasNext()) {
1355 FieldDescriptor fd=(FieldDescriptor)allit.next();
1356 TypeDescriptor type=fd.getType();
1357 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1360 output.println(",");
1361 output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+fd.getSafeSymbol()+"))");
1364 output.println("};");
1366 output.println("unsigned INTPTR * pointerarray[]={");
1367 boolean needcomma=false;
1368 for(int i=0; i<state.numClasses(); i++) {
1369 ClassDescriptor cn=cdarray[i];
1371 output.println(",");
1374 output.print(cn.getSafeSymbol()+"_pointers");
1376 output.print("NULL");
1380 for(int i=0; i<state.numArrays(); i++) {
1382 output.println(", ");
1383 TypeDescriptor tdelement=arraytable[i].dereference();
1384 if (tdelement.isArray()||tdelement.isClass())
1385 output.print("((unsigned INTPTR *)1)");
1391 output.println("};");
1393 output.println("int hasflags[]={");
1394 for(int i=0; i<state.numClasses(); i++) {
1395 ClassDescriptor cn=cdarray[i];
1397 output.println(", ");
1399 if ((cn != null) && (cn.hasFlags()))
1404 output.println("};");
1407 /** Print out table to give us supertypes */
1408 private void generateSuperTypeTable(PrintWriter output) {
1409 output.println("int supertypes[]={");
1410 boolean needcomma=false;
1411 for(int i=0; i<state.numClasses(); i++) {
1412 ClassDescriptor cn=cdarray[i];
1414 output.println(",");
1416 if ((cn != null) && (cn.getSuperDesc()!=null)) {
1417 ClassDescriptor cdsuper=cn.getSuperDesc();
1418 output.print(cdsuper.getId());
1422 output.println("};");
1425 /** Force consistent field ordering between inherited classes. */
1427 private void printClassStruct(ClassDescriptor cn, PrintWriter classdefout) {
1429 ClassDescriptor sp=cn.getSuperDesc();
1431 printClassStruct(sp, classdefout);
1433 if (!fieldorder.containsKey(cn)) {
1434 Vector fields=new Vector();
1435 fieldorder.put(cn,fields);
1436 Vector fieldvec=cn.getFieldVec();
1437 for(int i=0;i<fieldvec.size();i++) {
1438 FieldDescriptor fd=(FieldDescriptor)fieldvec.get(i);
1439 if ((sp==null||!sp.getFieldTable().contains(fd.getSymbol())))
1443 Vector fields=(Vector)fieldorder.get(cn);
1445 for(int i=0; i<fields.size(); i++) {
1446 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
1447 if (fd.getType().isClass()||fd.getType().isArray())
1448 classdefout.println(" struct "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1450 classdefout.println(" "+fd.getType().getSafeSymbol()+" "+fd.getSafeSymbol()+";");
1455 /* Map flags to integers consistently between inherited
1458 protected void mapFlags(ClassDescriptor cn) {
1459 ClassDescriptor sp=cn.getSuperDesc();
1463 if (!flagorder.containsKey(cn)) {
1464 Hashtable flags=new Hashtable();
1465 flagorder.put(cn,flags);
1467 Hashtable superflags=(Hashtable)flagorder.get(sp);
1468 Iterator superflagit=superflags.keySet().iterator();
1469 while(superflagit.hasNext()) {
1470 FlagDescriptor fd=(FlagDescriptor)superflagit.next();
1471 Integer number=(Integer)superflags.get(fd);
1472 flags.put(fd, number);
1473 if ((number.intValue()+1)>max)
1474 max=number.intValue()+1;
1478 Iterator flagit=cn.getFlags();
1479 while(flagit.hasNext()) {
1480 FlagDescriptor fd=(FlagDescriptor)flagit.next();
1481 if (sp==null||!sp.getFlagTable().contains(fd.getSymbol()))
1482 flags.put(fd, new Integer(max++));
1488 /** This function outputs (1) structures that parameters are
1489 * passed in (when PRECISE GC is enabled) and (2) function
1490 * prototypes for the methods */
1492 protected void generateCallStructs(ClassDescriptor cn, PrintWriter classdefout, PrintWriter output, PrintWriter headersout) {
1493 /* Output class structure */
1494 classdefout.println("struct "+cn.getSafeSymbol()+" {");
1495 classdefout.println(" int type;");
1496 if(state.MLP || state.OOOJAVA){
1497 classdefout.println(" int oid;");
1498 classdefout.println(" int allocsite;");
1500 if (state.EVENTMONITOR) {
1501 classdefout.println(" int objuid;");
1504 classdefout.println(" pthread_t tid;");
1505 classdefout.println(" void * lockentry;");
1506 classdefout.println(" int lockcount;");
1510 classdefout.println(" int flag;");
1511 if((!state.MULTICORE) || (cn.getSymbol().equals("TagDescriptor"))) {
1512 classdefout.println(" void * flagptr;");
1513 } else if (state.MULTICORE) {
1514 classdefout.println(" int version;");
1515 classdefout.println(" int * lock;"); // lock entry for this obj
1516 classdefout.println(" int mutex;");
1517 classdefout.println(" int lockcount;");
1518 if(state.MULTICOREGC) {
1519 classdefout.println(" int marked;");
1522 if (state.OPTIONAL) {
1523 classdefout.println(" int numfses;");
1524 classdefout.println(" int * fses;");
1527 printClassStruct(cn, classdefout);
1528 classdefout.println("};\n");
1530 if (state.DSM||state.SINGLETM) {
1531 /* Cycle through LocalityBindings */
1532 HashSet<MethodDescriptor> nativemethods=new HashSet<MethodDescriptor>();
1533 Set<LocalityBinding> lbset=locality.getClassBindings(cn);
1535 for(Iterator<LocalityBinding> lbit=lbset.iterator(); lbit.hasNext();) {
1536 LocalityBinding lb=lbit.next();
1537 MethodDescriptor md=lb.getMethod();
1538 if (md.getModifiers().isNative()) {
1539 //make sure we only print a native method once
1540 if (nativemethods.contains(md)) {
1541 FlatMethod fm=state.getMethodFlat(md);
1542 generateTempStructs(fm, lb);
1545 nativemethods.add(md);
1547 generateMethod(cn, md, lb, headersout, output);
1550 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1551 MethodDescriptor md=(MethodDescriptor)methodit.next();
1552 if (md.getModifiers().isNative()&&!nativemethods.contains(md)) {
1553 //Need to build param structure for library code
1554 FlatMethod fm=state.getMethodFlat(md);
1555 generateTempStructs(fm, null);
1556 generateMethodParam(cn, md, null, output);
1561 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1562 MethodDescriptor md=(MethodDescriptor)methodit.next();
1563 generateMethod(cn, md, null, headersout, output);
1567 private void generateMethodParam(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter output) {
1568 /* Output parameter structure */
1569 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1570 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1571 if ((state.DSM||state.SINGLETM)&&lb!=null)
1572 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1574 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1575 output.println(" int size;");
1576 output.println(" void * next;");
1577 for(int i=0; i<objectparams.numPointers(); i++) {
1578 TempDescriptor temp=objectparams.getPointer(i);
1579 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1581 output.println("};\n");
1585 private void generateMethod(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter headersout, PrintWriter output) {
1586 FlatMethod fm=state.getMethodFlat(md);
1587 generateTempStructs(fm, lb);
1589 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1590 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md);
1592 generateMethodParam(cn, md, lb, output);
1594 /* Output temp structure */
1595 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1596 if (state.DSM||state.SINGLETM)
1597 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1599 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1600 output.println(" int size;");
1601 output.println(" void * next;");
1602 for(int i=0; i<objecttemps.numPointers(); i++) {
1603 TempDescriptor temp=objecttemps.getPointer(i);
1604 if (temp.getType().isNull())
1605 output.println(" void * "+temp.getSafeSymbol()+";");
1607 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1609 output.println("};\n");
1612 /********* Output method declaration ***********/
1613 if (state.DSM||state.SINGLETM) {
1614 headersout.println("#define D"+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1616 headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1618 /* First the return type */
1619 if (md.getReturnType()!=null) {
1620 if (md.getReturnType().isClass()||md.getReturnType().isArray())
1621 headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1623 headersout.print(md.getReturnType().getSafeSymbol()+" ");
1625 //catch the constructor case
1626 headersout.print("void ");
1628 /* Next the method name */
1629 if (state.DSM||state.SINGLETM) {
1630 headersout.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1632 headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1634 boolean printcomma=false;
1635 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1636 if (state.DSM||state.SINGLETM) {
1637 headersout.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1639 headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1643 /* Output parameter list*/
1644 for(int i=0; i<objectparams.numPrimitives(); i++) {
1645 TempDescriptor temp=objectparams.getPrimitive(i);
1647 headersout.print(", ");
1649 if (temp.getType().isClass()||temp.getType().isArray())
1650 headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1652 headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1654 headersout.println(");\n");
1658 /** This function outputs (1) structures that parameters are
1659 * passed in (when PRECISE GC is enabled) and (2) function
1660 * prototypes for the tasks */
1662 private void generateTaskStructs(PrintWriter output, PrintWriter headersout) {
1663 /* Cycle through tasks */
1664 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
1666 while(taskit.hasNext()) {
1667 /* Classify parameters */
1668 TaskDescriptor task=(TaskDescriptor)taskit.next();
1669 FlatMethod fm=state.getMethodFlat(task);
1670 generateTempStructs(fm, null);
1672 ParamsObject objectparams=(ParamsObject) paramstable.get(task);
1673 TempObject objecttemps=(TempObject) tempstable.get(task);
1675 /* Output parameter structure */
1676 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1677 output.println("struct "+task.getSafeSymbol()+"_params {");
1678 output.println(" int size;");
1679 output.println(" void * next;");
1680 for(int i=0; i<objectparams.numPointers(); i++) {
1681 TempDescriptor temp=objectparams.getPointer(i);
1682 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1685 output.println("};\n");
1686 if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
1687 maxtaskparams=objectparams.numPointers()+fm.numTags();
1691 /* Output temp structure */
1692 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1693 output.println("struct "+task.getSafeSymbol()+"_locals {");
1694 output.println(" int size;");
1695 output.println(" void * next;");
1696 for(int i=0; i<objecttemps.numPointers(); i++) {
1697 TempDescriptor temp=objecttemps.getPointer(i);
1698 if (temp.getType().isNull())
1699 output.println(" void * "+temp.getSafeSymbol()+";");
1700 else if(temp.getType().isTag())
1701 output.println(" struct "+
1702 (new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1704 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1706 output.println("};\n");
1709 /* Output task declaration */
1710 headersout.print("void " + task.getSafeSymbol()+"(");
1712 boolean printcomma=false;
1713 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1714 headersout.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
1716 headersout.print("void * parameterarray[]");
1717 headersout.println(");\n");
1721 /***** Generate code for FlatMethod fm. *****/
1723 Hashtable<FlatAtomicEnterNode, AtomicRecord> atomicmethodmap;
1724 static int atomicmethodcount=0;
1727 BranchAnalysis branchanalysis;
1728 private void generateFlatMethod(FlatMethod fm, LocalityBinding lb, PrintWriter output) {
1729 if (State.PRINTFLAT)
1730 System.out.println(fm.printMethod());
1731 MethodDescriptor md=fm.getMethod();
1732 TaskDescriptor task=fm.getTask();
1733 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
1734 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : md!=null ? md : task);
1736 HashSet<AtomicRecord> arset=null;
1737 branchanalysis=null;
1739 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1741 if (atomicmethodmap==null)
1742 atomicmethodmap=new Hashtable<FlatAtomicEnterNode, AtomicRecord>();
1744 //fix these so we get right strings for local variables
1745 localsprefixaddr=localsprefix;
1746 localsprefixderef=localsprefix+"->";
1747 arset=new HashSet<AtomicRecord>();
1749 //build branchanalysis
1750 branchanalysis=new BranchAnalysis(locality, lb, delaycomp.getNotReady(lb), delaycomp.livecode(lb), state);
1752 //Generate commit methods here
1753 for(Iterator<FlatNode> fnit=fm.getNodeSet().iterator();fnit.hasNext();) {
1754 FlatNode fn=fnit.next();
1755 if (fn.kind()==FKind.FlatAtomicEnterNode&&
1756 locality.getAtomic(lb).get(fn.getPrev(0)).intValue()==0&&
1757 delaycomp.needsFission(lb, (FlatAtomicEnterNode) fn)) {
1758 //We have an atomic enter
1759 FlatAtomicEnterNode faen=(FlatAtomicEnterNode) fn;
1760 Set<FlatNode> exitset=faen.getExits();
1762 String methodname=md.getSymbol()+(atomicmethodcount++);
1763 AtomicRecord ar=new AtomicRecord();
1767 atomicmethodmap.put(faen, ar);
1769 //build data structure declaration
1770 output.println("struct atomicprimitives_"+methodname+" {");
1772 Set<FlatNode> recordset=delaycomp.livecode(lb);
1773 Set<TempDescriptor> liveinto=delaycomp.liveinto(lb, faen, recordset);
1774 Set<TempDescriptor> liveout=delaycomp.liveout(lb, faen);
1775 Set<TempDescriptor> liveoutvirtualread=delaycomp.liveoutvirtualread(lb, faen);
1777 ar.reallivein=new HashSet(liveinto);
1779 ar.liveoutvirtualread=liveoutvirtualread;
1782 for(Iterator<TempDescriptor> it=liveinto.iterator(); it.hasNext();) {
1783 TempDescriptor tmp=it.next();
1784 //remove the pointers
1785 if (tmp.getType().isPtr()) {
1788 //let's print it here
1789 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1792 for(Iterator<TempDescriptor> it=liveout.iterator(); it.hasNext();) {
1793 TempDescriptor tmp=it.next();
1794 //remove the pointers
1795 if (tmp.getType().isPtr()) {
1797 } else if (!liveinto.contains(tmp)) {
1798 //let's print it here
1799 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1802 output.println("};");
1804 //print out method name
1805 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) {");
1806 //build code for commit method
1808 //first define local primitives
1809 Set<TempDescriptor> alltemps=delaycomp.alltemps(lb, faen, recordset);
1810 for(Iterator<TempDescriptor> tmpit=alltemps.iterator();tmpit.hasNext();) {
1811 TempDescriptor tmp=tmpit.next();
1812 if (!tmp.getType().isPtr()) {
1813 if (liveinto.contains(tmp)||liveoutvirtualread.contains(tmp)) {
1814 //read from live into set
1815 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+"=primitives->"+tmp.getSafeSymbol()+";");
1818 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1822 //turn off write barrier generation
1824 state.SINGLETM=false;
1825 generateCode(faen, fm, lb, exitset, output, false);
1826 state.SINGLETM=true;
1827 //turn on write barrier generation
1829 output.println("}\n\n");
1833 //redefine these back to normal
1835 localsprefixaddr="&"+localsprefix;
1836 localsprefixderef=localsprefix+".";
1838 generateHeader(fm, lb, md!=null ? md : task,output);
1839 TempObject objecttemp=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
1841 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1842 for(Iterator<AtomicRecord> arit=arset.iterator();arit.hasNext();) {
1843 AtomicRecord ar=arit.next();
1844 output.println("struct atomicprimitives_"+ar.name+" primitives_"+ar.name+";");
1848 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1849 if (md!=null&&(state.DSM||state.SINGLETM))
1850 output.print(" struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1851 else if (md!=null&&!(state.DSM||state.SINGLETM))
1852 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1854 output.print(" struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={");
1855 output.print(objecttemp.numPointers()+",");
1856 output.print(paramsprefix);
1857 for(int j=0; j<objecttemp.numPointers(); j++)
1858 output.print(", NULL");
1859 output.println("};");
1862 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1863 TempDescriptor td=objecttemp.getPrimitive(i);
1864 TypeDescriptor type=td.getType();
1866 output.println(" void * "+td.getSafeSymbol()+";");
1867 else if (type.isClass()||type.isArray())
1868 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1870 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1874 if( state.MLP || state.OOOJAVA ) {
1875 if( fm.getNext(0) instanceof FlatSESEEnterNode ) {
1876 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
1877 if( (state.MLP && callerSESEplaceholder != mlpa.getMainSESE()) ||
1878 (state.OOOJAVA && callerSESEplaceholder != oooa.getMainSESE())
1880 // declare variables for naming static SESE's
1881 output.println(" /* static SESE names */");
1882 Iterator<SESEandAgePair> pItr = callerSESEplaceholder.getNeededStaticNames().iterator();
1883 while( pItr.hasNext() ) {
1884 SESEandAgePair pair = pItr.next();
1885 output.println(" void* "+pair+";");
1888 // declare variables for tracking dynamic sources
1889 output.println(" /* dynamic variable sources */");
1890 Iterator<TempDescriptor> dynSrcItr = callerSESEplaceholder.getDynamicVarSet().iterator();
1891 while( dynSrcItr.hasNext() ) {
1892 TempDescriptor dynSrcVar = dynSrcItr.next();
1893 output.println(" SESEcommon* "+dynSrcVar+"_srcSESE = NULL;");
1894 output.println(" INTPTR "+dynSrcVar+"_srcOffset;");
1899 // set up related allocation sites's waiting queues
1902 ConflictGraph graph = null;
1903 graph = mlpa.getConflictGraphResults().get(fm);
1904 if (graph != null && graph.hasConflictEdge()) {
1905 output.println(" /* set up waiting queues */");
1906 output.println(" int numMemoryQueue=0;");
1907 output.println(" int memoryQueueItemID=0;");
1908 HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
1910 System.out.println("#lockSet="+lockSet.hashCode());
1911 System.out.println("lockset="+lockSet);
1912 for (Iterator iterator = lockSet.iterator(); iterator.hasNext();) {
1913 SESELock seseLock = (SESELock) iterator.next();
1914 System.out.println("id="+seseLock.getID());
1915 System.out.println("#="+seseLock);
1917 System.out.println("size="+lockSet.size());
1918 if (lockSet.size() > 0) {
1919 output.println(" numMemoryQueue=" + lockSet.size() + ";");
1920 output.println(" runningSESE->numMemoryQueue=numMemoryQueue;");
1921 output.println(" runningSESE->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
1926 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
1927 if(callerSESEplaceholder!= oooa.getMainSESE()){
1928 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(callerSESEplaceholder);
1929 if (graph != null && graph.hasConflictEdge()) {
1930 output.println(" // set up waiting queues ");
1931 output.println(" int numMemoryQueue=0;");
1932 output.println(" int memoryQueueItemID=0;");
1933 Set<Analysis.OoOJava.SESELock> lockSet = oooa.getLockMappings(graph);
1934 System.out.println("#lockSet="+lockSet.hashCode());
1935 System.out.println("lockset="+lockSet);
1936 for (Iterator iterator = lockSet.iterator(); iterator.hasNext();) {
1937 Analysis.OoOJava.SESELock seseLock = (Analysis.OoOJava.SESELock) iterator.next();
1938 System.out.println("id="+seseLock.getID());
1939 System.out.println("#="+seseLock);
1941 System.out.println("size="+lockSet.size());
1942 if (lockSet.size() > 0) {
1943 output.println(" numMemoryQueue=" + lockSet.size() + ";");
1944 output.println(" runningSESE->numMemoryQueue=numMemoryQueue;");
1945 output.println(" runningSESE->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
1955 /* Check to see if we need to do a GC if this is a
1956 * multi-threaded program...*/
1958 if (((state.MLP||state.OOOJAVA||state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
1959 || this.state.MULTICOREGC) {
1960 //Don't bother if we aren't in recursive methods...The loops case will catch it
1961 if (callgraph.getAllMethods(md).contains(md)) {
1962 if (state.DSM&&lb.isAtomic())
1963 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
1964 else if (this.state.MULTICOREGC) {
1965 output.println("if(gcflag) gc("+localsprefixaddr+");");
1967 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
1972 generateCode(fm.getNext(0), fm, lb, null, output, true);
1974 output.println("}\n\n");
1978 protected void initializeSESE( FlatSESEEnterNode fsen ) {
1980 FlatMethod fm = fsen.getfmEnclosing();
1981 MethodDescriptor md = fm.getMethod();
1982 ClassDescriptor cn = md.getClassDesc();
1985 // Creates bogus method descriptor to index into tables
1986 Modifiers modBogus = new Modifiers();
1987 MethodDescriptor mdBogus =
1988 new MethodDescriptor( modBogus,
1989 new TypeDescriptor( TypeDescriptor.VOID ),
1990 "sese_"+fsen.getPrettyIdentifier()+fsen.getIdentifier()
1993 mdBogus.setClassDesc( fsen.getcdEnclosing() );
1994 FlatMethod fmBogus = new FlatMethod( mdBogus, null );
1995 fsen.setfmBogus( fmBogus );
1996 fsen.setmdBogus( mdBogus );
1998 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1999 inSetAndOutSet.addAll( fsen.getInVarSet() );
2000 inSetAndOutSet.addAll( fsen.getOutVarSet() );
2002 // Build paramsobj for bogus method descriptor
2003 ParamsObject objectparams = new ParamsObject( mdBogus, tag++ );
2004 paramstable.put( mdBogus, objectparams );
2006 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
2007 while( itr.hasNext() ) {
2008 TempDescriptor temp = itr.next();
2009 TypeDescriptor type = temp.getType();
2010 if( type.isPtr() ) {
2011 objectparams.addPtr( temp );
2013 objectparams.addPrim( temp );
2017 // Build normal temp object for bogus method descriptor
2018 TempObject objecttemps = new TempObject( objectparams, mdBogus, tag++ );
2019 tempstable.put( mdBogus, objecttemps );
2021 for( Iterator nodeit = fsen.getNodeSet().iterator(); nodeit.hasNext(); ) {
2022 FlatNode fn = (FlatNode)nodeit.next();
2023 TempDescriptor[] writes = fn.writesTemps();
2025 for( int i = 0; i < writes.length; i++ ) {
2026 TempDescriptor temp = writes[i];
2027 TypeDescriptor type = temp.getType();
2029 if( type.isPtr() ) {
2030 objecttemps.addPtr( temp );
2032 objecttemps.addPrim( temp );
2038 // used when generating the specific SESE record struct
2039 // to remember the FIRST field name of sese records
2040 // that the current SESE depends on--we need to know the
2041 // offset to the first one for garbage collection
2042 protected void addingDepRecField( FlatSESEEnterNode fsen,
2044 if( fsen.getFirstDepRecField() == null ) {
2045 fsen.setFirstDepRecField( field );
2047 fsen.incNumDepRecs();
2050 protected void generateMethodSESE(FlatSESEEnterNode fsen,
2052 PrintWriter outputStructs,
2053 PrintWriter outputMethHead,
2054 PrintWriter outputMethods
2057 ParamsObject objectparams = (ParamsObject) paramstable.get( fsen.getmdBogus() );
2058 TempObject objecttemps = (TempObject) tempstable .get( fsen.getmdBogus() );
2060 // generate locals structure
2061 outputStructs.println("struct "+
2062 fsen.getcdEnclosing().getSafeSymbol()+
2063 fsen.getmdBogus().getSafeSymbol()+"_"+
2064 fsen.getmdBogus().getSafeMethodDescriptor()+
2066 outputStructs.println(" int size;");
2067 outputStructs.println(" void * next;");
2068 for(int i=0; i<objecttemps.numPointers(); i++) {
2069 TempDescriptor temp=objecttemps.getPointer(i);
2071 if (temp.getType().isNull())
2072 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
2074 outputStructs.println(" struct "+
2075 temp.getType().getSafeSymbol()+" * "+
2076 temp.getSafeSymbol()+";");
2078 outputStructs.println("};\n");
2081 // divide in-set and out-set into objects and primitives to prep
2082 // for the record generation just below
2083 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
2084 inSetAndOutSet.addAll( fsen.getInVarSet() );
2085 inSetAndOutSet.addAll( fsen.getOutVarSet() );
2087 Set<TempDescriptor> inSetAndOutSetObjs = new HashSet<TempDescriptor>();
2088 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
2090 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
2091 while( itr.hasNext() ) {
2092 TempDescriptor temp = itr.next();
2093 TypeDescriptor type = temp.getType();
2094 if( type.isPtr() ) {
2095 inSetAndOutSetObjs.add( temp );
2097 inSetAndOutSetPrims.add( temp );
2102 // generate the SESE record structure
2103 outputStructs.println(fsen.getSESErecordName()+" {");
2105 // data common to any SESE, and it must be placed first so
2106 // a module that doesn't know what kind of SESE record this
2107 // is can cast the pointer to a common struct
2108 outputStructs.println(" SESEcommon common;");
2110 // then garbage list stuff
2111 outputStructs.println(" /* next is in-set and out-set objects that look like a garbage list */");
2112 outputStructs.println(" int size;");
2113 outputStructs.println(" void * next;");
2115 // I think that the set of TempDescriptors inSetAndOutSetObjs
2116 // calculated above should match the pointer object params
2117 // used in the following code, but let's just leave the working
2118 // implementation unless there is actually a problem...
2119 for(int i=0; i<objectparams.numPointers(); i++) {
2120 TempDescriptor temp=objectparams.getPointer(i);
2121 if (temp.getType().isNull())
2122 outputStructs.println(" void * "+temp.getSafeSymbol()+
2123 "; /* in-or-out-set obj in gl */");
2125 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+
2126 temp.getSafeSymbol()+"; /* in-or-out-set obj in gl */");
2129 outputStructs.println(" /* next is primitives for in-set and out-set and dynamic tracking */");
2131 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
2132 while( itrPrims.hasNext() ) {
2133 TempDescriptor temp = itrPrims.next();
2134 TypeDescriptor type = temp.getType();
2135 if(type.isPrimitive()){
2136 outputStructs.println(" "+temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol()+"; /* in-set or out-set primitive */");
2140 // note that the sese record pointer will be added below, just primitive part of tracking here
2141 Iterator<TempDescriptor> itrDynInVars = fsen.getDynamicInVarSet().iterator();
2142 while( itrDynInVars.hasNext() ) {
2143 TempDescriptor dynInVar = itrDynInVars.next();
2144 outputStructs.println(" INTPTR "+dynInVar+"_srcOffset; /* dynamic tracking primitive */");
2148 outputStructs.println(" /* everything after this should be pointers to an SESE record */" );
2150 // other half of info for dynamic tracking, the SESE record pointer
2151 itrDynInVars = fsen.getDynamicInVarSet().iterator();
2152 while( itrDynInVars.hasNext() ) {
2153 TempDescriptor dynInVar = itrDynInVars.next();
2154 String depRecField = dynInVar+"_srcSESE";
2155 outputStructs.println(" SESEcommon* "+depRecField+";");
2156 addingDepRecField( fsen, depRecField );
2159 // statically known sese sources are record pointers, too
2160 Iterator<SESEandAgePair> itrStaticInVarSrcs = fsen.getStaticInVarSrcs().iterator();
2161 while( itrStaticInVarSrcs.hasNext() ) {
2162 SESEandAgePair srcPair = itrStaticInVarSrcs.next();
2163 outputStructs.println(" "+srcPair.getSESE().getSESErecordName()+"* "+srcPair+";");
2164 addingDepRecField( fsen, srcPair.toString() );
2167 if( fsen.getFirstDepRecField() != null ) {
2168 outputStructs.println(" /* compiler believes first dependent SESE record field above is: "+
2169 fsen.getFirstDepRecField()+" */" );
2172 outputStructs.println("};\n");
2175 // write method declaration to header file
2176 outputMethHead.print("void ");
2177 outputMethHead.print(fsen.getSESEmethodName()+"(");
2178 outputMethHead.print(fsen.getSESErecordName()+"* "+paramsprefix);
2179 outputMethHead.println(");\n");
2182 generateFlatMethodSESE( fsen.getfmBogus(),
2183 fsen.getcdEnclosing(),
2189 private void generateFlatMethodSESE(FlatMethod fm,
2191 FlatSESEEnterNode fsen,
2192 FlatSESEExitNode seseExit,
2196 MethodDescriptor md=fm.getMethod();
2198 output.print("void ");
2199 output.print(fsen.getSESEmethodName()+"(");
2200 output.print(fsen.getSESErecordName()+"* "+paramsprefix);
2201 output.println("){\n");
2204 TempObject objecttemp=(TempObject) tempstable.get(md);
2206 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2207 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
2208 output.print(objecttemp.numPointers()+",");
2209 output.print("&(((SESEcommon*)(___params___))[1])");
2210 for(int j=0; j<objecttemp.numPointers(); j++)
2211 output.print(", NULL");
2212 output.println("};");
2215 output.println(" /* regular local primitives */");
2216 for(int i=0; i<objecttemp.numPrimitives(); i++) {
2217 TempDescriptor td=objecttemp.getPrimitive(i);
2218 TypeDescriptor type=td.getType();
2220 output.println(" void * "+td.getSafeSymbol()+";");
2221 else if (type.isClass()||type.isArray())
2222 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
2224 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
2228 // declare variables for naming static SESE's
2229 output.println(" /* static SESE names */");
2230 Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
2231 while( pItr.hasNext() ) {
2232 SESEandAgePair pair = pItr.next();
2233 output.println(" SESEcommon* "+pair+" = NULL;");
2236 // declare variables for tracking dynamic sources
2237 output.println(" /* dynamic variable sources */");
2238 Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
2239 while( dynSrcItr.hasNext() ) {
2240 TempDescriptor dynSrcVar = dynSrcItr.next();
2241 output.println(" SESEcommon* "+dynSrcVar+"_srcSESE = NULL;");
2242 output.println(" INTPTR "+dynSrcVar+"_srcOffset;");
2245 // declare local temps for in-set primitives, and if it is
2246 // a ready-source variable, get the value from the record
2247 output.println(" /* local temps for in-set primitives */");
2248 Iterator<TempDescriptor> itrInSet = fsen.getInVarSet().iterator();
2249 while( itrInSet.hasNext() ) {
2250 TempDescriptor temp = itrInSet.next();
2251 TypeDescriptor type = temp.getType();
2252 if( !type.isPtr() ) {
2253 if( fsen.getReadyInVarSet().contains( temp ) ) {
2254 output.println(" "+type+" "+temp+" = "+paramsprefix+"->"+temp+";");
2256 output.println(" "+type+" "+temp+";");
2261 // declare local temps for out-set primitives if its not already
2262 // in the in-set, and it's value will get written so no problem
2263 output.println(" /* local temp for out-set prim, not already in the in-set */");
2264 Iterator<TempDescriptor> itrOutSet = fsen.getOutVarSet().iterator();
2265 while( itrOutSet.hasNext() ) {
2266 TempDescriptor temp = itrOutSet.next();
2267 TypeDescriptor type = temp.getType();
2268 if( !type.isPtr() && !fsen.getInVarSet().contains( temp ) ) {
2269 output.println(" "+type+" "+temp+";");
2274 // initialize thread-local var to a the task's record, which is fused
2275 // with the param list
2276 output.println(" ");
2277 output.println(" /* code of this task's body should use this to access the running task record */");
2278 output.println(" runningSESE = &(___params___->common);");
2279 output.println(" ");
2281 // setup memory queue
2284 output.println(" // set up memory queues ");
2285 output.println(" int numMemoryQueue=0;");
2286 output.println(" int memoryQueueItemID=0;");
2287 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(fsen);
2288 if (graph != null && graph.hasConflictEdge()) {
2289 output.println(" {");
2290 Set<Analysis.OoOJava.SESELock> lockSet = oooa.getLockMappings(graph);
2291 System.out.println("#lockSet="+lockSet);
2292 if (lockSet.size() > 0) {
2293 output.println(" numMemoryQueue=" + lockSet.size() + ";");
2294 output.println(" runningSESE->numMemoryQueue=numMemoryQueue;");
2295 output.println(" runningSESE->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2298 output.println(" }");
2301 output.println(" // set up memory queues ");
2302 output.println(" int numMemoryQueue=0;");
2303 output.println(" int memoryQueueItemID=0;");
2304 ConflictGraph graph = null;
2305 graph = mlpa.getConflictGraphResults().get(fsen);
2306 if (graph != null && graph.hasConflictEdge()) {
2307 output.println(" {");
2308 HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
2310 System.out.println("#lockSet="+lockSet);
2312 if (lockSet.size() > 0) {
2313 output.println(" numMemoryQueue=" + lockSet.size() + "; ");
2314 output.println(" runningSESE->numMemoryQueue=numMemoryQueue;");
2315 output.println(" runningSESE->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2318 output.println(" }");
2324 // set up a task's mem pool to recycle the allocation of children tasks
2325 // don't bother if the task never has children (a leaf task)
2326 output.println( "#ifndef OOO_DISABLE_TASKMEMPOOL" );
2327 if( !fsen.getIsLeafSESE() ) {
2328 output.println(" runningSESE->taskRecordMemPool = poolcreate( "+
2329 maxTaskRecSizeStr+" );");
2331 // make it clear we purposefully did not initialize this
2332 output.println(" runningSESE->taskRecordMemPool = (MemPool*)0x1;");
2334 output.println( "#endif" );
2337 // copy in-set into place, ready vars were already
2338 // copied when the SESE was issued
2339 Iterator<TempDescriptor> tempItr;
2341 // static vars are from a known SESE
2342 output.println(" // copy variables from static sources");
2343 tempItr = fsen.getStaticInVarSet().iterator();
2344 while( tempItr.hasNext() ) {
2345 TempDescriptor temp = tempItr.next();
2346 VariableSourceToken vst = fsen.getStaticInVarSrc( temp );
2347 SESEandAgePair srcPair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2348 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2349 " = "+paramsprefix+"->"+srcPair+"->"+vst.getAddrVar()+";");
2352 output.println(" // decrement references to static sources");
2353 for( Iterator<SESEandAgePair> pairItr = fsen.getStaticInVarSrcs().iterator();
2356 SESEandAgePair srcPair = pairItr.next();
2357 output.println(" {");
2358 output.println(" SESEcommon* src = &("+paramsprefix+"->"+srcPair+"->common);");
2359 output.println(" RELEASE_REFERENCE_TO( src );");
2360 output.println(" }");
2364 // dynamic vars come from an SESE and src
2365 output.println(" // copy variables from dynamic sources");
2366 tempItr = fsen.getDynamicInVarSet().iterator();
2367 while( tempItr.hasNext() ) {
2368 TempDescriptor temp = tempItr.next();
2369 TypeDescriptor type = temp.getType();
2371 // go grab it from the SESE source
2372 output.println(" if( "+paramsprefix+"->"+temp+"_srcSESE != NULL ) {");
2375 if( type.isNull() ) {
2377 } else if( type.isClass() || type.isArray() ) {
2378 typeStr = "struct "+type.getSafeSymbol()+"*";
2380 typeStr = type.getSafeSymbol();
2383 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2384 " = *(("+typeStr+"*) ("+
2385 paramsprefix+"->"+temp+"_srcSESE + "+
2386 paramsprefix+"->"+temp+"_srcOffset));");
2388 output.println(" SESEcommon* src = "+paramsprefix+"->"+temp+"_srcSESE;");
2389 output.println(" RELEASE_REFERENCE_TO( src );");
2391 // or if the source was our parent, its already in our record to grab
2392 output.println(" } else {");
2393 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2394 " = "+paramsprefix+"->"+temp+";");
2395 output.println(" }");
2398 // Check to see if we need to do a GC if this is a
2399 // multi-threaded program...
2400 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2401 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2402 //Don't bother if we aren't in recursive methods...The loops case will catch it
2403 // if (callgraph.getAllMethods(md).contains(md)) {
2404 // if(this.state.MULTICOREGC) {
2405 // output.println("if(gcflag) gc("+localsprefixaddr+");");
2407 // output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2412 if( state.COREPROF ) {
2413 output.println("#ifdef CP_EVENTID_TASKEXECUTE");
2414 output.println(" CP_LOGEVENT( CP_EVENTID_TASKEXECUTE, CP_EVENTTYPE_BEGIN );");
2415 output.println("#endif");
2418 HashSet<FlatNode> exitset=new HashSet<FlatNode>();
2419 exitset.add(seseExit);
2420 generateCode(fsen.getNext(0), fm, null, exitset, output, true);
2421 output.println("}\n\n");
2426 // when a new mlp thread is created for an issued SESE, it is started
2427 // by running this method which blocks on a cond variable until
2428 // it is allowed to transition to execute. Then a case statement
2429 // allows it to invoke the method with the proper SESE body, and after
2430 // exiting the SESE method, executes proper SESE exit code before the
2431 // thread can be destroyed
2432 private void generateSESEinvocationMethod(PrintWriter outmethodheader,
2433 PrintWriter outmethod
2436 outmethodheader.println("void* invokeSESEmethod( void* seseRecord );");
2437 outmethod.println( "void* invokeSESEmethod( void* seseRecord ) {");
2438 outmethod.println( " int status;");
2439 outmethod.println( " char errmsg[128];");
2441 // generate a case for each SESE class that can be invoked
2442 outmethod.println( " switch( *((int*)seseRecord) ) {");
2443 outmethod.println( " ");
2444 Iterator<FlatSESEEnterNode> seseit;
2446 seseit=mlpa.getAllSESEs().iterator();
2448 seseit=oooa.getAllSESEs().iterator();
2450 while(seseit.hasNext()){
2451 FlatSESEEnterNode fsen = seseit.next();
2453 outmethod.println( " /* "+fsen.getPrettyIdentifier()+" */");
2454 outmethod.println( " case "+fsen.getIdentifier()+":");
2455 outmethod.println( " "+fsen.getSESEmethodName()+"( seseRecord );");
2457 if( (state.MLP && fsen.equals( mlpa.getMainSESE() )) ||
2458 (state.OOOJAVA && fsen.equals( oooa.getMainSESE() ))
2460 outmethod.println( " /* work scheduler works forever, explicitly exit */");
2461 outmethod.println( " CP_EXIT();");
2462 outmethod.println( " CP_DUMP();");
2463 outmethod.println( " workScheduleExit();");
2464 outmethod.println( " exit( 0 );");
2467 outmethod.println( " break;");
2468 outmethod.println( "");
2471 // default case should never be taken, error out
2472 outmethod.println( " default:");
2473 outmethod.println( " printf(\"Error: unknown SESE class ID in invoke method.\\n\");");
2474 outmethod.println( " exit(-30);");
2475 outmethod.println( " break;");
2476 outmethod.println( " }");
2477 outmethod.println( " return NULL;");
2478 outmethod.println( "}\n\n");
2482 protected void generateCode(FlatNode first,
2485 Set<FlatNode> stopset,
2486 PrintWriter output, boolean firstpass) {
2488 /* Assign labels to FlatNode's if necessary.*/
2490 Hashtable<FlatNode, Integer> nodetolabel;
2492 if (state.DELAYCOMP&&!firstpass)
2493 nodetolabel=dcassignLabels(first, stopset);
2495 nodetolabel=assignLabels(first, stopset);
2497 Set<FlatNode> storeset=null;
2498 HashSet<FlatNode> genset=null;
2499 HashSet<FlatNode> refset=null;
2500 Set<FlatNode> unionset=null;
2502 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
2503 storeset=delaycomp.livecode(lb);
2504 genset=new HashSet<FlatNode>();
2505 if (state.STMARRAY&&!state.DUALVIEW) {
2506 refset=new HashSet<FlatNode>();
2507 refset.addAll(delaycomp.getDeref(lb));
2508 refset.removeAll(delaycomp.getCannotDelay(lb));
2509 refset.removeAll(delaycomp.getOther(lb));
2512 genset.addAll(delaycomp.getCannotDelay(lb));
2513 genset.addAll(delaycomp.getOther(lb));
2515 genset.addAll(delaycomp.getNotReady(lb));
2516 if (state.STMARRAY&&!state.DUALVIEW) {
2517 genset.removeAll(refset);
2520 unionset=new HashSet<FlatNode>();
2521 unionset.addAll(storeset);
2522 unionset.addAll(genset);
2523 if (state.STMARRAY&&!state.DUALVIEW)
2524 unionset.addAll(refset);
2527 /* Do the actual code generation */
2528 FlatNode current_node=null;
2529 HashSet tovisit=new HashSet();
2530 HashSet visited=new HashSet();
2532 tovisit.add(first.getNext(0));
2535 while(current_node!=null||!tovisit.isEmpty()) {
2536 if (current_node==null) {
2537 current_node=(FlatNode)tovisit.iterator().next();
2538 tovisit.remove(current_node);
2539 } else if (tovisit.contains(current_node)) {
2540 tovisit.remove(current_node);
2542 visited.add(current_node);
2543 if (nodetolabel.containsKey(current_node)) {
2544 output.println("L"+nodetolabel.get(current_node)+":");
2546 if (state.INSTRUCTIONFAILURE) {
2547 if (state.THREAD||state.DSM||state.SINGLETM) {
2548 output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
2550 output.println("if ((--instructioncount)==0) injectinstructionfailure();");
2552 if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
2554 if (!state.DELAYCOMP||firstpass) {
2555 generateFlatNode(fm, lb, current_node, output);
2557 //store primitive variables in out set
2558 AtomicRecord ar=atomicmethodmap.get((FlatAtomicEnterNode)first);
2559 Set<TempDescriptor> liveout=ar.liveout;
2560 for(Iterator<TempDescriptor> tmpit=liveout.iterator();tmpit.hasNext();) {
2561 TempDescriptor tmp=tmpit.next();
2562 output.println("primitives->"+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2565 if ((state.MLP || state.OOOJAVA) && stopset!=null) {
2566 assert first.getPrev( 0 ) instanceof FlatSESEEnterNode;
2567 assert current_node instanceof FlatSESEExitNode;
2568 FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev( 0 );
2569 FlatSESEExitNode fsxn = (FlatSESEExitNode) current_node;
2570 assert fsen.getFlatExit().equals( fsxn );
2571 assert fsxn.getFlatEnter().equals( fsen );
2573 if (current_node.kind()!=FKind.FlatReturnNode) {
2574 output.println(" return;");
2577 } else if(current_node.numNext()==1) {
2579 if ((state.MLP|| state.OOOJAVA) &&
2580 current_node.kind()==FKind.FlatSESEEnterNode &&
2581 !((FlatSESEEnterNode)current_node).getIsCallerSESEplaceholder()
2583 FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
2584 generateFlatNode(fm, lb, current_node, output);
2585 nextnode=fsen.getFlatExit().getNext(0);
2586 } else if (state.DELAYCOMP) {
2587 boolean specialprimitive=false;
2588 //skip literals...no need to add extra overhead
2589 if (storeset!=null&&storeset.contains(current_node)&¤t_node.kind()==FKind.FlatLiteralNode) {
2590 TypeDescriptor typedesc=((FlatLiteralNode)current_node).getType();
2591 if (!typedesc.isClass()&&!typedesc.isArray()) {
2592 specialprimitive=true;
2596 if (genset==null||genset.contains(current_node)||specialprimitive)
2597 generateFlatNode(fm, lb, current_node, output);
2598 if (state.STMARRAY&&!state.DUALVIEW&&refset!=null&&refset.contains(current_node)) {
2599 //need to acquire lock
2600 handleArrayDeref(fm, lb, current_node, output, firstpass);
2602 if (storeset!=null&&storeset.contains(current_node)&&!specialprimitive) {
2603 TempDescriptor wrtmp=current_node.writesTemps()[0];
2605 //need to store value written by previous node
2606 if (wrtmp.getType().isPtr()) {
2607 //only lock the objects that may actually need locking
2608 if (recorddc.getNeedTrans(lb, current_node)&&
2609 (!state.STMARRAY||state.DUALVIEW||!wrtmp.getType().isArray()||
2610 wrtmp.getType().getSymbol().equals(TypeUtil.ObjectClass))) {
2611 output.println("STOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2613 output.println("STOREPTRNOLOCK("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2616 output.println("STORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");/* "+current_node.nodeid+" */");
2619 //need to read value read by previous node
2620 if (wrtmp.getType().isPtr()) {
2621 output.println("RESTOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2623 output.println("RESTORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+"); /* "+current_node.nodeid+" */");
2627 nextnode=current_node.getNext(0);
2630 generateFlatNode(fm, lb, current_node, output);
2631 nextnode=current_node.getNext(0);
2633 if (visited.contains(nextnode)) {
2634 output.println("goto L"+nodetolabel.get(nextnode)+";");
2637 current_node=nextnode;
2638 } else if (current_node.numNext()==2) {
2640 if (state.DELAYCOMP) {
2641 boolean computeside=false;
2643 //need to record which way it should go
2644 if (genset==null||genset.contains(current_node)) {
2645 if (storeset!=null&&storeset.contains(current_node)) {
2646 //need to store which way branch goes
2647 generateStoreFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2649 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2651 //which side to execute
2655 if (genset.contains(current_node)) {
2656 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2657 } else if (storeset.contains(current_node)) {
2659 branchanalysis.generateGroupCode(current_node, output, nodetolabel);
2661 //which side to execute
2666 Set<FlatNode> leftset=DelayComputation.getNext(current_node, 0, unionset, lb,locality, true);
2668 if (leftset.size()==0)
2670 if (visited.contains(current_node.getNext(branch))) {
2671 //already visited -- build jump
2672 output.println("goto L"+nodetolabel.get(current_node.getNext(branch))+";");
2675 current_node=current_node.getNext(branch);
2678 if (!visited.contains(current_node.getNext(1)))
2679 tovisit.add(current_node.getNext(1));
2680 if (visited.contains(current_node.getNext(0))) {
2681 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2684 current_node=current_node.getNext(0);
2688 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2689 if (!visited.contains(current_node.getNext(1)))
2690 tovisit.add(current_node.getNext(1));
2691 if (visited.contains(current_node.getNext(0))) {
2692 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2695 current_node=current_node.getNext(0);
2697 } else throw new Error();
2701 protected void handleArrayDeref(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output, boolean firstpass) {
2702 if (fn.kind()==FKind.FlatSetElementNode) {
2703 FlatSetElementNode fsen=(FlatSetElementNode) fn;
2704 String dst=generateTemp(fm, fsen.getDst(), lb);
2705 String src=generateTemp(fm, fsen.getSrc(), lb);
2706 String index=generateTemp(fm, fsen.getIndex(), lb);
2707 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
2709 if (elementtype.isArray()||elementtype.isClass())
2712 type=elementtype.getSafeSymbol()+" ";
2714 output.println("STOREARRAY("+dst+","+index+","+type+")");
2716 output.println("{");
2717 output.println(" struct ArrayObject *array;");
2718 output.println(" int index;");
2719 output.println(" RESTOREARRAY(array,index);");
2720 output.println(" (("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index]="+src+";");
2721 output.println("}");
2723 } else if (fn.kind()==FKind.FlatElementNode) {
2724 FlatElementNode fen=(FlatElementNode) fn;
2725 String src=generateTemp(fm, fen.getSrc(), lb);
2726 String index=generateTemp(fm, fen.getIndex(), lb);
2727 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
2728 String dst=generateTemp(fm, fen.getDst(), lb);
2730 if (elementtype.isArray()||elementtype.isClass())
2733 type=elementtype.getSafeSymbol()+" ";
2735 output.println("STOREARRAY("+src+","+index+","+type+")");
2737 output.println("{");
2738 output.println(" struct ArrayObject *array;");
2739 output.println(" int index;");
2740 output.println(" RESTOREARRAY(array,index);");
2741 output.println(" "+dst+"=(("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index];");
2742 output.println("}");
2746 /** Special label assignment for delaycomputation */
2747 protected Hashtable<FlatNode, Integer> dcassignLabels(FlatNode first, Set<FlatNode> lastset) {
2748 HashSet tovisit=new HashSet();
2749 HashSet visited=new HashSet();
2751 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2753 //Label targets of branches
2754 Set<FlatNode> targets=branchanalysis.getTargets();
2755 for(Iterator<FlatNode> it=targets.iterator();it.hasNext();) {
2756 nodetolabel.put(it.next(), new Integer(labelindex++));
2761 /*Assign labels first. A node needs a label if the previous
2762 * node has two exits or this node is a join point. */
2764 while(!tovisit.isEmpty()) {
2765 FlatNode fn=(FlatNode)tovisit.iterator().next();
2770 if(lastset!=null&&lastset.contains(fn)) {
2771 // if last is not null and matches, don't go
2772 // any further for assigning labels
2776 for(int i=0; i<fn.numNext(); i++) {
2777 FlatNode nn=fn.getNext(i);
2780 //1) Edge >1 of node
2781 nodetolabel.put(nn,new Integer(labelindex++));
2783 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2787 nodetolabel.put(nn,new Integer(labelindex++));
2795 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first) {
2796 return assignLabels(first, null);
2799 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
2800 HashSet tovisit=new HashSet();
2801 HashSet visited=new HashSet();
2803 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2806 /*Assign labels first. A node needs a label if the previous
2807 * node has two exits or this node is a join point. */
2809 while(!tovisit.isEmpty()) {
2810 FlatNode fn=(FlatNode)tovisit.iterator().next();
2815 if(lastset!=null&&lastset.contains(fn)) {
2816 // if last is not null and matches, don't go
2817 // any further for assigning labels
2821 for(int i=0; i<fn.numNext(); i++) {
2822 FlatNode nn=fn.getNext(i);
2825 //1) Edge >1 of node
2826 nodetolabel.put(nn,new Integer(labelindex++));
2828 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2832 nodetolabel.put(nn,new Integer(labelindex++));
2840 /** Generate text string that corresponds to the TempDescriptor td. */
2841 protected String generateTemp(FlatMethod fm, TempDescriptor td, LocalityBinding lb) {
2842 MethodDescriptor md=fm.getMethod();
2843 TaskDescriptor task=fm.getTask();
2844 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
2846 if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
2847 return td.getSafeSymbol();
2850 if (objecttemps.isLocalPtr(td)) {
2851 return localsprefixderef+td.getSafeSymbol();
2854 if (objecttemps.isParamPtr(td)) {
2855 return paramsprefix+"->"+td.getSafeSymbol();
2861 protected void generateFlatNode(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output) {
2863 // insert pre-node actions from the code plan
2864 if( state.MLP|| state.OOOJAVA ) {
2868 cp = mlpa.getCodePlan( fn );
2870 cp = oooa.getCodePlan(fn);
2875 FlatSESEEnterNode currentSESE = cp.getCurrentSESE();
2877 // for each sese and age pair that this parent statement
2878 // must stall on, take that child's stall semaphore, the
2879 // copying of values comes after the statement
2880 Iterator<VariableSourceToken> vstItr = cp.getStallTokens().iterator();
2881 while( vstItr.hasNext() ) {
2882 VariableSourceToken vst = vstItr.next();
2884 SESEandAgePair pair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2886 output.println(" {");
2887 output.println(" "+pair.getSESE().getSESErecordName()+"* child = ("+
2888 pair.getSESE().getSESErecordName()+"*) "+pair+";");
2890 output.println(" SESEcommon* common = (SESEcommon*) "+pair+";");
2891 if( state.COREPROF ) {
2892 output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
2893 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_BEGIN );");
2894 output.println("#endif");
2896 output.println(" pthread_mutex_lock( &(common->lock) );");
2897 output.println(" while( common->doneExecuting == FALSE ) {");
2898 output.println(" pthread_cond_wait( &(common->doneCond), &(common->lock) );");
2899 output.println(" }");
2900 output.println(" pthread_mutex_unlock( &(common->lock) );");
2902 // copy things we might have stalled for
2903 Iterator<TempDescriptor> tdItr = cp.getCopySet( vst ).iterator();
2904 while( tdItr.hasNext() ) {
2905 TempDescriptor td = tdItr.next();
2906 FlatMethod fmContext;
2907 if( currentSESE.getIsCallerSESEplaceholder() ) {
2908 fmContext = currentSESE.getfmEnclosing();
2910 fmContext = currentSESE.getfmBogus();
2912 output.println(" "+generateTemp( fmContext, td, null )+
2913 " = child->"+vst.getAddrVar().getSafeSymbol()+";");
2915 if( state.COREPROF ) {
2916 output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
2917 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_END );");
2918 output.println("#endif");
2920 output.println(" }");
2923 // for each variable with a dynamic source, stall just for that variable
2924 Iterator<TempDescriptor> dynItr = cp.getDynamicStallSet().iterator();
2925 while( dynItr.hasNext() ) {
2926 TempDescriptor dynVar = dynItr.next();
2928 // only stall if the dynamic source is not yourself, denoted by src==NULL
2929 // otherwise the dynamic write nodes will have the local var up-to-date
2930 output.println(" {");
2931 output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
2932 output.println(" SESEcommon* common = (SESEcommon*) "+dynVar+"_srcSESE;");
2933 if( state.COREPROF ) {
2934 output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
2935 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_BEGIN );");
2936 output.println("#endif");
2938 output.println(" psem_take( &(common->stallSem) );");
2940 FlatMethod fmContext;
2941 if( currentSESE.getIsCallerSESEplaceholder() ) {
2942 fmContext = currentSESE.getfmEnclosing();
2944 fmContext = currentSESE.getfmBogus();
2947 TypeDescriptor type=dynVar.getType();
2949 if( type.isNull() ) {
2951 } else if( type.isClass() || type.isArray() ) {
2952 typeStr = "struct "+type.getSafeSymbol()+"*";
2954 typeStr = type.getSafeSymbol();
2957 output.println(" "+generateTemp( fmContext, dynVar, null )+
2958 " = *(("+typeStr+"*) ("+
2959 dynVar+"_srcSESE + "+dynVar+"_srcOffset));");
2960 if( state.COREPROF ) {
2961 output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
2962 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_END );");
2963 output.println("#endif");
2965 output.println(" }");
2966 output.println(" }");
2969 // for each assignment of a variable to rhs that has a dynamic source,
2970 // copy the dynamic sources
2971 Iterator dynAssignItr = cp.getDynAssigns().entrySet().iterator();
2972 while( dynAssignItr.hasNext() ) {
2973 Map.Entry me = (Map.Entry) dynAssignItr.next();
2974 TempDescriptor lhs = (TempDescriptor) me.getKey();
2975 TempDescriptor rhs = (TempDescriptor) me.getValue();
2977 output.println(" {");
2978 output.println(" SESEcommon* oldSrc = "+lhs+"_srcSESE;");
2980 output.println(" "+lhs+"_srcSESE = "+rhs+"_srcSESE;");
2981 output.println(" "+lhs+"_srcOffset = "+rhs+"_srcOffset;");
2983 // no matter what we did above, track reference count of whatever
2984 // this variable pointed to, do release last in case we're just
2985 // copying the same value in because 1->2->1 is safe but ref count
2986 // 1->0->1 has a window where it looks like it should be free'd
2987 output.println(" if( "+rhs+"_srcSESE != NULL ) {");
2988 output.println(" ADD_REFERENCE_TO( "+rhs+"_srcSESE );");
2989 output.println(" }");
2990 output.println(" if( oldSrc != NULL ) {");
2991 output.println(" RELEASE_REFERENCE_TO( oldSrc );");
2992 output.println(" }");
2993 output.println(" }");
2996 // for each lhs that is dynamic from a non-dynamic source, set the
2997 // dynamic source vars to the current SESE
2998 dynItr = cp.getDynAssignCurr().iterator();
2999 while( dynItr.hasNext() ) {
3000 TempDescriptor dynVar = dynItr.next();
3001 assert currentSESE.getDynamicVarSet().contains( dynVar );
3003 // first release a reference to current record
3004 output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
3005 output.println(" RELEASE_REFERENCE_TO( oldSrc );");
3006 output.println(" }");
3008 output.println(" "+dynVar+"_srcSESE = NULL;");
3012 // handling stall site
3013 if (state.OOOJAVA) {
3014 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(currentSESE);
3016 Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
3017 Set<Analysis.OoOJava.WaitingElement> waitingElementSet =
3018 graph.getStallSiteWaitingElementSet(fn, seseLockSet);
3020 if(waitingElementSet.size()>0){
3021 output.println("// stall on parent's stall sites ");
3022 output.println(" {");
3023 output.println(" REntry* rentry;");
3025 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
3026 Analysis.OoOJava.WaitingElement waitingElement = (Analysis.OoOJava.WaitingElement) iterator.next();
3028 if(state.RCR && rcr != null){
3029 Analysis.OoOJava.ConflictGraph conflictGraph = graph;
3030 Hashtable<Taint, Set<Effect>> conflicts;
3031 ReachGraph rg = oooa.getDisjointAnalysis().getReachGraph(currentSESE.getmdEnclosing());
3032 if(rcr.cSideDebug) {
3033 rg.writeGraph("RCR_RG_STALLSITE_DEBUG");
3035 if((conflictGraph != null) &&
3036 (conflicts = graph.getConflictEffectSet(fn)) != null &&
3040 Hashtable<Taint, Set<Effect>> effects=oooa.getDisjointAnalysis().getEffectsAnalysis().get(fn);
3041 rcr.traverseStallSite(fn, waitingElement.getTempDesc(), effects, conflicts, rg);
3045 if( waitingElement.getStatus() >= ConflictNode.COARSE ){
3046 output.println(" rentry=mlpCreateREntry("+ waitingElement.getStatus()+ ", runningSESE);");
3048 output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", runningSESE, (void*)&" +generateTemp(fm,waitingElement.getTempDesc(),lb)+ ");");
3050 output.println(" psem_init( &(rentry->parentStallSem) );");
3051 output.println(" rentry->queue=runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
3052 output.println(" if(ADDRENTRY(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()
3053 + "],rentry)==NOTREADY){");
3054 if( state.COREPROF ) {
3055 output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3056 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_BEGIN );");
3057 output.println("#endif");
3059 output.println(" psem_take( &(rentry->parentStallSem) );");
3060 if( state.COREPROF ) {
3061 output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3062 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_END );");
3063 output.println("#endif");
3065 output.println(" } ");
3067 if(state.RCR && rcr != null) {
3068 output.println(" "+rcr.getTraverserInvocation(waitingElement.getTempDesc(),
3069 generateTemp(fm, waitingElement.getTempDesc(), null), fn));
3072 output.println(" }");
3076 ParentChildConflictsMap conflictsMap = mlpa.getConflictsResults().get(fn);
3077 if (conflictsMap != null) {
3078 Set<Long> allocSet = conflictsMap.getAllocationSiteIDSetofStallSite();
3079 if (allocSet.size() > 0) {
3080 FlatNode enclosingFlatNode=null;
3081 if( currentSESE.getIsCallerSESEplaceholder() && currentSESE.getParent()==null){
3082 enclosingFlatNode=currentSESE.getfmEnclosing();
3084 enclosingFlatNode=currentSESE;
3086 ConflictGraph graph=mlpa.getConflictGraphResults().get(enclosingFlatNode);
3087 HashSet<SESELock> seseLockSet=mlpa.getConflictGraphLockMap().get(graph);
3088 Set<WaitingElement> waitingElementSet=graph.getStallSiteWaitingElementSet(conflictsMap, seseLockSet);
3090 if(waitingElementSet.size()>0){
3091 output.println("// stall on parent's stall sites ");
3092 output.println(" {");
3093 output.println(" REntry* rentry;");
3095 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
3096 WaitingElement waitingElement = (WaitingElement) iterator.next();
3098 if( waitingElement.getStatus() >= ConflictNode.COARSE ){
3099 // HERE! a parent might conflict with a child
3100 output.println(" rentry=mlpCreateREntry("+ waitingElement.getStatus()+ ", runningSESE);");
3102 output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", runningSESE, (void*)&___locals___."+ waitingElement.getDynID() + ");");
3104 output.println(" psem_init( &(rentry->parentStallSem) );");
3105 output.println(" rentry->queue=runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
3107 .println(" if(ADDRENTRY(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()
3108 + "],rentry)==NOTREADY){");
3109 if( state.COREPROF ) {
3110 output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3111 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_BEGIN );");
3112 output.println("#endif");
3114 output.println(" psem_take( &(rentry->parentStallSem) );");
3115 if( state.COREPROF ) {
3116 output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3117 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_END );");
3118 output.println("#endif");
3120 output.println(" } ");
3122 output.println(" }");
3131 case FKind.FlatAtomicEnterNode:
3132 generateFlatAtomicEnterNode(fm, lb, (FlatAtomicEnterNode) fn, output);
3135 case FKind.FlatAtomicExitNode:
3136 generateFlatAtomicExitNode(fm, lb, (FlatAtomicExitNode) fn, output);
3139 case FKind.FlatInstanceOfNode:
3140 generateFlatInstanceOfNode(fm, lb, (FlatInstanceOfNode)fn, output);
3143 case FKind.FlatSESEEnterNode:
3144 generateFlatSESEEnterNode(fm, lb, (FlatSESEEnterNode)fn, output);
3147 case FKind.FlatSESEExitNode:
3148 generateFlatSESEExitNode(fm, lb, (FlatSESEExitNode)fn, output);
3151 case FKind.FlatWriteDynamicVarNode:
3152 generateFlatWriteDynamicVarNode(fm, lb, (FlatWriteDynamicVarNode)fn, output);
3155 case FKind.FlatGlobalConvNode:
3156 generateFlatGlobalConvNode(fm, lb, (FlatGlobalConvNode) fn, output);
3159 case FKind.FlatTagDeclaration:
3160 generateFlatTagDeclaration(fm, lb, (FlatTagDeclaration) fn,output);
3163 case FKind.FlatCall:
3164 generateFlatCall(fm, lb, (FlatCall) fn,output);
3167 case FKind.FlatFieldNode:
3168 generateFlatFieldNode(fm, lb, (FlatFieldNode) fn,output);
3171 case FKind.FlatElementNode:
3172 generateFlatElementNode(fm, lb, (FlatElementNode) fn,output);
3175 case FKind.FlatSetElementNode:
3176 generateFlatSetElementNode(fm, lb, (FlatSetElementNode) fn,output);
3179 case FKind.FlatSetFieldNode:
3180 generateFlatSetFieldNode(fm, lb, (FlatSetFieldNode) fn,output);
3184 generateFlatNew(fm, lb, (FlatNew) fn,output);
3187 case FKind.FlatOpNode:
3188 generateFlatOpNode(fm, lb, (FlatOpNode) fn,output);
3191 case FKind.FlatCastNode:
3192 generateFlatCastNode(fm, lb, (FlatCastNode) fn,output);
3195 case FKind.FlatLiteralNode:
3196 generateFlatLiteralNode(fm, lb, (FlatLiteralNode) fn,output);
3199 case FKind.FlatReturnNode:
3200 generateFlatReturnNode(fm, lb, (FlatReturnNode) fn,output);
3204 output.println("/* nop */");
3207 case FKind.FlatExit:
3208 output.println("/* exit */");
3211 case FKind.FlatBackEdge:
3212 if (state.SINGLETM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
3213 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
3215 if(state.DSM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
3216 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
3218 if (((state.MLP|| state.OOOJAVA||state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
3219 || (this.state.MULTICOREGC)) {
3220 if(state.DSM&&locality.getAtomic(lb).get(fn).intValue()>0) {
3221 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
3222 } else if(this.state.MULTICOREGC) {
3223 output.println("if (gcflag) gc("+localsprefixaddr+");");
3225 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3228 output.println("/* nop */");
3231 case FKind.FlatCheckNode:
3232 generateFlatCheckNode(fm, lb, (FlatCheckNode) fn, output);
3235 case FKind.FlatFlagActionNode:
3236 generateFlatFlagActionNode(fm, lb, (FlatFlagActionNode) fn, output);
3239 case FKind.FlatPrefetchNode:
3240 generateFlatPrefetchNode(fm,lb, (FlatPrefetchNode) fn, output);
3243 case FKind.FlatOffsetNode:
3244 generateFlatOffsetNode(fm, lb, (FlatOffsetNode)fn, output);
3251 // insert post-node actions from the code-plan
3254 CodePlan cp = mlpa.getCodePlan( fn );
3262 public void generateFlatOffsetNode(FlatMethod fm, LocalityBinding lb, FlatOffsetNode fofn, PrintWriter output) {
3263 output.println("/* FlatOffsetNode */");
3264 FieldDescriptor fd=fofn.getField();
3265 output.println(generateTemp(fm, fofn.getDst(),lb)+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+ fd.getSafeSymbol()+");");
3266 output.println("/* offset */");
3269 public void generateFlatPrefetchNode(FlatMethod fm, LocalityBinding lb, FlatPrefetchNode fpn, PrintWriter output) {
3270 if (state.PREFETCH) {
3271 Vector oids = new Vector();
3272 Vector fieldoffset = new Vector();
3273 Vector endoffset = new Vector();
3274 int tuplecount = 0; //Keeps track of number of prefetch tuples that need to be generated
3275 for(Iterator it = fpn.hspp.iterator(); it.hasNext();) {
3276 PrefetchPair pp = (PrefetchPair) it.next();
3277 Integer statusbase = locality.getNodePreTempInfo(lb,fpn).get(pp.base);
3278 /* Find prefetches that can generate oid */
3279 if(statusbase == LocalityAnalysis.GLOBAL) {
3280 generateTransCode(fm, lb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(lb).get(fpn).intValue()>0, false);
3282 } else if (statusbase == LocalityAnalysis.LOCAL) {
3283 generateTransCode(fm,lb,pp,oids,fieldoffset,endoffset,tuplecount,false,true);
3290 System.out.println("Adding prefetch "+fpn+ " to method:" +fm);
3291 output.println("{");
3292 output.println("/* prefetch */");
3293 output.println("/* prefetchid_" + fpn.siteid + " */");
3294 output.println("void * prefptr;");
3295 output.println("int tmpindex;");
3297 output.println("if((evalPrefetch["+fpn.siteid+"].operMode) || (evalPrefetch["+fpn.siteid+"].retrycount <= 0)) {");
3298 /*Create C code for oid array */
3299 output.print(" unsigned int oidarray_[] = {");
3300 boolean needcomma=false;
3301 for (Iterator it = oids.iterator(); it.hasNext();) {
3304 output.print(it.next());
3307 output.println("};");
3309 /*Create C code for endoffset values */
3310 output.print(" unsigned short endoffsetarry_[] = {");
3312 for (Iterator it = endoffset.iterator(); it.hasNext();) {
3315 output.print(it.next());
3318 output.println("};");
3320 /*Create C code for Field Offset Values */
3321 output.print(" short fieldarry_[] = {");
3323 for (Iterator it = fieldoffset.iterator(); it.hasNext();) {
3326 output.print(it.next());
3329 output.println("};");
3330 /* make the prefetch call to Runtime */
3331 output.println(" if(!evalPrefetch["+fpn.siteid+"].operMode) {");
3332 output.println(" evalPrefetch["+fpn.siteid+"].retrycount = RETRYINTERVAL;");
3333 output.println(" }");
3334 output.println(" prefetch("+fpn.siteid+" ,"+tuplecount+", oidarray_, endoffsetarry_, fieldarry_);");
3335 output.println(" } else {");
3336 output.println(" evalPrefetch["+fpn.siteid+"].retrycount--;");
3337 output.println(" }");
3338 output.println("}");
3342 public void generateTransCode(FlatMethod fm, LocalityBinding lb,PrefetchPair pp, Vector oids, Vector fieldoffset, Vector endoffset, int tuplecount, boolean inside, boolean localbase) {
3343 short offsetcount = 0;
3347 } else if (localbase) {
3348 for(; breakindex<pp.desc.size(); breakindex++) {
3349 Descriptor desc=pp.getDescAt(breakindex);
3350 if (desc instanceof FieldDescriptor) {
3351 FieldDescriptor fd=(FieldDescriptor)desc;
3352 if (fd.isGlobal()) {
3360 if (breakindex>pp.desc.size()) //all local
3363 TypeDescriptor lasttype=pp.base.getType();
3364 String basestr=generateTemp(fm, pp.base, lb);
3366 boolean maybenull=fm.getMethod().isStatic()||
3367 !pp.base.equals(fm.getParameter(0));
3369 for(int i=0; i<breakindex; i++) {
3370 String indexcheck="";
3372 Descriptor desc=pp.getDescAt(i);
3373 if (desc instanceof FieldDescriptor) {
3374 FieldDescriptor fd=(FieldDescriptor)desc;
3376 if (!teststr.equals(""))
3378 teststr+="((prefptr="+basestr+")!=NULL)";
3379 basestr="((struct "+lasttype.getSafeSymbol()+" *)prefptr)->"+fd.getSafeSymbol();
3381 basestr=basestr+"->"+fd.getSafeSymbol();
3384 lasttype=fd.getType();
3386 IndexDescriptor id=(IndexDescriptor)desc;
3387 indexcheck="((tmpindex=";
3388 for(int j=0; j<id.tddesc.size(); j++) {
3389 indexcheck+=generateTemp(fm, id.getTempDescAt(j), lb)+"+";
3391 indexcheck+=id.offset+")>=0)&(tmpindex<((struct ArrayObject *)prefptr)->___length___)";
3393 if (!teststr.equals(""))
3395 teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck;
3396 basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]";
3398 lasttype=lasttype.dereference();
3403 if (teststr.equals("")) {
3404 oid="((unsigned int)"+basestr+")";
3406 oid="((unsigned int)(("+teststr+")?"+basestr+":NULL))";
3410 for(int i = breakindex; i < pp.desc.size(); i++) {
3411 String newfieldoffset;
3412 Object desc = pp.getDescAt(i);
3413 if(desc instanceof FieldDescriptor) {
3414 FieldDescriptor fd=(FieldDescriptor)desc;
3415 newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))");
3416 lasttype=fd.getType();
3418 newfieldoffset = "";
3419 IndexDescriptor id=(IndexDescriptor)desc;
3420 for(int j = 0; j < id.tddesc.size(); j++) {
3421 newfieldoffset += generateTemp(fm, id.getTempDescAt(j), lb) + "+";
3423 newfieldoffset += id.offset.toString();
3424 lasttype=lasttype.dereference();
3426 fieldoffset.add(newfieldoffset);
3429 int base=(tuplecount>0) ? ((Short)endoffset.get(tuplecount-1)).intValue() : 0;
3430 base+=pp.desc.size()-breakindex;
3431 endoffset.add(new Short((short)base));
3436 public void generateFlatGlobalConvNode(FlatMethod fm, LocalityBinding lb, FlatGlobalConvNode fgcn, PrintWriter output) {
3437 if (lb!=fgcn.getLocality())
3439 /* Have to generate flat globalconv */
3440 if (fgcn.getMakePtr()) {
3442 //DEBUG: output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+",\" "+fm+":"+fgcn+"\");");
3443 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3445 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fgcn)||state.READSET&&dc.getNeedWriteTrans(lb, fgcn)) {
3446 //need to do translation
3447 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+", (void *)("+localsprefixaddr+"));");
3448 } else if (state.READSET&&dc.getNeedTrans(lb, fgcn)) {
3449 if (state.HYBRID&&delaycomp.getConv(lb).contains(fgcn)) {
3450 output.println("TRANSREADRDFISSION("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3452 output.println("TRANSREADRD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3456 /* Need to convert to OID */
3457 if ((dc==null)||dc.getNeedSrcTrans(lb,fgcn)) {
3458 if (fgcn.doConvert()||(delaycomp!=null&&delaycomp.needsFission(lb, fgcn.getAtomicEnter())&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) {
3459 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc(),lb)+");");
3461 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=NULL;");
3467 public void generateFlatInstanceOfNode(FlatMethod fm, LocalityBinding lb, FlatInstanceOfNode fion, PrintWriter output) {
3469 if (fion.getType().isArray()) {
3470 type=state.getArrayNumber(fion.getType())+state.numClasses();
3472 type=fion.getType().getClassDesc().getId();
3475 if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
3476 output.println(generateTemp(fm, fion.getDst(), lb)+"=1;");
3478 output.println(generateTemp(fm, fion.getDst(), lb)+"=instanceof("+generateTemp(fm,fion.getSrc(),lb)+","+type+");");
3481 int sandboxcounter=0;
3482 public void generateFlatAtomicEnterNode(FlatMethod fm, LocalityBinding lb, FlatAtomicEnterNode faen, PrintWriter output) {
3483 /* Check to see if we need to generate code for this atomic */
3484 if (locality==null) {
3485 if (GENERATEPRECISEGC) {
3486 output.println("if (pthread_mutex_trylock(&atomiclock)!=0) {");
3487 output.println("stopforgc((struct garbagelist *) &___locals___);");
3488 output.println("pthread_mutex_lock(&atomiclock);");
3489 output.println("restartaftergc();");
3490 output.println("}");
3492 output.println("pthread_mutex_lock(&atomiclock);");
3497 if (locality.getAtomic(lb).get(faen.getPrev(0)).intValue()>0)
3501 if (state.SANDBOX) {
3502 outsandbox.println("int atomiccounter"+sandboxcounter+"=LOW_CHECK_FREQUENCY;");
3503 output.println("counter_reset_pointer=&atomiccounter"+sandboxcounter+";");
3506 if (state.DELAYCOMP&&delaycomp.needsFission(lb, faen)) {
3507 AtomicRecord ar=atomicmethodmap.get(faen);
3509 for(Iterator<TempDescriptor> tmpit=ar.livein.iterator();tmpit.hasNext();) {
3510 TempDescriptor tmp=tmpit.next();
3511 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3514 //copy outs that depend on path
3515 for(Iterator<TempDescriptor> tmpit=ar.liveoutvirtualread.iterator();tmpit.hasNext();) {
3516 TempDescriptor tmp=tmpit.next();
3517 if (!ar.livein.contains(tmp))
3518 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3522 /* Backup the temps. */
3523 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3524 TempDescriptor tmp=tmpit.next();
3525 output.println(generateTemp(fm, backuptable.get(lb).get(tmp),lb)+"="+generateTemp(fm,tmp,lb)+";");
3528 output.println("goto transstart"+faen.getIdentifier()+";");
3530 /******* Print code to retry aborted transaction *******/
3531 output.println("transretry"+faen.getIdentifier()+":");
3534 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3535 TempDescriptor tmp=tmpit.next();
3536 output.println(generateTemp(fm, tmp,lb)+"="+generateTemp(fm,backuptable.get(lb).get(tmp),lb)+";");
3540 /********* Need to revert local object store ********/
3541 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3543 output.println("while ("+revertptr+") {");
3544 output.println("struct ___Object___ * tmpptr;");
3545 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3546 output.println("REVERT_OBJ("+revertptr+");");
3547 output.println(revertptr+"=tmpptr;");
3548 output.println("}");
3550 /******* Tell the runtime to start the transaction *******/
3552 output.println("transstart"+faen.getIdentifier()+":");
3553 if (state.SANDBOX) {
3554 output.println("transaction_check_counter=*counter_reset_pointer;");
3557 output.println("transStart();");
3559 if (state.ABORTREADERS||state.SANDBOX) {
3561 output.println("abortenabled=1;");
3562 output.println("if (_setjmp(aborttrans)) {");
3563 output.println(" goto transretry"+faen.getIdentifier()+"; }");
3567 public void generateFlatAtomicExitNode(FlatMethod fm, LocalityBinding lb, FlatAtomicExitNode faen, PrintWriter output) {
3568 /* Check to see if we need to generate code for this atomic */
3569 if (locality==null) {
3570 output.println("pthread_mutex_unlock(&atomiclock);");
3573 if (locality.getAtomic(lb).get(faen).intValue()>0)
3575 //store the revert list before we lose the transaction object
3578 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3579 output.println(revertptr+"=revertlist;");
3580 output.println("if (transCommit()) {");
3581 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3582 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3583 output.println("} else {");
3584 /* Need to commit local object store */
3585 output.println("while ("+revertptr+") {");
3586 output.println("struct ___Object___ * tmpptr;");
3587 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3588 output.println("COMMIT_OBJ("+revertptr+");");
3589 output.println(revertptr+"=tmpptr;");
3590 output.println("}");
3591 output.println("}");
3595 if (!state.DELAYCOMP) {
3597 output.println("if (transCommit()) {");
3598 /* Transaction aborts if it returns true */
3599 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3600 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3601 output.println("}");
3603 if (delaycomp.optimizeTrans(lb, faen.getAtomicEnter())&&(!state.STMARRAY||state.DUALVIEW)) {
3604 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3605 output.println("LIGHTWEIGHTCOMMIT("+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+", transretry"+faen.getAtomicEnter().getIdentifier()+");");
3607 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3608 TempDescriptor tmp=tmpit.next();
3609 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3611 } else if (delaycomp.needsFission(lb, faen.getAtomicEnter())) {
3612 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3614 output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {");
3615 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3616 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3617 output.println("}");
3619 output.println("else {");
3620 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3621 TempDescriptor tmp=tmpit.next();
3622 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3624 output.println("}");
3626 output.println("if (transCommit(NULL, NULL, NULL, NULL)) {");
3627 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3628 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3629 output.println("}");
3634 public void generateFlatSESEEnterNode( FlatMethod fm,
3636 FlatSESEEnterNode fsen,
3639 // if MLP flag is off, okay that SESE nodes are in IR graph,
3640 // just skip over them and code generates exactly the same
3641 if( !(state.MLP || state.OOOJAVA) ) {
3644 // there may be an SESE in an unreachable method, skip over
3645 if( (state.MLP && !mlpa.getAllSESEs().contains( fsen )) ||
3646 (state.OOOJAVA && !oooa.getAllSESEs().contains(fsen))
3651 // also, if we have encountered a placeholder, just skip it
3652 if( fsen.getIsCallerSESEplaceholder() ) {
3656 output.println(" {");
3658 if( state.COREPROF ) {
3659 output.println("#ifdef CP_EVENTID_TASKDISPATCH");
3660 output.println(" CP_LOGEVENT( CP_EVENTID_TASKDISPATCH, CP_EVENTTYPE_BEGIN );");
3661 output.println("#endif");
3664 // before doing anything, lock your own record and increment the running children
3665 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3666 (state.OOOJAVA && fsen != oooa.getMainSESE())
3668 output.println(" atomic_inc(&(runningSESE->numRunningChildren));");
3671 // allocate the space for this record
3672 output.println( "#ifndef OOO_DISABLE_TASKMEMPOOL" );
3673 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3674 (state.OOOJAVA && fsen != oooa.getMainSESE())
3677 fsen.getSESErecordName()+"* seseToIssue = ("+
3678 fsen.getSESErecordName()+"*) poolalloc( runningSESE->taskRecordMemPool );");
3681 fsen.getSESErecordName()+"* seseToIssue = ("+
3682 fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
3683 fsen.getSESErecordName()+" ) );");
3685 output.println( "#else" );
3687 fsen.getSESErecordName()+"* seseToIssue = ("+
3688 fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
3689 fsen.getSESErecordName()+" ) );");
3690 output.println( "#endif" );
3693 // set up the SESE in-set and out-set objects, which look
3694 // like a garbage list
3695 output.println(" struct garbagelist * gl= (struct garbagelist *)&(((SESEcommon*)(seseToIssue))[1]);");
3696 output.println(" gl->size="+calculateSizeOfSESEParamList(fsen)+";");
3697 output.println(" gl->next = NULL;");
3699 // there are pointers to SESE records the newly-issued SESE
3700 // will use to get values it depends on them for--how many
3701 // are there, and what is the offset from the total SESE
3702 // record to the first dependent record pointer?
3703 output.println(" seseToIssue->common.numDependentSESErecords="+
3704 fsen.getNumDepRecs()+";");
3706 // we only need this (and it will only compile) when the number of dependent
3707 // SESE records is non-zero
3708 if( fsen.getFirstDepRecField() != null ) {
3709 output.println(" seseToIssue->common.offsetToDepSESErecords=(INTPTR)sizeof("+
3710 fsen.getSESErecordName()+") - (INTPTR)&((("+
3711 fsen.getSESErecordName()+"*)0)->"+fsen.getFirstDepRecField()+");"
3715 // fill in common data
3716 output.println(" int localCount=0;");
3717 output.println(" seseToIssue->common.classID = "+fsen.getIdentifier()+";");
3718 output.println(" psem_init( &(seseToIssue->common.stallSem) );");
3720 output.println(" seseToIssue->common.forwardList = createQueue();");
3721 output.println(" seseToIssue->common.unresolvedDependencies = 10000;");
3722 output.println(" pthread_cond_init( &(seseToIssue->common.doneCond), NULL );");
3723 output.println(" seseToIssue->common.doneExecuting = FALSE;");
3724 output.println(" pthread_cond_init( &(seseToIssue->common.runningChildrenCond), NULL );");
3725 output.println(" seseToIssue->common.numRunningChildren = 0;");
3726 output.println(" seseToIssue->common.parent = runningSESE;");
3727 // start with refCount = 2, one being the count that the child itself
3728 // will decrement when it retires, to say it is done using its own
3729 // record, and the other count is for the parent that will remember
3730 // the static name of this new child below
3731 output.println(" seseToIssue->common.refCount = 2;");
3733 // all READY in-vars should be copied now and be done with it
3734 Iterator<TempDescriptor> tempItr = fsen.getReadyInVarSet().iterator();
3735 while( tempItr.hasNext() ) {
3736 TempDescriptor temp = tempItr.next();
3738 // when we are issuing the main SESE or an SESE with placeholder
3739 // caller SESE as parent, generate temp child child's eclosing method,
3740 // otherwise use the parent's enclosing method as the context
3741 boolean useParentContext = false;
3743 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3744 (state.OOOJAVA && fsen != oooa.getMainSESE())
3746 assert fsen.getParent() != null;
3747 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3748 useParentContext = true;
3752 if( useParentContext ) {
3753 output.println(" seseToIssue->"+temp+" = "+
3754 generateTemp( fsen.getParent().getfmBogus(), temp, null )+";");
3756 output.println(" seseToIssue->"+temp+" = "+
3757 generateTemp( fsen.getfmEnclosing(), temp, null )+";");
3761 // before potentially adding this SESE to other forwarding lists,
3763 output.println(" pthread_mutex_init( &(seseToIssue->common.lock), NULL );");
3765 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3766 (state.OOOJAVA && fsen != oooa.getMainSESE())
3768 // count up outstanding dependencies, static first, then dynamic
3769 Iterator<SESEandAgePair> staticSrcsItr = fsen.getStaticInVarSrcs().iterator();
3770 while( staticSrcsItr.hasNext() ) {
3771 SESEandAgePair srcPair = staticSrcsItr.next();
3772 output.println(" {");
3773 output.println(" SESEcommon* src = (SESEcommon*)"+srcPair+";");
3775 if(GENERATEPRECISEGC){
3776 output.println(" stopforgc((struct garbagelist *)&___locals___);");
3778 output.println(" pthread_mutex_lock( &(src->lock) );");
3779 if(GENERATEPRECISEGC){
3780 output.println(" restartaftergc();");
3782 output.println(" if( !isEmpty( src->forwardList ) &&");
3783 output.println(" seseToIssue == peekItem( src->forwardList ) ) {");
3784 output.println(" printf( \"This shouldnt already be here\\n\");");
3785 output.println(" exit( -1 );");
3786 output.println(" }");
3787 output.println(" if( !src->doneExecuting ) {");
3788 output.println(" addNewItem( src->forwardList, seseToIssue );");
3789 output.println(" ++(localCount);");
3790 output.println(" }");
3791 output.println(" ADD_REFERENCE_TO( src );");
3792 output.println(" pthread_mutex_unlock( &(src->lock) );");
3793 output.println(" }");
3795 // whether or not it is an outstanding dependency, make sure
3796 // to pass the static name to the child's record
3797 output.println(" seseToIssue->"+srcPair+" = "+
3798 "("+srcPair.getSESE().getSESErecordName()+"*)"+
3802 // dynamic sources might already be accounted for in the static list,
3803 // so only add them to forwarding lists if they're not already there
3804 Iterator<TempDescriptor> dynVarsItr = fsen.getDynamicInVarSet().iterator();
3805 while( dynVarsItr.hasNext() ) {
3806 TempDescriptor dynInVar = dynVarsItr.next();
3807 output.println(" {");
3808 output.println(" SESEcommon* src = (SESEcommon*)"+dynInVar+"_srcSESE;");
3810 // the dynamic source is NULL if it comes from your own space--you can't pass
3811 // the address off to the new child, because you're not done executing and
3812 // might change the variable, so copy it right now
3813 output.println(" if( src != NULL ) {");
3815 if(GENERATEPRECISEGC){
3816 output.println(" stopforgc((struct garbagelist *)&___locals___);");
3818 output.println(" pthread_mutex_lock( &(src->lock) );");
3819 if(GENERATEPRECISEGC){
3820 output.println(" restartaftergc();");
3822 output.println(" if( isEmpty( src->forwardList ) ||");
3823 output.println(" seseToIssue != peekItem( src->forwardList ) ) {");
3824 output.println(" if( !src->doneExecuting ) {");
3825 output.println(" addNewItem( src->forwardList, seseToIssue );");
3826 output.println(" ++(localCount);");
3827 output.println(" }");
3828 output.println(" }");
3829 output.println(" ADD_REFERENCE_TO( src );");
3830 output.println(" pthread_mutex_unlock( &(src->lock) );");
3831 output.println(" seseToIssue->"+dynInVar+"_srcOffset = "+dynInVar+"_srcOffset;");
3832 output.println(" } else {");
3834 boolean useParentContext = false;
3835 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3836 (state.OOOJAVA && fsen != oooa.getMainSESE())
3838 assert fsen.getParent() != null;
3839 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3840 useParentContext = true;
3843 if( useParentContext ) {
3844 output.println(" seseToIssue->"+dynInVar+" = "+
3845 generateTemp( fsen.getParent().getfmBogus(), dynInVar, null )+";");
3847 output.println(" seseToIssue->"+dynInVar+" = "+
3848 generateTemp( fsen.getfmEnclosing(), dynInVar, null )+";");
3851 output.println(" }");
3852 output.println(" }");
3854 // even if the value is already copied, make sure your NULL source
3855 // gets passed so child knows it already has the dynamic value
3856 output.println(" seseToIssue->"+dynInVar+"_srcSESE = "+dynInVar+"_srcSESE;");
3860 // maintain pointers for finding dynamic SESE
3861 // instances from static names
3862 SESEandAgePair pairNewest = new SESEandAgePair( fsen, 0 );
3863 SESEandAgePair pairOldest = new SESEandAgePair( fsen, fsen.getOldestAgeToTrack() );
3864 if( fsen.getParent() != null &&
3865 fsen.getParent().getNeededStaticNames().contains( pairNewest )
3868 for( int i = fsen.getOldestAgeToTrack(); i > 0; --i ) {
3869 SESEandAgePair pair1 = new SESEandAgePair( fsen, i );
3870 SESEandAgePair pair2 = new SESEandAgePair( fsen, i-1 );
3871 output.println(" "+pair1+" = "+pair2+";");
3873 output.println(" "+pairNewest+" = &(seseToIssue->common);");
3875 // no need to add a reference to whatever is the newest record, because
3876 // we initialized seseToIssue->refCount to *2*
3877 // but release a reference to whatever was the oldest BEFORE the shift
3878 output.println(" if( "+pairOldest+" != NULL ) {");
3879 output.println(" RELEASE_REFERENCE_TO( "+pairOldest+" );");
3880 output.println(" }");
3886 // count up memory conflict dependencies,
3890 //output.println(" seseToIssue->common.numMemoryQueue=0;");
3891 //output.println(" seseToIssue->common.rentryIdx=0;");
3892 //output.println(" seseToIssue->common.unresolvedRentryIdx=0;");
3893 //output.println(" seseToIssue->common.memoryQueueArray=NULL;");
3895 FlatSESEEnterNode parent = fsen.getParent();
3896 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(parent);
3897 if (graph != null && graph.hasConflictEdge()) {
3898 Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
3900 output.println(" //add memory queue element");
3901 Analysis.OoOJava.SESEWaitingQueue seseWaitingQueue=
3902 graph.getWaitingElementSetBySESEID(fsen.getIdentifier(), seseLockSet);
3903 if(seseWaitingQueue.getWaitingElementSize()>0){
3904 output.println(" {");
3905 output.println(" REntry* rentry=NULL;");
3906 output.println(" INTPTR* pointer=NULL;");
3907 output.println(" seseToIssue->common.rentryIdx=0;");
3909 Set<Integer> queueIDSet=seseWaitingQueue.getQueueIDSet();
3910 for (Iterator iterator = queueIDSet.iterator(); iterator
3912 Integer key = (Integer) iterator.next();
3913 int queueID=key.intValue();
3914 Set<Analysis.OoOJava.WaitingElement> waitingQueueSet =
3915 seseWaitingQueue.getWaitingElementSet(queueID);
3916 int enqueueType=seseWaitingQueue.getType(queueID);
3917 if(enqueueType==SESEWaitingQueue.EXCEPTION){
3918 output.println(" INITIALIZEBUF(runningSESE->memoryQueueArray["
3921 for (Iterator iterator2 = waitingQueueSet.iterator(); iterator2.hasNext();) {
3922 Analysis.OoOJava.WaitingElement waitingElement
3923 = (Analysis.OoOJava.WaitingElement) iterator2.next();
3924 if (waitingElement.getStatus() >= ConflictNode.COARSE) {
3925 output.println(" rentry=mlpCreateREntry("
3926 + waitingElement.getStatus()
3927 + ", &(seseToIssue->common));");
3929 TempDescriptor td = waitingElement.getTempDesc();
3930 // decide whether waiting element is dynamic or static
3931 if (fsen.getDynamicInVarSet().contains(td)) {
3932 // dynamic in-var case
3933 output.println(" pointer=seseToIssue->"
3934 + waitingElement.getDynID()
3935 + "_srcSESE+seseToIssue->"
3936 + waitingElement.getDynID()
3938 output.println(" rentry=mlpCreateFineREntry("
3939 + waitingElement.getStatus()
3940 + ", &(seseToIssue->common), pointer );");
3941 } else if (fsen.getStaticInVarSet().contains(td)) {
3942 // static in-var case
3943 VariableSourceToken vst = fsen.getStaticInVarSrc(td);
3946 String srcId = "SESE_"
3948 .getPrettyIdentifier()
3949 + vst.getSESE().getIdentifier()
3950 + "_" + vst.getAge();
3951 output.println(" pointer=(void*)&seseToIssue->"
3957 output.println(" rentry=mlpCreateFineREntry("
3958 + waitingElement.getStatus()
3959 + ", &(seseToIssue->common), pointer );");
3962 output.println(" rentry=mlpCreateFineREntry("
3963 + waitingElement.getStatus()
3964 + ", &(seseToIssue->common), (void*)&seseToIssue->"
3965 + waitingElement.getDynID()
3969 output.println(" rentry->queue=runningSESE->memoryQueueArray["
3970 + waitingElement.getQueueID()
3973 if(enqueueType==SESEWaitingQueue.NORMAL){
3974 output.println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
3975 output.println(" if(ADDRENTRY(runningSESE->memoryQueueArray["
3976 + waitingElement.getQueueID()
3977 + "],rentry)==NOTREADY){");
3978 output.println(" ++(localCount);");
3979 output.println(" }");
3981 // Trying to execute the dynamic coarse grain conflict strategy...
3982 if(state.RCR && rcr != null) {
3983 boolean useParentContext = false;
3985 if( (state.MLP &&fsen != mlpa.getMainSESE()) ||
3986 (state.OOOJAVA &&fsen != oooa.getMainSESE())) {
3987 assert fsen.getParent() != null;
3988 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3989 useParentContext = true;
3993 for (TempDescriptor invar : fsen.getInVarsForDynamicCoarseConflictResolution()) {
3995 if( useParentContext ) {
3996 varString = generateTemp( fsen.getParent().getfmBogus(), invar, null );
3998 varString = generateTemp( fsen.getfmEnclosing(), invar, null );
4000 output.println(" "+rcr.getTraverserInvocation(invar, varString, fsen));
4005 .println(" ADDRENTRYTOBUF(runningSESE->memoryQueueArray["
4006 + waitingElement.getQueueID()
4010 if(enqueueType!=SESEWaitingQueue.NORMAL){
4011 output.println(" localCount+=RESOLVEBUF(runningSESE->memoryQueueArray["
4012 + queueID+ "],&seseToIssue->common);");
4015 output.println(" }");
4021 ConflictGraph graph = null;
4022 FlatSESEEnterNode parent = fsen.getParent();
4023 if (parent != null) {
4024 if (parent.isCallerSESEplaceholder) {
4025 graph = mlpa.getConflictGraphResults().get(parent.getfmEnclosing());
4027 graph = mlpa.getConflictGraphResults().get(parent);
4030 if (graph != null && graph.hasConflictEdge()) {
4031 HashSet<SESELock> seseLockSet = mlpa.getConflictGraphLockMap()
4034 output.println(" //add memory queue element");
4035 SESEWaitingQueue seseWaitingQueue=graph.getWaitingElementSetBySESEID(fsen.getIdentifier(),
4037 if(seseWaitingQueue.getWaitingElementSize()>0){
4038 output.println(" {");
4039 output.println(" REntry* rentry=NULL;");
4040 output.println(" INTPTR* pointer=NULL;");
4041 output.println(" seseToIssue->common.rentryIdx=0;");
4043 Set<Integer> queueIDSet=seseWaitingQueue.getQueueIDSet();
4044 for (Iterator iterator = queueIDSet.iterator(); iterator
4046 Integer key = (Integer) iterator.next();
4047 int queueID=key.intValue();
4048 Set<WaitingElement> waitingQueueSet = seseWaitingQueue.getWaitingElementSet(queueID);
4049 int enqueueType=seseWaitingQueue.getType(queueID);
4050 if(enqueueType==SESEWaitingQueue.EXCEPTION){
4051 output.println(" INITIALIZEBUF(runningSESE->memoryQueueArray["
4054 for (Iterator iterator2 = waitingQueueSet.iterator(); iterator2
4056 WaitingElement waitingElement = (WaitingElement) iterator2
4058 if (waitingElement.getStatus() >= ConflictNode.COARSE) {
4059 output.println(" rentry=mlpCreateREntry("
4060 + waitingElement.getStatus()
4061 + ", &(seseToIssue->common));");
4063 TempDescriptor td = waitingElement
4065 // decide whether waiting element is dynamic or
4067 if (fsen.getDynamicInVarSet().contains(td)) {
4068 // dynamic in-var case
4069 output.println(" pointer=seseToIssue->"
4070 + waitingElement.getDynID()
4071 + "_srcSESE+seseToIssue->"
4072 + waitingElement.getDynID()
4075 .println(" rentry=mlpCreateFineREntry("
4078 + ", &(seseToIssue->common), pointer );");
4079 } else if (fsen.getStaticInVarSet()
4081 // static in-var case
4082 VariableSourceToken vst = fsen
4083 .getStaticInVarSrc(td);
4086 String srcId = "SESE_"
4088 .getPrettyIdentifier()
4089 + vst.getSESE().getIdentifier()
4090 + "_" + vst.getAge();
4092 .println(" pointer=(void*)&seseToIssue->"
4099 .println(" rentry=mlpCreateFineREntry("
4102 + ", &(seseToIssue->common), pointer );");
4107 .println(" rentry=mlpCreateFineREntry("
4110 + ", &(seseToIssue->common), (void*)&seseToIssue->"
4111 + waitingElement.getDynID()
4116 .println(" rentry->queue=runningSESE->memoryQueueArray["
4117 + waitingElement.getQueueID()
4120 if(enqueueType==SESEWaitingQueue.NORMAL){
4122 .println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
4124 .println(" if(ADDRENTRY(runningSESE->memoryQueueArray["
4125 + waitingElement.getQueueID()
4126 + "],rentry)==NOTREADY){");
4127 output.println(" ++(localCount);");
4128 output.println(" } ");
4131 .println(" ADDRENTRYTOBUF(runningSESE->memoryQueueArray["
4132 + waitingElement.getQueueID()
4136 if(enqueueType!=SESEWaitingQueue.NORMAL){
4137 output.println(" localCount+=RESOLVEBUF(runningSESE->memoryQueueArray["
4138 + queueID+ "],&seseToIssue->common);");
4141 output.println(" }");
4149 // release this SESE for siblings to update its dependencies or,
4150 // eventually, for it to mark itself finished
4151 // output.println(" pthread_mutex_unlock( &(seseToIssue->common.lock) );");
4153 // if there were no outstanding dependencies, issue here
4154 output.println(" if( atomic_sub_and_test(10000-localCount,&(seseToIssue->common.unresolvedDependencies) ) ) {");
4155 output.println(" workScheduleSubmit( (void*)seseToIssue );");
4156 output.println(" }");
4158 output.println(" if( seseToIssue->common.unresolvedDependencies == 0 ) {");
4159 output.println(" workScheduleSubmit( (void*)seseToIssue );");
4160 output.println(" }");
4162 // release this SESE for siblings to update its dependencies or,
4163 // eventually, for it to mark itself finished
4164 // output.println(" pthread_mutex_unlock( &(seseToIssue->common.lock) );");
4166 if( state.COREPROF ) {
4167 output.println("#ifdef CP_EVENTID_TASKDISPATCH");
4168 output.println(" CP_LOGEVENT( CP_EVENTID_TASKDISPATCH, CP_EVENTTYPE_END );");
4169 output.println("#endif");
4172 output.println(" }");
4176 public void generateFlatSESEExitNode( FlatMethod fm,
4178 FlatSESEExitNode fsexn,
4182 // if MLP flag is off, okay that SESE nodes are in IR graph,
4183 // just skip over them and code generates exactly the same
4184 if( ! (state.MLP || state.OOOJAVA) ) {
4188 // get the enter node for this exit that has meta data embedded
4189 FlatSESEEnterNode fsen = fsexn.getFlatEnter();
4191 // there may be an SESE in an unreachable method, skip over
4192 if( (state.MLP && !mlpa.getAllSESEs().contains( fsen )) ||
4193 (state.OOOJAVA && !oooa.getAllSESEs().contains( fsen ))
4198 // also, if we have encountered a placeholder, just jump it
4199 if( fsen.getIsCallerSESEplaceholder() ) {
4203 if( state.COREPROF ) {
4204 output.println("#ifdef CP_EVENTID_TASKEXECUTE");
4205 output.println(" CP_LOGEVENT( CP_EVENTID_TASKEXECUTE, CP_EVENTTYPE_END );");
4206 output.println("#endif");
4209 output.println(" /* SESE exiting */");
4211 if( state.COREPROF ) {
4212 output.println("#ifdef CP_EVENTID_TASKRETIRE");
4213 output.println(" CP_LOGEVENT( CP_EVENTID_TASKRETIRE, CP_EVENTTYPE_BEGIN );");
4214 output.println("#endif");
4217 String com = paramsprefix+"->common";
4219 // this SESE cannot be done until all of its children are done
4220 // so grab your own lock with the condition variable for watching
4221 // that the number of your running children is greater than zero
4222 if (GENERATEPRECISEGC){
4223 output.println(" stopforgc((struct garbagelist *)&___locals___);");
4225 output.println(" pthread_mutex_lock( &("+com+".lock) );");
4226 if (GENERATEPRECISEGC){
4227 output.println(" restartaftergc();");
4229 output.println(" while( "+com+".numRunningChildren > 0 ) {");
4230 if (GENERATEPRECISEGC){
4231 // output.println(" stopforgc((struct garbagelist *)&(((SESEcommon*)(___params___))[1]));");
4232 output.println(" stopforgc((struct garbagelist *)&___locals___);");
4234 output.println(" pthread_cond_wait( &("+com+".runningChildrenCond), &("+com+".lock) );");
4235 if (GENERATEPRECISEGC){
4236 output.println(" restartaftergc();");
4238 output.println(" }");
4241 // copy out-set from local temps into the sese record
4242 Iterator<TempDescriptor> itr = fsen.getOutVarSet().iterator();
4243 while( itr.hasNext() ) {
4244 TempDescriptor temp = itr.next();
4246 // only have to do this for primitives non-arrays
4248 temp.getType().isPrimitive() && !temp.getType().isArray()
4254 // have to determine the context enclosing this sese
4255 boolean useParentContext = false;
4257 if( (state.MLP &&fsen != mlpa.getMainSESE()) ||
4258 (state.OOOJAVA &&fsen != oooa.getMainSESE())
4260 assert fsen.getParent() != null;
4261 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
4262 useParentContext = true;
4267 if( useParentContext ) {
4268 from = generateTemp( fsen.getParent().getfmBogus(), temp, null );
4270 from = generateTemp( fsen.getfmEnclosing(), temp, null );
4273 output.println(" "+paramsprefix+
4274 "->"+temp.getSafeSymbol()+
4278 // mark yourself done, your SESE data is now read-only
4279 output.println(" "+com+".doneExecuting = TRUE;");
4280 output.println(" pthread_cond_signal( &("+com+".doneCond) );");
4281 output.println(" pthread_mutex_unlock( &("+com+".lock) );");
4283 // decrement dependency count for all SESE's on your forwarding list
4284 output.println(" while( !isEmpty( "+com+".forwardList ) ) {");
4285 output.println(" SESEcommon* consumer = (SESEcommon*) getItem( "+com+".forwardList );");
4288 output.println(" if(consumer->rentryIdx>0){");
4289 output.println(" // resolved null pointer");
4290 output.println(" int idx;");
4291 output.println(" for(idx=0;idx<consumer->rentryIdx;idx++){");
4292 output.println(" resolvePointer(consumer->rentryArray[idx]);");
4293 output.println(" }");
4294 output.println(" }");
4297 // output.println(" pthread_mutex_lock( &(consumer->lock) );");
4298 // output.println(" --(consumer->unresolvedDependencies);");
4299 // output.println(" if( consumer->unresolvedDependencies == 0 ) {");
4300 output.println(" if( atomic_sub_and_test(1, &(consumer->unresolvedDependencies)) ){");
4301 output.println(" workScheduleSubmit( (void*)consumer );");
4302 output.println(" }");
4303 // output.println(" pthread_mutex_unlock( &(consumer->lock) );");
4304 output.println(" }");
4308 // clean up its lock element from waiting queue, and decrement dependency count for next SESE block
4309 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
4310 (state.OOOJAVA && fsen != oooa.getMainSESE())
4314 output.println(" /* check memory dependency*/");
4315 output.println(" {");
4316 output.println(" int idx;");
4317 output.println(" for(idx=0;idx<___params___->common.rentryIdx;idx++){");
4318 output.println(" REntry* re=___params___->common.rentryArray[idx];");
4319 output.println(" RETIRERENTRY(re->queue,re);");
4320 output.println(" }");
4321 output.println(" }");
4325 // if parent is stalling on you, let them know you're done
4326 if( (state.MLP && fsexn.getFlatEnter() != mlpa.getMainSESE()) ||
4327 (state.OOOJAVA && fsexn.getFlatEnter() != oooa.getMainSESE())
4329 output.println(" psem_give( &("+paramsprefix+"->common.stallSem) );");
4332 // last of all, decrement your parent's number of running children
4333 output.println(" if( "+paramsprefix+"->common.parent != NULL ) {");
4334 output.println(" if (atomic_sub_and_test(1, &"+paramsprefix+"->common.parent->numRunningChildren)) {");
4335 if (GENERATEPRECISEGC){
4336 output.println(" stopforgc((struct garbagelist *)&___locals___);");
4338 output.println(" pthread_mutex_lock( &("+paramsprefix+"->common.parent->lock) );");
4339 if (GENERATEPRECISEGC){
4340 output.println(" restartaftergc();");
4342 output.println(" pthread_cond_signal( &("+paramsprefix+"->common.parent->runningChildrenCond) );");
4343 output.println(" pthread_mutex_unlock( &("+paramsprefix+"->common.parent->lock) );");
4344 output.println(" }");
4345 output.println(" }");
4347 // a task has variables to track static/dynamic instances
4348 // that serve as sources, release the parent's ref of each
4349 // non-null var of these types
4351 output.println(" // releasing static SESEs");
4352 Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
4353 while( pItr.hasNext() ) {
4354 SESEandAgePair pair = pItr.next();
4355 output.println(" if( "+pair+" != NULL ) {");
4356 output.println(" RELEASE_REFERENCE_TO( "+pair+" );");
4357 output.println(" }");
4359 output.println(" // releasing dynamic variable sources");
4360 Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
4361 while( dynSrcItr.hasNext() ) {
4362 TempDescriptor dynSrcVar = dynSrcItr.next();
4363 output.println(" if( "+dynSrcVar+"_srcSESE != NULL ) {");
4364 output.println(" RELEASE_REFERENCE_TO( "+dynSrcVar+"_srcSESE );");
4365 output.println(" }");
4369 // destroy this task's mempool if it is not a leaf task
4370 if( !fsen.getIsLeafSESE() ) {
4371 output.println( "#ifndef OOO_DISABLE_TASKMEMPOOL" );
4372 output.println(" pooldestroy( runningSESE->taskRecordMemPool );");
4373 output.println( "#endif" );
4377 // if this is not the Main sese (which has no parent) then return
4378 // THIS task's record to the PARENT'S task record pool, and only if
4379 // the reference count is now zero
4380 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
4381 (state.OOOJAVA && fsen != oooa.getMainSESE())
4383 output.println(" RELEASE_REFERENCE_TO( runningSESE );");
4385 // the main task has no parent, just free its record
4386 output.println(" mlpFreeSESErecord( runningSESE );");
4389 // as this thread is wrapping up the task, make sure the thread-local var
4390 // for the currently running task record references an invalid task
4391 output.println(" runningSESE = (SESEcommon*) 0x1;");
4393 if( state.COREPROF ) {
4394 output.println("#ifdef CP_EVENTID_TASKRETIRE");
4395 output.println(" CP_LOGEVENT( CP_EVENTID_TASKRETIRE, CP_EVENTTYPE_END );");
4396 output.println("#endif");
4400 public void generateFlatWriteDynamicVarNode( FlatMethod fm,
4402 FlatWriteDynamicVarNode fwdvn,
4405 if( !(state.MLP || state.OOOJAVA) ) {
4406 // should node should not be in an IR graph if the
4407 // MLP flag is not set
4408 throw new Error("Unexpected presence of FlatWriteDynamicVarNode");
4411 Hashtable<TempDescriptor, VSTWrapper> writeDynamic = fwdvn.getVar2src();
4413 assert writeDynamic != null;
4415 Iterator wdItr = writeDynamic.entrySet().iterator();
4416 while( wdItr.hasNext() ) {
4417 Map.Entry me = (Map.Entry) wdItr.next();
4418 TempDescriptor refVar = (TempDescriptor) me.getKey();
4419 VSTWrapper vstW = (VSTWrapper) me.getValue();
4420 VariableSourceToken vst = vstW.vst;
4422 output.println(" {");
4423 output.println(" SESEcommon* oldSrc = "+refVar+"_srcSESE;");
4426 // if there is no given source, this variable is ready so
4427 // mark src pointer NULL to signify that the var is up-to-date
4428 output.println(" "+refVar+"_srcSESE = NULL;");
4430 // otherwise we track where it will come from
4431 SESEandAgePair instance = new SESEandAgePair( vst.getSESE(), vst.getAge() );
4432 output.println(" "+refVar+"_srcSESE = "+instance+";");
4433 output.println(" "+refVar+"_srcOffset = (INTPTR) &((("+
4434 vst.getSESE().getSESErecordName()+"*)0)->"+vst.getAddrVar()+");");
4437 // no matter what we did above, track reference count of whatever
4438 // this variable pointed to, do release last in case we're just
4439 // copying the same value in because 1->2->1 is safe but ref count
4440 // 1->0->1 has a window where it looks like it should be free'd
4441 output.println(" if( "+refVar+"_srcSESE != NULL ) {");
4442 output.println(" ADD_REFERENCE_TO( "+refVar+"_srcSESE );");
4443 output.println(" }");
4444 output.println(" if( oldSrc != NULL ) {");
4445 output.println(" RELEASE_REFERENCE_TO( oldSrc );");
4446 output.println(" }");
4447 output.println(" }");
4452 private void generateFlatCheckNode(FlatMethod fm, LocalityBinding lb, FlatCheckNode fcn, PrintWriter output) {
4453 if (state.CONSCHECK) {
4454 String specname=fcn.getSpec();
4455 String varname="repairstate___";
4456 output.println("{");
4457 output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
4459 TempDescriptor[] temps=fcn.getTemps();
4460 String[] vars=fcn.getVars();
4461 for(int i=0; i<temps.length; i++) {
4462 output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i],lb)+";");
4465 output.println("if (doanalysis"+specname+"("+varname+")) {");
4466 output.println("free"+specname+"_state("+varname+");");
4467 output.println("} else {");
4468 output.println("/* Bad invariant */");
4469 output.println("free"+specname+"_state("+varname+");");
4470 output.println("abort_task();");
4471 output.println("}");
4472 output.println("}");
4476 private void generateFlatCall(FlatMethod fm, LocalityBinding lb, FlatCall fc, PrintWriter output) {
4478 MethodDescriptor md=fc.getMethod();
4479 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? locality.getBinding(lb, fc) : md);
4480 ClassDescriptor cn=md.getClassDesc();
4481 output.println("{");
4482 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4484 LocalityBinding fclb=locality.getBinding(lb, fc);
4485 output.print(" struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
4487 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
4488 output.print(objectparams.numPointers());
4489 output.print(", "+localsprefixaddr);
4490 if (md.getThis()!=null) {
4492 output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis(),lb));
4494 if (fc.getThis()!=null&&md.getThis()==null) {
4495 System.out.println("WARNING!!!!!!!!!!!!");
4496 System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
4500 for(int i=0; i<fc.numArgs(); i++) {
4501 Descriptor var=md.getParameter(i);
4502 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
4503 if (objectparams.isParamPtr(paramtemp)) {
4504 TempDescriptor targ=fc.getArg(i);
4506 TypeDescriptor td=md.getParamType(i);
4508 output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
4510 output.print("(struct "+md.getParamType(i).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
4513 output.println("};");
4518 if (fc.getReturnTemp()!=null)
4519 output.print(generateTemp(fm,fc.getReturnTemp(),lb)+"=");
4521 /* Do we need to do virtual dispatch? */
4522 if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
4525 LocalityBinding fclb=locality.getBinding(lb, fc);
4526 output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
4528 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
4533 if (md.getReturnType().isClass()||md.getReturnType().isArray())
4534 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
4536 output.print(md.getReturnType().getSafeSymbol()+" ");
4537 output.print("(*)(");
4539 boolean printcomma=false;
4540 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4542 LocalityBinding fclb=locality.getBinding(lb, fc);
4543 output.print("struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
4545 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
4549 for(int i=0; i<objectparams.numPrimitives(); i++) {
4550 TempDescriptor temp=objectparams.getPrimitive(i);
4554 if (temp.getType().isClass()||temp.getType().isArray())
4555 output.print("struct " + temp.getType().getSafeSymbol()+" * ");
4557 output.print(temp.getType().getSafeSymbol());
4562 LocalityBinding fclb=locality.getBinding(lb, fc);
4563 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])");
4565 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
4569 boolean needcomma=false;
4570 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4571 output.print("&__parameterlist__");
4575 if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
4576 if (fc.getThis()!=null) {
4577 TypeDescriptor ptd=md.getThis().getType();
4580 if (ptd.isClass()&&!ptd.isArray())
4581 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
4582 output.print(generateTemp(fm,fc.getThis(),lb));
4587 for(int i=0; i<fc.numArgs(); i++) {
4588 Descriptor var=md.getParameter(i);
4589 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
4590 if (objectparams.isParamPrim(paramtemp)) {
4591 TempDescriptor targ=fc.getArg(i);
4595 TypeDescriptor ptd=md.getParamType(i);
4596 if (ptd.isClass()&&!ptd.isArray())
4597 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
4598 output.print(generateTemp(fm, targ,lb));
4602 output.println(");");
4603 output.println(" }");
4606 private boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
4607 Set subclasses=typeutil.getSubClasses(thiscd);
4608 if (subclasses==null)
4610 for(Iterator classit=subclasses.iterator(); classit.hasNext();) {
4611 ClassDescriptor cd=(ClassDescriptor)classit.next();
4612 Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol());
4613 for(Iterator matchit=possiblematches.iterator(); matchit.hasNext();) {
4614 MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
4615 if (md.matches(matchmd))
4622 private void generateFlatFieldNode(FlatMethod fm, LocalityBinding lb, FlatFieldNode ffn, PrintWriter output) {
4623 if (state.SINGLETM) {
4624 //single machine transactional memory case
4625 String field=ffn.getField().getSafeSymbol();
4626 String src=generateTemp(fm, ffn.getSrc(),lb);
4627 String dst=generateTemp(fm, ffn.getDst(),lb);
4629 output.println(dst+"="+ src +"->"+field+ ";");
4630 if (ffn.getField().getType().isPtr()&&locality.getAtomic(lb).get(ffn).intValue()>0&&
4631 locality.getNodePreTempInfo(lb, ffn).get(ffn.getSrc())!=LocalityAnalysis.SCRATCH) {
4632 if ((dc==null)||(!state.READSET&&dc.getNeedTrans(lb, ffn))||
4633 (state.READSET&&dc.getNeedWriteTrans(lb, ffn))) {
4634 output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));");
4635 } else if (state.READSET&&dc.getNeedTrans(lb, ffn)) {
4636 if (state.HYBRID&&delaycomp.getConv(lb).contains(ffn)) {
4637 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4639 output.println("TRANSREADRD("+dst+", "+dst+");");
4642 } else if (state.DSM) {
4643 Integer status=locality.getNodePreTempInfo(lb,ffn).get(ffn.getSrc());
4644 if (status==LocalityAnalysis.GLOBAL) {
4645 String field=ffn.getField().getSafeSymbol();
4646 String src=generateTemp(fm, ffn.getSrc(),lb);
4647 String dst=generateTemp(fm, ffn.getDst(),lb);
4649 if (ffn.getField().getType().isPtr()) {
4651 //TODO: Uncomment this when we have runtime support
4652 //if (ffn.getSrc()==ffn.getDst()) {
4653 //output.println("{");
4654 //output.println("void * temp="+src+";");
4655 //output.println("if (temp&0x1) {");
4656 //output.println("temp=(void *) transRead(trans, (unsigned int) temp);");
4657 //output.println(src+"->"+field+"="+temp+";");
4658 //output.println("}");
4659 //output.println(dst+"=temp;");
4660 //output.println("}");
4662 output.println(dst+"="+ src +"->"+field+ ";");
4663 //output.println("if ("+dst+"&0x1) {");
4664 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
4665 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
4666 //output.println(src+"->"+field+"="+src+"->"+field+";");
4667 //output.println("}");
4670 output.println(dst+"="+ src+"->"+field+";");
4672 } else if (status==LocalityAnalysis.LOCAL) {
4673 if (ffn.getField().getType().isPtr()&&
4674 ffn.getField().isGlobal()) {
4675 String field=ffn.getField().getSafeSymbol();
4676 String src=generateTemp(fm, ffn.getSrc(),lb);
4677 String dst=generateTemp(fm, ffn.getDst(),lb);
4678 output.println(dst+"="+ src +"->"+field+ ";");
4679 if (locality.getAtomic(lb).get(ffn).intValue()>0)
4680 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
4681 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
4683 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4684 } else if (status==LocalityAnalysis.EITHER) {
4685 //Code is reading from a null pointer
4686 output.println("if ("+generateTemp(fm, ffn.getSrc(),lb)+") {");
4687 output.println("#ifndef RAW");
4688 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4689 output.println("#endif");
4690 //This should throw a suitable null pointer error
4691 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4693 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4695 // DEBUG if(!ffn.getDst().getType().isPrimitive()){
4696 // DEBUG output.println("within((void*)"+generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+");");
4698 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4703 private void generateFlatSetFieldNode(FlatMethod fm, LocalityBinding lb, FlatSetFieldNode fsfn, PrintWriter output) {
4704 if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
4705 throw new Error("Can't set array length");
4706 if (state.SINGLETM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
4707 //Single Machine Transaction Case
4708 boolean srcptr=fsfn.getSrc().getType().isPtr();
4709 String src=generateTemp(fm,fsfn.getSrc(),lb);
4710 String dst=generateTemp(fm,fsfn.getDst(),lb);
4711 output.println("//"+srcptr+" "+fsfn.getSrc().getType().isNull());
4712 if (srcptr&&!fsfn.getSrc().getType().isNull()) {
4713 output.println("{");
4714 if ((dc==null)||dc.getNeedSrcTrans(lb, fsfn)&&
4715 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) {
4716 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4718 output.println("INTPTR srcoid=(INTPTR)"+src+";");
4721 if (wb.needBarrier(fsfn)&&
4722 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getDst())!=LocalityAnalysis.SCRATCH) {
4723 if (state.EVENTMONITOR) {
4724 output.println("if ("+dst+"->___objstatus___&DIRTY) EVLOGEVENTOBJ(EV_WRITE,"+dst+"->objuid)");
4726 output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;");
4728 if (srcptr&!fsfn.getSrc().getType().isNull()) {
4729 output.println("*((unsigned INTPTR *)&("+dst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4730 output.println("}");
4732 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4734 } else if (state.DSM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
4735 Integer statussrc=locality.getNodePreTempInfo(lb,fsfn).get(fsfn.getSrc());
4736 Integer statusdst=locality.getNodeTempInfo(lb).get(fsfn).get(fsfn.getDst());
4737 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4739 String src=generateTemp(fm,fsfn.getSrc(),lb);
4740 String dst=generateTemp(fm,fsfn.getDst(),lb);
4742 output.println("{");
4743 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4745 if (statusdst.equals(LocalityAnalysis.GLOBAL)) {
4748 if (wb.needBarrier(fsfn))
4749 output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;");
4751 output.println("*((unsigned INTPTR *)&("+glbdst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4753 output.println(glbdst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4754 } else if (statusdst.equals(LocalityAnalysis.LOCAL)) {
4755 /** Check if we need to copy */
4756 output.println("if(!"+dst+"->"+localcopystr+") {");
4757 /* Link object into list */
4758 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4759 output.println(revertptr+"=revertlist;");
4760 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4761 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4763 output.println("COPY_OBJ("+dst+");");
4764 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4765 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4766 output.println("}");
4768 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4770 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4771 } else if (statusdst.equals(LocalityAnalysis.EITHER)) {
4772 //writing to a null...bad
4773 output.println("if ("+dst+") {");
4774 output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}");
4776 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4778 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4781 output.println("}");
4784 if (state.FASTCHECK) {
4785 String dst=generateTemp(fm, fsfn.getDst(),lb);
4786 output.println("if(!"+dst+"->"+localcopystr+") {");
4787 /* Link object into list */
4788 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4789 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4791 output.println("COPY_OBJ("+dst+");");
4792 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4793 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4794 output.println("}");
4797 // DEBUG if(!fsfn.getField().getType().isPrimitive()){
4798 // DEBUG output.println("within((void*)"+generateTemp(fm,fsfn.getSrc(),lb)+");");
4800 output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
4804 private void generateFlatElementNode(FlatMethod fm, LocalityBinding lb, FlatElementNode fen, PrintWriter output) {
4805 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
4808 if (elementtype.isArray()||elementtype.isClass())
4811 type=elementtype.getSafeSymbol()+" ";
4813 if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
4814 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fen.getIndex(),lb)+") >= "+generateTemp(fm,fen.getSrc(),lb) + "->___length___))");
4815 output.println("failedboundschk();");
4817 if (state.SINGLETM) {
4818 //Single machine transaction case
4819 String dst=generateTemp(fm, fen.getDst(),lb);
4820 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))) {
4821 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4823 output.println("STMGETARRAY("+dst+", "+ generateTemp(fm,fen.getSrc(),lb)+", "+generateTemp(fm, fen.getIndex(),lb)+", "+type+");");
4826 if (elementtype.isPtr()&&locality.getAtomic(lb).get(fen).intValue()>0&&
4827 locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())!=LocalityAnalysis.SCRATCH) {
4828 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fen)||state.READSET&&dc.getNeedWriteTrans(lb, fen)) {
4829 output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));");
4830 } else if (state.READSET&&dc.getNeedTrans(lb, fen)) {
4831 if (state.HYBRID&&delaycomp.getConv(lb).contains(fen)) {
4832 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4834 output.println("TRANSREADRD("+dst+", "+dst+");");
4837 } else if (state.DSM) {
4838 Integer status=locality.getNodePreTempInfo(lb,fen).get(fen.getSrc());
4839 if (status==LocalityAnalysis.GLOBAL) {
4840 String dst=generateTemp(fm, fen.getDst(),lb);
4841 if (elementtype.isPtr()) {
4842 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4843 //DEBUG: output.println("TRANSREAD("+dst+", "+dst+",\""+fm+":"+fen+"\");");
4844 output.println("TRANSREAD("+dst+", "+dst+");");
4846 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4848 } else if (status==LocalityAnalysis.LOCAL) {
4849 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4850 } else if (status==LocalityAnalysis.EITHER) {
4851 //Code is reading from a null pointer
4852 output.println("if ("+generateTemp(fm, fen.getSrc(),lb)+") {");
4853 output.println("#ifndef RAW");
4854 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4855 output.println("#endif");
4856 //This should throw a suitable null pointer error
4857 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4859 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4861 // DEBUG output.println("within((void*)"+generateTemp(fm,fen.getSrc(),lb)+");");
4862 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4866 private void generateFlatSetElementNode(FlatMethod fm, LocalityBinding lb, FlatSetElementNode fsen, PrintWriter output) {
4867 //TODO: need dynamic check to make sure this assignment is actually legal
4868 //Because Object[] could actually be something more specific...ie. Integer[]
4870 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
4873 if (elementtype.isArray()||elementtype.isClass())
4876 type=elementtype.getSafeSymbol()+" ";
4878 if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
4879 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fsen.getIndex(),lb)+") >= "+generateTemp(fm,fsen.getDst(),lb) + "->___length___))");
4880 output.println("failedboundschk();");
4883 if (state.SINGLETM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4884 //Transaction set element case
4885 if (wb.needBarrier(fsen)&&
4886 locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH) {
4887 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___objstatus___))|=DIRTY;");
4889 if (fsen.getSrc().getType().isPtr()&&!fsen.getSrc().getType().isNull()) {
4890 output.println("{");
4891 String src=generateTemp(fm, fsen.getSrc(), lb);
4892 if ((dc==null)||dc.getNeedSrcTrans(lb, fsen)&&
4893 locality.getNodePreTempInfo(lb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) {
4894 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4896 output.println("INTPTR srcoid=(INTPTR)"+src+";");
4898 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
4899 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", srcoid, INTPTR);");
4901 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
4903 output.println("}");
4905 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
4906 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", "+ generateTemp(fm, fsen.getSrc(), lb) +", "+type+");");
4908 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4911 } else if (state.DSM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4912 Integer statussrc=locality.getNodePreTempInfo(lb,fsen).get(fsen.getSrc());
4913 Integer statusdst=locality.getNodePreTempInfo(lb,fsen).get(fsen.getDst());
4914 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4915 boolean dstglobal=statusdst==LocalityAnalysis.GLOBAL;
4916 boolean dstlocal=(statusdst==LocalityAnalysis.LOCAL)||(statusdst==LocalityAnalysis.EITHER);
4919 if (wb.needBarrier(fsen))
4920 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___localcopy___))|=DIRTY;");
4921 } else if (dstlocal) {
4922 /** Check if we need to copy */
4923 String dst=generateTemp(fm, fsen.getDst(),lb);
4924 output.println("if(!"+dst+"->"+localcopystr+") {");
4925 /* Link object into list */
4926 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4927 output.println(revertptr+"=revertlist;");
4928 if ((GENERATEPRECISEGC) || this.state.MULTICOREGC)
4929 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4931 output.println("COPY_OBJ("+dst+");");
4932 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4933 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4934 output.println("}");
4936 System.out.println("Node: "+fsen);
4937 System.out.println(lb);
4938 System.out.println("statusdst="+statusdst);
4939 System.out.println(fm.printMethod());
4940 throw new Error("Unknown array type");
4943 output.println("{");
4944 String src=generateTemp(fm, fsen.getSrc(), lb);
4945 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4946 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
4947 output.println("}");
4949 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4952 if (state.FASTCHECK) {
4953 String dst=generateTemp(fm, fsen.getDst(),lb);
4954 output.println("if(!"+dst+"->"+localcopystr+") {");
4955 /* Link object into list */
4956 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4957 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4959 output.println("COPY_OBJ("+dst+");");
4960 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4961 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4962 output.println("}");
4964 // DEBUG output.println("within((void*)"+generateTemp(fm,fsen.getDst(),lb)+");");
4965 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4969 protected void generateFlatNew(FlatMethod fm, LocalityBinding lb, FlatNew fn, PrintWriter output) {
4970 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
4971 //Stash pointer in case of GC
4972 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4973 output.println(revertptr+"=revertlist;");
4975 if (state.SINGLETM) {
4976 if (fn.getType().isArray()) {
4977 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4978 if (locality.getAtomic(lb).get(fn).intValue()>0) {
4979 //inside transaction
4980 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4982 //outside transaction
4983 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4986 if (locality.getAtomic(lb).get(fn).intValue()>0) {
4987 //inside transaction
4988 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4990 //outside transaction
4991 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4994 } else if (fn.getType().isArray()) {
4995 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4996 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4997 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4998 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4999 if(this.state.MLP || state.OOOJAVA){
5000 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray_mlp("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+", oid, "+oooa.getDisjointAnalysis().getAllocationSiteFromFlatNew(fn).getUniqueAllocSiteID()+");");
5001 output.println(" oid += numWorkers;");
5003 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
5006 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
5009 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
5010 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");");
5011 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5012 if (this.state.MLP || state.OOOJAVA){
5013 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new_mlp("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+", oid, "+oooa.getDisjointAnalysis().getAllocationSiteFromFlatNew(fn).getUniqueAllocSiteID()+");");
5014 output.println(" oid += numWorkers;");
5016 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
5019 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
5022 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
5023 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5024 String dst=generateTemp(fm,fn.getDst(),lb);
5025 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
5026 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
5027 output.println("revertlist=(struct ___Object___ *)"+dst+";");
5029 if (state.FASTCHECK) {
5030 String dst=generateTemp(fm,fn.getDst(),lb);
5031 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
5032 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
5033 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
5037 private void generateFlatTagDeclaration(FlatMethod fm, LocalityBinding lb, FlatTagDeclaration fn, PrintWriter output) {
5038 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5039 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
5041 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+state.getTagId(fn.getType())+");");
5045 private void generateFlatOpNode(FlatMethod fm, LocalityBinding lb, FlatOpNode fon, PrintWriter output) {
5046 if (fon.getRight()!=null) {
5047 if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
5048 if (fon.getLeft().getType().isLong())
5049 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
5051 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned int)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
5053 } else if (dc!=null) {
5054 output.print(generateTemp(fm, fon.getDest(),lb)+" = (");
5055 if (fon.getLeft().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
5056 output.print("(void *)");
5057 if (dc.getNeedLeftSrcTrans(lb, fon))
5058 output.print("("+generateTemp(fm, fon.getLeft(),lb)+"!=NULL?"+generateTemp(fm, fon.getLeft(),lb)+"->"+oidstr+":NULL)");
5060 output.print(generateTemp(fm, fon.getLeft(),lb));
5061 output.print(")"+fon.getOp().toString()+"(");
5062 if (fon.getRight().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
5063 output.print("(void *)");
5064 if (dc.getNeedRightSrcTrans(lb, fon))
5065 output.println("("+generateTemp(fm, fon.getRight(),lb)+"!=NULL?"+generateTemp(fm, fon.getRight(),lb)+"->"+oidstr+":NULL));");
5067 output.println(generateTemp(fm,fon.getRight(),lb)+");");
5069 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+fon.getOp().toString()+generateTemp(fm,fon.getRight(),lb)+";");
5070 } else if (fon.getOp().getOp()==Operation.ASSIGN)
5071 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
5072 else if (fon.getOp().getOp()==Operation.UNARYPLUS)
5073 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
5074 else if (fon.getOp().getOp()==Operation.UNARYMINUS)
5075 output.println(generateTemp(fm, fon.getDest(),lb)+" = -"+generateTemp(fm, fon.getLeft(),lb)+";");
5076 else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
5077 output.println(generateTemp(fm, fon.getDest(),lb)+" = !"+generateTemp(fm, fon.getLeft(),lb)+";");
5078 else if (fon.getOp().getOp()==Operation.COMP)
5079 output.println(generateTemp(fm, fon.getDest(),lb)+" = ~"+generateTemp(fm, fon.getLeft(),lb)+";");
5080 else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
5081 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+"->fses==NULL;");
5083 output.println(generateTemp(fm, fon.getDest(),lb)+fon.getOp().toString()+generateTemp(fm, fon.getLeft(),lb)+";");
5086 private void generateFlatCastNode(FlatMethod fm, LocalityBinding lb, FlatCastNode fcn, PrintWriter output) {
5087 /* TODO: Do type check here */
5088 if (fcn.getType().isArray()) {
5089 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
5090 } else if (fcn.getType().isClass())
5091 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
5093 output.println(generateTemp(fm,fcn.getDst(),lb)+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc(),lb)+";");
5096 private void generateFlatLiteralNode(FlatMethod fm, LocalityBinding lb, FlatLiteralNode fln, PrintWriter output) {
5097 if (fln.getValue()==null)
5098 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
5099 else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
5100 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5101 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
5102 //Stash pointer in case of GC
5103 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5104 output.println(revertptr+"=revertlist;");
5106 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
5107 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
5108 //Stash pointer in case of GC
5109 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5110 output.println("revertlist="+revertptr+";");
5113 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
5115 } else if (fln.getType().isBoolean()) {
5116 if (((Boolean)fln.getValue()).booleanValue())
5117 output.println(generateTemp(fm, fln.getDst(),lb)+"=1;");
5119 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
5120 } else if (fln.getType().isChar()) {
5121 String st=FlatLiteralNode.escapeString(fln.getValue().toString());
5122 output.println(generateTemp(fm, fln.getDst(),lb)+"='"+st+"';");
5123 } else if (fln.getType().isLong()) {
5124 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+"LL;");
5126 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+";");
5129 protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) {
5130 if (frn.getReturnTemp()!=null) {
5131 if (frn.getReturnTemp().getType().isPtr())
5132 output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";");
5134 output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";");
5136 output.println("return;");
5140 protected void generateStoreFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
5143 //only record if this group has more than one exit
5144 if (branchanalysis.numJumps(fcb)>1) {
5145 left=branchanalysis.jumpValue(fcb, 0);
5146 right=branchanalysis.jumpValue(fcb, 1);
5148 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") {");
5150 output.println("STOREBRANCH("+right+");");
5151 output.println("goto "+label+";");
5152 output.println("}");
5154 output.println("STOREBRANCH("+left+");");
5157 protected void generateFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
5158 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") goto "+label+";");
5161 /** This method generates header information for the method or
5162 * task referenced by the Descriptor des. */
5163 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) {
5164 generateHeader(fm, lb, des, output, false);
5167 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output, boolean addSESErecord) {
5169 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : des);
5170 MethodDescriptor md=null;
5171 TaskDescriptor task=null;
5172 if (des instanceof MethodDescriptor)
5173 md=(MethodDescriptor) des;
5175 task=(TaskDescriptor) des;
5177 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
5179 if (md!=null&&md.getReturnType()!=null) {
5180 if (md.getReturnType().isClass()||md.getReturnType().isArray())
5181 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
5183 output.print(md.getReturnType().getSafeSymbol()+" ");
5185 //catch the constructor case
5186 output.print("void ");
5188 if (state.DSM||state.SINGLETM) {
5189 output.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
5191 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
5193 output.print(task.getSafeSymbol()+"(");
5195 boolean printcomma=false;
5196 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5198 if (state.DSM||state.SINGLETM) {
5199 output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
5201 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
5203 output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
5209 for(int i=0; i<objectparams.numPrimitives(); i++) {
5210 TempDescriptor temp=objectparams.getPrimitive(i);
5214 if (temp.getType().isClass()||temp.getType().isArray())
5215 output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
5217 output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
5219 output.println(") {");
5220 } else if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
5221 /* Imprecise Task */
5222 output.println("void * parameterarray[]) {");
5223 /* Unpack variables */
5224 for(int i=0; i<objectparams.numPrimitives(); i++) {
5225 TempDescriptor temp=objectparams.getPrimitive(i);
5226 output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
5228 for(int i=0; i<fm.numTags(); i++) {
5229 TempDescriptor temp=fm.getTag(i);
5230 int offset=i+objectparams.numPrimitives();
5231 output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
5234 if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
5235 maxtaskparams=objectparams.numPrimitives()+fm.numTags();
5236 } else output.println(") {");
5239 public void generateFlatFlagActionNode(FlatMethod fm, LocalityBinding lb, FlatFlagActionNode ffan, PrintWriter output) {
5240 output.println("/* FlatFlagActionNode */");
5243 /* Process tag changes */
5244 Relation tagsettable=new Relation();
5245 Relation tagcleartable=new Relation();
5247 Iterator tagsit=ffan.getTempTagPairs();
5248 while (tagsit.hasNext()) {
5249 TempTagPair ttp=(TempTagPair) tagsit.next();
5250 TempDescriptor objtmp=ttp.getTemp();
5251 TagDescriptor tag=ttp.getTag();
5252 TempDescriptor tagtmp=ttp.getTagTemp();
5253 boolean tagstatus=ffan.getTagChange(ttp);
5255 tagsettable.put(objtmp, tagtmp);
5257 tagcleartable.put(objtmp, tagtmp);
5262 Hashtable flagandtable=new Hashtable();
5263 Hashtable flagortable=new Hashtable();
5265 /* Process flag changes */
5266 Iterator flagsit=ffan.getTempFlagPairs();
5267 while(flagsit.hasNext()) {
5268 TempFlagPair tfp=(TempFlagPair)flagsit.next();
5269 TempDescriptor temp=tfp.getTemp();
5270 Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
5271 FlagDescriptor flag=tfp.getFlag();
5273 //Newly allocate objects that don't set any flags case
5274 if (flagortable.containsKey(temp)) {
5278 flagortable.put(temp,new Integer(mask));
5280 int flagid=1<<((Integer)flagtable.get(flag)).intValue();
5281 boolean flagstatus=ffan.getFlagChange(tfp);
5284 if (flagortable.containsKey(temp)) {
5285 mask=((Integer)flagortable.get(temp)).intValue();
5288 flagortable.put(temp,new Integer(mask));
5290 int mask=0xFFFFFFFF;
5291 if (flagandtable.containsKey(temp)) {
5292 mask=((Integer)flagandtable.get(temp)).intValue();
5294 mask&=(0xFFFFFFFF^flagid);
5295 flagandtable.put(temp,new Integer(mask));
5301 HashSet flagtagset=new HashSet();
5302 flagtagset.addAll(flagortable.keySet());
5303 flagtagset.addAll(flagandtable.keySet());
5304 flagtagset.addAll(tagsettable.keySet());
5305 flagtagset.addAll(tagcleartable.keySet());
5307 Iterator ftit=flagtagset.iterator();
5308 while(ftit.hasNext()) {
5309 TempDescriptor temp=(TempDescriptor)ftit.next();
5312 Set tagtmps=tagcleartable.get(temp);
5313 if (tagtmps!=null) {
5314 Iterator tagit=tagtmps.iterator();
5315 while(tagit.hasNext()) {
5316 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
5317 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
5318 output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5320 output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5324 tagtmps=tagsettable.get(temp);
5325 if (tagtmps!=null) {
5326 Iterator tagit=tagtmps.iterator();
5327 while(tagit.hasNext()) {
5328 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
5329 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
5330 output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5332 output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp, lb)+", "+generateTemp(fm,tagtmp, lb)+");");
5337 int andmask=0xFFFFFFF;
5339 if (flagortable.containsKey(temp))
5340 ormask=((Integer)flagortable.get(temp)).intValue();
5341 if (flagandtable.containsKey(temp))
5342 andmask=((Integer)flagandtable.get(temp)).intValue();
5343 generateFlagOrAnd(ffan, fm, lb, temp, output, ormask, andmask);
5344 generateObjectDistribute(ffan, fm, lb, temp, output);
5348 protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp,
5349 PrintWriter output, int ormask, int andmask) {
5350 if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
5351 output.println("flagorandinit("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
5353 output.println("flagorand("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
5357 protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, PrintWriter output) {
5358 output.println("enqueueObject("+generateTemp(fm, temp, lb)+");");
5361 void generateOptionalHeader(PrintWriter headers) {
5364 headers.println("#include \"task.h\"\n\n");
5365 headers.println("#ifndef _OPTIONAL_STRUCT_");
5366 headers.println("#define _OPTIONAL_STRUCT_");
5368 //STRUCT PREDICATEMEMBER
5369 headers.println("struct predicatemember{");
5370 headers.println("int type;");
5371 headers.println("int numdnfterms;");
5372 headers.println("int * flags;");
5373 headers.println("int numtags;");
5374 headers.println("int * tags;\n};\n\n");
5376 //STRUCT OPTIONALTASKDESCRIPTOR
5377 headers.println("struct optionaltaskdescriptor{");
5378 headers.println("struct taskdescriptor * task;");
5379 headers.println("int index;");
5380 headers.println("int numenterflags;");
5381 headers.println("int * enterflags;");
5382 headers.println("int numpredicatemembers;");
5383 headers.println("struct predicatemember ** predicatememberarray;");
5384 headers.println("};\n\n");
5386 //STRUCT TASKFAILURE
5387 headers.println("struct taskfailure {");
5388 headers.println("struct taskdescriptor * task;");
5389 headers.println("int index;");
5390 headers.println("int numoptionaltaskdescriptors;");
5391 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
5393 //STRUCT FSANALYSISWRAPPER
5394 headers.println("struct fsanalysiswrapper{");
5395 headers.println("int flags;");
5396 headers.println("int numtags;");
5397 headers.println("int * tags;");
5398 headers.println("int numtaskfailures;");
5399 headers.println("struct taskfailure ** taskfailurearray;");
5400 headers.println("int numoptionaltaskdescriptors;");
5401 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
5403 //STRUCT CLASSANALYSISWRAPPER
5404 headers.println("struct classanalysiswrapper{");
5405 headers.println("int type;");
5406 headers.println("int numotd;");
5407 headers.println("struct optionaltaskdescriptor ** otdarray;");
5408 headers.println("int numfsanalysiswrappers;");
5409 headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
5411 headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
5413 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
5414 while(taskit.hasNext()) {
5415 TaskDescriptor td=(TaskDescriptor)taskit.next();
5416 headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
5421 //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
5422 int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
5423 int predicateindex = 0;
5424 //iterate through the classes concerned by the predicate
5425 Set c_vard = predicate.vardescriptors;
5426 Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
5429 for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext();) {
5430 VarDescriptor vard = (VarDescriptor)vard_it.next();
5431 TypeDescriptor typed = vard.getType();
5433 //generate for flags
5434 HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
5435 output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5437 if (fen_hashset!=null) {
5438 for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext();) {
5439 FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
5441 DNFFlag dflag=fen.getDNF();
5442 numberterms+=dflag.size();
5444 Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
5446 for(int j=0; j<dflag.size(); j++) {
5448 output.println(",");
5449 Vector term=dflag.get(j);
5452 for(int k=0; k<term.size(); k++) {
5453 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
5454 FlagDescriptor fd=dfa.getFlag();
5455 boolean negated=dfa.getNegated();
5456 int flagid=1<<((Integer)flags.get(fd)).intValue();
5461 output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
5466 output.println("};\n");
5469 TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
5470 output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5473 for(int j=0; j<tagel.numTags(); j++) {
5475 output.println(",");
5476 TempDescriptor tmp=tagel.getTemp(j);
5477 if (!slotnumber.containsKey(tmp)) {
5478 Integer slotint=new Integer(current_slot++);
5479 slotnumber.put(tmp,slotint);
5481 int slot=slotnumber.get(tmp).intValue();
5482 output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
5484 numtags = tagel.numTags();
5486 output.println("};");
5488 //store the result into a predicatemember struct
5489 output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
5490 output.println("/*type*/"+typed.getClassDesc().getId()+",");
5491 output.println("/* number of dnf terms */"+numberterms+",");
5492 output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5493 output.println("/* number of tag */"+numtags+",");
5494 output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5495 output.println("};\n");
5500 //generate an array that stores the entire predicate
5501 output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5502 for( int j = 0; j<predicateindex; j++) {
5503 if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5504 else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5506 output.println("};\n");
5507 return predicateindex;
5511 void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
5512 generateOptionalHeader(headers);
5514 output.println("#include \"optionalstruct.h\"\n\n");
5515 output.println("#include \"stdlib.h\"\n");
5517 HashSet processedcd = new HashSet();
5519 Enumeration e = safeexecution.keys();
5520 while (e.hasMoreElements()) {
5523 ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
5524 Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp); //will be used several times
5526 //Generate the struct of optionals
5527 Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
5528 numotd = c_otd.size();
5529 if(maxotd<numotd) maxotd = numotd;
5530 if( !c_otd.isEmpty() ) {
5531 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
5532 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
5534 //generate the int arrays for the predicate
5535 Predicate predicate = otd.predicate;
5536 int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
5537 TreeSet<Integer> fsset=new TreeSet<Integer>();
5538 //iterate through possible FSes corresponding to
5539 //the state when entering
5541 for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext();) {
5542 FlagState fs = (FlagState)fses.next();
5544 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
5545 FlagDescriptor flagd = (FlagDescriptor)flags.next();
5546 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
5549 fsset.add(new Integer(flagid));
5550 //tag information not needed because tag
5551 //changes are not tolerated.
5554 output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5555 boolean needcomma=false;
5556 for(Iterator<Integer> it=fsset.iterator(); it.hasNext();) {
5559 output.println(it.next());
5562 output.println("};\n");
5565 //generate optionaltaskdescriptor that actually
5566 //includes exit fses, predicate and the task
5568 output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
5569 output.println("&task_"+otd.td.getSafeSymbol()+",");
5570 output.println("/*index*/"+otd.getIndex()+",");
5571 output.println("/*number of enter flags*/"+fsset.size()+",");
5572 output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5573 output.println("/*number of members */"+predicateindex+",");
5574 output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5575 output.println("};\n");
5579 // if there are no optionals, there is no need to build the rest of the struct
5581 output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
5582 c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
5583 if( !c_otd.isEmpty() ) {
5584 boolean needcomma=false;
5585 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
5586 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
5588 output.println(",");
5590 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5593 output.println("};\n");
5595 //get all the possible flagstates reachable by an object
5596 Hashtable hashtbtemp = safeexecution.get(cdtemp);
5598 TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
5599 fsts.addAll(hashtbtemp.keySet());
5600 for(Iterator fsit=fsts.iterator(); fsit.hasNext();) {
5601 FlagState fs = (FlagState)fsit.next();
5604 //get the set of OptionalTaskDescriptors corresponding
5605 HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
5606 //iterate through the OptionalTaskDescriptors and
5607 //store the pointers to the optionals struct (see on
5608 //top) into an array
5610 output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
5611 for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext();) {
5612 OptionalTaskDescriptor mm = mos.next();
5614 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
5616 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5619 output.println("};\n");
5621 //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
5624 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
5625 FlagDescriptor flagd = (FlagDescriptor)flags.next();
5626 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
5630 //process tag information
5633 boolean first = true;
5634 Enumeration tag_enum = fs.getTags();
5635 output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
5636 while(tag_enum.hasMoreElements()) {
5638 TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
5642 output.println(", ");
5643 output.println("/*tagid*/"+state.getTagId(tagd));
5645 output.println("};");
5647 Set<TaskIndex> tiset=sa.getTaskIndex(fs);
5648 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
5649 TaskIndex ti=itti.next();
5653 Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
5655 output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
5656 boolean needcomma=false;
5657 for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext();) {
5658 OptionalTaskDescriptor otd=otdit.next();
5662 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5664 output.println("};");
5666 output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
5667 output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
5668 output.print(ti.getIndex()+", ");
5669 output.print(otdset.size()+", ");
5670 output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
5671 output.println("};");
5674 tiset=sa.getTaskIndex(fs);
5675 boolean needcomma=false;
5677 output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
5678 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
5679 TaskIndex ti=itti.next();
5680 if (ti.isRuntime()) {
5687 output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
5689 output.println("};\n");
5691 //Store the result in fsanalysiswrapper
5693 output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
5694 output.println("/*flag*/"+flagid+",");
5695 output.println("/* number of tags*/"+tagcounter+",");
5696 output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
5697 output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
5698 output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
5699 output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
5700 output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
5701 output.println("};\n");
5705 //Build the array of fsanalysiswrappers
5706 output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
5707 boolean needcomma=false;
5708 for(int i = 0; i<fscounter; i++) {
5709 if (needcomma) output.print(",");
5710 output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
5713 output.println("};");
5715 //Build the classanalysiswrapper referring to the previous array
5716 output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
5717 output.println("/*type*/"+cdtemp.getId()+",");
5718 output.println("/*numotd*/"+numotd+",");
5719 output.println("otdarray"+cdtemp.getSafeSymbol()+",");
5720 output.println("/* number of fsanalysiswrappers */"+fscounter+",");
5721 output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
5722 processedcd.add(cdtemp);
5725 //build an array containing every classes for which code has been build
5726 output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
5727 for(int i=0; i<state.numClasses(); i++) {
5728 ClassDescriptor cn=cdarray[i];
5731 if ((cn != null) && (processedcd.contains(cn)))
5732 output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
5734 output.print("NULL");
5736 output.println("};");
5738 output.println("#define MAXOTD "+maxotd);
5739 headers.println("#endif");
5742 public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
5743 Relation r=new Relation();
5744 for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext();) {
5745 OptionalTaskDescriptor otd=otdit.next();
5746 TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
5750 LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
5751 for(Iterator it=r.keySet().iterator(); it.hasNext();) {
5752 Set s=r.get(it.next());
5753 for(Iterator it2=s.iterator(); it2.hasNext();) {
5754 OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
5762 protected void outputTransCode(PrintWriter output) {
5765 private int calculateSizeOfSESEParamList(FlatSESEEnterNode fsen){
5767 Set<TempDescriptor> tdSet=new HashSet<TempDescriptor>();
5769 for (Iterator iterator = fsen.getInVarSet().iterator(); iterator.hasNext();) {
5770 TempDescriptor tempDescriptor = (TempDescriptor) iterator.next();
5771 if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()){
5772 tdSet.add(tempDescriptor);
5776 for (Iterator iterator = fsen.getOutVarSet().iterator(); iterator.hasNext();) {
5777 TempDescriptor tempDescriptor = (TempDescriptor) iterator.next();
5778 if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()){
5779 tdSet.add(tempDescriptor);
5783 return tdSet.size();
5786 private String calculateSizeOfSESEParamSize(FlatSESEEnterNode fsen){
5787 HashMap <String,Integer> map=new HashMap();
5788 HashSet <TempDescriptor> processed=new HashSet<TempDescriptor>();
5791 // space for all in and out set primitives
5792 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
5793 inSetAndOutSet.addAll( fsen.getInVarSet() );
5794 inSetAndOutSet.addAll( fsen.getOutVarSet() );
5796 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
5798 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
5799 while( itr.hasNext() ) {
5800 TempDescriptor temp = itr.next();
5801 TypeDescriptor type = temp.getType();
5802 if( !type.isPtr() ) {
5803 inSetAndOutSetPrims.add( temp );
5807 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
5808 while( itrPrims.hasNext() ) {
5809 TempDescriptor temp = itrPrims.next();
5810 TypeDescriptor type = temp.getType();
5811 if(type.isPrimitive()){
5812 Integer count=map.get(type.getSymbol());
5814 count=new Integer(1);
5815 map.put(type.getSymbol(), count);
5817 map.put(type.getSymbol(), new Integer(count.intValue()+1));
5822 Set<String> keySet=map.keySet();
5823 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
5824 String key = (String) iterator.next();
5825 rtr+="+sizeof("+key+")*"+map.get(key);