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());
278 } catch (FileNotFoundException e) {
279 System.out.println("Runtime Conflict Resolver could not create output file.");
283 while(seseit.hasNext()){
284 FlatSESEEnterNode fsen = seseit.next();
285 initializeSESE( fsen );
287 //this code will culminate all conflicts into one master hashtable.
288 if(state.RCR && rcr != null) {
289 Analysis.OoOJava.ConflictGraph conflictGraph;
290 Hashtable<Taint, Set<Effect>> conflicts;
292 System.out.println("-------");
293 System.out.println(fsen);
294 System.out.println(fsen.getIsCallerSESEplaceholder());
295 System.out.println(fsen.getParent());
297 if (fsen.getParent()!=null) {
298 conflictGraph = oooa.getConflictGraph(fsen.getParent());
299 System.out.println("CG="+conflictGraph);
300 if (conflictGraph!=null)
301 System.out.println("Conflicts="+conflictGraph.getConflictEffectSet(fsen));
304 if(!fsen.getIsCallerSESEplaceholder() && fsen.getParent()!=null &&
305 (conflictGraph = oooa.getConflictGraph(fsen.getParent())) != null &&
306 (conflicts = conflictGraph.getConflictEffectSet(fsen)) != null) {
307 FlatMethod fm=fsen.getfmEnclosing();
308 ReachGraph rg=oooa.getDisjointAnalysis().getReachGraph(fm.getMethod());
310 rg.writeGraph("RCR_RG_SESE_DEBUG");
312 rcr.addToTraverseToDoList(fsen, rg, conflicts);
318 /* Build the actual methods */
319 outputMethods(outmethod);
321 // Output function prototypes and structures for SESE's and code
322 if( state.MLP || state.OOOJAVA ) {
324 // spit out a global to inform all worker threads with
325 // the maximum size is for any task record
326 outmethod.println("int "+maxTaskRecSizeStr+" = 0;");
328 // used to differentiate, during code generation, whether we are
329 // passing over SESE body code, or non-SESE code
332 // first generate code for each sese's internals
333 Iterator<FlatSESEEnterNode> seseit;
335 seseit=mlpa.getAllSESEs().iterator();
337 seseit=oooa.getAllSESEs().iterator();
340 while(seseit.hasNext()) {
341 FlatSESEEnterNode fsen = seseit.next();
342 generateMethodSESE(fsen, null, outstructs, outmethodheader, outmethod);
345 // then write the invokeSESE switch to decouple scheduler
346 // from having to do unique details of sese invocation
347 generateSESEinvocationMethod(outmethodheader, outmethod);
351 /* Output code for tasks */
352 outputTaskCode(outtaskdefs, outmethod);
354 /* Record maximum number of task parameters */
355 outstructs.println("#define MAXTASKPARAMS "+maxtaskparams);
356 } else if (state.main!=null) {
357 /* Generate main method */
358 outputMainMethod(outmethod);
361 /* Generate information for task with optional parameters */
362 if (state.TASK&&state.OPTIONAL) {
363 generateOptionalArrays(outoptionalarrays, optionalheaders, state.getAnalysisResult(), state.getOptionalTaskDescriptors());
364 outoptionalarrays.close();
367 /* Output structure definitions for repair tool */
368 if (state.structfile!=null) {
369 buildRepairStructs(outrepairstructs);
370 outrepairstructs.close();
374 outmethodheader.println("#endif");
375 outmethodheader.close();
377 outstructs.println("#endif");
381 System.out.println("Runtime Conflict Resolver Done.");
386 /* This code just generates the main C method for java programs.
387 * The main C method packs up the arguments into a string array
388 * and passes it to the java main method. */
390 protected void outputMainMethod(PrintWriter outmethod) {
391 outmethod.println("int main(int argc, const char *argv[]) {");
392 outmethod.println(" int i;");
394 if (state.MLP || state.OOOJAVA) {
396 // do a calculation to determine which task record
397 // is the largest, store that as a global value for
398 // allocating records
399 Iterator<FlatSESEEnterNode> seseit;
401 seseit=mlpa.getAllSESEs().iterator();
403 seseit=oooa.getAllSESEs().iterator();
405 while(seseit.hasNext()){
406 FlatSESEEnterNode fsen = seseit.next();
407 outmethod.println("if( sizeof( "+fsen.getSESErecordName()+
408 " ) > "+maxTaskRecSizeStr+
409 " ) { "+maxTaskRecSizeStr+
410 " = sizeof( "+fsen.getSESErecordName()+
414 outmethod.println(" runningSESE = NULL;");
416 outmethod.println(" workScheduleInit( "+state.MLP_NUMCORES+", invokeSESEmethod );");
418 //initializes data structures needed for the RCR traverser
419 if(state.RCR && rcr != null) {
420 outmethod.println(" initializeStructsRCR();");
425 if (state.DSMRECOVERYSTATS) {
426 outmethod.println("#ifdef RECOVERYSTATS \n");
427 outmethod.println("handle();\n");
428 outmethod.println("#endif\n");
430 outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n");
431 outmethod.println("handle();\n");
432 outmethod.println("#endif\n");
436 if (state.THREAD||state.DSM||state.SINGLETM) {
437 outmethod.println("initializethreads();");
440 outmethod.println("if (dstmStartup(argv[1])) {");
441 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
442 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-2);");
444 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-2);");
447 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
448 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1);");
450 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1);");
454 outmethod.println(" for(i=2;i<argc;i++) {");
456 outmethod.println(" for(i=1;i<argc;i++) {");
457 outmethod.println(" int length=strlen(argv[i]);");
458 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
459 outmethod.println(" struct ___String___ *newstring=NewString(NULL, argv[i], length);");
461 outmethod.println(" struct ___String___ *newstring=NewString(argv[i], length);");
464 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-2]=newstring;");
466 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-1]=newstring;");
467 outmethod.println(" }");
469 MethodDescriptor md=typeutil.getMain();
470 ClassDescriptor cd=typeutil.getMainClass();
472 outmethod.println(" {");
473 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
474 if (state.DSM||state.SINGLETM) {
475 outmethod.print(" struct "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
477 outmethod.print(" struct "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
478 outmethod.println("1, NULL,"+"stringarray};");
479 if (state.DSM||state.SINGLETM)
480 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
482 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
484 if (state.DSM||state.SINGLETM)
485 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
487 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
489 outmethod.println(" }");
492 outmethod.println("}");
495 if (state.THREAD||state.DSM||state.SINGLETM) {
496 outmethod.println("pthread_mutex_lock(&gclistlock);");
497 outmethod.println("threadcount--;");
498 outmethod.println("pthread_cond_signal(&gccond);");
499 outmethod.println("pthread_mutex_unlock(&gclistlock);");
502 if (state.DSM||state.SINGLETM) {
503 //outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n");
504 outmethod.println("#if defined(TRANSSTATS) \n");
505 outmethod.println("printf(\"****** Transaction Stats ******\\n\");");
506 outmethod.println("printf(\"numTransCommit= %d\\n\", numTransCommit);");
507 outmethod.println("printf(\"numTransAbort= %d\\n\", numTransAbort);");
508 outmethod.println("printf(\"nSoftAbort= %d\\n\", nSoftAbort);");
510 outmethod.println("printf(\"nchashSearch= %d\\n\", nchashSearch);");
511 outmethod.println("printf(\"nmhashSearch= %d\\n\", nmhashSearch);");
512 outmethod.println("printf(\"nprehashSearch= %d\\n\", nprehashSearch);");
513 outmethod.println("printf(\"ndirtyCacheObj= %d\\n\", ndirtyCacheObj);");
514 outmethod.println("printf(\"nRemoteReadSend= %d\\n\", nRemoteSend);");
515 outmethod.println("printf(\"bytesSent= %d\\n\", bytesSent);");
516 outmethod.println("printf(\"bytesRecv= %d\\n\", bytesRecv);");
517 outmethod.println("printf(\"totalObjSize= %d\\n\", totalObjSize);");
518 outmethod.println("printf(\"sendRemoteReq= %d\\n\", sendRemoteReq);");
519 outmethod.println("printf(\"getResponse= %d\\n\", getResponse);");
520 } else if (state.SINGLETM) {
521 outmethod.println("printf(\"nSoftAbortAbort= %d\\n\", nSoftAbortAbort);");
522 outmethod.println("printf(\"nSoftAbortCommit= %d\\n\", nSoftAbortCommit);");
523 outmethod.println("#ifdef STMSTATS\n");
524 outmethod.println("for(i=0; i<TOTALNUMCLASSANDARRAY; i++) {\n");
525 outmethod.println(" printf(\"typesCausingAbort[%2d] numaccess= %5d numabort= %3d\\n\", i, typesCausingAbort[i].numaccess, typesCausingAbort[i].numabort);\n");
526 outmethod.println("}\n");
527 outmethod.println("#endif\n");
528 outmethod.println("fflush(stdout);");
530 outmethod.println("#endif\n");
533 if (state.EVENTMONITOR) {
534 outmethod.println("dumpdata();");
537 if (state.THREAD||state.SINGLETM)
538 outmethod.println("pthread_exit(NULL);");
540 if (state.MLP || state.OOOJAVA ) {
541 outmethod.println(" workScheduleBegin();");
544 outmethod.println("}");
547 /* This method outputs code for each task. */
549 private void outputTaskCode(PrintWriter outtaskdefs, PrintWriter outmethod) {
550 /* Compile task based program */
551 outtaskdefs.println("#include \"task.h\"");
552 outtaskdefs.println("#include \"methodheaders.h\"");
553 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
554 while(taskit.hasNext()) {
555 TaskDescriptor td=(TaskDescriptor)taskit.next();
556 FlatMethod fm=state.getMethodFlat(td);
557 generateFlatMethod(fm, null, outmethod);
558 generateTaskDescriptor(outtaskdefs, fm, td);
561 //Output task descriptors
562 taskit=state.getTaskSymbolTable().getDescriptorsIterator();
563 outtaskdefs.println("struct taskdescriptor * taskarray[]= {");
565 while(taskit.hasNext()) {
566 TaskDescriptor td=(TaskDescriptor)taskit.next();
570 outtaskdefs.println(",");
571 outtaskdefs.print("&task_"+td.getSafeSymbol());
573 outtaskdefs.println("};");
575 outtaskdefs.println("int numtasks="+state.getTaskSymbolTable().getValueSet().size()+";");
578 /* This method outputs most of the methods.c file. This includes
579 * some standard includes and then an array with the sizes of
580 * objets and array that stores supertype and then the code for
581 * the Java methods.. */
583 protected void outputMethods(PrintWriter outmethod) {
584 outmethod.println("#include \"methodheaders.h\"");
585 outmethod.println("#include \"virtualtable.h\"");
586 outmethod.println("#include \"runtime.h\"");
588 // always include: compiler directives will leave out
589 // instrumentation when option is not set
590 outmethod.println("#include \"coreprof/coreprof.h\"");
593 outmethod.println("#include \"sandboxdefs.c\"");
596 outmethod.println("#include \"addPrefetchEnhance.h\"");
597 outmethod.println("#include \"localobjects.h\"");
599 if (state.FASTCHECK) {
600 outmethod.println("#include \"localobjects.h\"");
602 if(state.MULTICORE) {
604 outmethod.println("#include \"task.h\"");
606 outmethod.println("#include \"multicoreruntime.h\"");
607 outmethod.println("#include \"runtime_arch.h\"");
609 if (state.THREAD||state.DSM||state.SINGLETM)
610 outmethod.println("#include <thread.h>");
611 if (state.main!=null) {
612 outmethod.println("#include <string.h>");
614 if (state.CONSCHECK) {
615 outmethod.println("#include \"checkers.h\"");
617 if (state.MLP || state.OOOJAVA ) {
618 outmethod.println("#include <stdlib.h>");
619 outmethod.println("#include <stdio.h>");
620 outmethod.println("#include \"mlp_runtime.h\"");
621 outmethod.println("#include \"psemaphore.h\"");
623 if( state.RCR && rcr != null) {
624 outmethod.println("#include \"RuntimeConflictResolver.h\"");
628 //Store the sizes of classes & array elements
629 generateSizeArray(outmethod);
631 //Store table of supertypes
632 generateSuperTypeTable(outmethod);
634 //Store the layout of classes
635 generateLayoutStructs(outmethod);
637 /* Generate code for methods */
638 if (state.DSM||state.SINGLETM) {
639 for(Iterator<LocalityBinding> lbit=locality.getLocalityBindings().iterator(); lbit.hasNext();) {
640 LocalityBinding lb=lbit.next();
641 MethodDescriptor md=lb.getMethod();
642 FlatMethod fm=state.getMethodFlat(md);
644 if (!md.getModifiers().isNative()) {
645 generateFlatMethod(fm, lb, outmethod);
646 //System.out.println("fm= " + fm + " md= " + md);
650 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
651 while(classit.hasNext()) {
652 ClassDescriptor cn=(ClassDescriptor)classit.next();
653 Iterator methodit=cn.getMethods();
654 while(methodit.hasNext()) {
655 /* Classify parameters */
656 MethodDescriptor md=(MethodDescriptor)methodit.next();
657 FlatMethod fm=state.getMethodFlat(md);
658 if (!md.getModifiers().isNative()) {
659 generateFlatMethod(fm, null, outmethod);
666 protected void outputStructs(PrintWriter outstructs) {
667 outstructs.println("#ifndef STRUCTDEFS_H");
668 outstructs.println("#define STRUCTDEFS_H");
669 outstructs.println("#include \"classdefs.h\"");
670 outstructs.println("#ifndef INTPTR");
671 outstructs.println("#ifdef BIT64");
672 outstructs.println("#define INTPTR long");
673 outstructs.println("#else");
674 outstructs.println("#define INTPTR int");
675 outstructs.println("#endif");
676 outstructs.println("#endif");
677 if( state.MLP || state.OOOJAVA ) {
678 outstructs.println("#include \"mlp_runtime.h\"");
679 outstructs.println("#include \"psemaphore.h\"");
682 /* Output #defines that the runtime uses to determine type
683 * numbers for various objects it needs */
684 outstructs.println("#define MAXCOUNT "+maxcount);
685 if (state.DSM||state.SINGLETM) {
686 LocalityBinding lbrun=new LocalityBinding(typeutil.getRun(), false);
688 lbrun.setGlobalThis(LocalityAnalysis.GLOBAL);
690 else if (state.SINGLETM) {
691 lbrun.setGlobalThis(LocalityAnalysis.NORMAL);
693 outstructs.println("#define RUNMETHOD "+virtualcalls.getLocalityNumber(lbrun));
697 LocalityBinding lbexecute = new LocalityBinding(typeutil.getExecute(), false);
699 lbexecute.setGlobalThis(LocalityAnalysis.GLOBAL);
700 else if( state.SINGLETM)
701 lbexecute.setGlobalThis(LocalityAnalysis.NORMAL);
702 outstructs.println("#define EXECUTEMETHOD " + virtualcalls.getLocalityNumber(lbexecute));
705 outstructs.println("#define STRINGARRAYTYPE "+
706 (state.getArrayNumber(
707 (new TypeDescriptor(typeutil.getClass(TypeUtil.StringClass))).makeArray(state))+state.numClasses()));
709 outstructs.println("#define OBJECTARRAYTYPE "+
710 (state.getArrayNumber(
711 (new TypeDescriptor(typeutil.getClass(TypeUtil.ObjectClass))).makeArray(state))+state.numClasses()));
714 outstructs.println("#define STRINGTYPE "+typeutil.getClass(TypeUtil.StringClass).getId());
715 outstructs.println("#define CHARARRAYTYPE "+
716 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.CHAR)).makeArray(state))+state.numClasses()));
718 outstructs.println("#define BYTEARRAYTYPE "+
719 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state))+state.numClasses()));
721 outstructs.println("#define BYTEARRAYARRAYTYPE "+
722 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state).makeArray(state))+state.numClasses()));
724 outstructs.println("#define NUMCLASSES "+state.numClasses());
725 int totalClassSize = state.numClasses() + state.numArrays();
726 outstructs.println("#define TOTALNUMCLASSANDARRAY "+ totalClassSize);
728 outstructs.println("#define STARTUPTYPE "+typeutil.getClass(TypeUtil.StartupClass).getId());
729 outstructs.println("#define TAGTYPE "+typeutil.getClass(TypeUtil.TagClass).getId());
730 outstructs.println("#define TAGARRAYTYPE "+
731 (state.getArrayNumber(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)).makeArray(state))+state.numClasses()));
735 protected void outputClassDeclarations(PrintWriter outclassdefs) {
736 if (state.THREAD||state.DSM||state.SINGLETM)
737 outclassdefs.println("#include <pthread.h>");
738 outclassdefs.println("#ifndef INTPTR");
739 outclassdefs.println("#ifdef BIT64");
740 outclassdefs.println("#define INTPTR long");
741 outclassdefs.println("#else");
742 outclassdefs.println("#define INTPTR int");
743 outclassdefs.println("#endif");
744 outclassdefs.println("#endif");
746 outclassdefs.println("#include \"optionalstruct.h\"");
747 outclassdefs.println("struct "+arraytype+";");
748 /* Start by declaring all structs */
749 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
750 while(it.hasNext()) {
751 ClassDescriptor cn=(ClassDescriptor)it.next();
752 outclassdefs.println("struct "+cn.getSafeSymbol()+";");
754 outclassdefs.println("");
755 //Print out definition for array type
756 outclassdefs.println("struct "+arraytype+" {");
757 outclassdefs.println(" int type;");
758 if(state.MLP || state.OOOJAVA ){
759 outclassdefs.println(" int oid;");
760 outclassdefs.println(" int allocsite;");
762 if (state.EVENTMONITOR) {
763 outclassdefs.println(" int objuid;");
766 outclassdefs.println(" pthread_t tid;");
767 outclassdefs.println(" void * lockentry;");
768 outclassdefs.println(" int lockcount;");
771 outclassdefs.println(" int mutex;");
772 outclassdefs.println(" int objlock;");
773 if(state.MULTICOREGC) {
774 outclassdefs.println(" int marked;");
778 outclassdefs.println(" int flag;");
779 if(!state.MULTICORE) {
780 outclassdefs.println(" void * flagptr;");
782 outclassdefs.println(" int version;");
783 outclassdefs.println(" int * lock;"); // lock entry for this obj
784 outclassdefs.println(" int mutex;");
785 outclassdefs.println(" int lockcount;");
786 if(state.MULTICOREGC) {
787 outclassdefs.println(" int marked;");
791 outclassdefs.println(" int numfses;");
792 outclassdefs.println(" int * fses;");
795 printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs);
797 if (state.STMARRAY) {
798 outclassdefs.println(" int lowindex;");
799 outclassdefs.println(" int highindex;");
802 outclassdefs.println(" int paddingforarray;");
803 if (state.DUALVIEW) {
804 outclassdefs.println(" int arrayversion;");
807 outclassdefs.println(" int ___length___;");
808 outclassdefs.println("};\n");
809 outclassdefs.println("extern int classsize[];");
810 outclassdefs.println("extern int hasflags[];");
811 outclassdefs.println("extern unsigned INTPTR * pointerarray[];");
812 outclassdefs.println("extern int supertypes[];");
815 /** Prints out definitions for generic task structures */
817 private void outputTaskTypes(PrintWriter outtask) {
818 outtask.println("#ifndef _TASK_H");
819 outtask.println("#define _TASK_H");
820 outtask.println("struct parameterdescriptor {");
821 outtask.println("int type;");
822 outtask.println("int numberterms;");
823 outtask.println("int *intarray;");
824 outtask.println("void * queue;");
825 outtask.println("int numbertags;");
826 outtask.println("int *tagarray;");
827 outtask.println("};");
829 outtask.println("struct taskdescriptor {");
830 outtask.println("void * taskptr;");
831 outtask.println("int numParameters;");
832 outtask.println(" int numTotal;");
833 outtask.println("struct parameterdescriptor **descriptorarray;");
834 outtask.println("char * name;");
835 outtask.println("};");
836 outtask.println("extern struct taskdescriptor * taskarray[];");
837 outtask.println("extern numtasks;");
838 outtask.println("#endif");
842 private void buildRepairStructs(PrintWriter outrepairstructs) {
843 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
844 while(classit.hasNext()) {
845 ClassDescriptor cn=(ClassDescriptor)classit.next();
846 outrepairstructs.println("structure "+cn.getSymbol()+" {");
847 outrepairstructs.println(" int __type__;");
849 outrepairstructs.println(" int __flag__;");
850 if(!state.MULTICORE) {
851 outrepairstructs.println(" int __flagptr__;");
854 printRepairStruct(cn, outrepairstructs);
855 outrepairstructs.println("}\n");
858 for(int i=0; i<state.numArrays(); i++) {
859 TypeDescriptor tdarray=arraytable[i];
860 TypeDescriptor tdelement=tdarray.dereference();
861 outrepairstructs.println("structure "+arraytype+"_"+state.getArrayNumber(tdarray)+" {");
862 outrepairstructs.println(" int __type__;");
863 printRepairStruct(typeutil.getClass(TypeUtil.ObjectClass), outrepairstructs);
864 outrepairstructs.println(" int length;");
866 // Need to add support to repair tool for this
867 if (tdelement.isClass()||tdelement.isArray())
868 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" * elem[this.length];");
870 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" elem[this.length];");
872 outrepairstructs.println("}\n");
876 private void printRepairStruct(ClassDescriptor cn, PrintWriter output) {
877 ClassDescriptor sp=cn.getSuperDesc();
879 printRepairStruct(sp, output);
881 Vector fields=(Vector)fieldorder.get(cn);
883 for(int i=0; i<fields.size(); i++) {
884 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
885 if (fd.getType().isArray()) {
886 output.println(" "+arraytype+"_"+ state.getArrayNumber(fd.getType()) +" * "+fd.getSymbol()+";");
887 } else if (fd.getType().isClass())
888 output.println(" "+fd.getType().getRepairSymbol()+" * "+fd.getSymbol()+";");
889 else if (fd.getType().isFloat())
890 output.println(" int "+fd.getSymbol()+"; /* really float */");
892 output.println(" "+fd.getType().getRepairSymbol()+" "+fd.getSymbol()+";");
896 /** This method outputs TaskDescriptor information */
897 private void generateTaskDescriptor(PrintWriter output, FlatMethod fm, TaskDescriptor task) {
898 for (int i=0; i<task.numParameters(); i++) {
899 VarDescriptor param_var=task.getParameter(i);
900 TypeDescriptor param_type=task.getParamType(i);
901 FlagExpressionNode param_flag=task.getFlag(param_var);
902 TagExpressionList param_tag=task.getTag(param_var);
905 if (param_flag==null) {
906 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
907 output.println("0x0, 0x0 };");
910 DNFFlag dflag=param_flag.getDNF();
911 dnfterms=dflag.size();
913 Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
914 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
915 for(int j=0; j<dflag.size(); j++) {
918 Vector term=dflag.get(j);
921 for(int k=0; k<term.size(); k++) {
922 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
923 FlagDescriptor fd=dfa.getFlag();
924 boolean negated=dfa.getNegated();
925 int flagid=1<<((Integer)flags.get(fd)).intValue();
930 output.print("0x"+Integer.toHexString(andmask)+", 0x"+Integer.toHexString(checkmask));
932 output.println("};");
935 output.println("int parametertag_"+i+"_"+task.getSafeSymbol()+"[]={");
936 //BUG...added next line to fix, test with any task program
938 for(int j=0; j<param_tag.numTags(); j++) {
941 /* for each tag we need */
942 /* which slot it is */
943 /* what type it is */
944 TagVarDescriptor tvd=(TagVarDescriptor)task.getParameterTable().get(param_tag.getName(j));
945 TempDescriptor tmp=param_tag.getTemp(j);
946 int slot=fm.getTagInt(tmp);
947 output.println(slot+", "+state.getTagId(tvd.getTag()));
949 output.println("};");
951 output.println("struct parameterdescriptor parameter_"+i+"_"+task.getSafeSymbol()+"={");
952 output.println("/* type */"+param_type.getClassDesc().getId()+",");
953 output.println("/* number of DNF terms */"+dnfterms+",");
954 output.println("parameterdnf_"+i+"_"+task.getSafeSymbol()+",");
955 output.println("0,");
956 //BUG, added next line to fix and else statement...test
957 //with any task program
959 output.println("/* number of tags */"+param_tag.numTags()+",");
961 output.println("/* number of tags */ 0,");
962 output.println("parametertag_"+i+"_"+task.getSafeSymbol());
963 output.println("};");
967 output.println("struct parameterdescriptor * parameterdescriptors_"+task.getSafeSymbol()+"[] = {");
968 for (int i=0; i<task.numParameters(); i++) {
971 output.print("¶meter_"+i+"_"+task.getSafeSymbol());
973 output.println("};");
975 output.println("struct taskdescriptor task_"+task.getSafeSymbol()+"={");
976 output.println("&"+task.getSafeSymbol()+",");
977 output.println("/* number of parameters */" +task.numParameters() + ",");
978 int numtotal=task.numParameters()+fm.numTags();
979 output.println("/* number total parameters */" +numtotal + ",");
980 output.println("parameterdescriptors_"+task.getSafeSymbol()+",");
981 output.println("\""+task.getSymbol()+"\"");
982 output.println("};");
986 /** The buildVirtualTables method outputs the virtual dispatch
987 * tables for methods. */
989 protected void buildVirtualTables(PrintWriter outvirtual) {
990 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
991 while(classit.hasNext()) {
992 ClassDescriptor cd=(ClassDescriptor)classit.next();
993 if (virtualcalls.getMethodCount(cd)>maxcount)
994 maxcount=virtualcalls.getMethodCount(cd);
996 MethodDescriptor[][] virtualtable=null;
997 LocalityBinding[][] lbvirtualtable=null;
998 if (state.DSM||state.SINGLETM)
999 lbvirtualtable=new LocalityBinding[state.numClasses()+state.numArrays()][maxcount];
1001 virtualtable=new MethodDescriptor[state.numClasses()+state.numArrays()][maxcount];
1003 /* Fill in virtual table */
1004 classit=state.getClassSymbolTable().getDescriptorsIterator();
1005 while(classit.hasNext()) {
1006 ClassDescriptor cd=(ClassDescriptor)classit.next();
1007 if (state.DSM||state.SINGLETM)
1008 fillinRow(cd, lbvirtualtable, cd.getId());
1010 fillinRow(cd, virtualtable, cd.getId());
1013 ClassDescriptor objectcd=typeutil.getClass(TypeUtil.ObjectClass);
1014 Iterator arrayit=state.getArrayIterator();
1015 while(arrayit.hasNext()) {
1016 TypeDescriptor td=(TypeDescriptor)arrayit.next();
1017 int id=state.getArrayNumber(td);
1018 if (state.DSM||state.SINGLETM)
1019 fillinRow(objectcd, lbvirtualtable, id+state.numClasses());
1021 fillinRow(objectcd, virtualtable, id+state.numClasses());
1024 outvirtual.print("void * virtualtable[]={");
1025 boolean needcomma=false;
1026 for(int i=0; i<state.numClasses()+state.numArrays(); i++) {
1027 for(int j=0; j<maxcount; j++) {
1029 outvirtual.print(", ");
1030 if ((state.DSM||state.SINGLETM)&&lbvirtualtable[i][j]!=null) {
1031 LocalityBinding lb=lbvirtualtable[i][j];
1032 MethodDescriptor md=lb.getMethod();
1033 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
1034 } else if (!(state.DSM||state.SINGLETM)&&virtualtable[i][j]!=null) {
1035 MethodDescriptor md=virtualtable[i][j];
1036 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
1038 outvirtual.print("0");
1042 outvirtual.println("");
1044 outvirtual.println("};");
1048 private void fillinRow(ClassDescriptor cd, MethodDescriptor[][] virtualtable, int rownum) {
1049 /* Get inherited methods */
1050 if (cd.getSuperDesc()!=null)
1051 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
1052 /* Override them with our methods */
1053 for(Iterator it=cd.getMethods(); it.hasNext();) {
1054 MethodDescriptor md=(MethodDescriptor)it.next();
1055 if (md.isStatic()||md.getReturnType()==null)
1057 int methodnum=virtualcalls.getMethodNumber(md);
1058 virtualtable[rownum][methodnum]=md;
1062 private void fillinRow(ClassDescriptor cd, LocalityBinding[][] virtualtable, int rownum) {
1063 /* Get inherited methods */
1064 if (cd.getSuperDesc()!=null)
1065 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
1066 /* Override them with our methods */
1067 if (locality.getClassBindings(cd)!=null)
1068 for(Iterator<LocalityBinding> lbit=locality.getClassBindings(cd).iterator(); lbit.hasNext();) {
1069 LocalityBinding lb=lbit.next();
1070 MethodDescriptor md=lb.getMethod();
1071 //Is the method static or a constructor
1072 if (md.isStatic()||md.getReturnType()==null)
1074 int methodnum=virtualcalls.getLocalityNumber(lb);
1075 virtualtable[rownum][methodnum]=lb;
1079 /** Generate array that contains the sizes of class objects. The
1080 * object allocation functions in the runtime use this
1083 private void generateSizeArray(PrintWriter outclassdefs) {
1084 outclassdefs.print("extern struct prefetchCountStats * evalPrefetch;\n");
1085 outclassdefs.print("#ifdef TRANSSTATS \n");
1086 outclassdefs.print("extern int numTransAbort;\n");
1087 outclassdefs.print("extern int numTransCommit;\n");
1088 outclassdefs.print("extern int nSoftAbort;\n");
1090 outclassdefs.print("extern int nchashSearch;\n");
1091 outclassdefs.print("extern int nmhashSearch;\n");
1092 outclassdefs.print("extern int nprehashSearch;\n");
1093 outclassdefs.print("extern int ndirtyCacheObj;\n");
1094 outclassdefs.print("extern int nRemoteSend;\n");
1095 outclassdefs.print("extern int sendRemoteReq;\n");
1096 outclassdefs.print("extern int getResponse;\n");
1097 outclassdefs.print("extern int bytesSent;\n");
1098 outclassdefs.print("extern int bytesRecv;\n");
1099 outclassdefs.print("extern int totalObjSize;\n");
1100 outclassdefs.print("extern void handle();\n");
1101 } else if (state.SINGLETM) {
1102 outclassdefs.println("extern int nSoftAbortAbort;");
1103 outclassdefs.println("extern int nSoftAbortCommit;");
1104 outclassdefs.println("#ifdef STMSTATS\n");
1105 outclassdefs.println("extern objtypestat_t typesCausingAbort[];");
1106 outclassdefs.println("#endif\n");
1108 outclassdefs.print("#endif\n");
1110 outclassdefs.print("int numprefetchsites = " + pa.prefetchsiteid + ";\n");
1111 if(this.state.MLP || state.OOOJAVA ){
1112 outclassdefs.print("extern __thread int oid;\n");
1113 outclassdefs.print("extern int numWorkers;\n");
1116 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1117 cdarray=new ClassDescriptor[state.numClasses()];
1119 while(it.hasNext()) {
1120 ClassDescriptor cd=(ClassDescriptor)it.next();
1121 cdarray[cd.getId()]=cd;
1124 arraytable=new TypeDescriptor[state.numArrays()];
1126 Iterator arrayit=state.getArrayIterator();
1127 while(arrayit.hasNext()) {
1128 TypeDescriptor td=(TypeDescriptor)arrayit.next();
1129 int id=state.getArrayNumber(td);
1135 /* Print out types */
1136 outclassdefs.println("/* ");
1137 for(int i=0; i<state.numClasses(); i++) {
1138 ClassDescriptor cd=cdarray[i];
1140 outclassdefs.println("NULL " + i);
1142 outclassdefs.println(cd +" "+i);
1146 for(int i=0; i<state.numArrays(); i++) {
1147 TypeDescriptor arraytd=arraytable[i];
1148 outclassdefs.println(arraytd.toPrettyString() +" "+(i+state.numClasses()));
1151 outclassdefs.println("*/");
1154 outclassdefs.print("int classsize[]={");
1156 boolean needcomma=false;
1157 for(int i=0; i<state.numClasses(); i++) {
1159 outclassdefs.print(", ");
1161 outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")");
1163 outclassdefs.print("0");
1169 for(int i=0; i<state.numArrays(); i++) {
1171 outclassdefs.print(", ");
1172 TypeDescriptor tdelement=arraytable[i].dereference();
1173 if (tdelement.isArray()||tdelement.isClass())
1174 outclassdefs.print("sizeof(void *)");
1176 outclassdefs.print("sizeof("+tdelement.getSafeSymbol()+")");
1180 outclassdefs.println("};");
1182 ClassDescriptor objectclass=typeutil.getClass(TypeUtil.ObjectClass);
1184 outclassdefs.print("int typearray[]={");
1185 for(int i=0; i<state.numClasses(); i++) {
1186 ClassDescriptor cd=cdarray[i];
1187 ClassDescriptor supercd=i>0?cd.getSuperDesc():null;
1189 outclassdefs.print(", ");
1191 outclassdefs.print("-1");
1193 outclassdefs.print(supercd.getId());
1197 for(int i=0; i<state.numArrays(); i++) {
1198 TypeDescriptor arraytd=arraytable[i];
1199 ClassDescriptor arraycd=arraytd.getClassDesc();
1200 if (arraycd==null) {
1202 outclassdefs.print(", ");
1203 outclassdefs.print(objectclass.getId());
1207 ClassDescriptor cd=arraycd.getSuperDesc();
1210 TypeDescriptor supertd=new TypeDescriptor(cd);
1211 supertd.setArrayCount(arraytd.getArrayCount());
1212 type=state.getArrayNumber(supertd);
1214 type+=state.numClasses();
1217 cd=cd.getSuperDesc();
1220 outclassdefs.print(", ");
1221 outclassdefs.print(type);
1225 outclassdefs.println("};");
1230 outclassdefs.print("int typearray2[]={");
1231 for(int i=0; i<state.numArrays(); i++) {
1232 TypeDescriptor arraytd=arraytable[i];
1233 ClassDescriptor arraycd=arraytd.getClassDesc();
1234 if (arraycd==null) {
1236 outclassdefs.print(", ");
1237 outclassdefs.print("-1");
1241 ClassDescriptor cd=arraycd.getSuperDesc();
1242 int level=arraytd.getArrayCount()-1;
1244 for(; level>0; level--) {
1245 TypeDescriptor supertd=new TypeDescriptor(objectclass);
1246 supertd.setArrayCount(level);
1247 type=state.getArrayNumber(supertd);
1249 type+=state.numClasses();
1254 outclassdefs.print(", ");
1255 outclassdefs.print(type);
1259 outclassdefs.println("};");
1262 /** Constructs params and temp objects for each method or task.
1263 * These objects tell the compiler which temps need to be
1266 protected void generateTempStructs(FlatMethod fm, LocalityBinding lb) {
1267 MethodDescriptor md=fm.getMethod();
1268 TaskDescriptor task=fm.getTask();
1269 Set<TempDescriptor> saveset=lb!=null ? locality.getTempSet(lb) : null;
1270 ParamsObject objectparams=md!=null ? new ParamsObject(md,tag++) : new ParamsObject(task, tag++);
1272 paramstable.put(lb, objectparams);
1273 backuptable.put(lb, new Hashtable<TempDescriptor, TempDescriptor>());
1274 } else if (md!=null)
1275 paramstable.put(md, objectparams);
1277 paramstable.put(task, objectparams);
1279 for(int i=0; i<fm.numParameters(); i++) {
1280 TempDescriptor temp=fm.getParameter(i);
1281 TypeDescriptor type=temp.getType();
1282 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1283 objectparams.addPtr(temp);
1285 objectparams.addPrim(temp);
1286 if(lb!=null&&saveset.contains(temp)) {
1287 backuptable.get(lb).put(temp, temp.createNew());
1291 for(int i=0; i<fm.numTags(); i++) {
1292 TempDescriptor temp=fm.getTag(i);
1293 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1294 objectparams.addPtr(temp);
1296 objectparams.addPrim(temp);
1299 TempObject objecttemps=md!=null ? new TempObject(objectparams,md,tag++) : new TempObject(objectparams, task, tag++);
1301 tempstable.put(lb, objecttemps);
1303 tempstable.put(md, objecttemps);
1305 tempstable.put(task, objecttemps);
1307 for(Iterator nodeit=fm.getNodeSet().iterator(); nodeit.hasNext();) {
1308 FlatNode fn=(FlatNode)nodeit.next();
1309 TempDescriptor[] writes=fn.writesTemps();
1310 for(int i=0; i<writes.length; i++) {
1311 TempDescriptor temp=writes[i];
1312 TypeDescriptor type=temp.getType();
1313 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1314 objecttemps.addPtr(temp);
1316 objecttemps.addPrim(temp);
1317 if(lb!=null&&saveset.contains(temp)&&
1318 !backuptable.get(lb).containsKey(temp))
1319 backuptable.get(lb).put(temp, temp.createNew());
1323 /* Create backup temps */
1325 for(Iterator<TempDescriptor> tmpit=backuptable.get(lb).values().iterator(); tmpit.hasNext();) {
1326 TempDescriptor tmp=tmpit.next();
1327 TypeDescriptor type=tmp.getType();
1328 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1329 objecttemps.addPtr(tmp);
1331 objecttemps.addPrim(tmp);
1333 /* Create temp to hold revert table */
1334 if (state.DSM&&(lb.getHasAtomic()||lb.isAtomic())) {
1335 TempDescriptor reverttmp=new TempDescriptor("revertlist", typeutil.getClass(TypeUtil.ObjectClass));
1336 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1337 objecttemps.addPtr(reverttmp);
1339 objecttemps.addPrim(reverttmp);
1340 reverttable.put(lb, reverttmp);
1345 /** This method outputs the following information about classes
1347 * (1) For classes, what are the locations of pointers.
1348 * (2) For arrays, does the array contain pointers or primitives.
1349 * (3) For classes, does the class contain flags.
1352 private void generateLayoutStructs(PrintWriter output) {
1353 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1354 while(it.hasNext()) {
1355 ClassDescriptor cn=(ClassDescriptor)it.next();
1356 output.println("unsigned INTPTR "+cn.getSafeSymbol()+"_pointers[]={");
1357 Iterator allit=cn.getFieldTable().getAllDescriptorsIterator();
1359 while(allit.hasNext()) {
1360 FieldDescriptor fd=(FieldDescriptor)allit.next();
1361 TypeDescriptor type=fd.getType();
1362 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1367 output.print(count);
1368 allit=cn.getFieldTable().getAllDescriptorsIterator();
1369 while(allit.hasNext()) {
1370 FieldDescriptor fd=(FieldDescriptor)allit.next();
1371 TypeDescriptor type=fd.getType();
1372 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1375 output.println(",");
1376 output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+fd.getSafeSymbol()+"))");
1379 output.println("};");
1381 output.println("unsigned INTPTR * pointerarray[]={");
1382 boolean needcomma=false;
1383 for(int i=0; i<state.numClasses(); i++) {
1384 ClassDescriptor cn=cdarray[i];
1386 output.println(",");
1389 output.print(cn.getSafeSymbol()+"_pointers");
1391 output.print("NULL");
1395 for(int i=0; i<state.numArrays(); i++) {
1397 output.println(", ");
1398 TypeDescriptor tdelement=arraytable[i].dereference();
1399 if (tdelement.isArray()||tdelement.isClass())
1400 output.print("((unsigned INTPTR *)1)");
1406 output.println("};");
1408 output.println("int hasflags[]={");
1409 for(int i=0; i<state.numClasses(); i++) {
1410 ClassDescriptor cn=cdarray[i];
1412 output.println(", ");
1414 if ((cn != null) && (cn.hasFlags()))
1419 output.println("};");
1422 /** Print out table to give us supertypes */
1423 private void generateSuperTypeTable(PrintWriter output) {
1424 output.println("int supertypes[]={");
1425 boolean needcomma=false;
1426 for(int i=0; i<state.numClasses(); i++) {
1427 ClassDescriptor cn=cdarray[i];
1429 output.println(",");
1431 if ((cn != null) && (cn.getSuperDesc()!=null)) {
1432 ClassDescriptor cdsuper=cn.getSuperDesc();
1433 output.print(cdsuper.getId());
1437 output.println("};");
1440 /** Force consistent field ordering between inherited classes. */
1442 private void printClassStruct(ClassDescriptor cn, PrintWriter classdefout) {
1444 ClassDescriptor sp=cn.getSuperDesc();
1446 printClassStruct(sp, classdefout);
1448 if (!fieldorder.containsKey(cn)) {
1449 Vector fields=new Vector();
1450 fieldorder.put(cn,fields);
1451 Vector fieldvec=cn.getFieldVec();
1452 for(int i=0;i<fieldvec.size();i++) {
1453 FieldDescriptor fd=(FieldDescriptor)fieldvec.get(i);
1454 if ((sp==null||!sp.getFieldTable().contains(fd.getSymbol())))
1458 Vector fields=(Vector)fieldorder.get(cn);
1460 for(int i=0; i<fields.size(); i++) {
1461 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
1462 if (fd.getType().isClass()||fd.getType().isArray())
1463 classdefout.println(" struct "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1465 classdefout.println(" "+fd.getType().getSafeSymbol()+" "+fd.getSafeSymbol()+";");
1470 /* Map flags to integers consistently between inherited
1473 protected void mapFlags(ClassDescriptor cn) {
1474 ClassDescriptor sp=cn.getSuperDesc();
1478 if (!flagorder.containsKey(cn)) {
1479 Hashtable flags=new Hashtable();
1480 flagorder.put(cn,flags);
1482 Hashtable superflags=(Hashtable)flagorder.get(sp);
1483 Iterator superflagit=superflags.keySet().iterator();
1484 while(superflagit.hasNext()) {
1485 FlagDescriptor fd=(FlagDescriptor)superflagit.next();
1486 Integer number=(Integer)superflags.get(fd);
1487 flags.put(fd, number);
1488 if ((number.intValue()+1)>max)
1489 max=number.intValue()+1;
1493 Iterator flagit=cn.getFlags();
1494 while(flagit.hasNext()) {
1495 FlagDescriptor fd=(FlagDescriptor)flagit.next();
1496 if (sp==null||!sp.getFlagTable().contains(fd.getSymbol()))
1497 flags.put(fd, new Integer(max++));
1503 /** This function outputs (1) structures that parameters are
1504 * passed in (when PRECISE GC is enabled) and (2) function
1505 * prototypes for the methods */
1507 protected void generateCallStructs(ClassDescriptor cn, PrintWriter classdefout, PrintWriter output, PrintWriter headersout) {
1508 /* Output class structure */
1509 classdefout.println("struct "+cn.getSafeSymbol()+" {");
1510 classdefout.println(" int type;");
1511 if(state.MLP || state.OOOJAVA){
1512 classdefout.println(" int oid;");
1513 classdefout.println(" int allocsite;");
1515 if (state.EVENTMONITOR) {
1516 classdefout.println(" int objuid;");
1519 classdefout.println(" pthread_t tid;");
1520 classdefout.println(" void * lockentry;");
1521 classdefout.println(" int lockcount;");
1524 classdefout.println(" int mutex;");
1525 classdefout.println(" int objlock;");
1526 if(state.MULTICOREGC) {
1527 classdefout.println(" int marked;");
1531 classdefout.println(" int flag;");
1532 if((!state.MULTICORE) || (cn.getSymbol().equals("TagDescriptor"))) {
1533 classdefout.println(" void * flagptr;");
1534 } else if (state.MULTICORE) {
1535 classdefout.println(" int version;");
1536 classdefout.println(" int * lock;"); // lock entry for this obj
1537 classdefout.println(" int mutex;");
1538 classdefout.println(" int lockcount;");
1539 if(state.MULTICOREGC) {
1540 classdefout.println(" int marked;");
1543 if (state.OPTIONAL) {
1544 classdefout.println(" int numfses;");
1545 classdefout.println(" int * fses;");
1548 printClassStruct(cn, classdefout);
1549 classdefout.println("};\n");
1551 if (state.DSM||state.SINGLETM) {
1552 /* Cycle through LocalityBindings */
1553 HashSet<MethodDescriptor> nativemethods=new HashSet<MethodDescriptor>();
1554 Set<LocalityBinding> lbset=locality.getClassBindings(cn);
1556 for(Iterator<LocalityBinding> lbit=lbset.iterator(); lbit.hasNext();) {
1557 LocalityBinding lb=lbit.next();
1558 MethodDescriptor md=lb.getMethod();
1559 if (md.getModifiers().isNative()) {
1560 //make sure we only print a native method once
1561 if (nativemethods.contains(md)) {
1562 FlatMethod fm=state.getMethodFlat(md);
1563 generateTempStructs(fm, lb);
1566 nativemethods.add(md);
1568 generateMethod(cn, md, lb, headersout, output);
1571 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1572 MethodDescriptor md=(MethodDescriptor)methodit.next();
1573 if (md.getModifiers().isNative()&&!nativemethods.contains(md)) {
1574 //Need to build param structure for library code
1575 FlatMethod fm=state.getMethodFlat(md);
1576 generateTempStructs(fm, null);
1577 generateMethodParam(cn, md, null, output);
1582 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1583 MethodDescriptor md=(MethodDescriptor)methodit.next();
1584 generateMethod(cn, md, null, headersout, output);
1588 private void generateMethodParam(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter output) {
1589 /* Output parameter structure */
1590 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1591 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1592 if ((state.DSM||state.SINGLETM)&&lb!=null)
1593 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1595 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1596 output.println(" int size;");
1597 output.println(" void * next;");
1598 for(int i=0; i<objectparams.numPointers(); i++) {
1599 TempDescriptor temp=objectparams.getPointer(i);
1600 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1602 output.println("};\n");
1606 private void generateMethod(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter headersout, PrintWriter output) {
1607 FlatMethod fm=state.getMethodFlat(md);
1608 generateTempStructs(fm, lb);
1610 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1611 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md);
1613 generateMethodParam(cn, md, lb, output);
1615 /* Output temp structure */
1616 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1617 if (state.DSM||state.SINGLETM)
1618 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1620 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1621 output.println(" int size;");
1622 output.println(" void * next;");
1623 for(int i=0; i<objecttemps.numPointers(); i++) {
1624 TempDescriptor temp=objecttemps.getPointer(i);
1625 if (temp.getType().isNull())
1626 output.println(" void * "+temp.getSafeSymbol()+";");
1628 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1630 output.println("};\n");
1633 /********* Output method declaration ***********/
1634 if (state.DSM||state.SINGLETM) {
1635 headersout.println("#define D"+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1637 headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1639 /* First the return type */
1640 if (md.getReturnType()!=null) {
1641 if (md.getReturnType().isClass()||md.getReturnType().isArray())
1642 headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1644 headersout.print(md.getReturnType().getSafeSymbol()+" ");
1646 //catch the constructor case
1647 headersout.print("void ");
1649 /* Next the method name */
1650 if (state.DSM||state.SINGLETM) {
1651 headersout.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1653 headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1655 boolean printcomma=false;
1656 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1657 if (state.DSM||state.SINGLETM) {
1658 headersout.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1660 headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1664 /* Output parameter list*/
1665 for(int i=0; i<objectparams.numPrimitives(); i++) {
1666 TempDescriptor temp=objectparams.getPrimitive(i);
1668 headersout.print(", ");
1670 if (temp.getType().isClass()||temp.getType().isArray())
1671 headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1673 headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1675 headersout.println(");\n");
1679 /** This function outputs (1) structures that parameters are
1680 * passed in (when PRECISE GC is enabled) and (2) function
1681 * prototypes for the tasks */
1683 private void generateTaskStructs(PrintWriter output, PrintWriter headersout) {
1684 /* Cycle through tasks */
1685 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
1687 while(taskit.hasNext()) {
1688 /* Classify parameters */
1689 TaskDescriptor task=(TaskDescriptor)taskit.next();
1690 FlatMethod fm=state.getMethodFlat(task);
1691 generateTempStructs(fm, null);
1693 ParamsObject objectparams=(ParamsObject) paramstable.get(task);
1694 TempObject objecttemps=(TempObject) tempstable.get(task);
1696 /* Output parameter structure */
1697 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1698 output.println("struct "+task.getSafeSymbol()+"_params {");
1699 output.println(" int size;");
1700 output.println(" void * next;");
1701 for(int i=0; i<objectparams.numPointers(); i++) {
1702 TempDescriptor temp=objectparams.getPointer(i);
1703 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1706 output.println("};\n");
1707 if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
1708 maxtaskparams=objectparams.numPointers()+fm.numTags();
1712 /* Output temp structure */
1713 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1714 output.println("struct "+task.getSafeSymbol()+"_locals {");
1715 output.println(" int size;");
1716 output.println(" void * next;");
1717 for(int i=0; i<objecttemps.numPointers(); i++) {
1718 TempDescriptor temp=objecttemps.getPointer(i);
1719 if (temp.getType().isNull())
1720 output.println(" void * "+temp.getSafeSymbol()+";");
1721 else if(temp.getType().isTag())
1722 output.println(" struct "+
1723 (new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1725 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1727 output.println("};\n");
1730 /* Output task declaration */
1731 headersout.print("void " + task.getSafeSymbol()+"(");
1733 boolean printcomma=false;
1734 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1735 headersout.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
1737 headersout.print("void * parameterarray[]");
1738 headersout.println(");\n");
1742 /***** Generate code for FlatMethod fm. *****/
1744 Hashtable<FlatAtomicEnterNode, AtomicRecord> atomicmethodmap;
1745 static int atomicmethodcount=0;
1748 BranchAnalysis branchanalysis;
1749 private void generateFlatMethod(FlatMethod fm, LocalityBinding lb, PrintWriter output) {
1750 if (State.PRINTFLAT)
1751 System.out.println(fm.printMethod());
1752 MethodDescriptor md=fm.getMethod();
1753 TaskDescriptor task=fm.getTask();
1754 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
1755 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : md!=null ? md : task);
1757 HashSet<AtomicRecord> arset=null;
1758 branchanalysis=null;
1760 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1762 if (atomicmethodmap==null)
1763 atomicmethodmap=new Hashtable<FlatAtomicEnterNode, AtomicRecord>();
1765 //fix these so we get right strings for local variables
1766 localsprefixaddr=localsprefix;
1767 localsprefixderef=localsprefix+"->";
1768 arset=new HashSet<AtomicRecord>();
1770 //build branchanalysis
1771 branchanalysis=new BranchAnalysis(locality, lb, delaycomp.getNotReady(lb), delaycomp.livecode(lb), state);
1773 //Generate commit methods here
1774 for(Iterator<FlatNode> fnit=fm.getNodeSet().iterator();fnit.hasNext();) {
1775 FlatNode fn=fnit.next();
1776 if (fn.kind()==FKind.FlatAtomicEnterNode&&
1777 locality.getAtomic(lb).get(fn.getPrev(0)).intValue()==0&&
1778 delaycomp.needsFission(lb, (FlatAtomicEnterNode) fn)) {
1779 //We have an atomic enter
1780 FlatAtomicEnterNode faen=(FlatAtomicEnterNode) fn;
1781 Set<FlatNode> exitset=faen.getExits();
1783 String methodname=md.getSymbol()+(atomicmethodcount++);
1784 AtomicRecord ar=new AtomicRecord();
1788 atomicmethodmap.put(faen, ar);
1790 //build data structure declaration
1791 output.println("struct atomicprimitives_"+methodname+" {");
1793 Set<FlatNode> recordset=delaycomp.livecode(lb);
1794 Set<TempDescriptor> liveinto=delaycomp.liveinto(lb, faen, recordset);
1795 Set<TempDescriptor> liveout=delaycomp.liveout(lb, faen);
1796 Set<TempDescriptor> liveoutvirtualread=delaycomp.liveoutvirtualread(lb, faen);
1798 ar.reallivein=new HashSet(liveinto);
1800 ar.liveoutvirtualread=liveoutvirtualread;
1803 for(Iterator<TempDescriptor> it=liveinto.iterator(); it.hasNext();) {
1804 TempDescriptor tmp=it.next();
1805 //remove the pointers
1806 if (tmp.getType().isPtr()) {
1809 //let's print it here
1810 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1813 for(Iterator<TempDescriptor> it=liveout.iterator(); it.hasNext();) {
1814 TempDescriptor tmp=it.next();
1815 //remove the pointers
1816 if (tmp.getType().isPtr()) {
1818 } else if (!liveinto.contains(tmp)) {
1819 //let's print it here
1820 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1823 output.println("};");
1825 //print out method name
1826 output.println("void "+methodname+"(struct "+ cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix+", struct "+ cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals *"+localsprefix+", struct atomicprimitives_"+methodname+" * primitives) {");
1827 //build code for commit method
1829 //first define local primitives
1830 Set<TempDescriptor> alltemps=delaycomp.alltemps(lb, faen, recordset);
1831 for(Iterator<TempDescriptor> tmpit=alltemps.iterator();tmpit.hasNext();) {
1832 TempDescriptor tmp=tmpit.next();
1833 if (!tmp.getType().isPtr()) {
1834 if (liveinto.contains(tmp)||liveoutvirtualread.contains(tmp)) {
1835 //read from live into set
1836 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+"=primitives->"+tmp.getSafeSymbol()+";");
1839 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1843 //turn off write barrier generation
1845 state.SINGLETM=false;
1846 generateCode(faen, fm, lb, exitset, output, false);
1847 state.SINGLETM=true;
1848 //turn on write barrier generation
1850 output.println("}\n\n");
1854 //redefine these back to normal
1856 localsprefixaddr="&"+localsprefix;
1857 localsprefixderef=localsprefix+".";
1859 generateHeader(fm, lb, md!=null ? md : task,output);
1860 TempObject objecttemp=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
1862 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1863 for(Iterator<AtomicRecord> arit=arset.iterator();arit.hasNext();) {
1864 AtomicRecord ar=arit.next();
1865 output.println("struct atomicprimitives_"+ar.name+" primitives_"+ar.name+";");
1869 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1870 if (md!=null&&(state.DSM||state.SINGLETM))
1871 output.print(" struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1872 else if (md!=null&&!(state.DSM||state.SINGLETM))
1873 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1875 output.print(" struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={");
1876 output.print(objecttemp.numPointers()+",");
1877 output.print(paramsprefix);
1878 for(int j=0; j<objecttemp.numPointers(); j++)
1879 output.print(", NULL");
1880 output.println("};");
1883 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1884 TempDescriptor td=objecttemp.getPrimitive(i);
1885 TypeDescriptor type=td.getType();
1887 output.println(" void * "+td.getSafeSymbol()+";");
1888 else if (type.isClass()||type.isArray())
1889 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1891 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1895 if( state.MLP || state.OOOJAVA ) {
1896 if( fm.getNext(0) instanceof FlatSESEEnterNode ) {
1897 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
1898 if( (state.MLP && callerSESEplaceholder != mlpa.getMainSESE()) ||
1899 (state.OOOJAVA && callerSESEplaceholder != oooa.getMainSESE())
1901 // declare variables for naming static SESE's
1902 output.println(" /* static SESE names */");
1903 Iterator<SESEandAgePair> pItr = callerSESEplaceholder.getNeededStaticNames().iterator();
1904 while( pItr.hasNext() ) {
1905 SESEandAgePair pair = pItr.next();
1906 output.println(" void* "+pair+" = NULL;");
1909 // declare variables for tracking dynamic sources
1910 output.println(" /* dynamic variable sources */");
1911 Iterator<TempDescriptor> dynSrcItr = callerSESEplaceholder.getDynamicVarSet().iterator();
1912 while( dynSrcItr.hasNext() ) {
1913 TempDescriptor dynSrcVar = dynSrcItr.next();
1914 output.println(" SESEcommon* "+dynSrcVar+"_srcSESE = NULL;");
1915 output.println(" INTPTR "+dynSrcVar+"_srcOffset = 0x1;");
1920 // set up related allocation sites's waiting queues
1923 ConflictGraph graph = null;
1924 graph = mlpa.getConflictGraphResults().get(fm);
1925 if (graph != null && graph.hasConflictEdge()) {
1926 output.println(" /* set up waiting queues */");
1927 output.println(" int numMemoryQueue=0;");
1928 output.println(" int memoryQueueItemID=0;");
1929 HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
1931 System.out.println("#lockSet="+lockSet.hashCode());
1932 System.out.println("lockset="+lockSet);
1933 for (Iterator iterator = lockSet.iterator(); iterator.hasNext();) {
1934 SESELock seseLock = (SESELock) iterator.next();
1935 System.out.println("id="+seseLock.getID());
1936 System.out.println("#="+seseLock);
1938 System.out.println("size="+lockSet.size());
1939 if (lockSet.size() > 0) {
1940 output.println(" numMemoryQueue=" + lockSet.size() + ";");
1941 output.println(" runningSESE->numMemoryQueue=numMemoryQueue;");
1942 output.println(" runningSESE->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
1947 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
1948 if(callerSESEplaceholder!= oooa.getMainSESE()){
1949 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(callerSESEplaceholder);
1950 if (graph != null && graph.hasConflictEdge()) {
1951 output.println(" // set up waiting queues ");
1952 output.println(" int numMemoryQueue=0;");
1953 output.println(" int memoryQueueItemID=0;");
1954 Set<Analysis.OoOJava.SESELock> lockSet = oooa.getLockMappings(graph);
1955 System.out.println("#lockSet="+lockSet.hashCode());
1956 System.out.println("lockset="+lockSet);
1957 for (Iterator iterator = lockSet.iterator(); iterator.hasNext();) {
1958 Analysis.OoOJava.SESELock seseLock = (Analysis.OoOJava.SESELock) iterator.next();
1959 System.out.println("id="+seseLock.getID());
1960 System.out.println("#="+seseLock);
1962 System.out.println("size="+lockSet.size());
1963 if (lockSet.size() > 0) {
1964 output.println(" numMemoryQueue=" + lockSet.size() + ";");
1965 output.println(" runningSESE->numMemoryQueue=numMemoryQueue;");
1966 output.println(" runningSESE->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
1976 /* Check to see if we need to do a GC if this is a
1977 * multi-threaded program...*/
1979 if (((state.MLP||state.OOOJAVA||state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
1980 || this.state.MULTICOREGC) {
1981 //Don't bother if we aren't in recursive methods...The loops case will catch it
1982 if (callgraph.getAllMethods(md).contains(md)) {
1983 if (state.DSM&&lb.isAtomic())
1984 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
1985 else if (this.state.MULTICOREGC) {
1986 output.println("if(gcflag) gc("+localsprefixaddr+");");
1988 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
1993 generateCode(fm.getNext(0), fm, lb, null, output, true);
1995 output.println("}\n\n");
1999 protected void initializeSESE( FlatSESEEnterNode fsen ) {
2001 FlatMethod fm = fsen.getfmEnclosing();
2002 MethodDescriptor md = fm.getMethod();
2003 ClassDescriptor cn = md.getClassDesc();
2006 // Creates bogus method descriptor to index into tables
2007 Modifiers modBogus = new Modifiers();
2008 MethodDescriptor mdBogus =
2009 new MethodDescriptor( modBogus,
2010 new TypeDescriptor( TypeDescriptor.VOID ),
2011 "sese_"+fsen.getPrettyIdentifier()+fsen.getIdentifier()
2014 mdBogus.setClassDesc( fsen.getcdEnclosing() );
2015 FlatMethod fmBogus = new FlatMethod( mdBogus, null );
2016 fsen.setfmBogus( fmBogus );
2017 fsen.setmdBogus( mdBogus );
2019 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
2020 inSetAndOutSet.addAll( fsen.getInVarSet() );
2021 inSetAndOutSet.addAll( fsen.getOutVarSet() );
2023 // Build paramsobj for bogus method descriptor
2024 ParamsObject objectparams = new ParamsObject( mdBogus, tag++ );
2025 paramstable.put( mdBogus, objectparams );
2027 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
2028 while( itr.hasNext() ) {
2029 TempDescriptor temp = itr.next();
2030 TypeDescriptor type = temp.getType();
2031 if( type.isPtr() ) {
2032 objectparams.addPtr( temp );
2034 objectparams.addPrim( temp );
2038 // Build normal temp object for bogus method descriptor
2039 TempObject objecttemps = new TempObject( objectparams, mdBogus, tag++ );
2040 tempstable.put( mdBogus, objecttemps );
2042 for( Iterator nodeit = fsen.getNodeSet().iterator(); nodeit.hasNext(); ) {
2043 FlatNode fn = (FlatNode)nodeit.next();
2044 TempDescriptor[] writes = fn.writesTemps();
2046 for( int i = 0; i < writes.length; i++ ) {
2047 TempDescriptor temp = writes[i];
2048 TypeDescriptor type = temp.getType();
2050 if( type.isPtr() ) {
2051 objecttemps.addPtr( temp );
2053 objecttemps.addPrim( temp );
2059 // used when generating the specific SESE record struct
2060 // to remember the FIRST field name of sese records
2061 // that the current SESE depends on--we need to know the
2062 // offset to the first one for garbage collection
2063 protected void addingDepRecField( FlatSESEEnterNode fsen,
2065 if( fsen.getFirstDepRecField() == null ) {
2066 fsen.setFirstDepRecField( field );
2068 fsen.incNumDepRecs();
2071 protected void generateMethodSESE(FlatSESEEnterNode fsen,
2073 PrintWriter outputStructs,
2074 PrintWriter outputMethHead,
2075 PrintWriter outputMethods
2078 ParamsObject objectparams = (ParamsObject) paramstable.get( fsen.getmdBogus() );
2079 TempObject objecttemps = (TempObject) tempstable .get( fsen.getmdBogus() );
2081 // generate locals structure
2082 outputStructs.println("struct "+
2083 fsen.getcdEnclosing().getSafeSymbol()+
2084 fsen.getmdBogus().getSafeSymbol()+"_"+
2085 fsen.getmdBogus().getSafeMethodDescriptor()+
2087 outputStructs.println(" int size;");
2088 outputStructs.println(" void * next;");
2089 for(int i=0; i<objecttemps.numPointers(); i++) {
2090 TempDescriptor temp=objecttemps.getPointer(i);
2092 if (temp.getType().isNull())
2093 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
2095 outputStructs.println(" struct "+
2096 temp.getType().getSafeSymbol()+" * "+
2097 temp.getSafeSymbol()+";");
2099 outputStructs.println("};\n");
2102 // divide in-set and out-set into objects and primitives to prep
2103 // for the record generation just below
2104 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
2105 inSetAndOutSet.addAll( fsen.getInVarSet() );
2106 inSetAndOutSet.addAll( fsen.getOutVarSet() );
2108 Set<TempDescriptor> inSetAndOutSetObjs = new HashSet<TempDescriptor>();
2109 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
2111 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
2112 while( itr.hasNext() ) {
2113 TempDescriptor temp = itr.next();
2114 TypeDescriptor type = temp.getType();
2115 if( type.isPtr() ) {
2116 inSetAndOutSetObjs.add( temp );
2118 inSetAndOutSetPrims.add( temp );
2123 // generate the SESE record structure
2124 outputStructs.println(fsen.getSESErecordName()+" {");
2126 // data common to any SESE, and it must be placed first so
2127 // a module that doesn't know what kind of SESE record this
2128 // is can cast the pointer to a common struct
2129 outputStructs.println(" SESEcommon common;");
2131 // then garbage list stuff
2132 outputStructs.println(" /* next is in-set and out-set objects that look like a garbage list */");
2133 outputStructs.println(" int size;");
2134 outputStructs.println(" void * next;");
2136 // I think that the set of TempDescriptors inSetAndOutSetObjs
2137 // calculated above should match the pointer object params
2138 // used in the following code, but let's just leave the working
2139 // implementation unless there is actually a problem...
2141 Vector<TempDescriptor> inset=fsen.getInVarVector();
2144 for(int i=0; i<inset.size();i++) {
2145 TempDescriptor temp=inset.get(i);
2146 TypeDescriptor type=temp.getType();
2149 if (temp.getType().isNull())
2150 outputStructs.println(" void * "+temp.getSafeSymbol()+
2151 "; /* in-or-out-set obj in gl */");
2153 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+
2154 temp.getSafeSymbol()+"; /* in-or-out-set obj in gl */");
2158 for(int i=0; i<objectparams.numPointers(); i++) {
2159 TempDescriptor temp=objectparams.getPointer(i);
2160 if (!inset.contains(temp)) {
2161 if (temp.getType().isNull())
2162 outputStructs.println(" void * "+temp.getSafeSymbol()+
2163 "; /* in-or-out-set obj in gl */");
2165 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+
2166 temp.getSafeSymbol()+"; /* in-or-out-set obj in gl */");
2170 outputStructs.println(" /* next is primitives for in-set and out-set and dynamic tracking */");
2172 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
2173 while( itrPrims.hasNext() ) {
2174 TempDescriptor temp = itrPrims.next();
2175 TypeDescriptor type = temp.getType();
2176 if(type.isPrimitive()){
2177 outputStructs.println(" "+temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol()+"; /* in-set or out-set primitive */");
2181 // note that the sese record pointer will be added below, just primitive part of tracking here
2182 Iterator<TempDescriptor> itrDynInVars = fsen.getDynamicInVarSet().iterator();
2183 while( itrDynInVars.hasNext() ) {
2184 TempDescriptor dynInVar = itrDynInVars.next();
2185 outputStructs.println(" INTPTR "+dynInVar+"_srcOffset; /* dynamic tracking primitive */");
2189 outputStructs.println(" /* everything after this should be pointers to an SESE record */" );
2191 // other half of info for dynamic tracking, the SESE record pointer
2192 itrDynInVars = fsen.getDynamicInVarSet().iterator();
2193 while( itrDynInVars.hasNext() ) {
2194 TempDescriptor dynInVar = itrDynInVars.next();
2195 String depRecField = dynInVar+"_srcSESE";
2196 outputStructs.println(" SESEcommon* "+depRecField+";");
2197 addingDepRecField( fsen, depRecField );
2200 // statically known sese sources are record pointers, too
2201 Iterator<SESEandAgePair> itrStaticInVarSrcs = fsen.getStaticInVarSrcs().iterator();
2202 while( itrStaticInVarSrcs.hasNext() ) {
2203 SESEandAgePair srcPair = itrStaticInVarSrcs.next();
2204 outputStructs.println(" "+srcPair.getSESE().getSESErecordName()+"* "+srcPair+";");
2205 addingDepRecField(fsen, srcPair.toString());
2209 outputStructs.println("struct rcrRecord rcrRecords["+incount+"]");
2212 if( fsen.getFirstDepRecField() != null ) {
2213 outputStructs.println(" /* compiler believes first dependent SESE record field above is: "+
2214 fsen.getFirstDepRecField()+" */" );
2216 outputStructs.println("};\n");
2219 // write method declaration to header file
2220 outputMethHead.print("void ");
2221 outputMethHead.print(fsen.getSESEmethodName()+"(");
2222 outputMethHead.print(fsen.getSESErecordName()+"* "+paramsprefix);
2223 outputMethHead.println(");\n");
2226 generateFlatMethodSESE( fsen.getfmBogus(),
2227 fsen.getcdEnclosing(),
2233 private void generateFlatMethodSESE(FlatMethod fm,
2235 FlatSESEEnterNode fsen,
2236 FlatSESEExitNode seseExit,
2240 MethodDescriptor md=fm.getMethod();
2242 output.print("void ");
2243 output.print(fsen.getSESEmethodName()+"(");
2244 output.print(fsen.getSESErecordName()+"* "+paramsprefix);
2245 output.println("){\n");
2248 TempObject objecttemp=(TempObject) tempstable.get(md);
2250 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2251 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
2252 output.print(objecttemp.numPointers()+",");
2253 output.print("&(((SESEcommon*)(___params___))[1])");
2254 for(int j=0; j<objecttemp.numPointers(); j++)
2255 output.print(", NULL");
2256 output.println("};");
2259 output.println(" /* regular local primitives */");
2260 for(int i=0; i<objecttemp.numPrimitives(); i++) {
2261 TempDescriptor td=objecttemp.getPrimitive(i);
2262 TypeDescriptor type=td.getType();
2264 output.println(" void * "+td.getSafeSymbol()+";");
2265 else if (type.isClass()||type.isArray())
2266 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
2268 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
2272 // declare variables for naming static SESE's
2273 output.println(" /* static SESE names */");
2274 Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
2275 while( pItr.hasNext() ) {
2276 SESEandAgePair pair = pItr.next();
2277 output.println(" SESEcommon* "+pair+" = NULL;");
2280 // declare variables for tracking dynamic sources
2281 output.println(" /* dynamic variable sources */");
2282 Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
2283 while( dynSrcItr.hasNext() ) {
2284 TempDescriptor dynSrcVar = dynSrcItr.next();
2285 output.println(" SESEcommon* "+dynSrcVar+"_srcSESE = NULL;");
2286 output.println(" INTPTR "+dynSrcVar+"_srcOffset = 0x1;");
2289 // declare local temps for in-set primitives, and if it is
2290 // a ready-source variable, get the value from the record
2291 output.println(" /* local temps for in-set primitives */");
2292 Iterator<TempDescriptor> itrInSet = fsen.getInVarSet().iterator();
2293 while( itrInSet.hasNext() ) {
2294 TempDescriptor temp = itrInSet.next();
2295 TypeDescriptor type = temp.getType();
2296 if( !type.isPtr() ) {
2297 if( fsen.getReadyInVarSet().contains( temp ) ) {
2298 output.println(" "+type+" "+temp+" = "+paramsprefix+"->"+temp+";");
2300 output.println(" "+type+" "+temp+";");
2305 // declare local temps for out-set primitives if its not already
2306 // in the in-set, and it's value will get written so no problem
2307 output.println(" /* local temp for out-set prim, not already in the in-set */");
2308 Iterator<TempDescriptor> itrOutSet = fsen.getOutVarSet().iterator();
2309 while( itrOutSet.hasNext() ) {
2310 TempDescriptor temp = itrOutSet.next();
2311 TypeDescriptor type = temp.getType();
2312 if( !type.isPtr() && !fsen.getInVarSet().contains( temp ) ) {
2313 output.println(" "+type+" "+temp+";");
2318 // initialize thread-local var to a the task's record, which is fused
2319 // with the param list
2320 output.println(" ");
2321 output.println(" /* code of this task's body should use this to access the running task record */");
2322 output.println(" runningSESE = &(___params___->common);");
2323 output.println(" ");
2325 // setup memory queue
2328 output.println(" // set up memory queues ");
2329 output.println(" int numMemoryQueue=0;");
2330 output.println(" int memoryQueueItemID=0;");
2331 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(fsen);
2332 if (graph != null && graph.hasConflictEdge()) {
2333 output.println(" {");
2334 Set<Analysis.OoOJava.SESELock> lockSet = oooa.getLockMappings(graph);
2335 System.out.println("#lockSet="+lockSet);
2336 if (lockSet.size() > 0) {
2337 output.println(" numMemoryQueue=" + lockSet.size() + ";");
2338 output.println(" runningSESE->numMemoryQueue=numMemoryQueue;");
2339 output.println(" runningSESE->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2342 output.println(" }");
2345 output.println(" // set up memory queues ");
2346 output.println(" int numMemoryQueue=0;");
2347 output.println(" int memoryQueueItemID=0;");
2348 ConflictGraph graph = null;
2349 graph = mlpa.getConflictGraphResults().get(fsen);
2350 if (graph != null && graph.hasConflictEdge()) {
2351 output.println(" {");
2352 HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
2354 System.out.println("#lockSet="+lockSet);
2356 if (lockSet.size() > 0) {
2357 output.println(" numMemoryQueue=" + lockSet.size() + "; ");
2358 output.println(" runningSESE->numMemoryQueue=numMemoryQueue;");
2359 output.println(" runningSESE->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2362 output.println(" }");
2367 // set up a task's mem pool to recycle the allocation of children tasks
2368 // don't bother if the task never has children (a leaf task)
2369 output.println( "#ifndef OOO_DISABLE_TASKMEMPOOL" );
2370 if( !fsen.getIsLeafSESE() ) {
2371 output.println(" runningSESE->taskRecordMemPool = poolcreate( "+
2372 maxTaskRecSizeStr+" );");
2374 // make it clear we purposefully did not initialize this
2375 output.println(" runningSESE->taskRecordMemPool = (MemPool*)0x1;");
2377 output.println( "#endif // OOO_DISABLE_TASKMEMPOOL" );
2380 // copy in-set into place, ready vars were already
2381 // copied when the SESE was issued
2382 Iterator<TempDescriptor> tempItr;
2384 // static vars are from a known SESE
2385 output.println(" // copy variables from static sources");
2386 tempItr = fsen.getStaticInVarSet().iterator();
2387 while( tempItr.hasNext() ) {
2388 TempDescriptor temp = tempItr.next();
2389 VariableSourceToken vst = fsen.getStaticInVarSrc( temp );
2390 SESEandAgePair srcPair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2391 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2392 " = "+paramsprefix+"->"+srcPair+"->"+vst.getAddrVar()+";");
2395 output.println(" // decrement references to static sources");
2396 for( Iterator<SESEandAgePair> pairItr = fsen.getStaticInVarSrcs().iterator(); pairItr.hasNext(); ) {
2397 SESEandAgePair srcPair = pairItr.next();
2398 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
2399 output.println(" {");
2400 output.println(" SESEcommon* src = &("+paramsprefix+"->"+srcPair+"->common);");
2401 output.println(" RELEASE_REFERENCE_TO( src );");
2402 output.println(" }");
2403 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
2407 // dynamic vars come from an SESE and src
2408 output.println(" // copy variables from dynamic sources");
2409 tempItr = fsen.getDynamicInVarSet().iterator();
2410 while( tempItr.hasNext() ) {
2411 TempDescriptor temp = tempItr.next();
2412 TypeDescriptor type = temp.getType();
2414 // go grab it from the SESE source
2415 output.println(" if( "+paramsprefix+"->"+temp+"_srcSESE != NULL ) {");
2418 if( type.isNull() ) {
2420 } else if( type.isClass() || type.isArray() ) {
2421 typeStr = "struct "+type.getSafeSymbol()+"*";
2423 typeStr = type.getSafeSymbol();
2426 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2427 " = *(("+typeStr+"*) ((void*)"+
2428 paramsprefix+"->"+temp+"_srcSESE + "+
2429 paramsprefix+"->"+temp+"_srcOffset));");
2431 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
2432 output.println(" SESEcommon* src = "+paramsprefix+"->"+temp+"_srcSESE;");
2433 output.println(" RELEASE_REFERENCE_TO( src );");
2434 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
2436 // or if the source was our parent, its already in our record to grab
2437 output.println(" } else {");
2438 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2439 " = "+paramsprefix+"->"+temp+";");
2440 output.println(" }");
2443 // Check to see if we need to do a GC if this is a
2444 // multi-threaded program...
2445 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2446 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2447 //Don't bother if we aren't in recursive methods...The loops case will catch it
2448 // if (callgraph.getAllMethods(md).contains(md)) {
2449 // if(this.state.MULTICOREGC) {
2450 // output.println("if(gcflag) gc("+localsprefixaddr+");");
2452 // output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2457 if( state.COREPROF ) {
2458 output.println("#ifdef CP_EVENTID_TASKEXECUTE");
2459 output.println(" CP_LOGEVENT( CP_EVENTID_TASKEXECUTE, CP_EVENTTYPE_BEGIN );");
2460 output.println("#endif");
2463 HashSet<FlatNode> exitset=new HashSet<FlatNode>();
2464 exitset.add(seseExit);
2465 generateCode(fsen.getNext(0), fm, null, exitset, output, true);
2466 output.println("}\n\n");
2471 // when a new mlp thread is created for an issued SESE, it is started
2472 // by running this method which blocks on a cond variable until
2473 // it is allowed to transition to execute. Then a case statement
2474 // allows it to invoke the method with the proper SESE body, and after
2475 // exiting the SESE method, executes proper SESE exit code before the
2476 // thread can be destroyed
2477 private void generateSESEinvocationMethod(PrintWriter outmethodheader,
2478 PrintWriter outmethod
2481 outmethodheader.println("void* invokeSESEmethod( void* seseRecord );");
2482 outmethod.println( "void* invokeSESEmethod( void* seseRecord ) {");
2483 outmethod.println( " int status;");
2484 outmethod.println( " char errmsg[128];");
2486 // generate a case for each SESE class that can be invoked
2487 outmethod.println( " switch( *((int*)seseRecord) ) {");
2488 outmethod.println( " ");
2489 Iterator<FlatSESEEnterNode> seseit;
2491 seseit=mlpa.getAllSESEs().iterator();
2493 seseit=oooa.getAllSESEs().iterator();
2495 while(seseit.hasNext()){
2496 FlatSESEEnterNode fsen = seseit.next();
2498 outmethod.println( " /* "+fsen.getPrettyIdentifier()+" */");
2499 outmethod.println( " case "+fsen.getIdentifier()+":");
2500 outmethod.println( " "+fsen.getSESEmethodName()+"( seseRecord );");
2502 if( (state.MLP && fsen.equals( mlpa.getMainSESE() )) ||
2503 (state.OOOJAVA && fsen.equals( oooa.getMainSESE() ))
2505 outmethod.println( " /* work scheduler works forever, explicitly exit */");
2506 outmethod.println( " CP_EXIT();");
2507 outmethod.println( " CP_DUMP();");
2508 outmethod.println( " workScheduleExit();");
2509 outmethod.println( " exit( 0 );");
2512 outmethod.println( " break;");
2513 outmethod.println( "");
2516 // default case should never be taken, error out
2517 outmethod.println( " default:");
2518 outmethod.println( " printf(\"Error: unknown SESE class ID in invoke method.\\n\");");
2519 outmethod.println( " exit(-30);");
2520 outmethod.println( " break;");
2521 outmethod.println( " }");
2522 outmethod.println( " return NULL;");
2523 outmethod.println( "}\n\n");
2527 protected void generateCode(FlatNode first,
2530 Set<FlatNode> stopset,
2531 PrintWriter output, boolean firstpass) {
2533 /* Assign labels to FlatNode's if necessary.*/
2535 Hashtable<FlatNode, Integer> nodetolabel;
2537 if (state.DELAYCOMP&&!firstpass)
2538 nodetolabel=dcassignLabels(first, stopset);
2540 nodetolabel=assignLabels(first, stopset);
2542 Set<FlatNode> storeset=null;
2543 HashSet<FlatNode> genset=null;
2544 HashSet<FlatNode> refset=null;
2545 Set<FlatNode> unionset=null;
2547 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
2548 storeset=delaycomp.livecode(lb);
2549 genset=new HashSet<FlatNode>();
2550 if (state.STMARRAY&&!state.DUALVIEW) {
2551 refset=new HashSet<FlatNode>();
2552 refset.addAll(delaycomp.getDeref(lb));
2553 refset.removeAll(delaycomp.getCannotDelay(lb));
2554 refset.removeAll(delaycomp.getOther(lb));
2557 genset.addAll(delaycomp.getCannotDelay(lb));
2558 genset.addAll(delaycomp.getOther(lb));
2560 genset.addAll(delaycomp.getNotReady(lb));
2561 if (state.STMARRAY&&!state.DUALVIEW) {
2562 genset.removeAll(refset);
2565 unionset=new HashSet<FlatNode>();
2566 unionset.addAll(storeset);
2567 unionset.addAll(genset);
2568 if (state.STMARRAY&&!state.DUALVIEW)
2569 unionset.addAll(refset);
2572 /* Do the actual code generation */
2573 FlatNode current_node=null;
2574 HashSet tovisit=new HashSet();
2575 HashSet visited=new HashSet();
2577 tovisit.add(first.getNext(0));
2580 while(current_node!=null||!tovisit.isEmpty()) {
2581 if (current_node==null) {
2582 current_node=(FlatNode)tovisit.iterator().next();
2583 tovisit.remove(current_node);
2584 } else if (tovisit.contains(current_node)) {
2585 tovisit.remove(current_node);
2587 visited.add(current_node);
2588 if (nodetolabel.containsKey(current_node)) {
2589 output.println("L"+nodetolabel.get(current_node)+":");
2591 if (state.INSTRUCTIONFAILURE) {
2592 if (state.THREAD||state.DSM||state.SINGLETM) {
2593 output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
2595 output.println("if ((--instructioncount)==0) injectinstructionfailure();");
2597 if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
2599 if (!state.DELAYCOMP||firstpass) {
2600 generateFlatNode(fm, lb, current_node, output);
2602 //store primitive variables in out set
2603 AtomicRecord ar=atomicmethodmap.get((FlatAtomicEnterNode)first);
2604 Set<TempDescriptor> liveout=ar.liveout;
2605 for(Iterator<TempDescriptor> tmpit=liveout.iterator();tmpit.hasNext();) {
2606 TempDescriptor tmp=tmpit.next();
2607 output.println("primitives->"+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2610 if ((state.MLP || state.OOOJAVA) && stopset!=null) {
2611 assert first.getPrev( 0 ) instanceof FlatSESEEnterNode;
2612 assert current_node instanceof FlatSESEExitNode;
2613 FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev( 0 );
2614 FlatSESEExitNode fsxn = (FlatSESEExitNode) current_node;
2615 assert fsen.getFlatExit().equals( fsxn );
2616 assert fsxn.getFlatEnter().equals( fsen );
2618 if (current_node.kind()!=FKind.FlatReturnNode) {
2619 output.println(" return;");
2622 } else if(current_node.numNext()==1) {
2624 if ((state.MLP|| state.OOOJAVA) &&
2625 current_node.kind()==FKind.FlatSESEEnterNode &&
2626 !((FlatSESEEnterNode)current_node).getIsCallerSESEplaceholder()
2628 FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
2629 generateFlatNode(fm, lb, current_node, output);
2630 nextnode=fsen.getFlatExit().getNext(0);
2631 } else if (state.DELAYCOMP) {
2632 boolean specialprimitive=false;
2633 //skip literals...no need to add extra overhead
2634 if (storeset!=null&&storeset.contains(current_node)&¤t_node.kind()==FKind.FlatLiteralNode) {
2635 TypeDescriptor typedesc=((FlatLiteralNode)current_node).getType();
2636 if (!typedesc.isClass()&&!typedesc.isArray()) {
2637 specialprimitive=true;
2641 if (genset==null||genset.contains(current_node)||specialprimitive)
2642 generateFlatNode(fm, lb, current_node, output);
2643 if (state.STMARRAY&&!state.DUALVIEW&&refset!=null&&refset.contains(current_node)) {
2644 //need to acquire lock
2645 handleArrayDeref(fm, lb, current_node, output, firstpass);
2647 if (storeset!=null&&storeset.contains(current_node)&&!specialprimitive) {
2648 TempDescriptor wrtmp=current_node.writesTemps()[0];
2650 //need to store value written by previous node
2651 if (wrtmp.getType().isPtr()) {
2652 //only lock the objects that may actually need locking
2653 if (recorddc.getNeedTrans(lb, current_node)&&
2654 (!state.STMARRAY||state.DUALVIEW||!wrtmp.getType().isArray()||
2655 wrtmp.getType().getSymbol().equals(TypeUtil.ObjectClass))) {
2656 output.println("STOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2658 output.println("STOREPTRNOLOCK("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2661 output.println("STORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");/* "+current_node.nodeid+" */");
2664 //need to read value read by previous node
2665 if (wrtmp.getType().isPtr()) {
2666 output.println("RESTOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2668 output.println("RESTORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+"); /* "+current_node.nodeid+" */");
2672 nextnode=current_node.getNext(0);
2675 generateFlatNode(fm, lb, current_node, output);
2676 nextnode=current_node.getNext(0);
2678 if (visited.contains(nextnode)) {
2679 output.println("goto L"+nodetolabel.get(nextnode)+";");
2682 current_node=nextnode;
2683 } else if (current_node.numNext()==2) {
2685 if (state.DELAYCOMP) {
2686 boolean computeside=false;
2688 //need to record which way it should go
2689 if (genset==null||genset.contains(current_node)) {
2690 if (storeset!=null&&storeset.contains(current_node)) {
2691 //need to store which way branch goes
2692 generateStoreFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2694 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2696 //which side to execute
2700 if (genset.contains(current_node)) {
2701 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2702 } else if (storeset.contains(current_node)) {
2704 branchanalysis.generateGroupCode(current_node, output, nodetolabel);
2706 //which side to execute
2711 Set<FlatNode> leftset=DelayComputation.getNext(current_node, 0, unionset, lb,locality, true);
2713 if (leftset.size()==0)
2715 if (visited.contains(current_node.getNext(branch))) {
2716 //already visited -- build jump
2717 output.println("goto L"+nodetolabel.get(current_node.getNext(branch))+";");
2720 current_node=current_node.getNext(branch);
2723 if (!visited.contains(current_node.getNext(1)))
2724 tovisit.add(current_node.getNext(1));
2725 if (visited.contains(current_node.getNext(0))) {
2726 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2729 current_node=current_node.getNext(0);
2733 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2734 if (!visited.contains(current_node.getNext(1)))
2735 tovisit.add(current_node.getNext(1));
2736 if (visited.contains(current_node.getNext(0))) {
2737 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2740 current_node=current_node.getNext(0);
2742 } else throw new Error();
2746 protected void handleArrayDeref(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output, boolean firstpass) {
2747 if (fn.kind()==FKind.FlatSetElementNode) {
2748 FlatSetElementNode fsen=(FlatSetElementNode) fn;
2749 String dst=generateTemp(fm, fsen.getDst(), lb);
2750 String src=generateTemp(fm, fsen.getSrc(), lb);
2751 String index=generateTemp(fm, fsen.getIndex(), lb);
2752 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
2754 if (elementtype.isArray()||elementtype.isClass())
2757 type=elementtype.getSafeSymbol()+" ";
2759 output.println("STOREARRAY("+dst+","+index+","+type+")");
2761 output.println("{");
2762 output.println(" struct ArrayObject *array;");
2763 output.println(" int index;");
2764 output.println(" RESTOREARRAY(array,index);");
2765 output.println(" (("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index]="+src+";");
2766 output.println("}");
2768 } else if (fn.kind()==FKind.FlatElementNode) {
2769 FlatElementNode fen=(FlatElementNode) fn;
2770 String src=generateTemp(fm, fen.getSrc(), lb);
2771 String index=generateTemp(fm, fen.getIndex(), lb);
2772 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
2773 String dst=generateTemp(fm, fen.getDst(), lb);
2775 if (elementtype.isArray()||elementtype.isClass())
2778 type=elementtype.getSafeSymbol()+" ";
2780 output.println("STOREARRAY("+src+","+index+","+type+")");
2782 output.println("{");
2783 output.println(" struct ArrayObject *array;");
2784 output.println(" int index;");
2785 output.println(" RESTOREARRAY(array,index);");
2786 output.println(" "+dst+"=(("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index];");
2787 output.println("}");
2791 /** Special label assignment for delaycomputation */
2792 protected Hashtable<FlatNode, Integer> dcassignLabels(FlatNode first, Set<FlatNode> lastset) {
2793 HashSet tovisit=new HashSet();
2794 HashSet visited=new HashSet();
2796 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2798 //Label targets of branches
2799 Set<FlatNode> targets=branchanalysis.getTargets();
2800 for(Iterator<FlatNode> it=targets.iterator();it.hasNext();) {
2801 nodetolabel.put(it.next(), new Integer(labelindex++));
2806 /*Assign labels first. A node needs a label if the previous
2807 * node has two exits or this node is a join point. */
2809 while(!tovisit.isEmpty()) {
2810 FlatNode fn=(FlatNode)tovisit.iterator().next();
2815 if(lastset!=null&&lastset.contains(fn)) {
2816 // if last is not null and matches, don't go
2817 // any further for assigning labels
2821 for(int i=0; i<fn.numNext(); i++) {
2822 FlatNode nn=fn.getNext(i);
2825 //1) Edge >1 of node
2826 nodetolabel.put(nn,new Integer(labelindex++));
2828 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2832 nodetolabel.put(nn,new Integer(labelindex++));
2840 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first) {
2841 return assignLabels(first, null);
2844 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
2845 HashSet tovisit=new HashSet();
2846 HashSet visited=new HashSet();
2848 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2851 /*Assign labels first. A node needs a label if the previous
2852 * node has two exits or this node is a join point. */
2854 while(!tovisit.isEmpty()) {
2855 FlatNode fn=(FlatNode)tovisit.iterator().next();
2860 if(lastset!=null&&lastset.contains(fn)) {
2861 // if last is not null and matches, don't go
2862 // any further for assigning labels
2866 for(int i=0; i<fn.numNext(); i++) {
2867 FlatNode nn=fn.getNext(i);
2870 //1) Edge >1 of node
2871 nodetolabel.put(nn,new Integer(labelindex++));
2873 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2877 nodetolabel.put(nn,new Integer(labelindex++));
2885 /** Generate text string that corresponds to the TempDescriptor td. */
2886 protected String generateTemp(FlatMethod fm, TempDescriptor td, LocalityBinding lb) {
2887 MethodDescriptor md=fm.getMethod();
2888 TaskDescriptor task=fm.getTask();
2889 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
2891 if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
2892 return td.getSafeSymbol();
2895 if (objecttemps.isLocalPtr(td)) {
2896 return localsprefixderef+td.getSafeSymbol();
2899 if (objecttemps.isParamPtr(td)) {
2900 return paramsprefix+"->"+td.getSafeSymbol();
2906 protected void generateFlatNode(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output) {
2908 // insert pre-node actions from the code plan
2909 if( state.MLP|| state.OOOJAVA ) {
2913 cp = mlpa.getCodePlan( fn );
2915 cp = oooa.getCodePlan(fn);
2920 FlatSESEEnterNode currentSESE = cp.getCurrentSESE();
2922 // for each sese and age pair that this parent statement
2923 // must stall on, take that child's stall semaphore, the
2924 // copying of values comes after the statement
2925 Iterator<VariableSourceToken> vstItr = cp.getStallTokens().iterator();
2926 while( vstItr.hasNext() ) {
2927 VariableSourceToken vst = vstItr.next();
2929 SESEandAgePair pair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2931 output.println(" {");
2932 output.println(" "+pair.getSESE().getSESErecordName()+"* child = ("+
2933 pair.getSESE().getSESErecordName()+"*) "+pair+";");
2935 output.println(" SESEcommon* common = (SESEcommon*) "+pair+";");
2936 if( state.COREPROF ) {
2937 output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
2938 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_BEGIN );");
2939 output.println("#endif");
2941 output.println(" pthread_mutex_lock( &(common->lock) );");
2942 output.println(" if( common->doneExecuting == FALSE ) {");
2943 output.println(" stopforgc((struct garbagelist *)&___locals___);");
2944 output.println(" do {");
2945 output.println(" pthread_cond_wait( &(common->doneCond), &(common->lock) );");
2946 output.println(" } while( common->doneExecuting == FALSE );");
2947 output.println(" restartaftergc();");
2948 output.println(" }");
2949 output.println(" pthread_mutex_unlock( &(common->lock) );");
2951 // copy things we might have stalled for
2952 Iterator<TempDescriptor> tdItr = cp.getCopySet( vst ).iterator();
2953 while( tdItr.hasNext() ) {
2954 TempDescriptor td = tdItr.next();
2955 FlatMethod fmContext;
2956 if( currentSESE.getIsCallerSESEplaceholder() ) {
2957 fmContext = currentSESE.getfmEnclosing();
2959 fmContext = currentSESE.getfmBogus();
2961 output.println(" "+generateTemp( fmContext, td, null )+
2962 " = child->"+vst.getAddrVar().getSafeSymbol()+";");
2964 if( state.COREPROF ) {
2965 output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
2966 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_END );");
2967 output.println("#endif");
2969 output.println(" }");
2972 // for each variable with a dynamic source, stall just for that variable
2973 Iterator<TempDescriptor> dynItr = cp.getDynamicStallSet().iterator();
2974 while( dynItr.hasNext() ) {
2975 TempDescriptor dynVar = dynItr.next();
2977 // only stall if the dynamic source is not yourself, denoted by src==NULL
2978 // otherwise the dynamic write nodes will have the local var up-to-date
2979 output.println(" {");
2980 output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
2981 output.println(" SESEcommon* common = (SESEcommon*) "+dynVar+"_srcSESE;");
2982 if( state.COREPROF ) {
2983 output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
2984 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_BEGIN );");
2985 output.println("#endif");
2987 output.println(" psem_take( &(common->stallSem) );");
2989 FlatMethod fmContext;
2990 if( currentSESE.getIsCallerSESEplaceholder() ) {
2991 fmContext = currentSESE.getfmEnclosing();
2993 fmContext = currentSESE.getfmBogus();
2996 TypeDescriptor type=dynVar.getType();
2998 if( type.isNull() ) {
3000 } else if( type.isClass() || type.isArray() ) {
3001 typeStr = "struct "+type.getSafeSymbol()+"*";
3003 typeStr = type.getSafeSymbol();
3006 output.println(" "+generateTemp( fmContext, dynVar, null )+
3007 " = *(("+typeStr+"*) ((void*)"+
3008 dynVar+"_srcSESE + "+dynVar+"_srcOffset));");
3009 if( state.COREPROF ) {
3010 output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
3011 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_END );");
3012 output.println("#endif");
3014 output.println(" }");
3015 output.println(" }");
3018 // for each assignment of a variable to rhs that has a dynamic source,
3019 // copy the dynamic sources
3020 Iterator dynAssignItr = cp.getDynAssigns().entrySet().iterator();
3021 while( dynAssignItr.hasNext() ) {
3022 Map.Entry me = (Map.Entry) dynAssignItr.next();
3023 TempDescriptor lhs = (TempDescriptor) me.getKey();
3024 TempDescriptor rhs = (TempDescriptor) me.getValue();
3026 output.println(" {");
3027 output.println(" SESEcommon* oldSrc = "+lhs+"_srcSESE;");
3029 output.println(" "+lhs+"_srcSESE = "+rhs+"_srcSESE;");
3030 output.println(" "+lhs+"_srcOffset = "+rhs+"_srcOffset;");
3032 // no matter what we did above, track reference count of whatever
3033 // this variable pointed to, do release last in case we're just
3034 // copying the same value in because 1->2->1 is safe but ref count
3035 // 1->0->1 has a window where it looks like it should be free'd
3036 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
3037 output.println(" if( "+rhs+"_srcSESE != NULL ) {");
3038 output.println(" ADD_REFERENCE_TO( "+rhs+"_srcSESE );");
3039 output.println(" }");
3040 output.println(" if( oldSrc != NULL ) {");
3041 output.println(" RELEASE_REFERENCE_TO( oldSrc );");
3042 output.println(" }");
3043 output.println(" }");
3044 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
3047 // for each lhs that is dynamic from a non-dynamic source, set the
3048 // dynamic source vars to the current SESE
3049 dynItr = cp.getDynAssignCurr().iterator();
3050 while( dynItr.hasNext() ) {
3051 TempDescriptor dynVar = dynItr.next();
3052 assert currentSESE.getDynamicVarSet().contains( dynVar );
3054 // first release a reference to current record
3055 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
3056 output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
3057 output.println(" RELEASE_REFERENCE_TO( oldSrc );");
3058 output.println(" }");
3059 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
3061 output.println(" "+dynVar+"_srcSESE = NULL;");
3065 // handling stall site
3066 if (state.OOOJAVA) {
3067 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(currentSESE);
3069 Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
3070 Set<Analysis.OoOJava.WaitingElement> waitingElementSet =
3071 graph.getStallSiteWaitingElementSet(fn, seseLockSet);
3073 if(waitingElementSet.size()>0){
3074 output.println("// stall on parent's stall sites ");
3075 output.println(" {");
3076 output.println(" REntry* rentry;");
3078 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
3079 Analysis.OoOJava.WaitingElement waitingElement = (Analysis.OoOJava.WaitingElement) iterator.next();
3081 if(state.RCR && rcr != null){
3082 Analysis.OoOJava.ConflictGraph conflictGraph = graph;
3083 Hashtable<Taint, Set<Effect>> conflicts;
3084 ReachGraph rg = oooa.getDisjointAnalysis().getReachGraph(currentSESE.getmdEnclosing());
3085 if(rcr.cSideDebug) {
3086 rg.writeGraph("RCR_RG_STALLSITE_DEBUG");
3088 if((conflictGraph != null) &&
3089 (conflicts = graph.getConflictEffectSet(fn)) != null &&
3091 rcr.addToTraverseToDoList(fn, waitingElement.getTempDesc(), rg, conflicts);
3095 if( waitingElement.getStatus() >= ConflictNode.COARSE ){
3096 output.println(" rentry=mlpCreateREntry("+ waitingElement.getStatus()+ ", runningSESE);");
3098 output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", runningSESE, (void*)&" +generateTemp(fm,waitingElement.getTempDesc(),lb)+ ");");
3100 output.println(" psem_init( &(rentry->parentStallSem) );");
3101 output.println(" rentry->queue=runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
3102 output.println(" if(ADDRENTRY(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()
3103 + "],rentry)==NOTREADY){");
3104 if( state.COREPROF ) {
3105 output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3106 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_BEGIN );");
3107 output.println("#endif");
3109 output.println(" psem_take( &(rentry->parentStallSem) );");
3110 if( state.COREPROF ) {
3111 output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3112 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_END );");
3113 output.println("#endif");
3115 output.println(" } ");
3117 if(state.RCR && rcr != null) {
3118 output.println(" "+rcr.getTraverserInvocation(waitingElement.getTempDesc(),
3119 generateTemp(fm, waitingElement.getTempDesc(), null), fn));
3122 output.println(" }");
3126 ParentChildConflictsMap conflictsMap = mlpa.getConflictsResults().get(fn);
3127 if (conflictsMap != null) {
3128 Set<Long> allocSet = conflictsMap.getAllocationSiteIDSetofStallSite();
3129 if (allocSet.size() > 0) {
3130 FlatNode enclosingFlatNode=null;
3131 if( currentSESE.getIsCallerSESEplaceholder() && currentSESE.getParent()==null){
3132 enclosingFlatNode=currentSESE.getfmEnclosing();
3134 enclosingFlatNode=currentSESE;
3136 ConflictGraph graph=mlpa.getConflictGraphResults().get(enclosingFlatNode);
3137 HashSet<SESELock> seseLockSet=mlpa.getConflictGraphLockMap().get(graph);
3138 Set<WaitingElement> waitingElementSet=graph.getStallSiteWaitingElementSet(conflictsMap, seseLockSet);
3140 if(waitingElementSet.size()>0){
3141 output.println("// stall on parent's stall sites ");
3142 output.println(" {");
3143 output.println(" REntry* rentry;");
3145 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
3146 WaitingElement waitingElement = (WaitingElement) iterator.next();
3148 if( waitingElement.getStatus() >= ConflictNode.COARSE ){
3149 // HERE! a parent might conflict with a child
3150 output.println(" rentry=mlpCreateREntry("+ waitingElement.getStatus()+ ", runningSESE);");
3152 output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", runningSESE, (void*)&___locals___."+ waitingElement.getDynID() + ");");
3154 output.println(" psem_init( &(rentry->parentStallSem) );");
3155 output.println(" rentry->queue=runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
3157 .println(" if(ADDRENTRY(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()
3158 + "],rentry)==NOTREADY){");
3159 if( state.COREPROF ) {
3160 output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3161 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_BEGIN );");
3162 output.println("#endif");
3164 output.println(" psem_take( &(rentry->parentStallSem) );");
3165 if( state.COREPROF ) {
3166 output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3167 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_END );");
3168 output.println("#endif");
3170 output.println(" } ");
3172 output.println(" }");
3181 case FKind.FlatAtomicEnterNode:
3182 generateFlatAtomicEnterNode(fm, lb, (FlatAtomicEnterNode) fn, output);
3185 case FKind.FlatAtomicExitNode:
3186 generateFlatAtomicExitNode(fm, lb, (FlatAtomicExitNode) fn, output);
3189 case FKind.FlatInstanceOfNode:
3190 generateFlatInstanceOfNode(fm, lb, (FlatInstanceOfNode)fn, output);
3193 case FKind.FlatSESEEnterNode:
3194 generateFlatSESEEnterNode(fm, lb, (FlatSESEEnterNode)fn, output);
3197 case FKind.FlatSESEExitNode:
3198 generateFlatSESEExitNode(fm, lb, (FlatSESEExitNode)fn, output);
3201 case FKind.FlatWriteDynamicVarNode:
3202 generateFlatWriteDynamicVarNode(fm, lb, (FlatWriteDynamicVarNode)fn, output);
3205 case FKind.FlatGlobalConvNode:
3206 generateFlatGlobalConvNode(fm, lb, (FlatGlobalConvNode) fn, output);
3209 case FKind.FlatTagDeclaration:
3210 generateFlatTagDeclaration(fm, lb, (FlatTagDeclaration) fn,output);
3213 case FKind.FlatCall:
3214 generateFlatCall(fm, lb, (FlatCall) fn,output);
3217 case FKind.FlatFieldNode:
3218 generateFlatFieldNode(fm, lb, (FlatFieldNode) fn,output);
3221 case FKind.FlatElementNode:
3222 generateFlatElementNode(fm, lb, (FlatElementNode) fn,output);
3225 case FKind.FlatSetElementNode:
3226 generateFlatSetElementNode(fm, lb, (FlatSetElementNode) fn,output);
3229 case FKind.FlatSetFieldNode:
3230 generateFlatSetFieldNode(fm, lb, (FlatSetFieldNode) fn,output);
3234 generateFlatNew(fm, lb, (FlatNew) fn,output);
3237 case FKind.FlatOpNode:
3238 generateFlatOpNode(fm, lb, (FlatOpNode) fn,output);
3241 case FKind.FlatCastNode:
3242 generateFlatCastNode(fm, lb, (FlatCastNode) fn,output);
3245 case FKind.FlatLiteralNode:
3246 generateFlatLiteralNode(fm, lb, (FlatLiteralNode) fn,output);
3249 case FKind.FlatReturnNode:
3250 generateFlatReturnNode(fm, lb, (FlatReturnNode) fn,output);
3254 output.println("/* nop */");
3257 case FKind.FlatGenReachNode:
3258 // this node is just for generating a reach graph
3259 // in disjointness analysis at a particular program point
3262 case FKind.FlatExit:
3263 output.println("/* exit */");
3266 case FKind.FlatBackEdge:
3267 if (state.SINGLETM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
3268 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
3270 if(state.DSM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
3271 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
3273 if (((state.MLP|| state.OOOJAVA||state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
3274 || (this.state.MULTICOREGC)) {
3275 if(state.DSM&&locality.getAtomic(lb).get(fn).intValue()>0) {
3276 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
3277 } else if(this.state.MULTICOREGC) {
3278 output.println("if (gcflag) gc("+localsprefixaddr+");");
3280 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3283 output.println("/* nop */");
3286 case FKind.FlatCheckNode:
3287 generateFlatCheckNode(fm, lb, (FlatCheckNode) fn, output);
3290 case FKind.FlatFlagActionNode:
3291 generateFlatFlagActionNode(fm, lb, (FlatFlagActionNode) fn, output);
3294 case FKind.FlatPrefetchNode:
3295 generateFlatPrefetchNode(fm,lb, (FlatPrefetchNode) fn, output);
3298 case FKind.FlatOffsetNode:
3299 generateFlatOffsetNode(fm, lb, (FlatOffsetNode)fn, output);
3306 // insert post-node actions from the code-plan
3309 CodePlan cp = mlpa.getCodePlan( fn );
3317 public void generateFlatOffsetNode(FlatMethod fm, LocalityBinding lb, FlatOffsetNode fofn, PrintWriter output) {
3318 output.println("/* FlatOffsetNode */");
3319 FieldDescriptor fd=fofn.getField();
3320 output.println(generateTemp(fm, fofn.getDst(),lb)+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+ fd.getSafeSymbol()+");");
3321 output.println("/* offset */");
3324 public void generateFlatPrefetchNode(FlatMethod fm, LocalityBinding lb, FlatPrefetchNode fpn, PrintWriter output) {
3325 if (state.PREFETCH) {
3326 Vector oids = new Vector();
3327 Vector fieldoffset = new Vector();
3328 Vector endoffset = new Vector();
3329 int tuplecount = 0; //Keeps track of number of prefetch tuples that need to be generated
3330 for(Iterator it = fpn.hspp.iterator(); it.hasNext();) {
3331 PrefetchPair pp = (PrefetchPair) it.next();
3332 Integer statusbase = locality.getNodePreTempInfo(lb,fpn).get(pp.base);
3333 /* Find prefetches that can generate oid */
3334 if(statusbase == LocalityAnalysis.GLOBAL) {
3335 generateTransCode(fm, lb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(lb).get(fpn).intValue()>0, false);
3337 } else if (statusbase == LocalityAnalysis.LOCAL) {
3338 generateTransCode(fm,lb,pp,oids,fieldoffset,endoffset,tuplecount,false,true);
3345 System.out.println("Adding prefetch "+fpn+ " to method:" +fm);
3346 output.println("{");
3347 output.println("/* prefetch */");
3348 output.println("/* prefetchid_" + fpn.siteid + " */");
3349 output.println("void * prefptr;");
3350 output.println("int tmpindex;");
3352 output.println("if((evalPrefetch["+fpn.siteid+"].operMode) || (evalPrefetch["+fpn.siteid+"].retrycount <= 0)) {");
3353 /*Create C code for oid array */
3354 output.print(" unsigned int oidarray_[] = {");
3355 boolean needcomma=false;
3356 for (Iterator it = oids.iterator(); it.hasNext();) {
3359 output.print(it.next());
3362 output.println("};");
3364 /*Create C code for endoffset values */
3365 output.print(" unsigned short endoffsetarry_[] = {");
3367 for (Iterator it = endoffset.iterator(); it.hasNext();) {
3370 output.print(it.next());
3373 output.println("};");
3375 /*Create C code for Field Offset Values */
3376 output.print(" short fieldarry_[] = {");
3378 for (Iterator it = fieldoffset.iterator(); it.hasNext();) {
3381 output.print(it.next());
3384 output.println("};");
3385 /* make the prefetch call to Runtime */
3386 output.println(" if(!evalPrefetch["+fpn.siteid+"].operMode) {");
3387 output.println(" evalPrefetch["+fpn.siteid+"].retrycount = RETRYINTERVAL;");
3388 output.println(" }");
3389 output.println(" prefetch("+fpn.siteid+" ,"+tuplecount+", oidarray_, endoffsetarry_, fieldarry_);");
3390 output.println(" } else {");
3391 output.println(" evalPrefetch["+fpn.siteid+"].retrycount--;");
3392 output.println(" }");
3393 output.println("}");
3397 public void generateTransCode(FlatMethod fm, LocalityBinding lb,PrefetchPair pp, Vector oids, Vector fieldoffset, Vector endoffset, int tuplecount, boolean inside, boolean localbase) {
3398 short offsetcount = 0;
3402 } else if (localbase) {
3403 for(; breakindex<pp.desc.size(); breakindex++) {
3404 Descriptor desc=pp.getDescAt(breakindex);
3405 if (desc instanceof FieldDescriptor) {
3406 FieldDescriptor fd=(FieldDescriptor)desc;
3407 if (fd.isGlobal()) {
3415 if (breakindex>pp.desc.size()) //all local
3418 TypeDescriptor lasttype=pp.base.getType();
3419 String basestr=generateTemp(fm, pp.base, lb);
3421 boolean maybenull=fm.getMethod().isStatic()||
3422 !pp.base.equals(fm.getParameter(0));
3424 for(int i=0; i<breakindex; i++) {
3425 String indexcheck="";
3427 Descriptor desc=pp.getDescAt(i);
3428 if (desc instanceof FieldDescriptor) {
3429 FieldDescriptor fd=(FieldDescriptor)desc;
3431 if (!teststr.equals(""))
3433 teststr+="((prefptr="+basestr+")!=NULL)";
3434 basestr="((struct "+lasttype.getSafeSymbol()+" *)prefptr)->"+fd.getSafeSymbol();
3436 basestr=basestr+"->"+fd.getSafeSymbol();
3439 lasttype=fd.getType();
3441 IndexDescriptor id=(IndexDescriptor)desc;
3442 indexcheck="((tmpindex=";
3443 for(int j=0; j<id.tddesc.size(); j++) {
3444 indexcheck+=generateTemp(fm, id.getTempDescAt(j), lb)+"+";
3446 indexcheck+=id.offset+")>=0)&(tmpindex<((struct ArrayObject *)prefptr)->___length___)";
3448 if (!teststr.equals(""))
3450 teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck;
3451 basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]";
3453 lasttype=lasttype.dereference();
3458 if (teststr.equals("")) {
3459 oid="((unsigned int)"+basestr+")";
3461 oid="((unsigned int)(("+teststr+")?"+basestr+":NULL))";
3465 for(int i = breakindex; i < pp.desc.size(); i++) {
3466 String newfieldoffset;
3467 Object desc = pp.getDescAt(i);
3468 if(desc instanceof FieldDescriptor) {
3469 FieldDescriptor fd=(FieldDescriptor)desc;
3470 newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))");
3471 lasttype=fd.getType();
3473 newfieldoffset = "";
3474 IndexDescriptor id=(IndexDescriptor)desc;
3475 for(int j = 0; j < id.tddesc.size(); j++) {
3476 newfieldoffset += generateTemp(fm, id.getTempDescAt(j), lb) + "+";
3478 newfieldoffset += id.offset.toString();
3479 lasttype=lasttype.dereference();
3481 fieldoffset.add(newfieldoffset);
3484 int base=(tuplecount>0) ? ((Short)endoffset.get(tuplecount-1)).intValue() : 0;
3485 base+=pp.desc.size()-breakindex;
3486 endoffset.add(new Short((short)base));
3491 public void generateFlatGlobalConvNode(FlatMethod fm, LocalityBinding lb, FlatGlobalConvNode fgcn, PrintWriter output) {
3492 if (lb!=fgcn.getLocality())
3494 /* Have to generate flat globalconv */
3495 if (fgcn.getMakePtr()) {
3497 //DEBUG: output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+",\" "+fm+":"+fgcn+"\");");
3498 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3500 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fgcn)||state.READSET&&dc.getNeedWriteTrans(lb, fgcn)) {
3501 //need to do translation
3502 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+", (void *)("+localsprefixaddr+"));");
3503 } else if (state.READSET&&dc.getNeedTrans(lb, fgcn)) {
3504 if (state.HYBRID&&delaycomp.getConv(lb).contains(fgcn)) {
3505 output.println("TRANSREADRDFISSION("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3507 output.println("TRANSREADRD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3511 /* Need to convert to OID */
3512 if ((dc==null)||dc.getNeedSrcTrans(lb,fgcn)) {
3513 if (fgcn.doConvert()||(delaycomp!=null&&delaycomp.needsFission(lb, fgcn.getAtomicEnter())&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) {
3514 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc(),lb)+");");
3516 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=NULL;");
3522 public void generateFlatInstanceOfNode(FlatMethod fm, LocalityBinding lb, FlatInstanceOfNode fion, PrintWriter output) {
3524 if (fion.getType().isArray()) {
3525 type=state.getArrayNumber(fion.getType())+state.numClasses();
3527 type=fion.getType().getClassDesc().getId();
3530 if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
3531 output.println(generateTemp(fm, fion.getDst(), lb)+"=1;");
3533 output.println(generateTemp(fm, fion.getDst(), lb)+"=instanceof("+generateTemp(fm,fion.getSrc(),lb)+","+type+");");
3536 int sandboxcounter=0;
3537 public void generateFlatAtomicEnterNode(FlatMethod fm, LocalityBinding lb, FlatAtomicEnterNode faen, PrintWriter output) {
3538 /* Check to see if we need to generate code for this atomic */
3539 if (locality==null) {
3540 if (GENERATEPRECISEGC) {
3541 output.println("if (pthread_mutex_trylock(&atomiclock)!=0) {");
3542 output.println("stopforgc((struct garbagelist *) &___locals___);");
3543 output.println("pthread_mutex_lock(&atomiclock);");
3544 output.println("restartaftergc();");
3545 output.println("}");
3547 output.println("pthread_mutex_lock(&atomiclock);");
3552 if (locality.getAtomic(lb).get(faen.getPrev(0)).intValue()>0)
3556 if (state.SANDBOX) {
3557 outsandbox.println("int atomiccounter"+sandboxcounter+"=LOW_CHECK_FREQUENCY;");
3558 output.println("counter_reset_pointer=&atomiccounter"+sandboxcounter+";");
3561 if (state.DELAYCOMP&&delaycomp.needsFission(lb, faen)) {
3562 AtomicRecord ar=atomicmethodmap.get(faen);
3564 for(Iterator<TempDescriptor> tmpit=ar.livein.iterator();tmpit.hasNext();) {
3565 TempDescriptor tmp=tmpit.next();
3566 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3569 //copy outs that depend on path
3570 for(Iterator<TempDescriptor> tmpit=ar.liveoutvirtualread.iterator();tmpit.hasNext();) {
3571 TempDescriptor tmp=tmpit.next();
3572 if (!ar.livein.contains(tmp))
3573 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3577 /* Backup the temps. */
3578 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3579 TempDescriptor tmp=tmpit.next();
3580 output.println(generateTemp(fm, backuptable.get(lb).get(tmp),lb)+"="+generateTemp(fm,tmp,lb)+";");
3583 output.println("goto transstart"+faen.getIdentifier()+";");
3585 /******* Print code to retry aborted transaction *******/
3586 output.println("transretry"+faen.getIdentifier()+":");
3589 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3590 TempDescriptor tmp=tmpit.next();
3591 output.println(generateTemp(fm, tmp,lb)+"="+generateTemp(fm,backuptable.get(lb).get(tmp),lb)+";");
3595 /********* Need to revert local object store ********/
3596 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3598 output.println("while ("+revertptr+") {");
3599 output.println("struct ___Object___ * tmpptr;");
3600 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3601 output.println("REVERT_OBJ("+revertptr+");");
3602 output.println(revertptr+"=tmpptr;");
3603 output.println("}");
3605 /******* Tell the runtime to start the transaction *******/
3607 output.println("transstart"+faen.getIdentifier()+":");
3608 if (state.SANDBOX) {
3609 output.println("transaction_check_counter=*counter_reset_pointer;");
3612 output.println("transStart();");
3614 if (state.ABORTREADERS||state.SANDBOX) {
3616 output.println("abortenabled=1;");
3617 output.println("if (_setjmp(aborttrans)) {");
3618 output.println(" goto transretry"+faen.getIdentifier()+"; }");
3622 public void generateFlatAtomicExitNode(FlatMethod fm, LocalityBinding lb, FlatAtomicExitNode faen, PrintWriter output) {
3623 /* Check to see if we need to generate code for this atomic */
3624 if (locality==null) {
3625 output.println("pthread_mutex_unlock(&atomiclock);");
3628 if (locality.getAtomic(lb).get(faen).intValue()>0)
3630 //store the revert list before we lose the transaction object
3633 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3634 output.println(revertptr+"=revertlist;");
3635 output.println("if (transCommit()) {");
3636 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3637 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3638 output.println("} else {");
3639 /* Need to commit local object store */
3640 output.println("while ("+revertptr+") {");
3641 output.println("struct ___Object___ * tmpptr;");
3642 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3643 output.println("COMMIT_OBJ("+revertptr+");");
3644 output.println(revertptr+"=tmpptr;");
3645 output.println("}");
3646 output.println("}");
3650 if (!state.DELAYCOMP) {
3652 output.println("if (transCommit()) {");
3653 /* Transaction aborts if it returns true */
3654 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3655 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3656 output.println("}");
3658 if (delaycomp.optimizeTrans(lb, faen.getAtomicEnter())&&(!state.STMARRAY||state.DUALVIEW)) {
3659 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3660 output.println("LIGHTWEIGHTCOMMIT("+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+", transretry"+faen.getAtomicEnter().getIdentifier()+");");
3662 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3663 TempDescriptor tmp=tmpit.next();
3664 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3666 } else if (delaycomp.needsFission(lb, faen.getAtomicEnter())) {
3667 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3669 output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {");
3670 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3671 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3672 output.println("}");
3674 output.println("else {");
3675 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3676 TempDescriptor tmp=tmpit.next();
3677 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3679 output.println("}");
3681 output.println("if (transCommit(NULL, NULL, NULL, NULL)) {");
3682 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3683 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3684 output.println("}");
3689 public void generateFlatSESEEnterNode( FlatMethod fm,
3691 FlatSESEEnterNode fsen,
3694 // if MLP flag is off, okay that SESE nodes are in IR graph,
3695 // just skip over them and code generates exactly the same
3696 if( !(state.MLP || state.OOOJAVA) ) {
3699 // there may be an SESE in an unreachable method, skip over
3700 if( (state.MLP && !mlpa.getAllSESEs().contains( fsen )) ||
3701 (state.OOOJAVA && !oooa.getAllSESEs().contains(fsen))
3706 // also, if we have encountered a placeholder, just skip it
3707 if( fsen.getIsCallerSESEplaceholder() ) {
3711 output.println(" {");
3713 if( state.COREPROF ) {
3714 output.println("#ifdef CP_EVENTID_TASKDISPATCH");
3715 output.println(" CP_LOGEVENT( CP_EVENTID_TASKDISPATCH, CP_EVENTTYPE_BEGIN );");
3716 output.println("#endif");
3720 // before doing anything, lock your own record and increment the running children
3721 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3722 (state.OOOJAVA && fsen != oooa.getMainSESE())
3724 output.println(" atomic_inc(&(runningSESE->numRunningChildren));");
3730 // allocate the space for this record
3731 output.println( "#ifndef OOO_DISABLE_TASKMEMPOOL" );
3732 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3733 (state.OOOJAVA && fsen != oooa.getMainSESE())
3736 //output.println(" CP_LOGEVENT( CP_EVENTID_DEBUG_B, CP_EVENTTYPE_BEGIN );");
3738 fsen.getSESErecordName()+"* seseToIssue = ("+
3739 fsen.getSESErecordName()+"*) poolalloc( runningSESE->taskRecordMemPool );");
3740 //output.println(" CP_LOGEVENT( CP_EVENTID_DEBUG_B, CP_EVENTTYPE_END );");
3744 fsen.getSESErecordName()+"* seseToIssue = ("+
3745 fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
3746 fsen.getSESErecordName()+" ) );");
3748 output.println( "#else // OOO_DISABLE_TASKMEMPOOL" );
3750 fsen.getSESErecordName()+"* seseToIssue = ("+
3751 fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
3752 fsen.getSESErecordName()+" ) );");
3753 output.println( "#endif // OOO_DISABLE_TASKMEMPOOL" );
3760 // set up the SESE in-set and out-set objects, which look
3761 // like a garbage list
3762 output.println(" struct garbagelist * gl= (struct garbagelist *)&(((SESEcommon*)(seseToIssue))[1]);");
3763 output.println(" gl->size="+calculateSizeOfSESEParamList(fsen)+";");
3764 output.println(" gl->next = NULL;");
3766 // there are pointers to SESE records the newly-issued SESE
3767 // will use to get values it depends on them for--how many
3768 // are there, and what is the offset from the total SESE
3769 // record to the first dependent record pointer?
3770 output.println(" seseToIssue->common.numDependentSESErecords="+
3771 fsen.getNumDepRecs()+";");
3773 // we only need this (and it will only compile) when the number of dependent
3774 // SESE records is non-zero
3775 if( fsen.getFirstDepRecField() != null ) {
3776 output.println(" seseToIssue->common.offsetToDepSESErecords=(INTPTR)sizeof("+
3777 fsen.getSESErecordName()+") - (INTPTR)&((("+
3778 fsen.getSESErecordName()+"*)0)->"+fsen.getFirstDepRecField()+");"
3783 output.println(" seseToIssumer->common.offsetToParamRecords=(INTPTR)sizeof("+fsen.getSESErecordName()+") - (INTPTR) & ((("+fsen.getSESErecordName()+"*)0)->rcrRecords);");
3786 // fill in common data
3787 output.println(" int localCount=0;");
3788 output.println(" seseToIssue->common.classID = "+fsen.getIdentifier()+";");
3789 output.println(" psem_init( &(seseToIssue->common.stallSem) );");
3790 output.println(" seseToIssue->common.forwardList = createQueue();");
3791 output.println(" seseToIssue->common.unresolvedDependencies = 10000;");
3792 output.println(" pthread_cond_init( &(seseToIssue->common.doneCond), NULL );");
3793 output.println(" seseToIssue->common.doneExecuting = FALSE;");
3794 output.println(" pthread_cond_init( &(seseToIssue->common.runningChildrenCond), NULL );");
3795 output.println(" seseToIssue->common.numRunningChildren = 0;");
3796 output.println(" seseToIssue->common.parent = runningSESE;");
3797 // start with refCount = 2, one being the count that the child itself
3798 // will decrement when it retires, to say it is done using its own
3799 // record, and the other count is for the parent that will remember
3800 // the static name of this new child below
3801 output.println(" seseToIssue->common.refCount = 2;");
3803 // all READY in-vars should be copied now and be done with it
3804 Iterator<TempDescriptor> tempItr = fsen.getReadyInVarSet().iterator();
3805 while( tempItr.hasNext() ) {
3806 TempDescriptor temp = tempItr.next();
3808 // when we are issuing the main SESE or an SESE with placeholder
3809 // caller SESE as parent, generate temp child child's eclosing method,
3810 // otherwise use the parent's enclosing method as the context
3811 boolean useParentContext = false;
3813 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3814 (state.OOOJAVA && fsen != oooa.getMainSESE())
3816 assert fsen.getParent() != null;
3817 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3818 useParentContext = true;
3822 if( useParentContext ) {
3823 output.println(" seseToIssue->"+temp+" = "+
3824 generateTemp( fsen.getParent().getfmBogus(), temp, null )+";");
3826 output.println(" seseToIssue->"+temp+" = "+
3827 generateTemp( fsen.getfmEnclosing(), temp, null )+";");
3831 // before potentially adding this SESE to other forwarding lists,
3833 output.println(" pthread_mutex_init( &(seseToIssue->common.lock), NULL );");
3836 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3837 (state.OOOJAVA && fsen != oooa.getMainSESE())
3839 // count up outstanding dependencies, static first, then dynamic
3840 Iterator<SESEandAgePair> staticSrcsItr = fsen.getStaticInVarSrcs().iterator();
3841 while( staticSrcsItr.hasNext() ) {
3842 SESEandAgePair srcPair = staticSrcsItr.next();
3843 output.println(" {");
3844 output.println(" SESEcommon* src = (SESEcommon*)"+srcPair+";");
3845 output.println(" pthread_mutex_lock( &(src->lock) );");
3847 output.println(" if( !src->doneExecuting ) {");
3848 output.println(" addNewItem( src->forwardList, seseToIssue );");
3849 output.println(" ++(localCount);");
3850 output.println(" }");
3851 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
3852 output.println(" ADD_REFERENCE_TO( src );");
3853 output.println("#endif" );
3854 output.println(" pthread_mutex_unlock( &(src->lock) );");
3855 output.println(" }");
3857 // whether or not it is an outstanding dependency, make sure
3858 // to pass the static name to the child's record
3859 output.println(" seseToIssue->"+srcPair+" = "+
3860 "("+srcPair.getSESE().getSESErecordName()+"*)"+
3864 // dynamic sources might already be accounted for in the static list,
3865 // so only add them to forwarding lists if they're not already there
3866 Iterator<TempDescriptor> dynVarsItr = fsen.getDynamicInVarSet().iterator();
3867 while( dynVarsItr.hasNext() ) {
3868 TempDescriptor dynInVar = dynVarsItr.next();
3869 output.println(" {");
3870 output.println(" SESEcommon* src = (SESEcommon*)"+dynInVar+"_srcSESE;");
3872 // the dynamic source is NULL if it comes from your own space--you can't pass
3873 // the address off to the new child, because you're not done executing and
3874 // might change the variable, so copy it right now
3875 output.println(" if( src != NULL ) {");
3876 output.println(" pthread_mutex_lock( &(src->lock) );");
3880 output.println(" if( isEmpty( src->forwardList ) ||");
3881 output.println(" seseToIssue != peekItem( src->forwardList ) ) {");
3882 output.println(" if( !src->doneExecuting ) {");
3883 output.println(" addNewItem( src->forwardList, seseToIssue );");
3884 output.println(" ++(localCount);");
3885 output.println(" }");
3886 output.println(" }");
3887 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
3888 output.println(" ADD_REFERENCE_TO( src );");
3889 output.println("#endif" );
3890 output.println(" pthread_mutex_unlock( &(src->lock) );");
3891 output.println(" seseToIssue->"+dynInVar+"_srcOffset = "+dynInVar+"_srcOffset;");
3892 output.println(" } else {");
3894 boolean useParentContext = false;
3895 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3896 (state.OOOJAVA && fsen != oooa.getMainSESE())
3898 assert fsen.getParent() != null;
3899 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3900 useParentContext = true;
3903 if( useParentContext ) {
3904 output.println(" seseToIssue->"+dynInVar+" = "+
3905 generateTemp( fsen.getParent().getfmBogus(), dynInVar, null )+";");
3907 output.println(" seseToIssue->"+dynInVar+" = "+
3908 generateTemp( fsen.getfmEnclosing(), dynInVar, null )+";");
3911 output.println(" }");
3912 output.println(" }");
3914 // even if the value is already copied, make sure your NULL source
3915 // gets passed so child knows it already has the dynamic value
3916 output.println(" seseToIssue->"+dynInVar+"_srcSESE = "+dynInVar+"_srcSESE;");
3922 // maintain pointers for finding dynamic SESE
3923 // instances from static names
3924 SESEandAgePair pairNewest = new SESEandAgePair( fsen, 0 );
3925 SESEandAgePair pairOldest = new SESEandAgePair( fsen, fsen.getOldestAgeToTrack() );
3926 if( fsen.getParent() != null &&
3927 fsen.getParent().getNeededStaticNames().contains( pairNewest )
3929 output.println(" {");
3930 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
3931 output.println(" SESEcommon* oldest = "+pairOldest+";");
3932 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
3934 for( int i = fsen.getOldestAgeToTrack(); i > 0; --i ) {
3935 SESEandAgePair pair1 = new SESEandAgePair( fsen, i );
3936 SESEandAgePair pair2 = new SESEandAgePair( fsen, i-1 );
3937 output.println(" "+pair1+" = "+pair2+";");
3939 output.println(" "+pairNewest+" = &(seseToIssue->common);");
3941 // no need to add a reference to whatever is the newest record, because
3942 // we initialized seseToIssue->refCount to *2*
3943 // but release a reference to whatever was the oldest BEFORE the shift
3944 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
3945 output.println(" if( oldest != NULL ) {");
3946 output.println(" RELEASE_REFERENCE_TO( oldest );");
3947 output.println(" }");
3948 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
3949 output.println(" }");
3959 //clear out the parameter records
3964 if( state.COREPROF ) {
3965 output.println("#ifdef CP_EVENTID_PREPAREMEMQ");
3966 output.println(" CP_LOGEVENT( CP_EVENTID_PREPAREMEMQ, CP_EVENTTYPE_BEGIN );");
3967 output.println("#endif");
3972 // count up memory conflict dependencies,
3975 FlatSESEEnterNode parent = fsen.getParent();
3976 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(parent);
3977 if (graph != null && graph.hasConflictEdge()) {
3978 Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
3980 output.println(" //add memory queue element");
3981 Analysis.OoOJava.SESEWaitingQueue seseWaitingQueue=
3982 graph.getWaitingElementSetBySESEID(fsen.getIdentifier(), seseLockSet);
3983 if(seseWaitingQueue.getWaitingElementSize()>0) {
3984 output.println(" {");
3985 output.println(" REntry* rentry=NULL;");
3986 output.println(" INTPTR* pointer=NULL;");
3987 output.println(" seseToIssue->common.rentryIdx=0;");
3989 Set<Integer> queueIDSet=seseWaitingQueue.getQueueIDSet();
3990 for (Iterator iterator = queueIDSet.iterator(); iterator.hasNext();) {
3991 Integer key = (Integer) iterator.next();
3992 int queueID=key.intValue();
3993 Set<Analysis.OoOJava.WaitingElement> waitingQueueSet =
3994 seseWaitingQueue.getWaitingElementSet(queueID);
3995 int enqueueType=seseWaitingQueue.getType(queueID);
3996 if(enqueueType==SESEWaitingQueue.EXCEPTION) {
3997 output.println(" INITIALIZEBUF(runningSESE->memoryQueueArray[" + queueID+ "]);");
3999 for (Iterator iterator2 = waitingQueueSet.iterator(); iterator2.hasNext();) {
4000 Analysis.OoOJava.WaitingElement waitingElement
4001 = (Analysis.OoOJava.WaitingElement) iterator2.next();
4002 if (waitingElement.getStatus() >= ConflictNode.COARSE) {
4003 output.println(" rentry=mlpCreateREntry("
4004 + waitingElement.getStatus()
4005 + ", &(seseToIssue->common));");
4007 TempDescriptor td = waitingElement.getTempDesc();
4008 // decide whether waiting element is dynamic or static
4009 if (fsen.getDynamicInVarSet().contains(td)) {
4010 // dynamic in-var case
4011 output.println(" pointer=seseToIssue->"
4012 + waitingElement.getDynID()
4013 + "_srcSESE+seseToIssue->"
4014 + waitingElement.getDynID()
4016 output.println(" rentry=mlpCreateFineREntry("
4017 + waitingElement.getStatus()
4018 + ", &(seseToIssue->common), pointer );");
4019 } else if (fsen.getStaticInVarSet().contains(td)) {
4020 // static in-var case
4021 VariableSourceToken vst = fsen.getStaticInVarSrc(td);
4024 String srcId = "SESE_" + vst.getSESE().getPrettyIdentifier()
4025 + vst.getSESE().getIdentifier()
4026 + "_" + vst.getAge();
4027 output.println(" pointer=(void*)&seseToIssue->"
4033 output.println(" rentry=mlpCreateFineREntry("
4034 + waitingElement.getStatus()
4035 + ", &(seseToIssue->common), pointer );");
4038 output.println(" rentry=mlpCreateFineREntry("
4039 + waitingElement.getStatus()
4040 + ", &(seseToIssue->common), (void*)&seseToIssue->"
4041 + waitingElement.getDynID()
4045 output.println(" rentry->queue=runningSESE->memoryQueueArray["
4046 + waitingElement.getQueueID()
4049 if(enqueueType==SESEWaitingQueue.NORMAL){
4050 output.println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
4051 output.println(" if(ADDRENTRY(runningSESE->memoryQueueArray["
4052 + waitingElement.getQueueID()
4053 + "],rentry)==NOTREADY) {");
4054 output.println(" localCount++;");
4055 output.println(" }");
4057 // Trying to execute the dynamic coarse grain conflict strategy...
4058 if(state.RCR && rcr != null) {
4059 boolean useParentContext = false;
4061 if( (state.MLP &&fsen != mlpa.getMainSESE()) ||
4062 (state.OOOJAVA &&fsen != oooa.getMainSESE())) {
4063 assert fsen.getParent() != null;
4064 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
4065 useParentContext = true;
4069 for (TempDescriptor invar : fsen.getInVarsForDynamicCoarseConflictResolution()) {
4071 if( useParentContext ) {
4072 varString = generateTemp( fsen.getParent().getfmBogus(), invar, null );
4074 varString = generateTemp( fsen.getfmEnclosing(), invar, null );
4076 output.println(" "+rcr.getTraverserInvocation(invar, varString, fsen));
4080 output.println(" ADDRENTRYTOBUF(runningSESE->memoryQueueArray[" + waitingElement.getQueueID() + "],rentry);");
4083 if(enqueueType!=SESEWaitingQueue.NORMAL){
4084 output.println(" localCount+=RESOLVEBUF(runningSESE->memoryQueueArray["
4085 + queueID+ "],&seseToIssue->common);");
4088 output.println(" }");
4093 ConflictGraph graph = null;
4094 FlatSESEEnterNode parent = fsen.getParent();
4095 if (parent != null) {
4096 if (parent.isCallerSESEplaceholder) {
4097 graph = mlpa.getConflictGraphResults().get(parent.getfmEnclosing());
4099 graph = mlpa.getConflictGraphResults().get(parent);
4102 if (graph != null && graph.hasConflictEdge()) {
4103 HashSet<SESELock> seseLockSet = mlpa.getConflictGraphLockMap()
4106 output.println(" //add memory queue element");
4107 SESEWaitingQueue seseWaitingQueue=graph.getWaitingElementSetBySESEID(fsen.getIdentifier(),
4109 if(seseWaitingQueue.getWaitingElementSize()>0){
4110 output.println(" {");
4111 output.println(" REntry* rentry=NULL;");
4112 output.println(" INTPTR* pointer=NULL;");
4113 output.println(" seseToIssue->common.rentryIdx=0;");
4115 Set<Integer> queueIDSet=seseWaitingQueue.getQueueIDSet();
4116 for (Iterator iterator = queueIDSet.iterator(); iterator
4118 Integer key = (Integer) iterator.next();
4119 int queueID=key.intValue();
4120 Set<WaitingElement> waitingQueueSet = seseWaitingQueue.getWaitingElementSet(queueID);
4121 int enqueueType=seseWaitingQueue.getType(queueID);
4122 if(enqueueType==SESEWaitingQueue.EXCEPTION){
4123 output.println(" INITIALIZEBUF(runningSESE->memoryQueueArray["
4126 for (Iterator iterator2 = waitingQueueSet.iterator(); iterator2
4128 WaitingElement waitingElement = (WaitingElement) iterator2
4130 if (waitingElement.getStatus() >= ConflictNode.COARSE) {
4131 output.println(" rentry=mlpCreateREntry("
4132 + waitingElement.getStatus()
4133 + ", &(seseToIssue->common));");
4135 TempDescriptor td = waitingElement
4137 // decide whether waiting element is dynamic or
4139 if (fsen.getDynamicInVarSet().contains(td)) {
4140 // dynamic in-var case
4141 output.println(" pointer=seseToIssue->"
4142 + waitingElement.getDynID()
4143 + "_srcSESE+seseToIssue->"
4144 + waitingElement.getDynID()
4147 .println(" rentry=mlpCreateFineREntry("
4150 + ", &(seseToIssue->common), pointer );");
4151 } else if (fsen.getStaticInVarSet()
4153 // static in-var case
4154 VariableSourceToken vst = fsen
4155 .getStaticInVarSrc(td);
4158 String srcId = "SESE_"
4160 .getPrettyIdentifier()
4161 + vst.getSESE().getIdentifier()
4162 + "_" + vst.getAge();
4164 .println(" pointer=(void*)&seseToIssue->"
4171 .println(" rentry=mlpCreateFineREntry("
4174 + ", &(seseToIssue->common), pointer );");
4179 .println(" rentry=mlpCreateFineREntry("
4182 + ", &(seseToIssue->common), (void*)&seseToIssue->"
4183 + waitingElement.getDynID()
4188 .println(" rentry->queue=runningSESE->memoryQueueArray["
4189 + waitingElement.getQueueID()
4192 if(enqueueType==SESEWaitingQueue.NORMAL){
4194 .println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
4196 .println(" if(ADDRENTRY(runningSESE->memoryQueueArray["
4197 + waitingElement.getQueueID()
4198 + "],rentry)==NOTREADY){");
4199 output.println(" ++(localCount);");
4200 output.println(" } ");
4203 .println(" ADDRENTRYTOBUF(runningSESE->memoryQueueArray["
4204 + waitingElement.getQueueID()
4208 if(enqueueType!=SESEWaitingQueue.NORMAL){
4209 output.println(" localCount+=RESOLVEBUF(runningSESE->memoryQueueArray["
4210 + queueID+ "],&seseToIssue->common);");
4213 output.println(" }");
4220 if( state.COREPROF ) {
4221 output.println("#ifdef CP_EVENTID_PREPAREMEMQ");
4222 output.println(" CP_LOGEVENT( CP_EVENTID_PREPAREMEMQ, CP_EVENTTYPE_END );");
4223 output.println("#endif");
4226 // Enqueue Task Record
4228 output.println(" enqueueTR((void *)seseToIssue);");
4231 // if there were no outstanding dependencies, issue here
4232 output.println(" if( atomic_sub_and_test(10000-localCount,&(seseToIssue->common.unresolvedDependencies) ) ) {");
4233 output.println(" workScheduleSubmit( (void*)seseToIssue );");
4234 output.println(" }");
4238 if( state.COREPROF ) {
4239 output.println("#ifdef CP_EVENTID_TASKDISPATCH");
4240 output.println(" CP_LOGEVENT( CP_EVENTID_TASKDISPATCH, CP_EVENTTYPE_END );");
4241 output.println("#endif");
4244 output.println(" }");
4248 public void generateFlatSESEExitNode( FlatMethod fm,
4250 FlatSESEExitNode fsexn,
4254 // if MLP flag is off, okay that SESE nodes are in IR graph,
4255 // just skip over them and code generates exactly the same
4256 if( ! (state.MLP || state.OOOJAVA) ) {
4260 // get the enter node for this exit that has meta data embedded
4261 FlatSESEEnterNode fsen = fsexn.getFlatEnter();
4263 // there may be an SESE in an unreachable method, skip over
4264 if( (state.MLP && !mlpa.getAllSESEs().contains( fsen )) ||
4265 (state.OOOJAVA && !oooa.getAllSESEs().contains( fsen ))
4270 // also, if we have encountered a placeholder, just jump it
4271 if( fsen.getIsCallerSESEplaceholder() ) {
4275 if( state.COREPROF ) {
4276 output.println("#ifdef CP_EVENTID_TASKEXECUTE");
4277 output.println(" CP_LOGEVENT( CP_EVENTID_TASKEXECUTE, CP_EVENTTYPE_END );");
4278 output.println("#endif");
4281 output.println(" /* SESE exiting */");
4283 if( state.COREPROF ) {
4284 output.println("#ifdef CP_EVENTID_TASKRETIRE");
4285 output.println(" CP_LOGEVENT( CP_EVENTID_TASKRETIRE, CP_EVENTTYPE_BEGIN );");
4286 output.println("#endif");
4289 String com = paramsprefix+"->common";
4291 // this SESE cannot be done until all of its children are done
4292 // so grab your own lock with the condition variable for watching
4293 // that the number of your running children is greater than zero
4294 output.println(" pthread_mutex_lock( &("+com+".lock) );");
4295 output.println(" if ( "+com+".numRunningChildren > 0 ) {");
4296 output.println(" stopforgc((struct garbagelist *)&___locals___);");
4297 output.println(" do {");
4298 output.println(" pthread_cond_wait( &("+com+".runningChildrenCond), &("+com+".lock) );");
4299 output.println(" } while( "+com+".numRunningChildren > 0 );");
4300 output.println(" restartaftergc();");
4301 output.println(" }");
4304 // copy out-set from local temps into the sese record
4305 Iterator<TempDescriptor> itr = fsen.getOutVarSet().iterator();
4306 while( itr.hasNext() ) {
4307 TempDescriptor temp = itr.next();
4309 // only have to do this for primitives non-arrays
4311 temp.getType().isPrimitive() && !temp.getType().isArray()
4317 // have to determine the context enclosing this sese
4318 boolean useParentContext = false;
4320 if( (state.MLP &&fsen != mlpa.getMainSESE()) ||
4321 (state.OOOJAVA &&fsen != oooa.getMainSESE())
4323 assert fsen.getParent() != null;
4324 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
4325 useParentContext = true;
4330 if( useParentContext ) {
4331 from = generateTemp( fsen.getParent().getfmBogus(), temp, null );
4333 from = generateTemp( fsen.getfmEnclosing(), temp, null );
4336 output.println(" "+paramsprefix+
4337 "->"+temp.getSafeSymbol()+
4341 // mark yourself done, your SESE data is now read-only
4342 output.println(" "+com+".doneExecuting = TRUE;");
4343 output.println(" pthread_cond_signal( &("+com+".doneCond) );");
4344 output.println(" pthread_mutex_unlock( &("+com+".lock) );");
4346 // decrement dependency count for all SESE's on your forwarding list
4349 output.println(" while( !isEmpty( "+com+".forwardList ) ) {");
4350 output.println(" SESEcommon* consumer = (SESEcommon*) getItem( "+com+".forwardList );");
4353 output.println(" if(consumer->rentryIdx>0){");
4354 output.println(" // resolved null pointer");
4355 output.println(" int idx;");
4356 output.println(" for(idx=0;idx<consumer->rentryIdx;idx++){");
4357 output.println(" resolvePointer(consumer->rentryArray[idx]);");
4358 output.println(" }");
4359 output.println(" }");
4362 output.println(" if( atomic_sub_and_test(1, &(consumer->unresolvedDependencies)) ){");
4363 output.println(" workScheduleSubmit( (void*)consumer );");
4364 output.println(" }");
4365 output.println(" }");
4369 // clean up its lock element from waiting queue, and decrement dependency count for next SESE block
4370 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
4371 (state.OOOJAVA && fsen != oooa.getMainSESE())
4375 output.println(" /* check memory dependency*/");
4376 output.println(" {");
4377 output.println(" int idx;");
4378 output.println(" for(idx=0;idx<___params___->common.rentryIdx;idx++){");
4379 output.println(" REntry* re=___params___->common.rentryArray[idx];");
4380 output.println(" RETIRERENTRY(re->queue,re);");
4381 output.println(" }");
4382 output.println(" }");
4386 // if parent is stalling on you, let them know you're done
4387 if( (state.MLP && fsexn.getFlatEnter() != mlpa.getMainSESE()) ||
4388 (state.OOOJAVA && fsexn.getFlatEnter() != oooa.getMainSESE())
4390 output.println(" psem_give( &("+paramsprefix+"->common.stallSem) );");
4393 // last of all, decrement your parent's number of running children
4394 output.println(" if( "+paramsprefix+"->common.parent != NULL ) {");
4395 output.println(" if (atomic_sub_and_test(1, &"+paramsprefix+"->common.parent->numRunningChildren)) {");
4396 output.println(" pthread_mutex_lock( &("+paramsprefix+"->common.parent->lock) );");
4397 output.println(" pthread_cond_signal( &("+paramsprefix+"->common.parent->runningChildrenCond) );");
4398 output.println(" pthread_mutex_unlock( &("+paramsprefix+"->common.parent->lock) );");
4399 output.println(" }");
4400 output.println(" }");
4402 // a task has variables to track static/dynamic instances
4403 // that serve as sources, release the parent's ref of each
4404 // non-null var of these types
4405 output.println(" // releasing static SESEs");
4406 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
4407 Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
4408 while( pItr.hasNext() ) {
4409 SESEandAgePair pair = pItr.next();
4410 output.println(" if( "+pair+" != NULL ) {");
4411 output.println(" RELEASE_REFERENCE_TO( "+pair+" );");
4412 output.println(" }");
4414 output.println(" // releasing dynamic variable sources");
4415 Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
4416 while( dynSrcItr.hasNext() ) {
4417 TempDescriptor dynSrcVar = dynSrcItr.next();
4418 output.println(" if( "+dynSrcVar+"_srcSESE != NULL ) {");
4419 output.println(" RELEASE_REFERENCE_TO( "+dynSrcVar+"_srcSESE );");
4420 output.println(" }");
4422 // destroy this task's mempool if it is not a leaf task
4423 if( !fsen.getIsLeafSESE() ) {
4424 output.println(" pooldestroy( runningSESE->taskRecordMemPool );");
4426 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
4429 // if this is not the Main sese (which has no parent) then return
4430 // THIS task's record to the PARENT'S task record pool, and only if
4431 // the reference count is now zero
4432 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
4433 (state.OOOJAVA && fsen != oooa.getMainSESE())
4435 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
4436 output.println(" RELEASE_REFERENCE_TO( runningSESE );");
4437 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
4439 // the main task has no parent, just free its record
4440 output.println(" mlpFreeSESErecord( runningSESE );");
4443 // as this thread is wrapping up the task, make sure the thread-local var
4444 // for the currently running task record references an invalid task
4445 output.println(" runningSESE = (SESEcommon*) 0x1;");
4447 if( state.COREPROF ) {
4448 output.println("#ifdef CP_EVENTID_TASKRETIRE");
4449 output.println(" CP_LOGEVENT( CP_EVENTID_TASKRETIRE, CP_EVENTTYPE_END );");
4450 output.println("#endif");
4454 public void generateFlatWriteDynamicVarNode( FlatMethod fm,
4456 FlatWriteDynamicVarNode fwdvn,
4459 if( !(state.MLP || state.OOOJAVA) ) {
4460 // should node should not be in an IR graph if the
4461 // MLP flag is not set
4462 throw new Error("Unexpected presence of FlatWriteDynamicVarNode");
4465 Hashtable<TempDescriptor, VSTWrapper> writeDynamic = fwdvn.getVar2src();
4467 assert writeDynamic != null;
4469 Iterator wdItr = writeDynamic.entrySet().iterator();
4470 while( wdItr.hasNext() ) {
4471 Map.Entry me = (Map.Entry) wdItr.next();
4472 TempDescriptor refVar = (TempDescriptor) me.getKey();
4473 VSTWrapper vstW = (VSTWrapper) me.getValue();
4474 VariableSourceToken vst = vstW.vst;
4476 output.println(" {");
4477 output.println(" SESEcommon* oldSrc = "+refVar+"_srcSESE;");
4480 // if there is no given source, this variable is ready so
4481 // mark src pointer NULL to signify that the var is up-to-date
4482 output.println(" "+refVar+"_srcSESE = NULL;");
4484 // otherwise we track where it will come from
4485 SESEandAgePair instance = new SESEandAgePair( vst.getSESE(), vst.getAge() );
4486 output.println(" "+refVar+"_srcSESE = "+instance+";");
4487 output.println(" "+refVar+"_srcOffset = (INTPTR) &((("+
4488 vst.getSESE().getSESErecordName()+"*)0)->"+vst.getAddrVar()+");");
4491 // no matter what we did above, track reference count of whatever
4492 // this variable pointed to, do release last in case we're just
4493 // copying the same value in because 1->2->1 is safe but ref count
4494 // 1->0->1 has a window where it looks like it should be free'd
4495 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
4496 output.println(" if( "+refVar+"_srcSESE != NULL ) {");
4497 output.println(" ADD_REFERENCE_TO( "+refVar+"_srcSESE );");
4498 output.println(" }");
4499 output.println(" if( oldSrc != NULL ) {");
4500 output.println(" RELEASE_REFERENCE_TO( oldSrc );");
4501 output.println(" }");
4502 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
4504 output.println(" }");
4509 private void generateFlatCheckNode(FlatMethod fm, LocalityBinding lb, FlatCheckNode fcn, PrintWriter output) {
4510 if (state.CONSCHECK) {
4511 String specname=fcn.getSpec();
4512 String varname="repairstate___";
4513 output.println("{");
4514 output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
4516 TempDescriptor[] temps=fcn.getTemps();
4517 String[] vars=fcn.getVars();
4518 for(int i=0; i<temps.length; i++) {
4519 output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i],lb)+";");
4522 output.println("if (doanalysis"+specname+"("+varname+")) {");
4523 output.println("free"+specname+"_state("+varname+");");
4524 output.println("} else {");
4525 output.println("/* Bad invariant */");
4526 output.println("free"+specname+"_state("+varname+");");
4527 output.println("abort_task();");
4528 output.println("}");
4529 output.println("}");
4533 private void generateFlatCall(FlatMethod fm, LocalityBinding lb, FlatCall fc, PrintWriter output) {
4535 MethodDescriptor md=fc.getMethod();
4536 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? locality.getBinding(lb, fc) : md);
4537 ClassDescriptor cn=md.getClassDesc();
4538 output.println("{");
4539 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4541 LocalityBinding fclb=locality.getBinding(lb, fc);
4542 output.print(" struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
4544 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
4545 output.print(objectparams.numPointers());
4546 output.print(", "+localsprefixaddr);
4547 if (md.getThis()!=null) {
4549 output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis(),lb));
4551 if (fc.getThis()!=null&&md.getThis()==null) {
4552 System.out.println("WARNING!!!!!!!!!!!!");
4553 System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
4557 for(int i=0; i<fc.numArgs(); i++) {
4558 Descriptor var=md.getParameter(i);
4559 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
4560 if (objectparams.isParamPtr(paramtemp)) {
4561 TempDescriptor targ=fc.getArg(i);
4563 TypeDescriptor td=md.getParamType(i);
4565 output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
4567 output.print("(struct "+md.getParamType(i).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
4570 output.println("};");
4575 if (fc.getReturnTemp()!=null)
4576 output.print(generateTemp(fm,fc.getReturnTemp(),lb)+"=");
4578 /* Do we need to do virtual dispatch? */
4579 if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
4582 LocalityBinding fclb=locality.getBinding(lb, fc);
4583 output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
4585 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
4590 if (md.getReturnType().isClass()||md.getReturnType().isArray())
4591 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
4593 output.print(md.getReturnType().getSafeSymbol()+" ");
4594 output.print("(*)(");
4596 boolean printcomma=false;
4597 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4599 LocalityBinding fclb=locality.getBinding(lb, fc);
4600 output.print("struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
4602 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
4606 for(int i=0; i<objectparams.numPrimitives(); i++) {
4607 TempDescriptor temp=objectparams.getPrimitive(i);
4611 if (temp.getType().isClass()||temp.getType().isArray())
4612 output.print("struct " + temp.getType().getSafeSymbol()+" * ");
4614 output.print(temp.getType().getSafeSymbol());
4619 LocalityBinding fclb=locality.getBinding(lb, fc);
4620 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])");
4622 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
4626 boolean needcomma=false;
4627 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4628 output.print("&__parameterlist__");
4632 if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
4633 if (fc.getThis()!=null) {
4634 TypeDescriptor ptd=md.getThis().getType();
4637 if (ptd.isClass()&&!ptd.isArray())
4638 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
4639 output.print(generateTemp(fm,fc.getThis(),lb));
4644 for(int i=0; i<fc.numArgs(); i++) {
4645 Descriptor var=md.getParameter(i);
4646 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
4647 if (objectparams.isParamPrim(paramtemp)) {
4648 TempDescriptor targ=fc.getArg(i);
4652 TypeDescriptor ptd=md.getParamType(i);
4653 if (ptd.isClass()&&!ptd.isArray())
4654 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
4655 output.print(generateTemp(fm, targ,lb));
4659 output.println(");");
4660 output.println(" }");
4663 private boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
4664 Set subclasses=typeutil.getSubClasses(thiscd);
4665 if (subclasses==null)
4667 for(Iterator classit=subclasses.iterator(); classit.hasNext();) {
4668 ClassDescriptor cd=(ClassDescriptor)classit.next();
4669 Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol());
4670 for(Iterator matchit=possiblematches.iterator(); matchit.hasNext();) {
4671 MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
4672 if (md.matches(matchmd))
4679 private void generateFlatFieldNode(FlatMethod fm, LocalityBinding lb, FlatFieldNode ffn, PrintWriter output) {
4680 if (state.SINGLETM) {
4681 //single machine transactional memory case
4682 String field=ffn.getField().getSafeSymbol();
4683 String src=generateTemp(fm, ffn.getSrc(),lb);
4684 String dst=generateTemp(fm, ffn.getDst(),lb);
4686 output.println(dst+"="+ src +"->"+field+ ";");
4687 if (ffn.getField().getType().isPtr()&&locality.getAtomic(lb).get(ffn).intValue()>0&&
4688 locality.getNodePreTempInfo(lb, ffn).get(ffn.getSrc())!=LocalityAnalysis.SCRATCH) {
4689 if ((dc==null)||(!state.READSET&&dc.getNeedTrans(lb, ffn))||
4690 (state.READSET&&dc.getNeedWriteTrans(lb, ffn))) {
4691 output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));");
4692 } else if (state.READSET&&dc.getNeedTrans(lb, ffn)) {
4693 if (state.HYBRID&&delaycomp.getConv(lb).contains(ffn)) {
4694 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4696 output.println("TRANSREADRD("+dst+", "+dst+");");
4699 } else if (state.DSM) {
4700 Integer status=locality.getNodePreTempInfo(lb,ffn).get(ffn.getSrc());
4701 if (status==LocalityAnalysis.GLOBAL) {
4702 String field=ffn.getField().getSafeSymbol();
4703 String src=generateTemp(fm, ffn.getSrc(),lb);
4704 String dst=generateTemp(fm, ffn.getDst(),lb);
4706 if (ffn.getField().getType().isPtr()) {
4708 //TODO: Uncomment this when we have runtime support
4709 //if (ffn.getSrc()==ffn.getDst()) {
4710 //output.println("{");
4711 //output.println("void * temp="+src+";");
4712 //output.println("if (temp&0x1) {");
4713 //output.println("temp=(void *) transRead(trans, (unsigned int) temp);");
4714 //output.println(src+"->"+field+"="+temp+";");
4715 //output.println("}");
4716 //output.println(dst+"=temp;");
4717 //output.println("}");
4719 output.println(dst+"="+ src +"->"+field+ ";");
4720 //output.println("if ("+dst+"&0x1) {");
4721 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
4722 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
4723 //output.println(src+"->"+field+"="+src+"->"+field+";");
4724 //output.println("}");
4727 output.println(dst+"="+ src+"->"+field+";");
4729 } else if (status==LocalityAnalysis.LOCAL) {
4730 if (ffn.getField().getType().isPtr()&&
4731 ffn.getField().isGlobal()) {
4732 String field=ffn.getField().getSafeSymbol();
4733 String src=generateTemp(fm, ffn.getSrc(),lb);
4734 String dst=generateTemp(fm, ffn.getDst(),lb);
4735 output.println(dst+"="+ src +"->"+field+ ";");
4736 if (locality.getAtomic(lb).get(ffn).intValue()>0)
4737 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
4738 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
4740 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4741 } else if (status==LocalityAnalysis.EITHER) {
4742 //Code is reading from a null pointer
4743 output.println("if ("+generateTemp(fm, ffn.getSrc(),lb)+") {");
4744 output.println("#ifndef RAW");
4745 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4746 output.println("#endif");
4747 //This should throw a suitable null pointer error
4748 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4750 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4752 // DEBUG if(!ffn.getDst().getType().isPrimitive()){
4753 // DEBUG output.println("within((void*)"+generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+");");
4755 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4760 private void generateFlatSetFieldNode(FlatMethod fm, LocalityBinding lb, FlatSetFieldNode fsfn, PrintWriter output) {
4761 if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
4762 throw new Error("Can't set array length");
4763 if (state.SINGLETM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
4764 //Single Machine Transaction Case
4765 boolean srcptr=fsfn.getSrc().getType().isPtr();
4766 String src=generateTemp(fm,fsfn.getSrc(),lb);
4767 String dst=generateTemp(fm,fsfn.getDst(),lb);
4768 output.println("//"+srcptr+" "+fsfn.getSrc().getType().isNull());
4769 if (srcptr&&!fsfn.getSrc().getType().isNull()) {
4770 output.println("{");
4771 if ((dc==null)||dc.getNeedSrcTrans(lb, fsfn)&&
4772 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) {
4773 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4775 output.println("INTPTR srcoid=(INTPTR)"+src+";");
4778 if (wb.needBarrier(fsfn)&&
4779 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getDst())!=LocalityAnalysis.SCRATCH) {
4780 if (state.EVENTMONITOR) {
4781 output.println("if ("+dst+"->___objstatus___&DIRTY) EVLOGEVENTOBJ(EV_WRITE,"+dst+"->objuid)");
4783 output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;");
4785 if (srcptr&!fsfn.getSrc().getType().isNull()) {
4786 output.println("*((unsigned INTPTR *)&("+dst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4787 output.println("}");
4789 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4791 } else if (state.DSM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
4792 Integer statussrc=locality.getNodePreTempInfo(lb,fsfn).get(fsfn.getSrc());
4793 Integer statusdst=locality.getNodeTempInfo(lb).get(fsfn).get(fsfn.getDst());
4794 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4796 String src=generateTemp(fm,fsfn.getSrc(),lb);
4797 String dst=generateTemp(fm,fsfn.getDst(),lb);
4799 output.println("{");
4800 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4802 if (statusdst.equals(LocalityAnalysis.GLOBAL)) {
4805 if (wb.needBarrier(fsfn))
4806 output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;");
4808 output.println("*((unsigned INTPTR *)&("+glbdst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4810 output.println(glbdst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4811 } else if (statusdst.equals(LocalityAnalysis.LOCAL)) {
4812 /** Check if we need to copy */
4813 output.println("if(!"+dst+"->"+localcopystr+") {");
4814 /* Link object into list */
4815 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4816 output.println(revertptr+"=revertlist;");
4817 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4818 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4820 output.println("COPY_OBJ("+dst+");");
4821 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4822 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4823 output.println("}");
4825 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4827 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4828 } else if (statusdst.equals(LocalityAnalysis.EITHER)) {
4829 //writing to a null...bad
4830 output.println("if ("+dst+") {");
4831 output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}");
4833 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4835 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4838 output.println("}");
4841 if (state.FASTCHECK) {
4842 String dst=generateTemp(fm, fsfn.getDst(),lb);
4843 output.println("if(!"+dst+"->"+localcopystr+") {");
4844 /* Link object into list */
4845 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4846 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4848 output.println("COPY_OBJ("+dst+");");
4849 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4850 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4851 output.println("}");
4854 // DEBUG if(!fsfn.getField().getType().isPrimitive()){
4855 // DEBUG output.println("within((void*)"+generateTemp(fm,fsfn.getSrc(),lb)+");");
4857 output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
4861 private void generateFlatElementNode(FlatMethod fm, LocalityBinding lb, FlatElementNode fen, PrintWriter output) {
4862 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
4865 if (elementtype.isArray()||elementtype.isClass())
4868 type=elementtype.getSafeSymbol()+" ";
4870 if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
4871 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fen.getIndex(),lb)+") >= "+generateTemp(fm,fen.getSrc(),lb) + "->___length___))");
4872 output.println("failedboundschk();");
4874 if (state.SINGLETM) {
4875 //Single machine transaction case
4876 String dst=generateTemp(fm, fen.getDst(),lb);
4877 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))) {
4878 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4880 output.println("STMGETARRAY("+dst+", "+ generateTemp(fm,fen.getSrc(),lb)+", "+generateTemp(fm, fen.getIndex(),lb)+", "+type+");");
4883 if (elementtype.isPtr()&&locality.getAtomic(lb).get(fen).intValue()>0&&
4884 locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())!=LocalityAnalysis.SCRATCH) {
4885 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fen)||state.READSET&&dc.getNeedWriteTrans(lb, fen)) {
4886 output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));");
4887 } else if (state.READSET&&dc.getNeedTrans(lb, fen)) {
4888 if (state.HYBRID&&delaycomp.getConv(lb).contains(fen)) {
4889 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4891 output.println("TRANSREADRD("+dst+", "+dst+");");
4894 } else if (state.DSM) {
4895 Integer status=locality.getNodePreTempInfo(lb,fen).get(fen.getSrc());
4896 if (status==LocalityAnalysis.GLOBAL) {
4897 String dst=generateTemp(fm, fen.getDst(),lb);
4898 if (elementtype.isPtr()) {
4899 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4900 //DEBUG: output.println("TRANSREAD("+dst+", "+dst+",\""+fm+":"+fen+"\");");
4901 output.println("TRANSREAD("+dst+", "+dst+");");
4903 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4905 } else if (status==LocalityAnalysis.LOCAL) {
4906 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4907 } else if (status==LocalityAnalysis.EITHER) {
4908 //Code is reading from a null pointer
4909 output.println("if ("+generateTemp(fm, fen.getSrc(),lb)+") {");
4910 output.println("#ifndef RAW");
4911 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4912 output.println("#endif");
4913 //This should throw a suitable null pointer error
4914 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4916 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4918 // DEBUG output.println("within((void*)"+generateTemp(fm,fen.getSrc(),lb)+");");
4919 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4923 private void generateFlatSetElementNode(FlatMethod fm, LocalityBinding lb, FlatSetElementNode fsen, PrintWriter output) {
4924 //TODO: need dynamic check to make sure this assignment is actually legal
4925 //Because Object[] could actually be something more specific...ie. Integer[]
4927 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
4930 if (elementtype.isArray()||elementtype.isClass())
4933 type=elementtype.getSafeSymbol()+" ";
4935 if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
4936 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fsen.getIndex(),lb)+") >= "+generateTemp(fm,fsen.getDst(),lb) + "->___length___))");
4937 output.println("failedboundschk();");
4940 if (state.SINGLETM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4941 //Transaction set element case
4942 if (wb.needBarrier(fsen)&&
4943 locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH) {
4944 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___objstatus___))|=DIRTY;");
4946 if (fsen.getSrc().getType().isPtr()&&!fsen.getSrc().getType().isNull()) {
4947 output.println("{");
4948 String src=generateTemp(fm, fsen.getSrc(), lb);
4949 if ((dc==null)||dc.getNeedSrcTrans(lb, fsen)&&
4950 locality.getNodePreTempInfo(lb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) {
4951 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4953 output.println("INTPTR srcoid=(INTPTR)"+src+";");
4955 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
4956 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", srcoid, INTPTR);");
4958 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
4960 output.println("}");
4962 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
4963 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", "+ generateTemp(fm, fsen.getSrc(), lb) +", "+type+");");
4965 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4968 } else if (state.DSM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4969 Integer statussrc=locality.getNodePreTempInfo(lb,fsen).get(fsen.getSrc());
4970 Integer statusdst=locality.getNodePreTempInfo(lb,fsen).get(fsen.getDst());
4971 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4972 boolean dstglobal=statusdst==LocalityAnalysis.GLOBAL;
4973 boolean dstlocal=(statusdst==LocalityAnalysis.LOCAL)||(statusdst==LocalityAnalysis.EITHER);
4976 if (wb.needBarrier(fsen))
4977 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___localcopy___))|=DIRTY;");
4978 } else if (dstlocal) {
4979 /** Check if we need to copy */
4980 String dst=generateTemp(fm, fsen.getDst(),lb);
4981 output.println("if(!"+dst+"->"+localcopystr+") {");
4982 /* Link object into list */
4983 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4984 output.println(revertptr+"=revertlist;");
4985 if ((GENERATEPRECISEGC) || this.state.MULTICOREGC)
4986 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4988 output.println("COPY_OBJ("+dst+");");
4989 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4990 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4991 output.println("}");
4993 System.out.println("Node: "+fsen);
4994 System.out.println(lb);
4995 System.out.println("statusdst="+statusdst);
4996 System.out.println(fm.printMethod());
4997 throw new Error("Unknown array type");
5000 output.println("{");
5001 String src=generateTemp(fm, fsen.getSrc(), lb);
5002 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
5003 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
5004 output.println("}");
5006 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
5009 if (state.FASTCHECK) {
5010 String dst=generateTemp(fm, fsen.getDst(),lb);
5011 output.println("if(!"+dst+"->"+localcopystr+") {");
5012 /* Link object into list */
5013 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
5014 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
5016 output.println("COPY_OBJ("+dst+");");
5017 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
5018 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
5019 output.println("}");
5021 // DEBUG output.println("within((void*)"+generateTemp(fm,fsen.getDst(),lb)+");");
5022 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
5026 protected void generateFlatNew(FlatMethod fm, LocalityBinding lb, FlatNew fn, PrintWriter output) {
5027 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
5028 //Stash pointer in case of GC
5029 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5030 output.println(revertptr+"=revertlist;");
5032 if (state.SINGLETM) {
5033 if (fn.getType().isArray()) {
5034 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
5035 if (locality.getAtomic(lb).get(fn).intValue()>0) {
5036 //inside transaction
5037 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
5039 //outside transaction
5040 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
5043 if (locality.getAtomic(lb).get(fn).intValue()>0) {
5044 //inside transaction
5045 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
5047 //outside transaction
5048 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
5051 } else if (fn.getType().isArray()) {
5052 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
5053 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
5054 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
5055 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5056 if(this.state.MLP || state.OOOJAVA){
5057 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray_mlp("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+", oid, "+oooa.getDisjointAnalysis().getAllocationSiteFromFlatNew(fn).getUniqueAllocSiteID()+");");
5058 output.println(" oid += numWorkers;");
5060 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
5063 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
5066 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
5067 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");");
5068 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5069 if (this.state.MLP || state.OOOJAVA){
5070 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new_mlp("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+", oid, "+oooa.getDisjointAnalysis().getAllocationSiteFromFlatNew(fn).getUniqueAllocSiteID()+");");
5071 output.println(" oid += numWorkers;");
5073 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
5076 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
5079 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
5080 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5081 String dst=generateTemp(fm,fn.getDst(),lb);
5082 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
5083 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
5084 output.println("revertlist=(struct ___Object___ *)"+dst+";");
5086 if (state.FASTCHECK) {
5087 String dst=generateTemp(fm,fn.getDst(),lb);
5088 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
5089 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
5090 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
5094 private void generateFlatTagDeclaration(FlatMethod fm, LocalityBinding lb, FlatTagDeclaration fn, PrintWriter output) {
5095 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5096 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
5098 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+state.getTagId(fn.getType())+");");
5102 private void generateFlatOpNode(FlatMethod fm, LocalityBinding lb, FlatOpNode fon, PrintWriter output) {
5103 if (fon.getRight()!=null) {
5104 if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
5105 if (fon.getLeft().getType().isLong())
5106 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
5108 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned int)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
5110 } else if (dc!=null) {
5111 output.print(generateTemp(fm, fon.getDest(),lb)+" = (");
5112 if (fon.getLeft().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
5113 output.print("(void *)");
5114 if (dc.getNeedLeftSrcTrans(lb, fon))
5115 output.print("("+generateTemp(fm, fon.getLeft(),lb)+"!=NULL?"+generateTemp(fm, fon.getLeft(),lb)+"->"+oidstr+":NULL)");
5117 output.print(generateTemp(fm, fon.getLeft(),lb));
5118 output.print(")"+fon.getOp().toString()+"(");
5119 if (fon.getRight().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
5120 output.print("(void *)");
5121 if (dc.getNeedRightSrcTrans(lb, fon))
5122 output.println("("+generateTemp(fm, fon.getRight(),lb)+"!=NULL?"+generateTemp(fm, fon.getRight(),lb)+"->"+oidstr+":NULL));");
5124 output.println(generateTemp(fm,fon.getRight(),lb)+");");
5126 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+fon.getOp().toString()+generateTemp(fm,fon.getRight(),lb)+";");
5127 } else if (fon.getOp().getOp()==Operation.ASSIGN)
5128 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
5129 else if (fon.getOp().getOp()==Operation.UNARYPLUS)
5130 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
5131 else if (fon.getOp().getOp()==Operation.UNARYMINUS)
5132 output.println(generateTemp(fm, fon.getDest(),lb)+" = -"+generateTemp(fm, fon.getLeft(),lb)+";");
5133 else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
5134 output.println(generateTemp(fm, fon.getDest(),lb)+" = !"+generateTemp(fm, fon.getLeft(),lb)+";");
5135 else if (fon.getOp().getOp()==Operation.COMP)
5136 output.println(generateTemp(fm, fon.getDest(),lb)+" = ~"+generateTemp(fm, fon.getLeft(),lb)+";");
5137 else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
5138 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+"->fses==NULL;");
5140 output.println(generateTemp(fm, fon.getDest(),lb)+fon.getOp().toString()+generateTemp(fm, fon.getLeft(),lb)+";");
5143 private void generateFlatCastNode(FlatMethod fm, LocalityBinding lb, FlatCastNode fcn, PrintWriter output) {
5144 /* TODO: Do type check here */
5145 if (fcn.getType().isArray()) {
5146 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
5147 } else if (fcn.getType().isClass())
5148 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
5150 output.println(generateTemp(fm,fcn.getDst(),lb)+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc(),lb)+";");
5153 private void generateFlatLiteralNode(FlatMethod fm, LocalityBinding lb, FlatLiteralNode fln, PrintWriter output) {
5154 if (fln.getValue()==null)
5155 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
5156 else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
5157 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5158 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
5159 //Stash pointer in case of GC
5160 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5161 output.println(revertptr+"=revertlist;");
5163 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
5164 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
5165 //Stash pointer in case of GC
5166 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5167 output.println("revertlist="+revertptr+";");
5170 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
5172 } else if (fln.getType().isBoolean()) {
5173 if (((Boolean)fln.getValue()).booleanValue())
5174 output.println(generateTemp(fm, fln.getDst(),lb)+"=1;");
5176 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
5177 } else if (fln.getType().isChar()) {
5178 String st=FlatLiteralNode.escapeString(fln.getValue().toString());
5179 output.println(generateTemp(fm, fln.getDst(),lb)+"='"+st+"';");
5180 } else if (fln.getType().isLong()) {
5181 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+"LL;");
5183 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+";");
5186 protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) {
5187 if (frn.getReturnTemp()!=null) {
5188 if (frn.getReturnTemp().getType().isPtr())
5189 output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";");
5191 output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";");
5193 output.println("return;");
5197 protected void generateStoreFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
5200 //only record if this group has more than one exit
5201 if (branchanalysis.numJumps(fcb)>1) {
5202 left=branchanalysis.jumpValue(fcb, 0);
5203 right=branchanalysis.jumpValue(fcb, 1);
5205 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") {");
5207 output.println("STOREBRANCH("+right+");");
5208 output.println("goto "+label+";");
5209 output.println("}");
5211 output.println("STOREBRANCH("+left+");");
5214 protected void generateFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
5215 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") goto "+label+";");
5218 /** This method generates header information for the method or
5219 * task referenced by the Descriptor des. */
5220 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) {
5221 generateHeader(fm, lb, des, output, false);
5224 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output, boolean addSESErecord) {
5226 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : des);
5227 MethodDescriptor md=null;
5228 TaskDescriptor task=null;
5229 if (des instanceof MethodDescriptor)
5230 md=(MethodDescriptor) des;
5232 task=(TaskDescriptor) des;
5234 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
5236 if (md!=null&&md.getReturnType()!=null) {
5237 if (md.getReturnType().isClass()||md.getReturnType().isArray())
5238 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
5240 output.print(md.getReturnType().getSafeSymbol()+" ");
5242 //catch the constructor case
5243 output.print("void ");
5245 if (state.DSM||state.SINGLETM) {
5246 output.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
5248 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
5250 output.print(task.getSafeSymbol()+"(");
5252 boolean printcomma=false;
5253 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5255 if (state.DSM||state.SINGLETM) {
5256 output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
5258 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
5260 output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
5266 for(int i=0; i<objectparams.numPrimitives(); i++) {
5267 TempDescriptor temp=objectparams.getPrimitive(i);
5271 if (temp.getType().isClass()||temp.getType().isArray())
5272 output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
5274 output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
5276 output.println(") {");
5277 } else if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
5278 /* Imprecise Task */
5279 output.println("void * parameterarray[]) {");
5280 /* Unpack variables */
5281 for(int i=0; i<objectparams.numPrimitives(); i++) {
5282 TempDescriptor temp=objectparams.getPrimitive(i);
5283 output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
5285 for(int i=0; i<fm.numTags(); i++) {
5286 TempDescriptor temp=fm.getTag(i);
5287 int offset=i+objectparams.numPrimitives();
5288 output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
5291 if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
5292 maxtaskparams=objectparams.numPrimitives()+fm.numTags();
5293 } else output.println(") {");
5296 public void generateFlatFlagActionNode(FlatMethod fm, LocalityBinding lb, FlatFlagActionNode ffan, PrintWriter output) {
5297 output.println("/* FlatFlagActionNode */");
5300 /* Process tag changes */
5301 Relation tagsettable=new Relation();
5302 Relation tagcleartable=new Relation();
5304 Iterator tagsit=ffan.getTempTagPairs();
5305 while (tagsit.hasNext()) {
5306 TempTagPair ttp=(TempTagPair) tagsit.next();
5307 TempDescriptor objtmp=ttp.getTemp();
5308 TagDescriptor tag=ttp.getTag();
5309 TempDescriptor tagtmp=ttp.getTagTemp();
5310 boolean tagstatus=ffan.getTagChange(ttp);
5312 tagsettable.put(objtmp, tagtmp);
5314 tagcleartable.put(objtmp, tagtmp);
5319 Hashtable flagandtable=new Hashtable();
5320 Hashtable flagortable=new Hashtable();
5322 /* Process flag changes */
5323 Iterator flagsit=ffan.getTempFlagPairs();
5324 while(flagsit.hasNext()) {
5325 TempFlagPair tfp=(TempFlagPair)flagsit.next();
5326 TempDescriptor temp=tfp.getTemp();
5327 Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
5328 FlagDescriptor flag=tfp.getFlag();
5330 //Newly allocate objects that don't set any flags case
5331 if (flagortable.containsKey(temp)) {
5335 flagortable.put(temp,new Integer(mask));
5337 int flagid=1<<((Integer)flagtable.get(flag)).intValue();
5338 boolean flagstatus=ffan.getFlagChange(tfp);
5341 if (flagortable.containsKey(temp)) {
5342 mask=((Integer)flagortable.get(temp)).intValue();
5345 flagortable.put(temp,new Integer(mask));
5347 int mask=0xFFFFFFFF;
5348 if (flagandtable.containsKey(temp)) {
5349 mask=((Integer)flagandtable.get(temp)).intValue();
5351 mask&=(0xFFFFFFFF^flagid);
5352 flagandtable.put(temp,new Integer(mask));
5358 HashSet flagtagset=new HashSet();
5359 flagtagset.addAll(flagortable.keySet());
5360 flagtagset.addAll(flagandtable.keySet());
5361 flagtagset.addAll(tagsettable.keySet());
5362 flagtagset.addAll(tagcleartable.keySet());
5364 Iterator ftit=flagtagset.iterator();
5365 while(ftit.hasNext()) {
5366 TempDescriptor temp=(TempDescriptor)ftit.next();
5369 Set tagtmps=tagcleartable.get(temp);
5370 if (tagtmps!=null) {
5371 Iterator tagit=tagtmps.iterator();
5372 while(tagit.hasNext()) {
5373 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
5374 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
5375 output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5377 output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5381 tagtmps=tagsettable.get(temp);
5382 if (tagtmps!=null) {
5383 Iterator tagit=tagtmps.iterator();
5384 while(tagit.hasNext()) {
5385 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
5386 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
5387 output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5389 output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp, lb)+", "+generateTemp(fm,tagtmp, lb)+");");
5394 int andmask=0xFFFFFFF;
5396 if (flagortable.containsKey(temp))
5397 ormask=((Integer)flagortable.get(temp)).intValue();
5398 if (flagandtable.containsKey(temp))
5399 andmask=((Integer)flagandtable.get(temp)).intValue();
5400 generateFlagOrAnd(ffan, fm, lb, temp, output, ormask, andmask);
5401 generateObjectDistribute(ffan, fm, lb, temp, output);
5405 protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp,
5406 PrintWriter output, int ormask, int andmask) {
5407 if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
5408 output.println("flagorandinit("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
5410 output.println("flagorand("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
5414 protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, PrintWriter output) {
5415 output.println("enqueueObject("+generateTemp(fm, temp, lb)+");");
5418 void generateOptionalHeader(PrintWriter headers) {
5421 headers.println("#include \"task.h\"\n\n");
5422 headers.println("#ifndef _OPTIONAL_STRUCT_");
5423 headers.println("#define _OPTIONAL_STRUCT_");
5425 //STRUCT PREDICATEMEMBER
5426 headers.println("struct predicatemember{");
5427 headers.println("int type;");
5428 headers.println("int numdnfterms;");
5429 headers.println("int * flags;");
5430 headers.println("int numtags;");
5431 headers.println("int * tags;\n};\n\n");
5433 //STRUCT OPTIONALTASKDESCRIPTOR
5434 headers.println("struct optionaltaskdescriptor{");
5435 headers.println("struct taskdescriptor * task;");
5436 headers.println("int index;");
5437 headers.println("int numenterflags;");
5438 headers.println("int * enterflags;");
5439 headers.println("int numpredicatemembers;");
5440 headers.println("struct predicatemember ** predicatememberarray;");
5441 headers.println("};\n\n");
5443 //STRUCT TASKFAILURE
5444 headers.println("struct taskfailure {");
5445 headers.println("struct taskdescriptor * task;");
5446 headers.println("int index;");
5447 headers.println("int numoptionaltaskdescriptors;");
5448 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
5450 //STRUCT FSANALYSISWRAPPER
5451 headers.println("struct fsanalysiswrapper{");
5452 headers.println("int flags;");
5453 headers.println("int numtags;");
5454 headers.println("int * tags;");
5455 headers.println("int numtaskfailures;");
5456 headers.println("struct taskfailure ** taskfailurearray;");
5457 headers.println("int numoptionaltaskdescriptors;");
5458 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
5460 //STRUCT CLASSANALYSISWRAPPER
5461 headers.println("struct classanalysiswrapper{");
5462 headers.println("int type;");
5463 headers.println("int numotd;");
5464 headers.println("struct optionaltaskdescriptor ** otdarray;");
5465 headers.println("int numfsanalysiswrappers;");
5466 headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
5468 headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
5470 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
5471 while(taskit.hasNext()) {
5472 TaskDescriptor td=(TaskDescriptor)taskit.next();
5473 headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
5478 //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
5479 int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
5480 int predicateindex = 0;
5481 //iterate through the classes concerned by the predicate
5482 Set c_vard = predicate.vardescriptors;
5483 Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
5486 for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext();) {
5487 VarDescriptor vard = (VarDescriptor)vard_it.next();
5488 TypeDescriptor typed = vard.getType();
5490 //generate for flags
5491 HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
5492 output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5494 if (fen_hashset!=null) {
5495 for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext();) {
5496 FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
5498 DNFFlag dflag=fen.getDNF();
5499 numberterms+=dflag.size();
5501 Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
5503 for(int j=0; j<dflag.size(); j++) {
5505 output.println(",");
5506 Vector term=dflag.get(j);
5509 for(int k=0; k<term.size(); k++) {
5510 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
5511 FlagDescriptor fd=dfa.getFlag();
5512 boolean negated=dfa.getNegated();
5513 int flagid=1<<((Integer)flags.get(fd)).intValue();
5518 output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
5523 output.println("};\n");
5526 TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
5527 output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5530 for(int j=0; j<tagel.numTags(); j++) {
5532 output.println(",");
5533 TempDescriptor tmp=tagel.getTemp(j);
5534 if (!slotnumber.containsKey(tmp)) {
5535 Integer slotint=new Integer(current_slot++);
5536 slotnumber.put(tmp,slotint);
5538 int slot=slotnumber.get(tmp).intValue();
5539 output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
5541 numtags = tagel.numTags();
5543 output.println("};");
5545 //store the result into a predicatemember struct
5546 output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
5547 output.println("/*type*/"+typed.getClassDesc().getId()+",");
5548 output.println("/* number of dnf terms */"+numberterms+",");
5549 output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5550 output.println("/* number of tag */"+numtags+",");
5551 output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5552 output.println("};\n");
5557 //generate an array that stores the entire predicate
5558 output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5559 for( int j = 0; j<predicateindex; j++) {
5560 if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5561 else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5563 output.println("};\n");
5564 return predicateindex;
5568 void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
5569 generateOptionalHeader(headers);
5571 output.println("#include \"optionalstruct.h\"\n\n");
5572 output.println("#include \"stdlib.h\"\n");
5574 HashSet processedcd = new HashSet();
5576 Enumeration e = safeexecution.keys();
5577 while (e.hasMoreElements()) {
5580 ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
5581 Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp); //will be used several times
5583 //Generate the struct of optionals
5584 Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
5585 numotd = c_otd.size();
5586 if(maxotd<numotd) maxotd = numotd;
5587 if( !c_otd.isEmpty() ) {
5588 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
5589 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
5591 //generate the int arrays for the predicate
5592 Predicate predicate = otd.predicate;
5593 int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
5594 TreeSet<Integer> fsset=new TreeSet<Integer>();
5595 //iterate through possible FSes corresponding to
5596 //the state when entering
5598 for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext();) {
5599 FlagState fs = (FlagState)fses.next();
5601 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
5602 FlagDescriptor flagd = (FlagDescriptor)flags.next();
5603 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
5606 fsset.add(new Integer(flagid));
5607 //tag information not needed because tag
5608 //changes are not tolerated.
5611 output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5612 boolean needcomma=false;
5613 for(Iterator<Integer> it=fsset.iterator(); it.hasNext();) {
5616 output.println(it.next());
5619 output.println("};\n");
5622 //generate optionaltaskdescriptor that actually
5623 //includes exit fses, predicate and the task
5625 output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
5626 output.println("&task_"+otd.td.getSafeSymbol()+",");
5627 output.println("/*index*/"+otd.getIndex()+",");
5628 output.println("/*number of enter flags*/"+fsset.size()+",");
5629 output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5630 output.println("/*number of members */"+predicateindex+",");
5631 output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5632 output.println("};\n");
5636 // if there are no optionals, there is no need to build the rest of the struct
5638 output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
5639 c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
5640 if( !c_otd.isEmpty() ) {
5641 boolean needcomma=false;
5642 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
5643 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
5645 output.println(",");
5647 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5650 output.println("};\n");
5652 //get all the possible flagstates reachable by an object
5653 Hashtable hashtbtemp = safeexecution.get(cdtemp);
5655 TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
5656 fsts.addAll(hashtbtemp.keySet());
5657 for(Iterator fsit=fsts.iterator(); fsit.hasNext();) {
5658 FlagState fs = (FlagState)fsit.next();
5661 //get the set of OptionalTaskDescriptors corresponding
5662 HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
5663 //iterate through the OptionalTaskDescriptors and
5664 //store the pointers to the optionals struct (see on
5665 //top) into an array
5667 output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
5668 for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext();) {
5669 OptionalTaskDescriptor mm = mos.next();
5671 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
5673 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5676 output.println("};\n");
5678 //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
5681 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
5682 FlagDescriptor flagd = (FlagDescriptor)flags.next();
5683 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
5687 //process tag information
5690 boolean first = true;
5691 Enumeration tag_enum = fs.getTags();
5692 output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
5693 while(tag_enum.hasMoreElements()) {
5695 TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
5699 output.println(", ");
5700 output.println("/*tagid*/"+state.getTagId(tagd));
5702 output.println("};");
5704 Set<TaskIndex> tiset=sa.getTaskIndex(fs);
5705 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
5706 TaskIndex ti=itti.next();
5710 Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
5712 output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
5713 boolean needcomma=false;
5714 for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext();) {
5715 OptionalTaskDescriptor otd=otdit.next();
5719 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5721 output.println("};");
5723 output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
5724 output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
5725 output.print(ti.getIndex()+", ");
5726 output.print(otdset.size()+", ");
5727 output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
5728 output.println("};");
5731 tiset=sa.getTaskIndex(fs);
5732 boolean needcomma=false;
5734 output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
5735 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
5736 TaskIndex ti=itti.next();
5737 if (ti.isRuntime()) {
5744 output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
5746 output.println("};\n");
5748 //Store the result in fsanalysiswrapper
5750 output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
5751 output.println("/*flag*/"+flagid+",");
5752 output.println("/* number of tags*/"+tagcounter+",");
5753 output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
5754 output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
5755 output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
5756 output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
5757 output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
5758 output.println("};\n");
5762 //Build the array of fsanalysiswrappers
5763 output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
5764 boolean needcomma=false;
5765 for(int i = 0; i<fscounter; i++) {
5766 if (needcomma) output.print(",");
5767 output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
5770 output.println("};");
5772 //Build the classanalysiswrapper referring to the previous array
5773 output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
5774 output.println("/*type*/"+cdtemp.getId()+",");
5775 output.println("/*numotd*/"+numotd+",");
5776 output.println("otdarray"+cdtemp.getSafeSymbol()+",");
5777 output.println("/* number of fsanalysiswrappers */"+fscounter+",");
5778 output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
5779 processedcd.add(cdtemp);
5782 //build an array containing every classes for which code has been build
5783 output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
5784 for(int i=0; i<state.numClasses(); i++) {
5785 ClassDescriptor cn=cdarray[i];
5788 if ((cn != null) && (processedcd.contains(cn)))
5789 output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
5791 output.print("NULL");
5793 output.println("};");
5795 output.println("#define MAXOTD "+maxotd);
5796 headers.println("#endif");
5799 public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
5800 Relation r=new Relation();
5801 for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext();) {
5802 OptionalTaskDescriptor otd=otdit.next();
5803 TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
5807 LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
5808 for(Iterator it=r.keySet().iterator(); it.hasNext();) {
5809 Set s=r.get(it.next());
5810 for(Iterator it2=s.iterator(); it2.hasNext();) {
5811 OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
5819 protected void outputTransCode(PrintWriter output) {
5822 private int calculateSizeOfSESEParamList(FlatSESEEnterNode fsen){
5824 Set<TempDescriptor> tdSet=new HashSet<TempDescriptor>();
5826 for (Iterator iterator = fsen.getInVarSet().iterator(); iterator.hasNext();) {
5827 TempDescriptor tempDescriptor = (TempDescriptor) iterator.next();
5828 if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()){
5829 tdSet.add(tempDescriptor);
5833 for (Iterator iterator = fsen.getOutVarSet().iterator(); iterator.hasNext();) {
5834 TempDescriptor tempDescriptor = (TempDescriptor) iterator.next();
5835 if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()){
5836 tdSet.add(tempDescriptor);
5840 return tdSet.size();
5843 private String calculateSizeOfSESEParamSize(FlatSESEEnterNode fsen){
5844 HashMap <String,Integer> map=new HashMap();
5845 HashSet <TempDescriptor> processed=new HashSet<TempDescriptor>();
5848 // space for all in and out set primitives
5849 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
5850 inSetAndOutSet.addAll( fsen.getInVarSet() );
5851 inSetAndOutSet.addAll( fsen.getOutVarSet() );
5853 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
5855 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
5856 while( itr.hasNext() ) {
5857 TempDescriptor temp = itr.next();
5858 TypeDescriptor type = temp.getType();
5859 if( !type.isPtr() ) {
5860 inSetAndOutSetPrims.add( temp );
5864 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
5865 while( itrPrims.hasNext() ) {
5866 TempDescriptor temp = itrPrims.next();
5867 TypeDescriptor type = temp.getType();
5868 if(type.isPrimitive()){
5869 Integer count=map.get(type.getSymbol());
5871 count=new Integer(1);
5872 map.put(type.getSymbol(), count);
5874 map.put(type.getSymbol(), new Integer(count.intValue()+1));
5879 Set<String> keySet=map.keySet();
5880 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
5881 String key = (String) iterator.next();
5882 rtr+="+sizeof("+key+")*"+map.get(key);