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;
13 import Analysis.TaskStateAnalysis.FlagState;
14 import Analysis.TaskStateAnalysis.FlagComparator;
15 import Analysis.TaskStateAnalysis.OptionalTaskDescriptor;
16 import Analysis.TaskStateAnalysis.Predicate;
17 import Analysis.TaskStateAnalysis.SafetyAnalysis;
18 import Analysis.TaskStateAnalysis.TaskIndex;
19 import Analysis.Locality.LocalityAnalysis;
20 import Analysis.Locality.LocalityBinding;
21 import Analysis.Locality.DiscoverConflicts;
22 import Analysis.Locality.DCWrapper;
23 import Analysis.Locality.DelayComputation;
24 import Analysis.Locality.BranchAnalysis;
25 import Analysis.CallGraph.CallGraph;
26 import Analysis.Prefetch.*;
27 import Analysis.Loops.WriteBarrier;
28 import Analysis.Loops.GlobalFieldType;
29 import Analysis.Locality.TypeAnalysis;
30 import Analysis.MLP.ConflictGraph;
31 import Analysis.MLP.MLPAnalysis;
32 import Analysis.MLP.ParentChildConflictsMap;
33 import Analysis.MLP.SESELock;
34 import Analysis.MLP.VariableSourceToken;
35 import Analysis.MLP.CodePlan;
36 import Analysis.MLP.SESEandAgePair;
37 import Analysis.MLP.WaitingElement;
39 public class BuildCode {
42 Hashtable paramstable;
47 String localsprefix="___locals___";
48 String localsprefixaddr="&"+localsprefix;
49 String localsprefixderef=localsprefix+".";
50 String fcrevert="___fcrevert___";
51 String paramsprefix="___params___";
52 String oidstr="___nextobject___";
53 String nextobjstr="___nextobject___";
54 String localcopystr="___localcopy___";
55 public static boolean GENERATEPRECISEGC=false;
56 public static String PREFIX="";
57 public static String arraytype="ArrayObject";
58 public static int flagcount = 0;
61 protected int maxtaskparams=0;
62 private int maxcount=0;
63 ClassDescriptor[] cdarray;
64 TypeDescriptor[] arraytable;
65 LocalityAnalysis locality;
66 Hashtable<LocalityBinding, TempDescriptor> reverttable;
67 Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>> backuptable;
71 String mlperrstr = "if(status != 0) { "+
72 "sprintf(errmsg, \"MLP error at %s:%d\", __FILE__, __LINE__); "+
73 "perror(errmsg); exit(-1); }";
74 boolean nonSESEpass=true;
77 DiscoverConflicts recorddc;
82 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa) {
83 this(st, temptovar, typeutil, null, sa, pa, null);
86 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa) {
87 this(st, temptovar, typeutil, null, sa, pa, mlpa);
90 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, PrefetchAnalysis pa, MLPAnalysis mlpa) {
91 this(st, temptovar, typeutil, locality, null, pa, mlpa);
94 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa) {
99 callgraph=new CallGraph(state);
101 oidstr="___objlocation___";
102 this.temptovar=temptovar;
103 paramstable=new Hashtable();
104 tempstable=new Hashtable();
105 fieldorder=new Hashtable();
106 flagorder=new Hashtable();
107 this.typeutil=typeutil;
108 virtualcalls=new Virtual(state,locality);
109 if (locality!=null) {
110 this.locality=locality;
111 this.reverttable=new Hashtable<LocalityBinding, TempDescriptor>();
112 this.backuptable=new Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>>();
113 this.wb=new WriteBarrier(locality, st);
115 if (state.SINGLETM&&state.DCOPTS) {
116 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
117 GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
118 this.dc=new DiscoverConflicts(locality, st, typeanalysis, gft);
121 if (state.DELAYCOMP) {
122 //TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
123 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
124 GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
125 delaycomp=new DCWrapper(locality, st, typeanalysis, gft);
126 dc=delaycomp.getConflicts();
127 recorddc=new DiscoverConflicts(locality, st, typeanalysis, delaycomp.getCannotDelayMap(), true, true, null);
128 recorddc.doAnalysis();
132 /** The buildCode method outputs C code for all the methods. The Flat
133 * versions of the methods must already be generated and stored in
134 * the State object. */
135 PrintWriter outsandbox=null;
137 public void buildCode() {
138 /* Create output streams to write to */
139 PrintWriter outclassdefs=null;
140 PrintWriter outstructs=null;
141 PrintWriter outrepairstructs=null;
142 PrintWriter outmethodheader=null;
143 PrintWriter outmethod=null;
144 PrintWriter outvirtual=null;
145 PrintWriter outtask=null;
146 PrintWriter outtaskdefs=null;
147 PrintWriter outoptionalarrays=null;
148 PrintWriter optionalheaders=null;
152 outsandbox=new PrintWriter(new FileOutputStream(PREFIX+"sandboxdefs.c"), true);
154 outstructs=new PrintWriter(new FileOutputStream(PREFIX+"structdefs.h"), true);
155 outmethodheader=new PrintWriter(new FileOutputStream(PREFIX+"methodheaders.h"), true);
156 outclassdefs=new PrintWriter(new FileOutputStream(PREFIX+"classdefs.h"), true);
157 outmethod=new PrintWriter(new FileOutputStream(PREFIX+"methods.c"), true);
158 outvirtual=new PrintWriter(new FileOutputStream(PREFIX+"virtualtable.h"), true);
160 outtask=new PrintWriter(new FileOutputStream(PREFIX+"task.h"), true);
161 outtaskdefs=new PrintWriter(new FileOutputStream(PREFIX+"taskdefs.c"), true);
162 if (state.OPTIONAL) {
163 outoptionalarrays=new PrintWriter(new FileOutputStream(PREFIX+"optionalarrays.c"), true);
164 optionalheaders=new PrintWriter(new FileOutputStream(PREFIX+"optionalstruct.h"), true);
167 if (state.structfile!=null) {
168 outrepairstructs=new PrintWriter(new FileOutputStream(PREFIX+state.structfile+".struct"), true);
170 } catch (Exception e) {
175 /* Build the virtual dispatch tables */
176 buildVirtualTables(outvirtual);
178 /* Output includes */
179 outmethodheader.println("#ifndef METHODHEADERS_H");
180 outmethodheader.println("#define METHODHEADERS_H");
181 outmethodheader.println("#include \"structdefs.h\"");
183 outmethodheader.println("#include \"dstm.h\"");
185 outmethodheader.println("#include \"sandbox.h\"");
187 if (state.EVENTMONITOR) {
188 outmethodheader.println("#include \"monitor.h\"");
190 if (state.SINGLETM) {
191 outmethodheader.println("#include \"tm.h\"");
192 outmethodheader.println("#include \"delaycomp.h\"");
193 outmethodheader.println("#include \"inlinestm.h\"");
195 if (state.ABORTREADERS) {
196 outmethodheader.println("#include \"abortreaders.h\"");
197 outmethodheader.println("#include <setjmp.h>");
200 outmethodheader.println("#include <stdlib.h>");
201 outmethodheader.println("#include <stdio.h>");
202 outmethodheader.println("#include <string.h>");
203 outmethodheader.println("#include \"mlp_runtime.h\"");
204 outmethodheader.println("#include \"psemaphore.h\"");
207 /* Output Structures */
208 outputStructs(outstructs);
210 // Output the C class declarations
211 // These could mutually reference each other
212 outputClassDeclarations(outclassdefs);
214 // Output function prototypes and structures for parameters
215 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
216 while(it.hasNext()) {
217 ClassDescriptor cn=(ClassDescriptor)it.next();
218 generateCallStructs(cn, outclassdefs, outstructs, outmethodheader);
220 outclassdefs.close();
223 /* Map flags to integers */
224 /* The runtime keeps track of flags using these integers */
225 it=state.getClassSymbolTable().getDescriptorsIterator();
226 while(it.hasNext()) {
227 ClassDescriptor cn=(ClassDescriptor)it.next();
231 generateTaskStructs(outstructs, outmethodheader);
233 /* Outputs generic task structures if this is a task
235 outputTaskTypes(outtask);
239 // have to initialize some SESE compiler data before
240 // analyzing normal methods, which must happen before
241 // generating SESE internal code
242 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
243 FlatSESEEnterNode fsen = seseit.next();
244 initializeSESE( fsen );
248 /* Build the actual methods */
249 outputMethods(outmethod);
251 // Output function prototypes and structures for SESE's and code
254 // used to differentiate, during code generation, whether we are
255 // passing over SESE body code, or non-SESE code
258 // first generate code for each sese's internals
259 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
260 FlatSESEEnterNode fsen = seseit.next();
261 generateMethodSESE(fsen, null, outstructs, outmethodheader, outmethod);
264 // then write the invokeSESE switch to decouple scheduler
265 // from having to do unique details of sese invocation
266 generateSESEinvocationMethod(outmethodheader, outmethod);
270 /* Output code for tasks */
271 outputTaskCode(outtaskdefs, outmethod);
273 /* Record maximum number of task parameters */
274 outstructs.println("#define MAXTASKPARAMS "+maxtaskparams);
275 } else if (state.main!=null) {
276 /* Generate main method */
277 outputMainMethod(outmethod);
280 /* Generate information for task with optional parameters */
281 if (state.TASK&&state.OPTIONAL) {
282 generateOptionalArrays(outoptionalarrays, optionalheaders, state.getAnalysisResult(), state.getOptionalTaskDescriptors());
283 outoptionalarrays.close();
286 /* Output structure definitions for repair tool */
287 if (state.structfile!=null) {
288 buildRepairStructs(outrepairstructs);
289 outrepairstructs.close();
293 outmethodheader.println("#endif");
294 outmethodheader.close();
296 outstructs.println("#endif");
301 /* This code just generates the main C method for java programs.
302 * The main C method packs up the arguments into a string array
303 * and passes it to the java main method. */
305 private void outputMainMethod(PrintWriter outmethod) {
306 outmethod.println("int main(int argc, const char *argv[]) {");
307 outmethod.println(" int i;");
310 //outmethod.println(" pthread_once( &mlpOnceObj, mlpInitOncePerThread );");
311 outmethod.println(" workScheduleInit( "+state.MLP_NUMCORES+", invokeSESEmethod );");
315 outmethod.println("#ifdef TRANSSTATS \n");
316 outmethod.println("handle();\n");
317 outmethod.println("#endif\n");
319 if (state.THREAD||state.DSM||state.SINGLETM) {
320 outmethod.println("initializethreads();");
323 outmethod.println("if (dstmStartup(argv[1])) {");
324 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
325 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-2);");
327 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-2);");
330 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
331 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1);");
333 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1);");
337 outmethod.println(" for(i=2;i<argc;i++) {");
339 outmethod.println(" for(i=1;i<argc;i++) {");
340 outmethod.println(" int length=strlen(argv[i]);");
341 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
342 outmethod.println(" struct ___String___ *newstring=NewString(NULL, argv[i], length);");
344 outmethod.println(" struct ___String___ *newstring=NewString(argv[i], length);");
347 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-2]=newstring;");
349 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-1]=newstring;");
350 outmethod.println(" }");
352 MethodDescriptor md=typeutil.getMain();
353 ClassDescriptor cd=typeutil.getMainClass();
355 outmethod.println(" {");
356 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
357 if (state.DSM||state.SINGLETM) {
358 outmethod.print(" struct "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
360 outmethod.print(" struct "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
361 outmethod.println("1, NULL,"+"stringarray};");
362 if (state.DSM||state.SINGLETM)
363 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
365 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
367 if (state.DSM||state.SINGLETM)
368 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
370 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
372 outmethod.println(" }");
375 outmethod.println("}");
378 if (state.THREAD||state.DSM||state.SINGLETM) {
379 outmethod.println("pthread_mutex_lock(&gclistlock);");
380 outmethod.println("threadcount--;");
381 outmethod.println("pthread_cond_signal(&gccond);");
382 outmethod.println("pthread_mutex_unlock(&gclistlock);");
385 if (state.DSM||state.SINGLETM) {
386 outmethod.println("#ifdef TRANSSTATS \n");
387 outmethod.println("printf(\"****** Transaction Stats ******\\n\");");
388 outmethod.println("printf(\"numTransCommit= %d\\n\", numTransCommit);");
389 outmethod.println("printf(\"numTransAbort= %d\\n\", numTransAbort);");
390 outmethod.println("printf(\"nSoftAbort= %d\\n\", nSoftAbort);");
392 outmethod.println("printf(\"nchashSearch= %d\\n\", nchashSearch);");
393 outmethod.println("printf(\"nmhashSearch= %d\\n\", nmhashSearch);");
394 outmethod.println("printf(\"nprehashSearch= %d\\n\", nprehashSearch);");
395 outmethod.println("printf(\"ndirtyCacheObj= %d\\n\", ndirtyCacheObj);");
396 outmethod.println("printf(\"nRemoteReadSend= %d\\n\", nRemoteSend);");
397 outmethod.println("printf(\"bytesSent= %d\\n\", bytesSent);");
398 outmethod.println("printf(\"bytesRecv= %d\\n\", bytesRecv);");
399 outmethod.println("printf(\"totalObjSize= %d\\n\", totalObjSize);");
400 outmethod.println("printf(\"sendRemoteReq= %d\\n\", sendRemoteReq);");
401 outmethod.println("printf(\"getResponse= %d\\n\", getResponse);");
402 } else if (state.SINGLETM) {
403 outmethod.println("printf(\"nSoftAbortAbort= %d\\n\", nSoftAbortAbort);");
404 outmethod.println("printf(\"nSoftAbortCommit= %d\\n\", nSoftAbortCommit);");
405 outmethod.println("#ifdef STMSTATS\n");
406 outmethod.println("for(i=0; i<TOTALNUMCLASSANDARRAY; i++) {\n");
407 outmethod.println(" printf(\"typesCausingAbort[%2d] numaccess= %5d numabort= %3d\\n\", i, typesCausingAbort[i].numaccess, typesCausingAbort[i].numabort);\n");
408 outmethod.println("}\n");
409 outmethod.println("#endif\n");
410 outmethod.println("fflush(stdout);");
412 outmethod.println("#endif\n");
415 if(state.DSMRECOVERYSTATS) {
416 outmethod.println("#ifdef RECOVERYSTATS\n");
417 outmethod.println("printf(\"***** Recovery Stats *****\\n\");");
418 outmethod.println("printf(\"numRecovery = %d\\n\",numRecovery)");
419 outmethod.println("int nRecovery=0;");
420 outmethod.println("for(nRecovery=0;nRecovery<numRecovery;nRecovery++) {");
421 outmethod.println(" printf(\"Dead Machine = %s\\n\",deadMachine[nRecovery]);");
422 outmethod.println(" printf(\"Recovery Time = %.2f\\n\",elapsedTime[nRecovery]);");
423 outmethod.println(" }\n");
424 outmethod.println("fflush(stdout);");
425 outmethod.println("#endif\n");
428 if (state.EVENTMONITOR) {
429 outmethod.println("dumpdata();");
432 if (state.THREAD||state.SINGLETM)
433 outmethod.println("pthread_exit(NULL);");
436 outmethod.println(" workScheduleBegin();");
439 outmethod.println("}");
442 /* This method outputs code for each task. */
444 private void outputTaskCode(PrintWriter outtaskdefs, PrintWriter outmethod) {
445 /* Compile task based program */
446 outtaskdefs.println("#include \"task.h\"");
447 outtaskdefs.println("#include \"methodheaders.h\"");
448 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
449 while(taskit.hasNext()) {
450 TaskDescriptor td=(TaskDescriptor)taskit.next();
451 FlatMethod fm=state.getMethodFlat(td);
452 generateFlatMethod(fm, null, outmethod);
453 generateTaskDescriptor(outtaskdefs, fm, td);
456 //Output task descriptors
457 taskit=state.getTaskSymbolTable().getDescriptorsIterator();
458 outtaskdefs.println("struct taskdescriptor * taskarray[]= {");
460 while(taskit.hasNext()) {
461 TaskDescriptor td=(TaskDescriptor)taskit.next();
465 outtaskdefs.println(",");
466 outtaskdefs.print("&task_"+td.getSafeSymbol());
468 outtaskdefs.println("};");
470 outtaskdefs.println("int numtasks="+state.getTaskSymbolTable().getValueSet().size()+";");
473 /* This method outputs most of the methods.c file. This includes
474 * some standard includes and then an array with the sizes of
475 * objets and array that stores supertype and then the code for
476 * the Java methods.. */
478 protected void outputMethods(PrintWriter outmethod) {
479 outmethod.println("#include \"methodheaders.h\"");
480 outmethod.println("#include \"virtualtable.h\"");
481 outmethod.println("#include \"runtime.h\"");
483 outmethod.println("#include \"sandboxdefs.c\"");
486 outmethod.println("#include \"addPrefetchEnhance.h\"");
487 outmethod.println("#include \"localobjects.h\"");
489 if (state.FASTCHECK) {
490 outmethod.println("#include \"localobjects.h\"");
492 if(state.MULTICORE) {
493 outmethod.println("#include \"task.h\"");
494 outmethod.println("#include \"multicoreruntime.h\"");
495 outmethod.println("#include \"runtime_arch.h\"");
497 if (state.THREAD||state.DSM||state.SINGLETM)
498 outmethod.println("#include <thread.h>");
499 if (state.main!=null) {
500 outmethod.println("#include <string.h>");
502 if (state.CONSCHECK) {
503 outmethod.println("#include \"checkers.h\"");
506 outmethod.println("#include <stdlib.h>");
507 outmethod.println("#include <stdio.h>");
508 outmethod.println("#include \"mlp_runtime.h\"");
509 outmethod.println("#include \"psemaphore.h\"");
513 //Store the sizes of classes & array elements
514 generateSizeArray(outmethod);
516 //Store table of supertypes
517 generateSuperTypeTable(outmethod);
519 //Store the layout of classes
520 generateLayoutStructs(outmethod);
522 /* Generate code for methods */
523 if (state.DSM||state.SINGLETM) {
524 for(Iterator<LocalityBinding> lbit=locality.getLocalityBindings().iterator(); lbit.hasNext();) {
525 LocalityBinding lb=lbit.next();
526 MethodDescriptor md=lb.getMethod();
527 FlatMethod fm=state.getMethodFlat(md);
529 if (!md.getModifiers().isNative()) {
530 generateFlatMethod(fm, lb, outmethod);
531 //System.out.println("fm= " + fm + " md= " + md);
535 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
536 while(classit.hasNext()) {
537 ClassDescriptor cn=(ClassDescriptor)classit.next();
538 Iterator methodit=cn.getMethods();
539 while(methodit.hasNext()) {
540 /* Classify parameters */
541 MethodDescriptor md=(MethodDescriptor)methodit.next();
542 FlatMethod fm=state.getMethodFlat(md);
543 if (!md.getModifiers().isNative()) {
544 generateFlatMethod(fm, null, outmethod);
551 protected void outputStructs(PrintWriter outstructs) {
552 outstructs.println("#ifndef STRUCTDEFS_H");
553 outstructs.println("#define STRUCTDEFS_H");
554 outstructs.println("#include \"classdefs.h\"");
555 outstructs.println("#ifndef INTPTR");
556 outstructs.println("#ifdef BIT64");
557 outstructs.println("#define INTPTR long");
558 outstructs.println("#else");
559 outstructs.println("#define INTPTR int");
560 outstructs.println("#endif");
561 outstructs.println("#endif");
563 outstructs.println("#include \"mlp_runtime.h\"");
564 outstructs.println("#include \"psemaphore.h\"");
567 /* Output #defines that the runtime uses to determine type
568 * numbers for various objects it needs */
569 outstructs.println("#define MAXCOUNT "+maxcount);
570 if (state.DSM||state.SINGLETM) {
571 LocalityBinding lbrun=new LocalityBinding(typeutil.getRun(), false);
573 lbrun.setGlobalThis(LocalityAnalysis.GLOBAL);
575 else if (state.SINGLETM) {
576 lbrun.setGlobalThis(LocalityAnalysis.NORMAL);
578 outstructs.println("#define RUNMETHOD "+virtualcalls.getLocalityNumber(lbrun));
582 LocalityBinding lbexecute = new LocalityBinding(typeutil.getExecute(), false);
584 lbexecute.setGlobalThis(LocalityAnalysis.GLOBAL);
585 else if( state.SINGLETM)
586 lbexecute.setGlobalThis(LocalityAnalysis.NORMAL);
587 outstructs.println("#define EXECUTEMETHOD " + virtualcalls.getLocalityNumber(lbexecute));
590 outstructs.println("#define STRINGARRAYTYPE "+
591 (state.getArrayNumber(
592 (new TypeDescriptor(typeutil.getClass(TypeUtil.StringClass))).makeArray(state))+state.numClasses()));
594 outstructs.println("#define OBJECTARRAYTYPE "+
595 (state.getArrayNumber(
596 (new TypeDescriptor(typeutil.getClass(TypeUtil.ObjectClass))).makeArray(state))+state.numClasses()));
599 outstructs.println("#define STRINGTYPE "+typeutil.getClass(TypeUtil.StringClass).getId());
600 outstructs.println("#define CHARARRAYTYPE "+
601 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.CHAR)).makeArray(state))+state.numClasses()));
603 outstructs.println("#define BYTEARRAYTYPE "+
604 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state))+state.numClasses()));
606 outstructs.println("#define BYTEARRAYARRAYTYPE "+
607 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state).makeArray(state))+state.numClasses()));
609 outstructs.println("#define NUMCLASSES "+state.numClasses());
610 int totalClassSize = state.numClasses() + state.numArrays();
611 outstructs.println("#define TOTALNUMCLASSANDARRAY "+ totalClassSize);
613 outstructs.println("#define STARTUPTYPE "+typeutil.getClass(TypeUtil.StartupClass).getId());
614 outstructs.println("#define TAGTYPE "+typeutil.getClass(TypeUtil.TagClass).getId());
615 outstructs.println("#define TAGARRAYTYPE "+
616 (state.getArrayNumber(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)).makeArray(state))+state.numClasses()));
620 protected void outputClassDeclarations(PrintWriter outclassdefs) {
621 if (state.THREAD||state.DSM||state.SINGLETM)
622 outclassdefs.println("#include <pthread.h>");
623 outclassdefs.println("#ifndef INTPTR");
624 outclassdefs.println("#ifdef BIT64");
625 outclassdefs.println("#define INTPTR long");
626 outclassdefs.println("#else");
627 outclassdefs.println("#define INTPTR int");
628 outclassdefs.println("#endif");
629 outclassdefs.println("#endif");
631 outclassdefs.println("#include \"optionalstruct.h\"");
632 outclassdefs.println("struct "+arraytype+";");
633 /* Start by declaring all structs */
634 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
635 while(it.hasNext()) {
636 ClassDescriptor cn=(ClassDescriptor)it.next();
637 outclassdefs.println("struct "+cn.getSafeSymbol()+";");
639 outclassdefs.println("");
640 //Print out definition for array type
641 outclassdefs.println("struct "+arraytype+" {");
642 outclassdefs.println(" int type;");
643 if (state.EVENTMONITOR) {
644 outclassdefs.println(" int objuid;");
647 outclassdefs.println(" pthread_t tid;");
648 outclassdefs.println(" void * lockentry;");
649 outclassdefs.println(" int lockcount;");
652 outclassdefs.println(" int flag;");
653 if(!state.MULTICORE) {
654 outclassdefs.println(" void * flagptr;");
656 outclassdefs.println(" int version;");
657 outclassdefs.println(" int * lock;"); // lock entry for this obj
658 outclassdefs.println(" int mutex;");
659 outclassdefs.println(" int lockcount;");
660 if(state.MULTICOREGC) {
661 outclassdefs.println(" int marked;");
665 outclassdefs.println(" int numfses;");
666 outclassdefs.println(" int * fses;");
669 printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs);
671 if (state.STMARRAY) {
672 outclassdefs.println(" int lowindex;");
673 outclassdefs.println(" int highindex;");
676 outclassdefs.println(" int paddingforarray;");
677 if (state.DUALVIEW) {
678 outclassdefs.println(" int arrayversion;");
681 outclassdefs.println(" int ___length___;");
682 outclassdefs.println("};\n");
683 outclassdefs.println("extern int classsize[];");
684 outclassdefs.println("extern int hasflags[];");
685 outclassdefs.println("extern unsigned INTPTR * pointerarray[];");
686 outclassdefs.println("extern int supertypes[];");
689 /** Prints out definitions for generic task structures */
691 private void outputTaskTypes(PrintWriter outtask) {
692 outtask.println("#ifndef _TASK_H");
693 outtask.println("#define _TASK_H");
694 outtask.println("struct parameterdescriptor {");
695 outtask.println("int type;");
696 outtask.println("int numberterms;");
697 outtask.println("int *intarray;");
698 outtask.println("void * queue;");
699 outtask.println("int numbertags;");
700 outtask.println("int *tagarray;");
701 outtask.println("};");
703 outtask.println("struct taskdescriptor {");
704 outtask.println("void * taskptr;");
705 outtask.println("int numParameters;");
706 outtask.println(" int numTotal;");
707 outtask.println("struct parameterdescriptor **descriptorarray;");
708 outtask.println("char * name;");
709 outtask.println("};");
710 outtask.println("extern struct taskdescriptor * taskarray[];");
711 outtask.println("extern numtasks;");
712 outtask.println("#endif");
716 private void buildRepairStructs(PrintWriter outrepairstructs) {
717 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
718 while(classit.hasNext()) {
719 ClassDescriptor cn=(ClassDescriptor)classit.next();
720 outrepairstructs.println("structure "+cn.getSymbol()+" {");
721 outrepairstructs.println(" int __type__;");
723 outrepairstructs.println(" int __flag__;");
724 if(!state.MULTICORE) {
725 outrepairstructs.println(" int __flagptr__;");
728 printRepairStruct(cn, outrepairstructs);
729 outrepairstructs.println("}\n");
732 for(int i=0; i<state.numArrays(); i++) {
733 TypeDescriptor tdarray=arraytable[i];
734 TypeDescriptor tdelement=tdarray.dereference();
735 outrepairstructs.println("structure "+arraytype+"_"+state.getArrayNumber(tdarray)+" {");
736 outrepairstructs.println(" int __type__;");
737 printRepairStruct(typeutil.getClass(TypeUtil.ObjectClass), outrepairstructs);
738 outrepairstructs.println(" int length;");
740 // Need to add support to repair tool for this
741 if (tdelement.isClass()||tdelement.isArray())
742 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" * elem[this.length];");
744 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" elem[this.length];");
746 outrepairstructs.println("}\n");
750 private void printRepairStruct(ClassDescriptor cn, PrintWriter output) {
751 ClassDescriptor sp=cn.getSuperDesc();
753 printRepairStruct(sp, output);
755 Vector fields=(Vector)fieldorder.get(cn);
757 for(int i=0; i<fields.size(); i++) {
758 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
759 if (fd.getType().isArray()) {
760 output.println(" "+arraytype+"_"+ state.getArrayNumber(fd.getType()) +" * "+fd.getSymbol()+";");
761 } else if (fd.getType().isClass())
762 output.println(" "+fd.getType().getRepairSymbol()+" * "+fd.getSymbol()+";");
763 else if (fd.getType().isFloat())
764 output.println(" int "+fd.getSymbol()+"; /* really float */");
766 output.println(" "+fd.getType().getRepairSymbol()+" "+fd.getSymbol()+";");
770 /** This method outputs TaskDescriptor information */
771 private void generateTaskDescriptor(PrintWriter output, FlatMethod fm, TaskDescriptor task) {
772 for (int i=0; i<task.numParameters(); i++) {
773 VarDescriptor param_var=task.getParameter(i);
774 TypeDescriptor param_type=task.getParamType(i);
775 FlagExpressionNode param_flag=task.getFlag(param_var);
776 TagExpressionList param_tag=task.getTag(param_var);
779 if (param_flag==null) {
780 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
781 output.println("0x0, 0x0 };");
784 DNFFlag dflag=param_flag.getDNF();
785 dnfterms=dflag.size();
787 Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
788 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
789 for(int j=0; j<dflag.size(); j++) {
792 Vector term=dflag.get(j);
795 for(int k=0; k<term.size(); k++) {
796 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
797 FlagDescriptor fd=dfa.getFlag();
798 boolean negated=dfa.getNegated();
799 int flagid=1<<((Integer)flags.get(fd)).intValue();
804 output.print("0x"+Integer.toHexString(andmask)+", 0x"+Integer.toHexString(checkmask));
806 output.println("};");
809 output.println("int parametertag_"+i+"_"+task.getSafeSymbol()+"[]={");
810 //BUG...added next line to fix, test with any task program
812 for(int j=0; j<param_tag.numTags(); j++) {
815 /* for each tag we need */
816 /* which slot it is */
817 /* what type it is */
818 TagVarDescriptor tvd=(TagVarDescriptor)task.getParameterTable().get(param_tag.getName(j));
819 TempDescriptor tmp=param_tag.getTemp(j);
820 int slot=fm.getTagInt(tmp);
821 output.println(slot+", "+state.getTagId(tvd.getTag()));
823 output.println("};");
825 output.println("struct parameterdescriptor parameter_"+i+"_"+task.getSafeSymbol()+"={");
826 output.println("/* type */"+param_type.getClassDesc().getId()+",");
827 output.println("/* number of DNF terms */"+dnfterms+",");
828 output.println("parameterdnf_"+i+"_"+task.getSafeSymbol()+",");
829 output.println("0,");
830 //BUG, added next line to fix and else statement...test
831 //with any task program
833 output.println("/* number of tags */"+param_tag.numTags()+",");
835 output.println("/* number of tags */ 0,");
836 output.println("parametertag_"+i+"_"+task.getSafeSymbol());
837 output.println("};");
841 output.println("struct parameterdescriptor * parameterdescriptors_"+task.getSafeSymbol()+"[] = {");
842 for (int i=0; i<task.numParameters(); i++) {
845 output.print("¶meter_"+i+"_"+task.getSafeSymbol());
847 output.println("};");
849 output.println("struct taskdescriptor task_"+task.getSafeSymbol()+"={");
850 output.println("&"+task.getSafeSymbol()+",");
851 output.println("/* number of parameters */" +task.numParameters() + ",");
852 int numtotal=task.numParameters()+fm.numTags();
853 output.println("/* number total parameters */" +numtotal + ",");
854 output.println("parameterdescriptors_"+task.getSafeSymbol()+",");
855 output.println("\""+task.getSymbol()+"\"");
856 output.println("};");
860 /** The buildVirtualTables method outputs the virtual dispatch
861 * tables for methods. */
863 protected void buildVirtualTables(PrintWriter outvirtual) {
864 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
865 while(classit.hasNext()) {
866 ClassDescriptor cd=(ClassDescriptor)classit.next();
867 if (virtualcalls.getMethodCount(cd)>maxcount)
868 maxcount=virtualcalls.getMethodCount(cd);
870 MethodDescriptor[][] virtualtable=null;
871 LocalityBinding[][] lbvirtualtable=null;
872 if (state.DSM||state.SINGLETM)
873 lbvirtualtable=new LocalityBinding[state.numClasses()+state.numArrays()][maxcount];
875 virtualtable=new MethodDescriptor[state.numClasses()+state.numArrays()][maxcount];
877 /* Fill in virtual table */
878 classit=state.getClassSymbolTable().getDescriptorsIterator();
879 while(classit.hasNext()) {
880 ClassDescriptor cd=(ClassDescriptor)classit.next();
881 if (state.DSM||state.SINGLETM)
882 fillinRow(cd, lbvirtualtable, cd.getId());
884 fillinRow(cd, virtualtable, cd.getId());
887 ClassDescriptor objectcd=typeutil.getClass(TypeUtil.ObjectClass);
888 Iterator arrayit=state.getArrayIterator();
889 while(arrayit.hasNext()) {
890 TypeDescriptor td=(TypeDescriptor)arrayit.next();
891 int id=state.getArrayNumber(td);
892 if (state.DSM||state.SINGLETM)
893 fillinRow(objectcd, lbvirtualtable, id+state.numClasses());
895 fillinRow(objectcd, virtualtable, id+state.numClasses());
898 outvirtual.print("void * virtualtable[]={");
899 boolean needcomma=false;
900 for(int i=0; i<state.numClasses()+state.numArrays(); i++) {
901 for(int j=0; j<maxcount; j++) {
903 outvirtual.print(", ");
904 if ((state.DSM||state.SINGLETM)&&lbvirtualtable[i][j]!=null) {
905 LocalityBinding lb=lbvirtualtable[i][j];
906 MethodDescriptor md=lb.getMethod();
907 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
908 } else if (!(state.DSM||state.SINGLETM)&&virtualtable[i][j]!=null) {
909 MethodDescriptor md=virtualtable[i][j];
910 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
912 outvirtual.print("0");
916 outvirtual.println("");
918 outvirtual.println("};");
922 private void fillinRow(ClassDescriptor cd, MethodDescriptor[][] virtualtable, int rownum) {
923 /* Get inherited methods */
924 if (cd.getSuperDesc()!=null)
925 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
926 /* Override them with our methods */
927 for(Iterator it=cd.getMethods(); it.hasNext();) {
928 MethodDescriptor md=(MethodDescriptor)it.next();
929 if (md.isStatic()||md.getReturnType()==null)
931 int methodnum=virtualcalls.getMethodNumber(md);
932 virtualtable[rownum][methodnum]=md;
936 private void fillinRow(ClassDescriptor cd, LocalityBinding[][] virtualtable, int rownum) {
937 /* Get inherited methods */
938 if (cd.getSuperDesc()!=null)
939 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
940 /* Override them with our methods */
941 if (locality.getClassBindings(cd)!=null)
942 for(Iterator<LocalityBinding> lbit=locality.getClassBindings(cd).iterator(); lbit.hasNext();) {
943 LocalityBinding lb=lbit.next();
944 MethodDescriptor md=lb.getMethod();
945 //Is the method static or a constructor
946 if (md.isStatic()||md.getReturnType()==null)
948 int methodnum=virtualcalls.getLocalityNumber(lb);
949 virtualtable[rownum][methodnum]=lb;
953 /** Generate array that contains the sizes of class objects. The
954 * object allocation functions in the runtime use this
957 private void generateSizeArray(PrintWriter outclassdefs) {
958 outclassdefs.print("extern struct prefetchCountStats * evalPrefetch;\n");
959 outclassdefs.print("#ifdef TRANSSTATS \n");
960 outclassdefs.print("extern int numTransAbort;\n");
961 outclassdefs.print("extern int numTransCommit;\n");
962 outclassdefs.print("extern int nSoftAbort;\n");
964 outclassdefs.print("extern int nchashSearch;\n");
965 outclassdefs.print("extern int nmhashSearch;\n");
966 outclassdefs.print("extern int nprehashSearch;\n");
967 outclassdefs.print("extern int ndirtyCacheObj;\n");
968 outclassdefs.print("extern int nRemoteSend;\n");
969 outclassdefs.print("extern int sendRemoteReq;\n");
970 outclassdefs.print("extern int getResponse;\n");
971 outclassdefs.print("extern int bytesSent;\n");
972 outclassdefs.print("extern int bytesRecv;\n");
973 outclassdefs.print("extern int totalObjSize;\n");
974 outclassdefs.print("extern void handle();\n");
975 } else if (state.SINGLETM) {
976 outclassdefs.println("extern int nSoftAbortAbort;");
977 outclassdefs.println("extern int nSoftAbortCommit;");
978 outclassdefs.println("#ifdef STMSTATS\n");
979 outclassdefs.println("extern objtypestat_t typesCausingAbort[];");
980 outclassdefs.println("#endif\n");
982 outclassdefs.print("#endif\n");
984 if(state.DSMRECOVERYSTATS) {
985 outclassdefs.print("#ifdef RECOVERYSTATS\n");
986 outclassdefs.print("extern int numRecovery;\n");
987 outclassdefs.print("extern unsigned int deadMachine[8];\n");
988 outclassdefs.print("extern double elapsedTime[8];\n");
989 outclassdefs.print("#endif\n");
991 outclassdefs.print("int numprefetchsites = " + pa.prefetchsiteid + ";\n");
993 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
994 cdarray=new ClassDescriptor[state.numClasses()];
996 while(it.hasNext()) {
997 ClassDescriptor cd=(ClassDescriptor)it.next();
998 cdarray[cd.getId()]=cd;
1001 arraytable=new TypeDescriptor[state.numArrays()];
1003 Iterator arrayit=state.getArrayIterator();
1004 while(arrayit.hasNext()) {
1005 TypeDescriptor td=(TypeDescriptor)arrayit.next();
1006 int id=state.getArrayNumber(td);
1012 /* Print out types */
1013 outclassdefs.println("/* ");
1014 for(int i=0; i<state.numClasses(); i++) {
1015 ClassDescriptor cd=cdarray[i];
1017 outclassdefs.println("NULL " + i);
1019 outclassdefs.println(cd +" "+i);
1023 for(int i=0; i<state.numArrays(); i++) {
1024 TypeDescriptor arraytd=arraytable[i];
1025 outclassdefs.println(arraytd.toPrettyString() +" "+(i+state.numClasses()));
1028 outclassdefs.println("*/");
1031 outclassdefs.print("int classsize[]={");
1033 boolean needcomma=false;
1034 for(int i=0; i<state.numClasses(); i++) {
1036 outclassdefs.print(", ");
1038 outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")");
1040 outclassdefs.print("0");
1046 for(int i=0; i<state.numArrays(); i++) {
1048 outclassdefs.print(", ");
1049 TypeDescriptor tdelement=arraytable[i].dereference();
1050 if (tdelement.isArray()||tdelement.isClass())
1051 outclassdefs.print("sizeof(void *)");
1053 outclassdefs.print("sizeof("+tdelement.getSafeSymbol()+")");
1057 outclassdefs.println("};");
1059 ClassDescriptor objectclass=typeutil.getClass(TypeUtil.ObjectClass);
1061 outclassdefs.print("int typearray[]={");
1062 for(int i=0; i<state.numClasses(); i++) {
1063 ClassDescriptor cd=cdarray[i];
1064 ClassDescriptor supercd=i>0?cd.getSuperDesc():null;
1066 outclassdefs.print(", ");
1068 outclassdefs.print("-1");
1070 outclassdefs.print(supercd.getId());
1074 for(int i=0; i<state.numArrays(); i++) {
1075 TypeDescriptor arraytd=arraytable[i];
1076 ClassDescriptor arraycd=arraytd.getClassDesc();
1077 if (arraycd==null) {
1079 outclassdefs.print(", ");
1080 outclassdefs.print(objectclass.getId());
1084 ClassDescriptor cd=arraycd.getSuperDesc();
1087 TypeDescriptor supertd=new TypeDescriptor(cd);
1088 supertd.setArrayCount(arraytd.getArrayCount());
1089 type=state.getArrayNumber(supertd);
1091 type+=state.numClasses();
1094 cd=cd.getSuperDesc();
1097 outclassdefs.print(", ");
1098 outclassdefs.print(type);
1102 outclassdefs.println("};");
1107 outclassdefs.print("int typearray2[]={");
1108 for(int i=0; i<state.numArrays(); i++) {
1109 TypeDescriptor arraytd=arraytable[i];
1110 ClassDescriptor arraycd=arraytd.getClassDesc();
1111 if (arraycd==null) {
1113 outclassdefs.print(", ");
1114 outclassdefs.print("-1");
1118 ClassDescriptor cd=arraycd.getSuperDesc();
1119 int level=arraytd.getArrayCount()-1;
1121 for(; level>0; level--) {
1122 TypeDescriptor supertd=new TypeDescriptor(objectclass);
1123 supertd.setArrayCount(level);
1124 type=state.getArrayNumber(supertd);
1126 type+=state.numClasses();
1131 outclassdefs.print(", ");
1132 outclassdefs.print(type);
1136 outclassdefs.println("};");
1139 /** Constructs params and temp objects for each method or task.
1140 * These objects tell the compiler which temps need to be
1143 protected void generateTempStructs(FlatMethod fm, LocalityBinding lb) {
1144 MethodDescriptor md=fm.getMethod();
1145 TaskDescriptor task=fm.getTask();
1146 Set<TempDescriptor> saveset=lb!=null ? locality.getTempSet(lb) : null;
1147 ParamsObject objectparams=md!=null ? new ParamsObject(md,tag++) : new ParamsObject(task, tag++);
1149 paramstable.put(lb, objectparams);
1150 backuptable.put(lb, new Hashtable<TempDescriptor, TempDescriptor>());
1151 } else if (md!=null)
1152 paramstable.put(md, objectparams);
1154 paramstable.put(task, objectparams);
1156 for(int i=0; i<fm.numParameters(); i++) {
1157 TempDescriptor temp=fm.getParameter(i);
1158 TypeDescriptor type=temp.getType();
1159 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1160 objectparams.addPtr(temp);
1162 objectparams.addPrim(temp);
1163 if(lb!=null&&saveset.contains(temp)) {
1164 backuptable.get(lb).put(temp, temp.createNew());
1168 for(int i=0; i<fm.numTags(); i++) {
1169 TempDescriptor temp=fm.getTag(i);
1170 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1171 objectparams.addPtr(temp);
1173 objectparams.addPrim(temp);
1176 TempObject objecttemps=md!=null ? new TempObject(objectparams,md,tag++) : new TempObject(objectparams, task, tag++);
1178 tempstable.put(lb, objecttemps);
1180 tempstable.put(md, objecttemps);
1182 tempstable.put(task, objecttemps);
1184 for(Iterator nodeit=fm.getNodeSet().iterator(); nodeit.hasNext();) {
1185 FlatNode fn=(FlatNode)nodeit.next();
1186 TempDescriptor[] writes=fn.writesTemps();
1187 for(int i=0; i<writes.length; i++) {
1188 TempDescriptor temp=writes[i];
1189 TypeDescriptor type=temp.getType();
1190 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1191 objecttemps.addPtr(temp);
1193 objecttemps.addPrim(temp);
1194 if(lb!=null&&saveset.contains(temp)&&
1195 !backuptable.get(lb).containsKey(temp))
1196 backuptable.get(lb).put(temp, temp.createNew());
1200 /* Create backup temps */
1202 for(Iterator<TempDescriptor> tmpit=backuptable.get(lb).values().iterator(); tmpit.hasNext();) {
1203 TempDescriptor tmp=tmpit.next();
1204 TypeDescriptor type=tmp.getType();
1205 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1206 objecttemps.addPtr(tmp);
1208 objecttemps.addPrim(tmp);
1210 /* Create temp to hold revert table */
1211 if (state.DSM&&(lb.getHasAtomic()||lb.isAtomic())) {
1212 TempDescriptor reverttmp=new TempDescriptor("revertlist", typeutil.getClass(TypeUtil.ObjectClass));
1213 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1214 objecttemps.addPtr(reverttmp);
1216 objecttemps.addPrim(reverttmp);
1217 reverttable.put(lb, reverttmp);
1222 /** This method outputs the following information about classes
1224 * (1) For classes, what are the locations of pointers.
1225 * (2) For arrays, does the array contain pointers or primitives.
1226 * (3) For classes, does the class contain flags.
1229 private void generateLayoutStructs(PrintWriter output) {
1230 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1231 while(it.hasNext()) {
1232 ClassDescriptor cn=(ClassDescriptor)it.next();
1233 output.println("unsigned INTPTR "+cn.getSafeSymbol()+"_pointers[]={");
1234 Iterator allit=cn.getFieldTable().getAllDescriptorsIterator();
1236 while(allit.hasNext()) {
1237 FieldDescriptor fd=(FieldDescriptor)allit.next();
1238 TypeDescriptor type=fd.getType();
1239 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1244 output.print(count);
1245 allit=cn.getFieldTable().getAllDescriptorsIterator();
1246 while(allit.hasNext()) {
1247 FieldDescriptor fd=(FieldDescriptor)allit.next();
1248 TypeDescriptor type=fd.getType();
1249 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1252 output.println(",");
1253 output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+fd.getSafeSymbol()+"))");
1256 output.println("};");
1258 output.println("unsigned INTPTR * pointerarray[]={");
1259 boolean needcomma=false;
1260 for(int i=0; i<state.numClasses(); i++) {
1261 ClassDescriptor cn=cdarray[i];
1263 output.println(",");
1266 output.print(cn.getSafeSymbol()+"_pointers");
1268 output.print("NULL");
1272 for(int i=0; i<state.numArrays(); i++) {
1274 output.println(", ");
1275 TypeDescriptor tdelement=arraytable[i].dereference();
1276 if (tdelement.isArray()||tdelement.isClass())
1277 output.print("((unsigned INTPTR *)1)");
1283 output.println("};");
1285 output.println("int hasflags[]={");
1286 for(int i=0; i<state.numClasses(); i++) {
1287 ClassDescriptor cn=cdarray[i];
1289 output.println(", ");
1291 if ((cn != null) && (cn.hasFlags()))
1296 output.println("};");
1299 /** Print out table to give us supertypes */
1300 private void generateSuperTypeTable(PrintWriter output) {
1301 output.println("int supertypes[]={");
1302 boolean needcomma=false;
1303 for(int i=0; i<state.numClasses(); i++) {
1304 ClassDescriptor cn=cdarray[i];
1306 output.println(",");
1308 if ((cn != null) && (cn.getSuperDesc()!=null)) {
1309 ClassDescriptor cdsuper=cn.getSuperDesc();
1310 output.print(cdsuper.getId());
1314 output.println("};");
1317 /** Force consistent field ordering between inherited classes. */
1319 private void printClassStruct(ClassDescriptor cn, PrintWriter classdefout) {
1321 ClassDescriptor sp=cn.getSuperDesc();
1323 printClassStruct(sp, classdefout);
1325 if (!fieldorder.containsKey(cn)) {
1326 Vector fields=new Vector();
1327 fieldorder.put(cn,fields);
1328 Vector fieldvec=cn.getFieldVec();
1329 for(int i=0;i<fieldvec.size();i++) {
1330 FieldDescriptor fd=(FieldDescriptor)fieldvec.get(i);
1331 if ((sp==null||!sp.getFieldTable().contains(fd.getSymbol())))
1335 Vector fields=(Vector)fieldorder.get(cn);
1337 for(int i=0; i<fields.size(); i++) {
1338 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
1339 if (fd.getType().isClass()||fd.getType().isArray())
1340 classdefout.println(" struct "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1342 classdefout.println(" "+fd.getType().getSafeSymbol()+" "+fd.getSafeSymbol()+";");
1347 /* Map flags to integers consistently between inherited
1350 protected void mapFlags(ClassDescriptor cn) {
1351 ClassDescriptor sp=cn.getSuperDesc();
1355 if (!flagorder.containsKey(cn)) {
1356 Hashtable flags=new Hashtable();
1357 flagorder.put(cn,flags);
1359 Hashtable superflags=(Hashtable)flagorder.get(sp);
1360 Iterator superflagit=superflags.keySet().iterator();
1361 while(superflagit.hasNext()) {
1362 FlagDescriptor fd=(FlagDescriptor)superflagit.next();
1363 Integer number=(Integer)superflags.get(fd);
1364 flags.put(fd, number);
1365 if ((number.intValue()+1)>max)
1366 max=number.intValue()+1;
1370 Iterator flagit=cn.getFlags();
1371 while(flagit.hasNext()) {
1372 FlagDescriptor fd=(FlagDescriptor)flagit.next();
1373 if (sp==null||!sp.getFlagTable().contains(fd.getSymbol()))
1374 flags.put(fd, new Integer(max++));
1380 /** This function outputs (1) structures that parameters are
1381 * passed in (when PRECISE GC is enabled) and (2) function
1382 * prototypes for the methods */
1384 protected void generateCallStructs(ClassDescriptor cn, PrintWriter classdefout, PrintWriter output, PrintWriter headersout) {
1385 /* Output class structure */
1386 classdefout.println("struct "+cn.getSafeSymbol()+" {");
1387 classdefout.println(" int type;");
1388 if (state.EVENTMONITOR) {
1389 classdefout.println(" int objuid;");
1392 classdefout.println(" pthread_t tid;");
1393 classdefout.println(" void * lockentry;");
1394 classdefout.println(" int lockcount;");
1398 classdefout.println(" int flag;");
1399 if((!state.MULTICORE) || (cn.getSymbol().equals("TagDescriptor"))) {
1400 classdefout.println(" void * flagptr;");
1401 } else if (state.MULTICORE) {
1402 classdefout.println(" int version;");
1403 classdefout.println(" int * lock;"); // lock entry for this obj
1404 classdefout.println(" int mutex;");
1405 classdefout.println(" int lockcount;");
1406 if(state.MULTICOREGC) {
1407 classdefout.println(" int marked;");
1410 if (state.OPTIONAL) {
1411 classdefout.println(" int numfses;");
1412 classdefout.println(" int * fses;");
1415 printClassStruct(cn, classdefout);
1416 classdefout.println("};\n");
1418 if (state.DSM||state.SINGLETM) {
1419 /* Cycle through LocalityBindings */
1420 HashSet<MethodDescriptor> nativemethods=new HashSet<MethodDescriptor>();
1421 Set<LocalityBinding> lbset=locality.getClassBindings(cn);
1423 for(Iterator<LocalityBinding> lbit=lbset.iterator(); lbit.hasNext();) {
1424 LocalityBinding lb=lbit.next();
1425 MethodDescriptor md=lb.getMethod();
1426 if (md.getModifiers().isNative()) {
1427 //make sure we only print a native method once
1428 if (nativemethods.contains(md)) {
1429 FlatMethod fm=state.getMethodFlat(md);
1430 generateTempStructs(fm, lb);
1433 nativemethods.add(md);
1435 generateMethod(cn, md, lb, headersout, output);
1438 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1439 MethodDescriptor md=(MethodDescriptor)methodit.next();
1440 if (md.getModifiers().isNative()&&!nativemethods.contains(md)) {
1441 //Need to build param structure for library code
1442 FlatMethod fm=state.getMethodFlat(md);
1443 generateTempStructs(fm, null);
1444 generateMethodParam(cn, md, null, output);
1449 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1450 MethodDescriptor md=(MethodDescriptor)methodit.next();
1451 generateMethod(cn, md, null, headersout, output);
1455 private void generateMethodParam(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter output) {
1456 /* Output parameter structure */
1457 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1458 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1459 if ((state.DSM||state.SINGLETM)&&lb!=null)
1460 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1462 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1463 output.println(" INTPTR size;");
1464 output.println(" void * next;");
1465 for(int i=0; i<objectparams.numPointers(); i++) {
1466 TempDescriptor temp=objectparams.getPointer(i);
1467 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1469 output.println("};\n");
1473 private void generateMethod(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter headersout, PrintWriter output) {
1474 FlatMethod fm=state.getMethodFlat(md);
1475 generateTempStructs(fm, lb);
1477 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1478 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md);
1480 generateMethodParam(cn, md, lb, output);
1482 /* Output temp structure */
1483 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1484 if (state.DSM||state.SINGLETM)
1485 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1487 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1488 output.println(" INTPTR size;");
1489 output.println(" void * next;");
1490 for(int i=0; i<objecttemps.numPointers(); i++) {
1491 TempDescriptor temp=objecttemps.getPointer(i);
1492 if (temp.getType().isNull())
1493 output.println(" void * "+temp.getSafeSymbol()+";");
1495 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1497 output.println("};\n");
1500 /********* Output method declaration ***********/
1501 if (state.DSM||state.SINGLETM) {
1502 headersout.println("#define D"+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1504 headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1506 /* First the return type */
1507 if (md.getReturnType()!=null) {
1508 if (md.getReturnType().isClass()||md.getReturnType().isArray())
1509 headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1511 headersout.print(md.getReturnType().getSafeSymbol()+" ");
1513 //catch the constructor case
1514 headersout.print("void ");
1516 /* Next the method name */
1517 if (state.DSM||state.SINGLETM) {
1518 headersout.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1520 headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1522 boolean printcomma=false;
1523 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1524 if (state.DSM||state.SINGLETM) {
1525 headersout.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1527 headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1531 /* Output parameter list*/
1532 for(int i=0; i<objectparams.numPrimitives(); i++) {
1533 TempDescriptor temp=objectparams.getPrimitive(i);
1535 headersout.print(", ");
1537 if (temp.getType().isClass()||temp.getType().isArray())
1538 headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1540 headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1542 headersout.println(");\n");
1546 /** This function outputs (1) structures that parameters are
1547 * passed in (when PRECISE GC is enabled) and (2) function
1548 * prototypes for the tasks */
1550 private void generateTaskStructs(PrintWriter output, PrintWriter headersout) {
1551 /* Cycle through tasks */
1552 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
1554 while(taskit.hasNext()) {
1555 /* Classify parameters */
1556 TaskDescriptor task=(TaskDescriptor)taskit.next();
1557 FlatMethod fm=state.getMethodFlat(task);
1558 generateTempStructs(fm, null);
1560 ParamsObject objectparams=(ParamsObject) paramstable.get(task);
1561 TempObject objecttemps=(TempObject) tempstable.get(task);
1563 /* Output parameter structure */
1564 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1565 output.println("struct "+task.getSafeSymbol()+"_params {");
1567 output.println(" INTPTR size;");
1568 output.println(" void * next;");
1569 for(int i=0; i<objectparams.numPointers(); i++) {
1570 TempDescriptor temp=objectparams.getPointer(i);
1571 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1574 output.println("};\n");
1575 if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
1576 maxtaskparams=objectparams.numPointers()+fm.numTags();
1580 /* Output temp structure */
1581 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1582 output.println("struct "+task.getSafeSymbol()+"_locals {");
1583 output.println(" INTPTR size;");
1584 output.println(" void * next;");
1585 for(int i=0; i<objecttemps.numPointers(); i++) {
1586 TempDescriptor temp=objecttemps.getPointer(i);
1587 if (temp.getType().isNull())
1588 output.println(" void * "+temp.getSafeSymbol()+";");
1589 else if(temp.getType().isTag())
1590 output.println(" struct "+
1591 (new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1593 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1595 output.println("};\n");
1598 /* Output task declaration */
1599 headersout.print("void " + task.getSafeSymbol()+"(");
1601 boolean printcomma=false;
1602 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1603 headersout.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
1605 headersout.print("void * parameterarray[]");
1606 headersout.println(");\n");
1610 /***** Generate code for FlatMethod fm. *****/
1612 Hashtable<FlatAtomicEnterNode, AtomicRecord> atomicmethodmap;
1613 static int atomicmethodcount=0;
1616 BranchAnalysis branchanalysis;
1617 private void generateFlatMethod(FlatMethod fm, LocalityBinding lb, PrintWriter output) {
1618 if (State.PRINTFLAT)
1619 System.out.println(fm.printMethod());
1620 MethodDescriptor md=fm.getMethod();
1621 TaskDescriptor task=fm.getTask();
1622 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
1623 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : md!=null ? md : task);
1625 HashSet<AtomicRecord> arset=null;
1626 branchanalysis=null;
1628 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1630 if (atomicmethodmap==null)
1631 atomicmethodmap=new Hashtable<FlatAtomicEnterNode, AtomicRecord>();
1633 //fix these so we get right strings for local variables
1634 localsprefixaddr=localsprefix;
1635 localsprefixderef=localsprefix+"->";
1636 arset=new HashSet<AtomicRecord>();
1638 //build branchanalysis
1639 branchanalysis=new BranchAnalysis(locality, lb, delaycomp.getNotReady(lb), delaycomp.livecode(lb), state);
1641 //Generate commit methods here
1642 for(Iterator<FlatNode> fnit=fm.getNodeSet().iterator();fnit.hasNext();) {
1643 FlatNode fn=fnit.next();
1644 if (fn.kind()==FKind.FlatAtomicEnterNode&&
1645 locality.getAtomic(lb).get(fn.getPrev(0)).intValue()==0&&
1646 delaycomp.needsFission(lb, (FlatAtomicEnterNode) fn)) {
1647 //We have an atomic enter
1648 FlatAtomicEnterNode faen=(FlatAtomicEnterNode) fn;
1649 Set<FlatNode> exitset=faen.getExits();
1651 String methodname=md.getSymbol()+(atomicmethodcount++);
1652 AtomicRecord ar=new AtomicRecord();
1656 atomicmethodmap.put(faen, ar);
1658 //build data structure declaration
1659 output.println("struct atomicprimitives_"+methodname+" {");
1661 Set<FlatNode> recordset=delaycomp.livecode(lb);
1662 Set<TempDescriptor> liveinto=delaycomp.liveinto(lb, faen, recordset);
1663 Set<TempDescriptor> liveout=delaycomp.liveout(lb, faen);
1664 Set<TempDescriptor> liveoutvirtualread=delaycomp.liveoutvirtualread(lb, faen);
1666 ar.reallivein=new HashSet(liveinto);
1668 ar.liveoutvirtualread=liveoutvirtualread;
1671 for(Iterator<TempDescriptor> it=liveinto.iterator(); it.hasNext();) {
1672 TempDescriptor tmp=it.next();
1673 //remove the pointers
1674 if (tmp.getType().isPtr()) {
1677 //let's print it here
1678 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1681 for(Iterator<TempDescriptor> it=liveout.iterator(); it.hasNext();) {
1682 TempDescriptor tmp=it.next();
1683 //remove the pointers
1684 if (tmp.getType().isPtr()) {
1686 } else if (!liveinto.contains(tmp)) {
1687 //let's print it here
1688 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1691 output.println("};");
1693 //print out method name
1694 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) {");
1695 //build code for commit method
1697 //first define local primitives
1698 Set<TempDescriptor> alltemps=delaycomp.alltemps(lb, faen, recordset);
1699 for(Iterator<TempDescriptor> tmpit=alltemps.iterator();tmpit.hasNext();) {
1700 TempDescriptor tmp=tmpit.next();
1701 if (!tmp.getType().isPtr()) {
1702 if (liveinto.contains(tmp)||liveoutvirtualread.contains(tmp)) {
1703 //read from live into set
1704 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+"=primitives->"+tmp.getSafeSymbol()+";");
1707 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1711 //turn off write barrier generation
1713 state.SINGLETM=false;
1714 generateCode(faen, fm, lb, exitset, output, false);
1715 state.SINGLETM=true;
1716 //turn on write barrier generation
1718 output.println("}\n\n");
1722 //redefine these back to normal
1724 localsprefixaddr="&"+localsprefix;
1725 localsprefixderef=localsprefix+".";
1727 generateHeader(fm, lb, md!=null ? md : task,output);
1728 TempObject objecttemp=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
1730 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1731 for(Iterator<AtomicRecord> arit=arset.iterator();arit.hasNext();) {
1732 AtomicRecord ar=arit.next();
1733 output.println("struct atomicprimitives_"+ar.name+" primitives_"+ar.name+";");
1737 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1738 if (md!=null&&(state.DSM||state.SINGLETM))
1739 output.print(" struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1740 else if (md!=null&&!(state.DSM||state.SINGLETM))
1741 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1743 output.print(" struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={");
1745 output.print(objecttemp.numPointers()+",");
1746 output.print(paramsprefix);
1747 for(int j=0; j<objecttemp.numPointers(); j++)
1748 output.print(", NULL");
1749 output.println("};");
1752 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1753 TempDescriptor td=objecttemp.getPrimitive(i);
1754 TypeDescriptor type=td.getType();
1756 output.println(" void * "+td.getSafeSymbol()+";");
1757 else if (type.isClass()||type.isArray())
1758 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1760 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1765 if( fm.getNext(0) instanceof FlatSESEEnterNode ) {
1766 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
1767 if( callerSESEplaceholder != mlpa.getMainSESE() ) {
1768 // declare variables for naming static SESE's
1769 output.println(" /* static SESE names */");
1770 Iterator<SESEandAgePair> pItr = callerSESEplaceholder.getNeededStaticNames().iterator();
1771 while( pItr.hasNext() ) {
1772 SESEandAgePair p = pItr.next();
1773 output.println(" void* "+p+";");
1776 // declare variables for tracking dynamic sources
1777 output.println(" /* dynamic variable sources */");
1778 Iterator<TempDescriptor> dynSrcItr = callerSESEplaceholder.getDynamicVarSet().iterator();
1779 while( dynSrcItr.hasNext() ) {
1780 TempDescriptor dynSrcVar = dynSrcItr.next();
1781 output.println(" void* "+dynSrcVar+"_srcSESE;");
1782 output.println(" int "+dynSrcVar+"_srcOffset;");
1787 // set up related allocation sites's waiting queues
1789 output.println(" /* set up waiting queues */");
1790 output.println(" int numRelatedWaitingQueue=0;");
1791 output.println(" int waitingQueueItemID=0;");
1792 ConflictGraph graph=null;
1793 graph=mlpa.getConflictGraphResults().get(fm);
1795 HashSet<SESELock> lockSet=mlpa.getConflictGraphLockMap().get(graph);
1797 if(lockSet.size()>0){
1798 output.println(" numRelatedWaitingQueue="+lockSet.size()+";");
1799 output.println(" seseCaller->numRelatedWaitingQueue=numRelatedWaitingQueue;");
1800 output.println(" seseCaller->allocSiteArray=mlpCreateAllocSiteArray(numRelatedWaitingQueue);");
1802 for (Iterator iterator = lockSet.iterator(); iterator.hasNext();) {
1803 SESELock seseLock = (SESELock) iterator.next();
1804 output.println(" seseCaller->allocSiteArray["+idx+"].id="+seseLock.getID()+";");
1814 /* Check to see if we need to do a GC if this is a
1815 * multi-threaded program...*/
1817 if (((state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
1818 || this.state.MULTICOREGC) {
1819 //Don't bother if we aren't in recursive methods...The loops case will catch it
1820 if (callgraph.getAllMethods(md).contains(md)) {
1821 if (state.DSM&&lb.isAtomic())
1822 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
1823 else if (this.state.MULTICOREGC) {
1824 output.println("if(gcflag) gc("+localsprefixaddr+");");
1826 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
1831 generateCode(fm.getNext(0), fm, lb, null, output, true);
1833 output.println("}\n\n");
1837 protected void initializeSESE( FlatSESEEnterNode fsen ) {
1839 FlatMethod fm = fsen.getfmEnclosing();
1840 MethodDescriptor md = fm.getMethod();
1841 ClassDescriptor cn = md.getClassDesc();
1844 // Creates bogus method descriptor to index into tables
1845 Modifiers modBogus = new Modifiers();
1846 MethodDescriptor mdBogus =
1847 new MethodDescriptor( modBogus,
1848 new TypeDescriptor( TypeDescriptor.VOID ),
1849 "sese_"+fsen.getPrettyIdentifier()+fsen.getIdentifier()
1852 mdBogus.setClassDesc( fsen.getcdEnclosing() );
1853 FlatMethod fmBogus = new FlatMethod( mdBogus, null );
1854 fsen.setfmBogus( fmBogus );
1855 fsen.setmdBogus( mdBogus );
1857 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1858 inSetAndOutSet.addAll( fsen.getInVarSet() );
1859 inSetAndOutSet.addAll( fsen.getOutVarSet() );
1861 // Build paramsobj for bogus method descriptor
1862 ParamsObject objectparams = new ParamsObject( mdBogus, tag++ );
1863 paramstable.put( mdBogus, objectparams );
1865 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1866 while( itr.hasNext() ) {
1867 TempDescriptor temp = itr.next();
1868 TypeDescriptor type = temp.getType();
1869 if( type.isPtr() ) {
1870 objectparams.addPtr( temp );
1872 objectparams.addPrim( temp );
1876 // Build normal temp object for bogus method descriptor
1877 TempObject objecttemps = new TempObject( objectparams, mdBogus, tag++ );
1878 tempstable.put( mdBogus, objecttemps );
1880 for( Iterator nodeit = fsen.getNodeSet().iterator(); nodeit.hasNext(); ) {
1881 FlatNode fn = (FlatNode)nodeit.next();
1882 TempDescriptor[] writes = fn.writesTemps();
1884 for( int i = 0; i < writes.length; i++ ) {
1885 TempDescriptor temp = writes[i];
1886 TypeDescriptor type = temp.getType();
1888 if( type.isPtr() ) {
1889 objecttemps.addPtr( temp );
1891 objecttemps.addPrim( temp );
1897 protected void generateMethodSESE(FlatSESEEnterNode fsen,
1899 PrintWriter outputStructs,
1900 PrintWriter outputMethHead,
1901 PrintWriter outputMethods
1904 ParamsObject objectparams = (ParamsObject) paramstable.get( fsen.getmdBogus() );
1905 TempObject objecttemps = (TempObject) tempstable .get( fsen.getmdBogus() );
1907 // generate locals structure
1908 outputStructs.println("struct "+
1909 fsen.getcdEnclosing().getSafeSymbol()+
1910 fsen.getmdBogus().getSafeSymbol()+"_"+
1911 fsen.getmdBogus().getSafeMethodDescriptor()+
1913 outputStructs.println(" INTPTR size;");
1914 outputStructs.println(" void * next;");
1915 for(int i=0; i<objecttemps.numPointers(); i++) {
1916 TempDescriptor temp=objecttemps.getPointer(i);
1918 if( fsen.getPrettyIdentifier().equals( "calc" ) ) {
1919 System.out.println( " got a pointer "+temp );
1922 if (temp.getType().isNull())
1923 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
1925 outputStructs.println(" struct "+
1926 temp.getType().getSafeSymbol()+" * "+
1927 temp.getSafeSymbol()+";");
1929 outputStructs.println("};\n");
1932 // generate the SESE record structure
1933 outputStructs.println(fsen.getSESErecordName()+" {");
1935 // data common to any SESE, and it must be placed first so
1936 // a module that doesn't know what kind of SESE record this
1937 // is can cast the pointer to a common struct
1938 outputStructs.println(" SESEcommon common;");
1940 // then garbage list stuff
1941 outputStructs.println(" INTPTR size;");
1942 outputStructs.println(" void * next;");
1944 // in-set source tracking
1945 // in-vars that are READY come from parent, don't need anything
1946 // stuff STATIC needs a custom SESE pointer for each age pair
1947 Iterator<SESEandAgePair> itrStaticInVarSrcs = fsen.getStaticInVarSrcs().iterator();
1948 while( itrStaticInVarSrcs.hasNext() ) {
1949 SESEandAgePair srcPair = itrStaticInVarSrcs.next();
1950 outputStructs.println(" "+srcPair.getSESE().getSESErecordName()+"* "+srcPair+";");
1953 // DYNAMIC stuff needs a source SESE ptr and offset
1954 Iterator<TempDescriptor> itrDynInVars = fsen.getDynamicInVarSet().iterator();
1955 while( itrDynInVars.hasNext() ) {
1956 TempDescriptor dynInVar = itrDynInVars.next();
1957 outputStructs.println(" void* "+dynInVar+"_srcSESE;");
1958 outputStructs.println(" int "+dynInVar+"_srcOffset;");
1961 // space for all in and out set primitives
1962 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1963 inSetAndOutSet.addAll( fsen.getInVarSet() );
1964 inSetAndOutSet.addAll( fsen.getOutVarSet() );
1966 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
1968 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1969 while( itr.hasNext() ) {
1970 TempDescriptor temp = itr.next();
1971 TypeDescriptor type = temp.getType();
1972 if( !type.isPtr() ) {
1973 inSetAndOutSetPrims.add( temp );
1977 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
1978 while( itrPrims.hasNext() ) {
1979 TempDescriptor temp = itrPrims.next();
1980 TypeDescriptor type = temp.getType();
1981 outputStructs.println(" "+temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol()+";");
1984 for(int i=0; i<objectparams.numPointers(); i++) {
1985 TempDescriptor temp=objectparams.getPointer(i);
1986 if (temp.getType().isNull())
1987 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
1989 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1992 outputStructs.println("};\n");
1995 // write method declaration to header file
1996 outputMethHead.print("void ");
1997 outputMethHead.print(fsen.getSESEmethodName()+"(");
1998 outputMethHead.print(fsen.getSESErecordName()+"* "+paramsprefix);
1999 outputMethHead.println(");\n");
2002 generateFlatMethodSESE( fsen.getfmBogus(),
2003 fsen.getcdEnclosing(),
2009 private void generateFlatMethodSESE(FlatMethod fm,
2011 FlatSESEEnterNode fsen,
2012 FlatSESEExitNode seseExit,
2016 MethodDescriptor md=fm.getMethod();
2018 output.print("void ");
2019 output.print(fsen.getSESEmethodName()+"(");
2020 output.print(fsen.getSESErecordName()+"* "+paramsprefix);
2021 output.println("){\n");
2023 TempObject objecttemp=(TempObject) tempstable.get(md);
2025 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2026 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
2027 output.print(objecttemp.numPointers()+",");
2028 output.print("(void*) &("+paramsprefix+"->size)");
2029 for(int j=0; j<objecttemp.numPointers(); j++)
2030 output.print(", NULL");
2031 output.println("};");
2034 output.println(" /* regular local primitives */");
2035 for(int i=0; i<objecttemp.numPrimitives(); i++) {
2036 TempDescriptor td=objecttemp.getPrimitive(i);
2037 TypeDescriptor type=td.getType();
2039 output.println(" void * "+td.getSafeSymbol()+";");
2040 else if (type.isClass()||type.isArray())
2041 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
2043 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
2047 // declare variables for naming static SESE's
2048 output.println(" /* static SESE names */");
2049 Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
2050 while( pItr.hasNext() ) {
2051 SESEandAgePair p = pItr.next();
2052 output.println(" void* "+p+";");
2055 // declare variables for tracking dynamic sources
2056 output.println(" /* dynamic variable sources */");
2057 Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
2058 while( dynSrcItr.hasNext() ) {
2059 TempDescriptor dynSrcVar = dynSrcItr.next();
2060 output.println(" void* "+dynSrcVar+"_srcSESE;");
2061 output.println(" int "+dynSrcVar+"_srcOffset;");
2064 // declare local temps for in-set primitives, and if it is
2065 // a ready-source variable, get the value from the record
2066 output.println(" /* local temps for in-set primitives */");
2067 Iterator<TempDescriptor> itrInSet = fsen.getInVarSet().iterator();
2068 while( itrInSet.hasNext() ) {
2069 TempDescriptor temp = itrInSet.next();
2070 TypeDescriptor type = temp.getType();
2071 if( !type.isPtr() ) {
2072 if( fsen.getReadyInVarSet().contains( temp ) ) {
2073 output.println(" "+type+" "+temp+" = "+paramsprefix+"->"+temp+";");
2075 output.println(" "+type+" "+temp+";");
2080 // declare local temps for out-set primitives if its not already
2081 // in the in-set, and it's value will get written so no problem
2082 output.println(" /* local temp for out-set prim, not already in the in-set */");
2083 Iterator<TempDescriptor> itrOutSet = fsen.getOutVarSet().iterator();
2084 while( itrOutSet.hasNext() ) {
2085 TempDescriptor temp = itrOutSet.next();
2086 TypeDescriptor type = temp.getType();
2087 if( !type.isPtr() && !fsen.getInVarSet().contains( temp ) ) {
2088 output.println(" "+type+" "+temp+";");
2092 // set up related allocation sites's waiting queues
2094 output.println(" /* set up waiting queues */");
2095 output.println(" int numRelatedWaitingQueue=0;");
2096 output.println(" int waitingQueueItemID=0;");
2097 ConflictGraph graph=null;
2098 graph=mlpa.getConflictGraphResults().get(fsen);
2099 if (graph != null) {
2100 output.println(" {");
2101 output.println(" SESEcommon* parentCommon = &(___params___->common);");
2102 HashSet<SESELock> lockSet=mlpa.getConflictGraphLockMap().get(graph);
2104 if (lockSet.size() > 0) {
2105 output.println(" numRelatedWaitingQueue=" + lockSet.size()
2108 .println(" parentCommon->numRelatedWaitingQueue=numRelatedWaitingQueue;");
2110 .println(" parentCommon->allocSiteArray=mlpCreateAllocSiteArray(numRelatedWaitingQueue);");
2112 for (Iterator iterator = lockSet.iterator(); iterator.hasNext();) {
2113 SESELock seseLock = (SESELock) iterator.next();
2114 output.println(" parentCommon->allocSiteArray[" + idx
2115 + "].id=" + seseLock.getID() + ";");
2120 output.println(" }");
2123 // copy in-set into place, ready vars were already
2124 // copied when the SESE was issued
2125 Iterator<TempDescriptor> tempItr;
2127 // static vars are from a known SESE
2128 tempItr = fsen.getStaticInVarSet().iterator();
2129 while( tempItr.hasNext() ) {
2130 TempDescriptor temp = tempItr.next();
2131 VariableSourceToken vst = fsen.getStaticInVarSrc( temp );
2132 SESEandAgePair srcPair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2134 // can't grab something from this source until it is done
2135 output.println(" {");
2136 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+srcPair+";" );
2137 output.println(" pthread_mutex_lock( &(com->lock) );");
2138 output.println(" while( com->doneExecuting == FALSE ) {");
2139 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
2140 output.println(" }");
2141 output.println(" pthread_mutex_unlock( &(com->lock) );");
2143 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2144 " = "+paramsprefix+"->"+srcPair+"->"+vst.getAddrVar()+";");
2146 output.println(" }");
2149 // dynamic vars come from an SESE and src
2150 tempItr = fsen.getDynamicInVarSet().iterator();
2151 while( tempItr.hasNext() ) {
2152 TempDescriptor temp = tempItr.next();
2153 TypeDescriptor type = temp.getType();
2155 // go grab it from the SESE source
2156 output.println(" if( "+paramsprefix+"->"+temp+"_srcSESE != NULL ) {");
2158 // gotta wait until the source is done
2159 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+temp+"_srcSESE;" );
2160 output.println(" pthread_mutex_lock( &(com->lock) );");
2161 output.println(" while( com->doneExecuting == FALSE ) {");
2162 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
2163 output.println(" }");
2164 output.println(" pthread_mutex_unlock( &(com->lock) );");
2167 if( type.isNull() ) {
2169 } else if( type.isClass() || type.isArray() ) {
2170 typeStr = "struct "+type.getSafeSymbol()+"*";
2172 typeStr = type.getSafeSymbol();
2175 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2176 " = *(("+typeStr+"*) ("+
2177 paramsprefix+"->"+temp+"_srcSESE + "+
2178 paramsprefix+"->"+temp+"_srcOffset));");
2180 // or if the source was our parent, its in the record to grab
2181 output.println(" } else {");
2182 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2183 " = "+paramsprefix+"->"+temp+";");
2184 output.println(" }");
2187 // Check to see if we need to do a GC if this is a
2188 // multi-threaded program...
2189 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2190 //Don't bother if we aren't in recursive methods...The loops case will catch it
2191 if (callgraph.getAllMethods(md).contains(md)) {
2192 if(this.state.MULTICOREGC) {
2193 output.println("if(gcflag) gc("+localsprefixaddr+");");
2195 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2200 // initialize thread-local var to a non-zero, invalid address
2201 output.println(" seseCaller = (SESEcommon*) 0x2;");
2202 HashSet<FlatNode> exitset=new HashSet<FlatNode>();
2203 exitset.add(seseExit);
2204 generateCode(fsen.getNext(0), fm, null, exitset, output, true);
2205 output.println("}\n\n");
2210 // when a new mlp thread is created for an issued SESE, it is started
2211 // by running this method which blocks on a cond variable until
2212 // it is allowed to transition to execute. Then a case statement
2213 // allows it to invoke the method with the proper SESE body, and after
2214 // exiting the SESE method, executes proper SESE exit code before the
2215 // thread can be destroyed
2216 private void generateSESEinvocationMethod(PrintWriter outmethodheader,
2217 PrintWriter outmethod
2220 outmethodheader.println("void* invokeSESEmethod( void* seseRecord );");
2221 outmethod.println( "void* invokeSESEmethod( void* seseRecord ) {");
2222 outmethod.println( " int status;");
2223 outmethod.println( " char errmsg[128];");
2225 // generate a case for each SESE class that can be invoked
2226 outmethod.println( " switch( *((int*)seseRecord) ) {");
2227 outmethod.println( " ");
2228 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
2229 FlatSESEEnterNode fsen = seseit.next();
2231 outmethod.println( " /* "+fsen.getPrettyIdentifier()+" */");
2232 outmethod.println( " case "+fsen.getIdentifier()+":");
2233 outmethod.println( " "+fsen.getSESEmethodName()+"( seseRecord );");
2235 if( fsen.equals( mlpa.getMainSESE() ) ) {
2236 outmethod.println( " /* work scheduler works forever, explicitly exit */");
2237 outmethod.println( " exit( 0 );");
2240 outmethod.println( " break;");
2241 outmethod.println( "");
2244 // default case should never be taken, error out
2245 outmethod.println( " default:");
2246 outmethod.println( " printf(\"Error: unknown SESE class ID in invoke method.\\n\");");
2247 outmethod.println( " exit(-30);");
2248 outmethod.println( " break;");
2249 outmethod.println( " }");
2250 outmethod.println( " return NULL;");
2251 outmethod.println( "}\n\n");
2255 protected void generateCode(FlatNode first,
2258 Set<FlatNode> stopset,
2259 PrintWriter output, boolean firstpass) {
2261 /* Assign labels to FlatNode's if necessary.*/
2263 Hashtable<FlatNode, Integer> nodetolabel;
2265 if (state.DELAYCOMP&&!firstpass)
2266 nodetolabel=dcassignLabels(first, stopset);
2268 nodetolabel=assignLabels(first, stopset);
2270 Set<FlatNode> storeset=null;
2271 HashSet<FlatNode> genset=null;
2272 HashSet<FlatNode> refset=null;
2273 Set<FlatNode> unionset=null;
2275 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
2276 storeset=delaycomp.livecode(lb);
2277 genset=new HashSet<FlatNode>();
2278 if (state.STMARRAY&&!state.DUALVIEW) {
2279 refset=new HashSet<FlatNode>();
2280 refset.addAll(delaycomp.getDeref(lb));
2281 refset.removeAll(delaycomp.getCannotDelay(lb));
2282 refset.removeAll(delaycomp.getOther(lb));
2285 genset.addAll(delaycomp.getCannotDelay(lb));
2286 genset.addAll(delaycomp.getOther(lb));
2288 genset.addAll(delaycomp.getNotReady(lb));
2289 if (state.STMARRAY&&!state.DUALVIEW) {
2290 genset.removeAll(refset);
2293 unionset=new HashSet<FlatNode>();
2294 unionset.addAll(storeset);
2295 unionset.addAll(genset);
2296 if (state.STMARRAY&&!state.DUALVIEW)
2297 unionset.addAll(refset);
2300 /* Do the actual code generation */
2301 FlatNode current_node=null;
2302 HashSet tovisit=new HashSet();
2303 HashSet visited=new HashSet();
2305 tovisit.add(first.getNext(0));
2308 while(current_node!=null||!tovisit.isEmpty()) {
2309 if (current_node==null) {
2310 current_node=(FlatNode)tovisit.iterator().next();
2311 tovisit.remove(current_node);
2312 } else if (tovisit.contains(current_node)) {
2313 tovisit.remove(current_node);
2315 visited.add(current_node);
2316 if (nodetolabel.containsKey(current_node)) {
2317 output.println("L"+nodetolabel.get(current_node)+":");
2319 if (state.INSTRUCTIONFAILURE) {
2320 if (state.THREAD||state.DSM||state.SINGLETM) {
2321 output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
2323 output.println("if ((--instructioncount)==0) injectinstructionfailure();");
2325 if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
2327 if (!state.DELAYCOMP||firstpass) {
2328 generateFlatNode(fm, lb, current_node, output);
2330 //store primitive variables in out set
2331 AtomicRecord ar=atomicmethodmap.get((FlatAtomicEnterNode)first);
2332 Set<TempDescriptor> liveout=ar.liveout;
2333 for(Iterator<TempDescriptor> tmpit=liveout.iterator();tmpit.hasNext();) {
2334 TempDescriptor tmp=tmpit.next();
2335 output.println("primitives->"+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2338 if (state.MLP && stopset!=null) {
2339 assert first.getPrev( 0 ) instanceof FlatSESEEnterNode;
2340 assert current_node instanceof FlatSESEExitNode;
2341 FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev( 0 );
2342 FlatSESEExitNode fsxn = (FlatSESEExitNode) current_node;
2343 assert fsen.getFlatExit().equals( fsxn );
2344 assert fsxn.getFlatEnter().equals( fsen );
2346 if (current_node.kind()!=FKind.FlatReturnNode) {
2347 output.println(" return;");
2350 } else if(current_node.numNext()==1) {
2353 current_node.kind()==FKind.FlatSESEEnterNode &&
2354 !((FlatSESEEnterNode)current_node).getIsCallerSESEplaceholder()
2356 FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
2357 generateFlatNode(fm, lb, current_node, output);
2358 nextnode=fsen.getFlatExit().getNext(0);
2359 } else if (state.DELAYCOMP) {
2360 boolean specialprimitive=false;
2361 //skip literals...no need to add extra overhead
2362 if (storeset!=null&&storeset.contains(current_node)&¤t_node.kind()==FKind.FlatLiteralNode) {
2363 TypeDescriptor typedesc=((FlatLiteralNode)current_node).getType();
2364 if (!typedesc.isClass()&&!typedesc.isArray()) {
2365 specialprimitive=true;
2369 if (genset==null||genset.contains(current_node)||specialprimitive)
2370 generateFlatNode(fm, lb, current_node, output);
2371 if (state.STMARRAY&&!state.DUALVIEW&&refset!=null&&refset.contains(current_node)) {
2372 //need to acquire lock
2373 handleArrayDeref(fm, lb, current_node, output, firstpass);
2375 if (storeset!=null&&storeset.contains(current_node)&&!specialprimitive) {
2376 TempDescriptor wrtmp=current_node.writesTemps()[0];
2378 //need to store value written by previous node
2379 if (wrtmp.getType().isPtr()) {
2380 //only lock the objects that may actually need locking
2381 if (recorddc.getNeedTrans(lb, current_node)&&
2382 (!state.STMARRAY||state.DUALVIEW||!wrtmp.getType().isArray()||
2383 wrtmp.getType().getSymbol().equals(TypeUtil.ObjectClass))) {
2384 output.println("STOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2386 output.println("STOREPTRNOLOCK("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2389 output.println("STORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");/* "+current_node.nodeid+" */");
2392 //need to read value read by previous node
2393 if (wrtmp.getType().isPtr()) {
2394 output.println("RESTOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2396 output.println("RESTORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+"); /* "+current_node.nodeid+" */");
2400 nextnode=current_node.getNext(0);
2403 generateFlatNode(fm, lb, current_node, output);
2404 nextnode=current_node.getNext(0);
2406 if (visited.contains(nextnode)) {
2407 output.println("goto L"+nodetolabel.get(nextnode)+";");
2410 current_node=nextnode;
2411 } else if (current_node.numNext()==2) {
2413 if (state.DELAYCOMP) {
2414 boolean computeside=false;
2416 //need to record which way it should go
2417 if (genset==null||genset.contains(current_node)) {
2418 if (storeset!=null&&storeset.contains(current_node)) {
2419 //need to store which way branch goes
2420 generateStoreFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2422 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2424 //which side to execute
2428 if (genset.contains(current_node)) {
2429 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2430 } else if (storeset.contains(current_node)) {
2432 branchanalysis.generateGroupCode(current_node, output, nodetolabel);
2434 //which side to execute
2439 Set<FlatNode> leftset=DelayComputation.getNext(current_node, 0, unionset, lb,locality, true);
2441 if (leftset.size()==0)
2443 if (visited.contains(current_node.getNext(branch))) {
2444 //already visited -- build jump
2445 output.println("goto L"+nodetolabel.get(current_node.getNext(branch))+";");
2448 current_node=current_node.getNext(branch);
2451 if (!visited.contains(current_node.getNext(1)))
2452 tovisit.add(current_node.getNext(1));
2453 if (visited.contains(current_node.getNext(0))) {
2454 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2457 current_node=current_node.getNext(0);
2461 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2462 if (!visited.contains(current_node.getNext(1)))
2463 tovisit.add(current_node.getNext(1));
2464 if (visited.contains(current_node.getNext(0))) {
2465 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2468 current_node=current_node.getNext(0);
2470 } else throw new Error();
2474 protected void handleArrayDeref(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output, boolean firstpass) {
2475 if (fn.kind()==FKind.FlatSetElementNode) {
2476 FlatSetElementNode fsen=(FlatSetElementNode) fn;
2477 String dst=generateTemp(fm, fsen.getDst(), lb);
2478 String src=generateTemp(fm, fsen.getSrc(), lb);
2479 String index=generateTemp(fm, fsen.getIndex(), lb);
2480 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
2482 if (elementtype.isArray()||elementtype.isClass())
2485 type=elementtype.getSafeSymbol()+" ";
2487 output.println("STOREARRAY("+dst+","+index+","+type+")");
2489 output.println("{");
2490 output.println(" struct ArrayObject *array;");
2491 output.println(" int index;");
2492 output.println(" RESTOREARRAY(array,index);");
2493 output.println(" (("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index]="+src+";");
2494 output.println("}");
2496 } else if (fn.kind()==FKind.FlatElementNode) {
2497 FlatElementNode fen=(FlatElementNode) fn;
2498 String src=generateTemp(fm, fen.getSrc(), lb);
2499 String index=generateTemp(fm, fen.getIndex(), lb);
2500 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
2501 String dst=generateTemp(fm, fen.getDst(), lb);
2503 if (elementtype.isArray()||elementtype.isClass())
2506 type=elementtype.getSafeSymbol()+" ";
2508 output.println("STOREARRAY("+src+","+index+","+type+")");
2510 output.println("{");
2511 output.println(" struct ArrayObject *array;");
2512 output.println(" int index;");
2513 output.println(" RESTOREARRAY(array,index);");
2514 output.println(" "+dst+"=(("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index];");
2515 output.println("}");
2519 /** Special label assignment for delaycomputation */
2520 protected Hashtable<FlatNode, Integer> dcassignLabels(FlatNode first, Set<FlatNode> lastset) {
2521 HashSet tovisit=new HashSet();
2522 HashSet visited=new HashSet();
2524 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2526 //Label targets of branches
2527 Set<FlatNode> targets=branchanalysis.getTargets();
2528 for(Iterator<FlatNode> it=targets.iterator();it.hasNext();) {
2529 nodetolabel.put(it.next(), new Integer(labelindex++));
2534 /*Assign labels first. A node needs a label if the previous
2535 * node has two exits or this node is a join point. */
2537 while(!tovisit.isEmpty()) {
2538 FlatNode fn=(FlatNode)tovisit.iterator().next();
2543 if(lastset!=null&&lastset.contains(fn)) {
2544 // if last is not null and matches, don't go
2545 // any further for assigning labels
2549 for(int i=0; i<fn.numNext(); i++) {
2550 FlatNode nn=fn.getNext(i);
2553 //1) Edge >1 of node
2554 nodetolabel.put(nn,new Integer(labelindex++));
2556 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2560 nodetolabel.put(nn,new Integer(labelindex++));
2568 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first) {
2569 return assignLabels(first, null);
2572 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
2573 HashSet tovisit=new HashSet();
2574 HashSet visited=new HashSet();
2576 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2579 /*Assign labels first. A node needs a label if the previous
2580 * node has two exits or this node is a join point. */
2582 while(!tovisit.isEmpty()) {
2583 FlatNode fn=(FlatNode)tovisit.iterator().next();
2588 if(lastset!=null&&lastset.contains(fn)) {
2589 // if last is not null and matches, don't go
2590 // any further for assigning labels
2594 for(int i=0; i<fn.numNext(); i++) {
2595 FlatNode nn=fn.getNext(i);
2598 //1) Edge >1 of node
2599 nodetolabel.put(nn,new Integer(labelindex++));
2601 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2605 nodetolabel.put(nn,new Integer(labelindex++));
2613 /** Generate text string that corresponds to the TempDescriptor td. */
2614 protected String generateTemp(FlatMethod fm, TempDescriptor td, LocalityBinding lb) {
2615 MethodDescriptor md=fm.getMethod();
2616 TaskDescriptor task=fm.getTask();
2617 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
2619 if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
2620 //System.out.println("generateTemp returns " + td.getSafeSymbol());
2621 return td.getSafeSymbol();
2624 if (objecttemps.isLocalPtr(td)) {
2625 return localsprefixderef+td.getSafeSymbol();
2628 if (objecttemps.isParamPtr(td)) {
2629 return paramsprefix+"->"+td.getSafeSymbol();
2635 protected void generateFlatNode(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output) {
2637 // insert pre-node actions from the code plan
2640 CodePlan cp = mlpa.getCodePlan( fn );
2643 FlatSESEEnterNode currentSESE = cp.getCurrentSESE();
2645 // for each sese and age pair that this parent statement
2646 // must stall on, take that child's stall semaphore, the
2647 // copying of values comes after the statement
2648 Iterator<VariableSourceToken> vstItr = cp.getStallTokens().iterator();
2649 while( vstItr.hasNext() ) {
2650 VariableSourceToken vst = vstItr.next();
2652 SESEandAgePair p = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2654 output.println(" {");
2655 output.println(" SESEcommon* common = (SESEcommon*) "+p+";");
2657 output.println(" pthread_mutex_lock( &(common->lock) );");
2658 output.println(" while( common->doneExecuting == FALSE ) {");
2659 output.println(" pthread_cond_wait( &(common->doneCond), &(common->lock) );");
2660 output.println(" }");
2661 output.println(" pthread_mutex_unlock( &(common->lock) );");
2663 //output.println(" psem_take( &(common->stallSem) );");
2665 // copy things we might have stalled for
2666 output.println(" "+p.getSESE().getSESErecordName()+"* child = ("+
2667 p.getSESE().getSESErecordName()+"*) "+p+";");
2669 Iterator<TempDescriptor> tdItr = cp.getCopySet( vst ).iterator();
2670 while( tdItr.hasNext() ) {
2671 TempDescriptor td = tdItr.next();
2672 FlatMethod fmContext;
2673 if( currentSESE.getIsCallerSESEplaceholder() ) {
2674 fmContext = currentSESE.getfmEnclosing();
2676 fmContext = currentSESE.getfmBogus();
2678 output.println(" "+generateTemp( fmContext, td, null )+
2679 " = child->"+vst.getAddrVar().getSafeSymbol()+";");
2682 output.println(" }");
2685 // for each variable with a dynamic source, stall just for that variable
2686 Iterator<TempDescriptor> dynItr = cp.getDynamicStallSet().iterator();
2687 while( dynItr.hasNext() ) {
2688 TempDescriptor dynVar = dynItr.next();
2690 // only stall if the dynamic source is not yourself, denoted by src==NULL
2691 // otherwise the dynamic write nodes will have the local var up-to-date
2692 output.println(" {");
2693 output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
2694 output.println(" SESEcommon* common = (SESEcommon*) "+dynVar+"_srcSESE;");
2695 output.println(" psem_take( &(common->stallSem) );");
2697 FlatMethod fmContext;
2698 if( currentSESE.getIsCallerSESEplaceholder() ) {
2699 fmContext = currentSESE.getfmEnclosing();
2701 fmContext = currentSESE.getfmBogus();
2703 output.println(" "+generateTemp( fmContext, dynVar, null )+
2704 " = *(("+dynVar.getType()+"*) ("+
2705 dynVar+"_srcSESE + "+dynVar+"_srcOffset));");
2707 output.println(" }");
2708 output.println(" }");
2711 // for each assignment of a variable to rhs that has a dynamic source,
2712 // copy the dynamic sources
2713 Iterator dynAssignItr = cp.getDynAssigns().entrySet().iterator();
2714 while( dynAssignItr.hasNext() ) {
2715 Map.Entry me = (Map.Entry) dynAssignItr.next();
2716 TempDescriptor lhs = (TempDescriptor) me.getKey();
2717 TempDescriptor rhs = (TempDescriptor) me.getValue();
2718 output.println(" "+lhs+"_srcSESE = "+rhs+"_srcSESE;");
2719 output.println(" "+lhs+"_srcOffset = "+rhs+"_srcOffset;");
2722 // for each lhs that is dynamic from a non-dynamic source, set the
2723 // dynamic source vars to the current SESE
2724 dynItr = cp.getDynAssignCurr().iterator();
2725 while( dynItr.hasNext() ) {
2726 TempDescriptor dynVar = dynItr.next();
2727 output.println(" "+dynVar+"_srcSESE = NULL;");
2731 // handling stall site
2733 ParentChildConflictsMap conflictsMap=mlpa.getConflictsResults().get(fn);
2735 if (conflictsMap != null) {
2737 Set<Long> allocSet = conflictsMap
2738 .getAllocationSiteIDSetofStallSite();
2740 if (allocSet.size() > 0) {
2742 FlatNode enclosingFlatNode=null;
2743 if( currentSESE.getIsCallerSESEplaceholder() && currentSESE.getParent()==null){
2744 enclosingFlatNode=currentSESE.getfmEnclosing();
2746 enclosingFlatNode=currentSESE;
2749 ConflictGraph graph=mlpa.getConflictGraphResults().get(enclosingFlatNode);
2750 HashSet<SESELock> seseLockSet=mlpa.getConflictGraphLockMap().get(graph);
2751 Set<WaitingElement> waitingElementSet=graph.getStallSiteWaitingElementSet(conflictsMap, seseLockSet);
2753 if(waitingElementSet.size()>0){
2754 output.println(" /* stall on parent's stall sites */");
2755 output.println(" {");
2756 output.println(" pthread_mutex_lock( &(seseCaller->lock) );");
2757 output.println(" ConflictNode* node;");
2758 output.println(" struct Queue* list=NULL;");
2759 output.println(" WaitingElement* newElement=NULL;");
2760 output.println(" struct QueueItem* newQItem=NULL;");
2761 output.println(" waitingQueueItemID++;");
2762 output.println(" psem_init( &(seseCaller->memoryStallSiteSem) );");
2763 output.println(" int qIdx;");
2764 output.println(" int takeCount=0;");
2765 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
2766 WaitingElement waitingElement = (WaitingElement) iterator.next();
2768 output.println(" qIdx=getQueueIdx(seseCaller->allocSiteArray,numRelatedWaitingQueue,"
2769 + waitingElement.getWaitingID() + ");");
2770 output.println(" if(qIdx!=-1 && !isEmpty(seseCaller->allocSiteArray[qIdx].waitingQueue)){");
2771 output.println(" list=createQueue();");
2772 for (Iterator iterator2 = waitingElement.getAllocList().iterator(); iterator2.hasNext();) {
2773 Integer allocID = (Integer) iterator2 .next();
2774 output.println(" node=mlpCreateConflictNode( "+ allocID + " );");
2775 output.println(" addNewItem(list,node);");
2777 output.println(" newElement=mlpCreateWaitingElement( "+ waitingElement.getStatus()
2778 + ", seseCaller, list, waitingQueueItemID );");
2779 output.println(" addNewItemBack(seseCaller->allocSiteArray[qIdx].waitingQueue,newElement);");
2780 output.println(" takeCount++;");
2781 output.println(" }");
2785 output.println(" pthread_mutex_unlock( &(seseCaller->lock) );");
2786 output.println(" if( takeCount>0 ){");
2787 output.println(" psem_take( &(seseCaller->memoryStallSiteSem) );");
2788 output.println(" }");
2789 output.println(" }");
2793 } // end of if (conflictsMap != null) {
2798 case FKind.FlatAtomicEnterNode:
2799 generateFlatAtomicEnterNode(fm, lb, (FlatAtomicEnterNode) fn, output);
2802 case FKind.FlatAtomicExitNode:
2803 generateFlatAtomicExitNode(fm, lb, (FlatAtomicExitNode) fn, output);
2806 case FKind.FlatInstanceOfNode:
2807 generateFlatInstanceOfNode(fm, lb, (FlatInstanceOfNode)fn, output);
2810 case FKind.FlatSESEEnterNode:
2811 generateFlatSESEEnterNode(fm, lb, (FlatSESEEnterNode)fn, output);
2814 case FKind.FlatSESEExitNode:
2815 generateFlatSESEExitNode(fm, lb, (FlatSESEExitNode)fn, output);
2818 case FKind.FlatWriteDynamicVarNode:
2819 generateFlatWriteDynamicVarNode(fm, lb, (FlatWriteDynamicVarNode)fn, output);
2822 case FKind.FlatGlobalConvNode:
2823 generateFlatGlobalConvNode(fm, lb, (FlatGlobalConvNode) fn, output);
2826 case FKind.FlatTagDeclaration:
2827 generateFlatTagDeclaration(fm, lb, (FlatTagDeclaration) fn,output);
2830 case FKind.FlatCall:
2831 generateFlatCall(fm, lb, (FlatCall) fn,output);
2834 case FKind.FlatFieldNode:
2835 generateFlatFieldNode(fm, lb, (FlatFieldNode) fn,output);
2838 case FKind.FlatElementNode:
2839 generateFlatElementNode(fm, lb, (FlatElementNode) fn,output);
2842 case FKind.FlatSetElementNode:
2843 generateFlatSetElementNode(fm, lb, (FlatSetElementNode) fn,output);
2846 case FKind.FlatSetFieldNode:
2847 generateFlatSetFieldNode(fm, lb, (FlatSetFieldNode) fn,output);
2851 generateFlatNew(fm, lb, (FlatNew) fn,output);
2854 case FKind.FlatOpNode:
2855 generateFlatOpNode(fm, lb, (FlatOpNode) fn,output);
2858 case FKind.FlatCastNode:
2859 generateFlatCastNode(fm, lb, (FlatCastNode) fn,output);
2862 case FKind.FlatLiteralNode:
2863 generateFlatLiteralNode(fm, lb, (FlatLiteralNode) fn,output);
2866 case FKind.FlatReturnNode:
2867 generateFlatReturnNode(fm, lb, (FlatReturnNode) fn,output);
2871 output.println("/* nop */");
2874 case FKind.FlatExit:
2875 output.println("/* exit */");
2878 case FKind.FlatBackEdge:
2879 if (state.SINGLETM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
2880 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
2882 if (((state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
2883 || (this.state.MULTICOREGC)) {
2884 if(state.DSM&&locality.getAtomic(lb).get(fn).intValue()>0) {
2885 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
2886 } else if(this.state.MULTICOREGC) {
2887 output.println("if (gcflag) gc("+localsprefixaddr+");");
2889 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2892 output.println("/* nop */");
2895 case FKind.FlatCheckNode:
2896 generateFlatCheckNode(fm, lb, (FlatCheckNode) fn, output);
2899 case FKind.FlatFlagActionNode:
2900 generateFlatFlagActionNode(fm, lb, (FlatFlagActionNode) fn, output);
2903 case FKind.FlatPrefetchNode:
2904 generateFlatPrefetchNode(fm,lb, (FlatPrefetchNode) fn, output);
2907 case FKind.FlatOffsetNode:
2908 generateFlatOffsetNode(fm, lb, (FlatOffsetNode)fn, output);
2915 // insert post-node actions from the code-plan
2917 CodePlan cp = mlpa.getCodePlan( fn );
2924 public void generateFlatOffsetNode(FlatMethod fm, LocalityBinding lb, FlatOffsetNode fofn, PrintWriter output) {
2925 output.println("/* FlatOffsetNode */");
2926 FieldDescriptor fd=fofn.getField();
2927 output.println(generateTemp(fm, fofn.getDst(),lb)+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+ fd.getSafeSymbol()+");");
2928 output.println("/* offset */");
2931 public void generateFlatPrefetchNode(FlatMethod fm, LocalityBinding lb, FlatPrefetchNode fpn, PrintWriter output) {
2932 if (state.PREFETCH) {
2933 Vector oids = new Vector();
2934 Vector fieldoffset = new Vector();
2935 Vector endoffset = new Vector();
2936 int tuplecount = 0; //Keeps track of number of prefetch tuples that need to be generated
2937 for(Iterator it = fpn.hspp.iterator(); it.hasNext();) {
2938 PrefetchPair pp = (PrefetchPair) it.next();
2939 Integer statusbase = locality.getNodePreTempInfo(lb,fpn).get(pp.base);
2940 /* Find prefetches that can generate oid */
2941 if(statusbase == LocalityAnalysis.GLOBAL) {
2942 generateTransCode(fm, lb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(lb).get(fpn).intValue()>0, false);
2944 } else if (statusbase == LocalityAnalysis.LOCAL) {
2945 generateTransCode(fm,lb,pp,oids,fieldoffset,endoffset,tuplecount,false,true);
2952 System.out.println("Adding prefetch "+fpn+ " to method:" +fm);
2953 output.println("{");
2954 output.println("/* prefetch */");
2955 output.println("/* prefetchid_" + fpn.siteid + " */");
2956 output.println("void * prefptr;");
2957 output.println("int tmpindex;");
2959 output.println("if((evalPrefetch["+fpn.siteid+"].operMode) || (evalPrefetch["+fpn.siteid+"].retrycount <= 0)) {");
2960 /*Create C code for oid array */
2961 output.print(" unsigned int oidarray_[] = {");
2962 boolean needcomma=false;
2963 for (Iterator it = oids.iterator(); it.hasNext();) {
2966 output.print(it.next());
2969 output.println("};");
2971 /*Create C code for endoffset values */
2972 output.print(" unsigned short endoffsetarry_[] = {");
2974 for (Iterator it = endoffset.iterator(); it.hasNext();) {
2977 output.print(it.next());
2980 output.println("};");
2982 /*Create C code for Field Offset Values */
2983 output.print(" short fieldarry_[] = {");
2985 for (Iterator it = fieldoffset.iterator(); it.hasNext();) {
2988 output.print(it.next());
2991 output.println("};");
2992 /* make the prefetch call to Runtime */
2993 output.println(" if(!evalPrefetch["+fpn.siteid+"].operMode) {");
2994 output.println(" evalPrefetch["+fpn.siteid+"].retrycount = RETRYINTERVAL;");
2995 output.println(" }");
2996 output.println(" prefetch("+fpn.siteid+" ,"+tuplecount+", oidarray_, endoffsetarry_, fieldarry_);");
2997 output.println(" } else {");
2998 output.println(" evalPrefetch["+fpn.siteid+"].retrycount--;");
2999 output.println(" }");
3000 output.println("}");
3004 public void generateTransCode(FlatMethod fm, LocalityBinding lb,PrefetchPair pp, Vector oids, Vector fieldoffset, Vector endoffset, int tuplecount, boolean inside, boolean localbase) {
3005 short offsetcount = 0;
3009 } else if (localbase) {
3010 for(; breakindex<pp.desc.size(); breakindex++) {
3011 Descriptor desc=pp.getDescAt(breakindex);
3012 if (desc instanceof FieldDescriptor) {
3013 FieldDescriptor fd=(FieldDescriptor)desc;
3014 if (fd.isGlobal()) {
3022 if (breakindex>pp.desc.size()) //all local
3025 TypeDescriptor lasttype=pp.base.getType();
3026 String basestr=generateTemp(fm, pp.base, lb);
3028 boolean maybenull=fm.getMethod().isStatic()||
3029 !pp.base.equals(fm.getParameter(0));
3031 for(int i=0; i<breakindex; i++) {
3032 String indexcheck="";
3034 Descriptor desc=pp.getDescAt(i);
3035 if (desc instanceof FieldDescriptor) {
3036 FieldDescriptor fd=(FieldDescriptor)desc;
3038 if (!teststr.equals(""))
3040 teststr+="((prefptr="+basestr+")!=NULL)";
3041 basestr="((struct "+lasttype.getSafeSymbol()+" *)prefptr)->"+fd.getSafeSymbol();
3043 basestr=basestr+"->"+fd.getSafeSymbol();
3046 lasttype=fd.getType();
3048 IndexDescriptor id=(IndexDescriptor)desc;
3049 indexcheck="((tmpindex=";
3050 for(int j=0; j<id.tddesc.size(); j++) {
3051 indexcheck+=generateTemp(fm, id.getTempDescAt(j), lb)+"+";
3053 indexcheck+=id.offset+")>=0)&(tmpindex<((struct ArrayObject *)prefptr)->___length___)";
3055 if (!teststr.equals(""))
3057 teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck;
3058 basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]";
3060 lasttype=lasttype.dereference();
3065 if (teststr.equals("")) {
3066 oid="((unsigned int)"+basestr+")";
3068 oid="((unsigned int)(("+teststr+")?"+basestr+":NULL))";
3072 for(int i = breakindex; i < pp.desc.size(); i++) {
3073 String newfieldoffset;
3074 Object desc = pp.getDescAt(i);
3075 if(desc instanceof FieldDescriptor) {
3076 FieldDescriptor fd=(FieldDescriptor)desc;
3077 newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))");
3078 lasttype=fd.getType();
3080 newfieldoffset = "";
3081 IndexDescriptor id=(IndexDescriptor)desc;
3082 for(int j = 0; j < id.tddesc.size(); j++) {
3083 newfieldoffset += generateTemp(fm, id.getTempDescAt(j), lb) + "+";
3085 newfieldoffset += id.offset.toString();
3086 lasttype=lasttype.dereference();
3088 fieldoffset.add(newfieldoffset);
3091 int base=(tuplecount>0) ? ((Short)endoffset.get(tuplecount-1)).intValue() : 0;
3092 base+=pp.desc.size()-breakindex;
3093 endoffset.add(new Short((short)base));
3098 public void generateFlatGlobalConvNode(FlatMethod fm, LocalityBinding lb, FlatGlobalConvNode fgcn, PrintWriter output) {
3099 if (lb!=fgcn.getLocality())
3101 /* Have to generate flat globalconv */
3102 if (fgcn.getMakePtr()) {
3104 //DEBUG: output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+",\" "+fm+":"+fgcn+"\");");
3105 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3107 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fgcn)||state.READSET&&dc.getNeedWriteTrans(lb, fgcn)) {
3108 //need to do translation
3109 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+", (void *)("+localsprefixaddr+"));");
3110 } else if (state.READSET&&dc.getNeedTrans(lb, fgcn)) {
3111 if (state.HYBRID&&delaycomp.getConv(lb).contains(fgcn)) {
3112 output.println("TRANSREADRDFISSION("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3114 output.println("TRANSREADRD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3118 /* Need to convert to OID */
3119 if ((dc==null)||dc.getNeedSrcTrans(lb,fgcn)) {
3120 if (fgcn.doConvert()||(delaycomp!=null&&delaycomp.needsFission(lb, fgcn.getAtomicEnter())&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) {
3121 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc(),lb)+");");
3123 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=NULL;");
3129 public void generateFlatInstanceOfNode(FlatMethod fm, LocalityBinding lb, FlatInstanceOfNode fion, PrintWriter output) {
3131 if (fion.getType().isArray()) {
3132 type=state.getArrayNumber(fion.getType())+state.numClasses();
3134 type=fion.getType().getClassDesc().getId();
3137 if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
3138 output.println(generateTemp(fm, fion.getDst(), lb)+"=1;");
3140 output.println(generateTemp(fm, fion.getDst(), lb)+"=instanceof("+generateTemp(fm,fion.getSrc(),lb)+","+type+");");
3143 int sandboxcounter=0;
3144 public void generateFlatAtomicEnterNode(FlatMethod fm, LocalityBinding lb, FlatAtomicEnterNode faen, PrintWriter output) {
3145 /* Check to see if we need to generate code for this atomic */
3146 if (locality==null) {
3147 if (GENERATEPRECISEGC) {
3148 output.println("if (pthread_mutex_trylock(&atomiclock)!=0) {");
3149 output.println("stopforgc((struct garbagelist *) &___locals___);");
3150 output.println("pthread_mutex_lock(&atomiclock);");
3151 output.println("restartaftergc();");
3152 output.println("}");
3154 output.println("pthread_mutex_lock(&atomiclock);");
3159 if (locality.getAtomic(lb).get(faen.getPrev(0)).intValue()>0)
3163 if (state.SANDBOX) {
3164 outsandbox.println("int atomiccounter"+sandboxcounter+"=LOW_CHECK_FREQUENCY;");
3165 output.println("counter_reset_pointer=&atomiccounter"+sandboxcounter+";");
3168 if (state.DELAYCOMP&&delaycomp.needsFission(lb, faen)) {
3169 AtomicRecord ar=atomicmethodmap.get(faen);
3171 for(Iterator<TempDescriptor> tmpit=ar.livein.iterator();tmpit.hasNext();) {
3172 TempDescriptor tmp=tmpit.next();
3173 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3176 //copy outs that depend on path
3177 for(Iterator<TempDescriptor> tmpit=ar.liveoutvirtualread.iterator();tmpit.hasNext();) {
3178 TempDescriptor tmp=tmpit.next();
3179 if (!ar.livein.contains(tmp))
3180 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3184 /* Backup the temps. */
3185 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3186 TempDescriptor tmp=tmpit.next();
3187 output.println(generateTemp(fm, backuptable.get(lb).get(tmp),lb)+"="+generateTemp(fm,tmp,lb)+";");
3190 output.println("goto transstart"+faen.getIdentifier()+";");
3192 /******* Print code to retry aborted transaction *******/
3193 output.println("transretry"+faen.getIdentifier()+":");
3196 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3197 TempDescriptor tmp=tmpit.next();
3198 output.println(generateTemp(fm, tmp,lb)+"="+generateTemp(fm,backuptable.get(lb).get(tmp),lb)+";");
3202 /********* Need to revert local object store ********/
3203 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3205 output.println("while ("+revertptr+") {");
3206 output.println("struct ___Object___ * tmpptr;");
3207 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3208 output.println("REVERT_OBJ("+revertptr+");");
3209 output.println(revertptr+"=tmpptr;");
3210 output.println("}");
3212 /******* Tell the runtime to start the transaction *******/
3214 output.println("transstart"+faen.getIdentifier()+":");
3215 if (state.SANDBOX) {
3216 output.println("transaction_check_counter=*counter_reset_pointer;");
3219 output.println("transStart();");
3221 if (state.ABORTREADERS||state.SANDBOX) {
3223 output.println("abortenabled=1;");
3224 output.println("if (_setjmp(aborttrans)) {");
3225 output.println(" goto transretry"+faen.getIdentifier()+"; }");
3229 public void generateFlatAtomicExitNode(FlatMethod fm, LocalityBinding lb, FlatAtomicExitNode faen, PrintWriter output) {
3230 /* Check to see if we need to generate code for this atomic */
3231 if (locality==null) {
3232 output.println("pthread_mutex_unlock(&atomiclock);");
3235 if (locality.getAtomic(lb).get(faen).intValue()>0)
3237 //store the revert list before we lose the transaction object
3240 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3241 output.println(revertptr+"=revertlist;");
3242 output.println("if (transCommit()) {");
3243 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3244 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3245 output.println("} else {");
3246 /* Need to commit local object store */
3247 output.println("while ("+revertptr+") {");
3248 output.println("struct ___Object___ * tmpptr;");
3249 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3250 output.println("COMMIT_OBJ("+revertptr+");");
3251 output.println(revertptr+"=tmpptr;");
3252 output.println("}");
3253 output.println("}");
3257 if (!state.DELAYCOMP) {
3259 output.println("if (transCommit()) {");
3260 /* Transaction aborts if it returns true */
3261 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3262 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3263 output.println("}");
3265 if (delaycomp.optimizeTrans(lb, faen.getAtomicEnter())&&(!state.STMARRAY||state.DUALVIEW)) {
3266 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3267 output.println("LIGHTWEIGHTCOMMIT("+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+", transretry"+faen.getAtomicEnter().getIdentifier()+");");
3269 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3270 TempDescriptor tmp=tmpit.next();
3271 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3273 } else if (delaycomp.needsFission(lb, faen.getAtomicEnter())) {
3274 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3276 output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {");
3277 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3278 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3279 output.println("}");
3281 output.println("else {");
3282 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3283 TempDescriptor tmp=tmpit.next();
3284 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3286 output.println("}");
3288 output.println("if (transCommit(NULL, NULL, NULL, NULL)) {");
3289 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3290 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3291 output.println("}");
3296 public void generateFlatSESEEnterNode( FlatMethod fm,
3298 FlatSESEEnterNode fsen,
3302 // if MLP flag is off, okay that SESE nodes are in IR graph,
3303 // just skip over them and code generates exactly the same
3308 // there may be an SESE in an unreachable method, skip over
3309 if( !mlpa.getAllSESEs().contains( fsen ) ) {
3313 // also, if we have encountered a placeholder, just skip it
3314 if( fsen.getIsCallerSESEplaceholder() ) {
3318 output.println(" {");
3320 // set up the parent
3321 if( fsen == mlpa.getMainSESE() ) {
3322 output.println(" SESEcommon* parentCommon = NULL;");
3324 if( fsen.getParent() == null ) {
3325 System.out.println( "in "+fm+", "+fsen+" has null parent" );
3327 assert fsen.getParent() != null;
3328 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3329 output.println(" SESEcommon* parentCommon = &("+paramsprefix+"->common);");
3331 //output.println(" SESEcommon* parentCommon = (SESEcommon*) peekItem( seseCallStack );");
3332 output.println(" SESEcommon* parentCommon = seseCaller;");
3336 // before doing anything, lock your own record and increment the running children
3337 if( fsen != mlpa.getMainSESE() ) {
3338 output.println(" pthread_mutex_lock( &(parentCommon->lock) );");
3339 output.println(" ++(parentCommon->numRunningChildren);");
3340 output.println(" pthread_mutex_unlock( &(parentCommon->lock) );");
3343 // just allocate the space for this record
3344 output.println(" "+fsen.getSESErecordName()+"* seseToIssue = ("+
3345 fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
3346 fsen.getSESErecordName()+" ) );");
3348 // and keep the thread-local sese stack up to date
3349 //output.println(" addNewItem( seseCallStack, (void*) seseToIssue);");
3351 // fill in common data
3352 output.println(" seseToIssue->common.classID = "+fsen.getIdentifier()+";");
3353 output.println(" psem_init( &(seseToIssue->common.stallSem) );");
3355 output.println(" seseToIssue->common.forwardList = createQueue();");
3357 output.println(" seseToIssue->common.connectedList = createQueue();");
3359 output.println(" seseToIssue->common.unresolvedDependencies = 0;");
3360 output.println(" pthread_cond_init( &(seseToIssue->common.doneCond), NULL );");
3361 output.println(" seseToIssue->common.doneExecuting = FALSE;");
3362 output.println(" pthread_cond_init( &(seseToIssue->common.runningChildrenCond), NULL );");
3363 output.println(" seseToIssue->common.numRunningChildren = 0;");
3364 output.println(" seseToIssue->common.parent = parentCommon;");
3366 // all READY in-vars should be copied now and be done with it
3367 Iterator<TempDescriptor> tempItr = fsen.getReadyInVarSet().iterator();
3368 while( tempItr.hasNext() ) {
3369 TempDescriptor temp = tempItr.next();
3371 // when we are issuing the main SESE or an SESE with placeholder
3372 // caller SESE as parent, generate temp child child's eclosing method,
3373 // otherwise use the parent's enclosing method as the context
3374 boolean useParentContext = false;
3376 if( fsen != mlpa.getMainSESE() ) {
3377 assert fsen.getParent() != null;
3378 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3379 useParentContext = true;
3383 if( useParentContext ) {
3384 output.println(" seseToIssue->"+temp+" = "+
3385 generateTemp( fsen.getParent().getfmBogus(), temp, null )+";");
3387 output.println(" seseToIssue->"+temp+" = "+
3388 generateTemp( fsen.getfmEnclosing(), temp, null )+";");
3392 // count up memory conflict dependencies,
3394 ConflictGraph graph=null;
3395 FlatSESEEnterNode parent=fsen.getParent();
3397 if(parent.isCallerSESEplaceholder){
3398 graph=mlpa.getConflictGraphResults().get(parent.getfmEnclosing());
3400 graph=mlpa.getConflictGraphResults().get(parent);
3403 if (graph != null) {
3405 HashSet<SESELock> seseLockSet=mlpa.getConflictGraphLockMap().get(graph);
3408 output.println(" /*add waiting queue element*/");
3409 output.println(" struct Queue* newWaitingItemQueue=createQueue();");
3411 Set<WaitingElement> waitingQueueSet=graph.getWaitingElementSetBySESEID(fsen
3412 .getIdentifier(),seseLockSet);
3413 if (waitingQueueSet.size() > 0) {
3414 output.println(" {");
3415 output.println(" waitingQueueItemID++;");
3416 output.println(" ConflictNode* node;");
3417 output.println(" WaitingElement* newElement=NULL;");
3418 output.println(" struct Queue* list=NULL;");
3419 output.println(" struct QueueItem* newQItem=NULL;");
3421 .println(" pthread_mutex_lock( &(parentCommon->lock) );");
3422 for (Iterator iterator = waitingQueueSet.iterator(); iterator
3424 WaitingElement waitingElement = (WaitingElement) iterator.next();
3425 output.println(" list=createQueue();");
3426 for (Iterator iterator2 = waitingElement.getAllocList().iterator(); iterator2
3428 Integer allocID = (Integer) iterator2
3430 output.println(" node=mlpCreateConflictNode( "+allocID+" );");
3431 output.println(" addNewItem(list,node);");
3433 output.println(" seseToIssue->common.waitingQueueItemID=waitingQueueItemID;");
3434 output.println(" newElement=mlpCreateWaitingElement( "+waitingElement.getStatus()+", seseToIssue, list, waitingQueueItemID );");
3437 .println(" newQItem=addWaitingQueueElement(parentCommon->allocSiteArray,numRelatedWaitingQueue,"
3438 + waitingElement.getWaitingID() + ",newElement);");
3440 .println(" addNewItem(newWaitingItemQueue,newQItem);");
3442 .println(" ++(seseToIssue->common.unresolvedDependencies);");
3447 .println(" pthread_mutex_unlock( &(parentCommon->lock) );");
3448 output.println(" }");
3451 output.println(" /*decide whether it is runnable or not in regarding to memory conflicts*/");
3452 output.println(" {");
3453 output.println(" pthread_mutex_lock( &(parentCommon->lock) );");
3454 output.println(" if( !isEmpty(newWaitingItemQueue) ){");
3455 output.println(" int idx;");
3456 output.println(" for(idx = 0 ; idx < numRelatedWaitingQueue ; idx++){");
3457 output.println(" struct Queue *allocQueue=parentCommon->allocSiteArray[idx].waitingQueue;");
3458 output.println(" if( !isEmpty(allocQueue) ){");
3459 output.println(" struct QueueItem* nextQItem=getHead(allocQueue);");
3460 output.println(" while( nextQItem != NULL ){");
3461 output.println(" if(contains(newWaitingItemQueue,nextQItem) && isRunnable(allocQueue,nextQItem)){");
3462 output.println(" --(seseToIssue->common.unresolvedDependencies);");
3463 output.println(" }");
3464 output.println(" nextQItem=getNextQueueItem(nextQItem);");
3465 output.println(" }");
3466 output.println(" }");
3467 output.println(" }");
3468 output.println(" pthread_mutex_unlock( &(parentCommon->lock) );");
3469 output.println(" }");
3470 output.println(" }");
3475 // before potentially adding this SESE to other forwarding lists,
3476 // create it's lock and take it immediately
3477 output.println(" pthread_mutex_init( &(seseToIssue->common.lock), NULL );");
3478 output.println(" pthread_mutex_lock( &(seseToIssue->common.lock) );");
3480 if( fsen != mlpa.getMainSESE() ) {
3481 // count up outstanding dependencies, static first, then dynamic
3482 Iterator<SESEandAgePair> staticSrcsItr = fsen.getStaticInVarSrcs().iterator();
3483 while( staticSrcsItr.hasNext() ) {
3484 SESEandAgePair srcPair = staticSrcsItr.next();
3485 output.println(" {");
3486 output.println(" SESEcommon* src = (SESEcommon*)"+srcPair+";");
3487 output.println(" pthread_mutex_lock( &(src->lock) );");
3488 output.println(" if( !isEmpty( src->forwardList ) &&");
3489 output.println(" seseToIssue == peekItem( src->forwardList ) ) {");
3490 output.println(" printf( \"This shouldnt already be here\\n\");");
3491 output.println(" exit( -1 );");
3492 output.println(" }");
3493 output.println(" if( !src->doneExecuting ) {");
3494 output.println(" addNewItem( src->forwardList, seseToIssue );");
3495 output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3496 output.println(" }");
3497 output.println(" pthread_mutex_unlock( &(src->lock) );");
3498 output.println(" }");
3500 // whether or not it is an outstanding dependency, make sure
3501 // to pass the static name to the child's record
3502 output.println(" seseToIssue->"+srcPair+" = "+srcPair+";");
3505 // dynamic sources might already be accounted for in the static list,
3506 // so only add them to forwarding lists if they're not already there
3507 Iterator<TempDescriptor> dynVarsItr = fsen.getDynamicInVarSet().iterator();
3508 while( dynVarsItr.hasNext() ) {
3509 TempDescriptor dynInVar = dynVarsItr.next();
3510 output.println(" {");
3511 output.println(" SESEcommon* src = (SESEcommon*)"+dynInVar+"_srcSESE;");
3513 // the dynamic source is NULL if it comes from your own space--you can't pass
3514 // the address off to the new child, because you're not done executing and
3515 // might change the variable, so copy it right now
3516 output.println(" if( src != NULL ) {");
3517 output.println(" pthread_mutex_lock( &(src->lock) );");
3518 output.println(" if( isEmpty( src->forwardList ) ||");
3519 output.println(" seseToIssue != peekItem( src->forwardList ) ) {");
3520 output.println(" if( !src->doneExecuting ) {");
3521 output.println(" addNewItem( src->forwardList, seseToIssue );");
3522 output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3523 output.println(" }");
3524 output.println(" }");
3525 output.println(" pthread_mutex_unlock( &(src->lock) );");
3526 output.println(" seseToIssue->"+dynInVar+"_srcOffset = "+dynInVar+"_srcOffset;");
3527 output.println(" } else {");
3529 boolean useParentContext = false;
3530 if( fsen != mlpa.getMainSESE() ) {
3531 assert fsen.getParent() != null;
3532 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3533 useParentContext = true;
3536 if( useParentContext ) {
3537 output.println(" seseToIssue->"+dynInVar+" = "+
3538 generateTemp( fsen.getParent().getfmBogus(), dynInVar, null )+";");
3540 output.println(" seseToIssue->"+dynInVar+" = "+
3541 generateTemp( fsen.getfmEnclosing(), dynInVar, null )+";");
3544 output.println(" }");
3545 output.println(" }");
3547 // even if the value is already copied, make sure your NULL source
3548 // gets passed so child knows it already has the dynamic value
3549 output.println(" seseToIssue->"+dynInVar+"_srcSESE = "+dynInVar+"_srcSESE;");
3552 // maintain pointers for for finding dynamic SESE
3553 // instances from static names
3554 SESEandAgePair p = new SESEandAgePair( fsen, 0 );
3555 if( fsen.getParent() != null &&
3556 //!fsen.getParent().getIsCallerSESEplaceholder() &&
3557 fsen.getParent().getNeededStaticNames().contains( p )
3560 for( int i = fsen.getOldestAgeToTrack(); i > 0; --i ) {
3561 SESEandAgePair p1 = new SESEandAgePair( fsen, i );
3562 SESEandAgePair p2 = new SESEandAgePair( fsen, i-1 );
3563 output.println(" "+p1+" = "+p2+";");
3565 output.println(" "+p+" = seseToIssue;");
3570 // if there were no outstanding dependencies, issue here
3571 output.println(" if( seseToIssue->common.unresolvedDependencies == 0 ) {");
3572 output.println(" workScheduleSubmit( (void*)seseToIssue );");
3573 output.println(" }");
3575 // release this SESE for siblings to update its dependencies or,
3576 // eventually, for it to mark itself finished
3577 output.println(" pthread_mutex_unlock( &(seseToIssue->common.lock) );");
3578 output.println(" }");
3582 public void generateFlatSESEExitNode( FlatMethod fm,
3584 FlatSESEExitNode fsexn,
3588 // if MLP flag is off, okay that SESE nodes are in IR graph,
3589 // just skip over them and code generates exactly the same
3594 // get the enter node for this exit that has meta data embedded
3595 FlatSESEEnterNode fsen = fsexn.getFlatEnter();
3597 // there may be an SESE in an unreachable method, skip over
3598 if( !mlpa.getAllSESEs().contains( fsen ) ) {
3602 // also, if we have encountered a placeholder, just jump it
3603 if( fsen.getIsCallerSESEplaceholder() ) {
3607 output.println(" /* SESE exiting */");
3609 String com = paramsprefix+"->common";
3611 // this SESE cannot be done until all of its children are done
3612 // so grab your own lock with the condition variable for watching
3613 // that the number of your running children is greater than zero
3614 output.println(" pthread_mutex_lock( &("+com+".lock) );");
3615 output.println(" while( "+com+".numRunningChildren > 0 ) {");
3616 output.println(" pthread_cond_wait( &("+com+".runningChildrenCond), &("+com+".lock) );");
3617 output.println(" }");
3619 // copy out-set from local temps into the sese record
3620 Iterator<TempDescriptor> itr = fsen.getOutVarSet().iterator();
3621 while( itr.hasNext() ) {
3622 TempDescriptor temp = itr.next();
3624 // only have to do this for primitives
3625 if( !temp.getType().isPrimitive() ) {
3629 // have to determine the context enclosing this sese
3630 boolean useParentContext = false;
3632 if( fsen != mlpa.getMainSESE() ) {
3633 assert fsen.getParent() != null;
3634 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3635 useParentContext = true;
3640 if( useParentContext ) {
3641 from = generateTemp( fsen.getParent().getfmBogus(), temp, null );
3643 from = generateTemp( fsen.getfmEnclosing(), temp, null );
3646 output.println(" "+paramsprefix+
3647 "->"+temp.getSafeSymbol()+
3651 // mark yourself done, your SESE data is now read-only
3652 output.println(" "+com+".doneExecuting = TRUE;");
3653 output.println(" pthread_cond_signal( &("+com+".doneCond) );");
3654 output.println(" pthread_mutex_unlock( &("+com+".lock) );");
3656 // decrement dependency count for all SESE's on your forwarding list
3657 output.println(" while( !isEmpty( "+com+".forwardList ) ) {");
3658 output.println(" SESEcommon* consumer = (SESEcommon*) getItem( "+com+".forwardList );");
3659 output.println(" pthread_mutex_lock( &(consumer->lock) );");
3660 output.println(" --(consumer->unresolvedDependencies);");
3661 output.println(" if( consumer->unresolvedDependencies == 0 ) {");
3662 output.println(" workScheduleSubmit( (void*)consumer );");
3663 output.println(" }");
3664 output.println(" pthread_mutex_unlock( &(consumer->lock) );");
3665 output.println(" }");
3668 // clean up its lock element from waiting queue, and decrement dependency count for next SESE block
3669 if( fsen != mlpa.getMainSESE() ) {
3672 output.println(" /* check memory dependency*/");
3673 output.println(" {");
3674 output.println(" pthread_mutex_lock( &(___params___->common.parent->lock) );");
3675 output.println(" int idx;");
3676 output.println(" int giveCount=0;");
3677 output.println(" struct Queue* launchQueue=createQueue();");
3678 output.println(" struct QueueItem* nextQueueItem;");
3679 output.println(" for(idx = 0 ; idx < ___params___->common.parent->numRelatedWaitingQueue ; idx++){");
3680 output.println(" if(!isEmpty(___params___->common.parent->allocSiteArray[idx].waitingQueue)){");
3681 output.println(" struct QueueItem* qItem=getHead(___params___->common.parent->allocSiteArray[idx].waitingQueue);");
3682 output.println(" while(qItem!=NULL){");
3683 output.println(" WaitingElement* item=qItem->objectptr;");
3684 output.println(" SESEcommon* seseItem=(SESEcommon*)item->seseRec;");
3685 output.println(" if(seseItem->classID==___params___->common.classID && item->id==___params___->common.waitingQueueItemID){");
3686 output.println(" removeItem(___params___->common.parent->allocSiteArray[idx].waitingQueue,qItem);");
3687 output.println(" }");
3688 output.println(" qItem=getNextQueueItem(qItem);");
3689 output.println(" }");
3690 output.println(" if( !isEmpty(___params___->common.parent->allocSiteArray[idx].waitingQueue) ){");
3692 output.println(" struct QueueItem* nextQItem=getHead(___params___->common.parent->allocSiteArray[idx].waitingQueue);");
3693 output.println(" while(nextQItem!=NULL){");
3694 output.println(" WaitingElement* nextItem=nextQItem->objectptr;");
3695 output.println(" SESEcommon* seseNextItem=(SESEcommon*)nextItem->seseRec;");
3696 // output.println(" int isResolved=resolveWaitingQueue(___params___->common.parent->allocSiteArray[idx].waitingQueue,nextQItem);");
3697 output.println(" int isResolved=isRunnable(___params___->common.parent->allocSiteArray[idx].waitingQueue,nextQItem);");
3698 output.println(" if(seseNextItem->classID==___params___->common.parent->classID){"); // stall site
3699 output.println(" if(isResolved){");
3700 output.println(" struct QueueItem* stallItem=findItem(___params___->common.parent->allocSiteArray[idx].waitingQueue,nextItem);");
3701 output.println(" removeItem(___params___->common.parent->allocSiteArray[idx].waitingQueue,stallItem);");
3702 output.println(" giveCount++;");
3703 output.println(" }");
3704 output.println(" if(!isEmpty(___params___->common.parent->allocSiteArray[idx].waitingQueue)){");
3705 // output.println(" nextQItem=getHead(___params___->common.parent->allocSiteArray[idx].waitingQueue);");
3706 output.println(" nextQItem=getNextQueueItem(nextQItem);");
3707 output.println(" }else{");
3708 output.println(" nextQItem=NULL;");
3709 output.println(" }");
3710 output.println(" }else{");
3711 output.println(" if(isResolved){");
3712 output.println(" pthread_mutex_lock( &(seseNextItem->lock) );");
3713 output.println(" if(seseNextItem->unresolvedDependencies > 0){");
3714 output.println(" --(seseNextItem->unresolvedDependencies);");
3715 output.println(" if( seseNextItem->unresolvedDependencies == 0){");
3716 //output.println(" workScheduleSubmit( (void*)nextItem);");
3717 output.println(" addNewItem(launchQueue,(void*)seseNextItem);");
3718 output.println(" }");
3719 output.println(" }");
3720 output.println(" pthread_mutex_unlock( &(seseNextItem->lock) );");
3721 output.println(" }");
3722 output.println(" nextQItem=getNextQueueItem(nextQItem);");
3723 output.println(" }");
3724 output.println(" } "); // end of while(nextQItem!=NULL)
3725 output.println(" }");
3726 output.println(" }");
3727 // output.println(" }");
3728 output.println(" }");
3729 output.println(" pthread_mutex_unlock( &(___params___->common.parent->lock) );");
3730 output.println(" if(!isEmpty(launchQueue)){");
3731 output.println(" struct QueueItem* qItem=getHead(launchQueue);");
3732 output.println(" while(qItem!=NULL){");
3733 output.println(" workScheduleSubmit(qItem->objectptr);");
3734 output.println(" qItem=getNextQueueItem(qItem);");
3735 output.println(" }");
3736 output.println(" }");
3737 output.println(" if(giveCount>0){");
3738 output.println(" psem_give(&(___params___->common.parent->memoryStallSiteSem));");
3739 output.println(" }");
3740 output.println(" }");
3744 // if parent is stalling on you, let them know you're done
3745 if( fsexn.getFlatEnter() != mlpa.getMainSESE() ) {
3746 output.println(" psem_give( &("+paramsprefix+"->common.stallSem) );");
3749 // last of all, decrement your parent's number of running children
3750 output.println(" if( "+paramsprefix+"->common.parent != NULL ) {");
3751 output.println(" pthread_mutex_lock( &("+paramsprefix+"->common.parent->lock) );");
3752 output.println(" --("+paramsprefix+"->common.parent->numRunningChildren);");
3753 output.println(" pthread_cond_signal( &("+paramsprefix+"->common.parent->runningChildrenCond) );");
3754 output.println(" pthread_mutex_unlock( &("+paramsprefix+"->common.parent->lock) );");
3755 output.println(" }");
3757 // this is a thread-only variable that can be handled when critical sese-to-sese
3758 // data has been taken care of--set sese pointer to remember self over method
3759 // calls to a non-zero, invalid address
3760 output.println(" seseCaller = (SESEcommon*) 0x1;");
3764 public void generateFlatWriteDynamicVarNode( FlatMethod fm,
3766 FlatWriteDynamicVarNode fwdvn,
3770 // should node should not be in an IR graph if the
3771 // MLP flag is not set
3772 throw new Error("Unexpected presence of FlatWriteDynamicVarNode");
3775 Hashtable<TempDescriptor, VariableSourceToken> writeDynamic =
3778 assert writeDynamic != null;
3780 Iterator wdItr = writeDynamic.entrySet().iterator();
3781 while( wdItr.hasNext() ) {
3782 Map.Entry me = (Map.Entry) wdItr.next();
3783 TempDescriptor refVar = (TempDescriptor) me.getKey();
3784 VariableSourceToken vst = (VariableSourceToken) me.getValue();
3786 FlatSESEEnterNode current = fwdvn.getEnclosingSESE();
3788 // only do this if the variable in question should be tracked,
3789 // meaning that it was explicitly added to the dynamic var set
3790 if( !current.getDynamicVarSet().contains( vst.getAddrVar() ) ) {
3794 SESEandAgePair instance = new SESEandAgePair( vst.getSESE(), vst.getAge() );
3796 output.println(" {");
3798 if( current.equals( vst.getSESE() ) ) {
3799 // if the src comes from this SESE, it's a method local variable,
3800 // mark src pointer NULL to signify that the var is up-to-date
3801 output.println(" "+vst.getAddrVar()+"_srcSESE = NULL;");
3804 // otherwise we track where it will come from
3805 output.println(" "+vst.getAddrVar()+"_srcSESE = "+instance+";");
3806 output.println(" "+vst.getAddrVar()+"_srcOffset = (int) &((("+
3807 vst.getSESE().getSESErecordName()+"*)0)->"+vst.getAddrVar()+");");
3810 output.println(" }");
3815 private void generateFlatCheckNode(FlatMethod fm, LocalityBinding lb, FlatCheckNode fcn, PrintWriter output) {
3816 if (state.CONSCHECK) {
3817 String specname=fcn.getSpec();
3818 String varname="repairstate___";
3819 output.println("{");
3820 output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
3822 TempDescriptor[] temps=fcn.getTemps();
3823 String[] vars=fcn.getVars();
3824 for(int i=0; i<temps.length; i++) {
3825 output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i],lb)+";");
3828 output.println("if (doanalysis"+specname+"("+varname+")) {");
3829 output.println("free"+specname+"_state("+varname+");");
3830 output.println("} else {");
3831 output.println("/* Bad invariant */");
3832 output.println("free"+specname+"_state("+varname+");");
3833 output.println("abort_task();");
3834 output.println("}");
3835 output.println("}");
3839 private void generateFlatCall(FlatMethod fm, LocalityBinding lb, FlatCall fc, PrintWriter output) {
3841 if( state.MLP && !nonSESEpass ) {
3842 output.println(" seseCaller = (SESEcommon*)"+paramsprefix+";");
3845 MethodDescriptor md=fc.getMethod();
3846 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? locality.getBinding(lb, fc) : md);
3847 ClassDescriptor cn=md.getClassDesc();
3848 output.println("{");
3849 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3851 LocalityBinding fclb=locality.getBinding(lb, fc);
3852 output.print(" struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
3854 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
3856 output.print(objectparams.numPointers());
3857 output.print(", "+localsprefixaddr);
3858 if (md.getThis()!=null) {
3860 output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis(),lb));
3862 if (fc.getThis()!=null&&md.getThis()==null) {
3863 System.out.println("WARNING!!!!!!!!!!!!");
3864 System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
3868 for(int i=0; i<fc.numArgs(); i++) {
3869 Descriptor var=md.getParameter(i);
3870 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
3871 if (objectparams.isParamPtr(paramtemp)) {
3872 TempDescriptor targ=fc.getArg(i);
3874 TypeDescriptor td=md.getParamType(i);
3876 output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
3878 output.print("(struct "+md.getParamType(i).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
3881 output.println("};");
3886 if (fc.getReturnTemp()!=null)
3887 output.print(generateTemp(fm,fc.getReturnTemp(),lb)+"=");
3889 /* Do we need to do virtual dispatch? */
3890 if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
3893 LocalityBinding fclb=locality.getBinding(lb, fc);
3894 output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
3896 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
3901 if (md.getReturnType().isClass()||md.getReturnType().isArray())
3902 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
3904 output.print(md.getReturnType().getSafeSymbol()+" ");
3905 output.print("(*)(");
3907 boolean printcomma=false;
3908 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3910 LocalityBinding fclb=locality.getBinding(lb, fc);
3911 output.print("struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
3913 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
3917 for(int i=0; i<objectparams.numPrimitives(); i++) {
3918 TempDescriptor temp=objectparams.getPrimitive(i);
3922 if (temp.getType().isClass()||temp.getType().isArray())
3923 output.print("struct " + temp.getType().getSafeSymbol()+" * ");
3925 output.print(temp.getType().getSafeSymbol());
3930 LocalityBinding fclb=locality.getBinding(lb, fc);
3931 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])");
3933 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
3937 boolean needcomma=false;
3938 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3939 output.print("&__parameterlist__");
3943 if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
3944 if (fc.getThis()!=null) {
3945 TypeDescriptor ptd=md.getThis().getType();
3948 if (ptd.isClass()&&!ptd.isArray())
3949 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
3950 output.print(generateTemp(fm,fc.getThis(),lb));
3955 for(int i=0; i<fc.numArgs(); i++) {
3956 Descriptor var=md.getParameter(i);
3957 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
3958 if (objectparams.isParamPrim(paramtemp)) {
3959 TempDescriptor targ=fc.getArg(i);
3963 TypeDescriptor ptd=md.getParamType(i);
3964 if (ptd.isClass()&&!ptd.isArray())
3965 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
3966 output.print(generateTemp(fm, targ,lb));
3970 output.println(");");
3971 output.println(" }");
3974 private boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
3975 Set subclasses=typeutil.getSubClasses(thiscd);
3976 if (subclasses==null)
3978 for(Iterator classit=subclasses.iterator(); classit.hasNext();) {
3979 ClassDescriptor cd=(ClassDescriptor)classit.next();
3980 Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol());
3981 for(Iterator matchit=possiblematches.iterator(); matchit.hasNext();) {
3982 MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
3983 if (md.matches(matchmd))
3990 private void generateFlatFieldNode(FlatMethod fm, LocalityBinding lb, FlatFieldNode ffn, PrintWriter output) {
3991 if (state.SINGLETM) {
3992 //single machine transactional memory case
3993 String field=ffn.getField().getSafeSymbol();
3994 String src=generateTemp(fm, ffn.getSrc(),lb);
3995 String dst=generateTemp(fm, ffn.getDst(),lb);
3997 output.println(dst+"="+ src +"->"+field+ ";");
3998 if (ffn.getField().getType().isPtr()&&locality.getAtomic(lb).get(ffn).intValue()>0&&
3999 locality.getNodePreTempInfo(lb, ffn).get(ffn.getSrc())!=LocalityAnalysis.SCRATCH) {
4000 if ((dc==null)||(!state.READSET&&dc.getNeedTrans(lb, ffn))||
4001 (state.READSET&&dc.getNeedWriteTrans(lb, ffn))) {
4002 output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));");
4003 } else if (state.READSET&&dc.getNeedTrans(lb, ffn)) {
4004 if (state.HYBRID&&delaycomp.getConv(lb).contains(ffn)) {
4005 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4007 output.println("TRANSREADRD("+dst+", "+dst+");");
4010 } else if (state.DSM) {
4011 Integer status=locality.getNodePreTempInfo(lb,ffn).get(ffn.getSrc());
4012 if (status==LocalityAnalysis.GLOBAL) {
4013 String field=ffn.getField().getSafeSymbol();
4014 String src=generateTemp(fm, ffn.getSrc(),lb);
4015 String dst=generateTemp(fm, ffn.getDst(),lb);
4017 if (ffn.getField().getType().isPtr()) {
4019 //TODO: Uncomment this when we have runtime support
4020 //if (ffn.getSrc()==ffn.getDst()) {
4021 //output.println("{");
4022 //output.println("void * temp="+src+";");
4023 //output.println("if (temp&0x1) {");
4024 //output.println("temp=(void *) transRead(trans, (unsigned int) temp);");
4025 //output.println(src+"->"+field+"="+temp+";");
4026 //output.println("}");
4027 //output.println(dst+"=temp;");
4028 //output.println("}");
4030 output.println(dst+"="+ src +"->"+field+ ";");
4031 //output.println("if ("+dst+"&0x1) {");
4032 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
4033 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
4034 //output.println(src+"->"+field+"="+src+"->"+field+";");
4035 //output.println("}");
4038 output.println(dst+"="+ src+"->"+field+";");
4040 } else if (status==LocalityAnalysis.LOCAL) {
4041 if (ffn.getField().getType().isPtr()&&
4042 ffn.getField().isGlobal()) {
4043 String field=ffn.getField().getSafeSymbol();
4044 String src=generateTemp(fm, ffn.getSrc(),lb);
4045 String dst=generateTemp(fm, ffn.getDst(),lb);
4046 output.println(dst+"="+ src +"->"+field+ ";");
4047 if (locality.getAtomic(lb).get(ffn).intValue()>0)
4048 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
4049 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
4051 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4052 } else if (status==LocalityAnalysis.EITHER) {
4053 //Code is reading from a null pointer
4054 output.println("if ("+generateTemp(fm, ffn.getSrc(),lb)+") {");
4055 output.println("#ifndef RAW");
4056 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4057 output.println("#endif");
4058 //This should throw a suitable null pointer error
4059 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4061 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4063 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4067 private void generateFlatSetFieldNode(FlatMethod fm, LocalityBinding lb, FlatSetFieldNode fsfn, PrintWriter output) {
4068 if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
4069 throw new Error("Can't set array length");
4070 if (state.SINGLETM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
4071 //Single Machine Transaction Case
4072 boolean srcptr=fsfn.getSrc().getType().isPtr();
4073 String src=generateTemp(fm,fsfn.getSrc(),lb);
4074 String dst=generateTemp(fm,fsfn.getDst(),lb);
4075 output.println("//"+srcptr+" "+fsfn.getSrc().getType().isNull());
4076 if (srcptr&&!fsfn.getSrc().getType().isNull()) {
4077 output.println("{");
4078 if ((dc==null)||dc.getNeedSrcTrans(lb, fsfn)&&
4079 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) {
4080 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4082 output.println("INTPTR srcoid=(INTPTR)"+src+";");
4085 if (wb.needBarrier(fsfn)&&
4086 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getDst())!=LocalityAnalysis.SCRATCH) {
4087 if (state.EVENTMONITOR) {
4088 output.println("if ("+dst+"->___objstatus___&DIRTY) EVLOGEVENTOBJ(EV_WRITE,"+dst+"->objuid)");
4090 output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;");
4092 if (srcptr&!fsfn.getSrc().getType().isNull()) {
4093 output.println("*((unsigned INTPTR *)&("+dst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4094 output.println("}");
4096 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4098 } else if (state.DSM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
4099 Integer statussrc=locality.getNodePreTempInfo(lb,fsfn).get(fsfn.getSrc());
4100 Integer statusdst=locality.getNodeTempInfo(lb).get(fsfn).get(fsfn.getDst());
4101 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4103 String src=generateTemp(fm,fsfn.getSrc(),lb);
4104 String dst=generateTemp(fm,fsfn.getDst(),lb);
4106 output.println("{");
4107 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4109 if (statusdst.equals(LocalityAnalysis.GLOBAL)) {
4112 if (wb.needBarrier(fsfn))
4113 output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;");
4115 output.println("*((unsigned INTPTR *)&("+glbdst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4117 output.println(glbdst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4118 } else if (statusdst.equals(LocalityAnalysis.LOCAL)) {
4119 /** Check if we need to copy */
4120 output.println("if(!"+dst+"->"+localcopystr+") {");
4121 /* Link object into list */
4122 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4123 output.println(revertptr+"=revertlist;");
4124 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4125 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4127 output.println("COPY_OBJ("+dst+");");
4128 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4129 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4130 output.println("}");
4132 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4134 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4135 } else if (statusdst.equals(LocalityAnalysis.EITHER)) {
4136 //writing to a null...bad
4137 output.println("if ("+dst+") {");
4138 output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}");
4140 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4142 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4145 output.println("}");
4148 if (state.FASTCHECK) {
4149 String dst=generateTemp(fm, fsfn.getDst(),lb);
4150 output.println("if(!"+dst+"->"+localcopystr+") {");
4151 /* Link object into list */
4152 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4153 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4155 output.println("COPY_OBJ("+dst+");");
4156 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4157 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4158 output.println("}");
4160 output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
4164 private void generateFlatElementNode(FlatMethod fm, LocalityBinding lb, FlatElementNode fen, PrintWriter output) {
4165 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
4168 if (elementtype.isArray()||elementtype.isClass())
4171 type=elementtype.getSafeSymbol()+" ";
4173 if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
4174 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fen.getIndex(),lb)+") >= "+generateTemp(fm,fen.getSrc(),lb) + "->___length___))");
4175 output.println("failedboundschk();");
4177 if (state.SINGLETM) {
4178 //Single machine transaction case
4179 String dst=generateTemp(fm, fen.getDst(),lb);
4180 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))) {
4181 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4183 output.println("STMGETARRAY("+dst+", "+ generateTemp(fm,fen.getSrc(),lb)+", "+generateTemp(fm, fen.getIndex(),lb)+", "+type+");");
4186 if (elementtype.isPtr()&&locality.getAtomic(lb).get(fen).intValue()>0&&
4187 locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())!=LocalityAnalysis.SCRATCH) {
4188 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fen)||state.READSET&&dc.getNeedWriteTrans(lb, fen)) {
4189 output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));");
4190 } else if (state.READSET&&dc.getNeedTrans(lb, fen)) {
4191 if (state.HYBRID&&delaycomp.getConv(lb).contains(fen)) {
4192 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4194 output.println("TRANSREADRD("+dst+", "+dst+");");
4197 } else if (state.DSM) {
4198 Integer status=locality.getNodePreTempInfo(lb,fen).get(fen.getSrc());
4199 if (status==LocalityAnalysis.GLOBAL) {
4200 String dst=generateTemp(fm, fen.getDst(),lb);
4201 if (elementtype.isPtr()) {
4202 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4203 //DEBUG: output.println("TRANSREAD("+dst+", "+dst+",\""+fm+":"+fen+"\");");
4204 output.println("TRANSREAD("+dst+", "+dst+");");
4206 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4208 } else if (status==LocalityAnalysis.LOCAL) {
4209 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4210 } else if (status==LocalityAnalysis.EITHER) {
4211 //Code is reading from a null pointer
4212 output.println("if ("+generateTemp(fm, fen.getSrc(),lb)+") {");
4213 output.println("#ifndef RAW");
4214 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4215 output.println("#endif");
4216 //This should throw a suitable null pointer error
4217 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4219 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4221 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4225 private void generateFlatSetElementNode(FlatMethod fm, LocalityBinding lb, FlatSetElementNode fsen, PrintWriter output) {
4226 //TODO: need dynamic check to make sure this assignment is actually legal
4227 //Because Object[] could actually be something more specific...ie. Integer[]
4229 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
4232 if (elementtype.isArray()||elementtype.isClass())
4235 type=elementtype.getSafeSymbol()+" ";
4237 if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
4238 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fsen.getIndex(),lb)+") >= "+generateTemp(fm,fsen.getDst(),lb) + "->___length___))");
4239 output.println("failedboundschk();");
4242 if (state.SINGLETM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4243 //Transaction set element case
4244 if (wb.needBarrier(fsen)&&
4245 locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH) {
4246 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___objstatus___))|=DIRTY;");
4248 if (fsen.getSrc().getType().isPtr()&&!fsen.getSrc().getType().isNull()) {
4249 output.println("{");
4250 String src=generateTemp(fm, fsen.getSrc(), lb);
4251 if ((dc==null)||dc.getNeedSrcTrans(lb, fsen)&&
4252 locality.getNodePreTempInfo(lb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) {
4253 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4255 output.println("INTPTR srcoid=(INTPTR)"+src+";");
4257 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
4258 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", srcoid, INTPTR);");
4260 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
4262 output.println("}");
4264 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
4265 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", "+ generateTemp(fm, fsen.getSrc(), lb) +", "+type+");");
4267 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4270 } else if (state.DSM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4271 Integer statussrc=locality.getNodePreTempInfo(lb,fsen).get(fsen.getSrc());
4272 Integer statusdst=locality.getNodePreTempInfo(lb,fsen).get(fsen.getDst());
4273 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4274 boolean dstglobal=statusdst==LocalityAnalysis.GLOBAL;
4275 boolean dstlocal=(statusdst==LocalityAnalysis.LOCAL)||(statusdst==LocalityAnalysis.EITHER);
4278 if (wb.needBarrier(fsen))
4279 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___localcopy___))|=DIRTY;");
4280 } else if (dstlocal) {
4281 /** Check if we need to copy */
4282 String dst=generateTemp(fm, fsen.getDst(),lb);
4283 output.println("if(!"+dst+"->"+localcopystr+") {");
4284 /* Link object into list */
4285 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4286 output.println(revertptr+"=revertlist;");
4287 if ((GENERATEPRECISEGC) || this.state.MULTICOREGC)
4288 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4290 output.println("COPY_OBJ("+dst+");");
4291 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4292 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4293 output.println("}");
4295 System.out.println("Node: "+fsen);
4296 System.out.println(lb);
4297 System.out.println("statusdst="+statusdst);
4298 System.out.println(fm.printMethod());
4299 throw new Error("Unknown array type");
4302 output.println("{");
4303 String src=generateTemp(fm, fsen.getSrc(), lb);
4304 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4305 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
4306 output.println("}");
4308 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4311 if (state.FASTCHECK) {
4312 String dst=generateTemp(fm, fsen.getDst(),lb);
4313 output.println("if(!"+dst+"->"+localcopystr+") {");
4314 /* Link object into list */
4315 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4316 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4318 output.println("COPY_OBJ("+dst+");");
4319 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4320 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4321 output.println("}");
4323 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4327 protected void generateFlatNew(FlatMethod fm, LocalityBinding lb, FlatNew fn, PrintWriter output) {
4328 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
4329 //Stash pointer in case of GC
4330 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4331 output.println(revertptr+"=revertlist;");
4333 if (state.SINGLETM) {
4334 if (fn.getType().isArray()) {
4335 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4336 if (locality.getAtomic(lb).get(fn).intValue()>0) {
4337 //inside transaction
4338 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4340 //outside transaction
4341 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4344 if (locality.getAtomic(lb).get(fn).intValue()>0) {
4345 //inside transaction
4346 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4348 //outside transaction
4349 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4352 } else if (fn.getType().isArray()) {
4353 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4354 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4355 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4356 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4357 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4359 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4362 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4363 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");");
4364 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4365 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4367 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
4370 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
4371 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4372 String dst=generateTemp(fm,fn.getDst(),lb);
4373 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
4374 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4375 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4377 if (state.FASTCHECK) {
4378 String dst=generateTemp(fm,fn.getDst(),lb);
4379 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
4380 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4381 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4385 private void generateFlatTagDeclaration(FlatMethod fm, LocalityBinding lb, FlatTagDeclaration fn, PrintWriter output) {
4386 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4387 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
4389 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+state.getTagId(fn.getType())+");");
4393 private void generateFlatOpNode(FlatMethod fm, LocalityBinding lb, FlatOpNode fon, PrintWriter output) {
4394 if (fon.getRight()!=null) {
4395 if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
4396 if (fon.getLeft().getType().isLong())
4397 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
4399 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned int)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
4401 } else if (dc!=null) {
4402 output.print(generateTemp(fm, fon.getDest(),lb)+" = (");
4403 if (fon.getLeft().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
4404 output.print("(void *)");
4405 if (dc.getNeedLeftSrcTrans(lb, fon))
4406 output.print("("+generateTemp(fm, fon.getLeft(),lb)+"!=NULL?"+generateTemp(fm, fon.getLeft(),lb)+"->"+oidstr+":NULL)");
4408 output.print(generateTemp(fm, fon.getLeft(),lb));
4409 output.print(")"+fon.getOp().toString()+"(");
4410 if (fon.getRight().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
4411 output.print("(void *)");
4412 if (dc.getNeedRightSrcTrans(lb, fon))
4413 output.println("("+generateTemp(fm, fon.getRight(),lb)+"!=NULL?"+generateTemp(fm, fon.getRight(),lb)+"->"+oidstr+":NULL));");
4415 output.println(generateTemp(fm,fon.getRight(),lb)+");");
4417 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+fon.getOp().toString()+generateTemp(fm,fon.getRight(),lb)+";");
4418 } else if (fon.getOp().getOp()==Operation.ASSIGN)
4419 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
4420 else if (fon.getOp().getOp()==Operation.UNARYPLUS)
4421 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
4422 else if (fon.getOp().getOp()==Operation.UNARYMINUS)
4423 output.println(generateTemp(fm, fon.getDest(),lb)+" = -"+generateTemp(fm, fon.getLeft(),lb)+";");
4424 else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
4425 output.println(generateTemp(fm, fon.getDest(),lb)+" = !"+generateTemp(fm, fon.getLeft(),lb)+";");
4426 else if (fon.getOp().getOp()==Operation.COMP)
4427 output.println(generateTemp(fm, fon.getDest(),lb)+" = ~"+generateTemp(fm, fon.getLeft(),lb)+";");
4428 else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
4429 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+"->fses==NULL;");
4431 output.println(generateTemp(fm, fon.getDest(),lb)+fon.getOp().toString()+generateTemp(fm, fon.getLeft(),lb)+";");
4434 private void generateFlatCastNode(FlatMethod fm, LocalityBinding lb, FlatCastNode fcn, PrintWriter output) {
4435 /* TODO: Do type check here */
4436 if (fcn.getType().isArray()) {
4437 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
4438 } else if (fcn.getType().isClass())
4439 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
4441 output.println(generateTemp(fm,fcn.getDst(),lb)+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc(),lb)+";");
4444 private void generateFlatLiteralNode(FlatMethod fm, LocalityBinding lb, FlatLiteralNode fln, PrintWriter output) {
4445 if (fln.getValue()==null)
4446 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
4447 else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
4448 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4449 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
4450 //Stash pointer in case of GC
4451 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4452 output.println(revertptr+"=revertlist;");
4454 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
4455 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
4456 //Stash pointer in case of GC
4457 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4458 output.println("revertlist="+revertptr+";");
4461 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
4463 } else if (fln.getType().isBoolean()) {
4464 if (((Boolean)fln.getValue()).booleanValue())
4465 output.println(generateTemp(fm, fln.getDst(),lb)+"=1;");
4467 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
4468 } else if (fln.getType().isChar()) {
4469 String st=FlatLiteralNode.escapeString(fln.getValue().toString());
4470 output.println(generateTemp(fm, fln.getDst(),lb)+"='"+st+"';");
4471 } else if (fln.getType().isLong()) {
4472 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+"LL;");
4474 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+";");
4477 protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) {
4478 if (frn.getReturnTemp()!=null) {
4479 if (frn.getReturnTemp().getType().isPtr())
4480 output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";");
4482 output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";");
4484 output.println("return;");
4488 protected void generateStoreFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
4491 //only record if this group has more than one exit
4492 if (branchanalysis.numJumps(fcb)>1) {
4493 left=branchanalysis.jumpValue(fcb, 0);
4494 right=branchanalysis.jumpValue(fcb, 1);
4496 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") {");
4498 output.println("STOREBRANCH("+right+");");
4499 output.println("goto "+label+";");
4500 output.println("}");
4502 output.println("STOREBRANCH("+left+");");
4505 protected void generateFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
4506 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") goto "+label+";");
4509 /** This method generates header information for the method or
4510 * task referenced by the Descriptor des. */
4511 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) {
4512 generateHeader(fm, lb, des, output, false);
4515 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output, boolean addSESErecord) {
4517 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : des);
4518 MethodDescriptor md=null;
4519 TaskDescriptor task=null;
4520 if (des instanceof MethodDescriptor)
4521 md=(MethodDescriptor) des;
4523 task=(TaskDescriptor) des;
4525 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
4527 if (md!=null&&md.getReturnType()!=null) {
4528 if (md.getReturnType().isClass()||md.getReturnType().isArray())
4529 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
4531 output.print(md.getReturnType().getSafeSymbol()+" ");
4533 //catch the constructor case
4534 output.print("void ");
4536 if (state.DSM||state.SINGLETM) {
4537 output.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
4539 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
4541 output.print(task.getSafeSymbol()+"(");
4543 boolean printcomma=false;
4544 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4546 if (state.DSM||state.SINGLETM) {
4547 output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
4549 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
4551 output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
4557 for(int i=0; i<objectparams.numPrimitives(); i++) {
4558 TempDescriptor temp=objectparams.getPrimitive(i);
4562 if (temp.getType().isClass()||temp.getType().isArray())
4563 output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
4565 output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
4567 output.println(") {");
4568 } else if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
4569 /* Imprecise Task */
4570 output.println("void * parameterarray[]) {");
4571 /* Unpack variables */
4572 for(int i=0; i<objectparams.numPrimitives(); i++) {
4573 TempDescriptor temp=objectparams.getPrimitive(i);
4574 output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
4576 for(int i=0; i<fm.numTags(); i++) {
4577 TempDescriptor temp=fm.getTag(i);
4578 int offset=i+objectparams.numPrimitives();
4579 output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
4582 if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
4583 maxtaskparams=objectparams.numPrimitives()+fm.numTags();
4584 } else output.println(") {");
4587 public void generateFlatFlagActionNode(FlatMethod fm, LocalityBinding lb, FlatFlagActionNode ffan, PrintWriter output) {
4588 output.println("/* FlatFlagActionNode */");
4591 /* Process tag changes */
4592 Relation tagsettable=new Relation();
4593 Relation tagcleartable=new Relation();
4595 Iterator tagsit=ffan.getTempTagPairs();
4596 while (tagsit.hasNext()) {
4597 TempTagPair ttp=(TempTagPair) tagsit.next();
4598 TempDescriptor objtmp=ttp.getTemp();
4599 TagDescriptor tag=ttp.getTag();
4600 TempDescriptor tagtmp=ttp.getTagTemp();
4601 boolean tagstatus=ffan.getTagChange(ttp);
4603 tagsettable.put(objtmp, tagtmp);
4605 tagcleartable.put(objtmp, tagtmp);
4610 Hashtable flagandtable=new Hashtable();
4611 Hashtable flagortable=new Hashtable();
4613 /* Process flag changes */
4614 Iterator flagsit=ffan.getTempFlagPairs();
4615 while(flagsit.hasNext()) {
4616 TempFlagPair tfp=(TempFlagPair)flagsit.next();
4617 TempDescriptor temp=tfp.getTemp();
4618 Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
4619 FlagDescriptor flag=tfp.getFlag();
4621 //Newly allocate objects that don't set any flags case
4622 if (flagortable.containsKey(temp)) {
4626 flagortable.put(temp,new Integer(mask));
4628 int flagid=1<<((Integer)flagtable.get(flag)).intValue();
4629 boolean flagstatus=ffan.getFlagChange(tfp);
4632 if (flagortable.containsKey(temp)) {
4633 mask=((Integer)flagortable.get(temp)).intValue();
4636 flagortable.put(temp,new Integer(mask));
4638 int mask=0xFFFFFFFF;
4639 if (flagandtable.containsKey(temp)) {
4640 mask=((Integer)flagandtable.get(temp)).intValue();
4642 mask&=(0xFFFFFFFF^flagid);
4643 flagandtable.put(temp,new Integer(mask));
4649 HashSet flagtagset=new HashSet();
4650 flagtagset.addAll(flagortable.keySet());
4651 flagtagset.addAll(flagandtable.keySet());
4652 flagtagset.addAll(tagsettable.keySet());
4653 flagtagset.addAll(tagcleartable.keySet());
4655 Iterator ftit=flagtagset.iterator();
4656 while(ftit.hasNext()) {
4657 TempDescriptor temp=(TempDescriptor)ftit.next();
4660 Set tagtmps=tagcleartable.get(temp);
4661 if (tagtmps!=null) {
4662 Iterator tagit=tagtmps.iterator();
4663 while(tagit.hasNext()) {
4664 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
4665 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
4666 output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4668 output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4672 tagtmps=tagsettable.get(temp);
4673 if (tagtmps!=null) {
4674 Iterator tagit=tagtmps.iterator();
4675 while(tagit.hasNext()) {
4676 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
4677 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
4678 output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4680 output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp, lb)+", "+generateTemp(fm,tagtmp, lb)+");");
4685 int andmask=0xFFFFFFF;
4687 if (flagortable.containsKey(temp))
4688 ormask=((Integer)flagortable.get(temp)).intValue();
4689 if (flagandtable.containsKey(temp))
4690 andmask=((Integer)flagandtable.get(temp)).intValue();
4691 generateFlagOrAnd(ffan, fm, lb, temp, output, ormask, andmask);
4692 generateObjectDistribute(ffan, fm, lb, temp, output);
4696 protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp,
4697 PrintWriter output, int ormask, int andmask) {
4698 if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
4699 output.println("flagorandinit("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
4701 output.println("flagorand("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
4705 protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, PrintWriter output) {
4706 output.println("enqueueObject("+generateTemp(fm, temp, lb)+");");
4709 void generateOptionalHeader(PrintWriter headers) {
4712 headers.println("#include \"task.h\"\n\n");
4713 headers.println("#ifndef _OPTIONAL_STRUCT_");
4714 headers.println("#define _OPTIONAL_STRUCT_");
4716 //STRUCT PREDICATEMEMBER
4717 headers.println("struct predicatemember{");
4718 headers.println("int type;");
4719 headers.println("int numdnfterms;");
4720 headers.println("int * flags;");
4721 headers.println("int numtags;");
4722 headers.println("int * tags;\n};\n\n");
4724 //STRUCT OPTIONALTASKDESCRIPTOR
4725 headers.println("struct optionaltaskdescriptor{");
4726 headers.println("struct taskdescriptor * task;");
4727 headers.println("int index;");
4728 headers.println("int numenterflags;");
4729 headers.println("int * enterflags;");
4730 headers.println("int numpredicatemembers;");
4731 headers.println("struct predicatemember ** predicatememberarray;");
4732 headers.println("};\n\n");
4734 //STRUCT TASKFAILURE
4735 headers.println("struct taskfailure {");
4736 headers.println("struct taskdescriptor * task;");
4737 headers.println("int index;");
4738 headers.println("int numoptionaltaskdescriptors;");
4739 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
4741 //STRUCT FSANALYSISWRAPPER
4742 headers.println("struct fsanalysiswrapper{");
4743 headers.println("int flags;");
4744 headers.println("int numtags;");
4745 headers.println("int * tags;");
4746 headers.println("int numtaskfailures;");
4747 headers.println("struct taskfailure ** taskfailurearray;");
4748 headers.println("int numoptionaltaskdescriptors;");
4749 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
4751 //STRUCT CLASSANALYSISWRAPPER
4752 headers.println("struct classanalysiswrapper{");
4753 headers.println("int type;");
4754 headers.println("int numotd;");
4755 headers.println("struct optionaltaskdescriptor ** otdarray;");
4756 headers.println("int numfsanalysiswrappers;");
4757 headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
4759 headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
4761 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
4762 while(taskit.hasNext()) {
4763 TaskDescriptor td=(TaskDescriptor)taskit.next();
4764 headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
4769 //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
4770 int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
4771 int predicateindex = 0;
4772 //iterate through the classes concerned by the predicate
4773 Set c_vard = predicate.vardescriptors;
4774 Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
4777 for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext();) {
4778 VarDescriptor vard = (VarDescriptor)vard_it.next();
4779 TypeDescriptor typed = vard.getType();
4781 //generate for flags
4782 HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
4783 output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4785 if (fen_hashset!=null) {
4786 for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext();) {
4787 FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
4789 DNFFlag dflag=fen.getDNF();
4790 numberterms+=dflag.size();
4792 Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
4794 for(int j=0; j<dflag.size(); j++) {
4796 output.println(",");
4797 Vector term=dflag.get(j);
4800 for(int k=0; k<term.size(); k++) {
4801 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
4802 FlagDescriptor fd=dfa.getFlag();
4803 boolean negated=dfa.getNegated();
4804 int flagid=1<<((Integer)flags.get(fd)).intValue();
4809 output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
4814 output.println("};\n");
4817 TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
4818 output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4821 for(int j=0; j<tagel.numTags(); j++) {
4823 output.println(",");
4824 TempDescriptor tmp=tagel.getTemp(j);
4825 if (!slotnumber.containsKey(tmp)) {
4826 Integer slotint=new Integer(current_slot++);
4827 slotnumber.put(tmp,slotint);
4829 int slot=slotnumber.get(tmp).intValue();
4830 output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
4832 numtags = tagel.numTags();
4834 output.println("};");
4836 //store the result into a predicatemember struct
4837 output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
4838 output.println("/*type*/"+typed.getClassDesc().getId()+",");
4839 output.println("/* number of dnf terms */"+numberterms+",");
4840 output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4841 output.println("/* number of tag */"+numtags+",");
4842 output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4843 output.println("};\n");
4848 //generate an array that stores the entire predicate
4849 output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4850 for( int j = 0; j<predicateindex; j++) {
4851 if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4852 else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4854 output.println("};\n");
4855 return predicateindex;
4859 void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
4860 generateOptionalHeader(headers);
4862 output.println("#include \"optionalstruct.h\"\n\n");
4863 output.println("#include \"stdlib.h\"\n");
4865 HashSet processedcd = new HashSet();
4867 Enumeration e = safeexecution.keys();
4868 while (e.hasMoreElements()) {
4871 ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
4872 Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp); //will be used several times
4874 //Generate the struct of optionals
4875 Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
4876 numotd = c_otd.size();
4877 if(maxotd<numotd) maxotd = numotd;
4878 if( !c_otd.isEmpty() ) {
4879 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
4880 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
4882 //generate the int arrays for the predicate
4883 Predicate predicate = otd.predicate;
4884 int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
4885 TreeSet<Integer> fsset=new TreeSet<Integer>();
4886 //iterate through possible FSes corresponding to
4887 //the state when entering
4889 for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext();) {
4890 FlagState fs = (FlagState)fses.next();
4892 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
4893 FlagDescriptor flagd = (FlagDescriptor)flags.next();
4894 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
4897 fsset.add(new Integer(flagid));
4898 //tag information not needed because tag
4899 //changes are not tolerated.
4902 output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4903 boolean needcomma=false;
4904 for(Iterator<Integer> it=fsset.iterator(); it.hasNext();) {
4907 output.println(it.next());
4910 output.println("};\n");
4913 //generate optionaltaskdescriptor that actually
4914 //includes exit fses, predicate and the task
4916 output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
4917 output.println("&task_"+otd.td.getSafeSymbol()+",");
4918 output.println("/*index*/"+otd.getIndex()+",");
4919 output.println("/*number of enter flags*/"+fsset.size()+",");
4920 output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4921 output.println("/*number of members */"+predicateindex+",");
4922 output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4923 output.println("};\n");
4927 // if there are no optionals, there is no need to build the rest of the struct
4929 output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
4930 c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
4931 if( !c_otd.isEmpty() ) {
4932 boolean needcomma=false;
4933 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
4934 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
4936 output.println(",");
4938 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4941 output.println("};\n");
4943 //get all the possible flagstates reachable by an object
4944 Hashtable hashtbtemp = safeexecution.get(cdtemp);
4946 TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
4947 fsts.addAll(hashtbtemp.keySet());
4948 for(Iterator fsit=fsts.iterator(); fsit.hasNext();) {
4949 FlagState fs = (FlagState)fsit.next();
4952 //get the set of OptionalTaskDescriptors corresponding
4953 HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
4954 //iterate through the OptionalTaskDescriptors and
4955 //store the pointers to the optionals struct (see on
4956 //top) into an array
4958 output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
4959 for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext();) {
4960 OptionalTaskDescriptor mm = mos.next();
4962 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
4964 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4967 output.println("};\n");
4969 //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
4972 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
4973 FlagDescriptor flagd = (FlagDescriptor)flags.next();
4974 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
4978 //process tag information
4981 boolean first = true;
4982 Enumeration tag_enum = fs.getTags();
4983 output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
4984 while(tag_enum.hasMoreElements()) {
4986 TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
4990 output.println(", ");
4991 output.println("/*tagid*/"+state.getTagId(tagd));
4993 output.println("};");
4995 Set<TaskIndex> tiset=sa.getTaskIndex(fs);
4996 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
4997 TaskIndex ti=itti.next();
5001 Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
5003 output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
5004 boolean needcomma=false;
5005 for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext();) {
5006 OptionalTaskDescriptor otd=otdit.next();
5010 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5012 output.println("};");
5014 output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
5015 output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
5016 output.print(ti.getIndex()+", ");
5017 output.print(otdset.size()+", ");
5018 output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
5019 output.println("};");
5022 tiset=sa.getTaskIndex(fs);
5023 boolean needcomma=false;
5025 output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
5026 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
5027 TaskIndex ti=itti.next();
5028 if (ti.isRuntime()) {
5035 output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
5037 output.println("};\n");
5039 //Store the result in fsanalysiswrapper
5041 output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
5042 output.println("/*flag*/"+flagid+",");
5043 output.println("/* number of tags*/"+tagcounter+",");
5044 output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
5045 output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
5046 output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
5047 output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
5048 output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
5049 output.println("};\n");
5053 //Build the array of fsanalysiswrappers
5054 output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
5055 boolean needcomma=false;
5056 for(int i = 0; i<fscounter; i++) {
5057 if (needcomma) output.print(",");
5058 output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
5061 output.println("};");
5063 //Build the classanalysiswrapper referring to the previous array
5064 output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
5065 output.println("/*type*/"+cdtemp.getId()+",");
5066 output.println("/*numotd*/"+numotd+",");
5067 output.println("otdarray"+cdtemp.getSafeSymbol()+",");
5068 output.println("/* number of fsanalysiswrappers */"+fscounter+",");
5069 output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
5070 processedcd.add(cdtemp);
5073 //build an array containing every classes for which code has been build
5074 output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
5075 for(int i=0; i<state.numClasses(); i++) {
5076 ClassDescriptor cn=cdarray[i];
5079 if ((cn != null) && (processedcd.contains(cn)))
5080 output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
5082 output.print("NULL");
5084 output.println("};");
5086 output.println("#define MAXOTD "+maxotd);
5087 headers.println("#endif");
5090 public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
5091 Relation r=new Relation();
5092 for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext();) {
5093 OptionalTaskDescriptor otd=otdit.next();
5094 TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
5098 LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
5099 for(Iterator it=r.keySet().iterator(); it.hasNext();) {
5100 Set s=r.get(it.next());
5101 for(Iterator it2=s.iterator(); it2.hasNext();) {
5102 OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
5110 protected void outputTransCode(PrintWriter output) {