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 mlperrstr = "if(status != 0) { "+
82 "sprintf(errmsg, \"MLP error at %s:%d\", __FILE__, __LINE__); "+
83 "perror(errmsg); exit(-1); }";
84 boolean nonSESEpass=true;
85 RuntimeConflictResolver rcr = null;
88 DiscoverConflicts recorddc;
93 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa) {
94 this(st, temptovar, typeutil, null, sa, pa, null, null);
97 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa, OoOJavaAnalysis oooa) {
98 this(st, temptovar, typeutil, null, sa, pa, mlpa, oooa);
101 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, PrefetchAnalysis pa, MLPAnalysis mlpa, OoOJavaAnalysis oooa) {
102 this(st, temptovar, typeutil, locality, null, pa, mlpa, oooa);
105 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa, OoOJavaAnalysis oooa) {
111 callgraph=new CallGraph(state);
113 oidstr="___objlocation___";
114 this.temptovar=temptovar;
115 paramstable=new Hashtable();
116 tempstable=new Hashtable();
117 fieldorder=new Hashtable();
118 flagorder=new Hashtable();
119 this.typeutil=typeutil;
120 virtualcalls=new Virtual(state,locality);
121 if (locality!=null) {
122 this.locality=locality;
123 this.reverttable=new Hashtable<LocalityBinding, TempDescriptor>();
124 this.backuptable=new Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>>();
125 this.wb=new WriteBarrier(locality, st);
127 if (state.SINGLETM&&state.DCOPTS) {
128 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
129 GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
130 this.dc=new DiscoverConflicts(locality, st, typeanalysis, gft);
133 if (state.DELAYCOMP) {
134 //TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
135 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
136 GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
137 delaycomp=new DCWrapper(locality, st, typeanalysis, gft);
138 dc=delaycomp.getConflicts();
139 recorddc=new DiscoverConflicts(locality, st, typeanalysis, delaycomp.getCannotDelayMap(), true, true, null);
140 recorddc.doAnalysis();
144 /** The buildCode method outputs C code for all the methods. The Flat
145 * versions of the methods must already be generated and stored in
146 * the State object. */
147 PrintWriter outsandbox=null;
149 public void buildCode() {
150 /* Create output streams to write to */
151 PrintWriter outclassdefs=null;
152 PrintWriter outstructs=null;
153 PrintWriter outrepairstructs=null;
154 PrintWriter outmethodheader=null;
155 PrintWriter outmethod=null;
156 PrintWriter outvirtual=null;
157 PrintWriter outtask=null;
158 PrintWriter outtaskdefs=null;
159 PrintWriter outoptionalarrays=null;
160 PrintWriter optionalheaders=null;
164 outsandbox=new PrintWriter(new FileOutputStream(PREFIX+"sandboxdefs.c"), true);
166 outstructs=new PrintWriter(new FileOutputStream(PREFIX+"structdefs.h"), true);
167 outmethodheader=new PrintWriter(new FileOutputStream(PREFIX+"methodheaders.h"), true);
168 outclassdefs=new PrintWriter(new FileOutputStream(PREFIX+"classdefs.h"), true);
169 outmethod=new PrintWriter(new FileOutputStream(PREFIX+"methods.c"), true);
170 outvirtual=new PrintWriter(new FileOutputStream(PREFIX+"virtualtable.h"), true);
172 outtask=new PrintWriter(new FileOutputStream(PREFIX+"task.h"), true);
173 outtaskdefs=new PrintWriter(new FileOutputStream(PREFIX+"taskdefs.c"), true);
174 if (state.OPTIONAL) {
175 outoptionalarrays=new PrintWriter(new FileOutputStream(PREFIX+"optionalarrays.c"), true);
176 optionalheaders=new PrintWriter(new FileOutputStream(PREFIX+"optionalstruct.h"), true);
179 if (state.structfile!=null) {
180 outrepairstructs=new PrintWriter(new FileOutputStream(PREFIX+state.structfile+".struct"), true);
182 } catch (Exception e) {
187 /* Build the virtual dispatch tables */
188 buildVirtualTables(outvirtual);
190 /* Output includes */
191 outmethodheader.println("#ifndef METHODHEADERS_H");
192 outmethodheader.println("#define METHODHEADERS_H");
193 outmethodheader.println("#include \"structdefs.h\"");
195 outmethodheader.println("#include \"dstm.h\"");
197 outmethodheader.println("#include \"sandbox.h\"");
199 if (state.EVENTMONITOR) {
200 outmethodheader.println("#include \"monitor.h\"");
202 if (state.SINGLETM) {
203 outmethodheader.println("#include \"tm.h\"");
204 outmethodheader.println("#include \"delaycomp.h\"");
205 outmethodheader.println("#include \"inlinestm.h\"");
207 if (state.ABORTREADERS) {
208 outmethodheader.println("#include \"abortreaders.h\"");
209 outmethodheader.println("#include <setjmp.h>");
211 if (state.MLP || state.OOOJAVA) {
212 outmethodheader.println("#include <stdlib.h>");
213 outmethodheader.println("#include <stdio.h>");
214 outmethodheader.println("#include <string.h>");
215 outmethodheader.println("#include \"mlp_runtime.h\"");
216 outmethodheader.println("#include \"psemaphore.h\"");
219 /* Output Structures */
220 outputStructs(outstructs);
222 // Output the C class declarations
223 // These could mutually reference each other
226 outclassdefs.println("#ifndef __CLASSDEF_H_");
227 outclassdefs.println("#define __CLASSDEF_H_");
228 outputClassDeclarations(outclassdefs);
230 // Output function prototypes and structures for parameters
231 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
232 while(it.hasNext()) {
233 ClassDescriptor cn=(ClassDescriptor)it.next();
234 generateCallStructs(cn, outclassdefs, outstructs, outmethodheader);
236 outclassdefs.println("#endif");
237 outclassdefs.close();
240 /* Map flags to integers */
241 /* The runtime keeps track of flags using these integers */
242 it=state.getClassSymbolTable().getDescriptorsIterator();
243 while(it.hasNext()) {
244 ClassDescriptor cn=(ClassDescriptor)it.next();
248 generateTaskStructs(outstructs, outmethodheader);
250 /* Outputs generic task structures if this is a task
252 outputTaskTypes(outtask);
255 if( state.MLP || state.OOOJAVA) {
256 // have to initialize some SESE compiler data before
257 // analyzing normal methods, which must happen before
258 // generating SESE internal code
260 Iterator<FlatSESEEnterNode> seseit;
262 seseit=mlpa.getAllSESEs().iterator();
264 seseit=oooa.getAllSESEs().iterator();
267 //TODO signal the object that will report errors
270 rcr = new RuntimeConflictResolver(PREFIX);
272 catch (FileNotFoundException e) {
273 System.out.println("Runtime Conflict Resolver could not create output file.");
277 while(seseit.hasNext()){
278 FlatSESEEnterNode fsen = seseit.next();
279 initializeSESE( fsen );
281 if(state.RCR && rcr != null){
282 Analysis.OoOJava.ConflictGraph conflictGraph;
283 Hashtable<Taint, Set<Effect>> conflicts;
284 if(!fsen.getIsCallerSESEplaceholder() && fsen.getParent()!=null &&
285 (conflictGraph = oooa.getConflictGraph(fsen.getParent())) != null &&
286 (conflicts = conflictGraph.getConflictEffectSet(fsen)) != null){
288 FlatMethod fm=fsen.getfmEnclosing();
291 ReachGraph rg=oooa.getDisjointAnalysis().getReachGraph(fm.getMethod());
294 rg.writeGraph("RCR_RG_SESE_DEBUG");
298 Hashtable<Taint, Set<Effect>> effects=oooa.getDisjointAnalysis().getEffectsAnalysis().get(fsen);
300 rcr.traverseSESEBlock(fsen, effects, conflicts, rg);
306 /* Build the actual methods */
307 outputMethods(outmethod);
309 // Output function prototypes and structures for SESE's and code
310 if( state.MLP || state.OOOJAVA ) {
312 // used to differentiate, during code generation, whether we are
313 // passing over SESE body code, or non-SESE code
316 // first generate code for each sese's internals
317 Iterator<FlatSESEEnterNode> seseit;
319 seseit=mlpa.getAllSESEs().iterator();
321 seseit=oooa.getAllSESEs().iterator();
324 while(seseit.hasNext()) {
325 FlatSESEEnterNode fsen = seseit.next();
326 generateMethodSESE(fsen, null, outstructs, outmethodheader, outmethod);
329 // then write the invokeSESE switch to decouple scheduler
330 // from having to do unique details of sese invocation
331 generateSESEinvocationMethod(outmethodheader, outmethod);
335 /* Output code for tasks */
336 outputTaskCode(outtaskdefs, outmethod);
338 /* Record maximum number of task parameters */
339 outstructs.println("#define MAXTASKPARAMS "+maxtaskparams);
340 } else if (state.main!=null) {
341 /* Generate main method */
342 outputMainMethod(outmethod);
345 /* Generate information for task with optional parameters */
346 if (state.TASK&&state.OPTIONAL) {
347 generateOptionalArrays(outoptionalarrays, optionalheaders, state.getAnalysisResult(), state.getOptionalTaskDescriptors());
348 outoptionalarrays.close();
351 /* Output structure definitions for repair tool */
352 if (state.structfile!=null) {
353 buildRepairStructs(outrepairstructs);
354 outrepairstructs.close();
358 outmethodheader.println("#endif");
359 outmethodheader.close();
361 outstructs.println("#endif");
365 System.out.println("Runtime Conflict Resolver Done.");
370 /* This code just generates the main C method for java programs.
371 * The main C method packs up the arguments into a string array
372 * and passes it to the java main method. */
374 private void outputMainMethod(PrintWriter outmethod) {
375 outmethod.println("int main(int argc, const char *argv[]) {");
376 outmethod.println(" int i;");
378 if (state.MLP || state.OOOJAVA) {
379 //outmethod.println(" pthread_once( &mlpOnceObj, mlpInitOncePerThread );");
381 outmethod.println(" workScheduleInit( "+state.MLP_NUMCORES+", invokeSESEmethod );");
383 //initializes data structures needed for the RCR traverser
385 outmethod.println(" initializeStructsRCR();");
390 if (state.DSMRECOVERYSTATS) {
391 outmethod.println("#ifdef RECOVERYSTATS \n");
392 outmethod.println("handle();\n");
393 outmethod.println("#endif\n");
395 outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n");
396 outmethod.println("handle();\n");
397 outmethod.println("#endif\n");
401 if (state.THREAD||state.DSM||state.SINGLETM) {
402 outmethod.println("initializethreads();");
405 outmethod.println("if (dstmStartup(argv[1])) {");
406 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
407 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-2);");
409 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-2);");
412 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
413 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1);");
415 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1);");
419 outmethod.println(" for(i=2;i<argc;i++) {");
421 outmethod.println(" for(i=1;i<argc;i++) {");
422 outmethod.println(" int length=strlen(argv[i]);");
423 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
424 outmethod.println(" struct ___String___ *newstring=NewString(NULL, argv[i], length);");
426 outmethod.println(" struct ___String___ *newstring=NewString(argv[i], length);");
429 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-2]=newstring;");
431 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-1]=newstring;");
432 outmethod.println(" }");
434 MethodDescriptor md=typeutil.getMain();
435 ClassDescriptor cd=typeutil.getMainClass();
437 outmethod.println(" {");
438 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
439 if (state.DSM||state.SINGLETM) {
440 outmethod.print(" struct "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
442 outmethod.print(" struct "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
443 outmethod.println("1, NULL,"+"stringarray};");
444 if (state.DSM||state.SINGLETM)
445 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
447 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
449 if (state.DSM||state.SINGLETM)
450 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
452 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
454 outmethod.println(" }");
457 outmethod.println("}");
460 if (state.THREAD||state.DSM||state.SINGLETM) {
461 outmethod.println("pthread_mutex_lock(&gclistlock);");
462 outmethod.println("threadcount--;");
463 outmethod.println("pthread_cond_signal(&gccond);");
464 outmethod.println("pthread_mutex_unlock(&gclistlock);");
467 if (state.DSM||state.SINGLETM) {
468 //outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n");
469 outmethod.println("#if defined(TRANSSTATS) \n");
470 outmethod.println("printf(\"****** Transaction Stats ******\\n\");");
471 outmethod.println("printf(\"numTransCommit= %d\\n\", numTransCommit);");
472 outmethod.println("printf(\"numTransAbort= %d\\n\", numTransAbort);");
473 outmethod.println("printf(\"nSoftAbort= %d\\n\", nSoftAbort);");
475 outmethod.println("printf(\"nchashSearch= %d\\n\", nchashSearch);");
476 outmethod.println("printf(\"nmhashSearch= %d\\n\", nmhashSearch);");
477 outmethod.println("printf(\"nprehashSearch= %d\\n\", nprehashSearch);");
478 outmethod.println("printf(\"ndirtyCacheObj= %d\\n\", ndirtyCacheObj);");
479 outmethod.println("printf(\"nRemoteReadSend= %d\\n\", nRemoteSend);");
480 outmethod.println("printf(\"bytesSent= %d\\n\", bytesSent);");
481 outmethod.println("printf(\"bytesRecv= %d\\n\", bytesRecv);");
482 outmethod.println("printf(\"totalObjSize= %d\\n\", totalObjSize);");
483 outmethod.println("printf(\"sendRemoteReq= %d\\n\", sendRemoteReq);");
484 outmethod.println("printf(\"getResponse= %d\\n\", getResponse);");
485 } else if (state.SINGLETM) {
486 outmethod.println("printf(\"nSoftAbortAbort= %d\\n\", nSoftAbortAbort);");
487 outmethod.println("printf(\"nSoftAbortCommit= %d\\n\", nSoftAbortCommit);");
488 outmethod.println("#ifdef STMSTATS\n");
489 outmethod.println("for(i=0; i<TOTALNUMCLASSANDARRAY; i++) {\n");
490 outmethod.println(" printf(\"typesCausingAbort[%2d] numaccess= %5d numabort= %3d\\n\", i, typesCausingAbort[i].numaccess, typesCausingAbort[i].numabort);\n");
491 outmethod.println("}\n");
492 outmethod.println("#endif\n");
493 outmethod.println("fflush(stdout);");
495 outmethod.println("#endif\n");
498 if (state.EVENTMONITOR) {
499 outmethod.println("dumpdata();");
502 if (state.THREAD||state.SINGLETM)
503 outmethod.println("pthread_exit(NULL);");
505 if (state.MLP || state.OOOJAVA ) {
506 outmethod.println(" workScheduleBegin();");
509 outmethod.println("}");
512 /* This method outputs code for each task. */
514 private void outputTaskCode(PrintWriter outtaskdefs, PrintWriter outmethod) {
515 /* Compile task based program */
516 outtaskdefs.println("#include \"task.h\"");
517 outtaskdefs.println("#include \"methodheaders.h\"");
518 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
519 while(taskit.hasNext()) {
520 TaskDescriptor td=(TaskDescriptor)taskit.next();
521 FlatMethod fm=state.getMethodFlat(td);
522 generateFlatMethod(fm, null, outmethod);
523 generateTaskDescriptor(outtaskdefs, fm, td);
526 //Output task descriptors
527 taskit=state.getTaskSymbolTable().getDescriptorsIterator();
528 outtaskdefs.println("struct taskdescriptor * taskarray[]= {");
530 while(taskit.hasNext()) {
531 TaskDescriptor td=(TaskDescriptor)taskit.next();
535 outtaskdefs.println(",");
536 outtaskdefs.print("&task_"+td.getSafeSymbol());
538 outtaskdefs.println("};");
540 outtaskdefs.println("int numtasks="+state.getTaskSymbolTable().getValueSet().size()+";");
543 /* This method outputs most of the methods.c file. This includes
544 * some standard includes and then an array with the sizes of
545 * objets and array that stores supertype and then the code for
546 * the Java methods.. */
548 protected void outputMethods(PrintWriter outmethod) {
549 outmethod.println("#include \"methodheaders.h\"");
550 outmethod.println("#include \"virtualtable.h\"");
551 outmethod.println("#include \"runtime.h\"");
553 outmethod.println("#include \"sandboxdefs.c\"");
556 outmethod.println("#include \"addPrefetchEnhance.h\"");
557 outmethod.println("#include \"localobjects.h\"");
559 if (state.FASTCHECK) {
560 outmethod.println("#include \"localobjects.h\"");
562 if(state.MULTICORE) {
563 outmethod.println("#include \"task.h\"");
564 outmethod.println("#include \"multicoreruntime.h\"");
565 outmethod.println("#include \"runtime_arch.h\"");
567 if (state.THREAD||state.DSM||state.SINGLETM)
568 outmethod.println("#include <thread.h>");
569 if (state.main!=null) {
570 outmethod.println("#include <string.h>");
572 if (state.CONSCHECK) {
573 outmethod.println("#include \"checkers.h\"");
575 if (state.MLP || state.OOOJAVA ) {
576 outmethod.println("#include <stdlib.h>");
577 outmethod.println("#include <stdio.h>");
578 outmethod.println("#include \"mlp_runtime.h\"");
579 outmethod.println("#include \"psemaphore.h\"");
582 outmethod.println("#include \"RuntimeConflictResolver.h\"");
585 if (state.COREPROF) {
586 outmethod.println("#include \"coreprof.h\"");
589 //Store the sizes of classes & array elements
590 generateSizeArray(outmethod);
592 //Store table of supertypes
593 generateSuperTypeTable(outmethod);
595 //Store the layout of classes
596 generateLayoutStructs(outmethod);
598 /* Generate code for methods */
599 if (state.DSM||state.SINGLETM) {
600 for(Iterator<LocalityBinding> lbit=locality.getLocalityBindings().iterator(); lbit.hasNext();) {
601 LocalityBinding lb=lbit.next();
602 MethodDescriptor md=lb.getMethod();
603 FlatMethod fm=state.getMethodFlat(md);
605 if (!md.getModifiers().isNative()) {
606 generateFlatMethod(fm, lb, outmethod);
607 //System.out.println("fm= " + fm + " md= " + md);
611 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
612 while(classit.hasNext()) {
613 ClassDescriptor cn=(ClassDescriptor)classit.next();
614 Iterator methodit=cn.getMethods();
615 while(methodit.hasNext()) {
616 /* Classify parameters */
617 MethodDescriptor md=(MethodDescriptor)methodit.next();
618 FlatMethod fm=state.getMethodFlat(md);
619 if (!md.getModifiers().isNative()) {
620 generateFlatMethod(fm, null, outmethod);
627 protected void outputStructs(PrintWriter outstructs) {
628 outstructs.println("#ifndef STRUCTDEFS_H");
629 outstructs.println("#define STRUCTDEFS_H");
630 outstructs.println("#include \"classdefs.h\"");
631 outstructs.println("#ifndef INTPTR");
632 outstructs.println("#ifdef BIT64");
633 outstructs.println("#define INTPTR long");
634 outstructs.println("#else");
635 outstructs.println("#define INTPTR int");
636 outstructs.println("#endif");
637 outstructs.println("#endif");
638 if( state.MLP || state.OOOJAVA ) {
639 outstructs.println("#include \"mlp_runtime.h\"");
640 outstructs.println("#include \"psemaphore.h\"");
643 /* Output #defines that the runtime uses to determine type
644 * numbers for various objects it needs */
645 outstructs.println("#define MAXCOUNT "+maxcount);
646 if (state.DSM||state.SINGLETM) {
647 LocalityBinding lbrun=new LocalityBinding(typeutil.getRun(), false);
649 lbrun.setGlobalThis(LocalityAnalysis.GLOBAL);
651 else if (state.SINGLETM) {
652 lbrun.setGlobalThis(LocalityAnalysis.NORMAL);
654 outstructs.println("#define RUNMETHOD "+virtualcalls.getLocalityNumber(lbrun));
658 LocalityBinding lbexecute = new LocalityBinding(typeutil.getExecute(), false);
660 lbexecute.setGlobalThis(LocalityAnalysis.GLOBAL);
661 else if( state.SINGLETM)
662 lbexecute.setGlobalThis(LocalityAnalysis.NORMAL);
663 outstructs.println("#define EXECUTEMETHOD " + virtualcalls.getLocalityNumber(lbexecute));
666 outstructs.println("#define STRINGARRAYTYPE "+
667 (state.getArrayNumber(
668 (new TypeDescriptor(typeutil.getClass(TypeUtil.StringClass))).makeArray(state))+state.numClasses()));
670 outstructs.println("#define OBJECTARRAYTYPE "+
671 (state.getArrayNumber(
672 (new TypeDescriptor(typeutil.getClass(TypeUtil.ObjectClass))).makeArray(state))+state.numClasses()));
675 outstructs.println("#define STRINGTYPE "+typeutil.getClass(TypeUtil.StringClass).getId());
676 outstructs.println("#define CHARARRAYTYPE "+
677 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.CHAR)).makeArray(state))+state.numClasses()));
679 outstructs.println("#define BYTEARRAYTYPE "+
680 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state))+state.numClasses()));
682 outstructs.println("#define BYTEARRAYARRAYTYPE "+
683 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state).makeArray(state))+state.numClasses()));
685 outstructs.println("#define NUMCLASSES "+state.numClasses());
686 int totalClassSize = state.numClasses() + state.numArrays();
687 outstructs.println("#define TOTALNUMCLASSANDARRAY "+ totalClassSize);
689 outstructs.println("#define STARTUPTYPE "+typeutil.getClass(TypeUtil.StartupClass).getId());
690 outstructs.println("#define TAGTYPE "+typeutil.getClass(TypeUtil.TagClass).getId());
691 outstructs.println("#define TAGARRAYTYPE "+
692 (state.getArrayNumber(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)).makeArray(state))+state.numClasses()));
696 protected void outputClassDeclarations(PrintWriter outclassdefs) {
697 if (state.THREAD||state.DSM||state.SINGLETM)
698 outclassdefs.println("#include <pthread.h>");
699 outclassdefs.println("#ifndef INTPTR");
700 outclassdefs.println("#ifdef BIT64");
701 outclassdefs.println("#define INTPTR long");
702 outclassdefs.println("#else");
703 outclassdefs.println("#define INTPTR int");
704 outclassdefs.println("#endif");
705 outclassdefs.println("#endif");
707 outclassdefs.println("#include \"optionalstruct.h\"");
708 outclassdefs.println("struct "+arraytype+";");
709 /* Start by declaring all structs */
710 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
711 while(it.hasNext()) {
712 ClassDescriptor cn=(ClassDescriptor)it.next();
713 outclassdefs.println("struct "+cn.getSafeSymbol()+";");
715 outclassdefs.println("");
716 //Print out definition for array type
717 outclassdefs.println("struct "+arraytype+" {");
718 outclassdefs.println(" int type;");
719 if(state.MLP || state.OOOJAVA ){
720 outclassdefs.println(" int oid;");
721 outclassdefs.println(" int allocsite;");
723 if (state.EVENTMONITOR) {
724 outclassdefs.println(" int objuid;");
727 outclassdefs.println(" pthread_t tid;");
728 outclassdefs.println(" void * lockentry;");
729 outclassdefs.println(" int lockcount;");
732 outclassdefs.println(" int flag;");
733 if(!state.MULTICORE) {
734 outclassdefs.println(" void * flagptr;");
736 outclassdefs.println(" int version;");
737 outclassdefs.println(" int * lock;"); // lock entry for this obj
738 outclassdefs.println(" int mutex;");
739 outclassdefs.println(" int lockcount;");
740 if(state.MULTICOREGC) {
741 outclassdefs.println(" int marked;");
745 outclassdefs.println(" int numfses;");
746 outclassdefs.println(" int * fses;");
749 printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs);
751 if (state.STMARRAY) {
752 outclassdefs.println(" int lowindex;");
753 outclassdefs.println(" int highindex;");
756 outclassdefs.println(" int paddingforarray;");
757 if (state.DUALVIEW) {
758 outclassdefs.println(" int arrayversion;");
761 outclassdefs.println(" int ___length___;");
762 outclassdefs.println("};\n");
763 outclassdefs.println("extern int classsize[];");
764 outclassdefs.println("extern int hasflags[];");
765 outclassdefs.println("extern unsigned INTPTR * pointerarray[];");
766 outclassdefs.println("extern int supertypes[];");
769 /** Prints out definitions for generic task structures */
771 private void outputTaskTypes(PrintWriter outtask) {
772 outtask.println("#ifndef _TASK_H");
773 outtask.println("#define _TASK_H");
774 outtask.println("struct parameterdescriptor {");
775 outtask.println("int type;");
776 outtask.println("int numberterms;");
777 outtask.println("int *intarray;");
778 outtask.println("void * queue;");
779 outtask.println("int numbertags;");
780 outtask.println("int *tagarray;");
781 outtask.println("};");
783 outtask.println("struct taskdescriptor {");
784 outtask.println("void * taskptr;");
785 outtask.println("int numParameters;");
786 outtask.println(" int numTotal;");
787 outtask.println("struct parameterdescriptor **descriptorarray;");
788 outtask.println("char * name;");
789 outtask.println("};");
790 outtask.println("extern struct taskdescriptor * taskarray[];");
791 outtask.println("extern numtasks;");
792 outtask.println("#endif");
796 private void buildRepairStructs(PrintWriter outrepairstructs) {
797 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
798 while(classit.hasNext()) {
799 ClassDescriptor cn=(ClassDescriptor)classit.next();
800 outrepairstructs.println("structure "+cn.getSymbol()+" {");
801 outrepairstructs.println(" int __type__;");
803 outrepairstructs.println(" int __flag__;");
804 if(!state.MULTICORE) {
805 outrepairstructs.println(" int __flagptr__;");
808 printRepairStruct(cn, outrepairstructs);
809 outrepairstructs.println("}\n");
812 for(int i=0; i<state.numArrays(); i++) {
813 TypeDescriptor tdarray=arraytable[i];
814 TypeDescriptor tdelement=tdarray.dereference();
815 outrepairstructs.println("structure "+arraytype+"_"+state.getArrayNumber(tdarray)+" {");
816 outrepairstructs.println(" int __type__;");
817 printRepairStruct(typeutil.getClass(TypeUtil.ObjectClass), outrepairstructs);
818 outrepairstructs.println(" int length;");
820 // Need to add support to repair tool for this
821 if (tdelement.isClass()||tdelement.isArray())
822 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" * elem[this.length];");
824 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" elem[this.length];");
826 outrepairstructs.println("}\n");
830 private void printRepairStruct(ClassDescriptor cn, PrintWriter output) {
831 ClassDescriptor sp=cn.getSuperDesc();
833 printRepairStruct(sp, output);
835 Vector fields=(Vector)fieldorder.get(cn);
837 for(int i=0; i<fields.size(); i++) {
838 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
839 if (fd.getType().isArray()) {
840 output.println(" "+arraytype+"_"+ state.getArrayNumber(fd.getType()) +" * "+fd.getSymbol()+";");
841 } else if (fd.getType().isClass())
842 output.println(" "+fd.getType().getRepairSymbol()+" * "+fd.getSymbol()+";");
843 else if (fd.getType().isFloat())
844 output.println(" int "+fd.getSymbol()+"; /* really float */");
846 output.println(" "+fd.getType().getRepairSymbol()+" "+fd.getSymbol()+";");
850 /** This method outputs TaskDescriptor information */
851 private void generateTaskDescriptor(PrintWriter output, FlatMethod fm, TaskDescriptor task) {
852 for (int i=0; i<task.numParameters(); i++) {
853 VarDescriptor param_var=task.getParameter(i);
854 TypeDescriptor param_type=task.getParamType(i);
855 FlagExpressionNode param_flag=task.getFlag(param_var);
856 TagExpressionList param_tag=task.getTag(param_var);
859 if (param_flag==null) {
860 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
861 output.println("0x0, 0x0 };");
864 DNFFlag dflag=param_flag.getDNF();
865 dnfterms=dflag.size();
867 Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
868 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
869 for(int j=0; j<dflag.size(); j++) {
872 Vector term=dflag.get(j);
875 for(int k=0; k<term.size(); k++) {
876 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
877 FlagDescriptor fd=dfa.getFlag();
878 boolean negated=dfa.getNegated();
879 int flagid=1<<((Integer)flags.get(fd)).intValue();
884 output.print("0x"+Integer.toHexString(andmask)+", 0x"+Integer.toHexString(checkmask));
886 output.println("};");
889 output.println("int parametertag_"+i+"_"+task.getSafeSymbol()+"[]={");
890 //BUG...added next line to fix, test with any task program
892 for(int j=0; j<param_tag.numTags(); j++) {
895 /* for each tag we need */
896 /* which slot it is */
897 /* what type it is */
898 TagVarDescriptor tvd=(TagVarDescriptor)task.getParameterTable().get(param_tag.getName(j));
899 TempDescriptor tmp=param_tag.getTemp(j);
900 int slot=fm.getTagInt(tmp);
901 output.println(slot+", "+state.getTagId(tvd.getTag()));
903 output.println("};");
905 output.println("struct parameterdescriptor parameter_"+i+"_"+task.getSafeSymbol()+"={");
906 output.println("/* type */"+param_type.getClassDesc().getId()+",");
907 output.println("/* number of DNF terms */"+dnfterms+",");
908 output.println("parameterdnf_"+i+"_"+task.getSafeSymbol()+",");
909 output.println("0,");
910 //BUG, added next line to fix and else statement...test
911 //with any task program
913 output.println("/* number of tags */"+param_tag.numTags()+",");
915 output.println("/* number of tags */ 0,");
916 output.println("parametertag_"+i+"_"+task.getSafeSymbol());
917 output.println("};");
921 output.println("struct parameterdescriptor * parameterdescriptors_"+task.getSafeSymbol()+"[] = {");
922 for (int i=0; i<task.numParameters(); i++) {
925 output.print("¶meter_"+i+"_"+task.getSafeSymbol());
927 output.println("};");
929 output.println("struct taskdescriptor task_"+task.getSafeSymbol()+"={");
930 output.println("&"+task.getSafeSymbol()+",");
931 output.println("/* number of parameters */" +task.numParameters() + ",");
932 int numtotal=task.numParameters()+fm.numTags();
933 output.println("/* number total parameters */" +numtotal + ",");
934 output.println("parameterdescriptors_"+task.getSafeSymbol()+",");
935 output.println("\""+task.getSymbol()+"\"");
936 output.println("};");
940 /** The buildVirtualTables method outputs the virtual dispatch
941 * tables for methods. */
943 protected void buildVirtualTables(PrintWriter outvirtual) {
944 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
945 while(classit.hasNext()) {
946 ClassDescriptor cd=(ClassDescriptor)classit.next();
947 if (virtualcalls.getMethodCount(cd)>maxcount)
948 maxcount=virtualcalls.getMethodCount(cd);
950 MethodDescriptor[][] virtualtable=null;
951 LocalityBinding[][] lbvirtualtable=null;
952 if (state.DSM||state.SINGLETM)
953 lbvirtualtable=new LocalityBinding[state.numClasses()+state.numArrays()][maxcount];
955 virtualtable=new MethodDescriptor[state.numClasses()+state.numArrays()][maxcount];
957 /* Fill in virtual table */
958 classit=state.getClassSymbolTable().getDescriptorsIterator();
959 while(classit.hasNext()) {
960 ClassDescriptor cd=(ClassDescriptor)classit.next();
961 if (state.DSM||state.SINGLETM)
962 fillinRow(cd, lbvirtualtable, cd.getId());
964 fillinRow(cd, virtualtable, cd.getId());
967 ClassDescriptor objectcd=typeutil.getClass(TypeUtil.ObjectClass);
968 Iterator arrayit=state.getArrayIterator();
969 while(arrayit.hasNext()) {
970 TypeDescriptor td=(TypeDescriptor)arrayit.next();
971 int id=state.getArrayNumber(td);
972 if (state.DSM||state.SINGLETM)
973 fillinRow(objectcd, lbvirtualtable, id+state.numClasses());
975 fillinRow(objectcd, virtualtable, id+state.numClasses());
978 outvirtual.print("void * virtualtable[]={");
979 boolean needcomma=false;
980 for(int i=0; i<state.numClasses()+state.numArrays(); i++) {
981 for(int j=0; j<maxcount; j++) {
983 outvirtual.print(", ");
984 if ((state.DSM||state.SINGLETM)&&lbvirtualtable[i][j]!=null) {
985 LocalityBinding lb=lbvirtualtable[i][j];
986 MethodDescriptor md=lb.getMethod();
987 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
988 } else if (!(state.DSM||state.SINGLETM)&&virtualtable[i][j]!=null) {
989 MethodDescriptor md=virtualtable[i][j];
990 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
992 outvirtual.print("0");
996 outvirtual.println("");
998 outvirtual.println("};");
1002 private void fillinRow(ClassDescriptor cd, MethodDescriptor[][] virtualtable, int rownum) {
1003 /* Get inherited methods */
1004 if (cd.getSuperDesc()!=null)
1005 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
1006 /* Override them with our methods */
1007 for(Iterator it=cd.getMethods(); it.hasNext();) {
1008 MethodDescriptor md=(MethodDescriptor)it.next();
1009 if (md.isStatic()||md.getReturnType()==null)
1011 int methodnum=virtualcalls.getMethodNumber(md);
1012 virtualtable[rownum][methodnum]=md;
1016 private void fillinRow(ClassDescriptor cd, LocalityBinding[][] virtualtable, int rownum) {
1017 /* Get inherited methods */
1018 if (cd.getSuperDesc()!=null)
1019 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
1020 /* Override them with our methods */
1021 if (locality.getClassBindings(cd)!=null)
1022 for(Iterator<LocalityBinding> lbit=locality.getClassBindings(cd).iterator(); lbit.hasNext();) {
1023 LocalityBinding lb=lbit.next();
1024 MethodDescriptor md=lb.getMethod();
1025 //Is the method static or a constructor
1026 if (md.isStatic()||md.getReturnType()==null)
1028 int methodnum=virtualcalls.getLocalityNumber(lb);
1029 virtualtable[rownum][methodnum]=lb;
1033 /** Generate array that contains the sizes of class objects. The
1034 * object allocation functions in the runtime use this
1037 private void generateSizeArray(PrintWriter outclassdefs) {
1038 outclassdefs.print("extern struct prefetchCountStats * evalPrefetch;\n");
1039 outclassdefs.print("#ifdef TRANSSTATS \n");
1040 outclassdefs.print("extern int numTransAbort;\n");
1041 outclassdefs.print("extern int numTransCommit;\n");
1042 outclassdefs.print("extern int nSoftAbort;\n");
1044 outclassdefs.print("extern int nchashSearch;\n");
1045 outclassdefs.print("extern int nmhashSearch;\n");
1046 outclassdefs.print("extern int nprehashSearch;\n");
1047 outclassdefs.print("extern int ndirtyCacheObj;\n");
1048 outclassdefs.print("extern int nRemoteSend;\n");
1049 outclassdefs.print("extern int sendRemoteReq;\n");
1050 outclassdefs.print("extern int getResponse;\n");
1051 outclassdefs.print("extern int bytesSent;\n");
1052 outclassdefs.print("extern int bytesRecv;\n");
1053 outclassdefs.print("extern int totalObjSize;\n");
1054 outclassdefs.print("extern void handle();\n");
1055 } else if (state.SINGLETM) {
1056 outclassdefs.println("extern int nSoftAbortAbort;");
1057 outclassdefs.println("extern int nSoftAbortCommit;");
1058 outclassdefs.println("#ifdef STMSTATS\n");
1059 outclassdefs.println("extern objtypestat_t typesCausingAbort[];");
1060 outclassdefs.println("#endif\n");
1062 outclassdefs.print("#endif\n");
1064 outclassdefs.print("int numprefetchsites = " + pa.prefetchsiteid + ";\n");
1065 if(this.state.MLP || state.OOOJAVA ){
1066 outclassdefs.print("extern __thread int oid;\n");
1067 outclassdefs.print("extern int numWorkers;\n");
1070 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1071 cdarray=new ClassDescriptor[state.numClasses()];
1073 while(it.hasNext()) {
1074 ClassDescriptor cd=(ClassDescriptor)it.next();
1075 cdarray[cd.getId()]=cd;
1078 arraytable=new TypeDescriptor[state.numArrays()];
1080 Iterator arrayit=state.getArrayIterator();
1081 while(arrayit.hasNext()) {
1082 TypeDescriptor td=(TypeDescriptor)arrayit.next();
1083 int id=state.getArrayNumber(td);
1089 /* Print out types */
1090 outclassdefs.println("/* ");
1091 for(int i=0; i<state.numClasses(); i++) {
1092 ClassDescriptor cd=cdarray[i];
1094 outclassdefs.println("NULL " + i);
1096 outclassdefs.println(cd +" "+i);
1100 for(int i=0; i<state.numArrays(); i++) {
1101 TypeDescriptor arraytd=arraytable[i];
1102 outclassdefs.println(arraytd.toPrettyString() +" "+(i+state.numClasses()));
1105 outclassdefs.println("*/");
1108 outclassdefs.print("int classsize[]={");
1110 boolean needcomma=false;
1111 for(int i=0; i<state.numClasses(); i++) {
1113 outclassdefs.print(", ");
1115 outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")");
1117 outclassdefs.print("0");
1123 for(int i=0; i<state.numArrays(); i++) {
1125 outclassdefs.print(", ");
1126 TypeDescriptor tdelement=arraytable[i].dereference();
1127 if (tdelement.isArray()||tdelement.isClass())
1128 outclassdefs.print("sizeof(void *)");
1130 outclassdefs.print("sizeof("+tdelement.getSafeSymbol()+")");
1134 outclassdefs.println("};");
1136 ClassDescriptor objectclass=typeutil.getClass(TypeUtil.ObjectClass);
1138 outclassdefs.print("int typearray[]={");
1139 for(int i=0; i<state.numClasses(); i++) {
1140 ClassDescriptor cd=cdarray[i];
1141 ClassDescriptor supercd=i>0?cd.getSuperDesc():null;
1143 outclassdefs.print(", ");
1145 outclassdefs.print("-1");
1147 outclassdefs.print(supercd.getId());
1151 for(int i=0; i<state.numArrays(); i++) {
1152 TypeDescriptor arraytd=arraytable[i];
1153 ClassDescriptor arraycd=arraytd.getClassDesc();
1154 if (arraycd==null) {
1156 outclassdefs.print(", ");
1157 outclassdefs.print(objectclass.getId());
1161 ClassDescriptor cd=arraycd.getSuperDesc();
1164 TypeDescriptor supertd=new TypeDescriptor(cd);
1165 supertd.setArrayCount(arraytd.getArrayCount());
1166 type=state.getArrayNumber(supertd);
1168 type+=state.numClasses();
1171 cd=cd.getSuperDesc();
1174 outclassdefs.print(", ");
1175 outclassdefs.print(type);
1179 outclassdefs.println("};");
1184 outclassdefs.print("int typearray2[]={");
1185 for(int i=0; i<state.numArrays(); i++) {
1186 TypeDescriptor arraytd=arraytable[i];
1187 ClassDescriptor arraycd=arraytd.getClassDesc();
1188 if (arraycd==null) {
1190 outclassdefs.print(", ");
1191 outclassdefs.print("-1");
1195 ClassDescriptor cd=arraycd.getSuperDesc();
1196 int level=arraytd.getArrayCount()-1;
1198 for(; level>0; level--) {
1199 TypeDescriptor supertd=new TypeDescriptor(objectclass);
1200 supertd.setArrayCount(level);
1201 type=state.getArrayNumber(supertd);
1203 type+=state.numClasses();
1208 outclassdefs.print(", ");
1209 outclassdefs.print(type);
1213 outclassdefs.println("};");
1216 /** Constructs params and temp objects for each method or task.
1217 * These objects tell the compiler which temps need to be
1220 protected void generateTempStructs(FlatMethod fm, LocalityBinding lb) {
1221 MethodDescriptor md=fm.getMethod();
1222 TaskDescriptor task=fm.getTask();
1223 Set<TempDescriptor> saveset=lb!=null ? locality.getTempSet(lb) : null;
1224 ParamsObject objectparams=md!=null ? new ParamsObject(md,tag++) : new ParamsObject(task, tag++);
1226 paramstable.put(lb, objectparams);
1227 backuptable.put(lb, new Hashtable<TempDescriptor, TempDescriptor>());
1228 } else if (md!=null)
1229 paramstable.put(md, objectparams);
1231 paramstable.put(task, objectparams);
1233 for(int i=0; i<fm.numParameters(); i++) {
1234 TempDescriptor temp=fm.getParameter(i);
1235 TypeDescriptor type=temp.getType();
1236 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1237 objectparams.addPtr(temp);
1239 objectparams.addPrim(temp);
1240 if(lb!=null&&saveset.contains(temp)) {
1241 backuptable.get(lb).put(temp, temp.createNew());
1245 for(int i=0; i<fm.numTags(); i++) {
1246 TempDescriptor temp=fm.getTag(i);
1247 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1248 objectparams.addPtr(temp);
1250 objectparams.addPrim(temp);
1253 TempObject objecttemps=md!=null ? new TempObject(objectparams,md,tag++) : new TempObject(objectparams, task, tag++);
1255 tempstable.put(lb, objecttemps);
1257 tempstable.put(md, objecttemps);
1259 tempstable.put(task, objecttemps);
1261 for(Iterator nodeit=fm.getNodeSet().iterator(); nodeit.hasNext();) {
1262 FlatNode fn=(FlatNode)nodeit.next();
1263 TempDescriptor[] writes=fn.writesTemps();
1264 for(int i=0; i<writes.length; i++) {
1265 TempDescriptor temp=writes[i];
1266 TypeDescriptor type=temp.getType();
1267 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1268 objecttemps.addPtr(temp);
1270 objecttemps.addPrim(temp);
1271 if(lb!=null&&saveset.contains(temp)&&
1272 !backuptable.get(lb).containsKey(temp))
1273 backuptable.get(lb).put(temp, temp.createNew());
1277 /* Create backup temps */
1279 for(Iterator<TempDescriptor> tmpit=backuptable.get(lb).values().iterator(); tmpit.hasNext();) {
1280 TempDescriptor tmp=tmpit.next();
1281 TypeDescriptor type=tmp.getType();
1282 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1283 objecttemps.addPtr(tmp);
1285 objecttemps.addPrim(tmp);
1287 /* Create temp to hold revert table */
1288 if (state.DSM&&(lb.getHasAtomic()||lb.isAtomic())) {
1289 TempDescriptor reverttmp=new TempDescriptor("revertlist", typeutil.getClass(TypeUtil.ObjectClass));
1290 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1291 objecttemps.addPtr(reverttmp);
1293 objecttemps.addPrim(reverttmp);
1294 reverttable.put(lb, reverttmp);
1299 /** This method outputs the following information about classes
1301 * (1) For classes, what are the locations of pointers.
1302 * (2) For arrays, does the array contain pointers or primitives.
1303 * (3) For classes, does the class contain flags.
1306 private void generateLayoutStructs(PrintWriter output) {
1307 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1308 while(it.hasNext()) {
1309 ClassDescriptor cn=(ClassDescriptor)it.next();
1310 output.println("unsigned INTPTR "+cn.getSafeSymbol()+"_pointers[]={");
1311 Iterator allit=cn.getFieldTable().getAllDescriptorsIterator();
1313 while(allit.hasNext()) {
1314 FieldDescriptor fd=(FieldDescriptor)allit.next();
1315 TypeDescriptor type=fd.getType();
1316 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1321 output.print(count);
1322 allit=cn.getFieldTable().getAllDescriptorsIterator();
1323 while(allit.hasNext()) {
1324 FieldDescriptor fd=(FieldDescriptor)allit.next();
1325 TypeDescriptor type=fd.getType();
1326 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1329 output.println(",");
1330 output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+fd.getSafeSymbol()+"))");
1333 output.println("};");
1335 output.println("unsigned INTPTR * pointerarray[]={");
1336 boolean needcomma=false;
1337 for(int i=0; i<state.numClasses(); i++) {
1338 ClassDescriptor cn=cdarray[i];
1340 output.println(",");
1343 output.print(cn.getSafeSymbol()+"_pointers");
1345 output.print("NULL");
1349 for(int i=0; i<state.numArrays(); i++) {
1351 output.println(", ");
1352 TypeDescriptor tdelement=arraytable[i].dereference();
1353 if (tdelement.isArray()||tdelement.isClass())
1354 output.print("((unsigned INTPTR *)1)");
1360 output.println("};");
1362 output.println("int hasflags[]={");
1363 for(int i=0; i<state.numClasses(); i++) {
1364 ClassDescriptor cn=cdarray[i];
1366 output.println(", ");
1368 if ((cn != null) && (cn.hasFlags()))
1373 output.println("};");
1376 /** Print out table to give us supertypes */
1377 private void generateSuperTypeTable(PrintWriter output) {
1378 output.println("int supertypes[]={");
1379 boolean needcomma=false;
1380 for(int i=0; i<state.numClasses(); i++) {
1381 ClassDescriptor cn=cdarray[i];
1383 output.println(",");
1385 if ((cn != null) && (cn.getSuperDesc()!=null)) {
1386 ClassDescriptor cdsuper=cn.getSuperDesc();
1387 output.print(cdsuper.getId());
1391 output.println("};");
1394 /** Force consistent field ordering between inherited classes. */
1396 private void printClassStruct(ClassDescriptor cn, PrintWriter classdefout) {
1398 ClassDescriptor sp=cn.getSuperDesc();
1400 printClassStruct(sp, classdefout);
1402 if (!fieldorder.containsKey(cn)) {
1403 Vector fields=new Vector();
1404 fieldorder.put(cn,fields);
1405 Vector fieldvec=cn.getFieldVec();
1406 for(int i=0;i<fieldvec.size();i++) {
1407 FieldDescriptor fd=(FieldDescriptor)fieldvec.get(i);
1408 if ((sp==null||!sp.getFieldTable().contains(fd.getSymbol())))
1412 Vector fields=(Vector)fieldorder.get(cn);
1414 for(int i=0; i<fields.size(); i++) {
1415 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
1416 if (fd.getType().isClass()||fd.getType().isArray())
1417 classdefout.println(" struct "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1419 classdefout.println(" "+fd.getType().getSafeSymbol()+" "+fd.getSafeSymbol()+";");
1424 /* Map flags to integers consistently between inherited
1427 protected void mapFlags(ClassDescriptor cn) {
1428 ClassDescriptor sp=cn.getSuperDesc();
1432 if (!flagorder.containsKey(cn)) {
1433 Hashtable flags=new Hashtable();
1434 flagorder.put(cn,flags);
1436 Hashtable superflags=(Hashtable)flagorder.get(sp);
1437 Iterator superflagit=superflags.keySet().iterator();
1438 while(superflagit.hasNext()) {
1439 FlagDescriptor fd=(FlagDescriptor)superflagit.next();
1440 Integer number=(Integer)superflags.get(fd);
1441 flags.put(fd, number);
1442 if ((number.intValue()+1)>max)
1443 max=number.intValue()+1;
1447 Iterator flagit=cn.getFlags();
1448 while(flagit.hasNext()) {
1449 FlagDescriptor fd=(FlagDescriptor)flagit.next();
1450 if (sp==null||!sp.getFlagTable().contains(fd.getSymbol()))
1451 flags.put(fd, new Integer(max++));
1457 /** This function outputs (1) structures that parameters are
1458 * passed in (when PRECISE GC is enabled) and (2) function
1459 * prototypes for the methods */
1461 protected void generateCallStructs(ClassDescriptor cn, PrintWriter classdefout, PrintWriter output, PrintWriter headersout) {
1462 /* Output class structure */
1463 classdefout.println("struct "+cn.getSafeSymbol()+" {");
1464 classdefout.println(" int type;");
1465 if(state.MLP || state.OOOJAVA){
1466 classdefout.println(" int oid;");
1467 classdefout.println(" int allocsite;");
1469 if (state.EVENTMONITOR) {
1470 classdefout.println(" int objuid;");
1473 classdefout.println(" pthread_t tid;");
1474 classdefout.println(" void * lockentry;");
1475 classdefout.println(" int lockcount;");
1479 classdefout.println(" int flag;");
1480 if((!state.MULTICORE) || (cn.getSymbol().equals("TagDescriptor"))) {
1481 classdefout.println(" void * flagptr;");
1482 } else if (state.MULTICORE) {
1483 classdefout.println(" int version;");
1484 classdefout.println(" int * lock;"); // lock entry for this obj
1485 classdefout.println(" int mutex;");
1486 classdefout.println(" int lockcount;");
1487 if(state.MULTICOREGC) {
1488 classdefout.println(" int marked;");
1491 if (state.OPTIONAL) {
1492 classdefout.println(" int numfses;");
1493 classdefout.println(" int * fses;");
1496 printClassStruct(cn, classdefout);
1497 classdefout.println("};\n");
1499 if (state.DSM||state.SINGLETM) {
1500 /* Cycle through LocalityBindings */
1501 HashSet<MethodDescriptor> nativemethods=new HashSet<MethodDescriptor>();
1502 Set<LocalityBinding> lbset=locality.getClassBindings(cn);
1504 for(Iterator<LocalityBinding> lbit=lbset.iterator(); lbit.hasNext();) {
1505 LocalityBinding lb=lbit.next();
1506 MethodDescriptor md=lb.getMethod();
1507 if (md.getModifiers().isNative()) {
1508 //make sure we only print a native method once
1509 if (nativemethods.contains(md)) {
1510 FlatMethod fm=state.getMethodFlat(md);
1511 generateTempStructs(fm, lb);
1514 nativemethods.add(md);
1516 generateMethod(cn, md, lb, headersout, output);
1519 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1520 MethodDescriptor md=(MethodDescriptor)methodit.next();
1521 if (md.getModifiers().isNative()&&!nativemethods.contains(md)) {
1522 //Need to build param structure for library code
1523 FlatMethod fm=state.getMethodFlat(md);
1524 generateTempStructs(fm, null);
1525 generateMethodParam(cn, md, null, output);
1530 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1531 MethodDescriptor md=(MethodDescriptor)methodit.next();
1532 generateMethod(cn, md, null, headersout, output);
1536 private void generateMethodParam(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter output) {
1537 /* Output parameter structure */
1538 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1539 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1540 if ((state.DSM||state.SINGLETM)&&lb!=null)
1541 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1543 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1544 output.println(" int size;");
1545 output.println(" void * next;");
1546 for(int i=0; i<objectparams.numPointers(); i++) {
1547 TempDescriptor temp=objectparams.getPointer(i);
1548 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1550 output.println("};\n");
1554 private void generateMethod(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter headersout, PrintWriter output) {
1555 FlatMethod fm=state.getMethodFlat(md);
1556 generateTempStructs(fm, lb);
1558 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1559 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md);
1561 generateMethodParam(cn, md, lb, output);
1563 /* Output temp structure */
1564 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1565 if (state.DSM||state.SINGLETM)
1566 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1568 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1569 output.println(" int size;");
1570 output.println(" void * next;");
1571 for(int i=0; i<objecttemps.numPointers(); i++) {
1572 TempDescriptor temp=objecttemps.getPointer(i);
1573 if (temp.getType().isNull())
1574 output.println(" void * "+temp.getSafeSymbol()+";");
1576 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1578 output.println("};\n");
1581 /********* Output method declaration ***********/
1582 if (state.DSM||state.SINGLETM) {
1583 headersout.println("#define D"+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1585 headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1587 /* First the return type */
1588 if (md.getReturnType()!=null) {
1589 if (md.getReturnType().isClass()||md.getReturnType().isArray())
1590 headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1592 headersout.print(md.getReturnType().getSafeSymbol()+" ");
1594 //catch the constructor case
1595 headersout.print("void ");
1597 /* Next the method name */
1598 if (state.DSM||state.SINGLETM) {
1599 headersout.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1601 headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1603 boolean printcomma=false;
1604 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1605 if (state.DSM||state.SINGLETM) {
1606 headersout.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1608 headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1612 /* Output parameter list*/
1613 for(int i=0; i<objectparams.numPrimitives(); i++) {
1614 TempDescriptor temp=objectparams.getPrimitive(i);
1616 headersout.print(", ");
1618 if (temp.getType().isClass()||temp.getType().isArray())
1619 headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1621 headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1623 headersout.println(");\n");
1627 /** This function outputs (1) structures that parameters are
1628 * passed in (when PRECISE GC is enabled) and (2) function
1629 * prototypes for the tasks */
1631 private void generateTaskStructs(PrintWriter output, PrintWriter headersout) {
1632 /* Cycle through tasks */
1633 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
1635 while(taskit.hasNext()) {
1636 /* Classify parameters */
1637 TaskDescriptor task=(TaskDescriptor)taskit.next();
1638 FlatMethod fm=state.getMethodFlat(task);
1639 generateTempStructs(fm, null);
1641 ParamsObject objectparams=(ParamsObject) paramstable.get(task);
1642 TempObject objecttemps=(TempObject) tempstable.get(task);
1644 /* Output parameter structure */
1645 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1646 output.println("struct "+task.getSafeSymbol()+"_params {");
1647 output.println(" int size;");
1648 output.println(" void * next;");
1649 for(int i=0; i<objectparams.numPointers(); i++) {
1650 TempDescriptor temp=objectparams.getPointer(i);
1651 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1654 output.println("};\n");
1655 if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
1656 maxtaskparams=objectparams.numPointers()+fm.numTags();
1660 /* Output temp structure */
1661 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1662 output.println("struct "+task.getSafeSymbol()+"_locals {");
1663 output.println(" int size;");
1664 output.println(" void * next;");
1665 for(int i=0; i<objecttemps.numPointers(); i++) {
1666 TempDescriptor temp=objecttemps.getPointer(i);
1667 if (temp.getType().isNull())
1668 output.println(" void * "+temp.getSafeSymbol()+";");
1669 else if(temp.getType().isTag())
1670 output.println(" struct "+
1671 (new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1673 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1675 output.println("};\n");
1678 /* Output task declaration */
1679 headersout.print("void " + task.getSafeSymbol()+"(");
1681 boolean printcomma=false;
1682 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1683 headersout.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
1685 headersout.print("void * parameterarray[]");
1686 headersout.println(");\n");
1690 /***** Generate code for FlatMethod fm. *****/
1692 Hashtable<FlatAtomicEnterNode, AtomicRecord> atomicmethodmap;
1693 static int atomicmethodcount=0;
1696 BranchAnalysis branchanalysis;
1697 private void generateFlatMethod(FlatMethod fm, LocalityBinding lb, PrintWriter output) {
1698 if (State.PRINTFLAT)
1699 System.out.println(fm.printMethod());
1700 MethodDescriptor md=fm.getMethod();
1701 TaskDescriptor task=fm.getTask();
1702 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
1703 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : md!=null ? md : task);
1705 HashSet<AtomicRecord> arset=null;
1706 branchanalysis=null;
1708 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1710 if (atomicmethodmap==null)
1711 atomicmethodmap=new Hashtable<FlatAtomicEnterNode, AtomicRecord>();
1713 //fix these so we get right strings for local variables
1714 localsprefixaddr=localsprefix;
1715 localsprefixderef=localsprefix+"->";
1716 arset=new HashSet<AtomicRecord>();
1718 //build branchanalysis
1719 branchanalysis=new BranchAnalysis(locality, lb, delaycomp.getNotReady(lb), delaycomp.livecode(lb), state);
1721 //Generate commit methods here
1722 for(Iterator<FlatNode> fnit=fm.getNodeSet().iterator();fnit.hasNext();) {
1723 FlatNode fn=fnit.next();
1724 if (fn.kind()==FKind.FlatAtomicEnterNode&&
1725 locality.getAtomic(lb).get(fn.getPrev(0)).intValue()==0&&
1726 delaycomp.needsFission(lb, (FlatAtomicEnterNode) fn)) {
1727 //We have an atomic enter
1728 FlatAtomicEnterNode faen=(FlatAtomicEnterNode) fn;
1729 Set<FlatNode> exitset=faen.getExits();
1731 String methodname=md.getSymbol()+(atomicmethodcount++);
1732 AtomicRecord ar=new AtomicRecord();
1736 atomicmethodmap.put(faen, ar);
1738 //build data structure declaration
1739 output.println("struct atomicprimitives_"+methodname+" {");
1741 Set<FlatNode> recordset=delaycomp.livecode(lb);
1742 Set<TempDescriptor> liveinto=delaycomp.liveinto(lb, faen, recordset);
1743 Set<TempDescriptor> liveout=delaycomp.liveout(lb, faen);
1744 Set<TempDescriptor> liveoutvirtualread=delaycomp.liveoutvirtualread(lb, faen);
1746 ar.reallivein=new HashSet(liveinto);
1748 ar.liveoutvirtualread=liveoutvirtualread;
1751 for(Iterator<TempDescriptor> it=liveinto.iterator(); it.hasNext();) {
1752 TempDescriptor tmp=it.next();
1753 //remove the pointers
1754 if (tmp.getType().isPtr()) {
1757 //let's print it here
1758 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1761 for(Iterator<TempDescriptor> it=liveout.iterator(); it.hasNext();) {
1762 TempDescriptor tmp=it.next();
1763 //remove the pointers
1764 if (tmp.getType().isPtr()) {
1766 } else if (!liveinto.contains(tmp)) {
1767 //let's print it here
1768 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1771 output.println("};");
1773 //print out method name
1774 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) {");
1775 //build code for commit method
1777 //first define local primitives
1778 Set<TempDescriptor> alltemps=delaycomp.alltemps(lb, faen, recordset);
1779 for(Iterator<TempDescriptor> tmpit=alltemps.iterator();tmpit.hasNext();) {
1780 TempDescriptor tmp=tmpit.next();
1781 if (!tmp.getType().isPtr()) {
1782 if (liveinto.contains(tmp)||liveoutvirtualread.contains(tmp)) {
1783 //read from live into set
1784 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+"=primitives->"+tmp.getSafeSymbol()+";");
1787 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1791 //turn off write barrier generation
1793 state.SINGLETM=false;
1794 generateCode(faen, fm, lb, exitset, output, false);
1795 state.SINGLETM=true;
1796 //turn on write barrier generation
1798 output.println("}\n\n");
1802 //redefine these back to normal
1804 localsprefixaddr="&"+localsprefix;
1805 localsprefixderef=localsprefix+".";
1807 generateHeader(fm, lb, md!=null ? md : task,output);
1808 TempObject objecttemp=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
1810 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1811 for(Iterator<AtomicRecord> arit=arset.iterator();arit.hasNext();) {
1812 AtomicRecord ar=arit.next();
1813 output.println("struct atomicprimitives_"+ar.name+" primitives_"+ar.name+";");
1817 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1818 if (md!=null&&(state.DSM||state.SINGLETM))
1819 output.print(" struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1820 else if (md!=null&&!(state.DSM||state.SINGLETM))
1821 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1823 output.print(" struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={");
1824 output.print(objecttemp.numPointers()+",");
1825 output.print(paramsprefix);
1826 for(int j=0; j<objecttemp.numPointers(); j++)
1827 output.print(", NULL");
1828 output.println("};");
1831 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1832 TempDescriptor td=objecttemp.getPrimitive(i);
1833 TypeDescriptor type=td.getType();
1835 output.println(" void * "+td.getSafeSymbol()+";");
1836 else if (type.isClass()||type.isArray())
1837 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1839 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1843 if( state.MLP || state.OOOJAVA ) {
1844 if( fm.getNext(0) instanceof FlatSESEEnterNode ) {
1845 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
1846 if( (state.MLP && callerSESEplaceholder != mlpa.getMainSESE()) ||
1847 (state.OOOJAVA && callerSESEplaceholder != oooa.getMainSESE())
1849 // declare variables for naming static SESE's
1850 output.println(" /* static SESE names */");
1851 Iterator<SESEandAgePair> pItr = callerSESEplaceholder.getNeededStaticNames().iterator();
1852 while( pItr.hasNext() ) {
1853 SESEandAgePair pair = pItr.next();
1854 output.println(" void* "+pair+";");
1857 // declare variables for tracking dynamic sources
1858 output.println(" /* dynamic variable sources */");
1859 Iterator<TempDescriptor> dynSrcItr = callerSESEplaceholder.getDynamicVarSet().iterator();
1860 while( dynSrcItr.hasNext() ) {
1861 TempDescriptor dynSrcVar = dynSrcItr.next();
1862 output.println(" void* "+dynSrcVar+"_srcSESE;");
1863 output.println(" INTPTR "+dynSrcVar+"_srcOffset;");
1868 // set up related allocation sites's waiting queues
1871 ConflictGraph graph = null;
1872 graph = mlpa.getConflictGraphResults().get(fm);
1873 if (graph != null && graph.hasConflictEdge()) {
1874 output.println(" /* set up waiting queues */");
1875 output.println(" int numMemoryQueue=0;");
1876 output.println(" int memoryQueueItemID=0;");
1877 HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
1879 System.out.println("#lockSet="+lockSet.hashCode());
1880 System.out.println("lockset="+lockSet);
1881 for (Iterator iterator = lockSet.iterator(); iterator.hasNext();) {
1882 SESELock seseLock = (SESELock) iterator.next();
1883 System.out.println("id="+seseLock.getID());
1884 System.out.println("#="+seseLock);
1886 System.out.println("size="+lockSet.size());
1887 if (lockSet.size() > 0) {
1888 output.println(" numMemoryQueue=" + lockSet.size() + ";");
1890 .println(" seseCaller->numMemoryQueue=numMemoryQueue;");
1892 .println(" seseCaller->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
1897 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
1898 if(callerSESEplaceholder!= oooa.getMainSESE()){
1899 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(callerSESEplaceholder);
1900 if (graph != null && graph.hasConflictEdge()) {
1901 output.println(" // set up waiting queues ");
1902 output.println(" int numMemoryQueue=0;");
1903 output.println(" int memoryQueueItemID=0;");
1904 Set<Analysis.OoOJava.SESELock> lockSet = oooa.getLockMappings(graph);
1905 System.out.println("#lockSet="+lockSet.hashCode());
1906 System.out.println("lockset="+lockSet);
1907 for (Iterator iterator = lockSet.iterator(); iterator.hasNext();) {
1908 Analysis.OoOJava.SESELock seseLock = (Analysis.OoOJava.SESELock) iterator.next();
1909 System.out.println("id="+seseLock.getID());
1910 System.out.println("#="+seseLock);
1912 System.out.println("size="+lockSet.size());
1913 if (lockSet.size() > 0) {
1914 output.println(" numMemoryQueue=" + lockSet.size() + ";");
1916 .println(" seseCaller->numMemoryQueue=numMemoryQueue;");
1918 .println(" seseCaller->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
1928 /* Check to see if we need to do a GC if this is a
1929 * multi-threaded program...*/
1931 if (((state.MLP||state.OOOJAVA||state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
1932 || this.state.MULTICOREGC) {
1933 //Don't bother if we aren't in recursive methods...The loops case will catch it
1934 if (callgraph.getAllMethods(md).contains(md)) {
1935 if (state.DSM&&lb.isAtomic())
1936 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
1937 else if (this.state.MULTICOREGC) {
1938 output.println("if(gcflag) gc("+localsprefixaddr+");");
1940 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
1945 generateCode(fm.getNext(0), fm, lb, null, output, true);
1947 output.println("}\n\n");
1951 protected void initializeSESE( FlatSESEEnterNode fsen ) {
1953 FlatMethod fm = fsen.getfmEnclosing();
1954 MethodDescriptor md = fm.getMethod();
1955 ClassDescriptor cn = md.getClassDesc();
1958 // Creates bogus method descriptor to index into tables
1959 Modifiers modBogus = new Modifiers();
1960 MethodDescriptor mdBogus =
1961 new MethodDescriptor( modBogus,
1962 new TypeDescriptor( TypeDescriptor.VOID ),
1963 "sese_"+fsen.getPrettyIdentifier()+fsen.getIdentifier()
1966 mdBogus.setClassDesc( fsen.getcdEnclosing() );
1967 FlatMethod fmBogus = new FlatMethod( mdBogus, null );
1968 fsen.setfmBogus( fmBogus );
1969 fsen.setmdBogus( mdBogus );
1971 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1972 inSetAndOutSet.addAll( fsen.getInVarSet() );
1973 inSetAndOutSet.addAll( fsen.getOutVarSet() );
1975 // Build paramsobj for bogus method descriptor
1976 ParamsObject objectparams = new ParamsObject( mdBogus, tag++ );
1977 paramstable.put( mdBogus, objectparams );
1979 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1980 while( itr.hasNext() ) {
1981 TempDescriptor temp = itr.next();
1982 TypeDescriptor type = temp.getType();
1983 if( type.isPtr() ) {
1984 objectparams.addPtr( temp );
1986 objectparams.addPrim( temp );
1990 // Build normal temp object for bogus method descriptor
1991 TempObject objecttemps = new TempObject( objectparams, mdBogus, tag++ );
1992 tempstable.put( mdBogus, objecttemps );
1994 for( Iterator nodeit = fsen.getNodeSet().iterator(); nodeit.hasNext(); ) {
1995 FlatNode fn = (FlatNode)nodeit.next();
1996 TempDescriptor[] writes = fn.writesTemps();
1998 for( int i = 0; i < writes.length; i++ ) {
1999 TempDescriptor temp = writes[i];
2000 TypeDescriptor type = temp.getType();
2002 if( type.isPtr() ) {
2003 objecttemps.addPtr( temp );
2005 objecttemps.addPrim( temp );
2011 // used when generating the specific SESE record struct
2012 // to remember the FIRST field name of sese records
2013 // that the current SESE depends on--we need to know the
2014 // offset to the first one for garbage collection
2015 protected void addingDepRecField( FlatSESEEnterNode fsen,
2017 if( fsen.getFirstDepRecField() == null ) {
2018 fsen.setFirstDepRecField( field );
2020 fsen.incNumDepRecs();
2023 protected void generateMethodSESE(FlatSESEEnterNode fsen,
2025 PrintWriter outputStructs,
2026 PrintWriter outputMethHead,
2027 PrintWriter outputMethods
2030 ParamsObject objectparams = (ParamsObject) paramstable.get( fsen.getmdBogus() );
2031 TempObject objecttemps = (TempObject) tempstable .get( fsen.getmdBogus() );
2033 // generate locals structure
2034 outputStructs.println("struct "+
2035 fsen.getcdEnclosing().getSafeSymbol()+
2036 fsen.getmdBogus().getSafeSymbol()+"_"+
2037 fsen.getmdBogus().getSafeMethodDescriptor()+
2039 outputStructs.println(" int size;");
2040 outputStructs.println(" void * next;");
2041 for(int i=0; i<objecttemps.numPointers(); i++) {
2042 TempDescriptor temp=objecttemps.getPointer(i);
2044 if (temp.getType().isNull())
2045 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
2047 outputStructs.println(" struct "+
2048 temp.getType().getSafeSymbol()+" * "+
2049 temp.getSafeSymbol()+";");
2051 outputStructs.println("};\n");
2054 // divide in-set and out-set into objects and primitives to prep
2055 // for the record generation just below
2056 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
2057 inSetAndOutSet.addAll( fsen.getInVarSet() );
2058 inSetAndOutSet.addAll( fsen.getOutVarSet() );
2060 Set<TempDescriptor> inSetAndOutSetObjs = new HashSet<TempDescriptor>();
2061 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
2063 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
2064 while( itr.hasNext() ) {
2065 TempDescriptor temp = itr.next();
2066 TypeDescriptor type = temp.getType();
2067 if( type.isPtr() ) {
2068 inSetAndOutSetObjs.add( temp );
2070 inSetAndOutSetPrims.add( temp );
2075 // generate the SESE record structure
2076 outputStructs.println(fsen.getSESErecordName()+" {");
2078 // data common to any SESE, and it must be placed first so
2079 // a module that doesn't know what kind of SESE record this
2080 // is can cast the pointer to a common struct
2081 outputStructs.println(" SESEcommon common;");
2083 // then garbage list stuff
2084 outputStructs.println(" /* next is in-set and out-set objects that look like a garbage list */");
2085 outputStructs.println(" int size;");
2086 outputStructs.println(" void * next;");
2088 // I think that the set of TempDescriptors inSetAndOutSetObjs
2089 // calculated above should match the pointer object params
2090 // used in the following code, but let's just leave the working
2091 // implementation unless there is actually a problem...
2092 for(int i=0; i<objectparams.numPointers(); i++) {
2093 TempDescriptor temp=objectparams.getPointer(i);
2094 if (temp.getType().isNull())
2095 outputStructs.println(" void * "+temp.getSafeSymbol()+
2096 "; /* in-or-out-set obj in gl */");
2098 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+
2099 temp.getSafeSymbol()+"; /* in-or-out-set obj in gl */");
2102 outputStructs.println(" /* next is primitives for in-set and out-set and dynamic tracking */");
2104 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
2105 while( itrPrims.hasNext() ) {
2106 TempDescriptor temp = itrPrims.next();
2107 TypeDescriptor type = temp.getType();
2108 if(type.isPrimitive()){
2109 outputStructs.println(" "+temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol()+"; /* in-set or out-set primitive */");
2113 // note that the sese record pointer will be added below, just primitive part of tracking here
2114 Iterator<TempDescriptor> itrDynInVars = fsen.getDynamicInVarSet().iterator();
2115 while( itrDynInVars.hasNext() ) {
2116 TempDescriptor dynInVar = itrDynInVars.next();
2117 outputStructs.println(" INTPTR "+dynInVar+"_srcOffset; /* dynamic tracking primitive */");
2121 outputStructs.println(" /* everything after this should be pointers to an SESE record */" );
2123 // other half of info for dynamic tracking, the SESE record pointer
2124 itrDynInVars = fsen.getDynamicInVarSet().iterator();
2125 while( itrDynInVars.hasNext() ) {
2126 TempDescriptor dynInVar = itrDynInVars.next();
2127 String depRecField = dynInVar+"_srcSESE";
2128 outputStructs.println(" void* "+depRecField+";");
2129 addingDepRecField( fsen, depRecField );
2132 // statically known sese sources are record pointers, too
2133 Iterator<SESEandAgePair> itrStaticInVarSrcs = fsen.getStaticInVarSrcs().iterator();
2134 while( itrStaticInVarSrcs.hasNext() ) {
2135 SESEandAgePair srcPair = itrStaticInVarSrcs.next();
2136 outputStructs.println(" "+srcPair.getSESE().getSESErecordName()+"* "+srcPair+";");
2137 addingDepRecField( fsen, srcPair.toString() );
2140 if( fsen.getFirstDepRecField() != null ) {
2141 outputStructs.println(" /* compiler believes first dependent SESE record field above is: "+
2142 fsen.getFirstDepRecField()+" */" );
2145 outputStructs.println("};\n");
2148 // write method declaration to header file
2149 outputMethHead.print("void ");
2150 outputMethHead.print(fsen.getSESEmethodName()+"(");
2151 outputMethHead.print(fsen.getSESErecordName()+"* "+paramsprefix);
2152 outputMethHead.println(");\n");
2155 generateFlatMethodSESE( fsen.getfmBogus(),
2156 fsen.getcdEnclosing(),
2162 private void generateFlatMethodSESE(FlatMethod fm,
2164 FlatSESEEnterNode fsen,
2165 FlatSESEExitNode seseExit,
2169 MethodDescriptor md=fm.getMethod();
2171 output.print("void ");
2172 output.print(fsen.getSESEmethodName()+"(");
2173 output.print(fsen.getSESErecordName()+"* "+paramsprefix);
2174 output.println("){\n");
2176 TempObject objecttemp=(TempObject) tempstable.get(md);
2178 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2179 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
2180 output.print(objecttemp.numPointers()+",");
2181 output.print("&(((SESEcommon*)(___params___))[1])");
2182 for(int j=0; j<objecttemp.numPointers(); j++)
2183 output.print(", NULL");
2184 output.println("};");
2187 output.println(" /* regular local primitives */");
2188 for(int i=0; i<objecttemp.numPrimitives(); i++) {
2189 TempDescriptor td=objecttemp.getPrimitive(i);
2190 TypeDescriptor type=td.getType();
2192 output.println(" void * "+td.getSafeSymbol()+";");
2193 else if (type.isClass()||type.isArray())
2194 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
2196 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
2200 // declare variables for naming static SESE's
2201 output.println(" /* static SESE names */");
2202 Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
2203 while( pItr.hasNext() ) {
2204 SESEandAgePair pair = pItr.next();
2205 output.println(" void* "+pair+";");
2208 // declare variables for tracking dynamic sources
2209 output.println(" /* dynamic variable sources */");
2210 Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
2211 while( dynSrcItr.hasNext() ) {
2212 TempDescriptor dynSrcVar = dynSrcItr.next();
2213 output.println(" void* "+dynSrcVar+"_srcSESE;");
2214 output.println(" INTPTR "+dynSrcVar+"_srcOffset;");
2217 // declare local temps for in-set primitives, and if it is
2218 // a ready-source variable, get the value from the record
2219 output.println(" /* local temps for in-set primitives */");
2220 Iterator<TempDescriptor> itrInSet = fsen.getInVarSet().iterator();
2221 while( itrInSet.hasNext() ) {
2222 TempDescriptor temp = itrInSet.next();
2223 TypeDescriptor type = temp.getType();
2224 if( !type.isPtr() ) {
2225 if( fsen.getReadyInVarSet().contains( temp ) ) {
2226 output.println(" "+type+" "+temp+" = "+paramsprefix+"->"+temp+";");
2228 output.println(" "+type+" "+temp+";");
2233 // declare local temps for out-set primitives if its not already
2234 // in the in-set, and it's value will get written so no problem
2235 output.println(" /* local temp for out-set prim, not already in the in-set */");
2236 Iterator<TempDescriptor> itrOutSet = fsen.getOutVarSet().iterator();
2237 while( itrOutSet.hasNext() ) {
2238 TempDescriptor temp = itrOutSet.next();
2239 TypeDescriptor type = temp.getType();
2240 if( !type.isPtr() && !fsen.getInVarSet().contains( temp ) ) {
2241 output.println(" "+type+" "+temp+";");
2245 // setup memory queue
2248 output.println(" // set up memory queues ");
2249 output.println(" int numMemoryQueue=0;");
2250 output.println(" int memoryQueueItemID=0;");
2251 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(fsen);
2252 if (graph != null && graph.hasConflictEdge()) {
2253 output.println(" {");
2255 .println(" SESEcommon* parentCommon = &(___params___->common);");
2256 Set<Analysis.OoOJava.SESELock> lockSet = oooa.getLockMappings(graph);
2257 System.out.println("#lockSet="+lockSet);
2258 if (lockSet.size() > 0) {
2259 output.println(" numMemoryQueue=" + lockSet.size() + ";");
2261 .println(" parentCommon->numMemoryQueue=numMemoryQueue;");
2263 .println(" parentCommon->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2266 output.println(" }");
2269 output.println(" // set up memory queues ");
2270 output.println(" int numMemoryQueue=0;");
2271 output.println(" int memoryQueueItemID=0;");
2272 ConflictGraph graph = null;
2273 graph = mlpa.getConflictGraphResults().get(fsen);
2274 if (graph != null && graph.hasConflictEdge()) {
2275 output.println(" {");
2277 .println(" SESEcommon* parentCommon = &(___params___->common);");
2278 HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
2280 System.out.println("#lockSet="+lockSet);
2282 if (lockSet.size() > 0) {
2283 output.println(" numMemoryQueue=" + lockSet.size() + "; ");
2285 .println(" parentCommon->numMemoryQueue=numMemoryQueue;");
2287 .println(" parentCommon->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2290 output.println(" }");
2296 // copy in-set into place, ready vars were already
2297 // copied when the SESE was issued
2298 Iterator<TempDescriptor> tempItr;
2300 // static vars are from a known SESE
2301 tempItr = fsen.getStaticInVarSet().iterator();
2302 while( tempItr.hasNext() ) {
2303 TempDescriptor temp = tempItr.next();
2304 VariableSourceToken vst = fsen.getStaticInVarSrc( temp );
2305 SESEandAgePair srcPair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2307 // can't grab something from this source until it is done
2308 output.println(" {");
2310 If we are running, everything is done. This check is redundant.
2312 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+srcPair+";" );
2313 output.println(" pthread_mutex_lock( &(com->lock) );");
2314 output.println(" while( com->doneExecuting == FALSE ) {");
2315 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
2316 output.println(" }");
2317 output.println(" pthread_mutex_unlock( &(com->lock) );");
2319 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2320 " = "+paramsprefix+"->"+srcPair+"->"+vst.getAddrVar()+";");
2322 output.println(" }");
2325 // dynamic vars come from an SESE and src
2326 tempItr = fsen.getDynamicInVarSet().iterator();
2327 while( tempItr.hasNext() ) {
2328 TempDescriptor temp = tempItr.next();
2329 TypeDescriptor type = temp.getType();
2331 // go grab it from the SESE source
2332 output.println(" if( "+paramsprefix+"->"+temp+"_srcSESE != NULL ) {");
2334 // gotta wait until the source is done
2335 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+temp+"_srcSESE;" );
2337 If we are running, everything is done!
2338 output.println(" pthread_mutex_lock( &(com->lock) );");
2339 output.println(" while( com->doneExecuting == FALSE ) {");
2340 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
2341 output.println(" }");
2342 output.println(" pthread_mutex_unlock( &(com->lock) );");
2346 if( type.isNull() ) {
2348 } else if( type.isClass() || type.isArray() ) {
2349 typeStr = "struct "+type.getSafeSymbol()+"*";
2351 typeStr = type.getSafeSymbol();
2354 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2355 " = *(("+typeStr+"*) ("+
2356 paramsprefix+"->"+temp+"_srcSESE + "+
2357 paramsprefix+"->"+temp+"_srcOffset));");
2359 // or if the source was our parent, its in the record to grab
2360 output.println(" } else {");
2361 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2362 " = "+paramsprefix+"->"+temp+";");
2363 output.println(" }");
2366 // Check to see if we need to do a GC if this is a
2367 // multi-threaded program...
2368 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2369 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2370 //Don't bother if we aren't in recursive methods...The loops case will catch it
2371 // if (callgraph.getAllMethods(md).contains(md)) {
2372 // if(this.state.MULTICOREGC) {
2373 // output.println("if(gcflag) gc("+localsprefixaddr+");");
2375 // output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2380 // initialize thread-local var to a non-zero, invalid address
2381 output.println(" seseCaller = (SESEcommon*) 0x2;");
2382 HashSet<FlatNode> exitset=new HashSet<FlatNode>();
2383 exitset.add(seseExit);
2384 generateCode(fsen.getNext(0), fm, null, exitset, output, true);
2385 output.println("}\n\n");
2390 // when a new mlp thread is created for an issued SESE, it is started
2391 // by running this method which blocks on a cond variable until
2392 // it is allowed to transition to execute. Then a case statement
2393 // allows it to invoke the method with the proper SESE body, and after
2394 // exiting the SESE method, executes proper SESE exit code before the
2395 // thread can be destroyed
2396 private void generateSESEinvocationMethod(PrintWriter outmethodheader,
2397 PrintWriter outmethod
2400 outmethodheader.println("void* invokeSESEmethod( void* seseRecord );");
2401 outmethod.println( "void* invokeSESEmethod( void* seseRecord ) {");
2402 outmethod.println( " int status;");
2403 outmethod.println( " char errmsg[128];");
2405 // generate a case for each SESE class that can be invoked
2406 outmethod.println( " switch( *((int*)seseRecord) ) {");
2407 outmethod.println( " ");
2408 Iterator<FlatSESEEnterNode> seseit;
2410 seseit=mlpa.getAllSESEs().iterator();
2412 seseit=oooa.getAllSESEs().iterator();
2414 while(seseit.hasNext()){
2415 FlatSESEEnterNode fsen = seseit.next();
2417 outmethod.println( " /* "+fsen.getPrettyIdentifier()+" */");
2418 outmethod.println( " case "+fsen.getIdentifier()+":");
2419 outmethod.println( " "+fsen.getSESEmethodName()+"( seseRecord );");
2421 if( (state.MLP && fsen.equals( mlpa.getMainSESE() )) ||
2422 (state.OOOJAVA && fsen.equals( oooa.getMainSESE() ))
2424 outmethod.println( " /* work scheduler works forever, explicitly exit */");
2425 if (state.COREPROF) {
2426 outmethod.println("CP_EXIT();");
2427 outmethod.println("CP_DUMP();");
2429 outmethod.println( " exit( 0 );");
2432 outmethod.println( " break;");
2433 outmethod.println( "");
2436 // default case should never be taken, error out
2437 outmethod.println( " default:");
2438 outmethod.println( " printf(\"Error: unknown SESE class ID in invoke method.\\n\");");
2439 outmethod.println( " exit(-30);");
2440 outmethod.println( " break;");
2441 outmethod.println( " }");
2442 outmethod.println( " return NULL;");
2443 outmethod.println( "}\n\n");
2447 protected void generateCode(FlatNode first,
2450 Set<FlatNode> stopset,
2451 PrintWriter output, boolean firstpass) {
2453 /* Assign labels to FlatNode's if necessary.*/
2455 Hashtable<FlatNode, Integer> nodetolabel;
2457 if (state.DELAYCOMP&&!firstpass)
2458 nodetolabel=dcassignLabels(first, stopset);
2460 nodetolabel=assignLabels(first, stopset);
2462 Set<FlatNode> storeset=null;
2463 HashSet<FlatNode> genset=null;
2464 HashSet<FlatNode> refset=null;
2465 Set<FlatNode> unionset=null;
2467 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
2468 storeset=delaycomp.livecode(lb);
2469 genset=new HashSet<FlatNode>();
2470 if (state.STMARRAY&&!state.DUALVIEW) {
2471 refset=new HashSet<FlatNode>();
2472 refset.addAll(delaycomp.getDeref(lb));
2473 refset.removeAll(delaycomp.getCannotDelay(lb));
2474 refset.removeAll(delaycomp.getOther(lb));
2477 genset.addAll(delaycomp.getCannotDelay(lb));
2478 genset.addAll(delaycomp.getOther(lb));
2480 genset.addAll(delaycomp.getNotReady(lb));
2481 if (state.STMARRAY&&!state.DUALVIEW) {
2482 genset.removeAll(refset);
2485 unionset=new HashSet<FlatNode>();
2486 unionset.addAll(storeset);
2487 unionset.addAll(genset);
2488 if (state.STMARRAY&&!state.DUALVIEW)
2489 unionset.addAll(refset);
2492 /* Do the actual code generation */
2493 FlatNode current_node=null;
2494 HashSet tovisit=new HashSet();
2495 HashSet visited=new HashSet();
2497 tovisit.add(first.getNext(0));
2500 while(current_node!=null||!tovisit.isEmpty()) {
2501 if (current_node==null) {
2502 current_node=(FlatNode)tovisit.iterator().next();
2503 tovisit.remove(current_node);
2504 } else if (tovisit.contains(current_node)) {
2505 tovisit.remove(current_node);
2507 visited.add(current_node);
2508 if (nodetolabel.containsKey(current_node)) {
2509 output.println("L"+nodetolabel.get(current_node)+":");
2511 if (state.INSTRUCTIONFAILURE) {
2512 if (state.THREAD||state.DSM||state.SINGLETM) {
2513 output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
2515 output.println("if ((--instructioncount)==0) injectinstructionfailure();");
2517 if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
2519 if (!state.DELAYCOMP||firstpass) {
2520 generateFlatNode(fm, lb, current_node, output);
2522 //store primitive variables in out set
2523 AtomicRecord ar=atomicmethodmap.get((FlatAtomicEnterNode)first);
2524 Set<TempDescriptor> liveout=ar.liveout;
2525 for(Iterator<TempDescriptor> tmpit=liveout.iterator();tmpit.hasNext();) {
2526 TempDescriptor tmp=tmpit.next();
2527 output.println("primitives->"+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2530 if ((state.MLP || state.OOOJAVA) && stopset!=null) {
2531 assert first.getPrev( 0 ) instanceof FlatSESEEnterNode;
2532 assert current_node instanceof FlatSESEExitNode;
2533 FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev( 0 );
2534 FlatSESEExitNode fsxn = (FlatSESEExitNode) current_node;
2535 assert fsen.getFlatExit().equals( fsxn );
2536 assert fsxn.getFlatEnter().equals( fsen );
2538 if (current_node.kind()!=FKind.FlatReturnNode) {
2539 output.println(" return;");
2542 } else if(current_node.numNext()==1) {
2544 if ((state.MLP|| state.OOOJAVA) &&
2545 current_node.kind()==FKind.FlatSESEEnterNode &&
2546 !((FlatSESEEnterNode)current_node).getIsCallerSESEplaceholder()
2548 FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
2549 generateFlatNode(fm, lb, current_node, output);
2550 nextnode=fsen.getFlatExit().getNext(0);
2551 } else if (state.DELAYCOMP) {
2552 boolean specialprimitive=false;
2553 //skip literals...no need to add extra overhead
2554 if (storeset!=null&&storeset.contains(current_node)&¤t_node.kind()==FKind.FlatLiteralNode) {
2555 TypeDescriptor typedesc=((FlatLiteralNode)current_node).getType();
2556 if (!typedesc.isClass()&&!typedesc.isArray()) {
2557 specialprimitive=true;
2561 if (genset==null||genset.contains(current_node)||specialprimitive)
2562 generateFlatNode(fm, lb, current_node, output);
2563 if (state.STMARRAY&&!state.DUALVIEW&&refset!=null&&refset.contains(current_node)) {
2564 //need to acquire lock
2565 handleArrayDeref(fm, lb, current_node, output, firstpass);
2567 if (storeset!=null&&storeset.contains(current_node)&&!specialprimitive) {
2568 TempDescriptor wrtmp=current_node.writesTemps()[0];
2570 //need to store value written by previous node
2571 if (wrtmp.getType().isPtr()) {
2572 //only lock the objects that may actually need locking
2573 if (recorddc.getNeedTrans(lb, current_node)&&
2574 (!state.STMARRAY||state.DUALVIEW||!wrtmp.getType().isArray()||
2575 wrtmp.getType().getSymbol().equals(TypeUtil.ObjectClass))) {
2576 output.println("STOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2578 output.println("STOREPTRNOLOCK("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2581 output.println("STORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");/* "+current_node.nodeid+" */");
2584 //need to read value read by previous node
2585 if (wrtmp.getType().isPtr()) {
2586 output.println("RESTOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2588 output.println("RESTORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+"); /* "+current_node.nodeid+" */");
2592 nextnode=current_node.getNext(0);
2595 generateFlatNode(fm, lb, current_node, output);
2596 nextnode=current_node.getNext(0);
2598 if (visited.contains(nextnode)) {
2599 output.println("goto L"+nodetolabel.get(nextnode)+";");
2602 current_node=nextnode;
2603 } else if (current_node.numNext()==2) {
2605 if (state.DELAYCOMP) {
2606 boolean computeside=false;
2608 //need to record which way it should go
2609 if (genset==null||genset.contains(current_node)) {
2610 if (storeset!=null&&storeset.contains(current_node)) {
2611 //need to store which way branch goes
2612 generateStoreFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2614 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2616 //which side to execute
2620 if (genset.contains(current_node)) {
2621 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2622 } else if (storeset.contains(current_node)) {
2624 branchanalysis.generateGroupCode(current_node, output, nodetolabel);
2626 //which side to execute
2631 Set<FlatNode> leftset=DelayComputation.getNext(current_node, 0, unionset, lb,locality, true);
2633 if (leftset.size()==0)
2635 if (visited.contains(current_node.getNext(branch))) {
2636 //already visited -- build jump
2637 output.println("goto L"+nodetolabel.get(current_node.getNext(branch))+";");
2640 current_node=current_node.getNext(branch);
2643 if (!visited.contains(current_node.getNext(1)))
2644 tovisit.add(current_node.getNext(1));
2645 if (visited.contains(current_node.getNext(0))) {
2646 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2649 current_node=current_node.getNext(0);
2653 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2654 if (!visited.contains(current_node.getNext(1)))
2655 tovisit.add(current_node.getNext(1));
2656 if (visited.contains(current_node.getNext(0))) {
2657 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2660 current_node=current_node.getNext(0);
2662 } else throw new Error();
2666 protected void handleArrayDeref(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output, boolean firstpass) {
2667 if (fn.kind()==FKind.FlatSetElementNode) {
2668 FlatSetElementNode fsen=(FlatSetElementNode) fn;
2669 String dst=generateTemp(fm, fsen.getDst(), lb);
2670 String src=generateTemp(fm, fsen.getSrc(), lb);
2671 String index=generateTemp(fm, fsen.getIndex(), lb);
2672 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
2674 if (elementtype.isArray()||elementtype.isClass())
2677 type=elementtype.getSafeSymbol()+" ";
2679 output.println("STOREARRAY("+dst+","+index+","+type+")");
2681 output.println("{");
2682 output.println(" struct ArrayObject *array;");
2683 output.println(" int index;");
2684 output.println(" RESTOREARRAY(array,index);");
2685 output.println(" (("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index]="+src+";");
2686 output.println("}");
2688 } else if (fn.kind()==FKind.FlatElementNode) {
2689 FlatElementNode fen=(FlatElementNode) fn;
2690 String src=generateTemp(fm, fen.getSrc(), lb);
2691 String index=generateTemp(fm, fen.getIndex(), lb);
2692 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
2693 String dst=generateTemp(fm, fen.getDst(), lb);
2695 if (elementtype.isArray()||elementtype.isClass())
2698 type=elementtype.getSafeSymbol()+" ";
2700 output.println("STOREARRAY("+src+","+index+","+type+")");
2702 output.println("{");
2703 output.println(" struct ArrayObject *array;");
2704 output.println(" int index;");
2705 output.println(" RESTOREARRAY(array,index);");
2706 output.println(" "+dst+"=(("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index];");
2707 output.println("}");
2711 /** Special label assignment for delaycomputation */
2712 protected Hashtable<FlatNode, Integer> dcassignLabels(FlatNode first, Set<FlatNode> lastset) {
2713 HashSet tovisit=new HashSet();
2714 HashSet visited=new HashSet();
2716 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2718 //Label targets of branches
2719 Set<FlatNode> targets=branchanalysis.getTargets();
2720 for(Iterator<FlatNode> it=targets.iterator();it.hasNext();) {
2721 nodetolabel.put(it.next(), new Integer(labelindex++));
2726 /*Assign labels first. A node needs a label if the previous
2727 * node has two exits or this node is a join point. */
2729 while(!tovisit.isEmpty()) {
2730 FlatNode fn=(FlatNode)tovisit.iterator().next();
2735 if(lastset!=null&&lastset.contains(fn)) {
2736 // if last is not null and matches, don't go
2737 // any further for assigning labels
2741 for(int i=0; i<fn.numNext(); i++) {
2742 FlatNode nn=fn.getNext(i);
2745 //1) Edge >1 of node
2746 nodetolabel.put(nn,new Integer(labelindex++));
2748 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2752 nodetolabel.put(nn,new Integer(labelindex++));
2760 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first) {
2761 return assignLabels(first, null);
2764 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
2765 HashSet tovisit=new HashSet();
2766 HashSet visited=new HashSet();
2768 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2771 /*Assign labels first. A node needs a label if the previous
2772 * node has two exits or this node is a join point. */
2774 while(!tovisit.isEmpty()) {
2775 FlatNode fn=(FlatNode)tovisit.iterator().next();
2780 if(lastset!=null&&lastset.contains(fn)) {
2781 // if last is not null and matches, don't go
2782 // any further for assigning labels
2786 for(int i=0; i<fn.numNext(); i++) {
2787 FlatNode nn=fn.getNext(i);
2790 //1) Edge >1 of node
2791 nodetolabel.put(nn,new Integer(labelindex++));
2793 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2797 nodetolabel.put(nn,new Integer(labelindex++));
2805 /** Generate text string that corresponds to the TempDescriptor td. */
2806 protected String generateTemp(FlatMethod fm, TempDescriptor td, LocalityBinding lb) {
2807 MethodDescriptor md=fm.getMethod();
2808 TaskDescriptor task=fm.getTask();
2809 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
2811 if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
2812 return td.getSafeSymbol();
2815 if (objecttemps.isLocalPtr(td)) {
2816 return localsprefixderef+td.getSafeSymbol();
2819 if (objecttemps.isParamPtr(td)) {
2820 return paramsprefix+"->"+td.getSafeSymbol();
2826 protected void generateFlatNode(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output) {
2828 // insert pre-node actions from the code plan
2829 if( state.MLP|| state.OOOJAVA ) {
2833 cp = mlpa.getCodePlan( fn );
2835 cp = oooa.getCodePlan(fn);
2840 FlatSESEEnterNode currentSESE = cp.getCurrentSESE();
2842 // for each sese and age pair that this parent statement
2843 // must stall on, take that child's stall semaphore, the
2844 // copying of values comes after the statement
2845 Iterator<VariableSourceToken> vstItr = cp.getStallTokens().iterator();
2846 while( vstItr.hasNext() ) {
2847 VariableSourceToken vst = vstItr.next();
2849 SESEandAgePair pair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2851 output.println(" {");
2852 output.println(" SESEcommon* common = (SESEcommon*) "+pair+";");
2853 //output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_BEGIN );");
2854 output.println(" pthread_mutex_lock( &(common->lock) );");
2855 output.println(" while( common->doneExecuting == FALSE ) {");
2856 output.println(" pthread_cond_wait( &(common->doneCond), &(common->lock) );");
2857 output.println(" }");
2858 output.println(" pthread_mutex_unlock( &(common->lock) );");
2860 // copy things we might have stalled for
2861 output.println(" "+pair.getSESE().getSESErecordName()+"* child = ("+
2862 pair.getSESE().getSESErecordName()+"*) "+pair+";");
2864 Iterator<TempDescriptor> tdItr = cp.getCopySet( vst ).iterator();
2865 while( tdItr.hasNext() ) {
2866 TempDescriptor td = tdItr.next();
2867 FlatMethod fmContext;
2868 if( currentSESE.getIsCallerSESEplaceholder() ) {
2869 fmContext = currentSESE.getfmEnclosing();
2871 fmContext = currentSESE.getfmBogus();
2873 output.println(" "+generateTemp( fmContext, td, null )+
2874 " = child->"+vst.getAddrVar().getSafeSymbol()+";");
2877 //output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_END );");
2878 output.println(" }");
2881 // for each variable with a dynamic source, stall just for that variable
2882 Iterator<TempDescriptor> dynItr = cp.getDynamicStallSet().iterator();
2883 while( dynItr.hasNext() ) {
2884 TempDescriptor dynVar = dynItr.next();
2886 // only stall if the dynamic source is not yourself, denoted by src==NULL
2887 // otherwise the dynamic write nodes will have the local var up-to-date
2888 output.println(" {");
2889 output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
2890 //output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_BEGIN );");
2891 output.println(" SESEcommon* common = (SESEcommon*) "+dynVar+"_srcSESE;");
2892 output.println(" psem_take( &(common->stallSem) );");
2894 FlatMethod fmContext;
2895 if( currentSESE.getIsCallerSESEplaceholder() ) {
2896 fmContext = currentSESE.getfmEnclosing();
2898 fmContext = currentSESE.getfmBogus();
2901 TypeDescriptor type=dynVar.getType();
2903 if( type.isNull() ) {
2905 } else if( type.isClass() || type.isArray() ) {
2906 typeStr = "struct "+type.getSafeSymbol()+"*";
2908 typeStr = type.getSafeSymbol();
2911 output.println(" "+generateTemp( fmContext, dynVar, null )+
2912 " = *(("+typeStr+"*) ("+
2913 dynVar+"_srcSESE + "+dynVar+"_srcOffset));");
2914 //output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_END );");
2915 output.println(" }");
2916 output.println(" }");
2919 // for each assignment of a variable to rhs that has a dynamic source,
2920 // copy the dynamic sources
2921 Iterator dynAssignItr = cp.getDynAssigns().entrySet().iterator();
2922 while( dynAssignItr.hasNext() ) {
2923 Map.Entry me = (Map.Entry) dynAssignItr.next();
2924 TempDescriptor lhs = (TempDescriptor) me.getKey();
2925 TempDescriptor rhs = (TempDescriptor) me.getValue();
2926 output.println(" "+lhs+"_srcSESE = "+rhs+"_srcSESE;");
2927 output.println(" "+lhs+"_srcOffset = "+rhs+"_srcOffset;");
2930 // for each lhs that is dynamic from a non-dynamic source, set the
2931 // dynamic source vars to the current SESE
2932 dynItr = cp.getDynAssignCurr().iterator();
2933 while( dynItr.hasNext() ) {
2934 TempDescriptor dynVar = dynItr.next();
2935 assert currentSESE.getDynamicVarSet().contains( dynVar );
2936 output.println(" "+dynVar+"_srcSESE = NULL;");
2940 // handling stall site
2941 if (state.OOOJAVA) {
2942 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(currentSESE);
2944 Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
2945 Set<Analysis.OoOJava.WaitingElement> waitingElementSet =
2946 graph.getStallSiteWaitingElementSet(fn, seseLockSet);
2948 if(waitingElementSet.size()>0){
2949 output.println("// stall on parent's stall sites ");
2950 output.println(" {");
2951 output.println(" REntry* rentry;");
2953 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
2954 Analysis.OoOJava.WaitingElement waitingElement = (Analysis.OoOJava.WaitingElement) iterator.next();
2956 if(state.RCR && rcr != null){
2957 Analysis.OoOJava.ConflictGraph conflictGraph = graph;
2958 Hashtable<Taint, Set<Effect>> conflicts;
2959 ReachGraph rg = oooa.getDisjointAnalysis().getReachGraph(currentSESE.getmdEnclosing());
2960 if(rcr.cSideDebug) {
2961 rg.writeGraph("RCR_RG_STALLSITE_DEBUG");
2963 if((conflictGraph != null) &&
2964 (conflicts = graph.getConflictEffectSet(fn)) != null &&
2968 Hashtable<Taint, Set<Effect>> effects=oooa.getDisjointAnalysis().getEffectsAnalysis().get(fn);
2969 rcr.traverseStallSite(fn, waitingElement.getTempDesc(), effects, conflicts, rg);
2973 if( waitingElement.getStatus() >= ConflictNode.COARSE ){
2974 output.println(" rentry=mlpCreateREntry("+ waitingElement.getStatus()+ ", seseCaller);");
2976 output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", seseCaller, (void*)&" +generateTemp(fm,waitingElement.getTempDesc(),lb)+ ");");
2978 output.println(" psem_init( &(rentry->parentStallSem) );");
2979 output.println(" rentry->queue=seseCaller->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
2980 output.println(" if(ADDRENTRY(seseCaller->memoryQueueArray["+ waitingElement.getQueueID()
2981 + "],rentry)==NOTREADY){");
2982 //output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_BEGIN );");
2983 output.println(" psem_take( &(rentry->parentStallSem) );");
2984 //output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_END );");
2985 output.println(" } ");
2987 if(state.RCR && rcr != null) {
2988 output.println(" "+rcr.getTraverserInvocation(waitingElement.getTempDesc(),
2989 generateTemp(fm, waitingElement.getTempDesc(), null), fn));
2992 output.println(" }");
2996 ParentChildConflictsMap conflictsMap = mlpa.getConflictsResults().get(fn);
2997 if (conflictsMap != null) {
2998 Set<Long> allocSet = conflictsMap.getAllocationSiteIDSetofStallSite();
2999 if (allocSet.size() > 0) {
3000 FlatNode enclosingFlatNode=null;
3001 if( currentSESE.getIsCallerSESEplaceholder() && currentSESE.getParent()==null){
3002 enclosingFlatNode=currentSESE.getfmEnclosing();
3004 enclosingFlatNode=currentSESE;
3006 ConflictGraph graph=mlpa.getConflictGraphResults().get(enclosingFlatNode);
3007 HashSet<SESELock> seseLockSet=mlpa.getConflictGraphLockMap().get(graph);
3008 Set<WaitingElement> waitingElementSet=graph.getStallSiteWaitingElementSet(conflictsMap, seseLockSet);
3010 if(waitingElementSet.size()>0){
3011 output.println("// stall on parent's stall sites ");
3012 output.println(" {");
3013 output.println(" REntry* rentry;");
3015 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
3016 WaitingElement waitingElement = (WaitingElement) iterator.next();
3018 if( waitingElement.getStatus() >= ConflictNode.COARSE ){
3019 // HERE! a parent might conflict with a child
3020 output.println(" rentry=mlpCreateREntry("+ waitingElement.getStatus()+ ", seseCaller);");
3022 output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", seseCaller, (void*)&___locals___."+ waitingElement.getDynID() + ");");
3023 // output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", seseCaller, ___locals___."+ waitingElement.getDynID() + "->oid);");
3025 output.println(" psem_init( &(rentry->parentStallSem) );");
3026 output.println(" rentry->queue=seseCaller->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
3028 .println(" if(ADDRENTRY(seseCaller->memoryQueueArray["+ waitingElement.getQueueID()
3029 + "],rentry)==NOTREADY){");
3030 //output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_BEGIN );");
3031 output.println(" psem_take( &(rentry->parentStallSem) );");
3032 //output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_END );");
3033 output.println(" } ");
3035 output.println(" }");
3044 case FKind.FlatAtomicEnterNode:
3045 generateFlatAtomicEnterNode(fm, lb, (FlatAtomicEnterNode) fn, output);
3048 case FKind.FlatAtomicExitNode:
3049 generateFlatAtomicExitNode(fm, lb, (FlatAtomicExitNode) fn, output);
3052 case FKind.FlatInstanceOfNode:
3053 generateFlatInstanceOfNode(fm, lb, (FlatInstanceOfNode)fn, output);
3056 case FKind.FlatSESEEnterNode:
3057 generateFlatSESEEnterNode(fm, lb, (FlatSESEEnterNode)fn, output);
3060 case FKind.FlatSESEExitNode:
3061 generateFlatSESEExitNode(fm, lb, (FlatSESEExitNode)fn, output);
3064 case FKind.FlatWriteDynamicVarNode:
3065 generateFlatWriteDynamicVarNode(fm, lb, (FlatWriteDynamicVarNode)fn, output);
3068 case FKind.FlatGlobalConvNode:
3069 generateFlatGlobalConvNode(fm, lb, (FlatGlobalConvNode) fn, output);
3072 case FKind.FlatTagDeclaration:
3073 generateFlatTagDeclaration(fm, lb, (FlatTagDeclaration) fn,output);
3076 case FKind.FlatCall:
3077 generateFlatCall(fm, lb, (FlatCall) fn,output);
3080 case FKind.FlatFieldNode:
3081 generateFlatFieldNode(fm, lb, (FlatFieldNode) fn,output);
3084 case FKind.FlatElementNode:
3085 generateFlatElementNode(fm, lb, (FlatElementNode) fn,output);
3088 case FKind.FlatSetElementNode:
3089 generateFlatSetElementNode(fm, lb, (FlatSetElementNode) fn,output);
3092 case FKind.FlatSetFieldNode:
3093 generateFlatSetFieldNode(fm, lb, (FlatSetFieldNode) fn,output);
3097 generateFlatNew(fm, lb, (FlatNew) fn,output);
3100 case FKind.FlatOpNode:
3101 generateFlatOpNode(fm, lb, (FlatOpNode) fn,output);
3104 case FKind.FlatCastNode:
3105 generateFlatCastNode(fm, lb, (FlatCastNode) fn,output);
3108 case FKind.FlatLiteralNode:
3109 generateFlatLiteralNode(fm, lb, (FlatLiteralNode) fn,output);
3112 case FKind.FlatReturnNode:
3113 generateFlatReturnNode(fm, lb, (FlatReturnNode) fn,output);
3117 output.println("/* nop */");
3120 case FKind.FlatExit:
3121 output.println("/* exit */");
3124 case FKind.FlatBackEdge:
3125 if (state.SINGLETM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
3126 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
3128 if(state.DSM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
3129 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
3131 if (((state.MLP|| state.OOOJAVA||state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
3132 || (this.state.MULTICOREGC)) {
3133 if(state.DSM&&locality.getAtomic(lb).get(fn).intValue()>0) {
3134 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
3135 } else if(this.state.MULTICOREGC) {
3136 output.println("if (gcflag) gc("+localsprefixaddr+");");
3138 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3141 output.println("/* nop */");
3144 case FKind.FlatCheckNode:
3145 generateFlatCheckNode(fm, lb, (FlatCheckNode) fn, output);
3148 case FKind.FlatFlagActionNode:
3149 generateFlatFlagActionNode(fm, lb, (FlatFlagActionNode) fn, output);
3152 case FKind.FlatPrefetchNode:
3153 generateFlatPrefetchNode(fm,lb, (FlatPrefetchNode) fn, output);
3156 case FKind.FlatOffsetNode:
3157 generateFlatOffsetNode(fm, lb, (FlatOffsetNode)fn, output);
3164 // insert post-node actions from the code-plan
3167 CodePlan cp = mlpa.getCodePlan( fn );
3175 public void generateFlatOffsetNode(FlatMethod fm, LocalityBinding lb, FlatOffsetNode fofn, PrintWriter output) {
3176 output.println("/* FlatOffsetNode */");
3177 FieldDescriptor fd=fofn.getField();
3178 output.println(generateTemp(fm, fofn.getDst(),lb)+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+ fd.getSafeSymbol()+");");
3179 output.println("/* offset */");
3182 public void generateFlatPrefetchNode(FlatMethod fm, LocalityBinding lb, FlatPrefetchNode fpn, PrintWriter output) {
3183 if (state.PREFETCH) {
3184 Vector oids = new Vector();
3185 Vector fieldoffset = new Vector();
3186 Vector endoffset = new Vector();
3187 int tuplecount = 0; //Keeps track of number of prefetch tuples that need to be generated
3188 for(Iterator it = fpn.hspp.iterator(); it.hasNext();) {
3189 PrefetchPair pp = (PrefetchPair) it.next();
3190 Integer statusbase = locality.getNodePreTempInfo(lb,fpn).get(pp.base);
3191 /* Find prefetches that can generate oid */
3192 if(statusbase == LocalityAnalysis.GLOBAL) {
3193 generateTransCode(fm, lb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(lb).get(fpn).intValue()>0, false);
3195 } else if (statusbase == LocalityAnalysis.LOCAL) {
3196 generateTransCode(fm,lb,pp,oids,fieldoffset,endoffset,tuplecount,false,true);
3203 System.out.println("Adding prefetch "+fpn+ " to method:" +fm);
3204 output.println("{");
3205 output.println("/* prefetch */");
3206 output.println("/* prefetchid_" + fpn.siteid + " */");
3207 output.println("void * prefptr;");
3208 output.println("int tmpindex;");
3210 output.println("if((evalPrefetch["+fpn.siteid+"].operMode) || (evalPrefetch["+fpn.siteid+"].retrycount <= 0)) {");
3211 /*Create C code for oid array */
3212 output.print(" unsigned int oidarray_[] = {");
3213 boolean needcomma=false;
3214 for (Iterator it = oids.iterator(); it.hasNext();) {
3217 output.print(it.next());
3220 output.println("};");
3222 /*Create C code for endoffset values */
3223 output.print(" unsigned short endoffsetarry_[] = {");
3225 for (Iterator it = endoffset.iterator(); it.hasNext();) {
3228 output.print(it.next());
3231 output.println("};");
3233 /*Create C code for Field Offset Values */
3234 output.print(" short fieldarry_[] = {");
3236 for (Iterator it = fieldoffset.iterator(); it.hasNext();) {
3239 output.print(it.next());
3242 output.println("};");
3243 /* make the prefetch call to Runtime */
3244 output.println(" if(!evalPrefetch["+fpn.siteid+"].operMode) {");
3245 output.println(" evalPrefetch["+fpn.siteid+"].retrycount = RETRYINTERVAL;");
3246 output.println(" }");
3247 output.println(" prefetch("+fpn.siteid+" ,"+tuplecount+", oidarray_, endoffsetarry_, fieldarry_);");
3248 output.println(" } else {");
3249 output.println(" evalPrefetch["+fpn.siteid+"].retrycount--;");
3250 output.println(" }");
3251 output.println("}");
3255 public void generateTransCode(FlatMethod fm, LocalityBinding lb,PrefetchPair pp, Vector oids, Vector fieldoffset, Vector endoffset, int tuplecount, boolean inside, boolean localbase) {
3256 short offsetcount = 0;
3260 } else if (localbase) {
3261 for(; breakindex<pp.desc.size(); breakindex++) {
3262 Descriptor desc=pp.getDescAt(breakindex);
3263 if (desc instanceof FieldDescriptor) {
3264 FieldDescriptor fd=(FieldDescriptor)desc;
3265 if (fd.isGlobal()) {
3273 if (breakindex>pp.desc.size()) //all local
3276 TypeDescriptor lasttype=pp.base.getType();
3277 String basestr=generateTemp(fm, pp.base, lb);
3279 boolean maybenull=fm.getMethod().isStatic()||
3280 !pp.base.equals(fm.getParameter(0));
3282 for(int i=0; i<breakindex; i++) {
3283 String indexcheck="";
3285 Descriptor desc=pp.getDescAt(i);
3286 if (desc instanceof FieldDescriptor) {
3287 FieldDescriptor fd=(FieldDescriptor)desc;
3289 if (!teststr.equals(""))
3291 teststr+="((prefptr="+basestr+")!=NULL)";
3292 basestr="((struct "+lasttype.getSafeSymbol()+" *)prefptr)->"+fd.getSafeSymbol();
3294 basestr=basestr+"->"+fd.getSafeSymbol();
3297 lasttype=fd.getType();
3299 IndexDescriptor id=(IndexDescriptor)desc;
3300 indexcheck="((tmpindex=";
3301 for(int j=0; j<id.tddesc.size(); j++) {
3302 indexcheck+=generateTemp(fm, id.getTempDescAt(j), lb)+"+";
3304 indexcheck+=id.offset+")>=0)&(tmpindex<((struct ArrayObject *)prefptr)->___length___)";
3306 if (!teststr.equals(""))
3308 teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck;
3309 basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]";
3311 lasttype=lasttype.dereference();
3316 if (teststr.equals("")) {
3317 oid="((unsigned int)"+basestr+")";
3319 oid="((unsigned int)(("+teststr+")?"+basestr+":NULL))";
3323 for(int i = breakindex; i < pp.desc.size(); i++) {
3324 String newfieldoffset;
3325 Object desc = pp.getDescAt(i);
3326 if(desc instanceof FieldDescriptor) {
3327 FieldDescriptor fd=(FieldDescriptor)desc;
3328 newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))");
3329 lasttype=fd.getType();
3331 newfieldoffset = "";
3332 IndexDescriptor id=(IndexDescriptor)desc;
3333 for(int j = 0; j < id.tddesc.size(); j++) {
3334 newfieldoffset += generateTemp(fm, id.getTempDescAt(j), lb) + "+";
3336 newfieldoffset += id.offset.toString();
3337 lasttype=lasttype.dereference();
3339 fieldoffset.add(newfieldoffset);
3342 int base=(tuplecount>0) ? ((Short)endoffset.get(tuplecount-1)).intValue() : 0;
3343 base+=pp.desc.size()-breakindex;
3344 endoffset.add(new Short((short)base));
3349 public void generateFlatGlobalConvNode(FlatMethod fm, LocalityBinding lb, FlatGlobalConvNode fgcn, PrintWriter output) {
3350 if (lb!=fgcn.getLocality())
3352 /* Have to generate flat globalconv */
3353 if (fgcn.getMakePtr()) {
3355 //DEBUG: output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+",\" "+fm+":"+fgcn+"\");");
3356 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3358 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fgcn)||state.READSET&&dc.getNeedWriteTrans(lb, fgcn)) {
3359 //need to do translation
3360 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+", (void *)("+localsprefixaddr+"));");
3361 } else if (state.READSET&&dc.getNeedTrans(lb, fgcn)) {
3362 if (state.HYBRID&&delaycomp.getConv(lb).contains(fgcn)) {
3363 output.println("TRANSREADRDFISSION("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3365 output.println("TRANSREADRD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3369 /* Need to convert to OID */
3370 if ((dc==null)||dc.getNeedSrcTrans(lb,fgcn)) {
3371 if (fgcn.doConvert()||(delaycomp!=null&&delaycomp.needsFission(lb, fgcn.getAtomicEnter())&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) {
3372 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc(),lb)+");");
3374 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=NULL;");
3380 public void generateFlatInstanceOfNode(FlatMethod fm, LocalityBinding lb, FlatInstanceOfNode fion, PrintWriter output) {
3382 if (fion.getType().isArray()) {
3383 type=state.getArrayNumber(fion.getType())+state.numClasses();
3385 type=fion.getType().getClassDesc().getId();
3388 if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
3389 output.println(generateTemp(fm, fion.getDst(), lb)+"=1;");
3391 output.println(generateTemp(fm, fion.getDst(), lb)+"=instanceof("+generateTemp(fm,fion.getSrc(),lb)+","+type+");");
3394 int sandboxcounter=0;
3395 public void generateFlatAtomicEnterNode(FlatMethod fm, LocalityBinding lb, FlatAtomicEnterNode faen, PrintWriter output) {
3396 /* Check to see if we need to generate code for this atomic */
3397 if (locality==null) {
3398 if (GENERATEPRECISEGC) {
3399 output.println("if (pthread_mutex_trylock(&atomiclock)!=0) {");
3400 output.println("stopforgc((struct garbagelist *) &___locals___);");
3401 output.println("pthread_mutex_lock(&atomiclock);");
3402 output.println("restartaftergc();");
3403 output.println("}");
3405 output.println("pthread_mutex_lock(&atomiclock);");
3410 if (locality.getAtomic(lb).get(faen.getPrev(0)).intValue()>0)
3414 if (state.SANDBOX) {
3415 outsandbox.println("int atomiccounter"+sandboxcounter+"=LOW_CHECK_FREQUENCY;");
3416 output.println("counter_reset_pointer=&atomiccounter"+sandboxcounter+";");
3419 if (state.DELAYCOMP&&delaycomp.needsFission(lb, faen)) {
3420 AtomicRecord ar=atomicmethodmap.get(faen);
3422 for(Iterator<TempDescriptor> tmpit=ar.livein.iterator();tmpit.hasNext();) {
3423 TempDescriptor tmp=tmpit.next();
3424 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3427 //copy outs that depend on path
3428 for(Iterator<TempDescriptor> tmpit=ar.liveoutvirtualread.iterator();tmpit.hasNext();) {
3429 TempDescriptor tmp=tmpit.next();
3430 if (!ar.livein.contains(tmp))
3431 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3435 /* Backup the temps. */
3436 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3437 TempDescriptor tmp=tmpit.next();
3438 output.println(generateTemp(fm, backuptable.get(lb).get(tmp),lb)+"="+generateTemp(fm,tmp,lb)+";");
3441 output.println("goto transstart"+faen.getIdentifier()+";");
3443 /******* Print code to retry aborted transaction *******/
3444 output.println("transretry"+faen.getIdentifier()+":");
3447 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3448 TempDescriptor tmp=tmpit.next();
3449 output.println(generateTemp(fm, tmp,lb)+"="+generateTemp(fm,backuptable.get(lb).get(tmp),lb)+";");
3453 /********* Need to revert local object store ********/
3454 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3456 output.println("while ("+revertptr+") {");
3457 output.println("struct ___Object___ * tmpptr;");
3458 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3459 output.println("REVERT_OBJ("+revertptr+");");
3460 output.println(revertptr+"=tmpptr;");
3461 output.println("}");
3463 /******* Tell the runtime to start the transaction *******/
3465 output.println("transstart"+faen.getIdentifier()+":");
3466 if (state.SANDBOX) {
3467 output.println("transaction_check_counter=*counter_reset_pointer;");
3470 output.println("transStart();");
3472 if (state.ABORTREADERS||state.SANDBOX) {
3474 output.println("abortenabled=1;");
3475 output.println("if (_setjmp(aborttrans)) {");
3476 output.println(" goto transretry"+faen.getIdentifier()+"; }");
3480 public void generateFlatAtomicExitNode(FlatMethod fm, LocalityBinding lb, FlatAtomicExitNode faen, PrintWriter output) {
3481 /* Check to see if we need to generate code for this atomic */
3482 if (locality==null) {
3483 output.println("pthread_mutex_unlock(&atomiclock);");
3486 if (locality.getAtomic(lb).get(faen).intValue()>0)
3488 //store the revert list before we lose the transaction object
3491 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3492 output.println(revertptr+"=revertlist;");
3493 output.println("if (transCommit()) {");
3494 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3495 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3496 output.println("} else {");
3497 /* Need to commit local object store */
3498 output.println("while ("+revertptr+") {");
3499 output.println("struct ___Object___ * tmpptr;");
3500 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3501 output.println("COMMIT_OBJ("+revertptr+");");
3502 output.println(revertptr+"=tmpptr;");
3503 output.println("}");
3504 output.println("}");
3508 if (!state.DELAYCOMP) {
3510 output.println("if (transCommit()) {");
3511 /* Transaction aborts if it returns true */
3512 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3513 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3514 output.println("}");
3516 if (delaycomp.optimizeTrans(lb, faen.getAtomicEnter())&&(!state.STMARRAY||state.DUALVIEW)) {
3517 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3518 output.println("LIGHTWEIGHTCOMMIT("+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+", transretry"+faen.getAtomicEnter().getIdentifier()+");");
3520 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3521 TempDescriptor tmp=tmpit.next();
3522 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3524 } else if (delaycomp.needsFission(lb, faen.getAtomicEnter())) {
3525 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3527 output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {");
3528 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3529 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3530 output.println("}");
3532 output.println("else {");
3533 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3534 TempDescriptor tmp=tmpit.next();
3535 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3537 output.println("}");
3539 output.println("if (transCommit(NULL, NULL, NULL, NULL)) {");
3540 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3541 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3542 output.println("}");
3547 public void generateFlatSESEEnterNode( FlatMethod fm,
3549 FlatSESEEnterNode fsen,
3552 // if MLP flag is off, okay that SESE nodes are in IR graph,
3553 // just skip over them and code generates exactly the same
3554 if( !(state.MLP || state.OOOJAVA) ) {
3557 // there may be an SESE in an unreachable method, skip over
3558 if( (state.MLP && !mlpa.getAllSESEs().contains( fsen )) ||
3559 (state.OOOJAVA && !oooa.getAllSESEs().contains(fsen))
3564 // also, if we have encountered a placeholder, just skip it
3565 if( fsen.getIsCallerSESEplaceholder() ) {
3569 output.println(" {");
3572 //output.println("CP_LOGEVENT( CP_EVENTID_TASKDISPATCH, CP_EVENTTYPE_BEGIN );");
3574 // set up the parent
3575 if( (state.MLP && fsen == mlpa.getMainSESE()) ||
3576 (state.OOOJAVA && fsen == oooa.getMainSESE())
3578 output.println(" SESEcommon* parentCommon = NULL;");
3580 if( fsen.getParent() == null ) {
3581 System.out.println( "in "+fm+", "+fsen+" has null parent" );
3583 assert fsen.getParent() != null;
3584 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3585 output.println(" SESEcommon* parentCommon = &("+paramsprefix+"->common);");
3587 //output.println(" SESEcommon* parentCommon = (SESEcommon*) peekItem( seseCallStack );");
3588 output.println(" SESEcommon* parentCommon = seseCaller;");
3592 // before doing anything, lock your own record and increment the running children
3593 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3594 (state.OOOJAVA && fsen != oooa.getMainSESE())
3596 output.println(" atomic_inc(&parentCommon->numRunningChildren);");
3599 // allocate the space for this record
3601 fsen.getSESErecordName()+"* seseToIssue = ("+
3602 fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
3603 fsen.getSESErecordName()+" ) );");
3605 // set up the SESE in-set and out-set objects, which look
3606 // like a garbage list
3607 output.println(" struct garbagelist * gl= (struct garbagelist *)&(((SESEcommon*)(seseToIssue))[1]);");
3608 output.println(" gl->size="+calculateSizeOfSESEParamList(fsen)+";");
3609 output.println(" gl->next = NULL;");
3611 // there are pointers to SESE records the newly-issued SESE
3612 // will use to get values it depends on them for--how many
3613 // are there, and what is the offset from the total SESE
3614 // record to the first dependent record pointer?
3615 output.println(" seseToIssue->common.numDependentSESErecords="+
3616 fsen.getNumDepRecs()+";");
3618 // we only need this (and it will only compile) when the number of dependent
3619 // SESE records is non-zero
3620 if( fsen.getFirstDepRecField() != null ) {
3621 output.println(" seseToIssue->common.offsetToDepSESErecords=(INTPTR)sizeof("+
3622 fsen.getSESErecordName()+") - (INTPTR)&((("+
3623 fsen.getSESErecordName()+"*)0)->"+fsen.getFirstDepRecField()+");"
3628 // and keep the thread-local sese stack up to date (jjenista--this still relevant??)
3629 //output.println(" addNewItem( seseCallStack, (void*) seseToIssue);");
3631 // fill in common data
3632 output.println(" int localCount=0;");
3633 output.println(" seseToIssue->common.classID = "+fsen.getIdentifier()+";");
3634 output.println(" psem_init( &(seseToIssue->common.stallSem) );");
3636 output.println(" seseToIssue->common.forwardList = createQueue();");
3637 output.println(" seseToIssue->common.unresolvedDependencies = 10000;");
3638 output.println(" pthread_cond_init( &(seseToIssue->common.doneCond), NULL );");
3639 output.println(" seseToIssue->common.doneExecuting = FALSE;");
3640 output.println(" pthread_cond_init( &(seseToIssue->common.runningChildrenCond), NULL );");
3641 output.println(" seseToIssue->common.numRunningChildren = 0;");
3642 output.println(" seseToIssue->common.parent = parentCommon;");
3644 // all READY in-vars should be copied now and be done with it
3645 Iterator<TempDescriptor> tempItr = fsen.getReadyInVarSet().iterator();
3646 while( tempItr.hasNext() ) {
3647 TempDescriptor temp = tempItr.next();
3649 // when we are issuing the main SESE or an SESE with placeholder
3650 // caller SESE as parent, generate temp child child's eclosing method,
3651 // otherwise use the parent's enclosing method as the context
3652 boolean useParentContext = false;
3654 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3655 (state.OOOJAVA && fsen != oooa.getMainSESE())
3657 assert fsen.getParent() != null;
3658 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3659 useParentContext = true;
3663 if( useParentContext ) {
3664 output.println(" seseToIssue->"+temp+" = "+
3665 generateTemp( fsen.getParent().getfmBogus(), temp, null )+";");
3667 output.println(" seseToIssue->"+temp+" = "+
3668 generateTemp( fsen.getfmEnclosing(), temp, null )+";");
3672 // before potentially adding this SESE to other forwarding lists,
3673 // create it's lock and take it immediately
3674 output.println(" pthread_mutex_init( &(seseToIssue->common.lock), NULL );");
3675 // output.println(" pthread_mutex_lock( &(seseToIssue->common.lock) );");
3677 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3678 (state.OOOJAVA && fsen != oooa.getMainSESE())
3680 // count up outstanding dependencies, static first, then dynamic
3681 Iterator<SESEandAgePair> staticSrcsItr = fsen.getStaticInVarSrcs().iterator();
3682 while( staticSrcsItr.hasNext() ) {
3683 SESEandAgePair srcPair = staticSrcsItr.next();
3684 output.println(" {");
3685 output.println(" SESEcommon* src = (SESEcommon*)"+srcPair+";");
3687 if(GENERATEPRECISEGC){
3688 output.println(" stopforgc((struct garbagelist *)&___locals___);");
3690 output.println(" pthread_mutex_lock( &(src->lock) );");
3691 if(GENERATEPRECISEGC){
3692 output.println(" restartaftergc();");
3694 output.println(" if( !isEmpty( src->forwardList ) &&");
3695 output.println(" seseToIssue == peekItem( src->forwardList ) ) {");
3696 output.println(" printf( \"This shouldnt already be here\\n\");");
3697 output.println(" exit( -1 );");
3698 output.println(" }");
3699 output.println(" if( !src->doneExecuting ) {");
3700 output.println(" addNewItem( src->forwardList, seseToIssue );");
3701 // output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3702 output.println(" ++(localCount);");
3703 output.println(" }");
3704 output.println(" pthread_mutex_unlock( &(src->lock) );");
3705 output.println(" }");
3707 // whether or not it is an outstanding dependency, make sure
3708 // to pass the static name to the child's record
3709 output.println(" seseToIssue->"+srcPair+" = "+srcPair+";");
3712 // dynamic sources might already be accounted for in the static list,
3713 // so only add them to forwarding lists if they're not already there
3714 Iterator<TempDescriptor> dynVarsItr = fsen.getDynamicInVarSet().iterator();
3715 while( dynVarsItr.hasNext() ) {
3716 TempDescriptor dynInVar = dynVarsItr.next();
3717 output.println(" {");
3718 output.println(" SESEcommon* src = (SESEcommon*)"+dynInVar+"_srcSESE;");
3720 // the dynamic source is NULL if it comes from your own space--you can't pass
3721 // the address off to the new child, because you're not done executing and
3722 // might change the variable, so copy it right now
3723 output.println(" if( src != NULL ) {");
3725 if(GENERATEPRECISEGC){
3726 output.println(" stopforgc((struct garbagelist *)&___locals___);");
3728 output.println(" pthread_mutex_lock( &(src->lock) );");
3729 if(GENERATEPRECISEGC){
3730 output.println(" restartaftergc();");
3732 output.println(" if( isEmpty( src->forwardList ) ||");
3733 output.println(" seseToIssue != peekItem( src->forwardList ) ) {");
3734 output.println(" if( !src->doneExecuting ) {");
3735 output.println(" addNewItem( src->forwardList, seseToIssue );");
3736 // output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3737 output.println(" ++(localCount);");
3738 output.println(" }");
3739 output.println(" }");
3740 output.println(" pthread_mutex_unlock( &(src->lock) );");
3741 output.println(" seseToIssue->"+dynInVar+"_srcOffset = "+dynInVar+"_srcOffset;");
3742 output.println(" } else {");
3744 boolean useParentContext = false;
3745 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3746 (state.OOOJAVA && fsen != oooa.getMainSESE())
3748 assert fsen.getParent() != null;
3749 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3750 useParentContext = true;
3753 if( useParentContext ) {
3754 output.println(" seseToIssue->"+dynInVar+" = "+
3755 generateTemp( fsen.getParent().getfmBogus(), dynInVar, null )+";");
3757 output.println(" seseToIssue->"+dynInVar+" = "+
3758 generateTemp( fsen.getfmEnclosing(), dynInVar, null )+";");
3761 output.println(" }");
3762 output.println(" }");
3764 // even if the value is already copied, make sure your NULL source
3765 // gets passed so child knows it already has the dynamic value
3766 output.println(" seseToIssue->"+dynInVar+"_srcSESE = "+dynInVar+"_srcSESE;");
3769 // maintain pointers for finding dynamic SESE
3770 // instances from static names
3771 SESEandAgePair pair = new SESEandAgePair( fsen, 0 );
3772 if( fsen.getParent() != null &&
3773 //!fsen.getParent().getIsCallerSESEplaceholder() &&
3774 fsen.getParent().getNeededStaticNames().contains( pair )
3777 for( int i = fsen.getOldestAgeToTrack(); i > 0; --i ) {
3778 SESEandAgePair pair1 = new SESEandAgePair( fsen, i );
3779 SESEandAgePair pair2 = new SESEandAgePair( fsen, i-1 );
3780 output.println(" "+pair1+" = "+pair2+";");
3782 output.println(" "+pair+" = seseToIssue;");
3786 // count up memory conflict dependencies,
3790 FlatSESEEnterNode parent = fsen.getParent();
3791 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(parent);
3792 if (graph != null && graph.hasConflictEdge()) {
3793 Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
3795 output.println(" //add memory queue element");
3796 Analysis.OoOJava.SESEWaitingQueue seseWaitingQueue=
3797 graph.getWaitingElementSetBySESEID(fsen.getIdentifier(), seseLockSet);
3798 if(seseWaitingQueue.getWaitingElementSize()>0){
3799 output.println(" {");
3800 output.println(" REntry* rentry=NULL;");
3801 output.println(" INTPTR* pointer=NULL;");
3802 output.println(" seseToIssue->common.rentryIdx=0;");
3804 Set<Integer> queueIDSet=seseWaitingQueue.getQueueIDSet();
3805 for (Iterator iterator = queueIDSet.iterator(); iterator
3807 Integer key = (Integer) iterator.next();
3808 int queueID=key.intValue();
3809 Set<Analysis.OoOJava.WaitingElement> waitingQueueSet =
3810 seseWaitingQueue.getWaitingElementSet(queueID);
3811 int enqueueType=seseWaitingQueue.getType(queueID);
3812 if(enqueueType==SESEWaitingQueue.EXCEPTION){
3813 output.println(" INITIALIZEBUF(parentCommon->memoryQueueArray["
3816 for (Iterator iterator2 = waitingQueueSet.iterator(); iterator2
3818 Analysis.OoOJava.WaitingElement waitingElement
3819 = (Analysis.OoOJava.WaitingElement) iterator2.next();
3820 if (waitingElement.getStatus() >= ConflictNode.COARSE) {
3821 output.println(" rentry=mlpCreateREntry("
3822 + waitingElement.getStatus()
3823 + ", seseToIssue);");
3825 TempDescriptor td = waitingElement
3827 // decide whether waiting element is dynamic or static
3828 if (fsen.getDynamicInVarSet().contains(td)) {
3829 // dynamic in-var case
3830 output.println(" pointer=seseToIssue->"
3831 + waitingElement.getDynID()
3832 + "_srcSESE+seseToIssue->"
3833 + waitingElement.getDynID()
3836 .println(" rentry=mlpCreateFineREntry("
3839 + ", seseToIssue, pointer );");
3840 } else if (fsen.getStaticInVarSet()
3842 // static in-var case
3843 VariableSourceToken vst = fsen
3844 .getStaticInVarSrc(td);
3847 String srcId = "SESE_"
3849 .getPrettyIdentifier()
3850 + vst.getSESE().getIdentifier()
3851 + "_" + vst.getAge();
3853 .println(" pointer=(void*)&seseToIssue->"
3860 .println(" rentry=mlpCreateFineREntry("
3863 + ", seseToIssue, pointer );");
3868 .println(" rentry=mlpCreateFineREntry("
3871 + ", seseToIssue, (void*)&seseToIssue->"
3872 + waitingElement.getDynID()
3877 .println(" rentry->queue=parentCommon->memoryQueueArray["
3878 + waitingElement.getQueueID()
3881 if(enqueueType==SESEWaitingQueue.NORMAL){
3883 .println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
3885 .println(" if(ADDRENTRY(parentCommon->memoryQueueArray["
3886 + waitingElement.getQueueID()
3887 + "],rentry)==NOTREADY){");
3888 output.println(" ++(localCount);");
3889 output.println(" }");
3891 // Trying to execute the dynamic coarse grain conflict strategy...
3892 if(state.RCR && rcr != null) {
3893 boolean useParentContext = false;
3895 if( (state.MLP &&fsen != mlpa.getMainSESE()) ||
3896 (state.OOOJAVA &&fsen != oooa.getMainSESE())) {
3897 assert fsen.getParent() != null;
3898 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3899 useParentContext = true;
3903 for (TempDescriptor invar : fsen.getInVarsForDynamicCoarseConflictResolution()) {
3905 if( useParentContext ) {
3906 varString = generateTemp( fsen.getParent().getfmBogus(), invar, null );
3908 varString = generateTemp( fsen.getfmEnclosing(), invar, null );
3910 output.println(" "+rcr.getTraverserInvocation(invar, varString, fsen));
3915 .println(" ADDRENTRYTOBUF(parentCommon->memoryQueueArray["
3916 + waitingElement.getQueueID()
3920 if(enqueueType!=SESEWaitingQueue.NORMAL){
3921 output.println(" localCount+=RESOLVEBUF(parentCommon->memoryQueueArray["
3922 + queueID+ "],&seseToIssue->common);");
3925 output.println(" }");
3931 ConflictGraph graph = null;
3932 FlatSESEEnterNode parent = fsen.getParent();
3933 if (parent != null) {
3934 if (parent.isCallerSESEplaceholder) {
3935 graph = mlpa.getConflictGraphResults().get(parent.getfmEnclosing());
3937 graph = mlpa.getConflictGraphResults().get(parent);
3940 if (graph != null && graph.hasConflictEdge()) {
3941 HashSet<SESELock> seseLockSet = mlpa.getConflictGraphLockMap()
3944 output.println(" //add memory queue element");
3945 SESEWaitingQueue seseWaitingQueue=graph.getWaitingElementSetBySESEID(fsen.getIdentifier(),
3947 if(seseWaitingQueue.getWaitingElementSize()>0){
3948 output.println(" {");
3949 output.println(" REntry* rentry=NULL;");
3950 output.println(" INTPTR* pointer=NULL;");
3951 output.println(" seseToIssue->common.rentryIdx=0;");
3953 Set<Integer> queueIDSet=seseWaitingQueue.getQueueIDSet();
3954 for (Iterator iterator = queueIDSet.iterator(); iterator
3956 Integer key = (Integer) iterator.next();
3957 int queueID=key.intValue();
3958 Set<WaitingElement> waitingQueueSet = seseWaitingQueue.getWaitingElementSet(queueID);
3959 int enqueueType=seseWaitingQueue.getType(queueID);
3960 if(enqueueType==SESEWaitingQueue.EXCEPTION){
3961 output.println(" INITIALIZEBUF(parentCommon->memoryQueueArray["
3964 for (Iterator iterator2 = waitingQueueSet.iterator(); iterator2
3966 WaitingElement waitingElement = (WaitingElement) iterator2
3968 if (waitingElement.getStatus() >= ConflictNode.COARSE) {
3969 output.println(" rentry=mlpCreateREntry("
3970 + waitingElement.getStatus()
3971 + ", seseToIssue);");
3973 TempDescriptor td = waitingElement
3975 // decide whether waiting element is dynamic or
3977 if (fsen.getDynamicInVarSet().contains(td)) {
3978 // dynamic in-var case
3979 output.println(" pointer=seseToIssue->"
3980 + waitingElement.getDynID()
3981 + "_srcSESE+seseToIssue->"
3982 + waitingElement.getDynID()
3985 .println(" rentry=mlpCreateFineREntry("
3988 + ", seseToIssue, pointer );");
3989 } else if (fsen.getStaticInVarSet()
3991 // static in-var case
3992 VariableSourceToken vst = fsen
3993 .getStaticInVarSrc(td);
3996 String srcId = "SESE_"
3998 .getPrettyIdentifier()
3999 + vst.getSESE().getIdentifier()
4000 + "_" + vst.getAge();
4002 .println(" pointer=(void*)&seseToIssue->"
4009 .println(" rentry=mlpCreateFineREntry("
4012 + ", seseToIssue, pointer );");
4017 .println(" rentry=mlpCreateFineREntry("
4020 + ", seseToIssue, (void*)&seseToIssue->"
4021 + waitingElement.getDynID()
4026 .println(" rentry->queue=parentCommon->memoryQueueArray["
4027 + waitingElement.getQueueID()
4030 if(enqueueType==SESEWaitingQueue.NORMAL){
4032 .println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
4034 .println(" if(ADDRENTRY(parentCommon->memoryQueueArray["
4035 + waitingElement.getQueueID()
4036 + "],rentry)==NOTREADY){");
4037 output.println(" ++(localCount);");
4038 output.println(" } ");
4041 .println(" ADDRENTRYTOBUF(parentCommon->memoryQueueArray["
4042 + waitingElement.getQueueID()
4046 if(enqueueType!=SESEWaitingQueue.NORMAL){
4047 output.println(" localCount+=RESOLVEBUF(parentCommon->memoryQueueArray["
4048 + queueID+ "],&seseToIssue->common);");
4051 output.println(" }");
4059 // release this SESE for siblings to update its dependencies or,
4060 // eventually, for it to mark itself finished
4061 // output.println(" pthread_mutex_unlock( &(seseToIssue->common.lock) );");
4063 // if there were no outstanding dependencies, issue here
4064 output.println(" if( atomic_sub_and_test(10000-localCount,&(seseToIssue->common.unresolvedDependencies) ) ) {");
4065 output.println(" workScheduleSubmit( (void*)seseToIssue );");
4066 output.println(" }");
4068 output.println(" if( seseToIssue->common.unresolvedDependencies == 0 ) {");
4069 output.println(" workScheduleSubmit( (void*)seseToIssue );");
4070 output.println(" }");
4072 // release this SESE for siblings to update its dependencies or,
4073 // eventually, for it to mark itself finished
4074 // output.println(" pthread_mutex_unlock( &(seseToIssue->common.lock) );");
4077 //output.println("CP_LOGEVENT( CP_EVENTID_TASKDISPATCH, CP_EVENTTYPE_END );");
4079 output.println(" }");
4083 public void generateFlatSESEExitNode( FlatMethod fm,
4085 FlatSESEExitNode fsexn,
4089 // if MLP flag is off, okay that SESE nodes are in IR graph,
4090 // just skip over them and code generates exactly the same
4091 if( ! (state.MLP || state.OOOJAVA) ) {
4095 //output.println("CP_LOGEVENT( CP_EVENTID_TASKRETIRE, CP_EVENTTYPE_BEGIN );");
4097 // get the enter node for this exit that has meta data embedded
4098 FlatSESEEnterNode fsen = fsexn.getFlatEnter();
4100 // there may be an SESE in an unreachable method, skip over
4101 if( (state.MLP && !mlpa.getAllSESEs().contains( fsen )) ||
4102 (state.OOOJAVA && !oooa.getAllSESEs().contains( fsen ))
4107 // also, if we have encountered a placeholder, just jump it
4108 if( fsen.getIsCallerSESEplaceholder() ) {
4112 output.println(" /* SESE exiting */");
4114 String com = paramsprefix+"->common";
4116 // this SESE cannot be done until all of its children are done
4117 // so grab your own lock with the condition variable for watching
4118 // that the number of your running children is greater than zero
4119 if (GENERATEPRECISEGC){
4120 output.println(" stopforgc((struct garbagelist *)&___locals___);");
4122 output.println(" pthread_mutex_lock( &("+com+".lock) );");
4123 if (GENERATEPRECISEGC){
4124 output.println(" restartaftergc();");
4126 output.println(" while( "+com+".numRunningChildren > 0 ) {");
4127 if (GENERATEPRECISEGC){
4128 // output.println(" stopforgc((struct garbagelist *)&(((SESEcommon*)(___params___))[1]));");
4129 output.println(" stopforgc((struct garbagelist *)&___locals___);");
4131 output.println(" pthread_cond_wait( &("+com+".runningChildrenCond), &("+com+".lock) );");
4132 if (GENERATEPRECISEGC){
4133 output.println(" restartaftergc();");
4135 output.println(" }");
4138 // copy out-set from local temps into the sese record
4139 Iterator<TempDescriptor> itr = fsen.getOutVarSet().iterator();
4140 while( itr.hasNext() ) {
4141 TempDescriptor temp = itr.next();
4143 // only have to do this for primitives non-arrays
4145 temp.getType().isPrimitive() && !temp.getType().isArray()
4151 // have to determine the context enclosing this sese
4152 boolean useParentContext = false;
4154 if( (state.MLP &&fsen != mlpa.getMainSESE()) ||
4155 (state.OOOJAVA &&fsen != oooa.getMainSESE())
4157 assert fsen.getParent() != null;
4158 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
4159 useParentContext = true;
4164 if( useParentContext ) {
4165 from = generateTemp( fsen.getParent().getfmBogus(), temp, null );
4167 from = generateTemp( fsen.getfmEnclosing(), temp, null );
4170 output.println(" "+paramsprefix+
4171 "->"+temp.getSafeSymbol()+
4175 // mark yourself done, your SESE data is now read-only
4176 output.println(" "+com+".doneExecuting = TRUE;");
4177 output.println(" pthread_cond_signal( &("+com+".doneCond) );");
4178 output.println(" pthread_mutex_unlock( &("+com+".lock) );");
4180 // decrement dependency count for all SESE's on your forwarding list
4181 output.println(" while( !isEmpty( "+com+".forwardList ) ) {");
4182 output.println(" SESEcommon* consumer = (SESEcommon*) getItem( "+com+".forwardList );");
4185 output.println(" if(consumer->rentryIdx>0){");
4186 output.println(" // resolved null pointer");
4187 output.println(" int idx;");
4188 output.println(" for(idx=0;idx<consumer->rentryIdx;idx++){");
4189 output.println(" resolvePointer(consumer->rentryArray[idx]);");
4190 output.println(" }");
4191 output.println(" }");
4194 // output.println(" pthread_mutex_lock( &(consumer->lock) );");
4195 // output.println(" --(consumer->unresolvedDependencies);");
4196 // output.println(" if( consumer->unresolvedDependencies == 0 ) {");
4197 output.println(" if( atomic_sub_and_test(1, &(consumer->unresolvedDependencies)) ){");
4198 output.println(" workScheduleSubmit( (void*)consumer );");
4199 output.println(" }");
4200 // output.println(" pthread_mutex_unlock( &(consumer->lock) );");
4201 output.println(" }");
4205 // clean up its lock element from waiting queue, and decrement dependency count for next SESE block
4206 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
4207 (state.OOOJAVA && fsen != oooa.getMainSESE())
4211 output.println(" /* check memory dependency*/");
4212 output.println(" {");
4213 output.println(" int idx;");
4214 output.println(" for(idx=0;idx<___params___->common.rentryIdx;idx++){");
4215 output.println(" REntry* re=___params___->common.rentryArray[idx];");
4216 output.println(" RETIRERENTRY(re->queue,re);");
4217 output.println(" }");
4218 output.println(" }");
4222 // if parent is stalling on you, let them know you're done
4223 if( (state.MLP && fsexn.getFlatEnter() != mlpa.getMainSESE()) ||
4224 (state.OOOJAVA && fsexn.getFlatEnter() != oooa.getMainSESE())
4226 output.println(" psem_give( &("+paramsprefix+"->common.stallSem) );");
4229 // last of all, decrement your parent's number of running children
4230 output.println(" if( "+paramsprefix+"->common.parent != NULL ) {");
4231 output.println(" if (atomic_sub_and_test(1, &"+paramsprefix+"->common.parent->numRunningChildren)) {");
4232 if (GENERATEPRECISEGC){
4233 output.println(" stopforgc((struct garbagelist *)&___locals___);");
4235 output.println(" pthread_mutex_lock( &("+paramsprefix+"->common.parent->lock) );");
4236 if (GENERATEPRECISEGC){
4237 output.println(" restartaftergc();");
4239 output.println(" pthread_cond_signal( &("+paramsprefix+"->common.parent->runningChildrenCond) );");
4240 output.println(" pthread_mutex_unlock( &("+paramsprefix+"->common.parent->lock) );");
4241 output.println(" }");
4242 output.println(" }");
4244 // this is a thread-only variable that can be handled when critical sese-to-sese
4245 // data has been taken care of--set sese pointer to remember self over method
4246 // calls to a non-zero, invalid address
4247 output.println(" seseCaller = (SESEcommon*) 0x1;");
4250 //output.println("CP_LOGEVENT( CP_EVENTID_TASKRETIRE, CP_EVENTTYPE_END );");
4253 public void generateFlatWriteDynamicVarNode( FlatMethod fm,
4255 FlatWriteDynamicVarNode fwdvn,
4258 if( !(state.MLP || state.OOOJAVA) ) {
4259 // should node should not be in an IR graph if the
4260 // MLP flag is not set
4261 throw new Error("Unexpected presence of FlatWriteDynamicVarNode");
4264 Hashtable<TempDescriptor, VSTWrapper> writeDynamic = fwdvn.getVar2src();
4266 assert writeDynamic != null;
4268 Iterator wdItr = writeDynamic.entrySet().iterator();
4269 while( wdItr.hasNext() ) {
4270 Map.Entry me = (Map.Entry) wdItr.next();
4271 TempDescriptor refVar = (TempDescriptor) me.getKey();
4272 VSTWrapper vstW = (VSTWrapper) me.getValue();
4273 VariableSourceToken vst = vstW.vst;
4276 // only do this if the variable in question should be tracked,
4277 // meaning that it was explicitly added to the dynamic var set
4278 if( !current.getDynamicVarSet().contains( vst.getAddrVar() ) ) {
4284 // if there is no given source, this variable is ready so
4285 // mark src pointer NULL to signify that the var is up-to-date
4286 output.println(" "+refVar+"_srcSESE = NULL;");
4290 // otherwise we track where it will come from
4291 SESEandAgePair instance = new SESEandAgePair( vst.getSESE(), vst.getAge() );
4292 output.println(" "+refVar+"_srcSESE = "+instance+";");
4293 output.println(" "+refVar+"_srcOffset = (INTPTR) &((("+
4294 vst.getSESE().getSESErecordName()+"*)0)->"+vst.getAddrVar()+");");
4299 private void generateFlatCheckNode(FlatMethod fm, LocalityBinding lb, FlatCheckNode fcn, PrintWriter output) {
4300 if (state.CONSCHECK) {
4301 String specname=fcn.getSpec();
4302 String varname="repairstate___";
4303 output.println("{");
4304 output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
4306 TempDescriptor[] temps=fcn.getTemps();
4307 String[] vars=fcn.getVars();
4308 for(int i=0; i<temps.length; i++) {
4309 output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i],lb)+";");
4312 output.println("if (doanalysis"+specname+"("+varname+")) {");
4313 output.println("free"+specname+"_state("+varname+");");
4314 output.println("} else {");
4315 output.println("/* Bad invariant */");
4316 output.println("free"+specname+"_state("+varname+");");
4317 output.println("abort_task();");
4318 output.println("}");
4319 output.println("}");
4323 private void generateFlatCall(FlatMethod fm, LocalityBinding lb, FlatCall fc, PrintWriter output) {
4325 if( (state.MLP && !nonSESEpass) ||
4326 (state.OOOJAVA && !nonSESEpass)
4328 output.println(" seseCaller = (SESEcommon*)"+paramsprefix+";");
4331 MethodDescriptor md=fc.getMethod();
4332 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? locality.getBinding(lb, fc) : md);
4333 ClassDescriptor cn=md.getClassDesc();
4334 output.println("{");
4335 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4337 LocalityBinding fclb=locality.getBinding(lb, fc);
4338 output.print(" struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
4340 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
4341 output.print(objectparams.numPointers());
4342 output.print(", "+localsprefixaddr);
4343 if (md.getThis()!=null) {
4345 output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis(),lb));
4347 if (fc.getThis()!=null&&md.getThis()==null) {
4348 System.out.println("WARNING!!!!!!!!!!!!");
4349 System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
4353 for(int i=0; i<fc.numArgs(); i++) {
4354 Descriptor var=md.getParameter(i);
4355 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
4356 if (objectparams.isParamPtr(paramtemp)) {
4357 TempDescriptor targ=fc.getArg(i);
4359 TypeDescriptor td=md.getParamType(i);
4361 output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
4363 output.print("(struct "+md.getParamType(i).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
4366 output.println("};");
4371 if (fc.getReturnTemp()!=null)
4372 output.print(generateTemp(fm,fc.getReturnTemp(),lb)+"=");
4374 /* Do we need to do virtual dispatch? */
4375 if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
4378 LocalityBinding fclb=locality.getBinding(lb, fc);
4379 output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
4381 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
4386 if (md.getReturnType().isClass()||md.getReturnType().isArray())
4387 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
4389 output.print(md.getReturnType().getSafeSymbol()+" ");
4390 output.print("(*)(");
4392 boolean printcomma=false;
4393 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4395 LocalityBinding fclb=locality.getBinding(lb, fc);
4396 output.print("struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
4398 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
4402 for(int i=0; i<objectparams.numPrimitives(); i++) {
4403 TempDescriptor temp=objectparams.getPrimitive(i);
4407 if (temp.getType().isClass()||temp.getType().isArray())
4408 output.print("struct " + temp.getType().getSafeSymbol()+" * ");
4410 output.print(temp.getType().getSafeSymbol());
4415 LocalityBinding fclb=locality.getBinding(lb, fc);
4416 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])");
4418 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
4422 boolean needcomma=false;
4423 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4424 output.print("&__parameterlist__");
4428 if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
4429 if (fc.getThis()!=null) {
4430 TypeDescriptor ptd=md.getThis().getType();
4433 if (ptd.isClass()&&!ptd.isArray())
4434 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
4435 output.print(generateTemp(fm,fc.getThis(),lb));
4440 for(int i=0; i<fc.numArgs(); i++) {
4441 Descriptor var=md.getParameter(i);
4442 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
4443 if (objectparams.isParamPrim(paramtemp)) {
4444 TempDescriptor targ=fc.getArg(i);
4448 TypeDescriptor ptd=md.getParamType(i);
4449 if (ptd.isClass()&&!ptd.isArray())
4450 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
4451 output.print(generateTemp(fm, targ,lb));
4455 output.println(");");
4456 output.println(" }");
4459 private boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
4460 Set subclasses=typeutil.getSubClasses(thiscd);
4461 if (subclasses==null)
4463 for(Iterator classit=subclasses.iterator(); classit.hasNext();) {
4464 ClassDescriptor cd=(ClassDescriptor)classit.next();
4465 Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol());
4466 for(Iterator matchit=possiblematches.iterator(); matchit.hasNext();) {
4467 MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
4468 if (md.matches(matchmd))
4475 private void generateFlatFieldNode(FlatMethod fm, LocalityBinding lb, FlatFieldNode ffn, PrintWriter output) {
4476 if (state.SINGLETM) {
4477 //single machine transactional memory case
4478 String field=ffn.getField().getSafeSymbol();
4479 String src=generateTemp(fm, ffn.getSrc(),lb);
4480 String dst=generateTemp(fm, ffn.getDst(),lb);
4482 output.println(dst+"="+ src +"->"+field+ ";");
4483 if (ffn.getField().getType().isPtr()&&locality.getAtomic(lb).get(ffn).intValue()>0&&
4484 locality.getNodePreTempInfo(lb, ffn).get(ffn.getSrc())!=LocalityAnalysis.SCRATCH) {
4485 if ((dc==null)||(!state.READSET&&dc.getNeedTrans(lb, ffn))||
4486 (state.READSET&&dc.getNeedWriteTrans(lb, ffn))) {
4487 output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));");
4488 } else if (state.READSET&&dc.getNeedTrans(lb, ffn)) {
4489 if (state.HYBRID&&delaycomp.getConv(lb).contains(ffn)) {
4490 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4492 output.println("TRANSREADRD("+dst+", "+dst+");");
4495 } else if (state.DSM) {
4496 Integer status=locality.getNodePreTempInfo(lb,ffn).get(ffn.getSrc());
4497 if (status==LocalityAnalysis.GLOBAL) {
4498 String field=ffn.getField().getSafeSymbol();
4499 String src=generateTemp(fm, ffn.getSrc(),lb);
4500 String dst=generateTemp(fm, ffn.getDst(),lb);
4502 if (ffn.getField().getType().isPtr()) {
4504 //TODO: Uncomment this when we have runtime support
4505 //if (ffn.getSrc()==ffn.getDst()) {
4506 //output.println("{");
4507 //output.println("void * temp="+src+";");
4508 //output.println("if (temp&0x1) {");
4509 //output.println("temp=(void *) transRead(trans, (unsigned int) temp);");
4510 //output.println(src+"->"+field+"="+temp+";");
4511 //output.println("}");
4512 //output.println(dst+"=temp;");
4513 //output.println("}");
4515 output.println(dst+"="+ src +"->"+field+ ";");
4516 //output.println("if ("+dst+"&0x1) {");
4517 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
4518 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
4519 //output.println(src+"->"+field+"="+src+"->"+field+";");
4520 //output.println("}");
4523 output.println(dst+"="+ src+"->"+field+";");
4525 } else if (status==LocalityAnalysis.LOCAL) {
4526 if (ffn.getField().getType().isPtr()&&
4527 ffn.getField().isGlobal()) {
4528 String field=ffn.getField().getSafeSymbol();
4529 String src=generateTemp(fm, ffn.getSrc(),lb);
4530 String dst=generateTemp(fm, ffn.getDst(),lb);
4531 output.println(dst+"="+ src +"->"+field+ ";");
4532 if (locality.getAtomic(lb).get(ffn).intValue()>0)
4533 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
4534 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
4536 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4537 } else if (status==LocalityAnalysis.EITHER) {
4538 //Code is reading from a null pointer
4539 output.println("if ("+generateTemp(fm, ffn.getSrc(),lb)+") {");
4540 output.println("#ifndef RAW");
4541 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4542 output.println("#endif");
4543 //This should throw a suitable null pointer error
4544 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4546 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4548 // DEBUG if(!ffn.getDst().getType().isPrimitive()){
4549 // DEBUG output.println("within((void*)"+generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+");");
4551 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4556 private void generateFlatSetFieldNode(FlatMethod fm, LocalityBinding lb, FlatSetFieldNode fsfn, PrintWriter output) {
4557 if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
4558 throw new Error("Can't set array length");
4559 if (state.SINGLETM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
4560 //Single Machine Transaction Case
4561 boolean srcptr=fsfn.getSrc().getType().isPtr();
4562 String src=generateTemp(fm,fsfn.getSrc(),lb);
4563 String dst=generateTemp(fm,fsfn.getDst(),lb);
4564 output.println("//"+srcptr+" "+fsfn.getSrc().getType().isNull());
4565 if (srcptr&&!fsfn.getSrc().getType().isNull()) {
4566 output.println("{");
4567 if ((dc==null)||dc.getNeedSrcTrans(lb, fsfn)&&
4568 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) {
4569 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4571 output.println("INTPTR srcoid=(INTPTR)"+src+";");
4574 if (wb.needBarrier(fsfn)&&
4575 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getDst())!=LocalityAnalysis.SCRATCH) {
4576 if (state.EVENTMONITOR) {
4577 output.println("if ("+dst+"->___objstatus___&DIRTY) EVLOGEVENTOBJ(EV_WRITE,"+dst+"->objuid)");
4579 output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;");
4581 if (srcptr&!fsfn.getSrc().getType().isNull()) {
4582 output.println("*((unsigned INTPTR *)&("+dst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4583 output.println("}");
4585 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4587 } else if (state.DSM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
4588 Integer statussrc=locality.getNodePreTempInfo(lb,fsfn).get(fsfn.getSrc());
4589 Integer statusdst=locality.getNodeTempInfo(lb).get(fsfn).get(fsfn.getDst());
4590 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4592 String src=generateTemp(fm,fsfn.getSrc(),lb);
4593 String dst=generateTemp(fm,fsfn.getDst(),lb);
4595 output.println("{");
4596 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4598 if (statusdst.equals(LocalityAnalysis.GLOBAL)) {
4601 if (wb.needBarrier(fsfn))
4602 output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;");
4604 output.println("*((unsigned INTPTR *)&("+glbdst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4606 output.println(glbdst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4607 } else if (statusdst.equals(LocalityAnalysis.LOCAL)) {
4608 /** Check if we need to copy */
4609 output.println("if(!"+dst+"->"+localcopystr+") {");
4610 /* Link object into list */
4611 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4612 output.println(revertptr+"=revertlist;");
4613 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4614 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4616 output.println("COPY_OBJ("+dst+");");
4617 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4618 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4619 output.println("}");
4621 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4623 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4624 } else if (statusdst.equals(LocalityAnalysis.EITHER)) {
4625 //writing to a null...bad
4626 output.println("if ("+dst+") {");
4627 output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}");
4629 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4631 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4634 output.println("}");
4637 if (state.FASTCHECK) {
4638 String dst=generateTemp(fm, fsfn.getDst(),lb);
4639 output.println("if(!"+dst+"->"+localcopystr+") {");
4640 /* Link object into list */
4641 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4642 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4644 output.println("COPY_OBJ("+dst+");");
4645 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4646 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4647 output.println("}");
4650 // DEBUG if(!fsfn.getField().getType().isPrimitive()){
4651 // DEBUG output.println("within((void*)"+generateTemp(fm,fsfn.getSrc(),lb)+");");
4653 output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
4657 private void generateFlatElementNode(FlatMethod fm, LocalityBinding lb, FlatElementNode fen, PrintWriter output) {
4658 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
4661 if (elementtype.isArray()||elementtype.isClass())
4664 type=elementtype.getSafeSymbol()+" ";
4666 if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
4667 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fen.getIndex(),lb)+") >= "+generateTemp(fm,fen.getSrc(),lb) + "->___length___))");
4668 output.println("failedboundschk();");
4670 if (state.SINGLETM) {
4671 //Single machine transaction case
4672 String dst=generateTemp(fm, fen.getDst(),lb);
4673 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))) {
4674 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4676 output.println("STMGETARRAY("+dst+", "+ generateTemp(fm,fen.getSrc(),lb)+", "+generateTemp(fm, fen.getIndex(),lb)+", "+type+");");
4679 if (elementtype.isPtr()&&locality.getAtomic(lb).get(fen).intValue()>0&&
4680 locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())!=LocalityAnalysis.SCRATCH) {
4681 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fen)||state.READSET&&dc.getNeedWriteTrans(lb, fen)) {
4682 output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));");
4683 } else if (state.READSET&&dc.getNeedTrans(lb, fen)) {
4684 if (state.HYBRID&&delaycomp.getConv(lb).contains(fen)) {
4685 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4687 output.println("TRANSREADRD("+dst+", "+dst+");");
4690 } else if (state.DSM) {
4691 Integer status=locality.getNodePreTempInfo(lb,fen).get(fen.getSrc());
4692 if (status==LocalityAnalysis.GLOBAL) {
4693 String dst=generateTemp(fm, fen.getDst(),lb);
4694 if (elementtype.isPtr()) {
4695 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4696 //DEBUG: output.println("TRANSREAD("+dst+", "+dst+",\""+fm+":"+fen+"\");");
4697 output.println("TRANSREAD("+dst+", "+dst+");");
4699 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4701 } else if (status==LocalityAnalysis.LOCAL) {
4702 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4703 } else if (status==LocalityAnalysis.EITHER) {
4704 //Code is reading from a null pointer
4705 output.println("if ("+generateTemp(fm, fen.getSrc(),lb)+") {");
4706 output.println("#ifndef RAW");
4707 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4708 output.println("#endif");
4709 //This should throw a suitable null pointer error
4710 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4712 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4714 // DEBUG output.println("within((void*)"+generateTemp(fm,fen.getSrc(),lb)+");");
4715 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4719 private void generateFlatSetElementNode(FlatMethod fm, LocalityBinding lb, FlatSetElementNode fsen, PrintWriter output) {
4720 //TODO: need dynamic check to make sure this assignment is actually legal
4721 //Because Object[] could actually be something more specific...ie. Integer[]
4723 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
4726 if (elementtype.isArray()||elementtype.isClass())
4729 type=elementtype.getSafeSymbol()+" ";
4731 if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
4732 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fsen.getIndex(),lb)+") >= "+generateTemp(fm,fsen.getDst(),lb) + "->___length___))");
4733 output.println("failedboundschk();");
4736 if (state.SINGLETM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4737 //Transaction set element case
4738 if (wb.needBarrier(fsen)&&
4739 locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH) {
4740 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___objstatus___))|=DIRTY;");
4742 if (fsen.getSrc().getType().isPtr()&&!fsen.getSrc().getType().isNull()) {
4743 output.println("{");
4744 String src=generateTemp(fm, fsen.getSrc(), lb);
4745 if ((dc==null)||dc.getNeedSrcTrans(lb, fsen)&&
4746 locality.getNodePreTempInfo(lb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) {
4747 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4749 output.println("INTPTR srcoid=(INTPTR)"+src+";");
4751 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
4752 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", srcoid, INTPTR);");
4754 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
4756 output.println("}");
4758 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
4759 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", "+ generateTemp(fm, fsen.getSrc(), lb) +", "+type+");");
4761 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4764 } else if (state.DSM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4765 Integer statussrc=locality.getNodePreTempInfo(lb,fsen).get(fsen.getSrc());
4766 Integer statusdst=locality.getNodePreTempInfo(lb,fsen).get(fsen.getDst());
4767 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4768 boolean dstglobal=statusdst==LocalityAnalysis.GLOBAL;
4769 boolean dstlocal=(statusdst==LocalityAnalysis.LOCAL)||(statusdst==LocalityAnalysis.EITHER);
4772 if (wb.needBarrier(fsen))
4773 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___localcopy___))|=DIRTY;");
4774 } else if (dstlocal) {
4775 /** Check if we need to copy */
4776 String dst=generateTemp(fm, fsen.getDst(),lb);
4777 output.println("if(!"+dst+"->"+localcopystr+") {");
4778 /* Link object into list */
4779 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4780 output.println(revertptr+"=revertlist;");
4781 if ((GENERATEPRECISEGC) || this.state.MULTICOREGC)
4782 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4784 output.println("COPY_OBJ("+dst+");");
4785 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4786 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4787 output.println("}");
4789 System.out.println("Node: "+fsen);
4790 System.out.println(lb);
4791 System.out.println("statusdst="+statusdst);
4792 System.out.println(fm.printMethod());
4793 throw new Error("Unknown array type");
4796 output.println("{");
4797 String src=generateTemp(fm, fsen.getSrc(), lb);
4798 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4799 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
4800 output.println("}");
4802 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4805 if (state.FASTCHECK) {
4806 String dst=generateTemp(fm, fsen.getDst(),lb);
4807 output.println("if(!"+dst+"->"+localcopystr+") {");
4808 /* Link object into list */
4809 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4810 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4812 output.println("COPY_OBJ("+dst+");");
4813 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4814 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4815 output.println("}");
4817 // DEBUG output.println("within((void*)"+generateTemp(fm,fsen.getDst(),lb)+");");
4818 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4822 protected void generateFlatNew(FlatMethod fm, LocalityBinding lb, FlatNew fn, PrintWriter output) {
4823 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
4824 //Stash pointer in case of GC
4825 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4826 output.println(revertptr+"=revertlist;");
4828 if (state.SINGLETM) {
4829 if (fn.getType().isArray()) {
4830 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4831 if (locality.getAtomic(lb).get(fn).intValue()>0) {
4832 //inside transaction
4833 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4835 //outside transaction
4836 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4839 if (locality.getAtomic(lb).get(fn).intValue()>0) {
4840 //inside transaction
4841 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4843 //outside transaction
4844 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4847 } else if (fn.getType().isArray()) {
4848 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4849 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4850 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4851 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4852 if(this.state.MLP || state.OOOJAVA){
4853 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray_mlp("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+", oid, "+oooa.getDisjointAnalysis().getAllocationSiteFromFlatNew(fn).getUniqueAllocSiteID()+");");
4854 output.println(" oid += numWorkers;");
4856 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4859 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4862 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4863 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");");
4864 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4865 if (this.state.MLP || state.OOOJAVA){
4866 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new_mlp("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+", oid, "+oooa.getDisjointAnalysis().getAllocationSiteFromFlatNew(fn).getUniqueAllocSiteID()+");");
4867 output.println(" oid += numWorkers;");
4869 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4872 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
4875 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
4876 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4877 String dst=generateTemp(fm,fn.getDst(),lb);
4878 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
4879 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4880 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4882 if (state.FASTCHECK) {
4883 String dst=generateTemp(fm,fn.getDst(),lb);
4884 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
4885 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4886 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4890 private void generateFlatTagDeclaration(FlatMethod fm, LocalityBinding lb, FlatTagDeclaration fn, PrintWriter output) {
4891 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4892 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
4894 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+state.getTagId(fn.getType())+");");
4898 private void generateFlatOpNode(FlatMethod fm, LocalityBinding lb, FlatOpNode fon, PrintWriter output) {
4899 if (fon.getRight()!=null) {
4900 if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
4901 if (fon.getLeft().getType().isLong())
4902 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
4904 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned int)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
4906 } else if (dc!=null) {
4907 output.print(generateTemp(fm, fon.getDest(),lb)+" = (");
4908 if (fon.getLeft().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
4909 output.print("(void *)");
4910 if (dc.getNeedLeftSrcTrans(lb, fon))
4911 output.print("("+generateTemp(fm, fon.getLeft(),lb)+"!=NULL?"+generateTemp(fm, fon.getLeft(),lb)+"->"+oidstr+":NULL)");
4913 output.print(generateTemp(fm, fon.getLeft(),lb));
4914 output.print(")"+fon.getOp().toString()+"(");
4915 if (fon.getRight().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
4916 output.print("(void *)");
4917 if (dc.getNeedRightSrcTrans(lb, fon))
4918 output.println("("+generateTemp(fm, fon.getRight(),lb)+"!=NULL?"+generateTemp(fm, fon.getRight(),lb)+"->"+oidstr+":NULL));");
4920 output.println(generateTemp(fm,fon.getRight(),lb)+");");
4922 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+fon.getOp().toString()+generateTemp(fm,fon.getRight(),lb)+";");
4923 } else if (fon.getOp().getOp()==Operation.ASSIGN)
4924 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
4925 else if (fon.getOp().getOp()==Operation.UNARYPLUS)
4926 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
4927 else if (fon.getOp().getOp()==Operation.UNARYMINUS)
4928 output.println(generateTemp(fm, fon.getDest(),lb)+" = -"+generateTemp(fm, fon.getLeft(),lb)+";");
4929 else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
4930 output.println(generateTemp(fm, fon.getDest(),lb)+" = !"+generateTemp(fm, fon.getLeft(),lb)+";");
4931 else if (fon.getOp().getOp()==Operation.COMP)
4932 output.println(generateTemp(fm, fon.getDest(),lb)+" = ~"+generateTemp(fm, fon.getLeft(),lb)+";");
4933 else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
4934 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+"->fses==NULL;");
4936 output.println(generateTemp(fm, fon.getDest(),lb)+fon.getOp().toString()+generateTemp(fm, fon.getLeft(),lb)+";");
4939 private void generateFlatCastNode(FlatMethod fm, LocalityBinding lb, FlatCastNode fcn, PrintWriter output) {
4940 /* TODO: Do type check here */
4941 if (fcn.getType().isArray()) {
4942 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
4943 } else if (fcn.getType().isClass())
4944 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
4946 output.println(generateTemp(fm,fcn.getDst(),lb)+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc(),lb)+";");
4949 private void generateFlatLiteralNode(FlatMethod fm, LocalityBinding lb, FlatLiteralNode fln, PrintWriter output) {
4950 if (fln.getValue()==null)
4951 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
4952 else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
4953 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4954 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
4955 //Stash pointer in case of GC
4956 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4957 output.println(revertptr+"=revertlist;");
4959 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
4960 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
4961 //Stash pointer in case of GC
4962 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4963 output.println("revertlist="+revertptr+";");
4966 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
4968 } else if (fln.getType().isBoolean()) {
4969 if (((Boolean)fln.getValue()).booleanValue())
4970 output.println(generateTemp(fm, fln.getDst(),lb)+"=1;");
4972 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
4973 } else if (fln.getType().isChar()) {
4974 String st=FlatLiteralNode.escapeString(fln.getValue().toString());
4975 output.println(generateTemp(fm, fln.getDst(),lb)+"='"+st+"';");
4976 } else if (fln.getType().isLong()) {
4977 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+"LL;");
4979 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+";");
4982 protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) {
4983 if (frn.getReturnTemp()!=null) {
4984 if (frn.getReturnTemp().getType().isPtr())
4985 output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";");
4987 output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";");
4989 output.println("return;");
4993 protected void generateStoreFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
4996 //only record if this group has more than one exit
4997 if (branchanalysis.numJumps(fcb)>1) {
4998 left=branchanalysis.jumpValue(fcb, 0);
4999 right=branchanalysis.jumpValue(fcb, 1);
5001 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") {");
5003 output.println("STOREBRANCH("+right+");");
5004 output.println("goto "+label+";");
5005 output.println("}");
5007 output.println("STOREBRANCH("+left+");");
5010 protected void generateFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
5011 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") goto "+label+";");
5014 /** This method generates header information for the method or
5015 * task referenced by the Descriptor des. */
5016 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) {
5017 generateHeader(fm, lb, des, output, false);
5020 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output, boolean addSESErecord) {
5022 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : des);
5023 MethodDescriptor md=null;
5024 TaskDescriptor task=null;
5025 if (des instanceof MethodDescriptor)
5026 md=(MethodDescriptor) des;
5028 task=(TaskDescriptor) des;
5030 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
5032 if (md!=null&&md.getReturnType()!=null) {
5033 if (md.getReturnType().isClass()||md.getReturnType().isArray())
5034 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
5036 output.print(md.getReturnType().getSafeSymbol()+" ");
5038 //catch the constructor case
5039 output.print("void ");
5041 if (state.DSM||state.SINGLETM) {
5042 output.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
5044 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
5046 output.print(task.getSafeSymbol()+"(");
5048 boolean printcomma=false;
5049 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5051 if (state.DSM||state.SINGLETM) {
5052 output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
5054 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
5056 output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
5062 for(int i=0; i<objectparams.numPrimitives(); i++) {
5063 TempDescriptor temp=objectparams.getPrimitive(i);
5067 if (temp.getType().isClass()||temp.getType().isArray())
5068 output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
5070 output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
5072 output.println(") {");
5073 } else if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
5074 /* Imprecise Task */
5075 output.println("void * parameterarray[]) {");
5076 /* Unpack variables */
5077 for(int i=0; i<objectparams.numPrimitives(); i++) {
5078 TempDescriptor temp=objectparams.getPrimitive(i);
5079 output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
5081 for(int i=0; i<fm.numTags(); i++) {
5082 TempDescriptor temp=fm.getTag(i);
5083 int offset=i+objectparams.numPrimitives();
5084 output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
5087 if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
5088 maxtaskparams=objectparams.numPrimitives()+fm.numTags();
5089 } else output.println(") {");
5092 public void generateFlatFlagActionNode(FlatMethod fm, LocalityBinding lb, FlatFlagActionNode ffan, PrintWriter output) {
5093 output.println("/* FlatFlagActionNode */");
5096 /* Process tag changes */
5097 Relation tagsettable=new Relation();
5098 Relation tagcleartable=new Relation();
5100 Iterator tagsit=ffan.getTempTagPairs();
5101 while (tagsit.hasNext()) {
5102 TempTagPair ttp=(TempTagPair) tagsit.next();
5103 TempDescriptor objtmp=ttp.getTemp();
5104 TagDescriptor tag=ttp.getTag();
5105 TempDescriptor tagtmp=ttp.getTagTemp();
5106 boolean tagstatus=ffan.getTagChange(ttp);
5108 tagsettable.put(objtmp, tagtmp);
5110 tagcleartable.put(objtmp, tagtmp);
5115 Hashtable flagandtable=new Hashtable();
5116 Hashtable flagortable=new Hashtable();
5118 /* Process flag changes */
5119 Iterator flagsit=ffan.getTempFlagPairs();
5120 while(flagsit.hasNext()) {
5121 TempFlagPair tfp=(TempFlagPair)flagsit.next();
5122 TempDescriptor temp=tfp.getTemp();
5123 Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
5124 FlagDescriptor flag=tfp.getFlag();
5126 //Newly allocate objects that don't set any flags case
5127 if (flagortable.containsKey(temp)) {
5131 flagortable.put(temp,new Integer(mask));
5133 int flagid=1<<((Integer)flagtable.get(flag)).intValue();
5134 boolean flagstatus=ffan.getFlagChange(tfp);
5137 if (flagortable.containsKey(temp)) {
5138 mask=((Integer)flagortable.get(temp)).intValue();
5141 flagortable.put(temp,new Integer(mask));
5143 int mask=0xFFFFFFFF;
5144 if (flagandtable.containsKey(temp)) {
5145 mask=((Integer)flagandtable.get(temp)).intValue();
5147 mask&=(0xFFFFFFFF^flagid);
5148 flagandtable.put(temp,new Integer(mask));
5154 HashSet flagtagset=new HashSet();
5155 flagtagset.addAll(flagortable.keySet());
5156 flagtagset.addAll(flagandtable.keySet());
5157 flagtagset.addAll(tagsettable.keySet());
5158 flagtagset.addAll(tagcleartable.keySet());
5160 Iterator ftit=flagtagset.iterator();
5161 while(ftit.hasNext()) {
5162 TempDescriptor temp=(TempDescriptor)ftit.next();
5165 Set tagtmps=tagcleartable.get(temp);
5166 if (tagtmps!=null) {
5167 Iterator tagit=tagtmps.iterator();
5168 while(tagit.hasNext()) {
5169 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
5170 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
5171 output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5173 output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5177 tagtmps=tagsettable.get(temp);
5178 if (tagtmps!=null) {
5179 Iterator tagit=tagtmps.iterator();
5180 while(tagit.hasNext()) {
5181 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
5182 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
5183 output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5185 output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp, lb)+", "+generateTemp(fm,tagtmp, lb)+");");
5190 int andmask=0xFFFFFFF;
5192 if (flagortable.containsKey(temp))
5193 ormask=((Integer)flagortable.get(temp)).intValue();
5194 if (flagandtable.containsKey(temp))
5195 andmask=((Integer)flagandtable.get(temp)).intValue();
5196 generateFlagOrAnd(ffan, fm, lb, temp, output, ormask, andmask);
5197 generateObjectDistribute(ffan, fm, lb, temp, output);
5201 protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp,
5202 PrintWriter output, int ormask, int andmask) {
5203 if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
5204 output.println("flagorandinit("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
5206 output.println("flagorand("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
5210 protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, PrintWriter output) {
5211 output.println("enqueueObject("+generateTemp(fm, temp, lb)+");");
5214 void generateOptionalHeader(PrintWriter headers) {
5217 headers.println("#include \"task.h\"\n\n");
5218 headers.println("#ifndef _OPTIONAL_STRUCT_");
5219 headers.println("#define _OPTIONAL_STRUCT_");
5221 //STRUCT PREDICATEMEMBER
5222 headers.println("struct predicatemember{");
5223 headers.println("int type;");
5224 headers.println("int numdnfterms;");
5225 headers.println("int * flags;");
5226 headers.println("int numtags;");
5227 headers.println("int * tags;\n};\n\n");
5229 //STRUCT OPTIONALTASKDESCRIPTOR
5230 headers.println("struct optionaltaskdescriptor{");
5231 headers.println("struct taskdescriptor * task;");
5232 headers.println("int index;");
5233 headers.println("int numenterflags;");
5234 headers.println("int * enterflags;");
5235 headers.println("int numpredicatemembers;");
5236 headers.println("struct predicatemember ** predicatememberarray;");
5237 headers.println("};\n\n");
5239 //STRUCT TASKFAILURE
5240 headers.println("struct taskfailure {");
5241 headers.println("struct taskdescriptor * task;");
5242 headers.println("int index;");
5243 headers.println("int numoptionaltaskdescriptors;");
5244 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
5246 //STRUCT FSANALYSISWRAPPER
5247 headers.println("struct fsanalysiswrapper{");
5248 headers.println("int flags;");
5249 headers.println("int numtags;");
5250 headers.println("int * tags;");
5251 headers.println("int numtaskfailures;");
5252 headers.println("struct taskfailure ** taskfailurearray;");
5253 headers.println("int numoptionaltaskdescriptors;");
5254 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
5256 //STRUCT CLASSANALYSISWRAPPER
5257 headers.println("struct classanalysiswrapper{");
5258 headers.println("int type;");
5259 headers.println("int numotd;");
5260 headers.println("struct optionaltaskdescriptor ** otdarray;");
5261 headers.println("int numfsanalysiswrappers;");
5262 headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
5264 headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
5266 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
5267 while(taskit.hasNext()) {
5268 TaskDescriptor td=(TaskDescriptor)taskit.next();
5269 headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
5274 //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
5275 int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
5276 int predicateindex = 0;
5277 //iterate through the classes concerned by the predicate
5278 Set c_vard = predicate.vardescriptors;
5279 Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
5282 for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext();) {
5283 VarDescriptor vard = (VarDescriptor)vard_it.next();
5284 TypeDescriptor typed = vard.getType();
5286 //generate for flags
5287 HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
5288 output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5290 if (fen_hashset!=null) {
5291 for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext();) {
5292 FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
5294 DNFFlag dflag=fen.getDNF();
5295 numberterms+=dflag.size();
5297 Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
5299 for(int j=0; j<dflag.size(); j++) {
5301 output.println(",");
5302 Vector term=dflag.get(j);
5305 for(int k=0; k<term.size(); k++) {
5306 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
5307 FlagDescriptor fd=dfa.getFlag();
5308 boolean negated=dfa.getNegated();
5309 int flagid=1<<((Integer)flags.get(fd)).intValue();
5314 output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
5319 output.println("};\n");
5322 TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
5323 output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5326 for(int j=0; j<tagel.numTags(); j++) {
5328 output.println(",");
5329 TempDescriptor tmp=tagel.getTemp(j);
5330 if (!slotnumber.containsKey(tmp)) {
5331 Integer slotint=new Integer(current_slot++);
5332 slotnumber.put(tmp,slotint);
5334 int slot=slotnumber.get(tmp).intValue();
5335 output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
5337 numtags = tagel.numTags();
5339 output.println("};");
5341 //store the result into a predicatemember struct
5342 output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
5343 output.println("/*type*/"+typed.getClassDesc().getId()+",");
5344 output.println("/* number of dnf terms */"+numberterms+",");
5345 output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5346 output.println("/* number of tag */"+numtags+",");
5347 output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5348 output.println("};\n");
5353 //generate an array that stores the entire predicate
5354 output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5355 for( int j = 0; j<predicateindex; j++) {
5356 if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5357 else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5359 output.println("};\n");
5360 return predicateindex;
5364 void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
5365 generateOptionalHeader(headers);
5367 output.println("#include \"optionalstruct.h\"\n\n");
5368 output.println("#include \"stdlib.h\"\n");
5370 HashSet processedcd = new HashSet();
5372 Enumeration e = safeexecution.keys();
5373 while (e.hasMoreElements()) {
5376 ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
5377 Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp); //will be used several times
5379 //Generate the struct of optionals
5380 Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
5381 numotd = c_otd.size();
5382 if(maxotd<numotd) maxotd = numotd;
5383 if( !c_otd.isEmpty() ) {
5384 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
5385 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
5387 //generate the int arrays for the predicate
5388 Predicate predicate = otd.predicate;
5389 int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
5390 TreeSet<Integer> fsset=new TreeSet<Integer>();
5391 //iterate through possible FSes corresponding to
5392 //the state when entering
5394 for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext();) {
5395 FlagState fs = (FlagState)fses.next();
5397 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
5398 FlagDescriptor flagd = (FlagDescriptor)flags.next();
5399 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
5402 fsset.add(new Integer(flagid));
5403 //tag information not needed because tag
5404 //changes are not tolerated.
5407 output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5408 boolean needcomma=false;
5409 for(Iterator<Integer> it=fsset.iterator(); it.hasNext();) {
5412 output.println(it.next());
5415 output.println("};\n");
5418 //generate optionaltaskdescriptor that actually
5419 //includes exit fses, predicate and the task
5421 output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
5422 output.println("&task_"+otd.td.getSafeSymbol()+",");
5423 output.println("/*index*/"+otd.getIndex()+",");
5424 output.println("/*number of enter flags*/"+fsset.size()+",");
5425 output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5426 output.println("/*number of members */"+predicateindex+",");
5427 output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5428 output.println("};\n");
5432 // if there are no optionals, there is no need to build the rest of the struct
5434 output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
5435 c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
5436 if( !c_otd.isEmpty() ) {
5437 boolean needcomma=false;
5438 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
5439 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
5441 output.println(",");
5443 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5446 output.println("};\n");
5448 //get all the possible flagstates reachable by an object
5449 Hashtable hashtbtemp = safeexecution.get(cdtemp);
5451 TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
5452 fsts.addAll(hashtbtemp.keySet());
5453 for(Iterator fsit=fsts.iterator(); fsit.hasNext();) {
5454 FlagState fs = (FlagState)fsit.next();
5457 //get the set of OptionalTaskDescriptors corresponding
5458 HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
5459 //iterate through the OptionalTaskDescriptors and
5460 //store the pointers to the optionals struct (see on
5461 //top) into an array
5463 output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
5464 for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext();) {
5465 OptionalTaskDescriptor mm = mos.next();
5467 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
5469 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5472 output.println("};\n");
5474 //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
5477 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
5478 FlagDescriptor flagd = (FlagDescriptor)flags.next();
5479 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
5483 //process tag information
5486 boolean first = true;
5487 Enumeration tag_enum = fs.getTags();
5488 output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
5489 while(tag_enum.hasMoreElements()) {
5491 TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
5495 output.println(", ");
5496 output.println("/*tagid*/"+state.getTagId(tagd));
5498 output.println("};");
5500 Set<TaskIndex> tiset=sa.getTaskIndex(fs);
5501 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
5502 TaskIndex ti=itti.next();
5506 Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
5508 output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
5509 boolean needcomma=false;
5510 for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext();) {
5511 OptionalTaskDescriptor otd=otdit.next();
5515 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5517 output.println("};");
5519 output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
5520 output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
5521 output.print(ti.getIndex()+", ");
5522 output.print(otdset.size()+", ");
5523 output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
5524 output.println("};");
5527 tiset=sa.getTaskIndex(fs);
5528 boolean needcomma=false;
5530 output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
5531 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
5532 TaskIndex ti=itti.next();
5533 if (ti.isRuntime()) {
5540 output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
5542 output.println("};\n");
5544 //Store the result in fsanalysiswrapper
5546 output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
5547 output.println("/*flag*/"+flagid+",");
5548 output.println("/* number of tags*/"+tagcounter+",");
5549 output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
5550 output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
5551 output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
5552 output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
5553 output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
5554 output.println("};\n");
5558 //Build the array of fsanalysiswrappers
5559 output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
5560 boolean needcomma=false;
5561 for(int i = 0; i<fscounter; i++) {
5562 if (needcomma) output.print(",");
5563 output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
5566 output.println("};");
5568 //Build the classanalysiswrapper referring to the previous array
5569 output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
5570 output.println("/*type*/"+cdtemp.getId()+",");
5571 output.println("/*numotd*/"+numotd+",");
5572 output.println("otdarray"+cdtemp.getSafeSymbol()+",");
5573 output.println("/* number of fsanalysiswrappers */"+fscounter+",");
5574 output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
5575 processedcd.add(cdtemp);
5578 //build an array containing every classes for which code has been build
5579 output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
5580 for(int i=0; i<state.numClasses(); i++) {
5581 ClassDescriptor cn=cdarray[i];
5584 if ((cn != null) && (processedcd.contains(cn)))
5585 output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
5587 output.print("NULL");
5589 output.println("};");
5591 output.println("#define MAXOTD "+maxotd);
5592 headers.println("#endif");
5595 public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
5596 Relation r=new Relation();
5597 for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext();) {
5598 OptionalTaskDescriptor otd=otdit.next();
5599 TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
5603 LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
5604 for(Iterator it=r.keySet().iterator(); it.hasNext();) {
5605 Set s=r.get(it.next());
5606 for(Iterator it2=s.iterator(); it2.hasNext();) {
5607 OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
5615 protected void outputTransCode(PrintWriter output) {
5618 private int calculateSizeOfSESEParamList(FlatSESEEnterNode fsen){
5620 Set<TempDescriptor> tdSet=new HashSet<TempDescriptor>();
5622 for (Iterator iterator = fsen.getInVarSet().iterator(); iterator.hasNext();) {
5623 TempDescriptor tempDescriptor = (TempDescriptor) iterator.next();
5624 if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()){
5625 tdSet.add(tempDescriptor);
5629 for (Iterator iterator = fsen.getOutVarSet().iterator(); iterator.hasNext();) {
5630 TempDescriptor tempDescriptor = (TempDescriptor) iterator.next();
5631 if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()){
5632 tdSet.add(tempDescriptor);
5636 return tdSet.size();
5639 private String calculateSizeOfSESEParamSize(FlatSESEEnterNode fsen){
5640 HashMap <String,Integer> map=new HashMap();
5641 HashSet <TempDescriptor> processed=new HashSet<TempDescriptor>();
5644 // space for all in and out set primitives
5645 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
5646 inSetAndOutSet.addAll( fsen.getInVarSet() );
5647 inSetAndOutSet.addAll( fsen.getOutVarSet() );
5649 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
5651 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
5652 while( itr.hasNext() ) {
5653 TempDescriptor temp = itr.next();
5654 TypeDescriptor type = temp.getType();
5655 if( !type.isPtr() ) {
5656 inSetAndOutSetPrims.add( temp );
5660 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
5661 while( itrPrims.hasNext() ) {
5662 TempDescriptor temp = itrPrims.next();
5663 TypeDescriptor type = temp.getType();
5664 if(type.isPrimitive()){
5665 Integer count=map.get(type.getSymbol());
5667 count=new Integer(1);
5668 map.put(type.getSymbol(), count);
5670 map.put(type.getSymbol(), new Integer(count.intValue()+1));
5675 Set<String> keySet=map.keySet();
5676 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
5677 String key = (String) iterator.next();
5678 rtr+="+sizeof("+key+")*"+map.get(key);