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);
277 rcr.setGlobalEffects(oooa.getDisjointAnalysis().getEffectsAnalysis().getAllEffects());
279 catch (FileNotFoundException e) {
280 System.out.println("Runtime Conflict Resolver could not create output file.");
284 while(seseit.hasNext()){
285 FlatSESEEnterNode fsen = seseit.next();
286 initializeSESE( fsen );
288 //this code will culminate all conflicts into one master hashtable.
289 if(state.RCR && rcr != null) {
290 Analysis.OoOJava.ConflictGraph conflictGraph;
291 Hashtable<Taint, Set<Effect>> conflicts;
293 if(!fsen.getIsCallerSESEplaceholder() && fsen.getParent()!=null &&
294 (conflictGraph = oooa.getConflictGraph(fsen.getParent())) != null &&
295 (conflicts = conflictGraph.getConflictEffectSet(fsen)) != null){
297 FlatMethod fm=fsen.getfmEnclosing();
298 ReachGraph rg=oooa.getDisjointAnalysis().getReachGraph(fm.getMethod());
300 rg.writeGraph("RCR_RG_SESE_DEBUG");
302 rcr.addToTraverseToDoList(fsen, rg, conflicts);
308 /* Build the actual methods */
309 outputMethods(outmethod);
311 // Output function prototypes and structures for SESE's and code
312 if( state.MLP || state.OOOJAVA ) {
314 // spit out a global to inform all worker threads with
315 // the maximum size is for any task record
316 outmethod.println("int "+maxTaskRecSizeStr+" = 0;");
318 // used to differentiate, during code generation, whether we are
319 // passing over SESE body code, or non-SESE code
322 // first generate code for each sese's internals
323 Iterator<FlatSESEEnterNode> seseit;
325 seseit=mlpa.getAllSESEs().iterator();
327 seseit=oooa.getAllSESEs().iterator();
330 while(seseit.hasNext()) {
331 FlatSESEEnterNode fsen = seseit.next();
332 generateMethodSESE(fsen, null, outstructs, outmethodheader, outmethod);
335 // then write the invokeSESE switch to decouple scheduler
336 // from having to do unique details of sese invocation
337 generateSESEinvocationMethod(outmethodheader, outmethod);
341 /* Output code for tasks */
342 outputTaskCode(outtaskdefs, outmethod);
344 /* Record maximum number of task parameters */
345 outstructs.println("#define MAXTASKPARAMS "+maxtaskparams);
346 } else if (state.main!=null) {
347 /* Generate main method */
348 outputMainMethod(outmethod);
351 /* Generate information for task with optional parameters */
352 if (state.TASK&&state.OPTIONAL) {
353 generateOptionalArrays(outoptionalarrays, optionalheaders, state.getAnalysisResult(), state.getOptionalTaskDescriptors());
354 outoptionalarrays.close();
357 /* Output structure definitions for repair tool */
358 if (state.structfile!=null) {
359 buildRepairStructs(outrepairstructs);
360 outrepairstructs.close();
364 outmethodheader.println("#endif");
365 outmethodheader.close();
367 outstructs.println("#endif");
371 System.out.println("Runtime Conflict Resolver Done.");
376 /* This code just generates the main C method for java programs.
377 * The main C method packs up the arguments into a string array
378 * and passes it to the java main method. */
380 private void outputMainMethod(PrintWriter outmethod) {
381 outmethod.println("int main(int argc, const char *argv[]) {");
382 outmethod.println(" int i;");
384 if (state.MLP || state.OOOJAVA) {
386 // do a calculation to determine which task record
387 // is the largest, store that as a global value for
388 // allocating records
389 Iterator<FlatSESEEnterNode> seseit;
391 seseit=mlpa.getAllSESEs().iterator();
393 seseit=oooa.getAllSESEs().iterator();
395 while(seseit.hasNext()){
396 FlatSESEEnterNode fsen = seseit.next();
397 outmethod.println("if( sizeof( "+fsen.getSESErecordName()+
398 " ) > "+maxTaskRecSizeStr+
399 " ) { "+maxTaskRecSizeStr+
400 " = sizeof( "+fsen.getSESErecordName()+
404 outmethod.println(" runningSESE = NULL;");
406 outmethod.println(" workScheduleInit( "+state.MLP_NUMCORES+", invokeSESEmethod );");
408 //initializes data structures needed for the RCR traverser
409 if(state.RCR && rcr != null) {
410 outmethod.println(" initializeStructsRCR();");
415 if (state.DSMRECOVERYSTATS) {
416 outmethod.println("#ifdef RECOVERYSTATS \n");
417 outmethod.println("handle();\n");
418 outmethod.println("#endif\n");
420 outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n");
421 outmethod.println("handle();\n");
422 outmethod.println("#endif\n");
426 if (state.THREAD||state.DSM||state.SINGLETM) {
427 outmethod.println("initializethreads();");
430 outmethod.println("if (dstmStartup(argv[1])) {");
431 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
432 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-2);");
434 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-2);");
437 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
438 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1);");
440 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1);");
444 outmethod.println(" for(i=2;i<argc;i++) {");
446 outmethod.println(" for(i=1;i<argc;i++) {");
447 outmethod.println(" int length=strlen(argv[i]);");
448 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
449 outmethod.println(" struct ___String___ *newstring=NewString(NULL, argv[i], length);");
451 outmethod.println(" struct ___String___ *newstring=NewString(argv[i], length);");
454 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-2]=newstring;");
456 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-1]=newstring;");
457 outmethod.println(" }");
459 MethodDescriptor md=typeutil.getMain();
460 ClassDescriptor cd=typeutil.getMainClass();
462 outmethod.println(" {");
463 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
464 if (state.DSM||state.SINGLETM) {
465 outmethod.print(" struct "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
467 outmethod.print(" struct "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
468 outmethod.println("1, NULL,"+"stringarray};");
469 if (state.DSM||state.SINGLETM)
470 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
472 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
474 if (state.DSM||state.SINGLETM)
475 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
477 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
479 outmethod.println(" }");
482 outmethod.println("}");
485 if (state.THREAD||state.DSM||state.SINGLETM) {
486 outmethod.println("pthread_mutex_lock(&gclistlock);");
487 outmethod.println("threadcount--;");
488 outmethod.println("pthread_cond_signal(&gccond);");
489 outmethod.println("pthread_mutex_unlock(&gclistlock);");
492 if (state.DSM||state.SINGLETM) {
493 //outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n");
494 outmethod.println("#if defined(TRANSSTATS) \n");
495 outmethod.println("printf(\"****** Transaction Stats ******\\n\");");
496 outmethod.println("printf(\"numTransCommit= %d\\n\", numTransCommit);");
497 outmethod.println("printf(\"numTransAbort= %d\\n\", numTransAbort);");
498 outmethod.println("printf(\"nSoftAbort= %d\\n\", nSoftAbort);");
500 outmethod.println("printf(\"nchashSearch= %d\\n\", nchashSearch);");
501 outmethod.println("printf(\"nmhashSearch= %d\\n\", nmhashSearch);");
502 outmethod.println("printf(\"nprehashSearch= %d\\n\", nprehashSearch);");
503 outmethod.println("printf(\"ndirtyCacheObj= %d\\n\", ndirtyCacheObj);");
504 outmethod.println("printf(\"nRemoteReadSend= %d\\n\", nRemoteSend);");
505 outmethod.println("printf(\"bytesSent= %d\\n\", bytesSent);");
506 outmethod.println("printf(\"bytesRecv= %d\\n\", bytesRecv);");
507 outmethod.println("printf(\"totalObjSize= %d\\n\", totalObjSize);");
508 outmethod.println("printf(\"sendRemoteReq= %d\\n\", sendRemoteReq);");
509 outmethod.println("printf(\"getResponse= %d\\n\", getResponse);");
510 } else if (state.SINGLETM) {
511 outmethod.println("printf(\"nSoftAbortAbort= %d\\n\", nSoftAbortAbort);");
512 outmethod.println("printf(\"nSoftAbortCommit= %d\\n\", nSoftAbortCommit);");
513 outmethod.println("#ifdef STMSTATS\n");
514 outmethod.println("for(i=0; i<TOTALNUMCLASSANDARRAY; i++) {\n");
515 outmethod.println(" printf(\"typesCausingAbort[%2d] numaccess= %5d numabort= %3d\\n\", i, typesCausingAbort[i].numaccess, typesCausingAbort[i].numabort);\n");
516 outmethod.println("}\n");
517 outmethod.println("#endif\n");
518 outmethod.println("fflush(stdout);");
520 outmethod.println("#endif\n");
523 if (state.EVENTMONITOR) {
524 outmethod.println("dumpdata();");
527 if (state.THREAD||state.SINGLETM)
528 outmethod.println("pthread_exit(NULL);");
530 if (state.MLP || state.OOOJAVA ) {
531 outmethod.println(" workScheduleBegin();");
534 outmethod.println("}");
537 /* This method outputs code for each task. */
539 private void outputTaskCode(PrintWriter outtaskdefs, PrintWriter outmethod) {
540 /* Compile task based program */
541 outtaskdefs.println("#include \"task.h\"");
542 outtaskdefs.println("#include \"methodheaders.h\"");
543 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
544 while(taskit.hasNext()) {
545 TaskDescriptor td=(TaskDescriptor)taskit.next();
546 FlatMethod fm=state.getMethodFlat(td);
547 generateFlatMethod(fm, null, outmethod);
548 generateTaskDescriptor(outtaskdefs, fm, td);
551 //Output task descriptors
552 taskit=state.getTaskSymbolTable().getDescriptorsIterator();
553 outtaskdefs.println("struct taskdescriptor * taskarray[]= {");
555 while(taskit.hasNext()) {
556 TaskDescriptor td=(TaskDescriptor)taskit.next();
560 outtaskdefs.println(",");
561 outtaskdefs.print("&task_"+td.getSafeSymbol());
563 outtaskdefs.println("};");
565 outtaskdefs.println("int numtasks="+state.getTaskSymbolTable().getValueSet().size()+";");
568 /* This method outputs most of the methods.c file. This includes
569 * some standard includes and then an array with the sizes of
570 * objets and array that stores supertype and then the code for
571 * the Java methods.. */
573 protected void outputMethods(PrintWriter outmethod) {
574 outmethod.println("#include \"methodheaders.h\"");
575 outmethod.println("#include \"virtualtable.h\"");
576 outmethod.println("#include \"runtime.h\"");
578 // always include: compiler directives will leave out
579 // instrumentation when option is not set
580 outmethod.println("#include \"coreprof/coreprof.h\"");
583 outmethod.println("#include \"sandboxdefs.c\"");
586 outmethod.println("#include \"addPrefetchEnhance.h\"");
587 outmethod.println("#include \"localobjects.h\"");
589 if (state.FASTCHECK) {
590 outmethod.println("#include \"localobjects.h\"");
592 if(state.MULTICORE) {
593 outmethod.println("#include \"task.h\"");
594 outmethod.println("#include \"multicoreruntime.h\"");
595 outmethod.println("#include \"runtime_arch.h\"");
597 if (state.THREAD||state.DSM||state.SINGLETM)
598 outmethod.println("#include <thread.h>");
599 if (state.main!=null) {
600 outmethod.println("#include <string.h>");
602 if (state.CONSCHECK) {
603 outmethod.println("#include \"checkers.h\"");
605 if (state.MLP || state.OOOJAVA ) {
606 outmethod.println("#include <stdlib.h>");
607 outmethod.println("#include <stdio.h>");
608 outmethod.println("#include \"mlp_runtime.h\"");
609 outmethod.println("#include \"psemaphore.h\"");
611 if( state.RCR && rcr != null) {
612 outmethod.println("#include \"RuntimeConflictResolver.h\"");
616 //Store the sizes of classes & array elements
617 generateSizeArray(outmethod);
619 //Store table of supertypes
620 generateSuperTypeTable(outmethod);
622 //Store the layout of classes
623 generateLayoutStructs(outmethod);
625 /* Generate code for methods */
626 if (state.DSM||state.SINGLETM) {
627 for(Iterator<LocalityBinding> lbit=locality.getLocalityBindings().iterator(); lbit.hasNext();) {
628 LocalityBinding lb=lbit.next();
629 MethodDescriptor md=lb.getMethod();
630 FlatMethod fm=state.getMethodFlat(md);
632 if (!md.getModifiers().isNative()) {
633 generateFlatMethod(fm, lb, outmethod);
634 //System.out.println("fm= " + fm + " md= " + md);
638 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
639 while(classit.hasNext()) {
640 ClassDescriptor cn=(ClassDescriptor)classit.next();
641 Iterator methodit=cn.getMethods();
642 while(methodit.hasNext()) {
643 /* Classify parameters */
644 MethodDescriptor md=(MethodDescriptor)methodit.next();
645 FlatMethod fm=state.getMethodFlat(md);
646 if (!md.getModifiers().isNative()) {
647 generateFlatMethod(fm, null, outmethod);
654 protected void outputStructs(PrintWriter outstructs) {
655 outstructs.println("#ifndef STRUCTDEFS_H");
656 outstructs.println("#define STRUCTDEFS_H");
657 outstructs.println("#include \"classdefs.h\"");
658 outstructs.println("#ifndef INTPTR");
659 outstructs.println("#ifdef BIT64");
660 outstructs.println("#define INTPTR long");
661 outstructs.println("#else");
662 outstructs.println("#define INTPTR int");
663 outstructs.println("#endif");
664 outstructs.println("#endif");
665 if( state.MLP || state.OOOJAVA ) {
666 outstructs.println("#include \"mlp_runtime.h\"");
667 outstructs.println("#include \"psemaphore.h\"");
670 /* Output #defines that the runtime uses to determine type
671 * numbers for various objects it needs */
672 outstructs.println("#define MAXCOUNT "+maxcount);
673 if (state.DSM||state.SINGLETM) {
674 LocalityBinding lbrun=new LocalityBinding(typeutil.getRun(), false);
676 lbrun.setGlobalThis(LocalityAnalysis.GLOBAL);
678 else if (state.SINGLETM) {
679 lbrun.setGlobalThis(LocalityAnalysis.NORMAL);
681 outstructs.println("#define RUNMETHOD "+virtualcalls.getLocalityNumber(lbrun));
685 LocalityBinding lbexecute = new LocalityBinding(typeutil.getExecute(), false);
687 lbexecute.setGlobalThis(LocalityAnalysis.GLOBAL);
688 else if( state.SINGLETM)
689 lbexecute.setGlobalThis(LocalityAnalysis.NORMAL);
690 outstructs.println("#define EXECUTEMETHOD " + virtualcalls.getLocalityNumber(lbexecute));
693 outstructs.println("#define STRINGARRAYTYPE "+
694 (state.getArrayNumber(
695 (new TypeDescriptor(typeutil.getClass(TypeUtil.StringClass))).makeArray(state))+state.numClasses()));
697 outstructs.println("#define OBJECTARRAYTYPE "+
698 (state.getArrayNumber(
699 (new TypeDescriptor(typeutil.getClass(TypeUtil.ObjectClass))).makeArray(state))+state.numClasses()));
702 outstructs.println("#define STRINGTYPE "+typeutil.getClass(TypeUtil.StringClass).getId());
703 outstructs.println("#define CHARARRAYTYPE "+
704 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.CHAR)).makeArray(state))+state.numClasses()));
706 outstructs.println("#define BYTEARRAYTYPE "+
707 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state))+state.numClasses()));
709 outstructs.println("#define BYTEARRAYARRAYTYPE "+
710 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state).makeArray(state))+state.numClasses()));
712 outstructs.println("#define NUMCLASSES "+state.numClasses());
713 int totalClassSize = state.numClasses() + state.numArrays();
714 outstructs.println("#define TOTALNUMCLASSANDARRAY "+ totalClassSize);
716 outstructs.println("#define STARTUPTYPE "+typeutil.getClass(TypeUtil.StartupClass).getId());
717 outstructs.println("#define TAGTYPE "+typeutil.getClass(TypeUtil.TagClass).getId());
718 outstructs.println("#define TAGARRAYTYPE "+
719 (state.getArrayNumber(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)).makeArray(state))+state.numClasses()));
723 protected void outputClassDeclarations(PrintWriter outclassdefs) {
724 if (state.THREAD||state.DSM||state.SINGLETM)
725 outclassdefs.println("#include <pthread.h>");
726 outclassdefs.println("#ifndef INTPTR");
727 outclassdefs.println("#ifdef BIT64");
728 outclassdefs.println("#define INTPTR long");
729 outclassdefs.println("#else");
730 outclassdefs.println("#define INTPTR int");
731 outclassdefs.println("#endif");
732 outclassdefs.println("#endif");
734 outclassdefs.println("#include \"optionalstruct.h\"");
735 outclassdefs.println("struct "+arraytype+";");
736 /* Start by declaring all structs */
737 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
738 while(it.hasNext()) {
739 ClassDescriptor cn=(ClassDescriptor)it.next();
740 outclassdefs.println("struct "+cn.getSafeSymbol()+";");
742 outclassdefs.println("");
743 //Print out definition for array type
744 outclassdefs.println("struct "+arraytype+" {");
745 outclassdefs.println(" int type;");
746 if(state.MLP || state.OOOJAVA ){
747 outclassdefs.println(" int oid;");
748 outclassdefs.println(" int allocsite;");
750 if (state.EVENTMONITOR) {
751 outclassdefs.println(" int objuid;");
754 outclassdefs.println(" pthread_t tid;");
755 outclassdefs.println(" void * lockentry;");
756 outclassdefs.println(" int lockcount;");
759 outclassdefs.println(" int flag;");
760 if(!state.MULTICORE) {
761 outclassdefs.println(" void * flagptr;");
763 outclassdefs.println(" int version;");
764 outclassdefs.println(" int * lock;"); // lock entry for this obj
765 outclassdefs.println(" int mutex;");
766 outclassdefs.println(" int lockcount;");
767 if(state.MULTICOREGC) {
768 outclassdefs.println(" int marked;");
772 outclassdefs.println(" int numfses;");
773 outclassdefs.println(" int * fses;");
776 printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs);
778 if (state.STMARRAY) {
779 outclassdefs.println(" int lowindex;");
780 outclassdefs.println(" int highindex;");
783 outclassdefs.println(" int paddingforarray;");
784 if (state.DUALVIEW) {
785 outclassdefs.println(" int arrayversion;");
788 outclassdefs.println(" int ___length___;");
789 outclassdefs.println("};\n");
790 outclassdefs.println("extern int classsize[];");
791 outclassdefs.println("extern int hasflags[];");
792 outclassdefs.println("extern unsigned INTPTR * pointerarray[];");
793 outclassdefs.println("extern int supertypes[];");
796 /** Prints out definitions for generic task structures */
798 private void outputTaskTypes(PrintWriter outtask) {
799 outtask.println("#ifndef _TASK_H");
800 outtask.println("#define _TASK_H");
801 outtask.println("struct parameterdescriptor {");
802 outtask.println("int type;");
803 outtask.println("int numberterms;");
804 outtask.println("int *intarray;");
805 outtask.println("void * queue;");
806 outtask.println("int numbertags;");
807 outtask.println("int *tagarray;");
808 outtask.println("};");
810 outtask.println("struct taskdescriptor {");
811 outtask.println("void * taskptr;");
812 outtask.println("int numParameters;");
813 outtask.println(" int numTotal;");
814 outtask.println("struct parameterdescriptor **descriptorarray;");
815 outtask.println("char * name;");
816 outtask.println("};");
817 outtask.println("extern struct taskdescriptor * taskarray[];");
818 outtask.println("extern numtasks;");
819 outtask.println("#endif");
823 private void buildRepairStructs(PrintWriter outrepairstructs) {
824 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
825 while(classit.hasNext()) {
826 ClassDescriptor cn=(ClassDescriptor)classit.next();
827 outrepairstructs.println("structure "+cn.getSymbol()+" {");
828 outrepairstructs.println(" int __type__;");
830 outrepairstructs.println(" int __flag__;");
831 if(!state.MULTICORE) {
832 outrepairstructs.println(" int __flagptr__;");
835 printRepairStruct(cn, outrepairstructs);
836 outrepairstructs.println("}\n");
839 for(int i=0; i<state.numArrays(); i++) {
840 TypeDescriptor tdarray=arraytable[i];
841 TypeDescriptor tdelement=tdarray.dereference();
842 outrepairstructs.println("structure "+arraytype+"_"+state.getArrayNumber(tdarray)+" {");
843 outrepairstructs.println(" int __type__;");
844 printRepairStruct(typeutil.getClass(TypeUtil.ObjectClass), outrepairstructs);
845 outrepairstructs.println(" int length;");
847 // Need to add support to repair tool for this
848 if (tdelement.isClass()||tdelement.isArray())
849 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" * elem[this.length];");
851 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" elem[this.length];");
853 outrepairstructs.println("}\n");
857 private void printRepairStruct(ClassDescriptor cn, PrintWriter output) {
858 ClassDescriptor sp=cn.getSuperDesc();
860 printRepairStruct(sp, output);
862 Vector fields=(Vector)fieldorder.get(cn);
864 for(int i=0; i<fields.size(); i++) {
865 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
866 if (fd.getType().isArray()) {
867 output.println(" "+arraytype+"_"+ state.getArrayNumber(fd.getType()) +" * "+fd.getSymbol()+";");
868 } else if (fd.getType().isClass())
869 output.println(" "+fd.getType().getRepairSymbol()+" * "+fd.getSymbol()+";");
870 else if (fd.getType().isFloat())
871 output.println(" int "+fd.getSymbol()+"; /* really float */");
873 output.println(" "+fd.getType().getRepairSymbol()+" "+fd.getSymbol()+";");
877 /** This method outputs TaskDescriptor information */
878 private void generateTaskDescriptor(PrintWriter output, FlatMethod fm, TaskDescriptor task) {
879 for (int i=0; i<task.numParameters(); i++) {
880 VarDescriptor param_var=task.getParameter(i);
881 TypeDescriptor param_type=task.getParamType(i);
882 FlagExpressionNode param_flag=task.getFlag(param_var);
883 TagExpressionList param_tag=task.getTag(param_var);
886 if (param_flag==null) {
887 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
888 output.println("0x0, 0x0 };");
891 DNFFlag dflag=param_flag.getDNF();
892 dnfterms=dflag.size();
894 Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
895 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
896 for(int j=0; j<dflag.size(); j++) {
899 Vector term=dflag.get(j);
902 for(int k=0; k<term.size(); k++) {
903 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
904 FlagDescriptor fd=dfa.getFlag();
905 boolean negated=dfa.getNegated();
906 int flagid=1<<((Integer)flags.get(fd)).intValue();
911 output.print("0x"+Integer.toHexString(andmask)+", 0x"+Integer.toHexString(checkmask));
913 output.println("};");
916 output.println("int parametertag_"+i+"_"+task.getSafeSymbol()+"[]={");
917 //BUG...added next line to fix, test with any task program
919 for(int j=0; j<param_tag.numTags(); j++) {
922 /* for each tag we need */
923 /* which slot it is */
924 /* what type it is */
925 TagVarDescriptor tvd=(TagVarDescriptor)task.getParameterTable().get(param_tag.getName(j));
926 TempDescriptor tmp=param_tag.getTemp(j);
927 int slot=fm.getTagInt(tmp);
928 output.println(slot+", "+state.getTagId(tvd.getTag()));
930 output.println("};");
932 output.println("struct parameterdescriptor parameter_"+i+"_"+task.getSafeSymbol()+"={");
933 output.println("/* type */"+param_type.getClassDesc().getId()+",");
934 output.println("/* number of DNF terms */"+dnfterms+",");
935 output.println("parameterdnf_"+i+"_"+task.getSafeSymbol()+",");
936 output.println("0,");
937 //BUG, added next line to fix and else statement...test
938 //with any task program
940 output.println("/* number of tags */"+param_tag.numTags()+",");
942 output.println("/* number of tags */ 0,");
943 output.println("parametertag_"+i+"_"+task.getSafeSymbol());
944 output.println("};");
948 output.println("struct parameterdescriptor * parameterdescriptors_"+task.getSafeSymbol()+"[] = {");
949 for (int i=0; i<task.numParameters(); i++) {
952 output.print("¶meter_"+i+"_"+task.getSafeSymbol());
954 output.println("};");
956 output.println("struct taskdescriptor task_"+task.getSafeSymbol()+"={");
957 output.println("&"+task.getSafeSymbol()+",");
958 output.println("/* number of parameters */" +task.numParameters() + ",");
959 int numtotal=task.numParameters()+fm.numTags();
960 output.println("/* number total parameters */" +numtotal + ",");
961 output.println("parameterdescriptors_"+task.getSafeSymbol()+",");
962 output.println("\""+task.getSymbol()+"\"");
963 output.println("};");
967 /** The buildVirtualTables method outputs the virtual dispatch
968 * tables for methods. */
970 protected void buildVirtualTables(PrintWriter outvirtual) {
971 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
972 while(classit.hasNext()) {
973 ClassDescriptor cd=(ClassDescriptor)classit.next();
974 if (virtualcalls.getMethodCount(cd)>maxcount)
975 maxcount=virtualcalls.getMethodCount(cd);
977 MethodDescriptor[][] virtualtable=null;
978 LocalityBinding[][] lbvirtualtable=null;
979 if (state.DSM||state.SINGLETM)
980 lbvirtualtable=new LocalityBinding[state.numClasses()+state.numArrays()][maxcount];
982 virtualtable=new MethodDescriptor[state.numClasses()+state.numArrays()][maxcount];
984 /* Fill in virtual table */
985 classit=state.getClassSymbolTable().getDescriptorsIterator();
986 while(classit.hasNext()) {
987 ClassDescriptor cd=(ClassDescriptor)classit.next();
988 if (state.DSM||state.SINGLETM)
989 fillinRow(cd, lbvirtualtable, cd.getId());
991 fillinRow(cd, virtualtable, cd.getId());
994 ClassDescriptor objectcd=typeutil.getClass(TypeUtil.ObjectClass);
995 Iterator arrayit=state.getArrayIterator();
996 while(arrayit.hasNext()) {
997 TypeDescriptor td=(TypeDescriptor)arrayit.next();
998 int id=state.getArrayNumber(td);
999 if (state.DSM||state.SINGLETM)
1000 fillinRow(objectcd, lbvirtualtable, id+state.numClasses());
1002 fillinRow(objectcd, virtualtable, id+state.numClasses());
1005 outvirtual.print("void * virtualtable[]={");
1006 boolean needcomma=false;
1007 for(int i=0; i<state.numClasses()+state.numArrays(); i++) {
1008 for(int j=0; j<maxcount; j++) {
1010 outvirtual.print(", ");
1011 if ((state.DSM||state.SINGLETM)&&lbvirtualtable[i][j]!=null) {
1012 LocalityBinding lb=lbvirtualtable[i][j];
1013 MethodDescriptor md=lb.getMethod();
1014 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
1015 } else if (!(state.DSM||state.SINGLETM)&&virtualtable[i][j]!=null) {
1016 MethodDescriptor md=virtualtable[i][j];
1017 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
1019 outvirtual.print("0");
1023 outvirtual.println("");
1025 outvirtual.println("};");
1029 private void fillinRow(ClassDescriptor cd, MethodDescriptor[][] virtualtable, int rownum) {
1030 /* Get inherited methods */
1031 if (cd.getSuperDesc()!=null)
1032 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
1033 /* Override them with our methods */
1034 for(Iterator it=cd.getMethods(); it.hasNext();) {
1035 MethodDescriptor md=(MethodDescriptor)it.next();
1036 if (md.isStatic()||md.getReturnType()==null)
1038 int methodnum=virtualcalls.getMethodNumber(md);
1039 virtualtable[rownum][methodnum]=md;
1043 private void fillinRow(ClassDescriptor cd, LocalityBinding[][] virtualtable, int rownum) {
1044 /* Get inherited methods */
1045 if (cd.getSuperDesc()!=null)
1046 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
1047 /* Override them with our methods */
1048 if (locality.getClassBindings(cd)!=null)
1049 for(Iterator<LocalityBinding> lbit=locality.getClassBindings(cd).iterator(); lbit.hasNext();) {
1050 LocalityBinding lb=lbit.next();
1051 MethodDescriptor md=lb.getMethod();
1052 //Is the method static or a constructor
1053 if (md.isStatic()||md.getReturnType()==null)
1055 int methodnum=virtualcalls.getLocalityNumber(lb);
1056 virtualtable[rownum][methodnum]=lb;
1060 /** Generate array that contains the sizes of class objects. The
1061 * object allocation functions in the runtime use this
1064 private void generateSizeArray(PrintWriter outclassdefs) {
1065 outclassdefs.print("extern struct prefetchCountStats * evalPrefetch;\n");
1066 outclassdefs.print("#ifdef TRANSSTATS \n");
1067 outclassdefs.print("extern int numTransAbort;\n");
1068 outclassdefs.print("extern int numTransCommit;\n");
1069 outclassdefs.print("extern int nSoftAbort;\n");
1071 outclassdefs.print("extern int nchashSearch;\n");
1072 outclassdefs.print("extern int nmhashSearch;\n");
1073 outclassdefs.print("extern int nprehashSearch;\n");
1074 outclassdefs.print("extern int ndirtyCacheObj;\n");
1075 outclassdefs.print("extern int nRemoteSend;\n");
1076 outclassdefs.print("extern int sendRemoteReq;\n");
1077 outclassdefs.print("extern int getResponse;\n");
1078 outclassdefs.print("extern int bytesSent;\n");
1079 outclassdefs.print("extern int bytesRecv;\n");
1080 outclassdefs.print("extern int totalObjSize;\n");
1081 outclassdefs.print("extern void handle();\n");
1082 } else if (state.SINGLETM) {
1083 outclassdefs.println("extern int nSoftAbortAbort;");
1084 outclassdefs.println("extern int nSoftAbortCommit;");
1085 outclassdefs.println("#ifdef STMSTATS\n");
1086 outclassdefs.println("extern objtypestat_t typesCausingAbort[];");
1087 outclassdefs.println("#endif\n");
1089 outclassdefs.print("#endif\n");
1091 outclassdefs.print("int numprefetchsites = " + pa.prefetchsiteid + ";\n");
1092 if(this.state.MLP || state.OOOJAVA ){
1093 outclassdefs.print("extern __thread int oid;\n");
1094 outclassdefs.print("extern int numWorkers;\n");
1097 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1098 cdarray=new ClassDescriptor[state.numClasses()];
1100 while(it.hasNext()) {
1101 ClassDescriptor cd=(ClassDescriptor)it.next();
1102 cdarray[cd.getId()]=cd;
1105 arraytable=new TypeDescriptor[state.numArrays()];
1107 Iterator arrayit=state.getArrayIterator();
1108 while(arrayit.hasNext()) {
1109 TypeDescriptor td=(TypeDescriptor)arrayit.next();
1110 int id=state.getArrayNumber(td);
1116 /* Print out types */
1117 outclassdefs.println("/* ");
1118 for(int i=0; i<state.numClasses(); i++) {
1119 ClassDescriptor cd=cdarray[i];
1121 outclassdefs.println("NULL " + i);
1123 outclassdefs.println(cd +" "+i);
1127 for(int i=0; i<state.numArrays(); i++) {
1128 TypeDescriptor arraytd=arraytable[i];
1129 outclassdefs.println(arraytd.toPrettyString() +" "+(i+state.numClasses()));
1132 outclassdefs.println("*/");
1135 outclassdefs.print("int classsize[]={");
1137 boolean needcomma=false;
1138 for(int i=0; i<state.numClasses(); i++) {
1140 outclassdefs.print(", ");
1142 outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")");
1144 outclassdefs.print("0");
1150 for(int i=0; i<state.numArrays(); i++) {
1152 outclassdefs.print(", ");
1153 TypeDescriptor tdelement=arraytable[i].dereference();
1154 if (tdelement.isArray()||tdelement.isClass())
1155 outclassdefs.print("sizeof(void *)");
1157 outclassdefs.print("sizeof("+tdelement.getSafeSymbol()+")");
1161 outclassdefs.println("};");
1163 ClassDescriptor objectclass=typeutil.getClass(TypeUtil.ObjectClass);
1165 outclassdefs.print("int typearray[]={");
1166 for(int i=0; i<state.numClasses(); i++) {
1167 ClassDescriptor cd=cdarray[i];
1168 ClassDescriptor supercd=i>0?cd.getSuperDesc():null;
1170 outclassdefs.print(", ");
1172 outclassdefs.print("-1");
1174 outclassdefs.print(supercd.getId());
1178 for(int i=0; i<state.numArrays(); i++) {
1179 TypeDescriptor arraytd=arraytable[i];
1180 ClassDescriptor arraycd=arraytd.getClassDesc();
1181 if (arraycd==null) {
1183 outclassdefs.print(", ");
1184 outclassdefs.print(objectclass.getId());
1188 ClassDescriptor cd=arraycd.getSuperDesc();
1191 TypeDescriptor supertd=new TypeDescriptor(cd);
1192 supertd.setArrayCount(arraytd.getArrayCount());
1193 type=state.getArrayNumber(supertd);
1195 type+=state.numClasses();
1198 cd=cd.getSuperDesc();
1201 outclassdefs.print(", ");
1202 outclassdefs.print(type);
1206 outclassdefs.println("};");
1211 outclassdefs.print("int typearray2[]={");
1212 for(int i=0; i<state.numArrays(); i++) {
1213 TypeDescriptor arraytd=arraytable[i];
1214 ClassDescriptor arraycd=arraytd.getClassDesc();
1215 if (arraycd==null) {
1217 outclassdefs.print(", ");
1218 outclassdefs.print("-1");
1222 ClassDescriptor cd=arraycd.getSuperDesc();
1223 int level=arraytd.getArrayCount()-1;
1225 for(; level>0; level--) {
1226 TypeDescriptor supertd=new TypeDescriptor(objectclass);
1227 supertd.setArrayCount(level);
1228 type=state.getArrayNumber(supertd);
1230 type+=state.numClasses();
1235 outclassdefs.print(", ");
1236 outclassdefs.print(type);
1240 outclassdefs.println("};");
1243 /** Constructs params and temp objects for each method or task.
1244 * These objects tell the compiler which temps need to be
1247 protected void generateTempStructs(FlatMethod fm, LocalityBinding lb) {
1248 MethodDescriptor md=fm.getMethod();
1249 TaskDescriptor task=fm.getTask();
1250 Set<TempDescriptor> saveset=lb!=null ? locality.getTempSet(lb) : null;
1251 ParamsObject objectparams=md!=null ? new ParamsObject(md,tag++) : new ParamsObject(task, tag++);
1253 paramstable.put(lb, objectparams);
1254 backuptable.put(lb, new Hashtable<TempDescriptor, TempDescriptor>());
1255 } else if (md!=null)
1256 paramstable.put(md, objectparams);
1258 paramstable.put(task, objectparams);
1260 for(int i=0; i<fm.numParameters(); i++) {
1261 TempDescriptor temp=fm.getParameter(i);
1262 TypeDescriptor type=temp.getType();
1263 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1264 objectparams.addPtr(temp);
1266 objectparams.addPrim(temp);
1267 if(lb!=null&&saveset.contains(temp)) {
1268 backuptable.get(lb).put(temp, temp.createNew());
1272 for(int i=0; i<fm.numTags(); i++) {
1273 TempDescriptor temp=fm.getTag(i);
1274 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1275 objectparams.addPtr(temp);
1277 objectparams.addPrim(temp);
1280 TempObject objecttemps=md!=null ? new TempObject(objectparams,md,tag++) : new TempObject(objectparams, task, tag++);
1282 tempstable.put(lb, objecttemps);
1284 tempstable.put(md, objecttemps);
1286 tempstable.put(task, objecttemps);
1288 for(Iterator nodeit=fm.getNodeSet().iterator(); nodeit.hasNext();) {
1289 FlatNode fn=(FlatNode)nodeit.next();
1290 TempDescriptor[] writes=fn.writesTemps();
1291 for(int i=0; i<writes.length; i++) {
1292 TempDescriptor temp=writes[i];
1293 TypeDescriptor type=temp.getType();
1294 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1295 objecttemps.addPtr(temp);
1297 objecttemps.addPrim(temp);
1298 if(lb!=null&&saveset.contains(temp)&&
1299 !backuptable.get(lb).containsKey(temp))
1300 backuptable.get(lb).put(temp, temp.createNew());
1304 /* Create backup temps */
1306 for(Iterator<TempDescriptor> tmpit=backuptable.get(lb).values().iterator(); tmpit.hasNext();) {
1307 TempDescriptor tmp=tmpit.next();
1308 TypeDescriptor type=tmp.getType();
1309 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1310 objecttemps.addPtr(tmp);
1312 objecttemps.addPrim(tmp);
1314 /* Create temp to hold revert table */
1315 if (state.DSM&&(lb.getHasAtomic()||lb.isAtomic())) {
1316 TempDescriptor reverttmp=new TempDescriptor("revertlist", typeutil.getClass(TypeUtil.ObjectClass));
1317 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1318 objecttemps.addPtr(reverttmp);
1320 objecttemps.addPrim(reverttmp);
1321 reverttable.put(lb, reverttmp);
1326 /** This method outputs the following information about classes
1328 * (1) For classes, what are the locations of pointers.
1329 * (2) For arrays, does the array contain pointers or primitives.
1330 * (3) For classes, does the class contain flags.
1333 private void generateLayoutStructs(PrintWriter output) {
1334 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1335 while(it.hasNext()) {
1336 ClassDescriptor cn=(ClassDescriptor)it.next();
1337 output.println("unsigned INTPTR "+cn.getSafeSymbol()+"_pointers[]={");
1338 Iterator allit=cn.getFieldTable().getAllDescriptorsIterator();
1340 while(allit.hasNext()) {
1341 FieldDescriptor fd=(FieldDescriptor)allit.next();
1342 TypeDescriptor type=fd.getType();
1343 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1348 output.print(count);
1349 allit=cn.getFieldTable().getAllDescriptorsIterator();
1350 while(allit.hasNext()) {
1351 FieldDescriptor fd=(FieldDescriptor)allit.next();
1352 TypeDescriptor type=fd.getType();
1353 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1356 output.println(",");
1357 output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+fd.getSafeSymbol()+"))");
1360 output.println("};");
1362 output.println("unsigned INTPTR * pointerarray[]={");
1363 boolean needcomma=false;
1364 for(int i=0; i<state.numClasses(); i++) {
1365 ClassDescriptor cn=cdarray[i];
1367 output.println(",");
1370 output.print(cn.getSafeSymbol()+"_pointers");
1372 output.print("NULL");
1376 for(int i=0; i<state.numArrays(); i++) {
1378 output.println(", ");
1379 TypeDescriptor tdelement=arraytable[i].dereference();
1380 if (tdelement.isArray()||tdelement.isClass())
1381 output.print("((unsigned INTPTR *)1)");
1387 output.println("};");
1389 output.println("int hasflags[]={");
1390 for(int i=0; i<state.numClasses(); i++) {
1391 ClassDescriptor cn=cdarray[i];
1393 output.println(", ");
1395 if ((cn != null) && (cn.hasFlags()))
1400 output.println("};");
1403 /** Print out table to give us supertypes */
1404 private void generateSuperTypeTable(PrintWriter output) {
1405 output.println("int supertypes[]={");
1406 boolean needcomma=false;
1407 for(int i=0; i<state.numClasses(); i++) {
1408 ClassDescriptor cn=cdarray[i];
1410 output.println(",");
1412 if ((cn != null) && (cn.getSuperDesc()!=null)) {
1413 ClassDescriptor cdsuper=cn.getSuperDesc();
1414 output.print(cdsuper.getId());
1418 output.println("};");
1421 /** Force consistent field ordering between inherited classes. */
1423 private void printClassStruct(ClassDescriptor cn, PrintWriter classdefout) {
1425 ClassDescriptor sp=cn.getSuperDesc();
1427 printClassStruct(sp, classdefout);
1429 if (!fieldorder.containsKey(cn)) {
1430 Vector fields=new Vector();
1431 fieldorder.put(cn,fields);
1432 Vector fieldvec=cn.getFieldVec();
1433 for(int i=0;i<fieldvec.size();i++) {
1434 FieldDescriptor fd=(FieldDescriptor)fieldvec.get(i);
1435 if ((sp==null||!sp.getFieldTable().contains(fd.getSymbol())))
1439 Vector fields=(Vector)fieldorder.get(cn);
1441 for(int i=0; i<fields.size(); i++) {
1442 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
1443 if (fd.getType().isClass()||fd.getType().isArray())
1444 classdefout.println(" struct "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1446 classdefout.println(" "+fd.getType().getSafeSymbol()+" "+fd.getSafeSymbol()+";");
1451 /* Map flags to integers consistently between inherited
1454 protected void mapFlags(ClassDescriptor cn) {
1455 ClassDescriptor sp=cn.getSuperDesc();
1459 if (!flagorder.containsKey(cn)) {
1460 Hashtable flags=new Hashtable();
1461 flagorder.put(cn,flags);
1463 Hashtable superflags=(Hashtable)flagorder.get(sp);
1464 Iterator superflagit=superflags.keySet().iterator();
1465 while(superflagit.hasNext()) {
1466 FlagDescriptor fd=(FlagDescriptor)superflagit.next();
1467 Integer number=(Integer)superflags.get(fd);
1468 flags.put(fd, number);
1469 if ((number.intValue()+1)>max)
1470 max=number.intValue()+1;
1474 Iterator flagit=cn.getFlags();
1475 while(flagit.hasNext()) {
1476 FlagDescriptor fd=(FlagDescriptor)flagit.next();
1477 if (sp==null||!sp.getFlagTable().contains(fd.getSymbol()))
1478 flags.put(fd, new Integer(max++));
1484 /** This function outputs (1) structures that parameters are
1485 * passed in (when PRECISE GC is enabled) and (2) function
1486 * prototypes for the methods */
1488 protected void generateCallStructs(ClassDescriptor cn, PrintWriter classdefout, PrintWriter output, PrintWriter headersout) {
1489 /* Output class structure */
1490 classdefout.println("struct "+cn.getSafeSymbol()+" {");
1491 classdefout.println(" int type;");
1492 if(state.MLP || state.OOOJAVA){
1493 classdefout.println(" int oid;");
1494 classdefout.println(" int allocsite;");
1496 if (state.EVENTMONITOR) {
1497 classdefout.println(" int objuid;");
1500 classdefout.println(" pthread_t tid;");
1501 classdefout.println(" void * lockentry;");
1502 classdefout.println(" int lockcount;");
1506 classdefout.println(" int flag;");
1507 if((!state.MULTICORE) || (cn.getSymbol().equals("TagDescriptor"))) {
1508 classdefout.println(" void * flagptr;");
1509 } else if (state.MULTICORE) {
1510 classdefout.println(" int version;");
1511 classdefout.println(" int * lock;"); // lock entry for this obj
1512 classdefout.println(" int mutex;");
1513 classdefout.println(" int lockcount;");
1514 if(state.MULTICOREGC) {
1515 classdefout.println(" int marked;");
1518 if (state.OPTIONAL) {
1519 classdefout.println(" int numfses;");
1520 classdefout.println(" int * fses;");
1523 printClassStruct(cn, classdefout);
1524 classdefout.println("};\n");
1526 if (state.DSM||state.SINGLETM) {
1527 /* Cycle through LocalityBindings */
1528 HashSet<MethodDescriptor> nativemethods=new HashSet<MethodDescriptor>();
1529 Set<LocalityBinding> lbset=locality.getClassBindings(cn);
1531 for(Iterator<LocalityBinding> lbit=lbset.iterator(); lbit.hasNext();) {
1532 LocalityBinding lb=lbit.next();
1533 MethodDescriptor md=lb.getMethod();
1534 if (md.getModifiers().isNative()) {
1535 //make sure we only print a native method once
1536 if (nativemethods.contains(md)) {
1537 FlatMethod fm=state.getMethodFlat(md);
1538 generateTempStructs(fm, lb);
1541 nativemethods.add(md);
1543 generateMethod(cn, md, lb, headersout, output);
1546 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1547 MethodDescriptor md=(MethodDescriptor)methodit.next();
1548 if (md.getModifiers().isNative()&&!nativemethods.contains(md)) {
1549 //Need to build param structure for library code
1550 FlatMethod fm=state.getMethodFlat(md);
1551 generateTempStructs(fm, null);
1552 generateMethodParam(cn, md, null, output);
1557 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1558 MethodDescriptor md=(MethodDescriptor)methodit.next();
1559 generateMethod(cn, md, null, headersout, output);
1563 private void generateMethodParam(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter output) {
1564 /* Output parameter structure */
1565 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1566 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1567 if ((state.DSM||state.SINGLETM)&&lb!=null)
1568 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1570 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1571 output.println(" int size;");
1572 output.println(" void * next;");
1573 for(int i=0; i<objectparams.numPointers(); i++) {
1574 TempDescriptor temp=objectparams.getPointer(i);
1575 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1577 output.println("};\n");
1581 private void generateMethod(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter headersout, PrintWriter output) {
1582 FlatMethod fm=state.getMethodFlat(md);
1583 generateTempStructs(fm, lb);
1585 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1586 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md);
1588 generateMethodParam(cn, md, lb, output);
1590 /* Output temp structure */
1591 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1592 if (state.DSM||state.SINGLETM)
1593 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1595 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1596 output.println(" int size;");
1597 output.println(" void * next;");
1598 for(int i=0; i<objecttemps.numPointers(); i++) {
1599 TempDescriptor temp=objecttemps.getPointer(i);
1600 if (temp.getType().isNull())
1601 output.println(" void * "+temp.getSafeSymbol()+";");
1603 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1605 output.println("};\n");
1608 /********* Output method declaration ***********/
1609 if (state.DSM||state.SINGLETM) {
1610 headersout.println("#define D"+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1612 headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1614 /* First the return type */
1615 if (md.getReturnType()!=null) {
1616 if (md.getReturnType().isClass()||md.getReturnType().isArray())
1617 headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1619 headersout.print(md.getReturnType().getSafeSymbol()+" ");
1621 //catch the constructor case
1622 headersout.print("void ");
1624 /* Next the method name */
1625 if (state.DSM||state.SINGLETM) {
1626 headersout.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1628 headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1630 boolean printcomma=false;
1631 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1632 if (state.DSM||state.SINGLETM) {
1633 headersout.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1635 headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1639 /* Output parameter list*/
1640 for(int i=0; i<objectparams.numPrimitives(); i++) {
1641 TempDescriptor temp=objectparams.getPrimitive(i);
1643 headersout.print(", ");
1645 if (temp.getType().isClass()||temp.getType().isArray())
1646 headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1648 headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1650 headersout.println(");\n");
1654 /** This function outputs (1) structures that parameters are
1655 * passed in (when PRECISE GC is enabled) and (2) function
1656 * prototypes for the tasks */
1658 private void generateTaskStructs(PrintWriter output, PrintWriter headersout) {
1659 /* Cycle through tasks */
1660 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
1662 while(taskit.hasNext()) {
1663 /* Classify parameters */
1664 TaskDescriptor task=(TaskDescriptor)taskit.next();
1665 FlatMethod fm=state.getMethodFlat(task);
1666 generateTempStructs(fm, null);
1668 ParamsObject objectparams=(ParamsObject) paramstable.get(task);
1669 TempObject objecttemps=(TempObject) tempstable.get(task);
1671 /* Output parameter structure */
1672 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1673 output.println("struct "+task.getSafeSymbol()+"_params {");
1674 output.println(" int size;");
1675 output.println(" void * next;");
1676 for(int i=0; i<objectparams.numPointers(); i++) {
1677 TempDescriptor temp=objectparams.getPointer(i);
1678 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1681 output.println("};\n");
1682 if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
1683 maxtaskparams=objectparams.numPointers()+fm.numTags();
1687 /* Output temp structure */
1688 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1689 output.println("struct "+task.getSafeSymbol()+"_locals {");
1690 output.println(" int size;");
1691 output.println(" void * next;");
1692 for(int i=0; i<objecttemps.numPointers(); i++) {
1693 TempDescriptor temp=objecttemps.getPointer(i);
1694 if (temp.getType().isNull())
1695 output.println(" void * "+temp.getSafeSymbol()+";");
1696 else if(temp.getType().isTag())
1697 output.println(" struct "+
1698 (new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1700 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1702 output.println("};\n");
1705 /* Output task declaration */
1706 headersout.print("void " + task.getSafeSymbol()+"(");
1708 boolean printcomma=false;
1709 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1710 headersout.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
1712 headersout.print("void * parameterarray[]");
1713 headersout.println(");\n");
1717 /***** Generate code for FlatMethod fm. *****/
1719 Hashtable<FlatAtomicEnterNode, AtomicRecord> atomicmethodmap;
1720 static int atomicmethodcount=0;
1723 BranchAnalysis branchanalysis;
1724 private void generateFlatMethod(FlatMethod fm, LocalityBinding lb, PrintWriter output) {
1725 if (State.PRINTFLAT)
1726 System.out.println(fm.printMethod());
1727 MethodDescriptor md=fm.getMethod();
1728 TaskDescriptor task=fm.getTask();
1729 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
1730 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : md!=null ? md : task);
1732 HashSet<AtomicRecord> arset=null;
1733 branchanalysis=null;
1735 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1737 if (atomicmethodmap==null)
1738 atomicmethodmap=new Hashtable<FlatAtomicEnterNode, AtomicRecord>();
1740 //fix these so we get right strings for local variables
1741 localsprefixaddr=localsprefix;
1742 localsprefixderef=localsprefix+"->";
1743 arset=new HashSet<AtomicRecord>();
1745 //build branchanalysis
1746 branchanalysis=new BranchAnalysis(locality, lb, delaycomp.getNotReady(lb), delaycomp.livecode(lb), state);
1748 //Generate commit methods here
1749 for(Iterator<FlatNode> fnit=fm.getNodeSet().iterator();fnit.hasNext();) {
1750 FlatNode fn=fnit.next();
1751 if (fn.kind()==FKind.FlatAtomicEnterNode&&
1752 locality.getAtomic(lb).get(fn.getPrev(0)).intValue()==0&&
1753 delaycomp.needsFission(lb, (FlatAtomicEnterNode) fn)) {
1754 //We have an atomic enter
1755 FlatAtomicEnterNode faen=(FlatAtomicEnterNode) fn;
1756 Set<FlatNode> exitset=faen.getExits();
1758 String methodname=md.getSymbol()+(atomicmethodcount++);
1759 AtomicRecord ar=new AtomicRecord();
1763 atomicmethodmap.put(faen, ar);
1765 //build data structure declaration
1766 output.println("struct atomicprimitives_"+methodname+" {");
1768 Set<FlatNode> recordset=delaycomp.livecode(lb);
1769 Set<TempDescriptor> liveinto=delaycomp.liveinto(lb, faen, recordset);
1770 Set<TempDescriptor> liveout=delaycomp.liveout(lb, faen);
1771 Set<TempDescriptor> liveoutvirtualread=delaycomp.liveoutvirtualread(lb, faen);
1773 ar.reallivein=new HashSet(liveinto);
1775 ar.liveoutvirtualread=liveoutvirtualread;
1778 for(Iterator<TempDescriptor> it=liveinto.iterator(); it.hasNext();) {
1779 TempDescriptor tmp=it.next();
1780 //remove the pointers
1781 if (tmp.getType().isPtr()) {
1784 //let's print it here
1785 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1788 for(Iterator<TempDescriptor> it=liveout.iterator(); it.hasNext();) {
1789 TempDescriptor tmp=it.next();
1790 //remove the pointers
1791 if (tmp.getType().isPtr()) {
1793 } else if (!liveinto.contains(tmp)) {
1794 //let's print it here
1795 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1798 output.println("};");
1800 //print out method name
1801 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) {");
1802 //build code for commit method
1804 //first define local primitives
1805 Set<TempDescriptor> alltemps=delaycomp.alltemps(lb, faen, recordset);
1806 for(Iterator<TempDescriptor> tmpit=alltemps.iterator();tmpit.hasNext();) {
1807 TempDescriptor tmp=tmpit.next();
1808 if (!tmp.getType().isPtr()) {
1809 if (liveinto.contains(tmp)||liveoutvirtualread.contains(tmp)) {
1810 //read from live into set
1811 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+"=primitives->"+tmp.getSafeSymbol()+";");
1814 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1818 //turn off write barrier generation
1820 state.SINGLETM=false;
1821 generateCode(faen, fm, lb, exitset, output, false);
1822 state.SINGLETM=true;
1823 //turn on write barrier generation
1825 output.println("}\n\n");
1829 //redefine these back to normal
1831 localsprefixaddr="&"+localsprefix;
1832 localsprefixderef=localsprefix+".";
1834 generateHeader(fm, lb, md!=null ? md : task,output);
1835 TempObject objecttemp=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
1837 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1838 for(Iterator<AtomicRecord> arit=arset.iterator();arit.hasNext();) {
1839 AtomicRecord ar=arit.next();
1840 output.println("struct atomicprimitives_"+ar.name+" primitives_"+ar.name+";");
1844 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1845 if (md!=null&&(state.DSM||state.SINGLETM))
1846 output.print(" struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1847 else if (md!=null&&!(state.DSM||state.SINGLETM))
1848 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1850 output.print(" struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={");
1851 output.print(objecttemp.numPointers()+",");
1852 output.print(paramsprefix);
1853 for(int j=0; j<objecttemp.numPointers(); j++)
1854 output.print(", NULL");
1855 output.println("};");
1858 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1859 TempDescriptor td=objecttemp.getPrimitive(i);
1860 TypeDescriptor type=td.getType();
1862 output.println(" void * "+td.getSafeSymbol()+";");
1863 else if (type.isClass()||type.isArray())
1864 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1866 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1870 if( state.MLP || state.OOOJAVA ) {
1871 if( fm.getNext(0) instanceof FlatSESEEnterNode ) {
1872 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
1873 if( (state.MLP && callerSESEplaceholder != mlpa.getMainSESE()) ||
1874 (state.OOOJAVA && callerSESEplaceholder != oooa.getMainSESE())
1876 // declare variables for naming static SESE's
1877 output.println(" /* static SESE names */");
1878 Iterator<SESEandAgePair> pItr = callerSESEplaceholder.getNeededStaticNames().iterator();
1879 while( pItr.hasNext() ) {
1880 SESEandAgePair pair = pItr.next();
1881 output.println(" void* "+pair+";");
1884 // declare variables for tracking dynamic sources
1885 output.println(" /* dynamic variable sources */");
1886 Iterator<TempDescriptor> dynSrcItr = callerSESEplaceholder.getDynamicVarSet().iterator();
1887 while( dynSrcItr.hasNext() ) {
1888 TempDescriptor dynSrcVar = dynSrcItr.next();
1889 output.println(" SESEcommon* "+dynSrcVar+"_srcSESE = NULL;");
1890 output.println(" INTPTR "+dynSrcVar+"_srcOffset;");
1895 // set up related allocation sites's waiting queues
1898 ConflictGraph graph = null;
1899 graph = mlpa.getConflictGraphResults().get(fm);
1900 if (graph != null && graph.hasConflictEdge()) {
1901 output.println(" /* set up waiting queues */");
1902 output.println(" int numMemoryQueue=0;");
1903 output.println(" int memoryQueueItemID=0;");
1904 HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
1906 System.out.println("#lockSet="+lockSet.hashCode());
1907 System.out.println("lockset="+lockSet);
1908 for (Iterator iterator = lockSet.iterator(); iterator.hasNext();) {
1909 SESELock seseLock = (SESELock) iterator.next();
1910 System.out.println("id="+seseLock.getID());
1911 System.out.println("#="+seseLock);
1913 System.out.println("size="+lockSet.size());
1914 if (lockSet.size() > 0) {
1915 output.println(" numMemoryQueue=" + lockSet.size() + ";");
1916 output.println(" runningSESE->numMemoryQueue=numMemoryQueue;");
1917 output.println(" runningSESE->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
1922 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
1923 if(callerSESEplaceholder!= oooa.getMainSESE()){
1924 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(callerSESEplaceholder);
1925 if (graph != null && graph.hasConflictEdge()) {
1926 output.println(" // set up waiting queues ");
1927 output.println(" int numMemoryQueue=0;");
1928 output.println(" int memoryQueueItemID=0;");
1929 Set<Analysis.OoOJava.SESELock> lockSet = oooa.getLockMappings(graph);
1930 System.out.println("#lockSet="+lockSet.hashCode());
1931 System.out.println("lockset="+lockSet);
1932 for (Iterator iterator = lockSet.iterator(); iterator.hasNext();) {
1933 Analysis.OoOJava.SESELock seseLock = (Analysis.OoOJava.SESELock) iterator.next();
1934 System.out.println("id="+seseLock.getID());
1935 System.out.println("#="+seseLock);
1937 System.out.println("size="+lockSet.size());
1938 if (lockSet.size() > 0) {
1939 output.println(" numMemoryQueue=" + lockSet.size() + ";");
1940 output.println(" runningSESE->numMemoryQueue=numMemoryQueue;");
1941 output.println(" runningSESE->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
1951 /* Check to see if we need to do a GC if this is a
1952 * multi-threaded program...*/
1954 if (((state.MLP||state.OOOJAVA||state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
1955 || this.state.MULTICOREGC) {
1956 //Don't bother if we aren't in recursive methods...The loops case will catch it
1957 if (callgraph.getAllMethods(md).contains(md)) {
1958 if (state.DSM&&lb.isAtomic())
1959 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
1960 else if (this.state.MULTICOREGC) {
1961 output.println("if(gcflag) gc("+localsprefixaddr+");");
1963 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
1968 generateCode(fm.getNext(0), fm, lb, null, output, true);
1970 output.println("}\n\n");
1974 protected void initializeSESE( FlatSESEEnterNode fsen ) {
1976 FlatMethod fm = fsen.getfmEnclosing();
1977 MethodDescriptor md = fm.getMethod();
1978 ClassDescriptor cn = md.getClassDesc();
1981 // Creates bogus method descriptor to index into tables
1982 Modifiers modBogus = new Modifiers();
1983 MethodDescriptor mdBogus =
1984 new MethodDescriptor( modBogus,
1985 new TypeDescriptor( TypeDescriptor.VOID ),
1986 "sese_"+fsen.getPrettyIdentifier()+fsen.getIdentifier()
1989 mdBogus.setClassDesc( fsen.getcdEnclosing() );
1990 FlatMethod fmBogus = new FlatMethod( mdBogus, null );
1991 fsen.setfmBogus( fmBogus );
1992 fsen.setmdBogus( mdBogus );
1994 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1995 inSetAndOutSet.addAll( fsen.getInVarSet() );
1996 inSetAndOutSet.addAll( fsen.getOutVarSet() );
1998 // Build paramsobj for bogus method descriptor
1999 ParamsObject objectparams = new ParamsObject( mdBogus, tag++ );
2000 paramstable.put( mdBogus, objectparams );
2002 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
2003 while( itr.hasNext() ) {
2004 TempDescriptor temp = itr.next();
2005 TypeDescriptor type = temp.getType();
2006 if( type.isPtr() ) {
2007 objectparams.addPtr( temp );
2009 objectparams.addPrim( temp );
2013 // Build normal temp object for bogus method descriptor
2014 TempObject objecttemps = new TempObject( objectparams, mdBogus, tag++ );
2015 tempstable.put( mdBogus, objecttemps );
2017 for( Iterator nodeit = fsen.getNodeSet().iterator(); nodeit.hasNext(); ) {
2018 FlatNode fn = (FlatNode)nodeit.next();
2019 TempDescriptor[] writes = fn.writesTemps();
2021 for( int i = 0; i < writes.length; i++ ) {
2022 TempDescriptor temp = writes[i];
2023 TypeDescriptor type = temp.getType();
2025 if( type.isPtr() ) {
2026 objecttemps.addPtr( temp );
2028 objecttemps.addPrim( temp );
2034 // used when generating the specific SESE record struct
2035 // to remember the FIRST field name of sese records
2036 // that the current SESE depends on--we need to know the
2037 // offset to the first one for garbage collection
2038 protected void addingDepRecField( FlatSESEEnterNode fsen,
2040 if( fsen.getFirstDepRecField() == null ) {
2041 fsen.setFirstDepRecField( field );
2043 fsen.incNumDepRecs();
2046 protected void generateMethodSESE(FlatSESEEnterNode fsen,
2048 PrintWriter outputStructs,
2049 PrintWriter outputMethHead,
2050 PrintWriter outputMethods
2053 ParamsObject objectparams = (ParamsObject) paramstable.get( fsen.getmdBogus() );
2054 TempObject objecttemps = (TempObject) tempstable .get( fsen.getmdBogus() );
2056 // generate locals structure
2057 outputStructs.println("struct "+
2058 fsen.getcdEnclosing().getSafeSymbol()+
2059 fsen.getmdBogus().getSafeSymbol()+"_"+
2060 fsen.getmdBogus().getSafeMethodDescriptor()+
2062 outputStructs.println(" int size;");
2063 outputStructs.println(" void * next;");
2064 for(int i=0; i<objecttemps.numPointers(); i++) {
2065 TempDescriptor temp=objecttemps.getPointer(i);
2067 if (temp.getType().isNull())
2068 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
2070 outputStructs.println(" struct "+
2071 temp.getType().getSafeSymbol()+" * "+
2072 temp.getSafeSymbol()+";");
2074 outputStructs.println("};\n");
2077 // divide in-set and out-set into objects and primitives to prep
2078 // for the record generation just below
2079 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
2080 inSetAndOutSet.addAll( fsen.getInVarSet() );
2081 inSetAndOutSet.addAll( fsen.getOutVarSet() );
2083 Set<TempDescriptor> inSetAndOutSetObjs = new HashSet<TempDescriptor>();
2084 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
2086 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
2087 while( itr.hasNext() ) {
2088 TempDescriptor temp = itr.next();
2089 TypeDescriptor type = temp.getType();
2090 if( type.isPtr() ) {
2091 inSetAndOutSetObjs.add( temp );
2093 inSetAndOutSetPrims.add( temp );
2098 // generate the SESE record structure
2099 outputStructs.println(fsen.getSESErecordName()+" {");
2101 // data common to any SESE, and it must be placed first so
2102 // a module that doesn't know what kind of SESE record this
2103 // is can cast the pointer to a common struct
2104 outputStructs.println(" SESEcommon common;");
2106 // then garbage list stuff
2107 outputStructs.println(" /* next is in-set and out-set objects that look like a garbage list */");
2108 outputStructs.println(" int size;");
2109 outputStructs.println(" void * next;");
2111 // I think that the set of TempDescriptors inSetAndOutSetObjs
2112 // calculated above should match the pointer object params
2113 // used in the following code, but let's just leave the working
2114 // implementation unless there is actually a problem...
2115 for(int i=0; i<objectparams.numPointers(); i++) {
2116 TempDescriptor temp=objectparams.getPointer(i);
2117 if (temp.getType().isNull())
2118 outputStructs.println(" void * "+temp.getSafeSymbol()+
2119 "; /* in-or-out-set obj in gl */");
2121 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+
2122 temp.getSafeSymbol()+"; /* in-or-out-set obj in gl */");
2125 outputStructs.println(" /* next is primitives for in-set and out-set and dynamic tracking */");
2127 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
2128 while( itrPrims.hasNext() ) {
2129 TempDescriptor temp = itrPrims.next();
2130 TypeDescriptor type = temp.getType();
2131 if(type.isPrimitive()){
2132 outputStructs.println(" "+temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol()+"; /* in-set or out-set primitive */");
2136 // note that the sese record pointer will be added below, just primitive part of tracking here
2137 Iterator<TempDescriptor> itrDynInVars = fsen.getDynamicInVarSet().iterator();
2138 while( itrDynInVars.hasNext() ) {
2139 TempDescriptor dynInVar = itrDynInVars.next();
2140 outputStructs.println(" INTPTR "+dynInVar+"_srcOffset; /* dynamic tracking primitive */");
2144 outputStructs.println(" /* everything after this should be pointers to an SESE record */" );
2146 // other half of info for dynamic tracking, the SESE record pointer
2147 itrDynInVars = fsen.getDynamicInVarSet().iterator();
2148 while( itrDynInVars.hasNext() ) {
2149 TempDescriptor dynInVar = itrDynInVars.next();
2150 String depRecField = dynInVar+"_srcSESE";
2151 outputStructs.println(" SESEcommon* "+depRecField+";");
2152 addingDepRecField( fsen, depRecField );
2155 // statically known sese sources are record pointers, too
2156 Iterator<SESEandAgePair> itrStaticInVarSrcs = fsen.getStaticInVarSrcs().iterator();
2157 while( itrStaticInVarSrcs.hasNext() ) {
2158 SESEandAgePair srcPair = itrStaticInVarSrcs.next();
2159 outputStructs.println(" "+srcPair.getSESE().getSESErecordName()+"* "+srcPair+";");
2160 addingDepRecField( fsen, srcPair.toString() );
2163 if( fsen.getFirstDepRecField() != null ) {
2164 outputStructs.println(" /* compiler believes first dependent SESE record field above is: "+
2165 fsen.getFirstDepRecField()+" */" );
2168 outputStructs.println("};\n");
2171 // write method declaration to header file
2172 outputMethHead.print("void ");
2173 outputMethHead.print(fsen.getSESEmethodName()+"(");
2174 outputMethHead.print(fsen.getSESErecordName()+"* "+paramsprefix);
2175 outputMethHead.println(");\n");
2178 generateFlatMethodSESE( fsen.getfmBogus(),
2179 fsen.getcdEnclosing(),
2185 private void generateFlatMethodSESE(FlatMethod fm,
2187 FlatSESEEnterNode fsen,
2188 FlatSESEExitNode seseExit,
2192 MethodDescriptor md=fm.getMethod();
2194 output.print("void ");
2195 output.print(fsen.getSESEmethodName()+"(");
2196 output.print(fsen.getSESErecordName()+"* "+paramsprefix);
2197 output.println("){\n");
2200 TempObject objecttemp=(TempObject) tempstable.get(md);
2202 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2203 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
2204 output.print(objecttemp.numPointers()+",");
2205 output.print("&(((SESEcommon*)(___params___))[1])");
2206 for(int j=0; j<objecttemp.numPointers(); j++)
2207 output.print(", NULL");
2208 output.println("};");
2211 output.println(" /* regular local primitives */");
2212 for(int i=0; i<objecttemp.numPrimitives(); i++) {
2213 TempDescriptor td=objecttemp.getPrimitive(i);
2214 TypeDescriptor type=td.getType();
2216 output.println(" void * "+td.getSafeSymbol()+";");
2217 else if (type.isClass()||type.isArray())
2218 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
2220 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
2224 // declare variables for naming static SESE's
2225 output.println(" /* static SESE names */");
2226 Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
2227 while( pItr.hasNext() ) {
2228 SESEandAgePair pair = pItr.next();
2229 output.println(" SESEcommon* "+pair+" = NULL;");
2232 // declare variables for tracking dynamic sources
2233 output.println(" /* dynamic variable sources */");
2234 Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
2235 while( dynSrcItr.hasNext() ) {
2236 TempDescriptor dynSrcVar = dynSrcItr.next();
2237 output.println(" SESEcommon* "+dynSrcVar+"_srcSESE = NULL;");
2238 output.println(" INTPTR "+dynSrcVar+"_srcOffset;");
2241 // declare local temps for in-set primitives, and if it is
2242 // a ready-source variable, get the value from the record
2243 output.println(" /* local temps for in-set primitives */");
2244 Iterator<TempDescriptor> itrInSet = fsen.getInVarSet().iterator();
2245 while( itrInSet.hasNext() ) {
2246 TempDescriptor temp = itrInSet.next();
2247 TypeDescriptor type = temp.getType();
2248 if( !type.isPtr() ) {
2249 if( fsen.getReadyInVarSet().contains( temp ) ) {
2250 output.println(" "+type+" "+temp+" = "+paramsprefix+"->"+temp+";");
2252 output.println(" "+type+" "+temp+";");
2257 // declare local temps for out-set primitives if its not already
2258 // in the in-set, and it's value will get written so no problem
2259 output.println(" /* local temp for out-set prim, not already in the in-set */");
2260 Iterator<TempDescriptor> itrOutSet = fsen.getOutVarSet().iterator();
2261 while( itrOutSet.hasNext() ) {
2262 TempDescriptor temp = itrOutSet.next();
2263 TypeDescriptor type = temp.getType();
2264 if( !type.isPtr() && !fsen.getInVarSet().contains( temp ) ) {
2265 output.println(" "+type+" "+temp+";");
2270 // initialize thread-local var to a the task's record, which is fused
2271 // with the param list
2272 output.println(" ");
2273 output.println(" /* code of this task's body should use this to access the running task record */");
2274 output.println(" runningSESE = &(___params___->common);");
2275 output.println(" ");
2277 // setup memory queue
2280 output.println(" // set up memory queues ");
2281 output.println(" int numMemoryQueue=0;");
2282 output.println(" int memoryQueueItemID=0;");
2283 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(fsen);
2284 if (graph != null && graph.hasConflictEdge()) {
2285 output.println(" {");
2286 Set<Analysis.OoOJava.SESELock> lockSet = oooa.getLockMappings(graph);
2287 System.out.println("#lockSet="+lockSet);
2288 if (lockSet.size() > 0) {
2289 output.println(" numMemoryQueue=" + lockSet.size() + ";");
2290 output.println(" runningSESE->numMemoryQueue=numMemoryQueue;");
2291 output.println(" runningSESE->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2294 output.println(" }");
2297 output.println(" // set up memory queues ");
2298 output.println(" int numMemoryQueue=0;");
2299 output.println(" int memoryQueueItemID=0;");
2300 ConflictGraph graph = null;
2301 graph = mlpa.getConflictGraphResults().get(fsen);
2302 if (graph != null && graph.hasConflictEdge()) {
2303 output.println(" {");
2304 HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
2306 System.out.println("#lockSet="+lockSet);
2308 if (lockSet.size() > 0) {
2309 output.println(" numMemoryQueue=" + lockSet.size() + "; ");
2310 output.println(" runningSESE->numMemoryQueue=numMemoryQueue;");
2311 output.println(" runningSESE->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2314 output.println(" }");
2320 // set up a task's mem pool to recycle the allocation of children tasks
2321 // don't bother if the task never has children (a leaf task)
2322 output.println( "#ifndef OOO_DISABLE_TASKMEMPOOL" );
2323 if( !fsen.getIsLeafSESE() ) {
2324 output.println(" runningSESE->taskRecordMemPool = poolcreate( "+
2325 maxTaskRecSizeStr+" );");
2327 // make it clear we purposefully did not initialize this
2328 output.println(" runningSESE->taskRecordMemPool = (MemPool*)0x1;");
2330 output.println( "#endif" );
2333 // copy in-set into place, ready vars were already
2334 // copied when the SESE was issued
2335 Iterator<TempDescriptor> tempItr;
2337 // static vars are from a known SESE
2338 output.println(" // copy variables from static sources");
2339 tempItr = fsen.getStaticInVarSet().iterator();
2340 while( tempItr.hasNext() ) {
2341 TempDescriptor temp = tempItr.next();
2342 VariableSourceToken vst = fsen.getStaticInVarSrc( temp );
2343 SESEandAgePair srcPair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2344 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2345 " = "+paramsprefix+"->"+srcPair+"->"+vst.getAddrVar()+";");
2348 output.println(" // decrement references to static sources");
2349 for( Iterator<SESEandAgePair> pairItr = fsen.getStaticInVarSrcs().iterator();
2352 SESEandAgePair srcPair = pairItr.next();
2353 output.println(" {");
2354 output.println(" SESEcommon* src = &("+paramsprefix+"->"+srcPair+"->common);");
2355 output.println(" RELEASE_REFERENCE_TO( src );");
2356 output.println(" }");
2360 // dynamic vars come from an SESE and src
2361 output.println(" // copy variables from dynamic sources");
2362 tempItr = fsen.getDynamicInVarSet().iterator();
2363 while( tempItr.hasNext() ) {
2364 TempDescriptor temp = tempItr.next();
2365 TypeDescriptor type = temp.getType();
2367 // go grab it from the SESE source
2368 output.println(" if( "+paramsprefix+"->"+temp+"_srcSESE != NULL ) {");
2371 if( type.isNull() ) {
2373 } else if( type.isClass() || type.isArray() ) {
2374 typeStr = "struct "+type.getSafeSymbol()+"*";
2376 typeStr = type.getSafeSymbol();
2379 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2380 " = *(("+typeStr+"*) ("+
2381 paramsprefix+"->"+temp+"_srcSESE + "+
2382 paramsprefix+"->"+temp+"_srcOffset));");
2384 output.println(" SESEcommon* src = "+paramsprefix+"->"+temp+"_srcSESE;");
2385 output.println(" RELEASE_REFERENCE_TO( src );");
2387 // or if the source was our parent, its already in our record to grab
2388 output.println(" } else {");
2389 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2390 " = "+paramsprefix+"->"+temp+";");
2391 output.println(" }");
2394 // Check to see if we need to do a GC if this is a
2395 // multi-threaded program...
2396 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2397 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2398 //Don't bother if we aren't in recursive methods...The loops case will catch it
2399 // if (callgraph.getAllMethods(md).contains(md)) {
2400 // if(this.state.MULTICOREGC) {
2401 // output.println("if(gcflag) gc("+localsprefixaddr+");");
2403 // output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2408 if( state.COREPROF ) {
2409 output.println("#ifdef CP_EVENTID_TASKEXECUTE");
2410 output.println(" CP_LOGEVENT( CP_EVENTID_TASKEXECUTE, CP_EVENTTYPE_BEGIN );");
2411 output.println("#endif");
2414 HashSet<FlatNode> exitset=new HashSet<FlatNode>();
2415 exitset.add(seseExit);
2416 generateCode(fsen.getNext(0), fm, null, exitset, output, true);
2417 output.println("}\n\n");
2422 // when a new mlp thread is created for an issued SESE, it is started
2423 // by running this method which blocks on a cond variable until
2424 // it is allowed to transition to execute. Then a case statement
2425 // allows it to invoke the method with the proper SESE body, and after
2426 // exiting the SESE method, executes proper SESE exit code before the
2427 // thread can be destroyed
2428 private void generateSESEinvocationMethod(PrintWriter outmethodheader,
2429 PrintWriter outmethod
2432 outmethodheader.println("void* invokeSESEmethod( void* seseRecord );");
2433 outmethod.println( "void* invokeSESEmethod( void* seseRecord ) {");
2434 outmethod.println( " int status;");
2435 outmethod.println( " char errmsg[128];");
2437 // generate a case for each SESE class that can be invoked
2438 outmethod.println( " switch( *((int*)seseRecord) ) {");
2439 outmethod.println( " ");
2440 Iterator<FlatSESEEnterNode> seseit;
2442 seseit=mlpa.getAllSESEs().iterator();
2444 seseit=oooa.getAllSESEs().iterator();
2446 while(seseit.hasNext()){
2447 FlatSESEEnterNode fsen = seseit.next();
2449 outmethod.println( " /* "+fsen.getPrettyIdentifier()+" */");
2450 outmethod.println( " case "+fsen.getIdentifier()+":");
2451 outmethod.println( " "+fsen.getSESEmethodName()+"( seseRecord );");
2453 if( (state.MLP && fsen.equals( mlpa.getMainSESE() )) ||
2454 (state.OOOJAVA && fsen.equals( oooa.getMainSESE() ))
2456 outmethod.println( " /* work scheduler works forever, explicitly exit */");
2457 outmethod.println( " CP_EXIT();");
2458 outmethod.println( " CP_DUMP();");
2459 outmethod.println( " workScheduleExit();");
2460 outmethod.println( " exit( 0 );");
2463 outmethod.println( " break;");
2464 outmethod.println( "");
2467 // default case should never be taken, error out
2468 outmethod.println( " default:");
2469 outmethod.println( " printf(\"Error: unknown SESE class ID in invoke method.\\n\");");
2470 outmethod.println( " exit(-30);");
2471 outmethod.println( " break;");
2472 outmethod.println( " }");
2473 outmethod.println( " return NULL;");
2474 outmethod.println( "}\n\n");
2478 protected void generateCode(FlatNode first,
2481 Set<FlatNode> stopset,
2482 PrintWriter output, boolean firstpass) {
2484 /* Assign labels to FlatNode's if necessary.*/
2486 Hashtable<FlatNode, Integer> nodetolabel;
2488 if (state.DELAYCOMP&&!firstpass)
2489 nodetolabel=dcassignLabels(first, stopset);
2491 nodetolabel=assignLabels(first, stopset);
2493 Set<FlatNode> storeset=null;
2494 HashSet<FlatNode> genset=null;
2495 HashSet<FlatNode> refset=null;
2496 Set<FlatNode> unionset=null;
2498 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
2499 storeset=delaycomp.livecode(lb);
2500 genset=new HashSet<FlatNode>();
2501 if (state.STMARRAY&&!state.DUALVIEW) {
2502 refset=new HashSet<FlatNode>();
2503 refset.addAll(delaycomp.getDeref(lb));
2504 refset.removeAll(delaycomp.getCannotDelay(lb));
2505 refset.removeAll(delaycomp.getOther(lb));
2508 genset.addAll(delaycomp.getCannotDelay(lb));
2509 genset.addAll(delaycomp.getOther(lb));
2511 genset.addAll(delaycomp.getNotReady(lb));
2512 if (state.STMARRAY&&!state.DUALVIEW) {
2513 genset.removeAll(refset);
2516 unionset=new HashSet<FlatNode>();
2517 unionset.addAll(storeset);
2518 unionset.addAll(genset);
2519 if (state.STMARRAY&&!state.DUALVIEW)
2520 unionset.addAll(refset);
2523 /* Do the actual code generation */
2524 FlatNode current_node=null;
2525 HashSet tovisit=new HashSet();
2526 HashSet visited=new HashSet();
2528 tovisit.add(first.getNext(0));
2531 while(current_node!=null||!tovisit.isEmpty()) {
2532 if (current_node==null) {
2533 current_node=(FlatNode)tovisit.iterator().next();
2534 tovisit.remove(current_node);
2535 } else if (tovisit.contains(current_node)) {
2536 tovisit.remove(current_node);
2538 visited.add(current_node);
2539 if (nodetolabel.containsKey(current_node)) {
2540 output.println("L"+nodetolabel.get(current_node)+":");
2542 if (state.INSTRUCTIONFAILURE) {
2543 if (state.THREAD||state.DSM||state.SINGLETM) {
2544 output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
2546 output.println("if ((--instructioncount)==0) injectinstructionfailure();");
2548 if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
2550 if (!state.DELAYCOMP||firstpass) {
2551 generateFlatNode(fm, lb, current_node, output);
2553 //store primitive variables in out set
2554 AtomicRecord ar=atomicmethodmap.get((FlatAtomicEnterNode)first);
2555 Set<TempDescriptor> liveout=ar.liveout;
2556 for(Iterator<TempDescriptor> tmpit=liveout.iterator();tmpit.hasNext();) {
2557 TempDescriptor tmp=tmpit.next();
2558 output.println("primitives->"+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2561 if ((state.MLP || state.OOOJAVA) && stopset!=null) {
2562 assert first.getPrev( 0 ) instanceof FlatSESEEnterNode;
2563 assert current_node instanceof FlatSESEExitNode;
2564 FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev( 0 );
2565 FlatSESEExitNode fsxn = (FlatSESEExitNode) current_node;
2566 assert fsen.getFlatExit().equals( fsxn );
2567 assert fsxn.getFlatEnter().equals( fsen );
2569 if (current_node.kind()!=FKind.FlatReturnNode) {
2570 output.println(" return;");
2573 } else if(current_node.numNext()==1) {
2575 if ((state.MLP|| state.OOOJAVA) &&
2576 current_node.kind()==FKind.FlatSESEEnterNode &&
2577 !((FlatSESEEnterNode)current_node).getIsCallerSESEplaceholder()
2579 FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
2580 generateFlatNode(fm, lb, current_node, output);
2581 nextnode=fsen.getFlatExit().getNext(0);
2582 } else if (state.DELAYCOMP) {
2583 boolean specialprimitive=false;
2584 //skip literals...no need to add extra overhead
2585 if (storeset!=null&&storeset.contains(current_node)&¤t_node.kind()==FKind.FlatLiteralNode) {
2586 TypeDescriptor typedesc=((FlatLiteralNode)current_node).getType();
2587 if (!typedesc.isClass()&&!typedesc.isArray()) {
2588 specialprimitive=true;
2592 if (genset==null||genset.contains(current_node)||specialprimitive)
2593 generateFlatNode(fm, lb, current_node, output);
2594 if (state.STMARRAY&&!state.DUALVIEW&&refset!=null&&refset.contains(current_node)) {
2595 //need to acquire lock
2596 handleArrayDeref(fm, lb, current_node, output, firstpass);
2598 if (storeset!=null&&storeset.contains(current_node)&&!specialprimitive) {
2599 TempDescriptor wrtmp=current_node.writesTemps()[0];
2601 //need to store value written by previous node
2602 if (wrtmp.getType().isPtr()) {
2603 //only lock the objects that may actually need locking
2604 if (recorddc.getNeedTrans(lb, current_node)&&
2605 (!state.STMARRAY||state.DUALVIEW||!wrtmp.getType().isArray()||
2606 wrtmp.getType().getSymbol().equals(TypeUtil.ObjectClass))) {
2607 output.println("STOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2609 output.println("STOREPTRNOLOCK("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2612 output.println("STORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");/* "+current_node.nodeid+" */");
2615 //need to read value read by previous node
2616 if (wrtmp.getType().isPtr()) {
2617 output.println("RESTOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2619 output.println("RESTORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+"); /* "+current_node.nodeid+" */");
2623 nextnode=current_node.getNext(0);
2626 generateFlatNode(fm, lb, current_node, output);
2627 nextnode=current_node.getNext(0);
2629 if (visited.contains(nextnode)) {
2630 output.println("goto L"+nodetolabel.get(nextnode)+";");
2633 current_node=nextnode;
2634 } else if (current_node.numNext()==2) {
2636 if (state.DELAYCOMP) {
2637 boolean computeside=false;
2639 //need to record which way it should go
2640 if (genset==null||genset.contains(current_node)) {
2641 if (storeset!=null&&storeset.contains(current_node)) {
2642 //need to store which way branch goes
2643 generateStoreFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2645 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2647 //which side to execute
2651 if (genset.contains(current_node)) {
2652 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2653 } else if (storeset.contains(current_node)) {
2655 branchanalysis.generateGroupCode(current_node, output, nodetolabel);
2657 //which side to execute
2662 Set<FlatNode> leftset=DelayComputation.getNext(current_node, 0, unionset, lb,locality, true);
2664 if (leftset.size()==0)
2666 if (visited.contains(current_node.getNext(branch))) {
2667 //already visited -- build jump
2668 output.println("goto L"+nodetolabel.get(current_node.getNext(branch))+";");
2671 current_node=current_node.getNext(branch);
2674 if (!visited.contains(current_node.getNext(1)))
2675 tovisit.add(current_node.getNext(1));
2676 if (visited.contains(current_node.getNext(0))) {
2677 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2680 current_node=current_node.getNext(0);
2684 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2685 if (!visited.contains(current_node.getNext(1)))
2686 tovisit.add(current_node.getNext(1));
2687 if (visited.contains(current_node.getNext(0))) {
2688 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2691 current_node=current_node.getNext(0);
2693 } else throw new Error();
2697 protected void handleArrayDeref(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output, boolean firstpass) {
2698 if (fn.kind()==FKind.FlatSetElementNode) {
2699 FlatSetElementNode fsen=(FlatSetElementNode) fn;
2700 String dst=generateTemp(fm, fsen.getDst(), lb);
2701 String src=generateTemp(fm, fsen.getSrc(), lb);
2702 String index=generateTemp(fm, fsen.getIndex(), lb);
2703 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
2705 if (elementtype.isArray()||elementtype.isClass())
2708 type=elementtype.getSafeSymbol()+" ";
2710 output.println("STOREARRAY("+dst+","+index+","+type+")");
2712 output.println("{");
2713 output.println(" struct ArrayObject *array;");
2714 output.println(" int index;");
2715 output.println(" RESTOREARRAY(array,index);");
2716 output.println(" (("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index]="+src+";");
2717 output.println("}");
2719 } else if (fn.kind()==FKind.FlatElementNode) {
2720 FlatElementNode fen=(FlatElementNode) fn;
2721 String src=generateTemp(fm, fen.getSrc(), lb);
2722 String index=generateTemp(fm, fen.getIndex(), lb);
2723 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
2724 String dst=generateTemp(fm, fen.getDst(), lb);
2726 if (elementtype.isArray()||elementtype.isClass())
2729 type=elementtype.getSafeSymbol()+" ";
2731 output.println("STOREARRAY("+src+","+index+","+type+")");
2733 output.println("{");
2734 output.println(" struct ArrayObject *array;");
2735 output.println(" int index;");
2736 output.println(" RESTOREARRAY(array,index);");
2737 output.println(" "+dst+"=(("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index];");
2738 output.println("}");
2742 /** Special label assignment for delaycomputation */
2743 protected Hashtable<FlatNode, Integer> dcassignLabels(FlatNode first, Set<FlatNode> lastset) {
2744 HashSet tovisit=new HashSet();
2745 HashSet visited=new HashSet();
2747 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2749 //Label targets of branches
2750 Set<FlatNode> targets=branchanalysis.getTargets();
2751 for(Iterator<FlatNode> it=targets.iterator();it.hasNext();) {
2752 nodetolabel.put(it.next(), new Integer(labelindex++));
2757 /*Assign labels first. A node needs a label if the previous
2758 * node has two exits or this node is a join point. */
2760 while(!tovisit.isEmpty()) {
2761 FlatNode fn=(FlatNode)tovisit.iterator().next();
2766 if(lastset!=null&&lastset.contains(fn)) {
2767 // if last is not null and matches, don't go
2768 // any further for assigning labels
2772 for(int i=0; i<fn.numNext(); i++) {
2773 FlatNode nn=fn.getNext(i);
2776 //1) Edge >1 of node
2777 nodetolabel.put(nn,new Integer(labelindex++));
2779 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2783 nodetolabel.put(nn,new Integer(labelindex++));
2791 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first) {
2792 return assignLabels(first, null);
2795 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
2796 HashSet tovisit=new HashSet();
2797 HashSet visited=new HashSet();
2799 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2802 /*Assign labels first. A node needs a label if the previous
2803 * node has two exits or this node is a join point. */
2805 while(!tovisit.isEmpty()) {
2806 FlatNode fn=(FlatNode)tovisit.iterator().next();
2811 if(lastset!=null&&lastset.contains(fn)) {
2812 // if last is not null and matches, don't go
2813 // any further for assigning labels
2817 for(int i=0; i<fn.numNext(); i++) {
2818 FlatNode nn=fn.getNext(i);
2821 //1) Edge >1 of node
2822 nodetolabel.put(nn,new Integer(labelindex++));
2824 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2828 nodetolabel.put(nn,new Integer(labelindex++));
2836 /** Generate text string that corresponds to the TempDescriptor td. */
2837 protected String generateTemp(FlatMethod fm, TempDescriptor td, LocalityBinding lb) {
2838 MethodDescriptor md=fm.getMethod();
2839 TaskDescriptor task=fm.getTask();
2840 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
2842 if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
2843 return td.getSafeSymbol();
2846 if (objecttemps.isLocalPtr(td)) {
2847 return localsprefixderef+td.getSafeSymbol();
2850 if (objecttemps.isParamPtr(td)) {
2851 return paramsprefix+"->"+td.getSafeSymbol();
2857 protected void generateFlatNode(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output) {
2859 // insert pre-node actions from the code plan
2860 if( state.MLP|| state.OOOJAVA ) {
2864 cp = mlpa.getCodePlan( fn );
2866 cp = oooa.getCodePlan(fn);
2871 FlatSESEEnterNode currentSESE = cp.getCurrentSESE();
2873 // for each sese and age pair that this parent statement
2874 // must stall on, take that child's stall semaphore, the
2875 // copying of values comes after the statement
2876 Iterator<VariableSourceToken> vstItr = cp.getStallTokens().iterator();
2877 while( vstItr.hasNext() ) {
2878 VariableSourceToken vst = vstItr.next();
2880 SESEandAgePair pair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2882 output.println(" {");
2883 output.println(" "+pair.getSESE().getSESErecordName()+"* child = ("+
2884 pair.getSESE().getSESErecordName()+"*) "+pair+";");
2886 output.println(" SESEcommon* common = (SESEcommon*) "+pair+";");
2887 if( state.COREPROF ) {
2888 output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
2889 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_BEGIN );");
2890 output.println("#endif");
2892 output.println(" pthread_mutex_lock( &(common->lock) );");
2893 output.println(" while( common->doneExecuting == FALSE ) {");
2894 output.println(" pthread_cond_wait( &(common->doneCond), &(common->lock) );");
2895 output.println(" }");
2896 output.println(" pthread_mutex_unlock( &(common->lock) );");
2898 // copy things we might have stalled for
2899 Iterator<TempDescriptor> tdItr = cp.getCopySet( vst ).iterator();
2900 while( tdItr.hasNext() ) {
2901 TempDescriptor td = tdItr.next();
2902 FlatMethod fmContext;
2903 if( currentSESE.getIsCallerSESEplaceholder() ) {
2904 fmContext = currentSESE.getfmEnclosing();
2906 fmContext = currentSESE.getfmBogus();
2908 output.println(" "+generateTemp( fmContext, td, null )+
2909 " = child->"+vst.getAddrVar().getSafeSymbol()+";");
2911 if( state.COREPROF ) {
2912 output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
2913 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_END );");
2914 output.println("#endif");
2916 output.println(" }");
2919 // for each variable with a dynamic source, stall just for that variable
2920 Iterator<TempDescriptor> dynItr = cp.getDynamicStallSet().iterator();
2921 while( dynItr.hasNext() ) {
2922 TempDescriptor dynVar = dynItr.next();
2924 // only stall if the dynamic source is not yourself, denoted by src==NULL
2925 // otherwise the dynamic write nodes will have the local var up-to-date
2926 output.println(" {");
2927 output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
2928 output.println(" SESEcommon* common = (SESEcommon*) "+dynVar+"_srcSESE;");
2929 if( state.COREPROF ) {
2930 output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
2931 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_BEGIN );");
2932 output.println("#endif");
2934 output.println(" psem_take( &(common->stallSem) );");
2936 FlatMethod fmContext;
2937 if( currentSESE.getIsCallerSESEplaceholder() ) {
2938 fmContext = currentSESE.getfmEnclosing();
2940 fmContext = currentSESE.getfmBogus();
2943 TypeDescriptor type=dynVar.getType();
2945 if( type.isNull() ) {
2947 } else if( type.isClass() || type.isArray() ) {
2948 typeStr = "struct "+type.getSafeSymbol()+"*";
2950 typeStr = type.getSafeSymbol();
2953 output.println(" "+generateTemp( fmContext, dynVar, null )+
2954 " = *(("+typeStr+"*) ("+
2955 dynVar+"_srcSESE + "+dynVar+"_srcOffset));");
2956 if( state.COREPROF ) {
2957 output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
2958 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_END );");
2959 output.println("#endif");
2961 output.println(" }");
2962 output.println(" }");
2965 // for each assignment of a variable to rhs that has a dynamic source,
2966 // copy the dynamic sources
2967 Iterator dynAssignItr = cp.getDynAssigns().entrySet().iterator();
2968 while( dynAssignItr.hasNext() ) {
2969 Map.Entry me = (Map.Entry) dynAssignItr.next();
2970 TempDescriptor lhs = (TempDescriptor) me.getKey();
2971 TempDescriptor rhs = (TempDescriptor) me.getValue();
2973 output.println(" {");
2974 output.println(" SESEcommon* oldSrc = "+lhs+"_srcSESE;");
2976 output.println(" "+lhs+"_srcSESE = "+rhs+"_srcSESE;");
2977 output.println(" "+lhs+"_srcOffset = "+rhs+"_srcOffset;");
2979 // no matter what we did above, track reference count of whatever
2980 // this variable pointed to, do release last in case we're just
2981 // copying the same value in because 1->2->1 is safe but ref count
2982 // 1->0->1 has a window where it looks like it should be free'd
2983 output.println(" if( "+rhs+"_srcSESE != NULL ) {");
2984 output.println(" ADD_REFERENCE_TO( "+rhs+"_srcSESE );");
2985 output.println(" }");
2986 output.println(" if( oldSrc != NULL ) {");
2987 output.println(" RELEASE_REFERENCE_TO( oldSrc );");
2988 output.println(" }");
2989 output.println(" }");
2992 // for each lhs that is dynamic from a non-dynamic source, set the
2993 // dynamic source vars to the current SESE
2994 dynItr = cp.getDynAssignCurr().iterator();
2995 while( dynItr.hasNext() ) {
2996 TempDescriptor dynVar = dynItr.next();
2997 assert currentSESE.getDynamicVarSet().contains( dynVar );
2999 // first release a reference to current record
3000 output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
3001 output.println(" RELEASE_REFERENCE_TO( oldSrc );");
3002 output.println(" }");
3004 output.println(" "+dynVar+"_srcSESE = NULL;");
3008 // handling stall site
3009 if (state.OOOJAVA) {
3010 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(currentSESE);
3012 Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
3013 Set<Analysis.OoOJava.WaitingElement> waitingElementSet =
3014 graph.getStallSiteWaitingElementSet(fn, seseLockSet);
3016 if(waitingElementSet.size()>0){
3017 output.println("// stall on parent's stall sites ");
3018 output.println(" {");
3019 output.println(" REntry* rentry;");
3021 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
3022 Analysis.OoOJava.WaitingElement waitingElement = (Analysis.OoOJava.WaitingElement) iterator.next();
3024 if(state.RCR && rcr != null){
3025 Analysis.OoOJava.ConflictGraph conflictGraph = graph;
3026 Hashtable<Taint, Set<Effect>> conflicts;
3027 ReachGraph rg = oooa.getDisjointAnalysis().getReachGraph(currentSESE.getmdEnclosing());
3028 if(rcr.cSideDebug) {
3029 rg.writeGraph("RCR_RG_STALLSITE_DEBUG");
3031 if((conflictGraph != null) &&
3032 (conflicts = graph.getConflictEffectSet(fn)) != null &&
3035 rcr.addToTraverseToDoList(fn, waitingElement.getTempDesc(), rg, conflicts);
3039 if( waitingElement.getStatus() >= ConflictNode.COARSE ){
3040 output.println(" rentry=mlpCreateREntry("+ waitingElement.getStatus()+ ", runningSESE);");
3042 output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", runningSESE, (void*)&" +generateTemp(fm,waitingElement.getTempDesc(),lb)+ ");");
3044 output.println(" psem_init( &(rentry->parentStallSem) );");
3045 output.println(" rentry->queue=runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
3046 output.println(" if(ADDRENTRY(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()
3047 + "],rentry)==NOTREADY){");
3048 if( state.COREPROF ) {
3049 output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3050 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_BEGIN );");
3051 output.println("#endif");
3053 output.println(" psem_take( &(rentry->parentStallSem) );");
3054 if( state.COREPROF ) {
3055 output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3056 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_END );");
3057 output.println("#endif");
3059 output.println(" } ");
3061 if(state.RCR && rcr != null) {
3062 output.println(" "+rcr.getTraverserInvocation(waitingElement.getTempDesc(),
3063 generateTemp(fm, waitingElement.getTempDesc(), null), fn));
3066 output.println(" }");
3070 ParentChildConflictsMap conflictsMap = mlpa.getConflictsResults().get(fn);
3071 if (conflictsMap != null) {
3072 Set<Long> allocSet = conflictsMap.getAllocationSiteIDSetofStallSite();
3073 if (allocSet.size() > 0) {
3074 FlatNode enclosingFlatNode=null;
3075 if( currentSESE.getIsCallerSESEplaceholder() && currentSESE.getParent()==null){
3076 enclosingFlatNode=currentSESE.getfmEnclosing();
3078 enclosingFlatNode=currentSESE;
3080 ConflictGraph graph=mlpa.getConflictGraphResults().get(enclosingFlatNode);
3081 HashSet<SESELock> seseLockSet=mlpa.getConflictGraphLockMap().get(graph);
3082 Set<WaitingElement> waitingElementSet=graph.getStallSiteWaitingElementSet(conflictsMap, seseLockSet);
3084 if(waitingElementSet.size()>0){
3085 output.println("// stall on parent's stall sites ");
3086 output.println(" {");
3087 output.println(" REntry* rentry;");
3089 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
3090 WaitingElement waitingElement = (WaitingElement) iterator.next();
3092 if( waitingElement.getStatus() >= ConflictNode.COARSE ){
3093 // HERE! a parent might conflict with a child
3094 output.println(" rentry=mlpCreateREntry("+ waitingElement.getStatus()+ ", runningSESE);");
3096 output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", runningSESE, (void*)&___locals___."+ waitingElement.getDynID() + ");");
3098 output.println(" psem_init( &(rentry->parentStallSem) );");
3099 output.println(" rentry->queue=runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
3101 .println(" if(ADDRENTRY(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()
3102 + "],rentry)==NOTREADY){");
3103 if( state.COREPROF ) {
3104 output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3105 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_BEGIN );");
3106 output.println("#endif");
3108 output.println(" psem_take( &(rentry->parentStallSem) );");
3109 if( state.COREPROF ) {
3110 output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3111 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_END );");
3112 output.println("#endif");
3114 output.println(" } ");
3116 output.println(" }");
3125 case FKind.FlatAtomicEnterNode:
3126 generateFlatAtomicEnterNode(fm, lb, (FlatAtomicEnterNode) fn, output);
3129 case FKind.FlatAtomicExitNode:
3130 generateFlatAtomicExitNode(fm, lb, (FlatAtomicExitNode) fn, output);
3133 case FKind.FlatInstanceOfNode:
3134 generateFlatInstanceOfNode(fm, lb, (FlatInstanceOfNode)fn, output);
3137 case FKind.FlatSESEEnterNode:
3138 generateFlatSESEEnterNode(fm, lb, (FlatSESEEnterNode)fn, output);
3141 case FKind.FlatSESEExitNode:
3142 generateFlatSESEExitNode(fm, lb, (FlatSESEExitNode)fn, output);
3145 case FKind.FlatWriteDynamicVarNode:
3146 generateFlatWriteDynamicVarNode(fm, lb, (FlatWriteDynamicVarNode)fn, output);
3149 case FKind.FlatGlobalConvNode:
3150 generateFlatGlobalConvNode(fm, lb, (FlatGlobalConvNode) fn, output);
3153 case FKind.FlatTagDeclaration:
3154 generateFlatTagDeclaration(fm, lb, (FlatTagDeclaration) fn,output);
3157 case FKind.FlatCall:
3158 generateFlatCall(fm, lb, (FlatCall) fn,output);
3161 case FKind.FlatFieldNode:
3162 generateFlatFieldNode(fm, lb, (FlatFieldNode) fn,output);
3165 case FKind.FlatElementNode:
3166 generateFlatElementNode(fm, lb, (FlatElementNode) fn,output);
3169 case FKind.FlatSetElementNode:
3170 generateFlatSetElementNode(fm, lb, (FlatSetElementNode) fn,output);
3173 case FKind.FlatSetFieldNode:
3174 generateFlatSetFieldNode(fm, lb, (FlatSetFieldNode) fn,output);
3178 generateFlatNew(fm, lb, (FlatNew) fn,output);
3181 case FKind.FlatOpNode:
3182 generateFlatOpNode(fm, lb, (FlatOpNode) fn,output);
3185 case FKind.FlatCastNode:
3186 generateFlatCastNode(fm, lb, (FlatCastNode) fn,output);
3189 case FKind.FlatLiteralNode:
3190 generateFlatLiteralNode(fm, lb, (FlatLiteralNode) fn,output);
3193 case FKind.FlatReturnNode:
3194 generateFlatReturnNode(fm, lb, (FlatReturnNode) fn,output);
3198 output.println("/* nop */");
3201 case FKind.FlatExit:
3202 output.println("/* exit */");
3205 case FKind.FlatBackEdge:
3206 if (state.SINGLETM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
3207 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
3209 if(state.DSM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
3210 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
3212 if (((state.MLP|| state.OOOJAVA||state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
3213 || (this.state.MULTICOREGC)) {
3214 if(state.DSM&&locality.getAtomic(lb).get(fn).intValue()>0) {
3215 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
3216 } else if(this.state.MULTICOREGC) {
3217 output.println("if (gcflag) gc("+localsprefixaddr+");");
3219 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3222 output.println("/* nop */");
3225 case FKind.FlatCheckNode:
3226 generateFlatCheckNode(fm, lb, (FlatCheckNode) fn, output);
3229 case FKind.FlatFlagActionNode:
3230 generateFlatFlagActionNode(fm, lb, (FlatFlagActionNode) fn, output);
3233 case FKind.FlatPrefetchNode:
3234 generateFlatPrefetchNode(fm,lb, (FlatPrefetchNode) fn, output);
3237 case FKind.FlatOffsetNode:
3238 generateFlatOffsetNode(fm, lb, (FlatOffsetNode)fn, output);
3245 // insert post-node actions from the code-plan
3248 CodePlan cp = mlpa.getCodePlan( fn );
3256 public void generateFlatOffsetNode(FlatMethod fm, LocalityBinding lb, FlatOffsetNode fofn, PrintWriter output) {
3257 output.println("/* FlatOffsetNode */");
3258 FieldDescriptor fd=fofn.getField();
3259 output.println(generateTemp(fm, fofn.getDst(),lb)+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+ fd.getSafeSymbol()+");");
3260 output.println("/* offset */");
3263 public void generateFlatPrefetchNode(FlatMethod fm, LocalityBinding lb, FlatPrefetchNode fpn, PrintWriter output) {
3264 if (state.PREFETCH) {
3265 Vector oids = new Vector();
3266 Vector fieldoffset = new Vector();
3267 Vector endoffset = new Vector();
3268 int tuplecount = 0; //Keeps track of number of prefetch tuples that need to be generated
3269 for(Iterator it = fpn.hspp.iterator(); it.hasNext();) {
3270 PrefetchPair pp = (PrefetchPair) it.next();
3271 Integer statusbase = locality.getNodePreTempInfo(lb,fpn).get(pp.base);
3272 /* Find prefetches that can generate oid */
3273 if(statusbase == LocalityAnalysis.GLOBAL) {
3274 generateTransCode(fm, lb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(lb).get(fpn).intValue()>0, false);
3276 } else if (statusbase == LocalityAnalysis.LOCAL) {
3277 generateTransCode(fm,lb,pp,oids,fieldoffset,endoffset,tuplecount,false,true);
3284 System.out.println("Adding prefetch "+fpn+ " to method:" +fm);
3285 output.println("{");
3286 output.println("/* prefetch */");
3287 output.println("/* prefetchid_" + fpn.siteid + " */");
3288 output.println("void * prefptr;");
3289 output.println("int tmpindex;");
3291 output.println("if((evalPrefetch["+fpn.siteid+"].operMode) || (evalPrefetch["+fpn.siteid+"].retrycount <= 0)) {");
3292 /*Create C code for oid array */
3293 output.print(" unsigned int oidarray_[] = {");
3294 boolean needcomma=false;
3295 for (Iterator it = oids.iterator(); it.hasNext();) {
3298 output.print(it.next());
3301 output.println("};");
3303 /*Create C code for endoffset values */
3304 output.print(" unsigned short endoffsetarry_[] = {");
3306 for (Iterator it = endoffset.iterator(); it.hasNext();) {
3309 output.print(it.next());
3312 output.println("};");
3314 /*Create C code for Field Offset Values */
3315 output.print(" short fieldarry_[] = {");
3317 for (Iterator it = fieldoffset.iterator(); it.hasNext();) {
3320 output.print(it.next());
3323 output.println("};");
3324 /* make the prefetch call to Runtime */
3325 output.println(" if(!evalPrefetch["+fpn.siteid+"].operMode) {");
3326 output.println(" evalPrefetch["+fpn.siteid+"].retrycount = RETRYINTERVAL;");
3327 output.println(" }");
3328 output.println(" prefetch("+fpn.siteid+" ,"+tuplecount+", oidarray_, endoffsetarry_, fieldarry_);");
3329 output.println(" } else {");
3330 output.println(" evalPrefetch["+fpn.siteid+"].retrycount--;");
3331 output.println(" }");
3332 output.println("}");
3336 public void generateTransCode(FlatMethod fm, LocalityBinding lb,PrefetchPair pp, Vector oids, Vector fieldoffset, Vector endoffset, int tuplecount, boolean inside, boolean localbase) {
3337 short offsetcount = 0;
3341 } else if (localbase) {
3342 for(; breakindex<pp.desc.size(); breakindex++) {
3343 Descriptor desc=pp.getDescAt(breakindex);
3344 if (desc instanceof FieldDescriptor) {
3345 FieldDescriptor fd=(FieldDescriptor)desc;
3346 if (fd.isGlobal()) {
3354 if (breakindex>pp.desc.size()) //all local
3357 TypeDescriptor lasttype=pp.base.getType();
3358 String basestr=generateTemp(fm, pp.base, lb);
3360 boolean maybenull=fm.getMethod().isStatic()||
3361 !pp.base.equals(fm.getParameter(0));
3363 for(int i=0; i<breakindex; i++) {
3364 String indexcheck="";
3366 Descriptor desc=pp.getDescAt(i);
3367 if (desc instanceof FieldDescriptor) {
3368 FieldDescriptor fd=(FieldDescriptor)desc;
3370 if (!teststr.equals(""))
3372 teststr+="((prefptr="+basestr+")!=NULL)";
3373 basestr="((struct "+lasttype.getSafeSymbol()+" *)prefptr)->"+fd.getSafeSymbol();
3375 basestr=basestr+"->"+fd.getSafeSymbol();
3378 lasttype=fd.getType();
3380 IndexDescriptor id=(IndexDescriptor)desc;
3381 indexcheck="((tmpindex=";
3382 for(int j=0; j<id.tddesc.size(); j++) {
3383 indexcheck+=generateTemp(fm, id.getTempDescAt(j), lb)+"+";
3385 indexcheck+=id.offset+")>=0)&(tmpindex<((struct ArrayObject *)prefptr)->___length___)";
3387 if (!teststr.equals(""))
3389 teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck;
3390 basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]";
3392 lasttype=lasttype.dereference();
3397 if (teststr.equals("")) {
3398 oid="((unsigned int)"+basestr+")";
3400 oid="((unsigned int)(("+teststr+")?"+basestr+":NULL))";
3404 for(int i = breakindex; i < pp.desc.size(); i++) {
3405 String newfieldoffset;
3406 Object desc = pp.getDescAt(i);
3407 if(desc instanceof FieldDescriptor) {
3408 FieldDescriptor fd=(FieldDescriptor)desc;
3409 newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))");
3410 lasttype=fd.getType();
3412 newfieldoffset = "";
3413 IndexDescriptor id=(IndexDescriptor)desc;
3414 for(int j = 0; j < id.tddesc.size(); j++) {
3415 newfieldoffset += generateTemp(fm, id.getTempDescAt(j), lb) + "+";
3417 newfieldoffset += id.offset.toString();
3418 lasttype=lasttype.dereference();
3420 fieldoffset.add(newfieldoffset);
3423 int base=(tuplecount>0) ? ((Short)endoffset.get(tuplecount-1)).intValue() : 0;
3424 base+=pp.desc.size()-breakindex;
3425 endoffset.add(new Short((short)base));
3430 public void generateFlatGlobalConvNode(FlatMethod fm, LocalityBinding lb, FlatGlobalConvNode fgcn, PrintWriter output) {
3431 if (lb!=fgcn.getLocality())
3433 /* Have to generate flat globalconv */
3434 if (fgcn.getMakePtr()) {
3436 //DEBUG: output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+",\" "+fm+":"+fgcn+"\");");
3437 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3439 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fgcn)||state.READSET&&dc.getNeedWriteTrans(lb, fgcn)) {
3440 //need to do translation
3441 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+", (void *)("+localsprefixaddr+"));");
3442 } else if (state.READSET&&dc.getNeedTrans(lb, fgcn)) {
3443 if (state.HYBRID&&delaycomp.getConv(lb).contains(fgcn)) {
3444 output.println("TRANSREADRDFISSION("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3446 output.println("TRANSREADRD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3450 /* Need to convert to OID */
3451 if ((dc==null)||dc.getNeedSrcTrans(lb,fgcn)) {
3452 if (fgcn.doConvert()||(delaycomp!=null&&delaycomp.needsFission(lb, fgcn.getAtomicEnter())&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) {
3453 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc(),lb)+");");
3455 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=NULL;");
3461 public void generateFlatInstanceOfNode(FlatMethod fm, LocalityBinding lb, FlatInstanceOfNode fion, PrintWriter output) {
3463 if (fion.getType().isArray()) {
3464 type=state.getArrayNumber(fion.getType())+state.numClasses();
3466 type=fion.getType().getClassDesc().getId();
3469 if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
3470 output.println(generateTemp(fm, fion.getDst(), lb)+"=1;");
3472 output.println(generateTemp(fm, fion.getDst(), lb)+"=instanceof("+generateTemp(fm,fion.getSrc(),lb)+","+type+");");
3475 int sandboxcounter=0;
3476 public void generateFlatAtomicEnterNode(FlatMethod fm, LocalityBinding lb, FlatAtomicEnterNode faen, PrintWriter output) {
3477 /* Check to see if we need to generate code for this atomic */
3478 if (locality==null) {
3479 if (GENERATEPRECISEGC) {
3480 output.println("if (pthread_mutex_trylock(&atomiclock)!=0) {");
3481 output.println("stopforgc((struct garbagelist *) &___locals___);");
3482 output.println("pthread_mutex_lock(&atomiclock);");
3483 output.println("restartaftergc();");
3484 output.println("}");
3486 output.println("pthread_mutex_lock(&atomiclock);");
3491 if (locality.getAtomic(lb).get(faen.getPrev(0)).intValue()>0)
3495 if (state.SANDBOX) {
3496 outsandbox.println("int atomiccounter"+sandboxcounter+"=LOW_CHECK_FREQUENCY;");
3497 output.println("counter_reset_pointer=&atomiccounter"+sandboxcounter+";");
3500 if (state.DELAYCOMP&&delaycomp.needsFission(lb, faen)) {
3501 AtomicRecord ar=atomicmethodmap.get(faen);
3503 for(Iterator<TempDescriptor> tmpit=ar.livein.iterator();tmpit.hasNext();) {
3504 TempDescriptor tmp=tmpit.next();
3505 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3508 //copy outs that depend on path
3509 for(Iterator<TempDescriptor> tmpit=ar.liveoutvirtualread.iterator();tmpit.hasNext();) {
3510 TempDescriptor tmp=tmpit.next();
3511 if (!ar.livein.contains(tmp))
3512 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3516 /* Backup the temps. */
3517 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3518 TempDescriptor tmp=tmpit.next();
3519 output.println(generateTemp(fm, backuptable.get(lb).get(tmp),lb)+"="+generateTemp(fm,tmp,lb)+";");
3522 output.println("goto transstart"+faen.getIdentifier()+";");
3524 /******* Print code to retry aborted transaction *******/
3525 output.println("transretry"+faen.getIdentifier()+":");
3528 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3529 TempDescriptor tmp=tmpit.next();
3530 output.println(generateTemp(fm, tmp,lb)+"="+generateTemp(fm,backuptable.get(lb).get(tmp),lb)+";");
3534 /********* Need to revert local object store ********/
3535 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3537 output.println("while ("+revertptr+") {");
3538 output.println("struct ___Object___ * tmpptr;");
3539 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3540 output.println("REVERT_OBJ("+revertptr+");");
3541 output.println(revertptr+"=tmpptr;");
3542 output.println("}");
3544 /******* Tell the runtime to start the transaction *******/
3546 output.println("transstart"+faen.getIdentifier()+":");
3547 if (state.SANDBOX) {
3548 output.println("transaction_check_counter=*counter_reset_pointer;");
3551 output.println("transStart();");
3553 if (state.ABORTREADERS||state.SANDBOX) {
3555 output.println("abortenabled=1;");
3556 output.println("if (_setjmp(aborttrans)) {");
3557 output.println(" goto transretry"+faen.getIdentifier()+"; }");
3561 public void generateFlatAtomicExitNode(FlatMethod fm, LocalityBinding lb, FlatAtomicExitNode faen, PrintWriter output) {
3562 /* Check to see if we need to generate code for this atomic */
3563 if (locality==null) {
3564 output.println("pthread_mutex_unlock(&atomiclock);");
3567 if (locality.getAtomic(lb).get(faen).intValue()>0)
3569 //store the revert list before we lose the transaction object
3572 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3573 output.println(revertptr+"=revertlist;");
3574 output.println("if (transCommit()) {");
3575 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3576 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3577 output.println("} else {");
3578 /* Need to commit local object store */
3579 output.println("while ("+revertptr+") {");
3580 output.println("struct ___Object___ * tmpptr;");
3581 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3582 output.println("COMMIT_OBJ("+revertptr+");");
3583 output.println(revertptr+"=tmpptr;");
3584 output.println("}");
3585 output.println("}");
3589 if (!state.DELAYCOMP) {
3591 output.println("if (transCommit()) {");
3592 /* Transaction aborts if it returns true */
3593 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3594 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3595 output.println("}");
3597 if (delaycomp.optimizeTrans(lb, faen.getAtomicEnter())&&(!state.STMARRAY||state.DUALVIEW)) {
3598 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3599 output.println("LIGHTWEIGHTCOMMIT("+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+", transretry"+faen.getAtomicEnter().getIdentifier()+");");
3601 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3602 TempDescriptor tmp=tmpit.next();
3603 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3605 } else if (delaycomp.needsFission(lb, faen.getAtomicEnter())) {
3606 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3608 output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {");
3609 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3610 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3611 output.println("}");
3613 output.println("else {");
3614 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3615 TempDescriptor tmp=tmpit.next();
3616 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3618 output.println("}");
3620 output.println("if (transCommit(NULL, NULL, NULL, NULL)) {");
3621 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3622 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3623 output.println("}");
3628 public void generateFlatSESEEnterNode( FlatMethod fm,
3630 FlatSESEEnterNode fsen,
3633 // if MLP flag is off, okay that SESE nodes are in IR graph,
3634 // just skip over them and code generates exactly the same
3635 if( !(state.MLP || state.OOOJAVA) ) {
3638 // there may be an SESE in an unreachable method, skip over
3639 if( (state.MLP && !mlpa.getAllSESEs().contains( fsen )) ||
3640 (state.OOOJAVA && !oooa.getAllSESEs().contains(fsen))
3645 // also, if we have encountered a placeholder, just skip it
3646 if( fsen.getIsCallerSESEplaceholder() ) {
3650 output.println(" {");
3652 if( state.COREPROF ) {
3653 output.println("#ifdef CP_EVENTID_TASKDISPATCH");
3654 output.println(" CP_LOGEVENT( CP_EVENTID_TASKDISPATCH, CP_EVENTTYPE_BEGIN );");
3655 output.println("#endif");
3658 // before doing anything, lock your own record and increment the running children
3659 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3660 (state.OOOJAVA && fsen != oooa.getMainSESE())
3662 output.println(" atomic_inc(&(runningSESE->numRunningChildren));");
3665 // allocate the space for this record
3666 output.println( "#ifndef OOO_DISABLE_TASKMEMPOOL" );
3667 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3668 (state.OOOJAVA && fsen != oooa.getMainSESE())
3671 fsen.getSESErecordName()+"* seseToIssue = ("+
3672 fsen.getSESErecordName()+"*) poolalloc( runningSESE->taskRecordMemPool );");
3675 fsen.getSESErecordName()+"* seseToIssue = ("+
3676 fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
3677 fsen.getSESErecordName()+" ) );");
3679 output.println( "#else" );
3681 fsen.getSESErecordName()+"* seseToIssue = ("+
3682 fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
3683 fsen.getSESErecordName()+" ) );");
3684 output.println( "#endif" );
3687 // set up the SESE in-set and out-set objects, which look
3688 // like a garbage list
3689 output.println(" struct garbagelist * gl= (struct garbagelist *)&(((SESEcommon*)(seseToIssue))[1]);");
3690 output.println(" gl->size="+calculateSizeOfSESEParamList(fsen)+";");
3691 output.println(" gl->next = NULL;");
3693 // there are pointers to SESE records the newly-issued SESE
3694 // will use to get values it depends on them for--how many
3695 // are there, and what is the offset from the total SESE
3696 // record to the first dependent record pointer?
3697 output.println(" seseToIssue->common.numDependentSESErecords="+
3698 fsen.getNumDepRecs()+";");
3700 // we only need this (and it will only compile) when the number of dependent
3701 // SESE records is non-zero
3702 if( fsen.getFirstDepRecField() != null ) {
3703 output.println(" seseToIssue->common.offsetToDepSESErecords=(INTPTR)sizeof("+
3704 fsen.getSESErecordName()+") - (INTPTR)&((("+
3705 fsen.getSESErecordName()+"*)0)->"+fsen.getFirstDepRecField()+");"
3709 // fill in common data
3710 output.println(" int localCount=0;");
3711 output.println(" seseToIssue->common.classID = "+fsen.getIdentifier()+";");
3712 output.println(" psem_init( &(seseToIssue->common.stallSem) );");
3714 output.println(" seseToIssue->common.forwardList = createQueue();");
3715 output.println(" seseToIssue->common.unresolvedDependencies = 10000;");
3716 output.println(" pthread_cond_init( &(seseToIssue->common.doneCond), NULL );");
3717 output.println(" seseToIssue->common.doneExecuting = FALSE;");
3718 output.println(" pthread_cond_init( &(seseToIssue->common.runningChildrenCond), NULL );");
3719 output.println(" seseToIssue->common.numRunningChildren = 0;");
3720 output.println(" seseToIssue->common.parent = runningSESE;");
3721 // start with refCount = 2, one being the count that the child itself
3722 // will decrement when it retires, to say it is done using its own
3723 // record, and the other count is for the parent that will remember
3724 // the static name of this new child below
3725 output.println(" seseToIssue->common.refCount = 2;");
3727 // all READY in-vars should be copied now and be done with it
3728 Iterator<TempDescriptor> tempItr = fsen.getReadyInVarSet().iterator();
3729 while( tempItr.hasNext() ) {
3730 TempDescriptor temp = tempItr.next();
3732 // when we are issuing the main SESE or an SESE with placeholder
3733 // caller SESE as parent, generate temp child child's eclosing method,
3734 // otherwise use the parent's enclosing method as the context
3735 boolean useParentContext = false;
3737 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3738 (state.OOOJAVA && fsen != oooa.getMainSESE())
3740 assert fsen.getParent() != null;
3741 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3742 useParentContext = true;
3746 if( useParentContext ) {
3747 output.println(" seseToIssue->"+temp+" = "+
3748 generateTemp( fsen.getParent().getfmBogus(), temp, null )+";");
3750 output.println(" seseToIssue->"+temp+" = "+
3751 generateTemp( fsen.getfmEnclosing(), temp, null )+";");
3755 // before potentially adding this SESE to other forwarding lists,
3757 output.println(" pthread_mutex_init( &(seseToIssue->common.lock), NULL );");
3759 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3760 (state.OOOJAVA && fsen != oooa.getMainSESE())
3762 // count up outstanding dependencies, static first, then dynamic
3763 Iterator<SESEandAgePair> staticSrcsItr = fsen.getStaticInVarSrcs().iterator();
3764 while( staticSrcsItr.hasNext() ) {
3765 SESEandAgePair srcPair = staticSrcsItr.next();
3766 output.println(" {");
3767 output.println(" SESEcommon* src = (SESEcommon*)"+srcPair+";");
3769 if(GENERATEPRECISEGC){
3770 output.println(" stopforgc((struct garbagelist *)&___locals___);");
3772 output.println(" pthread_mutex_lock( &(src->lock) );");
3773 if(GENERATEPRECISEGC){
3774 output.println(" restartaftergc();");
3776 output.println(" if( !isEmpty( src->forwardList ) &&");
3777 output.println(" seseToIssue == peekItem( src->forwardList ) ) {");
3778 output.println(" printf( \"This shouldnt already be here\\n\");");
3779 output.println(" exit( -1 );");
3780 output.println(" }");
3781 output.println(" if( !src->doneExecuting ) {");
3782 output.println(" addNewItem( src->forwardList, seseToIssue );");
3783 output.println(" ++(localCount);");
3784 output.println(" }");
3785 output.println(" ADD_REFERENCE_TO( src );");
3786 output.println(" pthread_mutex_unlock( &(src->lock) );");
3787 output.println(" }");
3789 // whether or not it is an outstanding dependency, make sure
3790 // to pass the static name to the child's record
3791 output.println(" seseToIssue->"+srcPair+" = "+
3792 "("+srcPair.getSESE().getSESErecordName()+"*)"+
3796 // dynamic sources might already be accounted for in the static list,
3797 // so only add them to forwarding lists if they're not already there
3798 Iterator<TempDescriptor> dynVarsItr = fsen.getDynamicInVarSet().iterator();
3799 while( dynVarsItr.hasNext() ) {
3800 TempDescriptor dynInVar = dynVarsItr.next();
3801 output.println(" {");
3802 output.println(" SESEcommon* src = (SESEcommon*)"+dynInVar+"_srcSESE;");
3804 // the dynamic source is NULL if it comes from your own space--you can't pass
3805 // the address off to the new child, because you're not done executing and
3806 // might change the variable, so copy it right now
3807 output.println(" if( src != NULL ) {");
3809 if(GENERATEPRECISEGC){
3810 output.println(" stopforgc((struct garbagelist *)&___locals___);");
3812 output.println(" pthread_mutex_lock( &(src->lock) );");
3813 if(GENERATEPRECISEGC){
3814 output.println(" restartaftergc();");
3816 output.println(" if( isEmpty( src->forwardList ) ||");
3817 output.println(" seseToIssue != peekItem( src->forwardList ) ) {");
3818 output.println(" if( !src->doneExecuting ) {");
3819 output.println(" addNewItem( src->forwardList, seseToIssue );");
3820 output.println(" ++(localCount);");
3821 output.println(" }");
3822 output.println(" }");
3823 output.println(" ADD_REFERENCE_TO( src );");
3824 output.println(" pthread_mutex_unlock( &(src->lock) );");
3825 output.println(" seseToIssue->"+dynInVar+"_srcOffset = "+dynInVar+"_srcOffset;");
3826 output.println(" } else {");
3828 boolean useParentContext = false;
3829 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3830 (state.OOOJAVA && fsen != oooa.getMainSESE())
3832 assert fsen.getParent() != null;
3833 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3834 useParentContext = true;
3837 if( useParentContext ) {
3838 output.println(" seseToIssue->"+dynInVar+" = "+
3839 generateTemp( fsen.getParent().getfmBogus(), dynInVar, null )+";");
3841 output.println(" seseToIssue->"+dynInVar+" = "+
3842 generateTemp( fsen.getfmEnclosing(), dynInVar, null )+";");
3845 output.println(" }");
3846 output.println(" }");
3848 // even if the value is already copied, make sure your NULL source
3849 // gets passed so child knows it already has the dynamic value
3850 output.println(" seseToIssue->"+dynInVar+"_srcSESE = "+dynInVar+"_srcSESE;");
3854 // maintain pointers for finding dynamic SESE
3855 // instances from static names
3856 SESEandAgePair pairNewest = new SESEandAgePair( fsen, 0 );
3857 SESEandAgePair pairOldest = new SESEandAgePair( fsen, fsen.getOldestAgeToTrack() );
3858 if( fsen.getParent() != null &&
3859 fsen.getParent().getNeededStaticNames().contains( pairNewest )
3862 for( int i = fsen.getOldestAgeToTrack(); i > 0; --i ) {
3863 SESEandAgePair pair1 = new SESEandAgePair( fsen, i );
3864 SESEandAgePair pair2 = new SESEandAgePair( fsen, i-1 );
3865 output.println(" "+pair1+" = "+pair2+";");
3867 output.println(" "+pairNewest+" = &(seseToIssue->common);");
3869 // no need to add a reference to whatever is the newest record, because
3870 // we initialized seseToIssue->refCount to *2*
3871 // but release a reference to whatever was the oldest BEFORE the shift
3872 output.println(" if( "+pairOldest+" != NULL ) {");
3873 output.println(" RELEASE_REFERENCE_TO( "+pairOldest+" );");
3874 output.println(" }");
3880 // count up memory conflict dependencies,
3884 //output.println(" seseToIssue->common.numMemoryQueue=0;");
3885 //output.println(" seseToIssue->common.rentryIdx=0;");
3886 //output.println(" seseToIssue->common.unresolvedRentryIdx=0;");
3887 //output.println(" seseToIssue->common.memoryQueueArray=NULL;");
3889 FlatSESEEnterNode parent = fsen.getParent();
3890 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(parent);
3891 if (graph != null && graph.hasConflictEdge()) {
3892 Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
3894 output.println(" //add memory queue element");
3895 Analysis.OoOJava.SESEWaitingQueue seseWaitingQueue=
3896 graph.getWaitingElementSetBySESEID(fsen.getIdentifier(), seseLockSet);
3897 if(seseWaitingQueue.getWaitingElementSize()>0){
3898 output.println(" {");
3899 output.println(" REntry* rentry=NULL;");
3900 output.println(" INTPTR* pointer=NULL;");
3901 output.println(" seseToIssue->common.rentryIdx=0;");
3903 Set<Integer> queueIDSet=seseWaitingQueue.getQueueIDSet();
3904 for (Iterator iterator = queueIDSet.iterator(); iterator
3906 Integer key = (Integer) iterator.next();
3907 int queueID=key.intValue();
3908 Set<Analysis.OoOJava.WaitingElement> waitingQueueSet =
3909 seseWaitingQueue.getWaitingElementSet(queueID);
3910 int enqueueType=seseWaitingQueue.getType(queueID);
3911 if(enqueueType==SESEWaitingQueue.EXCEPTION){
3912 output.println(" INITIALIZEBUF(runningSESE->memoryQueueArray["
3915 for (Iterator iterator2 = waitingQueueSet.iterator(); iterator2.hasNext();) {
3916 Analysis.OoOJava.WaitingElement waitingElement
3917 = (Analysis.OoOJava.WaitingElement) iterator2.next();
3918 if (waitingElement.getStatus() >= ConflictNode.COARSE) {
3919 output.println(" rentry=mlpCreateREntry("
3920 + waitingElement.getStatus()
3921 + ", &(seseToIssue->common));");
3923 TempDescriptor td = waitingElement.getTempDesc();
3924 // decide whether waiting element is dynamic or static
3925 if (fsen.getDynamicInVarSet().contains(td)) {
3926 // dynamic in-var case
3927 output.println(" pointer=seseToIssue->"
3928 + waitingElement.getDynID()
3929 + "_srcSESE+seseToIssue->"
3930 + waitingElement.getDynID()
3932 output.println(" rentry=mlpCreateFineREntry("
3933 + waitingElement.getStatus()
3934 + ", &(seseToIssue->common), pointer );");
3935 } else if (fsen.getStaticInVarSet().contains(td)) {
3936 // static in-var case
3937 VariableSourceToken vst = fsen.getStaticInVarSrc(td);
3940 String srcId = "SESE_"
3942 .getPrettyIdentifier()
3943 + vst.getSESE().getIdentifier()
3944 + "_" + vst.getAge();
3945 output.println(" pointer=(void*)&seseToIssue->"
3951 output.println(" rentry=mlpCreateFineREntry("
3952 + waitingElement.getStatus()
3953 + ", &(seseToIssue->common), pointer );");
3956 output.println(" rentry=mlpCreateFineREntry("
3957 + waitingElement.getStatus()
3958 + ", &(seseToIssue->common), (void*)&seseToIssue->"
3959 + waitingElement.getDynID()
3963 output.println(" rentry->queue=runningSESE->memoryQueueArray["
3964 + waitingElement.getQueueID()
3967 if(enqueueType==SESEWaitingQueue.NORMAL){
3968 output.println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
3969 output.println(" if(ADDRENTRY(runningSESE->memoryQueueArray["
3970 + waitingElement.getQueueID()
3971 + "],rentry)==NOTREADY){");
3972 output.println(" ++(localCount);");
3973 output.println(" }");
3975 // Trying to execute the dynamic coarse grain conflict strategy...
3976 if(state.RCR && rcr != null) {
3977 boolean useParentContext = false;
3979 if( (state.MLP &&fsen != mlpa.getMainSESE()) ||
3980 (state.OOOJAVA &&fsen != oooa.getMainSESE())) {
3981 assert fsen.getParent() != null;
3982 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3983 useParentContext = true;
3987 for (TempDescriptor invar : fsen.getInVarsForDynamicCoarseConflictResolution()) {
3989 if( useParentContext ) {
3990 varString = generateTemp( fsen.getParent().getfmBogus(), invar, null );
3992 varString = generateTemp( fsen.getfmEnclosing(), invar, null );
3994 output.println(" "+rcr.getTraverserInvocation(invar, varString, fsen));
3999 .println(" ADDRENTRYTOBUF(runningSESE->memoryQueueArray["
4000 + waitingElement.getQueueID()
4004 if(enqueueType!=SESEWaitingQueue.NORMAL){
4005 output.println(" localCount+=RESOLVEBUF(runningSESE->memoryQueueArray["
4006 + queueID+ "],&seseToIssue->common);");
4009 output.println(" }");
4015 ConflictGraph graph = null;
4016 FlatSESEEnterNode parent = fsen.getParent();
4017 if (parent != null) {
4018 if (parent.isCallerSESEplaceholder) {
4019 graph = mlpa.getConflictGraphResults().get(parent.getfmEnclosing());
4021 graph = mlpa.getConflictGraphResults().get(parent);
4024 if (graph != null && graph.hasConflictEdge()) {
4025 HashSet<SESELock> seseLockSet = mlpa.getConflictGraphLockMap()
4028 output.println(" //add memory queue element");
4029 SESEWaitingQueue seseWaitingQueue=graph.getWaitingElementSetBySESEID(fsen.getIdentifier(),
4031 if(seseWaitingQueue.getWaitingElementSize()>0){
4032 output.println(" {");
4033 output.println(" REntry* rentry=NULL;");
4034 output.println(" INTPTR* pointer=NULL;");
4035 output.println(" seseToIssue->common.rentryIdx=0;");
4037 Set<Integer> queueIDSet=seseWaitingQueue.getQueueIDSet();
4038 for (Iterator iterator = queueIDSet.iterator(); iterator
4040 Integer key = (Integer) iterator.next();
4041 int queueID=key.intValue();
4042 Set<WaitingElement> waitingQueueSet = seseWaitingQueue.getWaitingElementSet(queueID);
4043 int enqueueType=seseWaitingQueue.getType(queueID);
4044 if(enqueueType==SESEWaitingQueue.EXCEPTION){
4045 output.println(" INITIALIZEBUF(runningSESE->memoryQueueArray["
4048 for (Iterator iterator2 = waitingQueueSet.iterator(); iterator2
4050 WaitingElement waitingElement = (WaitingElement) iterator2
4052 if (waitingElement.getStatus() >= ConflictNode.COARSE) {
4053 output.println(" rentry=mlpCreateREntry("
4054 + waitingElement.getStatus()
4055 + ", &(seseToIssue->common));");
4057 TempDescriptor td = waitingElement
4059 // decide whether waiting element is dynamic or
4061 if (fsen.getDynamicInVarSet().contains(td)) {
4062 // dynamic in-var case
4063 output.println(" pointer=seseToIssue->"
4064 + waitingElement.getDynID()
4065 + "_srcSESE+seseToIssue->"
4066 + waitingElement.getDynID()
4069 .println(" rentry=mlpCreateFineREntry("
4072 + ", &(seseToIssue->common), pointer );");
4073 } else if (fsen.getStaticInVarSet()
4075 // static in-var case
4076 VariableSourceToken vst = fsen
4077 .getStaticInVarSrc(td);
4080 String srcId = "SESE_"
4082 .getPrettyIdentifier()
4083 + vst.getSESE().getIdentifier()
4084 + "_" + vst.getAge();
4086 .println(" pointer=(void*)&seseToIssue->"
4093 .println(" rentry=mlpCreateFineREntry("
4096 + ", &(seseToIssue->common), pointer );");
4101 .println(" rentry=mlpCreateFineREntry("
4104 + ", &(seseToIssue->common), (void*)&seseToIssue->"
4105 + waitingElement.getDynID()
4110 .println(" rentry->queue=runningSESE->memoryQueueArray["
4111 + waitingElement.getQueueID()
4114 if(enqueueType==SESEWaitingQueue.NORMAL){
4116 .println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
4118 .println(" if(ADDRENTRY(runningSESE->memoryQueueArray["
4119 + waitingElement.getQueueID()
4120 + "],rentry)==NOTREADY){");
4121 output.println(" ++(localCount);");
4122 output.println(" } ");
4125 .println(" ADDRENTRYTOBUF(runningSESE->memoryQueueArray["
4126 + waitingElement.getQueueID()
4130 if(enqueueType!=SESEWaitingQueue.NORMAL){
4131 output.println(" localCount+=RESOLVEBUF(runningSESE->memoryQueueArray["
4132 + queueID+ "],&seseToIssue->common);");
4135 output.println(" }");
4143 // release this SESE for siblings to update its dependencies or,
4144 // eventually, for it to mark itself finished
4145 // output.println(" pthread_mutex_unlock( &(seseToIssue->common.lock) );");
4147 // if there were no outstanding dependencies, issue here
4148 output.println(" if( atomic_sub_and_test(10000-localCount,&(seseToIssue->common.unresolvedDependencies) ) ) {");
4149 output.println(" workScheduleSubmit( (void*)seseToIssue );");
4150 output.println(" }");
4152 output.println(" if( seseToIssue->common.unresolvedDependencies == 0 ) {");
4153 output.println(" workScheduleSubmit( (void*)seseToIssue );");
4154 output.println(" }");
4156 // release this SESE for siblings to update its dependencies or,
4157 // eventually, for it to mark itself finished
4158 // output.println(" pthread_mutex_unlock( &(seseToIssue->common.lock) );");
4160 if( state.COREPROF ) {
4161 output.println("#ifdef CP_EVENTID_TASKDISPATCH");
4162 output.println(" CP_LOGEVENT( CP_EVENTID_TASKDISPATCH, CP_EVENTTYPE_END );");
4163 output.println("#endif");
4166 output.println(" }");
4170 public void generateFlatSESEExitNode( FlatMethod fm,
4172 FlatSESEExitNode fsexn,
4176 // if MLP flag is off, okay that SESE nodes are in IR graph,
4177 // just skip over them and code generates exactly the same
4178 if( ! (state.MLP || state.OOOJAVA) ) {
4182 // get the enter node for this exit that has meta data embedded
4183 FlatSESEEnterNode fsen = fsexn.getFlatEnter();
4185 // there may be an SESE in an unreachable method, skip over
4186 if( (state.MLP && !mlpa.getAllSESEs().contains( fsen )) ||
4187 (state.OOOJAVA && !oooa.getAllSESEs().contains( fsen ))
4192 // also, if we have encountered a placeholder, just jump it
4193 if( fsen.getIsCallerSESEplaceholder() ) {
4197 if( state.COREPROF ) {
4198 output.println("#ifdef CP_EVENTID_TASKEXECUTE");
4199 output.println(" CP_LOGEVENT( CP_EVENTID_TASKEXECUTE, CP_EVENTTYPE_END );");
4200 output.println("#endif");
4203 output.println(" /* SESE exiting */");
4205 if( state.COREPROF ) {
4206 output.println("#ifdef CP_EVENTID_TASKRETIRE");
4207 output.println(" CP_LOGEVENT( CP_EVENTID_TASKRETIRE, CP_EVENTTYPE_BEGIN );");
4208 output.println("#endif");
4211 String com = paramsprefix+"->common";
4213 // this SESE cannot be done until all of its children are done
4214 // so grab your own lock with the condition variable for watching
4215 // that the number of your running children is greater than zero
4216 if (GENERATEPRECISEGC){
4217 output.println(" stopforgc((struct garbagelist *)&___locals___);");
4219 output.println(" pthread_mutex_lock( &("+com+".lock) );");
4220 if (GENERATEPRECISEGC){
4221 output.println(" restartaftergc();");
4223 output.println(" while( "+com+".numRunningChildren > 0 ) {");
4224 if (GENERATEPRECISEGC){
4225 // output.println(" stopforgc((struct garbagelist *)&(((SESEcommon*)(___params___))[1]));");
4226 output.println(" stopforgc((struct garbagelist *)&___locals___);");
4228 output.println(" pthread_cond_wait( &("+com+".runningChildrenCond), &("+com+".lock) );");
4229 if (GENERATEPRECISEGC){
4230 output.println(" restartaftergc();");
4232 output.println(" }");
4235 // copy out-set from local temps into the sese record
4236 Iterator<TempDescriptor> itr = fsen.getOutVarSet().iterator();
4237 while( itr.hasNext() ) {
4238 TempDescriptor temp = itr.next();
4240 // only have to do this for primitives non-arrays
4242 temp.getType().isPrimitive() && !temp.getType().isArray()
4248 // have to determine the context enclosing this sese
4249 boolean useParentContext = false;
4251 if( (state.MLP &&fsen != mlpa.getMainSESE()) ||
4252 (state.OOOJAVA &&fsen != oooa.getMainSESE())
4254 assert fsen.getParent() != null;
4255 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
4256 useParentContext = true;
4261 if( useParentContext ) {
4262 from = generateTemp( fsen.getParent().getfmBogus(), temp, null );
4264 from = generateTemp( fsen.getfmEnclosing(), temp, null );
4267 output.println(" "+paramsprefix+
4268 "->"+temp.getSafeSymbol()+
4272 // mark yourself done, your SESE data is now read-only
4273 output.println(" "+com+".doneExecuting = TRUE;");
4274 output.println(" pthread_cond_signal( &("+com+".doneCond) );");
4275 output.println(" pthread_mutex_unlock( &("+com+".lock) );");
4277 // decrement dependency count for all SESE's on your forwarding list
4278 output.println(" while( !isEmpty( "+com+".forwardList ) ) {");
4279 output.println(" SESEcommon* consumer = (SESEcommon*) getItem( "+com+".forwardList );");
4282 output.println(" if(consumer->rentryIdx>0){");
4283 output.println(" // resolved null pointer");
4284 output.println(" int idx;");
4285 output.println(" for(idx=0;idx<consumer->rentryIdx;idx++){");
4286 output.println(" resolvePointer(consumer->rentryArray[idx]);");
4287 output.println(" }");
4288 output.println(" }");
4291 // output.println(" pthread_mutex_lock( &(consumer->lock) );");
4292 // output.println(" --(consumer->unresolvedDependencies);");
4293 // output.println(" if( consumer->unresolvedDependencies == 0 ) {");
4294 output.println(" if( atomic_sub_and_test(1, &(consumer->unresolvedDependencies)) ){");
4295 output.println(" workScheduleSubmit( (void*)consumer );");
4296 output.println(" }");
4297 // output.println(" pthread_mutex_unlock( &(consumer->lock) );");
4298 output.println(" }");
4302 // clean up its lock element from waiting queue, and decrement dependency count for next SESE block
4303 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
4304 (state.OOOJAVA && fsen != oooa.getMainSESE())
4308 output.println(" /* check memory dependency*/");
4309 output.println(" {");
4310 output.println(" int idx;");
4311 output.println(" for(idx=0;idx<___params___->common.rentryIdx;idx++){");
4312 output.println(" REntry* re=___params___->common.rentryArray[idx];");
4313 output.println(" RETIRERENTRY(re->queue,re);");
4314 output.println(" }");
4315 output.println(" }");
4319 // if parent is stalling on you, let them know you're done
4320 if( (state.MLP && fsexn.getFlatEnter() != mlpa.getMainSESE()) ||
4321 (state.OOOJAVA && fsexn.getFlatEnter() != oooa.getMainSESE())
4323 output.println(" psem_give( &("+paramsprefix+"->common.stallSem) );");
4326 // last of all, decrement your parent's number of running children
4327 output.println(" if( "+paramsprefix+"->common.parent != NULL ) {");
4328 output.println(" if (atomic_sub_and_test(1, &"+paramsprefix+"->common.parent->numRunningChildren)) {");
4329 if (GENERATEPRECISEGC){
4330 output.println(" stopforgc((struct garbagelist *)&___locals___);");
4332 output.println(" pthread_mutex_lock( &("+paramsprefix+"->common.parent->lock) );");
4333 if (GENERATEPRECISEGC){
4334 output.println(" restartaftergc();");
4336 output.println(" pthread_cond_signal( &("+paramsprefix+"->common.parent->runningChildrenCond) );");
4337 output.println(" pthread_mutex_unlock( &("+paramsprefix+"->common.parent->lock) );");
4338 output.println(" }");
4339 output.println(" }");
4341 // a task has variables to track static/dynamic instances
4342 // that serve as sources, release the parent's ref of each
4343 // non-null var of these types
4345 output.println(" // releasing static SESEs");
4346 Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
4347 while( pItr.hasNext() ) {
4348 SESEandAgePair pair = pItr.next();
4349 output.println(" if( "+pair+" != NULL ) {");
4350 output.println(" RELEASE_REFERENCE_TO( "+pair+" );");
4351 output.println(" }");
4353 output.println(" // releasing dynamic variable sources");
4354 Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
4355 while( dynSrcItr.hasNext() ) {
4356 TempDescriptor dynSrcVar = dynSrcItr.next();
4357 output.println(" if( "+dynSrcVar+"_srcSESE != NULL ) {");
4358 output.println(" RELEASE_REFERENCE_TO( "+dynSrcVar+"_srcSESE );");
4359 output.println(" }");
4362 // destroy this task's mempool if it is not a leaf task
4363 if( !fsen.getIsLeafSESE() ) {
4364 output.println( "#ifndef OOO_DISABLE_TASKMEMPOOL" );
4365 output.println(" pooldestroy( runningSESE->taskRecordMemPool );");
4366 output.println( "#endif" );
4370 // if this is not the Main sese (which has no parent) then return
4371 // THIS task's record to the PARENT'S task record pool, and only if
4372 // the reference count is now zero
4373 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
4374 (state.OOOJAVA && fsen != oooa.getMainSESE())
4376 output.println(" RELEASE_REFERENCE_TO( runningSESE );");
4378 // the main task has no parent, just free its record
4379 output.println(" mlpFreeSESErecord( runningSESE );");
4382 // as this thread is wrapping up the task, make sure the thread-local var
4383 // for the currently running task record references an invalid task
4384 output.println(" runningSESE = (SESEcommon*) 0x1;");
4386 if( state.COREPROF ) {
4387 output.println("#ifdef CP_EVENTID_TASKRETIRE");
4388 output.println(" CP_LOGEVENT( CP_EVENTID_TASKRETIRE, CP_EVENTTYPE_END );");
4389 output.println("#endif");
4393 public void generateFlatWriteDynamicVarNode( FlatMethod fm,
4395 FlatWriteDynamicVarNode fwdvn,
4398 if( !(state.MLP || state.OOOJAVA) ) {
4399 // should node should not be in an IR graph if the
4400 // MLP flag is not set
4401 throw new Error("Unexpected presence of FlatWriteDynamicVarNode");
4404 Hashtable<TempDescriptor, VSTWrapper> writeDynamic = fwdvn.getVar2src();
4406 assert writeDynamic != null;
4408 Iterator wdItr = writeDynamic.entrySet().iterator();
4409 while( wdItr.hasNext() ) {
4410 Map.Entry me = (Map.Entry) wdItr.next();
4411 TempDescriptor refVar = (TempDescriptor) me.getKey();
4412 VSTWrapper vstW = (VSTWrapper) me.getValue();
4413 VariableSourceToken vst = vstW.vst;
4415 output.println(" {");
4416 output.println(" SESEcommon* oldSrc = "+refVar+"_srcSESE;");
4419 // if there is no given source, this variable is ready so
4420 // mark src pointer NULL to signify that the var is up-to-date
4421 output.println(" "+refVar+"_srcSESE = NULL;");
4423 // otherwise we track where it will come from
4424 SESEandAgePair instance = new SESEandAgePair( vst.getSESE(), vst.getAge() );
4425 output.println(" "+refVar+"_srcSESE = "+instance+";");
4426 output.println(" "+refVar+"_srcOffset = (INTPTR) &((("+
4427 vst.getSESE().getSESErecordName()+"*)0)->"+vst.getAddrVar()+");");
4430 // no matter what we did above, track reference count of whatever
4431 // this variable pointed to, do release last in case we're just
4432 // copying the same value in because 1->2->1 is safe but ref count
4433 // 1->0->1 has a window where it looks like it should be free'd
4434 output.println(" if( "+refVar+"_srcSESE != NULL ) {");
4435 output.println(" ADD_REFERENCE_TO( "+refVar+"_srcSESE );");
4436 output.println(" }");
4437 output.println(" if( oldSrc != NULL ) {");
4438 output.println(" RELEASE_REFERENCE_TO( oldSrc );");
4439 output.println(" }");
4440 output.println(" }");
4445 private void generateFlatCheckNode(FlatMethod fm, LocalityBinding lb, FlatCheckNode fcn, PrintWriter output) {
4446 if (state.CONSCHECK) {
4447 String specname=fcn.getSpec();
4448 String varname="repairstate___";
4449 output.println("{");
4450 output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
4452 TempDescriptor[] temps=fcn.getTemps();
4453 String[] vars=fcn.getVars();
4454 for(int i=0; i<temps.length; i++) {
4455 output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i],lb)+";");
4458 output.println("if (doanalysis"+specname+"("+varname+")) {");
4459 output.println("free"+specname+"_state("+varname+");");
4460 output.println("} else {");
4461 output.println("/* Bad invariant */");
4462 output.println("free"+specname+"_state("+varname+");");
4463 output.println("abort_task();");
4464 output.println("}");
4465 output.println("}");
4469 private void generateFlatCall(FlatMethod fm, LocalityBinding lb, FlatCall fc, PrintWriter output) {
4471 MethodDescriptor md=fc.getMethod();
4472 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? locality.getBinding(lb, fc) : md);
4473 ClassDescriptor cn=md.getClassDesc();
4474 output.println("{");
4475 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4477 LocalityBinding fclb=locality.getBinding(lb, fc);
4478 output.print(" struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
4480 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
4481 output.print(objectparams.numPointers());
4482 output.print(", "+localsprefixaddr);
4483 if (md.getThis()!=null) {
4485 output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis(),lb));
4487 if (fc.getThis()!=null&&md.getThis()==null) {
4488 System.out.println("WARNING!!!!!!!!!!!!");
4489 System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
4493 for(int i=0; i<fc.numArgs(); i++) {
4494 Descriptor var=md.getParameter(i);
4495 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
4496 if (objectparams.isParamPtr(paramtemp)) {
4497 TempDescriptor targ=fc.getArg(i);
4499 TypeDescriptor td=md.getParamType(i);
4501 output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
4503 output.print("(struct "+md.getParamType(i).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
4506 output.println("};");
4511 if (fc.getReturnTemp()!=null)
4512 output.print(generateTemp(fm,fc.getReturnTemp(),lb)+"=");
4514 /* Do we need to do virtual dispatch? */
4515 if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
4518 LocalityBinding fclb=locality.getBinding(lb, fc);
4519 output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
4521 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
4526 if (md.getReturnType().isClass()||md.getReturnType().isArray())
4527 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
4529 output.print(md.getReturnType().getSafeSymbol()+" ");
4530 output.print("(*)(");
4532 boolean printcomma=false;
4533 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4535 LocalityBinding fclb=locality.getBinding(lb, fc);
4536 output.print("struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
4538 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
4542 for(int i=0; i<objectparams.numPrimitives(); i++) {
4543 TempDescriptor temp=objectparams.getPrimitive(i);
4547 if (temp.getType().isClass()||temp.getType().isArray())
4548 output.print("struct " + temp.getType().getSafeSymbol()+" * ");
4550 output.print(temp.getType().getSafeSymbol());
4555 LocalityBinding fclb=locality.getBinding(lb, fc);
4556 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])");
4558 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
4562 boolean needcomma=false;
4563 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4564 output.print("&__parameterlist__");
4568 if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
4569 if (fc.getThis()!=null) {
4570 TypeDescriptor ptd=md.getThis().getType();
4573 if (ptd.isClass()&&!ptd.isArray())
4574 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
4575 output.print(generateTemp(fm,fc.getThis(),lb));
4580 for(int i=0; i<fc.numArgs(); i++) {
4581 Descriptor var=md.getParameter(i);
4582 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
4583 if (objectparams.isParamPrim(paramtemp)) {
4584 TempDescriptor targ=fc.getArg(i);
4588 TypeDescriptor ptd=md.getParamType(i);
4589 if (ptd.isClass()&&!ptd.isArray())
4590 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
4591 output.print(generateTemp(fm, targ,lb));
4595 output.println(");");
4596 output.println(" }");
4599 private boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
4600 Set subclasses=typeutil.getSubClasses(thiscd);
4601 if (subclasses==null)
4603 for(Iterator classit=subclasses.iterator(); classit.hasNext();) {
4604 ClassDescriptor cd=(ClassDescriptor)classit.next();
4605 Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol());
4606 for(Iterator matchit=possiblematches.iterator(); matchit.hasNext();) {
4607 MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
4608 if (md.matches(matchmd))
4615 private void generateFlatFieldNode(FlatMethod fm, LocalityBinding lb, FlatFieldNode ffn, PrintWriter output) {
4616 if (state.SINGLETM) {
4617 //single machine transactional memory case
4618 String field=ffn.getField().getSafeSymbol();
4619 String src=generateTemp(fm, ffn.getSrc(),lb);
4620 String dst=generateTemp(fm, ffn.getDst(),lb);
4622 output.println(dst+"="+ src +"->"+field+ ";");
4623 if (ffn.getField().getType().isPtr()&&locality.getAtomic(lb).get(ffn).intValue()>0&&
4624 locality.getNodePreTempInfo(lb, ffn).get(ffn.getSrc())!=LocalityAnalysis.SCRATCH) {
4625 if ((dc==null)||(!state.READSET&&dc.getNeedTrans(lb, ffn))||
4626 (state.READSET&&dc.getNeedWriteTrans(lb, ffn))) {
4627 output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));");
4628 } else if (state.READSET&&dc.getNeedTrans(lb, ffn)) {
4629 if (state.HYBRID&&delaycomp.getConv(lb).contains(ffn)) {
4630 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4632 output.println("TRANSREADRD("+dst+", "+dst+");");
4635 } else if (state.DSM) {
4636 Integer status=locality.getNodePreTempInfo(lb,ffn).get(ffn.getSrc());
4637 if (status==LocalityAnalysis.GLOBAL) {
4638 String field=ffn.getField().getSafeSymbol();
4639 String src=generateTemp(fm, ffn.getSrc(),lb);
4640 String dst=generateTemp(fm, ffn.getDst(),lb);
4642 if (ffn.getField().getType().isPtr()) {
4644 //TODO: Uncomment this when we have runtime support
4645 //if (ffn.getSrc()==ffn.getDst()) {
4646 //output.println("{");
4647 //output.println("void * temp="+src+";");
4648 //output.println("if (temp&0x1) {");
4649 //output.println("temp=(void *) transRead(trans, (unsigned int) temp);");
4650 //output.println(src+"->"+field+"="+temp+";");
4651 //output.println("}");
4652 //output.println(dst+"=temp;");
4653 //output.println("}");
4655 output.println(dst+"="+ src +"->"+field+ ";");
4656 //output.println("if ("+dst+"&0x1) {");
4657 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
4658 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
4659 //output.println(src+"->"+field+"="+src+"->"+field+";");
4660 //output.println("}");
4663 output.println(dst+"="+ src+"->"+field+";");
4665 } else if (status==LocalityAnalysis.LOCAL) {
4666 if (ffn.getField().getType().isPtr()&&
4667 ffn.getField().isGlobal()) {
4668 String field=ffn.getField().getSafeSymbol();
4669 String src=generateTemp(fm, ffn.getSrc(),lb);
4670 String dst=generateTemp(fm, ffn.getDst(),lb);
4671 output.println(dst+"="+ src +"->"+field+ ";");
4672 if (locality.getAtomic(lb).get(ffn).intValue()>0)
4673 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
4674 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
4676 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4677 } else if (status==LocalityAnalysis.EITHER) {
4678 //Code is reading from a null pointer
4679 output.println("if ("+generateTemp(fm, ffn.getSrc(),lb)+") {");
4680 output.println("#ifndef RAW");
4681 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4682 output.println("#endif");
4683 //This should throw a suitable null pointer error
4684 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4686 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4688 // DEBUG if(!ffn.getDst().getType().isPrimitive()){
4689 // DEBUG output.println("within((void*)"+generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+");");
4691 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4696 private void generateFlatSetFieldNode(FlatMethod fm, LocalityBinding lb, FlatSetFieldNode fsfn, PrintWriter output) {
4697 if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
4698 throw new Error("Can't set array length");
4699 if (state.SINGLETM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
4700 //Single Machine Transaction Case
4701 boolean srcptr=fsfn.getSrc().getType().isPtr();
4702 String src=generateTemp(fm,fsfn.getSrc(),lb);
4703 String dst=generateTemp(fm,fsfn.getDst(),lb);
4704 output.println("//"+srcptr+" "+fsfn.getSrc().getType().isNull());
4705 if (srcptr&&!fsfn.getSrc().getType().isNull()) {
4706 output.println("{");
4707 if ((dc==null)||dc.getNeedSrcTrans(lb, fsfn)&&
4708 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) {
4709 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4711 output.println("INTPTR srcoid=(INTPTR)"+src+";");
4714 if (wb.needBarrier(fsfn)&&
4715 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getDst())!=LocalityAnalysis.SCRATCH) {
4716 if (state.EVENTMONITOR) {
4717 output.println("if ("+dst+"->___objstatus___&DIRTY) EVLOGEVENTOBJ(EV_WRITE,"+dst+"->objuid)");
4719 output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;");
4721 if (srcptr&!fsfn.getSrc().getType().isNull()) {
4722 output.println("*((unsigned INTPTR *)&("+dst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4723 output.println("}");
4725 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4727 } else if (state.DSM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
4728 Integer statussrc=locality.getNodePreTempInfo(lb,fsfn).get(fsfn.getSrc());
4729 Integer statusdst=locality.getNodeTempInfo(lb).get(fsfn).get(fsfn.getDst());
4730 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4732 String src=generateTemp(fm,fsfn.getSrc(),lb);
4733 String dst=generateTemp(fm,fsfn.getDst(),lb);
4735 output.println("{");
4736 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4738 if (statusdst.equals(LocalityAnalysis.GLOBAL)) {
4741 if (wb.needBarrier(fsfn))
4742 output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;");
4744 output.println("*((unsigned INTPTR *)&("+glbdst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4746 output.println(glbdst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4747 } else if (statusdst.equals(LocalityAnalysis.LOCAL)) {
4748 /** Check if we need to copy */
4749 output.println("if(!"+dst+"->"+localcopystr+") {");
4750 /* Link object into list */
4751 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4752 output.println(revertptr+"=revertlist;");
4753 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4754 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4756 output.println("COPY_OBJ("+dst+");");
4757 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4758 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4759 output.println("}");
4761 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4763 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4764 } else if (statusdst.equals(LocalityAnalysis.EITHER)) {
4765 //writing to a null...bad
4766 output.println("if ("+dst+") {");
4767 output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}");
4769 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4771 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4774 output.println("}");
4777 if (state.FASTCHECK) {
4778 String dst=generateTemp(fm, fsfn.getDst(),lb);
4779 output.println("if(!"+dst+"->"+localcopystr+") {");
4780 /* Link object into list */
4781 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4782 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4784 output.println("COPY_OBJ("+dst+");");
4785 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4786 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4787 output.println("}");
4790 // DEBUG if(!fsfn.getField().getType().isPrimitive()){
4791 // DEBUG output.println("within((void*)"+generateTemp(fm,fsfn.getSrc(),lb)+");");
4793 output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
4797 private void generateFlatElementNode(FlatMethod fm, LocalityBinding lb, FlatElementNode fen, PrintWriter output) {
4798 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
4801 if (elementtype.isArray()||elementtype.isClass())
4804 type=elementtype.getSafeSymbol()+" ";
4806 if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
4807 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fen.getIndex(),lb)+") >= "+generateTemp(fm,fen.getSrc(),lb) + "->___length___))");
4808 output.println("failedboundschk();");
4810 if (state.SINGLETM) {
4811 //Single machine transaction case
4812 String dst=generateTemp(fm, fen.getDst(),lb);
4813 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))) {
4814 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4816 output.println("STMGETARRAY("+dst+", "+ generateTemp(fm,fen.getSrc(),lb)+", "+generateTemp(fm, fen.getIndex(),lb)+", "+type+");");
4819 if (elementtype.isPtr()&&locality.getAtomic(lb).get(fen).intValue()>0&&
4820 locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())!=LocalityAnalysis.SCRATCH) {
4821 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fen)||state.READSET&&dc.getNeedWriteTrans(lb, fen)) {
4822 output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));");
4823 } else if (state.READSET&&dc.getNeedTrans(lb, fen)) {
4824 if (state.HYBRID&&delaycomp.getConv(lb).contains(fen)) {
4825 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4827 output.println("TRANSREADRD("+dst+", "+dst+");");
4830 } else if (state.DSM) {
4831 Integer status=locality.getNodePreTempInfo(lb,fen).get(fen.getSrc());
4832 if (status==LocalityAnalysis.GLOBAL) {
4833 String dst=generateTemp(fm, fen.getDst(),lb);
4834 if (elementtype.isPtr()) {
4835 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4836 //DEBUG: output.println("TRANSREAD("+dst+", "+dst+",\""+fm+":"+fen+"\");");
4837 output.println("TRANSREAD("+dst+", "+dst+");");
4839 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4841 } else if (status==LocalityAnalysis.LOCAL) {
4842 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4843 } else if (status==LocalityAnalysis.EITHER) {
4844 //Code is reading from a null pointer
4845 output.println("if ("+generateTemp(fm, fen.getSrc(),lb)+") {");
4846 output.println("#ifndef RAW");
4847 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4848 output.println("#endif");
4849 //This should throw a suitable null pointer error
4850 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4852 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4854 // DEBUG output.println("within((void*)"+generateTemp(fm,fen.getSrc(),lb)+");");
4855 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4859 private void generateFlatSetElementNode(FlatMethod fm, LocalityBinding lb, FlatSetElementNode fsen, PrintWriter output) {
4860 //TODO: need dynamic check to make sure this assignment is actually legal
4861 //Because Object[] could actually be something more specific...ie. Integer[]
4863 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
4866 if (elementtype.isArray()||elementtype.isClass())
4869 type=elementtype.getSafeSymbol()+" ";
4871 if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
4872 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fsen.getIndex(),lb)+") >= "+generateTemp(fm,fsen.getDst(),lb) + "->___length___))");
4873 output.println("failedboundschk();");
4876 if (state.SINGLETM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4877 //Transaction set element case
4878 if (wb.needBarrier(fsen)&&
4879 locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH) {
4880 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___objstatus___))|=DIRTY;");
4882 if (fsen.getSrc().getType().isPtr()&&!fsen.getSrc().getType().isNull()) {
4883 output.println("{");
4884 String src=generateTemp(fm, fsen.getSrc(), lb);
4885 if ((dc==null)||dc.getNeedSrcTrans(lb, fsen)&&
4886 locality.getNodePreTempInfo(lb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) {
4887 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4889 output.println("INTPTR srcoid=(INTPTR)"+src+";");
4891 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
4892 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", srcoid, INTPTR);");
4894 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
4896 output.println("}");
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)+", "+ generateTemp(fm, fsen.getSrc(), lb) +", "+type+");");
4901 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4904 } else if (state.DSM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4905 Integer statussrc=locality.getNodePreTempInfo(lb,fsen).get(fsen.getSrc());
4906 Integer statusdst=locality.getNodePreTempInfo(lb,fsen).get(fsen.getDst());
4907 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4908 boolean dstglobal=statusdst==LocalityAnalysis.GLOBAL;
4909 boolean dstlocal=(statusdst==LocalityAnalysis.LOCAL)||(statusdst==LocalityAnalysis.EITHER);
4912 if (wb.needBarrier(fsen))
4913 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___localcopy___))|=DIRTY;");
4914 } else if (dstlocal) {
4915 /** Check if we need to copy */
4916 String dst=generateTemp(fm, fsen.getDst(),lb);
4917 output.println("if(!"+dst+"->"+localcopystr+") {");
4918 /* Link object into list */
4919 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4920 output.println(revertptr+"=revertlist;");
4921 if ((GENERATEPRECISEGC) || this.state.MULTICOREGC)
4922 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4924 output.println("COPY_OBJ("+dst+");");
4925 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4926 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4927 output.println("}");
4929 System.out.println("Node: "+fsen);
4930 System.out.println(lb);
4931 System.out.println("statusdst="+statusdst);
4932 System.out.println(fm.printMethod());
4933 throw new Error("Unknown array type");
4936 output.println("{");
4937 String src=generateTemp(fm, fsen.getSrc(), lb);
4938 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4939 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
4940 output.println("}");
4942 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4945 if (state.FASTCHECK) {
4946 String dst=generateTemp(fm, fsen.getDst(),lb);
4947 output.println("if(!"+dst+"->"+localcopystr+") {");
4948 /* Link object into list */
4949 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4950 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4952 output.println("COPY_OBJ("+dst+");");
4953 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4954 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4955 output.println("}");
4957 // DEBUG output.println("within((void*)"+generateTemp(fm,fsen.getDst(),lb)+");");
4958 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4962 protected void generateFlatNew(FlatMethod fm, LocalityBinding lb, FlatNew fn, PrintWriter output) {
4963 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
4964 //Stash pointer in case of GC
4965 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4966 output.println(revertptr+"=revertlist;");
4968 if (state.SINGLETM) {
4969 if (fn.getType().isArray()) {
4970 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4971 if (locality.getAtomic(lb).get(fn).intValue()>0) {
4972 //inside transaction
4973 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4975 //outside transaction
4976 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4979 if (locality.getAtomic(lb).get(fn).intValue()>0) {
4980 //inside transaction
4981 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4983 //outside transaction
4984 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4987 } else if (fn.getType().isArray()) {
4988 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4989 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4990 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4991 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4992 if(this.state.MLP || state.OOOJAVA){
4993 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray_mlp("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+", oid, "+oooa.getDisjointAnalysis().getAllocationSiteFromFlatNew(fn).getUniqueAllocSiteID()+");");
4994 output.println(" oid += numWorkers;");
4996 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4999 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
5002 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
5003 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");");
5004 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5005 if (this.state.MLP || state.OOOJAVA){
5006 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new_mlp("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+", oid, "+oooa.getDisjointAnalysis().getAllocationSiteFromFlatNew(fn).getUniqueAllocSiteID()+");");
5007 output.println(" oid += numWorkers;");
5009 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
5012 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
5015 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
5016 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5017 String dst=generateTemp(fm,fn.getDst(),lb);
5018 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
5019 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
5020 output.println("revertlist=(struct ___Object___ *)"+dst+";");
5022 if (state.FASTCHECK) {
5023 String dst=generateTemp(fm,fn.getDst(),lb);
5024 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
5025 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
5026 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
5030 private void generateFlatTagDeclaration(FlatMethod fm, LocalityBinding lb, FlatTagDeclaration fn, PrintWriter output) {
5031 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5032 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
5034 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+state.getTagId(fn.getType())+");");
5038 private void generateFlatOpNode(FlatMethod fm, LocalityBinding lb, FlatOpNode fon, PrintWriter output) {
5039 if (fon.getRight()!=null) {
5040 if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
5041 if (fon.getLeft().getType().isLong())
5042 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
5044 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned int)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
5046 } else if (dc!=null) {
5047 output.print(generateTemp(fm, fon.getDest(),lb)+" = (");
5048 if (fon.getLeft().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
5049 output.print("(void *)");
5050 if (dc.getNeedLeftSrcTrans(lb, fon))
5051 output.print("("+generateTemp(fm, fon.getLeft(),lb)+"!=NULL?"+generateTemp(fm, fon.getLeft(),lb)+"->"+oidstr+":NULL)");
5053 output.print(generateTemp(fm, fon.getLeft(),lb));
5054 output.print(")"+fon.getOp().toString()+"(");
5055 if (fon.getRight().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
5056 output.print("(void *)");
5057 if (dc.getNeedRightSrcTrans(lb, fon))
5058 output.println("("+generateTemp(fm, fon.getRight(),lb)+"!=NULL?"+generateTemp(fm, fon.getRight(),lb)+"->"+oidstr+":NULL));");
5060 output.println(generateTemp(fm,fon.getRight(),lb)+");");
5062 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+fon.getOp().toString()+generateTemp(fm,fon.getRight(),lb)+";");
5063 } else if (fon.getOp().getOp()==Operation.ASSIGN)
5064 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
5065 else if (fon.getOp().getOp()==Operation.UNARYPLUS)
5066 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
5067 else if (fon.getOp().getOp()==Operation.UNARYMINUS)
5068 output.println(generateTemp(fm, fon.getDest(),lb)+" = -"+generateTemp(fm, fon.getLeft(),lb)+";");
5069 else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
5070 output.println(generateTemp(fm, fon.getDest(),lb)+" = !"+generateTemp(fm, fon.getLeft(),lb)+";");
5071 else if (fon.getOp().getOp()==Operation.COMP)
5072 output.println(generateTemp(fm, fon.getDest(),lb)+" = ~"+generateTemp(fm, fon.getLeft(),lb)+";");
5073 else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
5074 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+"->fses==NULL;");
5076 output.println(generateTemp(fm, fon.getDest(),lb)+fon.getOp().toString()+generateTemp(fm, fon.getLeft(),lb)+";");
5079 private void generateFlatCastNode(FlatMethod fm, LocalityBinding lb, FlatCastNode fcn, PrintWriter output) {
5080 /* TODO: Do type check here */
5081 if (fcn.getType().isArray()) {
5082 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
5083 } else if (fcn.getType().isClass())
5084 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
5086 output.println(generateTemp(fm,fcn.getDst(),lb)+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc(),lb)+";");
5089 private void generateFlatLiteralNode(FlatMethod fm, LocalityBinding lb, FlatLiteralNode fln, PrintWriter output) {
5090 if (fln.getValue()==null)
5091 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
5092 else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
5093 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5094 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
5095 //Stash pointer in case of GC
5096 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5097 output.println(revertptr+"=revertlist;");
5099 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
5100 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
5101 //Stash pointer in case of GC
5102 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5103 output.println("revertlist="+revertptr+";");
5106 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
5108 } else if (fln.getType().isBoolean()) {
5109 if (((Boolean)fln.getValue()).booleanValue())
5110 output.println(generateTemp(fm, fln.getDst(),lb)+"=1;");
5112 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
5113 } else if (fln.getType().isChar()) {
5114 String st=FlatLiteralNode.escapeString(fln.getValue().toString());
5115 output.println(generateTemp(fm, fln.getDst(),lb)+"='"+st+"';");
5116 } else if (fln.getType().isLong()) {
5117 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+"LL;");
5119 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+";");
5122 protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) {
5123 if (frn.getReturnTemp()!=null) {
5124 if (frn.getReturnTemp().getType().isPtr())
5125 output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";");
5127 output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";");
5129 output.println("return;");
5133 protected void generateStoreFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
5136 //only record if this group has more than one exit
5137 if (branchanalysis.numJumps(fcb)>1) {
5138 left=branchanalysis.jumpValue(fcb, 0);
5139 right=branchanalysis.jumpValue(fcb, 1);
5141 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") {");
5143 output.println("STOREBRANCH("+right+");");
5144 output.println("goto "+label+";");
5145 output.println("}");
5147 output.println("STOREBRANCH("+left+");");
5150 protected void generateFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
5151 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") goto "+label+";");
5154 /** This method generates header information for the method or
5155 * task referenced by the Descriptor des. */
5156 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) {
5157 generateHeader(fm, lb, des, output, false);
5160 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output, boolean addSESErecord) {
5162 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : des);
5163 MethodDescriptor md=null;
5164 TaskDescriptor task=null;
5165 if (des instanceof MethodDescriptor)
5166 md=(MethodDescriptor) des;
5168 task=(TaskDescriptor) des;
5170 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
5172 if (md!=null&&md.getReturnType()!=null) {
5173 if (md.getReturnType().isClass()||md.getReturnType().isArray())
5174 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
5176 output.print(md.getReturnType().getSafeSymbol()+" ");
5178 //catch the constructor case
5179 output.print("void ");
5181 if (state.DSM||state.SINGLETM) {
5182 output.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
5184 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
5186 output.print(task.getSafeSymbol()+"(");
5188 boolean printcomma=false;
5189 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5191 if (state.DSM||state.SINGLETM) {
5192 output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
5194 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
5196 output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
5202 for(int i=0; i<objectparams.numPrimitives(); i++) {
5203 TempDescriptor temp=objectparams.getPrimitive(i);
5207 if (temp.getType().isClass()||temp.getType().isArray())
5208 output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
5210 output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
5212 output.println(") {");
5213 } else if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
5214 /* Imprecise Task */
5215 output.println("void * parameterarray[]) {");
5216 /* Unpack variables */
5217 for(int i=0; i<objectparams.numPrimitives(); i++) {
5218 TempDescriptor temp=objectparams.getPrimitive(i);
5219 output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
5221 for(int i=0; i<fm.numTags(); i++) {
5222 TempDescriptor temp=fm.getTag(i);
5223 int offset=i+objectparams.numPrimitives();
5224 output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
5227 if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
5228 maxtaskparams=objectparams.numPrimitives()+fm.numTags();
5229 } else output.println(") {");
5232 public void generateFlatFlagActionNode(FlatMethod fm, LocalityBinding lb, FlatFlagActionNode ffan, PrintWriter output) {
5233 output.println("/* FlatFlagActionNode */");
5236 /* Process tag changes */
5237 Relation tagsettable=new Relation();
5238 Relation tagcleartable=new Relation();
5240 Iterator tagsit=ffan.getTempTagPairs();
5241 while (tagsit.hasNext()) {
5242 TempTagPair ttp=(TempTagPair) tagsit.next();
5243 TempDescriptor objtmp=ttp.getTemp();
5244 TagDescriptor tag=ttp.getTag();
5245 TempDescriptor tagtmp=ttp.getTagTemp();
5246 boolean tagstatus=ffan.getTagChange(ttp);
5248 tagsettable.put(objtmp, tagtmp);
5250 tagcleartable.put(objtmp, tagtmp);
5255 Hashtable flagandtable=new Hashtable();
5256 Hashtable flagortable=new Hashtable();
5258 /* Process flag changes */
5259 Iterator flagsit=ffan.getTempFlagPairs();
5260 while(flagsit.hasNext()) {
5261 TempFlagPair tfp=(TempFlagPair)flagsit.next();
5262 TempDescriptor temp=tfp.getTemp();
5263 Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
5264 FlagDescriptor flag=tfp.getFlag();
5266 //Newly allocate objects that don't set any flags case
5267 if (flagortable.containsKey(temp)) {
5271 flagortable.put(temp,new Integer(mask));
5273 int flagid=1<<((Integer)flagtable.get(flag)).intValue();
5274 boolean flagstatus=ffan.getFlagChange(tfp);
5277 if (flagortable.containsKey(temp)) {
5278 mask=((Integer)flagortable.get(temp)).intValue();
5281 flagortable.put(temp,new Integer(mask));
5283 int mask=0xFFFFFFFF;
5284 if (flagandtable.containsKey(temp)) {
5285 mask=((Integer)flagandtable.get(temp)).intValue();
5287 mask&=(0xFFFFFFFF^flagid);
5288 flagandtable.put(temp,new Integer(mask));
5294 HashSet flagtagset=new HashSet();
5295 flagtagset.addAll(flagortable.keySet());
5296 flagtagset.addAll(flagandtable.keySet());
5297 flagtagset.addAll(tagsettable.keySet());
5298 flagtagset.addAll(tagcleartable.keySet());
5300 Iterator ftit=flagtagset.iterator();
5301 while(ftit.hasNext()) {
5302 TempDescriptor temp=(TempDescriptor)ftit.next();
5305 Set tagtmps=tagcleartable.get(temp);
5306 if (tagtmps!=null) {
5307 Iterator tagit=tagtmps.iterator();
5308 while(tagit.hasNext()) {
5309 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
5310 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
5311 output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5313 output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5317 tagtmps=tagsettable.get(temp);
5318 if (tagtmps!=null) {
5319 Iterator tagit=tagtmps.iterator();
5320 while(tagit.hasNext()) {
5321 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
5322 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
5323 output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5325 output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp, lb)+", "+generateTemp(fm,tagtmp, lb)+");");
5330 int andmask=0xFFFFFFF;
5332 if (flagortable.containsKey(temp))
5333 ormask=((Integer)flagortable.get(temp)).intValue();
5334 if (flagandtable.containsKey(temp))
5335 andmask=((Integer)flagandtable.get(temp)).intValue();
5336 generateFlagOrAnd(ffan, fm, lb, temp, output, ormask, andmask);
5337 generateObjectDistribute(ffan, fm, lb, temp, output);
5341 protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp,
5342 PrintWriter output, int ormask, int andmask) {
5343 if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
5344 output.println("flagorandinit("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
5346 output.println("flagorand("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
5350 protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, PrintWriter output) {
5351 output.println("enqueueObject("+generateTemp(fm, temp, lb)+");");
5354 void generateOptionalHeader(PrintWriter headers) {
5357 headers.println("#include \"task.h\"\n\n");
5358 headers.println("#ifndef _OPTIONAL_STRUCT_");
5359 headers.println("#define _OPTIONAL_STRUCT_");
5361 //STRUCT PREDICATEMEMBER
5362 headers.println("struct predicatemember{");
5363 headers.println("int type;");
5364 headers.println("int numdnfterms;");
5365 headers.println("int * flags;");
5366 headers.println("int numtags;");
5367 headers.println("int * tags;\n};\n\n");
5369 //STRUCT OPTIONALTASKDESCRIPTOR
5370 headers.println("struct optionaltaskdescriptor{");
5371 headers.println("struct taskdescriptor * task;");
5372 headers.println("int index;");
5373 headers.println("int numenterflags;");
5374 headers.println("int * enterflags;");
5375 headers.println("int numpredicatemembers;");
5376 headers.println("struct predicatemember ** predicatememberarray;");
5377 headers.println("};\n\n");
5379 //STRUCT TASKFAILURE
5380 headers.println("struct taskfailure {");
5381 headers.println("struct taskdescriptor * task;");
5382 headers.println("int index;");
5383 headers.println("int numoptionaltaskdescriptors;");
5384 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
5386 //STRUCT FSANALYSISWRAPPER
5387 headers.println("struct fsanalysiswrapper{");
5388 headers.println("int flags;");
5389 headers.println("int numtags;");
5390 headers.println("int * tags;");
5391 headers.println("int numtaskfailures;");
5392 headers.println("struct taskfailure ** taskfailurearray;");
5393 headers.println("int numoptionaltaskdescriptors;");
5394 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
5396 //STRUCT CLASSANALYSISWRAPPER
5397 headers.println("struct classanalysiswrapper{");
5398 headers.println("int type;");
5399 headers.println("int numotd;");
5400 headers.println("struct optionaltaskdescriptor ** otdarray;");
5401 headers.println("int numfsanalysiswrappers;");
5402 headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
5404 headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
5406 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
5407 while(taskit.hasNext()) {
5408 TaskDescriptor td=(TaskDescriptor)taskit.next();
5409 headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
5414 //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
5415 int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
5416 int predicateindex = 0;
5417 //iterate through the classes concerned by the predicate
5418 Set c_vard = predicate.vardescriptors;
5419 Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
5422 for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext();) {
5423 VarDescriptor vard = (VarDescriptor)vard_it.next();
5424 TypeDescriptor typed = vard.getType();
5426 //generate for flags
5427 HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
5428 output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5430 if (fen_hashset!=null) {
5431 for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext();) {
5432 FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
5434 DNFFlag dflag=fen.getDNF();
5435 numberterms+=dflag.size();
5437 Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
5439 for(int j=0; j<dflag.size(); j++) {
5441 output.println(",");
5442 Vector term=dflag.get(j);
5445 for(int k=0; k<term.size(); k++) {
5446 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
5447 FlagDescriptor fd=dfa.getFlag();
5448 boolean negated=dfa.getNegated();
5449 int flagid=1<<((Integer)flags.get(fd)).intValue();
5454 output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
5459 output.println("};\n");
5462 TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
5463 output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5466 for(int j=0; j<tagel.numTags(); j++) {
5468 output.println(",");
5469 TempDescriptor tmp=tagel.getTemp(j);
5470 if (!slotnumber.containsKey(tmp)) {
5471 Integer slotint=new Integer(current_slot++);
5472 slotnumber.put(tmp,slotint);
5474 int slot=slotnumber.get(tmp).intValue();
5475 output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
5477 numtags = tagel.numTags();
5479 output.println("};");
5481 //store the result into a predicatemember struct
5482 output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
5483 output.println("/*type*/"+typed.getClassDesc().getId()+",");
5484 output.println("/* number of dnf terms */"+numberterms+",");
5485 output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5486 output.println("/* number of tag */"+numtags+",");
5487 output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5488 output.println("};\n");
5493 //generate an array that stores the entire predicate
5494 output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5495 for( int j = 0; j<predicateindex; j++) {
5496 if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5497 else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5499 output.println("};\n");
5500 return predicateindex;
5504 void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
5505 generateOptionalHeader(headers);
5507 output.println("#include \"optionalstruct.h\"\n\n");
5508 output.println("#include \"stdlib.h\"\n");
5510 HashSet processedcd = new HashSet();
5512 Enumeration e = safeexecution.keys();
5513 while (e.hasMoreElements()) {
5516 ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
5517 Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp); //will be used several times
5519 //Generate the struct of optionals
5520 Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
5521 numotd = c_otd.size();
5522 if(maxotd<numotd) maxotd = numotd;
5523 if( !c_otd.isEmpty() ) {
5524 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
5525 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
5527 //generate the int arrays for the predicate
5528 Predicate predicate = otd.predicate;
5529 int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
5530 TreeSet<Integer> fsset=new TreeSet<Integer>();
5531 //iterate through possible FSes corresponding to
5532 //the state when entering
5534 for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext();) {
5535 FlagState fs = (FlagState)fses.next();
5537 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
5538 FlagDescriptor flagd = (FlagDescriptor)flags.next();
5539 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
5542 fsset.add(new Integer(flagid));
5543 //tag information not needed because tag
5544 //changes are not tolerated.
5547 output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5548 boolean needcomma=false;
5549 for(Iterator<Integer> it=fsset.iterator(); it.hasNext();) {
5552 output.println(it.next());
5555 output.println("};\n");
5558 //generate optionaltaskdescriptor that actually
5559 //includes exit fses, predicate and the task
5561 output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
5562 output.println("&task_"+otd.td.getSafeSymbol()+",");
5563 output.println("/*index*/"+otd.getIndex()+",");
5564 output.println("/*number of enter flags*/"+fsset.size()+",");
5565 output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5566 output.println("/*number of members */"+predicateindex+",");
5567 output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5568 output.println("};\n");
5572 // if there are no optionals, there is no need to build the rest of the struct
5574 output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
5575 c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
5576 if( !c_otd.isEmpty() ) {
5577 boolean needcomma=false;
5578 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
5579 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
5581 output.println(",");
5583 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5586 output.println("};\n");
5588 //get all the possible flagstates reachable by an object
5589 Hashtable hashtbtemp = safeexecution.get(cdtemp);
5591 TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
5592 fsts.addAll(hashtbtemp.keySet());
5593 for(Iterator fsit=fsts.iterator(); fsit.hasNext();) {
5594 FlagState fs = (FlagState)fsit.next();
5597 //get the set of OptionalTaskDescriptors corresponding
5598 HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
5599 //iterate through the OptionalTaskDescriptors and
5600 //store the pointers to the optionals struct (see on
5601 //top) into an array
5603 output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
5604 for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext();) {
5605 OptionalTaskDescriptor mm = mos.next();
5607 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
5609 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5612 output.println("};\n");
5614 //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
5617 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
5618 FlagDescriptor flagd = (FlagDescriptor)flags.next();
5619 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
5623 //process tag information
5626 boolean first = true;
5627 Enumeration tag_enum = fs.getTags();
5628 output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
5629 while(tag_enum.hasMoreElements()) {
5631 TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
5635 output.println(", ");
5636 output.println("/*tagid*/"+state.getTagId(tagd));
5638 output.println("};");
5640 Set<TaskIndex> tiset=sa.getTaskIndex(fs);
5641 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
5642 TaskIndex ti=itti.next();
5646 Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
5648 output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
5649 boolean needcomma=false;
5650 for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext();) {
5651 OptionalTaskDescriptor otd=otdit.next();
5655 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5657 output.println("};");
5659 output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
5660 output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
5661 output.print(ti.getIndex()+", ");
5662 output.print(otdset.size()+", ");
5663 output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
5664 output.println("};");
5667 tiset=sa.getTaskIndex(fs);
5668 boolean needcomma=false;
5670 output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
5671 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
5672 TaskIndex ti=itti.next();
5673 if (ti.isRuntime()) {
5680 output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
5682 output.println("};\n");
5684 //Store the result in fsanalysiswrapper
5686 output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
5687 output.println("/*flag*/"+flagid+",");
5688 output.println("/* number of tags*/"+tagcounter+",");
5689 output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
5690 output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
5691 output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
5692 output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
5693 output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
5694 output.println("};\n");
5698 //Build the array of fsanalysiswrappers
5699 output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
5700 boolean needcomma=false;
5701 for(int i = 0; i<fscounter; i++) {
5702 if (needcomma) output.print(",");
5703 output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
5706 output.println("};");
5708 //Build the classanalysiswrapper referring to the previous array
5709 output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
5710 output.println("/*type*/"+cdtemp.getId()+",");
5711 output.println("/*numotd*/"+numotd+",");
5712 output.println("otdarray"+cdtemp.getSafeSymbol()+",");
5713 output.println("/* number of fsanalysiswrappers */"+fscounter+",");
5714 output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
5715 processedcd.add(cdtemp);
5718 //build an array containing every classes for which code has been build
5719 output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
5720 for(int i=0; i<state.numClasses(); i++) {
5721 ClassDescriptor cn=cdarray[i];
5724 if ((cn != null) && (processedcd.contains(cn)))
5725 output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
5727 output.print("NULL");
5729 output.println("};");
5731 output.println("#define MAXOTD "+maxotd);
5732 headers.println("#endif");
5735 public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
5736 Relation r=new Relation();
5737 for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext();) {
5738 OptionalTaskDescriptor otd=otdit.next();
5739 TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
5743 LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
5744 for(Iterator it=r.keySet().iterator(); it.hasNext();) {
5745 Set s=r.get(it.next());
5746 for(Iterator it2=s.iterator(); it2.hasNext();) {
5747 OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
5755 protected void outputTransCode(PrintWriter output) {
5758 private int calculateSizeOfSESEParamList(FlatSESEEnterNode fsen){
5760 Set<TempDescriptor> tdSet=new HashSet<TempDescriptor>();
5762 for (Iterator iterator = fsen.getInVarSet().iterator(); iterator.hasNext();) {
5763 TempDescriptor tempDescriptor = (TempDescriptor) iterator.next();
5764 if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()){
5765 tdSet.add(tempDescriptor);
5769 for (Iterator iterator = fsen.getOutVarSet().iterator(); iterator.hasNext();) {
5770 TempDescriptor tempDescriptor = (TempDescriptor) iterator.next();
5771 if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()){
5772 tdSet.add(tempDescriptor);
5776 return tdSet.size();
5779 private String calculateSizeOfSESEParamSize(FlatSESEEnterNode fsen){
5780 HashMap <String,Integer> map=new HashMap();
5781 HashSet <TempDescriptor> processed=new HashSet<TempDescriptor>();
5784 // space for all in and out set primitives
5785 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
5786 inSetAndOutSet.addAll( fsen.getInVarSet() );
5787 inSetAndOutSet.addAll( fsen.getOutVarSet() );
5789 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
5791 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
5792 while( itr.hasNext() ) {
5793 TempDescriptor temp = itr.next();
5794 TypeDescriptor type = temp.getType();
5795 if( !type.isPtr() ) {
5796 inSetAndOutSetPrims.add( temp );
5800 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
5801 while( itrPrims.hasNext() ) {
5802 TempDescriptor temp = itrPrims.next();
5803 TypeDescriptor type = temp.getType();
5804 if(type.isPrimitive()){
5805 Integer count=map.get(type.getSymbol());
5807 count=new Integer(1);
5808 map.put(type.getSymbol(), count);
5810 map.put(type.getSymbol(), new Integer(count.intValue()+1));
5815 Set<String> keySet=map.keySet();
5816 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
5817 String key = (String) iterator.next();
5818 rtr+="+sizeof("+key+")*"+map.get(key);