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.DelayComputation;
23 import Analysis.CallGraph.CallGraph;
24 import Analysis.Prefetch.*;
25 import Analysis.Loops.WriteBarrier;
26 import Analysis.Loops.GlobalFieldType;
27 import Analysis.Locality.TypeAnalysis;
28 import Analysis.MLP.MLPAnalysis;
29 import Analysis.MLP.VariableSourceToken;
30 import Analysis.MLP.CodePlan;
31 import Analysis.MLP.SESEandAgePair;
33 public class BuildCode {
36 Hashtable paramstable;
41 String localsprefix="___locals___";
42 String localsprefixaddr="&"+localsprefix;
43 String localsprefixderef=localsprefix+".";
44 String fcrevert="___fcrevert___";
45 String paramsprefix="___params___";
46 String oidstr="___nextobject___";
47 String nextobjstr="___nextobject___";
48 String localcopystr="___localcopy___";
49 public static boolean GENERATEPRECISEGC=false;
50 public static String PREFIX="";
51 public static String arraytype="ArrayObject";
52 public static int flagcount = 0;
55 protected int maxtaskparams=0;
56 private int maxcount=0;
57 ClassDescriptor[] cdarray;
58 TypeDescriptor[] arraytable;
59 LocalityAnalysis locality;
60 Hashtable<LocalityBinding, TempDescriptor> reverttable;
61 Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>> backuptable;
65 String mlperrstr = "if(status != 0) { "+
66 "sprintf(errmsg, \"MLP error at %s:%d\", __FILE__, __LINE__); "+
67 "perror(errmsg); exit(-1); }";
68 Hashtable<FlatSESEEnterNode, FlatMethod> sese2bogusFlatMeth;
69 boolean nonSESEpass=true;
72 DiscoverConflicts recorddc;
73 DelayComputation delaycomp;
76 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa) {
77 this(st, temptovar, typeutil, null, sa, pa, null);
80 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa) {
81 this(st, temptovar, typeutil, null, sa, pa, mlpa);
84 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, PrefetchAnalysis pa, MLPAnalysis mlpa) {
85 this(st, temptovar, typeutil, locality, null, pa, mlpa);
88 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa) {
93 callgraph=new CallGraph(state);
95 oidstr="___objlocation___";
96 this.temptovar=temptovar;
97 paramstable=new Hashtable();
98 tempstable=new Hashtable();
99 fieldorder=new Hashtable();
100 flagorder=new Hashtable();
101 this.typeutil=typeutil;
102 virtualcalls=new Virtual(state,locality);
103 if (locality!=null) {
104 this.locality=locality;
105 this.reverttable=new Hashtable<LocalityBinding, TempDescriptor>();
106 this.backuptable=new Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>>();
107 this.wb=new WriteBarrier(locality, st);
109 if (state.SINGLETM&&state.DCOPTS) {
110 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
111 this.dc=new DiscoverConflicts(locality, st, typeanalysis, null);
114 if (state.DELAYCOMP) {
115 //TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
116 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
117 GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
118 delaycomp=new DelayComputation(locality, st, typeanalysis, gft);
119 delaycomp.doAnalysis();
120 dc=delaycomp.getConflicts();
121 recorddc=new DiscoverConflicts(locality, st, typeanalysis, delaycomp.getCannotDelayMap(), true, true, null);
122 recorddc.doAnalysis();
126 sese2bogusFlatMeth = new Hashtable<FlatSESEEnterNode, FlatMethod>();
130 /** The buildCode method outputs C code for all the methods. The Flat
131 * versions of the methods must already be generated and stored in
132 * the State object. */
134 public void buildCode() {
135 /* Create output streams to write to */
136 PrintWriter outclassdefs=null;
137 PrintWriter outstructs=null;
138 PrintWriter outrepairstructs=null;
139 PrintWriter outmethodheader=null;
140 PrintWriter outmethod=null;
141 PrintWriter outvirtual=null;
142 PrintWriter outtask=null;
143 PrintWriter outtaskdefs=null;
144 PrintWriter outoptionalarrays=null;
145 PrintWriter optionalheaders=null;
148 outstructs=new PrintWriter(new FileOutputStream(PREFIX+"structdefs.h"), true);
149 outmethodheader=new PrintWriter(new FileOutputStream(PREFIX+"methodheaders.h"), true);
150 outclassdefs=new PrintWriter(new FileOutputStream(PREFIX+"classdefs.h"), true);
151 outmethod=new PrintWriter(new FileOutputStream(PREFIX+"methods.c"), true);
152 outvirtual=new PrintWriter(new FileOutputStream(PREFIX+"virtualtable.h"), true);
154 outtask=new PrintWriter(new FileOutputStream(PREFIX+"task.h"), true);
155 outtaskdefs=new PrintWriter(new FileOutputStream(PREFIX+"taskdefs.c"), true);
156 if (state.OPTIONAL) {
157 outoptionalarrays=new PrintWriter(new FileOutputStream(PREFIX+"optionalarrays.c"), true);
158 optionalheaders=new PrintWriter(new FileOutputStream(PREFIX+"optionalstruct.h"), true);
161 if (state.structfile!=null) {
162 outrepairstructs=new PrintWriter(new FileOutputStream(PREFIX+state.structfile+".struct"), true);
164 } catch (Exception e) {
169 /* Build the virtual dispatch tables */
170 buildVirtualTables(outvirtual);
172 /* Output includes */
173 outmethodheader.println("#ifndef METHODHEADERS_H");
174 outmethodheader.println("#define METHODHEADERS_H");
175 outmethodheader.println("#include \"structdefs.h\"");
177 outmethodheader.println("#include \"dstm.h\"");
178 if (state.SINGLETM) {
179 outmethodheader.println("#include \"tm.h\"");
180 outmethodheader.println("#include \"delaycomp.h\"");
182 if (state.ABORTREADERS) {
183 outmethodheader.println("#include \"abortreaders.h\"");
184 outmethodheader.println("#include <setjmp.h>");
187 outmethodheader.println("#include <stdlib.h>");
188 outmethodheader.println("#include <stdio.h>");
189 outmethodheader.println("#include \"mlp_runtime.h\"");
192 /* Output Structures */
193 outputStructs(outstructs);
195 // Output the C class declarations
196 // These could mutually reference each other
197 outputClassDeclarations(outclassdefs);
199 // Output function prototypes and structures for parameters
200 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
201 while(it.hasNext()) {
202 ClassDescriptor cn=(ClassDescriptor)it.next();
203 generateCallStructs(cn, outclassdefs, outstructs, outmethodheader);
205 outclassdefs.close();
208 /* Map flags to integers */
209 /* The runtime keeps track of flags using these integers */
210 it=state.getClassSymbolTable().getDescriptorsIterator();
211 while(it.hasNext()) {
212 ClassDescriptor cn=(ClassDescriptor)it.next();
216 generateTaskStructs(outstructs, outmethodheader);
218 /* Outputs generic task structures if this is a task
220 outputTaskTypes(outtask);
223 /* Build the actual methods */
224 outputMethods(outmethod);
226 // Output function prototypes and structures for SESE's and code
230 // first generate code for each sese's internals
231 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
232 FlatSESEEnterNode fsen = seseit.next();
233 generateMethodSESE(fsen, null, outstructs, outmethodheader, outmethod);
236 // then write the invokeSESE switch to decouple scheduler
237 // from having to do unique details of sese invocation
238 generateSESEinvocationMethod(outmethodheader, outmethod);
242 /* Output code for tasks */
243 outputTaskCode(outtaskdefs, outmethod);
245 /* Record maximum number of task parameters */
246 outstructs.println("#define MAXTASKPARAMS "+maxtaskparams);
247 } else if (state.main!=null) {
248 /* Generate main method */
249 outputMainMethod(outmethod);
252 /* Generate information for task with optional parameters */
253 if (state.TASK&&state.OPTIONAL) {
254 generateOptionalArrays(outoptionalarrays, optionalheaders, state.getAnalysisResult(), state.getOptionalTaskDescriptors());
255 outoptionalarrays.close();
258 /* Output structure definitions for repair tool */
259 if (state.structfile!=null) {
260 buildRepairStructs(outrepairstructs);
261 outrepairstructs.close();
265 outmethodheader.println("#endif");
266 outmethodheader.close();
268 outstructs.println("#endif");
273 /* This code just generates the main C method for java programs.
274 * The main C method packs up the arguments into a string array
275 * and passes it to the java main method. */
277 private void outputMainMethod(PrintWriter outmethod) {
278 outmethod.println("int main(int argc, const char *argv[]) {");
279 outmethod.println(" int i;");
281 outmethod.println(" mlpInit( "+mlpa.getAllSESEs().size()+", "+mlpa.getMaxSESEage()+" );");
284 outmethod.println("#ifdef TRANSSTATS \n");
285 outmethod.println("handle();\n");
286 outmethod.println("#endif\n");
288 if (state.THREAD||state.DSM||state.SINGLETM) {
289 outmethod.println("initializethreads();");
292 outmethod.println("if (dstmStartup(argv[1])) {");
293 if (GENERATEPRECISEGC) {
294 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-2);");
296 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-2);");
299 if (GENERATEPRECISEGC) {
300 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1);");
302 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1);");
306 outmethod.println(" for(i=2;i<argc;i++) {");
308 outmethod.println(" for(i=1;i<argc;i++) {");
309 outmethod.println(" int length=strlen(argv[i]);");
310 if (GENERATEPRECISEGC) {
311 outmethod.println(" struct ___String___ *newstring=NewString(NULL, argv[i], length);");
313 outmethod.println(" struct ___String___ *newstring=NewString(argv[i], length);");
316 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-2]=newstring;");
318 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-1]=newstring;");
319 outmethod.println(" }");
321 MethodDescriptor md=typeutil.getMain();
322 ClassDescriptor cd=typeutil.getMainClass();
324 outmethod.println(" {");
325 if (GENERATEPRECISEGC) {
326 if (state.DSM||state.SINGLETM) {
327 outmethod.print(" struct "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
329 outmethod.print(" struct "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
330 outmethod.println("1, NULL,"+"stringarray};");
331 if (state.DSM||state.SINGLETM)
332 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
334 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
336 if (state.DSM||state.SINGLETM)
337 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
339 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
341 outmethod.println(" }");
344 outmethod.println("}");
347 if (state.THREAD||state.DSM||state.SINGLETM) {
348 outmethod.println("pthread_mutex_lock(&gclistlock);");
349 outmethod.println("threadcount--;");
350 outmethod.println("pthread_cond_signal(&gccond);");
351 outmethod.println("pthread_mutex_unlock(&gclistlock);");
354 if (state.DSM||state.SINGLETM) {
355 outmethod.println("#ifdef TRANSSTATS \n");
356 outmethod.println("printf(\"****** Transaction Stats ******\\n\");");
357 outmethod.println("printf(\"numTransAbort= %d\\n\", numTransAbort);");
358 outmethod.println("printf(\"numTransCommit= %d\\n\", numTransCommit);");
359 outmethod.println("printf(\"nSoftAbort= %d\\n\", nSoftAbort);");
361 outmethod.println("printf(\"nchashSearch= %d\\n\", nchashSearch);");
362 outmethod.println("printf(\"nmhashSearch= %d\\n\", nmhashSearch);");
363 outmethod.println("printf(\"nprehashSearch= %d\\n\", nprehashSearch);");
364 outmethod.println("printf(\"nRemoteReadSend= %d\\n\", nRemoteSend);");
365 outmethod.println("printf(\"bytesSent= %d\\n\", bytesSent);");
366 outmethod.println("printf(\"bytesRecv= %d\\n\", bytesRecv);");
367 } else if (state.SINGLETM) {
368 outmethod.println("printf(\"nSoftAbortAbort= %d\\n\", nSoftAbortAbort);");
369 outmethod.println("printf(\"nSoftAbortCommit= %d\\n\", nSoftAbortCommit);");
370 outmethod.println("#ifdef STMSTATS\n");
371 outmethod.println("for(i=0; i<TOTALNUMCLASSANDARRAY; i++) {\n");
372 outmethod.println(" printf(\"typesCausingAbort[%d]= %d\\n\", i, typesCausingAbort[i]);\n");
373 outmethod.println("}\n");
374 outmethod.println("#endif\n");
375 outmethod.println("fflush(stdout);");
377 outmethod.println("#endif\n");
380 if (state.THREAD||state.SINGLETM)
381 outmethod.println("pthread_exit(NULL);");
383 outmethod.println("}");
386 /* This method outputs code for each task. */
388 private void outputTaskCode(PrintWriter outtaskdefs, PrintWriter outmethod) {
389 /* Compile task based program */
390 outtaskdefs.println("#include \"task.h\"");
391 outtaskdefs.println("#include \"methodheaders.h\"");
392 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
393 while(taskit.hasNext()) {
394 TaskDescriptor td=(TaskDescriptor)taskit.next();
395 FlatMethod fm=state.getMethodFlat(td);
396 generateFlatMethod(fm, null, outmethod);
397 generateTaskDescriptor(outtaskdefs, fm, td);
400 //Output task descriptors
401 taskit=state.getTaskSymbolTable().getDescriptorsIterator();
402 outtaskdefs.println("struct taskdescriptor * taskarray[]= {");
404 while(taskit.hasNext()) {
405 TaskDescriptor td=(TaskDescriptor)taskit.next();
409 outtaskdefs.println(",");
410 outtaskdefs.print("&task_"+td.getSafeSymbol());
412 outtaskdefs.println("};");
414 outtaskdefs.println("int numtasks="+state.getTaskSymbolTable().getValueSet().size()+";");
417 /* This method outputs most of the methods.c file. This includes
418 * some standard includes and then an array with the sizes of
419 * objets and array that stores supertype and then the code for
420 * the Java methods.. */
422 protected void outputMethods(PrintWriter outmethod) {
423 outmethod.println("#include \"methodheaders.h\"");
424 outmethod.println("#include \"virtualtable.h\"");
425 outmethod.println("#include \"runtime.h\"");
427 outmethod.println("#include \"addPrefetchEnhance.h\"");
428 outmethod.println("#include \"localobjects.h\"");
430 if (state.FASTCHECK) {
431 outmethod.println("#include \"localobjects.h\"");
433 if(state.MULTICORE) {
434 outmethod.println("#include \"task.h\"");
435 outmethod.println("#include \"multicoreruntime.h\"");
436 outmethod.println("#include \"runtime_arch.h\"");
438 if (state.THREAD||state.DSM||state.SINGLETM)
439 outmethod.println("#include <thread.h>");
440 if (state.main!=null) {
441 outmethod.println("#include <string.h>");
443 if (state.CONSCHECK) {
444 outmethod.println("#include \"checkers.h\"");
447 outmethod.println("#include <stdlib.h>");
448 outmethod.println("#include <stdio.h>");
449 outmethod.println("#include \"mlp_runtime.h\"");
453 //Store the sizes of classes & array elements
454 generateSizeArray(outmethod);
456 //Store table of supertypes
457 generateSuperTypeTable(outmethod);
459 //Store the layout of classes
460 generateLayoutStructs(outmethod);
462 /* Generate code for methods */
463 if (state.DSM||state.SINGLETM) {
464 for(Iterator<LocalityBinding> lbit=locality.getLocalityBindings().iterator(); lbit.hasNext();) {
465 LocalityBinding lb=lbit.next();
466 MethodDescriptor md=lb.getMethod();
467 FlatMethod fm=state.getMethodFlat(md);
469 if (!md.getModifiers().isNative()) {
470 generateFlatMethod(fm, lb, outmethod);
474 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
475 while(classit.hasNext()) {
476 ClassDescriptor cn=(ClassDescriptor)classit.next();
477 Iterator methodit=cn.getMethods();
478 while(methodit.hasNext()) {
479 /* Classify parameters */
480 MethodDescriptor md=(MethodDescriptor)methodit.next();
481 FlatMethod fm=state.getMethodFlat(md);
482 if (!md.getModifiers().isNative()) {
483 generateFlatMethod(fm, null, outmethod);
490 protected void outputStructs(PrintWriter outstructs) {
491 outstructs.println("#ifndef STRUCTDEFS_H");
492 outstructs.println("#define STRUCTDEFS_H");
493 outstructs.println("#include \"classdefs.h\"");
494 outstructs.println("#ifndef INTPTR");
495 outstructs.println("#ifdef BIT64");
496 outstructs.println("#define INTPTR long");
497 outstructs.println("#else");
498 outstructs.println("#define INTPTR int");
499 outstructs.println("#endif");
500 outstructs.println("#endif");
502 /* Output #defines that the runtime uses to determine type
503 * numbers for various objects it needs */
504 outstructs.println("#define MAXCOUNT "+maxcount);
505 if (state.DSM||state.SINGLETM) {
506 LocalityBinding lb=new LocalityBinding(typeutil.getRun(), false);
508 lb.setGlobalThis(LocalityAnalysis.GLOBAL);
509 else if (state.SINGLETM)
510 lb.setGlobalThis(LocalityAnalysis.NORMAL);
511 outstructs.println("#define RUNMETHOD "+virtualcalls.getLocalityNumber(lb));
514 outstructs.println("#define STRINGARRAYTYPE "+
515 (state.getArrayNumber(
516 (new TypeDescriptor(typeutil.getClass(TypeUtil.StringClass))).makeArray(state))+state.numClasses()));
518 outstructs.println("#define OBJECTARRAYTYPE "+
519 (state.getArrayNumber(
520 (new TypeDescriptor(typeutil.getClass(TypeUtil.ObjectClass))).makeArray(state))+state.numClasses()));
523 outstructs.println("#define STRINGTYPE "+typeutil.getClass(TypeUtil.StringClass).getId());
524 outstructs.println("#define CHARARRAYTYPE "+
525 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.CHAR)).makeArray(state))+state.numClasses()));
527 outstructs.println("#define BYTEARRAYTYPE "+
528 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state))+state.numClasses()));
530 outstructs.println("#define BYTEARRAYARRAYTYPE "+
531 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state).makeArray(state))+state.numClasses()));
533 outstructs.println("#define NUMCLASSES "+state.numClasses());
534 int totalClassSize = state.numClasses() + state.numArrays();
535 outstructs.println("#define TOTALNUMCLASSANDARRAY "+ totalClassSize);
537 outstructs.println("#define STARTUPTYPE "+typeutil.getClass(TypeUtil.StartupClass).getId());
538 outstructs.println("#define TAGTYPE "+typeutil.getClass(TypeUtil.TagClass).getId());
539 outstructs.println("#define TAGARRAYTYPE "+
540 (state.getArrayNumber(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)).makeArray(state))+state.numClasses()));
544 protected void outputClassDeclarations(PrintWriter outclassdefs) {
545 if (state.THREAD||state.DSM||state.SINGLETM)
546 outclassdefs.println("#include <pthread.h>");
547 outclassdefs.println("#ifndef INTPTR");
548 outclassdefs.println("#ifdef BIT64");
549 outclassdefs.println("#define INTPTR long");
550 outclassdefs.println("#else");
551 outclassdefs.println("#define INTPTR int");
552 outclassdefs.println("#endif");
553 outclassdefs.println("#endif");
555 outclassdefs.println("#include \"optionalstruct.h\"");
556 outclassdefs.println("struct "+arraytype+";");
557 /* Start by declaring all structs */
558 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
559 while(it.hasNext()) {
560 ClassDescriptor cn=(ClassDescriptor)it.next();
561 outclassdefs.println("struct "+cn.getSafeSymbol()+";");
563 outclassdefs.println("");
564 //Print out definition for array type
565 outclassdefs.println("struct "+arraytype+" {");
566 outclassdefs.println(" int type;");
568 outclassdefs.println(" pthread_t tid;");
569 outclassdefs.println(" void * lockentry;");
570 outclassdefs.println(" int lockcount;");
573 outclassdefs.println(" int flag;");
574 if(!state.MULTICORE) {
575 outclassdefs.println(" void * flagptr;");
577 outclassdefs.println(" int version;");
578 outclassdefs.println(" struct ___Object___ * original;");
579 //outclassdefs.println(" int numlocks;"); // array for locks
580 outclassdefs.println(" int * lock;");
583 outclassdefs.println(" int numfses;");
584 outclassdefs.println(" int * fses;");
587 printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs);
589 outclassdefs.println(" int ___length___;");
590 outclassdefs.println("};\n");
591 outclassdefs.println("extern int classsize[];");
592 outclassdefs.println("extern int hasflags[];");
593 outclassdefs.println("extern unsigned INTPTR * pointerarray[];");
594 outclassdefs.println("extern int supertypes[];");
597 /** Prints out definitions for generic task structures */
599 private void outputTaskTypes(PrintWriter outtask) {
600 outtask.println("#ifndef _TASK_H");
601 outtask.println("#define _TASK_H");
602 outtask.println("struct parameterdescriptor {");
603 outtask.println("int type;");
604 outtask.println("int numberterms;");
605 outtask.println("int *intarray;");
606 outtask.println("void * queue;");
607 outtask.println("int numbertags;");
608 outtask.println("int *tagarray;");
609 outtask.println("};");
611 outtask.println("struct taskdescriptor {");
612 outtask.println("void * taskptr;");
613 outtask.println("int numParameters;");
614 outtask.println(" int numTotal;");
615 outtask.println("struct parameterdescriptor **descriptorarray;");
616 outtask.println("char * name;");
617 outtask.println("};");
618 outtask.println("extern struct taskdescriptor * taskarray[];");
619 outtask.println("extern numtasks;");
620 outtask.println("#endif");
624 private void buildRepairStructs(PrintWriter outrepairstructs) {
625 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
626 while(classit.hasNext()) {
627 ClassDescriptor cn=(ClassDescriptor)classit.next();
628 outrepairstructs.println("structure "+cn.getSymbol()+" {");
629 outrepairstructs.println(" int __type__;");
631 outrepairstructs.println(" int __flag__;");
632 if(!state.MULTICORE) {
633 outrepairstructs.println(" int __flagptr__;");
636 printRepairStruct(cn, outrepairstructs);
637 outrepairstructs.println("}\n");
640 for(int i=0; i<state.numArrays(); i++) {
641 TypeDescriptor tdarray=arraytable[i];
642 TypeDescriptor tdelement=tdarray.dereference();
643 outrepairstructs.println("structure "+arraytype+"_"+state.getArrayNumber(tdarray)+" {");
644 outrepairstructs.println(" int __type__;");
645 printRepairStruct(typeutil.getClass(TypeUtil.ObjectClass), outrepairstructs);
646 outrepairstructs.println(" int length;");
648 // Need to add support to repair tool for this
649 if (tdelement.isClass()||tdelement.isArray())
650 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" * elem[this.length];");
652 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" elem[this.length];");
654 outrepairstructs.println("}\n");
658 private void printRepairStruct(ClassDescriptor cn, PrintWriter output) {
659 ClassDescriptor sp=cn.getSuperDesc();
661 printRepairStruct(sp, output);
663 Vector fields=(Vector)fieldorder.get(cn);
665 for(int i=0; i<fields.size(); i++) {
666 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
667 if (fd.getType().isArray()) {
668 output.println(" "+arraytype+"_"+ state.getArrayNumber(fd.getType()) +" * "+fd.getSymbol()+";");
669 } else if (fd.getType().isClass())
670 output.println(" "+fd.getType().getRepairSymbol()+" * "+fd.getSymbol()+";");
671 else if (fd.getType().isFloat())
672 output.println(" int "+fd.getSymbol()+"; /* really float */");
674 output.println(" "+fd.getType().getRepairSymbol()+" "+fd.getSymbol()+";");
678 /** This method outputs TaskDescriptor information */
679 private void generateTaskDescriptor(PrintWriter output, FlatMethod fm, TaskDescriptor task) {
680 for (int i=0; i<task.numParameters(); i++) {
681 VarDescriptor param_var=task.getParameter(i);
682 TypeDescriptor param_type=task.getParamType(i);
683 FlagExpressionNode param_flag=task.getFlag(param_var);
684 TagExpressionList param_tag=task.getTag(param_var);
687 if (param_flag==null) {
688 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
689 output.println("0x0, 0x0 };");
692 DNFFlag dflag=param_flag.getDNF();
693 dnfterms=dflag.size();
695 Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
696 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
697 for(int j=0; j<dflag.size(); j++) {
700 Vector term=dflag.get(j);
703 for(int k=0; k<term.size(); k++) {
704 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
705 FlagDescriptor fd=dfa.getFlag();
706 boolean negated=dfa.getNegated();
707 int flagid=1<<((Integer)flags.get(fd)).intValue();
712 output.print("0x"+Integer.toHexString(andmask)+", 0x"+Integer.toHexString(checkmask));
714 output.println("};");
717 output.println("int parametertag_"+i+"_"+task.getSafeSymbol()+"[]={");
718 //BUG...added next line to fix, test with any task program
720 for(int j=0; j<param_tag.numTags(); j++) {
723 /* for each tag we need */
724 /* which slot it is */
725 /* what type it is */
726 TagVarDescriptor tvd=(TagVarDescriptor)task.getParameterTable().get(param_tag.getName(j));
727 TempDescriptor tmp=param_tag.getTemp(j);
728 int slot=fm.getTagInt(tmp);
729 output.println(slot+", "+state.getTagId(tvd.getTag()));
731 output.println("};");
733 output.println("struct parameterdescriptor parameter_"+i+"_"+task.getSafeSymbol()+"={");
734 output.println("/* type */"+param_type.getClassDesc().getId()+",");
735 output.println("/* number of DNF terms */"+dnfterms+",");
736 output.println("parameterdnf_"+i+"_"+task.getSafeSymbol()+",");
737 output.println("0,");
738 //BUG, added next line to fix and else statement...test
739 //with any task program
741 output.println("/* number of tags */"+param_tag.numTags()+",");
743 output.println("/* number of tags */ 0,");
744 output.println("parametertag_"+i+"_"+task.getSafeSymbol());
745 output.println("};");
749 output.println("struct parameterdescriptor * parameterdescriptors_"+task.getSafeSymbol()+"[] = {");
750 for (int i=0; i<task.numParameters(); i++) {
753 output.print("¶meter_"+i+"_"+task.getSafeSymbol());
755 output.println("};");
757 output.println("struct taskdescriptor task_"+task.getSafeSymbol()+"={");
758 output.println("&"+task.getSafeSymbol()+",");
759 output.println("/* number of parameters */" +task.numParameters() + ",");
760 int numtotal=task.numParameters()+fm.numTags();
761 output.println("/* number total parameters */" +numtotal + ",");
762 output.println("parameterdescriptors_"+task.getSafeSymbol()+",");
763 output.println("\""+task.getSymbol()+"\"");
764 output.println("};");
768 /** The buildVirtualTables method outputs the virtual dispatch
769 * tables for methods. */
771 protected void buildVirtualTables(PrintWriter outvirtual) {
772 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
773 while(classit.hasNext()) {
774 ClassDescriptor cd=(ClassDescriptor)classit.next();
775 if (virtualcalls.getMethodCount(cd)>maxcount)
776 maxcount=virtualcalls.getMethodCount(cd);
778 MethodDescriptor[][] virtualtable=null;
779 LocalityBinding[][] lbvirtualtable=null;
780 if (state.DSM||state.SINGLETM)
781 lbvirtualtable=new LocalityBinding[state.numClasses()+state.numArrays()][maxcount];
783 virtualtable=new MethodDescriptor[state.numClasses()+state.numArrays()][maxcount];
785 /* Fill in virtual table */
786 classit=state.getClassSymbolTable().getDescriptorsIterator();
787 while(classit.hasNext()) {
788 ClassDescriptor cd=(ClassDescriptor)classit.next();
789 if (state.DSM||state.SINGLETM)
790 fillinRow(cd, lbvirtualtable, cd.getId());
792 fillinRow(cd, virtualtable, cd.getId());
795 ClassDescriptor objectcd=typeutil.getClass(TypeUtil.ObjectClass);
796 Iterator arrayit=state.getArrayIterator();
797 while(arrayit.hasNext()) {
798 TypeDescriptor td=(TypeDescriptor)arrayit.next();
799 int id=state.getArrayNumber(td);
800 if (state.DSM||state.SINGLETM)
801 fillinRow(objectcd, lbvirtualtable, id+state.numClasses());
803 fillinRow(objectcd, virtualtable, id+state.numClasses());
806 outvirtual.print("void * virtualtable[]={");
807 boolean needcomma=false;
808 for(int i=0; i<state.numClasses()+state.numArrays(); i++) {
809 for(int j=0; j<maxcount; j++) {
811 outvirtual.print(", ");
812 if ((state.DSM||state.SINGLETM)&&lbvirtualtable[i][j]!=null) {
813 LocalityBinding lb=lbvirtualtable[i][j];
814 MethodDescriptor md=lb.getMethod();
815 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
816 } else if (!(state.DSM||state.SINGLETM)&&virtualtable[i][j]!=null) {
817 MethodDescriptor md=virtualtable[i][j];
818 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
820 outvirtual.print("0");
824 outvirtual.println("");
826 outvirtual.println("};");
830 private void fillinRow(ClassDescriptor cd, MethodDescriptor[][] virtualtable, int rownum) {
831 /* Get inherited methods */
832 if (cd.getSuperDesc()!=null)
833 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
834 /* Override them with our methods */
835 for(Iterator it=cd.getMethods(); it.hasNext();) {
836 MethodDescriptor md=(MethodDescriptor)it.next();
837 if (md.isStatic()||md.getReturnType()==null)
839 int methodnum=virtualcalls.getMethodNumber(md);
840 virtualtable[rownum][methodnum]=md;
844 private void fillinRow(ClassDescriptor cd, LocalityBinding[][] virtualtable, int rownum) {
845 /* Get inherited methods */
846 if (cd.getSuperDesc()!=null)
847 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
848 /* Override them with our methods */
849 if (locality.getClassBindings(cd)!=null)
850 for(Iterator<LocalityBinding> lbit=locality.getClassBindings(cd).iterator(); lbit.hasNext();) {
851 LocalityBinding lb=lbit.next();
852 MethodDescriptor md=lb.getMethod();
853 //Is the method static or a constructor
854 if (md.isStatic()||md.getReturnType()==null)
856 int methodnum=virtualcalls.getLocalityNumber(lb);
857 virtualtable[rownum][methodnum]=lb;
861 /** Generate array that contains the sizes of class objects. The
862 * object allocation functions in the runtime use this
865 private void generateSizeArray(PrintWriter outclassdefs) {
866 outclassdefs.print("extern struct prefetchCountStats * evalPrefetch;\n");
867 outclassdefs.print("#ifdef TRANSSTATS \n");
868 outclassdefs.print("extern int numTransAbort;\n");
869 outclassdefs.print("extern int numTransCommit;\n");
870 outclassdefs.print("extern int nSoftAbort;\n");
872 outclassdefs.print("extern int nchashSearch;\n");
873 outclassdefs.print("extern int nmhashSearch;\n");
874 outclassdefs.print("extern int nprehashSearch;\n");
875 outclassdefs.print("extern int nRemoteSend;\n");
876 outclassdefs.print("extern int bytesSent;\n");
877 outclassdefs.print("extern int bytesRecv;\n");
878 outclassdefs.print("extern void handle();\n");
879 } else if (state.SINGLETM) {
880 outclassdefs.println("extern int nSoftAbortAbort;");
881 outclassdefs.println("extern int nSoftAbortCommit;");
882 outclassdefs.println("#ifdef STMSTATS\n");
883 outclassdefs.println("extern int typesCausingAbort[];");
884 outclassdefs.println("#endif\n");
886 outclassdefs.print("#endif\n");
887 outclassdefs.print("int numprefetchsites = " + pa.prefetchsiteid + ";\n");
889 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
890 cdarray=new ClassDescriptor[state.numClasses()];
891 while(it.hasNext()) {
892 ClassDescriptor cd=(ClassDescriptor)it.next();
893 cdarray[cd.getId()]=cd;
896 arraytable=new TypeDescriptor[state.numArrays()];
898 Iterator arrayit=state.getArrayIterator();
899 while(arrayit.hasNext()) {
900 TypeDescriptor td=(TypeDescriptor)arrayit.next();
901 int id=state.getArrayNumber(td);
907 /* Print out types */
908 outclassdefs.println("/* ");
909 for(int i=0; i<state.numClasses(); i++) {
910 ClassDescriptor cd=cdarray[i];
911 outclassdefs.println(cd +" "+i);
914 for(int i=0; i<state.numArrays(); i++) {
915 TypeDescriptor arraytd=arraytable[i];
916 outclassdefs.println(arraytd.toPrettyString() +" "+(i+state.numClasses()));
919 outclassdefs.println("*/");
922 outclassdefs.print("int classsize[]={");
924 boolean needcomma=false;
925 for(int i=0; i<state.numClasses(); i++) {
927 outclassdefs.print(", ");
928 outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")");
933 for(int i=0; i<state.numArrays(); i++) {
935 outclassdefs.print(", ");
936 TypeDescriptor tdelement=arraytable[i].dereference();
937 if (tdelement.isArray()||tdelement.isClass())
938 outclassdefs.print("sizeof(void *)");
940 outclassdefs.print("sizeof("+tdelement.getSafeSymbol()+")");
944 outclassdefs.println("};");
946 ClassDescriptor objectclass=typeutil.getClass(TypeUtil.ObjectClass);
948 outclassdefs.print("int typearray[]={");
949 for(int i=0; i<state.numClasses(); i++) {
950 ClassDescriptor cd=cdarray[i];
951 ClassDescriptor supercd=cd.getSuperDesc();
953 outclassdefs.print(", ");
955 outclassdefs.print("-1");
957 outclassdefs.print(supercd.getId());
961 for(int i=0; i<state.numArrays(); i++) {
962 TypeDescriptor arraytd=arraytable[i];
963 ClassDescriptor arraycd=arraytd.getClassDesc();
966 outclassdefs.print(", ");
967 outclassdefs.print(objectclass.getId());
971 ClassDescriptor cd=arraycd.getSuperDesc();
974 TypeDescriptor supertd=new TypeDescriptor(cd);
975 supertd.setArrayCount(arraytd.getArrayCount());
976 type=state.getArrayNumber(supertd);
978 type+=state.numClasses();
981 cd=cd.getSuperDesc();
984 outclassdefs.print(", ");
985 outclassdefs.print(type);
989 outclassdefs.println("};");
994 outclassdefs.print("int typearray2[]={");
995 for(int i=0; i<state.numArrays(); i++) {
996 TypeDescriptor arraytd=arraytable[i];
997 ClassDescriptor arraycd=arraytd.getClassDesc();
1000 outclassdefs.print(", ");
1001 outclassdefs.print("-1");
1005 ClassDescriptor cd=arraycd.getSuperDesc();
1006 int level=arraytd.getArrayCount()-1;
1008 for(; level>0; level--) {
1009 TypeDescriptor supertd=new TypeDescriptor(objectclass);
1010 supertd.setArrayCount(level);
1011 type=state.getArrayNumber(supertd);
1013 type+=state.numClasses();
1018 outclassdefs.print(", ");
1019 outclassdefs.print(type);
1023 outclassdefs.println("};");
1026 /** Constructs params and temp objects for each method or task.
1027 * These objects tell the compiler which temps need to be
1030 protected void generateTempStructs(FlatMethod fm, LocalityBinding lb) {
1031 MethodDescriptor md=fm.getMethod();
1032 TaskDescriptor task=fm.getTask();
1033 Set<TempDescriptor> saveset=lb!=null ? locality.getTempSet(lb) : null;
1034 ParamsObject objectparams=md!=null ? new ParamsObject(md,tag++) : new ParamsObject(task, tag++);
1036 paramstable.put(lb, objectparams);
1037 backuptable.put(lb, new Hashtable<TempDescriptor, TempDescriptor>());
1038 } else if (md!=null)
1039 paramstable.put(md, objectparams);
1041 paramstable.put(task, objectparams);
1043 for(int i=0; i<fm.numParameters(); i++) {
1044 TempDescriptor temp=fm.getParameter(i);
1045 TypeDescriptor type=temp.getType();
1046 if (type.isPtr()&&GENERATEPRECISEGC)
1047 objectparams.addPtr(temp);
1049 objectparams.addPrim(temp);
1050 if(lb!=null&&saveset.contains(temp)) {
1051 backuptable.get(lb).put(temp, temp.createNew());
1055 for(int i=0; i<fm.numTags(); i++) {
1056 TempDescriptor temp=fm.getTag(i);
1057 if (GENERATEPRECISEGC)
1058 objectparams.addPtr(temp);
1060 objectparams.addPrim(temp);
1063 TempObject objecttemps=md!=null ? new TempObject(objectparams,md,tag++) : new TempObject(objectparams, task, tag++);
1065 tempstable.put(lb, objecttemps);
1067 tempstable.put(md, objecttemps);
1069 tempstable.put(task, objecttemps);
1071 for(Iterator nodeit=fm.getNodeSet().iterator(); nodeit.hasNext();) {
1072 FlatNode fn=(FlatNode)nodeit.next();
1073 TempDescriptor[] writes=fn.writesTemps();
1074 for(int i=0; i<writes.length; i++) {
1075 TempDescriptor temp=writes[i];
1076 TypeDescriptor type=temp.getType();
1077 if (type.isPtr()&&GENERATEPRECISEGC)
1078 objecttemps.addPtr(temp);
1080 objecttemps.addPrim(temp);
1081 if(lb!=null&&saveset.contains(temp)&&
1082 !backuptable.get(lb).containsKey(temp))
1083 backuptable.get(lb).put(temp, temp.createNew());
1087 /* Create backup temps */
1089 for(Iterator<TempDescriptor> tmpit=backuptable.get(lb).values().iterator(); tmpit.hasNext();) {
1090 TempDescriptor tmp=tmpit.next();
1091 TypeDescriptor type=tmp.getType();
1092 if (type.isPtr()&&GENERATEPRECISEGC)
1093 objecttemps.addPtr(tmp);
1095 objecttemps.addPrim(tmp);
1097 /* Create temp to hold revert table */
1098 if (state.DSM&&(lb.getHasAtomic()||lb.isAtomic())) {
1099 TempDescriptor reverttmp=new TempDescriptor("revertlist", typeutil.getClass(TypeUtil.ObjectClass));
1100 if (GENERATEPRECISEGC)
1101 objecttemps.addPtr(reverttmp);
1103 objecttemps.addPrim(reverttmp);
1104 reverttable.put(lb, reverttmp);
1109 /** This method outputs the following information about classes
1111 * (1) For classes, what are the locations of pointers.
1112 * (2) For arrays, does the array contain pointers or primitives.
1113 * (3) For classes, does the class contain flags.
1116 private void generateLayoutStructs(PrintWriter output) {
1117 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1118 while(it.hasNext()) {
1119 ClassDescriptor cn=(ClassDescriptor)it.next();
1120 output.println("unsigned INTPTR "+cn.getSafeSymbol()+"_pointers[]={");
1121 Iterator allit=cn.getFieldTable().getAllDescriptorsIterator();
1123 while(allit.hasNext()) {
1124 FieldDescriptor fd=(FieldDescriptor)allit.next();
1125 TypeDescriptor type=fd.getType();
1126 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1131 output.print(count);
1132 allit=cn.getFieldTable().getAllDescriptorsIterator();
1133 while(allit.hasNext()) {
1134 FieldDescriptor fd=(FieldDescriptor)allit.next();
1135 TypeDescriptor type=fd.getType();
1136 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1139 output.println(",");
1140 output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+fd.getSafeSymbol()+"))");
1143 output.println("};");
1145 output.println("unsigned INTPTR * pointerarray[]={");
1146 boolean needcomma=false;
1147 for(int i=0; i<state.numClasses(); i++) {
1148 ClassDescriptor cn=cdarray[i];
1150 output.println(",");
1152 output.print(cn.getSafeSymbol()+"_pointers");
1155 for(int i=0; i<state.numArrays(); i++) {
1157 output.println(", ");
1158 TypeDescriptor tdelement=arraytable[i].dereference();
1159 if (tdelement.isArray()||tdelement.isClass())
1160 output.print("((unsigned INTPTR *)1)");
1166 output.println("};");
1168 output.println("int hasflags[]={");
1169 for(int i=0; i<state.numClasses(); i++) {
1170 ClassDescriptor cn=cdarray[i];
1172 output.println(", ");
1179 output.println("};");
1182 /** Print out table to give us supertypes */
1183 private void generateSuperTypeTable(PrintWriter output) {
1184 output.println("int supertypes[]={");
1185 boolean needcomma=false;
1186 for(int i=0; i<state.numClasses(); i++) {
1187 ClassDescriptor cn=cdarray[i];
1189 output.println(",");
1191 if (cn.getSuperDesc()!=null) {
1192 ClassDescriptor cdsuper=cn.getSuperDesc();
1193 output.print(cdsuper.getId());
1197 output.println("};");
1200 /** Force consistent field ordering between inherited classes. */
1202 private void printClassStruct(ClassDescriptor cn, PrintWriter classdefout) {
1204 ClassDescriptor sp=cn.getSuperDesc();
1206 printClassStruct(sp, classdefout);
1208 if (!fieldorder.containsKey(cn)) {
1209 Vector fields=new Vector();
1210 fieldorder.put(cn,fields);
1211 if (sp==null&&!state.TASK) {
1212 fields.add(cn.getFieldTable().get("cachedCode"));
1214 Iterator fieldit=cn.getFields();
1215 while(fieldit.hasNext()) {
1216 FieldDescriptor fd=(FieldDescriptor)fieldit.next();
1217 if ((sp==null||!sp.getFieldTable().contains(fd.getSymbol()))&&!fd.getType().isPtr()&&
1218 (!fd.getSymbol().equals("cachedCode")||state.TASK))
1221 fieldit=cn.getFields();
1222 while(fieldit.hasNext()) {
1223 FieldDescriptor fd=(FieldDescriptor)fieldit.next();
1224 if ((sp==null||!sp.getFieldTable().contains(fd.getSymbol()))&&fd.getType().isPtr()&&
1225 (!fd.getSymbol().equals("cachedCode")||state.TASK))
1229 Vector fields=(Vector)fieldorder.get(cn);
1231 for(int i=0; i<fields.size(); i++) {
1232 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
1233 if (fd.getType().isClass()||fd.getType().isArray())
1234 classdefout.println(" struct "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1236 classdefout.println(" "+fd.getType().getSafeSymbol()+" "+fd.getSafeSymbol()+";");
1241 /* Map flags to integers consistently between inherited
1244 protected void mapFlags(ClassDescriptor cn) {
1245 ClassDescriptor sp=cn.getSuperDesc();
1249 if (!flagorder.containsKey(cn)) {
1250 Hashtable flags=new Hashtable();
1251 flagorder.put(cn,flags);
1253 Hashtable superflags=(Hashtable)flagorder.get(sp);
1254 Iterator superflagit=superflags.keySet().iterator();
1255 while(superflagit.hasNext()) {
1256 FlagDescriptor fd=(FlagDescriptor)superflagit.next();
1257 Integer number=(Integer)superflags.get(fd);
1258 flags.put(fd, number);
1259 if ((number.intValue()+1)>max)
1260 max=number.intValue()+1;
1264 Iterator flagit=cn.getFlags();
1265 while(flagit.hasNext()) {
1266 FlagDescriptor fd=(FlagDescriptor)flagit.next();
1267 if (sp==null||!sp.getFlagTable().contains(fd.getSymbol()))
1268 flags.put(fd, new Integer(max++));
1274 /** This function outputs (1) structures that parameters are
1275 * passed in (when PRECISE GC is enabled) and (2) function
1276 * prototypes for the methods */
1278 protected void generateCallStructs(ClassDescriptor cn, PrintWriter classdefout, PrintWriter output, PrintWriter headersout) {
1279 /* Output class structure */
1280 classdefout.println("struct "+cn.getSafeSymbol()+" {");
1281 classdefout.println(" int type;");
1283 classdefout.println(" pthread_t tid;");
1284 classdefout.println(" void * lockentry;");
1285 classdefout.println(" int lockcount;");
1289 classdefout.println(" int flag;");
1290 if((!state.MULTICORE) || (cn.getSymbol().equals("TagDescriptor"))) {
1291 classdefout.println(" void * flagptr;");
1292 } else if (state.MULTICORE) {
1293 classdefout.println(" int version;");
1294 classdefout.println(" struct ___Object___ * original;");
1295 //classdefout.println(" int numlocks;"); // array for locks
1296 classdefout.println(" int * lock;");
1298 if (state.OPTIONAL) {
1299 classdefout.println(" int numfses;");
1300 classdefout.println(" int * fses;");
1303 printClassStruct(cn, classdefout);
1304 classdefout.println("};\n");
1306 if (state.DSM||state.SINGLETM) {
1307 /* Cycle through LocalityBindings */
1308 HashSet<MethodDescriptor> nativemethods=new HashSet<MethodDescriptor>();
1309 Set<LocalityBinding> lbset=locality.getClassBindings(cn);
1311 for(Iterator<LocalityBinding> lbit=lbset.iterator(); lbit.hasNext();) {
1312 LocalityBinding lb=lbit.next();
1313 MethodDescriptor md=lb.getMethod();
1314 if (md.getModifiers().isNative()) {
1315 //make sure we only print a native method once
1316 if (nativemethods.contains(md)) {
1317 FlatMethod fm=state.getMethodFlat(md);
1318 generateTempStructs(fm, lb);
1321 nativemethods.add(md);
1323 generateMethod(cn, md, lb, headersout, output);
1326 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1327 MethodDescriptor md=(MethodDescriptor)methodit.next();
1328 if (md.getModifiers().isNative()&&!nativemethods.contains(md)) {
1329 //Need to build param structure for library code
1330 FlatMethod fm=state.getMethodFlat(md);
1331 generateTempStructs(fm, null);
1332 generateMethodParam(cn, md, null, output);
1337 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1338 MethodDescriptor md=(MethodDescriptor)methodit.next();
1339 generateMethod(cn, md, null, headersout, output);
1343 private void generateMethodParam(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter output) {
1344 /* Output parameter structure */
1345 if (GENERATEPRECISEGC) {
1346 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1347 if ((state.DSM||state.SINGLETM)&&lb!=null)
1348 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1350 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1351 output.println(" INTPTR size;");
1352 output.println(" void * next;");
1353 for(int i=0; i<objectparams.numPointers(); i++) {
1354 TempDescriptor temp=objectparams.getPointer(i);
1355 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1357 output.println("};\n");
1361 private void generateMethod(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter headersout, PrintWriter output) {
1362 FlatMethod fm=state.getMethodFlat(md);
1363 generateTempStructs(fm, lb);
1365 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1366 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md);
1368 generateMethodParam(cn, md, lb, output);
1370 /* Output temp structure */
1371 if (GENERATEPRECISEGC) {
1372 if (state.DSM||state.SINGLETM)
1373 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1375 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1376 output.println(" INTPTR size;");
1377 output.println(" void * next;");
1378 for(int i=0; i<objecttemps.numPointers(); i++) {
1379 TempDescriptor temp=objecttemps.getPointer(i);
1380 if (temp.getType().isNull())
1381 output.println(" void * "+temp.getSafeSymbol()+";");
1383 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1385 output.println("};\n");
1388 /********* Output method declaration ***********/
1389 if (state.DSM||state.SINGLETM) {
1390 headersout.println("#define D"+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1392 headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1394 /* First the return type */
1395 if (md.getReturnType()!=null) {
1396 if (md.getReturnType().isClass()||md.getReturnType().isArray())
1397 headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1399 headersout.print(md.getReturnType().getSafeSymbol()+" ");
1401 //catch the constructor case
1402 headersout.print("void ");
1404 /* Next the method name */
1405 if (state.DSM||state.SINGLETM) {
1406 headersout.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1408 headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1410 boolean printcomma=false;
1411 if (GENERATEPRECISEGC) {
1412 if (state.DSM||state.SINGLETM) {
1413 headersout.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1415 headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1419 /* Output parameter list*/
1420 for(int i=0; i<objectparams.numPrimitives(); i++) {
1421 TempDescriptor temp=objectparams.getPrimitive(i);
1423 headersout.print(", ");
1425 if (temp.getType().isClass()||temp.getType().isArray())
1426 headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1428 headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1430 headersout.println(");\n");
1434 /** This function outputs (1) structures that parameters are
1435 * passed in (when PRECISE GC is enabled) and (2) function
1436 * prototypes for the tasks */
1438 private void generateTaskStructs(PrintWriter output, PrintWriter headersout) {
1439 /* Cycle through tasks */
1440 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
1442 while(taskit.hasNext()) {
1443 /* Classify parameters */
1444 TaskDescriptor task=(TaskDescriptor)taskit.next();
1445 FlatMethod fm=state.getMethodFlat(task);
1446 generateTempStructs(fm, null);
1448 ParamsObject objectparams=(ParamsObject) paramstable.get(task);
1449 TempObject objecttemps=(TempObject) tempstable.get(task);
1451 /* Output parameter structure */
1452 if (GENERATEPRECISEGC) {
1453 output.println("struct "+task.getSafeSymbol()+"_params {");
1455 output.println(" INTPTR size;");
1456 output.println(" void * next;");
1457 for(int i=0; i<objectparams.numPointers(); i++) {
1458 TempDescriptor temp=objectparams.getPointer(i);
1459 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1462 output.println("};\n");
1463 if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
1464 maxtaskparams=objectparams.numPointers()+fm.numTags();
1468 /* Output temp structure */
1469 if (GENERATEPRECISEGC) {
1470 output.println("struct "+task.getSafeSymbol()+"_locals {");
1471 output.println(" INTPTR size;");
1472 output.println(" void * next;");
1473 for(int i=0; i<objecttemps.numPointers(); i++) {
1474 TempDescriptor temp=objecttemps.getPointer(i);
1475 if (temp.getType().isNull())
1476 output.println(" void * "+temp.getSafeSymbol()+";");
1477 else if(temp.getType().isTag())
1478 output.println(" struct "+
1479 (new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1481 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1483 output.println("};\n");
1486 /* Output task declaration */
1487 headersout.print("void " + task.getSafeSymbol()+"(");
1489 boolean printcomma=false;
1490 if (GENERATEPRECISEGC) {
1491 headersout.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
1493 headersout.print("void * parameterarray[]");
1494 headersout.println(");\n");
1498 /***** Generate code for FlatMethod fm. *****/
1500 Hashtable<FlatAtomicEnterNode, AtomicRecord> atomicmethodmap;
1501 static int atomicmethodcount=0;
1503 private void generateFlatMethod(FlatMethod fm, LocalityBinding lb, PrintWriter output) {
1504 if (State.PRINTFLAT)
1505 System.out.println(fm.printMethod());
1506 MethodDescriptor md=fm.getMethod();
1507 TaskDescriptor task=fm.getTask();
1508 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
1509 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : md!=null ? md : task);
1511 HashSet<AtomicRecord> arset=null;
1513 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1515 if (atomicmethodmap==null)
1516 atomicmethodmap=new Hashtable<FlatAtomicEnterNode, AtomicRecord>();
1518 //fix these so we get right strings for local variables
1519 localsprefixaddr=localsprefix;
1520 localsprefixderef=localsprefix+"->";
1521 arset=new HashSet<AtomicRecord>();
1523 //Generate commit methods here
1524 for(Iterator<FlatNode> fnit=fm.getNodeSet().iterator();fnit.hasNext();) {
1525 FlatNode fn=fnit.next();
1526 if (fn.kind()==FKind.FlatAtomicEnterNode&&
1527 locality.getAtomic(lb).get(fn.getPrev(0)).intValue()==0) {
1528 //We have an atomic enter
1529 FlatAtomicEnterNode faen=(FlatAtomicEnterNode) fn;
1530 Set<FlatNode> exitset=faen.getExits();
1532 String methodname=md.getSymbol()+(atomicmethodcount++);
1533 AtomicRecord ar=new AtomicRecord();
1537 atomicmethodmap.put(faen, ar);
1539 //build data structure declaration
1540 output.println("struct atomicprimitives_"+methodname+" {");
1542 Set<FlatNode> recordset=delaycomp.livecode(lb);
1543 Set<TempDescriptor> liveinto=delaycomp.liveinto(lb, faen, recordset);
1544 Set<TempDescriptor> liveout=delaycomp.liveout(lb, faen);
1545 Set<TempDescriptor> liveoutvirtualread=delaycomp.liveoutvirtualread(lb, faen);
1547 ar.reallivein=new HashSet(liveinto);
1549 ar.liveoutvirtualread=liveoutvirtualread;
1551 for(Iterator<TempDescriptor> it=liveinto.iterator(); it.hasNext();) {
1552 TempDescriptor tmp=it.next();
1553 //remove the pointers
1554 if (tmp.getType().isPtr()) {
1557 //let's print it here
1558 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1561 for(Iterator<TempDescriptor> it=liveout.iterator(); it.hasNext();) {
1562 TempDescriptor tmp=it.next();
1563 //remove the pointers
1564 if (tmp.getType().isPtr()) {
1566 } else if (!liveinto.contains(tmp)) {
1567 //let's print it here
1568 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1571 output.println("};");
1573 //print out method name
1574 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) {");
1575 //build code for commit method
1577 //first define local primitives
1578 Set<TempDescriptor> alltemps=delaycomp.alltemps(lb, faen, recordset);
1579 for(Iterator<TempDescriptor> tmpit=alltemps.iterator();tmpit.hasNext();) {
1580 TempDescriptor tmp=tmpit.next();
1581 if (!tmp.getType().isPtr()) {
1582 if (liveinto.contains(tmp)||liveoutvirtualread.contains(tmp)) {
1583 //read from live into set
1584 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+"=primitives->"+tmp.getSafeSymbol()+";");
1587 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1591 //turn off write barrier generation
1593 state.SINGLETM=false;
1594 generateCode(faen, fm, lb, exitset, output, false);
1595 state.SINGLETM=true;
1596 //turn on write barrier generation
1598 output.println("}\n\n");
1602 //redefine these back to normal
1604 localsprefixaddr="&"+localsprefix;
1605 localsprefixderef=localsprefix+".";
1607 generateHeader(fm, lb, md!=null ? md : task,output);
1608 TempObject objecttemp=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
1610 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1611 for(Iterator<AtomicRecord> arit=arset.iterator();arit.hasNext();) {
1612 AtomicRecord ar=arit.next();
1613 output.println("struct atomicprimitives_"+ar.name+" primitives_"+ar.name+";");
1617 if (GENERATEPRECISEGC) {
1618 if (md!=null&&(state.DSM||state.SINGLETM))
1619 output.print(" struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1620 else if (md!=null&&!(state.DSM||state.SINGLETM))
1621 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1623 output.print(" struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={");
1625 output.print(objecttemp.numPointers()+",");
1626 output.print(paramsprefix);
1627 for(int j=0; j<objecttemp.numPointers(); j++)
1628 output.print(", NULL");
1629 output.println("};");
1632 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1633 TempDescriptor td=objecttemp.getPrimitive(i);
1634 TypeDescriptor type=td.getType();
1636 output.println(" void * "+td.getSafeSymbol()+";");
1637 else if (type.isClass()||type.isArray())
1638 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1640 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1643 /* Check to see if we need to do a GC if this is a
1644 * multi-threaded program...*/
1646 if ((state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC) {
1647 //Don't bother if we aren't in recursive methods...The loops case will catch it
1648 if (callgraph.getAllMethods(md).contains(md)) {
1649 if (state.DSM&&lb.isAtomic())
1650 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
1652 output.println("if (needtocollect) checkcollect("+localsprefixaddr+");");
1656 generateCode(fm.getNext(0), fm, lb, null, output, true);
1658 output.println("}\n\n");
1661 // when a new mlp thread is created for an issued SESE, it is started
1662 // by running this method which blocks on a cond variable until
1663 // it is allowed to transition to execute. Then a case statement
1664 // allows it to invoke the method with the proper SESE body, and after
1665 // exiting the SESE method, executes proper SESE exit code before the
1666 // thread can be destroyed
1667 private void generateSESEinvocationMethod(PrintWriter outmethodheader,
1668 PrintWriter outmethod
1671 outmethodheader.println("void invokeSESEmethod( void* vargs );");
1672 outmethod.println( "void invokeSESEmethod( void* vargs ) {");
1673 outmethod.println( " int status;");
1674 outmethod.println( " char errmsg[128];");
1675 outmethod.println( " invokeSESEargs* args = (invokeSESEargs*) vargs;");
1678 // wait on a condition variable that dispatcher will signal
1679 // then this SESE instance's dependencies are resolved
1680 outmethod.println( " status = pthread_mutex_lock( args->invokee->startCondVarLock );");
1681 outmethod.println( " "+mlperrstr);
1682 outmethod.println( " while( !(args->invokee->startedExecuting) ){");
1683 outmethod.println( " status = pthread_cond_wait( args->invokee->startCondVar, args->invokee->startCondVarLock );");
1684 outmethod.println( " "+mlperrstr);
1685 outmethod.println( " }");
1688 // generate a case for each SESE class that can be invoked
1689 outmethod.println( " switch( args->classID ) {");
1690 outmethod.println( " ");
1691 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
1692 FlatSESEEnterNode fsen = seseit.next();
1693 outmethod.println( " /* "+fsen.getPrettyIdentifier()+" */");
1694 outmethod.println( " case "+fsen.getIdentifier()+":");
1695 generateSESEinvocation(fsen, outmethod);
1696 outmethod.println( " break;");
1697 outmethod.println( "");
1700 // default case should never be taken, error out
1701 outmethod.println( " default:");
1702 outmethod.println( " printf(\"Error: unknown SESE class ID in invoke method.\\n\");");
1703 outmethod.println( " exit(-30);");
1704 outmethod.println( " break;");
1705 outmethod.println( " }");
1706 outmethod.println( "}\n\n");
1709 private void generateSESEinvocation(FlatSESEEnterNode fsen,
1713 FlatMethod fm = fsen.getEnclosingFlatMeth();
1714 MethodDescriptor md = fm.getMethod();
1715 ClassDescriptor cn = md.getClassDesc();
1717 FlatMethod bogusfm = sese2bogusFlatMeth.get(fsen);
1718 MethodDescriptor bogusmd = bogusfm.getMethod();
1719 ParamsObject objectparams = (ParamsObject)paramstable.get(bogusmd);
1721 // first copy SESE record into param structure
1724 // then invoke the sese's method
1725 output.print(" "+cn.getSafeSymbol()+bogusmd.getSafeSymbol()+"_"+bogusmd.getSafeMethodDescriptor());
1726 output.print("( args->invokee, ");
1728 // first argument is parameter structure
1729 output.print("(struct "+cn.getSafeSymbol()+bogusmd.getSafeSymbol()+"__params*)");
1730 output.print("&(args->invokee->paramStruct)");
1732 // other arguments are primitive parameters
1733 for(int i=0; i<objectparams.numPrimitives(); i++) {
1734 TempDescriptor td=objectparams.getPrimitive(i);
1735 TypeDescriptor type=td.getType();
1736 assert type.isPrimitive();
1737 output.print( ", (("+fsen.namespaceStructNameString()+
1738 "*)args->invokee->namespace)->"+td );
1741 output.println(");");
1744 protected void generateMethodSESE(FlatSESEEnterNode fsen,
1746 PrintWriter outputStructs,
1747 PrintWriter outputMethHead,
1748 PrintWriter outputMethods
1752 FlatMethod fm = fsen.getEnclosingFlatMeth();
1753 MethodDescriptor md = fm.getMethod();
1754 ClassDescriptor cn = md.getClassDesc();
1757 //Creates bogus method descriptor to index into tables
1758 Modifiers bogusmod=new Modifiers();
1759 MethodDescriptor bogusmd=new MethodDescriptor(bogusmod,
1760 new TypeDescriptor(TypeDescriptor.VOID),
1761 "sese_"+fsen.getPrettyIdentifier()+fsen.getIdentifier());
1762 bogusmd.setClassDesc(cn);
1763 FlatMethod bogusfm=new FlatMethod(bogusmd, null);
1764 sese2bogusFlatMeth.put(fsen, bogusfm);
1767 //Build paramsobj for bogus method descriptor
1768 ParamsObject objectparams=new ParamsObject(bogusmd, tag++);
1769 paramstable.put(bogusmd, objectparams);
1771 for(int i=0; i<fsen.numParameters(); i++) {
1772 TempDescriptor temp=fsen.getParameter(i);
1773 TypeDescriptor type=temp.getType();
1774 if (type.isPtr()&&GENERATEPRECISEGC) {
1775 objectparams.addPtr(temp);
1777 objectparams.addPrim(temp);
1782 //Build normal temp object for bogus method descriptor
1783 TempObject objecttemps=new TempObject(objectparams,bogusmd,tag++);
1784 tempstable.put(bogusmd, objecttemps);
1786 for(Iterator nodeit=fsen.getNodeSet().iterator(); nodeit.hasNext();) {
1787 FlatNode fn=(FlatNode)nodeit.next();
1788 TempDescriptor[] writes=fn.writesTemps();
1789 for(int i=0; i<writes.length; i++) {
1790 TempDescriptor temp=writes[i];
1791 TypeDescriptor type=temp.getType();
1792 if (type.isPtr()&&GENERATEPRECISEGC)
1793 objecttemps.addPtr(temp);
1795 objecttemps.addPrim(temp);
1799 // declare namespace struct
1800 outputStructs.println(fsen.namespaceStructDeclarationString());
1802 //Generate code for parameters structure
1803 generateMethodParam(cn, bogusmd, null, outputStructs);
1805 //Generate code for locals structure
1806 outputStructs.println("struct "+cn.getSafeSymbol()+bogusmd.getSafeSymbol()+"_"+bogusmd.getSafeMethodDescriptor()+"_locals {");
1807 outputStructs.println(" INTPTR size;");
1808 outputStructs.println(" void * next;");
1809 for(int i=0; i<objecttemps.numPointers(); i++) {
1810 TempDescriptor temp=objecttemps.getPointer(i);
1811 if (temp.getType().isNull())
1812 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
1814 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1816 outputStructs.println("};\n");
1819 // write method declaration to header file
1820 outputMethHead.print("void ");
1821 outputMethHead.print(cn.getSafeSymbol()+bogusmd.getSafeSymbol()+"_"+bogusmd.getSafeMethodDescriptor()+"(");
1822 outputMethHead.print("SESErecord* currentSESE, ");
1823 boolean printcomma=false;
1824 if (GENERATEPRECISEGC) {
1825 outputMethHead.print("struct "+cn.getSafeSymbol()+
1826 bogusmd.getSafeSymbol()+"_"+
1827 bogusmd.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1830 // Output parameter list
1831 for(int i=0; i<objectparams.numPrimitives(); i++) {
1832 TempDescriptor temp=objectparams.getPrimitive(i);
1834 outputMethHead.print(", ");
1836 if (temp.getType().isClass()||temp.getType().isArray())
1837 outputMethHead.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1839 outputMethHead.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1841 outputMethHead.println(");\n");
1844 generateFlatMethodSESE(bogusfm, cn, fsen, fsen.getFlatExit(), outputMethods);
1847 private void generateFlatMethodSESE(FlatMethod fm,
1849 FlatSESEEnterNode seseEnter,
1850 FlatSESEExitNode seseExit,
1854 MethodDescriptor md=fm.getMethod();
1855 ParamsObject objectparams=(ParamsObject)paramstable.get(md);
1856 generateHeader(fm, null, md, output, true);
1857 TempObject objecttemp=(TempObject) tempstable.get(md);
1860 if (GENERATEPRECISEGC) {
1861 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1862 output.print(objecttemp.numPointers()+",");
1863 output.print(paramsprefix);
1864 for(int j=0; j<objecttemp.numPointers(); j++)
1865 output.print(", NULL");
1866 output.println("};");
1869 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1870 TempDescriptor td=objecttemp.getPrimitive(i);
1871 TypeDescriptor type=td.getType();
1873 output.println(" void * "+td.getSafeSymbol()+";");
1874 else if (type.isClass()||type.isArray())
1875 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1877 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1881 // declare variables for naming SESE's
1882 Iterator<SESEandAgePair> pItr = seseEnter.getNeededStaticNames().iterator();
1883 while( pItr.hasNext() ) {
1884 SESEandAgePair p = pItr.next();
1885 output.println(" SESErecord* "+p+";");
1889 // Check to see if we need to do a GC if this is a
1890 // multi-threaded program...
1891 if (GENERATEPRECISEGC) {
1892 //Don't bother if we aren't in recursive methods...The loops case will catch it
1893 if (callgraph.getAllMethods(md).contains(md)) {
1894 output.println("if (needtocollect) checkcollect("+localsprefixaddr+");");
1898 HashSet<FlatNode> exitset=new HashSet<FlatNode>();
1899 exitset.add(seseExit);
1900 generateCode(seseEnter.getNext(0), fm, null, exitset, output, true);
1903 output.println("}\n\n");
1906 protected void generateCode(FlatNode first,
1909 Set<FlatNode> stopset,
1910 PrintWriter output, boolean firstpass) {
1912 // for any method, allocate temps to use when
1913 // issuing a new SESE sometime during the execution
1914 // of that method, whether it be a user-defined method
1915 // or a method representing the body of an SESE
1916 // TODO: only do this if we know the method actually
1917 // contains an SESE issue, not currently an annotation
1919 output.println(" SESErecord* tempSESE;");
1920 output.println(" invokeSESEargs* tempSESEargs;");
1923 /* Assign labels to FlatNode's if necessary.*/
1924 Hashtable<FlatNode, Integer> nodetolabel=assignLabels(first, stopset);
1926 Set<FlatNode> storeset=null;
1927 HashSet<FlatNode> genset=null;
1928 Set<FlatNode> unionset=null;
1930 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1931 storeset=delaycomp.livecode(lb);
1932 genset=new HashSet<FlatNode>();
1934 genset.addAll(delaycomp.getCannotDelay(lb));
1935 genset.addAll(delaycomp.getOther(lb));
1937 genset.addAll(delaycomp.getNotReady(lb));
1939 unionset=new HashSet<FlatNode>();
1940 unionset.addAll(storeset);
1941 unionset.addAll(genset);
1944 /* Do the actual code generation */
1945 FlatNode current_node=null;
1946 HashSet tovisit=new HashSet();
1947 HashSet visited=new HashSet();
1949 tovisit.add(first.getNext(0));
1952 while(current_node!=null||!tovisit.isEmpty()) {
1953 if (current_node==null) {
1954 current_node=(FlatNode)tovisit.iterator().next();
1955 tovisit.remove(current_node);
1956 } else if (tovisit.contains(current_node)) {
1957 tovisit.remove(current_node);
1959 visited.add(current_node);
1960 if (nodetolabel.containsKey(current_node)) {
1961 output.println("L"+nodetolabel.get(current_node)+":");
1963 if (state.INSTRUCTIONFAILURE) {
1964 if (state.THREAD||state.DSM||state.SINGLETM) {
1965 output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
1967 output.println("if ((--instructioncount)==0) injectinstructionfailure();");
1969 if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
1971 if (!state.DELAYCOMP||firstpass) {
1972 generateFlatNode(fm, lb, current_node, output);
1974 //store primitive variables in out set
1975 AtomicRecord ar=atomicmethodmap.get((FlatAtomicEnterNode)first);
1976 Set<TempDescriptor> liveout=ar.liveout;
1977 for(Iterator<TempDescriptor> tmpit=liveout.iterator();tmpit.hasNext();) {
1978 TempDescriptor tmp=tmpit.next();
1979 output.println("primitives->"+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
1982 if (current_node.kind()!=FKind.FlatReturnNode) {
1983 output.println(" return;");
1986 } else if(current_node.numNext()==1) {
1988 if (state.MLP && current_node.kind()==FKind.FlatSESEEnterNode) {
1989 FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
1990 generateFlatNode(fm, lb, current_node, output);
1991 nextnode=fsen.getFlatExit().getNext(0);
1992 } else if (state.DELAYCOMP) {
1993 boolean specialprimitive=false;
1994 //skip literals...no need to add extra overhead
1995 if (storeset!=null&&storeset.contains(current_node)&¤t_node.kind()==FKind.FlatLiteralNode) {
1996 TypeDescriptor typedesc=((FlatLiteralNode)current_node).getType();
1997 if (!typedesc.isClass()&&!typedesc.isArray()) {
1998 specialprimitive=true;
2002 if (genset==null||genset.contains(current_node)||specialprimitive)
2003 generateFlatNode(fm, lb, current_node, output);
2004 if (storeset!=null&&storeset.contains(current_node)&&!specialprimitive) {
2005 TempDescriptor wrtmp=current_node.writesTemps()[0];
2007 //need to store value written by previous node
2008 if (wrtmp.getType().isPtr()) {
2009 //only lock the objects that may actually need locking
2010 if (recorddc.getNeedTrans(lb, current_node)) {
2011 output.println("STOREPTR("+generateTemp(fm, wrtmp,lb)+");");
2013 output.println("STOREPTRNOLOCK("+generateTemp(fm, wrtmp,lb)+");");
2016 output.println("STORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");");
2019 //need to read value read by previous node
2020 if (wrtmp.getType().isPtr()) {
2021 output.println("RESTOREPTR("+generateTemp(fm, wrtmp,lb)+");");
2023 output.println("RESTORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");");
2027 nextnode=current_node.getNext(0);
2030 generateFlatNode(fm, lb, current_node, output);
2031 nextnode=current_node.getNext(0);
2033 if (visited.contains(nextnode)) {
2034 output.println("goto L"+nodetolabel.get(nextnode)+";");
2037 current_node=nextnode;
2038 } else if (current_node.numNext()==2) {
2040 if (state.DELAYCOMP) {
2041 boolean computeside=false;
2043 //need to record which way it should go
2044 if (genset==null||genset.contains(current_node)) {
2045 if (storeset!=null&&storeset.contains(current_node)) {
2046 //need to store which way branch goes
2047 generateStoreFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2049 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2051 //which side to execute
2055 if (genset.contains(current_node)) {
2056 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2057 } else if (storeset.contains(current_node)) {
2059 output.println("RESTOREANDBRANCH(L"+nodetolabel.get(current_node.getNext(1))+");");
2061 //which side to execute
2066 Set<FlatNode> leftset=DelayComputation.getNext(current_node, 0, unionset, lb,locality, true);
2068 if (leftset.size()==0)
2070 if (visited.contains(current_node.getNext(branch))) {
2071 //already visited -- build jump
2072 output.println("goto L"+nodetolabel.get(current_node.getNext(branch))+";");
2075 current_node=current_node.getNext(branch);
2078 if (!visited.contains(current_node.getNext(1)))
2079 tovisit.add(current_node.getNext(1));
2080 if (visited.contains(current_node.getNext(0))) {
2081 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2084 current_node=current_node.getNext(0);
2088 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2089 if (!visited.contains(current_node.getNext(1)))
2090 tovisit.add(current_node.getNext(1));
2091 if (visited.contains(current_node.getNext(0))) {
2092 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2095 current_node=current_node.getNext(0);
2097 } else throw new Error();
2101 /** This method assigns labels to FlatNodes */
2102 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first) {
2103 return assignLabels(first, null);
2106 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
2107 HashSet tovisit=new HashSet();
2108 HashSet visited=new HashSet();
2110 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2113 /*Assign labels first. A node needs a label if the previous
2114 * node has two exits or this node is a join point. */
2116 while(!tovisit.isEmpty()) {
2117 FlatNode fn=(FlatNode)tovisit.iterator().next();
2122 if(lastset!=null&&lastset.contains(fn)) {
2123 // if last is not null and matches, don't go
2124 // any further for assigning labels
2128 for(int i=0; i<fn.numNext(); i++) {
2129 FlatNode nn=fn.getNext(i);
2132 //1) Edge >1 of node
2133 nodetolabel.put(nn,new Integer(labelindex++));
2135 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2139 nodetolabel.put(nn,new Integer(labelindex++));
2147 /** Generate text string that corresponds to the TempDescriptor td. */
2148 protected String generateTemp(FlatMethod fm, TempDescriptor td, LocalityBinding lb) {
2149 MethodDescriptor md=fm.getMethod();
2150 TaskDescriptor task=fm.getTask();
2151 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
2153 if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
2154 //System.out.println("generateTemp returns " + td.getSafeSymbol());
2155 return td.getSafeSymbol();
2158 if (objecttemps.isLocalPtr(td)) {
2159 return localsprefixderef+td.getSafeSymbol();
2162 if (objecttemps.isParamPtr(td)) {
2163 return paramsprefix+"->"+td.getSafeSymbol();
2169 protected void generateFlatNode(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output) {
2171 case FKind.FlatAtomicEnterNode:
2172 generateFlatAtomicEnterNode(fm, lb, (FlatAtomicEnterNode) fn, output);
2175 case FKind.FlatAtomicExitNode:
2176 generateFlatAtomicExitNode(fm, lb, (FlatAtomicExitNode) fn, output);
2179 case FKind.FlatInstanceOfNode:
2180 generateFlatInstanceOfNode(fm, lb, (FlatInstanceOfNode)fn, output);
2183 case FKind.FlatSESEEnterNode:
2184 generateFlatSESEEnterNode(fm, lb, (FlatSESEEnterNode)fn, output);
2187 case FKind.FlatSESEExitNode:
2188 generateFlatSESEExitNode(fm, lb, (FlatSESEExitNode)fn, output);
2191 case FKind.FlatGlobalConvNode:
2192 generateFlatGlobalConvNode(fm, lb, (FlatGlobalConvNode) fn, output);
2195 case FKind.FlatTagDeclaration:
2196 generateFlatTagDeclaration(fm, lb, (FlatTagDeclaration) fn,output);
2199 case FKind.FlatCall:
2200 generateFlatCall(fm, lb, (FlatCall) fn,output);
2203 case FKind.FlatFieldNode:
2204 generateFlatFieldNode(fm, lb, (FlatFieldNode) fn,output);
2207 case FKind.FlatElementNode:
2208 generateFlatElementNode(fm, lb, (FlatElementNode) fn,output);
2211 case FKind.FlatSetElementNode:
2212 generateFlatSetElementNode(fm, lb, (FlatSetElementNode) fn,output);
2215 case FKind.FlatSetFieldNode:
2216 generateFlatSetFieldNode(fm, lb, (FlatSetFieldNode) fn,output);
2220 generateFlatNew(fm, lb, (FlatNew) fn,output);
2223 case FKind.FlatOpNode:
2224 generateFlatOpNode(fm, lb, (FlatOpNode) fn,output);
2227 case FKind.FlatCastNode:
2228 generateFlatCastNode(fm, lb, (FlatCastNode) fn,output);
2231 case FKind.FlatLiteralNode:
2232 generateFlatLiteralNode(fm, lb, (FlatLiteralNode) fn,output);
2235 case FKind.FlatReturnNode:
2236 generateFlatReturnNode(fm, lb, (FlatReturnNode) fn,output);
2240 output.println("/* nop */");
2243 case FKind.FlatExit:
2244 output.println("/* exit */");
2247 case FKind.FlatBackEdge:
2248 if ((state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC) {
2249 if(state.DSM&&locality.getAtomic(lb).get(fn).intValue()>0) {
2250 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
2252 output.println("if (needtocollect) checkcollect("+localsprefixaddr+");");
2254 output.println("/* nop */");
2257 case FKind.FlatCheckNode:
2258 generateFlatCheckNode(fm, lb, (FlatCheckNode) fn, output);
2261 case FKind.FlatFlagActionNode:
2262 generateFlatFlagActionNode(fm, lb, (FlatFlagActionNode) fn, output);
2265 case FKind.FlatPrefetchNode:
2266 generateFlatPrefetchNode(fm,lb, (FlatPrefetchNode) fn, output);
2269 case FKind.FlatOffsetNode:
2270 generateFlatOffsetNode(fm, lb, (FlatOffsetNode)fn, output);
2279 CodePlan cp = mlpa.getCodePlan( fn );
2282 Set<VariableSourceToken> writeDynamic = cp.getWriteToDynamicSrc();
2283 if( writeDynamic != null ) {
2290 public void generateFlatOffsetNode(FlatMethod fm, LocalityBinding lb, FlatOffsetNode fofn, PrintWriter output) {
2291 output.println("/* FlatOffsetNode */");
2292 FieldDescriptor fd=fofn.getField();
2293 output.println(generateTemp(fm, fofn.getDst(),lb)+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+ fd.getSafeSymbol()+");");
2294 output.println("/* offset */");
2297 public void generateFlatPrefetchNode(FlatMethod fm, LocalityBinding lb, FlatPrefetchNode fpn, PrintWriter output) {
2298 if (state.PREFETCH) {
2299 Vector oids = new Vector();
2300 Vector fieldoffset = new Vector();
2301 Vector endoffset = new Vector();
2302 int tuplecount = 0; //Keeps track of number of prefetch tuples that need to be generated
2303 for(Iterator it = fpn.hspp.iterator(); it.hasNext();) {
2304 PrefetchPair pp = (PrefetchPair) it.next();
2305 Integer statusbase = locality.getNodePreTempInfo(lb,fpn).get(pp.base);
2306 /* Find prefetches that can generate oid */
2307 if(statusbase == LocalityAnalysis.GLOBAL) {
2308 generateTransCode(fm, lb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(lb).get(fpn).intValue()>0, false);
2310 } else if (statusbase == LocalityAnalysis.LOCAL) {
2311 generateTransCode(fm,lb,pp,oids,fieldoffset,endoffset,tuplecount,false,true);
2318 System.out.println("Adding prefetch "+fpn+ " to method:" +fm);
2319 output.println("{");
2320 output.println("/* prefetch */");
2321 output.println("/* prefetchid_" + fpn.siteid + " */");
2322 output.println("void * prefptr;");
2323 output.println("int tmpindex;");
2325 output.println("if((evalPrefetch["+fpn.siteid+"].operMode) || (evalPrefetch["+fpn.siteid+"].retrycount <= 0)) {");
2326 /*Create C code for oid array */
2327 output.print(" unsigned int oidarray_[] = {");
2328 boolean needcomma=false;
2329 for (Iterator it = oids.iterator(); it.hasNext();) {
2332 output.print(it.next());
2335 output.println("};");
2337 /*Create C code for endoffset values */
2338 output.print(" unsigned short endoffsetarry_[] = {");
2340 for (Iterator it = endoffset.iterator(); it.hasNext();) {
2343 output.print(it.next());
2346 output.println("};");
2348 /*Create C code for Field Offset Values */
2349 output.print(" short fieldarry_[] = {");
2351 for (Iterator it = fieldoffset.iterator(); it.hasNext();) {
2354 output.print(it.next());
2357 output.println("};");
2358 /* make the prefetch call to Runtime */
2359 output.println(" if(!evalPrefetch["+fpn.siteid+"].operMode) {");
2360 output.println(" evalPrefetch["+fpn.siteid+"].retrycount = RETRYINTERVAL;");
2361 output.println(" }");
2362 output.println(" prefetch("+fpn.siteid+" ,"+tuplecount+", oidarray_, endoffsetarry_, fieldarry_);");
2363 output.println(" } else {");
2364 output.println(" evalPrefetch["+fpn.siteid+"].retrycount--;");
2365 output.println(" }");
2366 output.println("}");
2370 public void generateTransCode(FlatMethod fm, LocalityBinding lb,PrefetchPair pp, Vector oids, Vector fieldoffset, Vector endoffset, int tuplecount, boolean inside, boolean localbase) {
2371 short offsetcount = 0;
2375 } else if (localbase) {
2376 for(; breakindex<pp.desc.size(); breakindex++) {
2377 Descriptor desc=pp.getDescAt(breakindex);
2378 if (desc instanceof FieldDescriptor) {
2379 FieldDescriptor fd=(FieldDescriptor)desc;
2380 if (fd.isGlobal()) {
2388 if (breakindex>pp.desc.size()) //all local
2391 TypeDescriptor lasttype=pp.base.getType();
2392 String basestr=generateTemp(fm, pp.base, lb);
2394 boolean maybenull=fm.getMethod().isStatic()||
2395 !pp.base.equals(fm.getParameter(0));
2397 for(int i=0; i<breakindex; i++) {
2398 String indexcheck="";
2400 Descriptor desc=pp.getDescAt(i);
2401 if (desc instanceof FieldDescriptor) {
2402 FieldDescriptor fd=(FieldDescriptor)desc;
2404 if (!teststr.equals(""))
2406 teststr+="((prefptr="+basestr+")!=NULL)";
2407 basestr="((struct "+lasttype.getSafeSymbol()+" *)prefptr)->"+fd.getSafeSymbol();
2409 basestr=basestr+"->"+fd.getSafeSymbol();
2412 lasttype=fd.getType();
2414 IndexDescriptor id=(IndexDescriptor)desc;
2415 indexcheck="((tmpindex=";
2416 for(int j=0; j<id.tddesc.size(); j++) {
2417 indexcheck+=generateTemp(fm, id.getTempDescAt(j), lb)+"+";
2419 indexcheck+=id.offset+")>=0)&(tmpindex<((struct ArrayObject *)prefptr)->___length___)";
2421 if (!teststr.equals(""))
2423 teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck;
2424 basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]";
2426 lasttype=lasttype.dereference();
2431 if (teststr.equals("")) {
2432 oid="((unsigned int)"+basestr+")";
2434 oid="((unsigned int)(("+teststr+")?"+basestr+":NULL))";
2438 for(int i = breakindex; i < pp.desc.size(); i++) {
2439 String newfieldoffset;
2440 Object desc = pp.getDescAt(i);
2441 if(desc instanceof FieldDescriptor) {
2442 FieldDescriptor fd=(FieldDescriptor)desc;
2443 newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))");
2444 lasttype=fd.getType();
2446 newfieldoffset = "";
2447 IndexDescriptor id=(IndexDescriptor)desc;
2448 for(int j = 0; j < id.tddesc.size(); j++) {
2449 newfieldoffset += generateTemp(fm, id.getTempDescAt(j), lb) + "+";
2451 newfieldoffset += id.offset.toString();
2452 lasttype=lasttype.dereference();
2454 fieldoffset.add(newfieldoffset);
2457 int base=(tuplecount>0) ? ((Short)endoffset.get(tuplecount-1)).intValue() : 0;
2458 base+=pp.desc.size()-breakindex;
2459 endoffset.add(new Short((short)base));
2464 public void generateFlatGlobalConvNode(FlatMethod fm, LocalityBinding lb, FlatGlobalConvNode fgcn, PrintWriter output) {
2465 if (lb!=fgcn.getLocality())
2467 /* Have to generate flat globalconv */
2468 if (fgcn.getMakePtr()) {
2470 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+");");
2472 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fgcn)||state.READSET&&dc.getNeedWriteTrans(lb, fgcn)) {
2473 //need to do translation
2474 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+", (void *)("+localsprefixaddr+"));");
2475 } else if (state.READSET&&dc.getNeedTrans(lb, fgcn)) {
2476 output.println("TRANSREADRD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
2480 /* Need to convert to OID */
2481 if ((dc==null)||dc.getNeedSrcTrans(lb,fgcn)) {
2482 if (fgcn.doConvert()||(delaycomp!=null&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) {
2483 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc(),lb)+");");
2485 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=NULL;");
2491 public void generateFlatInstanceOfNode(FlatMethod fm, LocalityBinding lb, FlatInstanceOfNode fion, PrintWriter output) {
2493 if (fion.getType().isArray()) {
2494 type=state.getArrayNumber(fion.getType())+state.numClasses();
2496 type=fion.getType().getClassDesc().getId();
2499 if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
2500 output.println(generateTemp(fm, fion.getDst(), lb)+"=1;");
2502 output.println(generateTemp(fm, fion.getDst(), lb)+"=instanceof("+generateTemp(fm,fion.getSrc(),lb)+","+type+");");
2505 public void generateFlatAtomicEnterNode(FlatMethod fm, LocalityBinding lb, FlatAtomicEnterNode faen, PrintWriter output) {
2506 /* Check to see if we need to generate code for this atomic */
2507 if (locality==null) {
2508 output.println("pthread_mutex_lock(&atomiclock);");
2512 if (locality.getAtomic(lb).get(faen.getPrev(0)).intValue()>0)
2516 if (state.DELAYCOMP) {
2517 AtomicRecord ar=atomicmethodmap.get(faen);
2519 for(Iterator<TempDescriptor> tmpit=ar.livein.iterator();tmpit.hasNext();) {
2520 TempDescriptor tmp=tmpit.next();
2521 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2524 //copy outs that depend on path
2525 for(Iterator<TempDescriptor> tmpit=ar.liveoutvirtualread.iterator();tmpit.hasNext();) {
2526 TempDescriptor tmp=tmpit.next();
2527 if (!ar.livein.contains(tmp))
2528 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2532 /* Backup the temps. */
2533 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
2534 TempDescriptor tmp=tmpit.next();
2535 output.println(generateTemp(fm, backuptable.get(lb).get(tmp),lb)+"="+generateTemp(fm,tmp,lb)+";");
2538 output.println("goto transstart"+faen.getIdentifier()+";");
2540 /******* Print code to retry aborted transaction *******/
2541 output.println("transretry"+faen.getIdentifier()+":");
2544 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
2545 TempDescriptor tmp=tmpit.next();
2546 output.println(generateTemp(fm, tmp,lb)+"="+generateTemp(fm,backuptable.get(lb).get(tmp),lb)+";");
2550 /********* Need to revert local object store ********/
2551 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
2553 output.println("while ("+revertptr+") {");
2554 output.println("struct ___Object___ * tmpptr;");
2555 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
2556 output.println("REVERT_OBJ("+revertptr+");");
2557 output.println(revertptr+"=tmpptr;");
2558 output.println("}");
2560 /******* Tell the runtime to start the transaction *******/
2562 output.println("transstart"+faen.getIdentifier()+":");
2563 output.println("transStart();");
2565 if (state.ABORTREADERS) {
2566 output.println("if (_setjmp(aborttrans)) {");
2567 output.println(" goto transretry"+faen.getIdentifier()+"; }");
2571 public void generateFlatAtomicExitNode(FlatMethod fm, LocalityBinding lb, FlatAtomicExitNode faen, PrintWriter output) {
2572 /* Check to see if we need to generate code for this atomic */
2573 if (locality==null) {
2574 output.println("pthread_mutex_unlock(&atomiclock);");
2577 if (locality.getAtomic(lb).get(faen).intValue()>0)
2579 //store the revert list before we lose the transaction object
2580 String revertptr=null;
2582 revertptr=generateTemp(fm, reverttable.get(lb),lb);
2583 output.println(revertptr+"=revertlist;");
2585 if (state.DELAYCOMP) {
2586 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
2589 output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {");
2591 output.println("if (transCommit()) {");
2592 /* Transaction aborts if it returns true */
2593 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
2595 output.println("} else {");
2596 /* Need to commit local object store */
2597 output.println("while ("+revertptr+") {");
2598 output.println("struct ___Object___ * tmpptr;");
2599 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
2600 output.println("COMMIT_OBJ("+revertptr+");");
2601 output.println(revertptr+"=tmpptr;");
2602 output.println("}");
2604 output.println("}");
2605 if (state.DELAYCOMP) {
2607 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
2608 output.println("else {");
2609 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
2610 TempDescriptor tmp=tmpit.next();
2611 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
2613 output.println("}");
2617 public void generateFlatSESEEnterNode(FlatMethod fm, LocalityBinding lb, FlatSESEEnterNode fsen, PrintWriter output) {
2619 // SESE nodes can be parsed for normal compilation, just skip over them
2623 output.println("\n /* SESE "+fsen.getPrettyIdentifier()+" issue */");
2624 output.println(" tempSESE = mlpCreateSESErecord( "+
2625 fsen.getIdentifier()+", "+
2626 "malloc( sizeof( "+fsen.namespaceStructNameString()+") ), "+
2629 for( int i = 0; i < fsen.numParameters(); ++i ) {
2630 TempDescriptor td = fsen.getParameter( i );
2631 output.println(" (("+fsen.namespaceStructNameString()+
2632 "*)tempSESE->namespace)->"+td+" = "+td+";");
2635 output.println(" mlpIssue( tempSESE );");
2636 //output.println(" tempSESE = mlpSchedule();");
2638 // do a pthread_create wit invokeSESE as the argument
2639 // and pack all args into a single void*
2640 output.println(" tempSESEargs = malloc( sizeof( invokeSESEargs ) );");
2641 output.println(" tempSESEargs->classID = "+fsen.getIdentifier()+";");
2642 output.println(" tempSESEargs->invokee = mlpSchedule();");
2644 if( fsen.getParent() == null ) {
2645 output.println(" tempSESEargs->parent = NULL;");
2647 output.println(" tempSESEargs->parent = currentSESE;");
2650 output.println(" invokeSESEmethod( (void*) tempSESEargs );");
2651 output.println("\n");
2654 public void generateFlatSESEExitNode(FlatMethod fm, LocalityBinding lb, FlatSESEExitNode fsen, PrintWriter output) {
2656 // SESE nodes can be parsed for normal compilation, just skip over them
2661 private void generateFlatCheckNode(FlatMethod fm, LocalityBinding lb, FlatCheckNode fcn, PrintWriter output) {
2662 if (state.CONSCHECK) {
2663 String specname=fcn.getSpec();
2664 String varname="repairstate___";
2665 output.println("{");
2666 output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
2668 TempDescriptor[] temps=fcn.getTemps();
2669 String[] vars=fcn.getVars();
2670 for(int i=0; i<temps.length; i++) {
2671 output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i],lb)+";");
2674 output.println("if (doanalysis"+specname+"("+varname+")) {");
2675 output.println("free"+specname+"_state("+varname+");");
2676 output.println("} else {");
2677 output.println("/* Bad invariant */");
2678 output.println("free"+specname+"_state("+varname+");");
2679 output.println("abort_task();");
2680 output.println("}");
2681 output.println("}");
2685 private void generateFlatCall(FlatMethod fm, LocalityBinding lb, FlatCall fc, PrintWriter output) {
2686 MethodDescriptor md=fc.getMethod();
2687 ParamsObject objectparams=(ParamsObject)paramstable.get(state.DSM||state.SINGLETM ? locality.getBinding(lb, fc) : md);
2688 ClassDescriptor cn=md.getClassDesc();
2689 output.println("{");
2690 if (GENERATEPRECISEGC) {
2691 if (state.DSM||state.SINGLETM) {
2692 LocalityBinding fclb=locality.getBinding(lb, fc);
2693 output.print(" struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
2695 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
2697 output.print(objectparams.numPointers());
2698 output.print(", "+localsprefixaddr);
2699 if (md.getThis()!=null) {
2701 output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis(),lb));
2703 if (fc.getThis()!=null&&md.getThis()==null) {
2704 System.out.println("WARNING!!!!!!!!!!!!");
2705 System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
2709 for(int i=0; i<fc.numArgs(); i++) {
2710 Descriptor var=md.getParameter(i);
2711 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
2712 if (objectparams.isParamPtr(paramtemp)) {
2713 TempDescriptor targ=fc.getArg(i);
2715 TypeDescriptor td=md.getParamType(i);
2717 output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
2719 output.print("(struct "+md.getParamType(i).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
2722 output.println("};");
2727 if (fc.getReturnTemp()!=null)
2728 output.print(generateTemp(fm,fc.getReturnTemp(),lb)+"=");
2730 /* Do we need to do virtual dispatch? */
2731 if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
2733 if (state.DSM||state.SINGLETM) {
2734 LocalityBinding fclb=locality.getBinding(lb, fc);
2735 output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
2737 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
2742 if (md.getReturnType().isClass()||md.getReturnType().isArray())
2743 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
2745 output.print(md.getReturnType().getSafeSymbol()+" ");
2746 output.print("(*)(");
2748 boolean printcomma=false;
2749 if (GENERATEPRECISEGC) {
2750 if (state.DSM||state.SINGLETM) {
2751 LocalityBinding fclb=locality.getBinding(lb, fc);
2752 output.print("struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
2754 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
2758 for(int i=0; i<objectparams.numPrimitives(); i++) {
2759 TempDescriptor temp=objectparams.getPrimitive(i);
2763 if (temp.getType().isClass()||temp.getType().isArray())
2764 output.print("struct " + temp.getType().getSafeSymbol()+" * ");
2766 output.print(temp.getType().getSafeSymbol());
2770 if (state.DSM||state.SINGLETM) {
2771 LocalityBinding fclb=locality.getBinding(lb, fc);
2772 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])");
2774 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
2778 boolean needcomma=false;
2779 if (GENERATEPRECISEGC) {
2780 output.print("&__parameterlist__");
2784 if (!GENERATEPRECISEGC) {
2785 if (fc.getThis()!=null) {
2786 TypeDescriptor ptd=md.getThis().getType();
2789 if (ptd.isClass()&&!ptd.isArray())
2790 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
2791 output.print(generateTemp(fm,fc.getThis(),lb));
2796 for(int i=0; i<fc.numArgs(); i++) {
2797 Descriptor var=md.getParameter(i);
2798 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
2799 if (objectparams.isParamPrim(paramtemp)) {
2800 TempDescriptor targ=fc.getArg(i);
2804 TypeDescriptor ptd=md.getParamType(i);
2805 if (ptd.isClass()&&!ptd.isArray())
2806 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
2807 output.print(generateTemp(fm, targ,lb));
2811 output.println(");");
2812 output.println(" }");
2815 private boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
2816 Set subclasses=typeutil.getSubClasses(thiscd);
2817 if (subclasses==null)
2819 for(Iterator classit=subclasses.iterator(); classit.hasNext();) {
2820 ClassDescriptor cd=(ClassDescriptor)classit.next();
2821 Set possiblematches=cd.getMethodTable().getSet(md.getSymbol());
2822 for(Iterator matchit=possiblematches.iterator(); matchit.hasNext();) {
2823 MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
2824 if (md.matches(matchmd))
2831 private void generateFlatFieldNode(FlatMethod fm, LocalityBinding lb, FlatFieldNode ffn, PrintWriter output) {
2832 if (state.SINGLETM) {
2833 //single machine transactional memory case
2834 String field=ffn.getField().getSafeSymbol();
2835 String src=generateTemp(fm, ffn.getSrc(),lb);
2836 String dst=generateTemp(fm, ffn.getDst(),lb);
2838 output.println(dst+"="+ src +"->"+field+ ";");
2839 if (ffn.getField().getType().isPtr()&&locality.getAtomic(lb).get(ffn).intValue()>0&&
2840 locality.getNodePreTempInfo(lb, ffn).get(ffn.getSrc())!=LocalityAnalysis.SCRATCH) {
2841 if ((dc==null)||(!state.READSET&&dc.getNeedTrans(lb, ffn))||
2842 (state.READSET&&dc.getNeedWriteTrans(lb, ffn))) {
2843 output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));");
2844 } else if (state.READSET&&dc.getNeedTrans(lb, ffn)) {
2845 output.println("TRANSREADRD("+dst+", "+dst+");");
2848 } else if (state.DSM) {
2849 Integer status=locality.getNodePreTempInfo(lb,ffn).get(ffn.getSrc());
2850 if (status==LocalityAnalysis.GLOBAL) {
2851 String field=ffn.getField().getSafeSymbol();
2852 String src=generateTemp(fm, ffn.getSrc(),lb);
2853 String dst=generateTemp(fm, ffn.getDst(),lb);
2855 if (ffn.getField().getType().isPtr()) {
2857 //TODO: Uncomment this when we have runtime support
2858 //if (ffn.getSrc()==ffn.getDst()) {
2859 //output.println("{");
2860 //output.println("void * temp="+src+";");
2861 //output.println("if (temp&0x1) {");
2862 //output.println("temp=(void *) transRead(trans, (unsigned int) temp);");
2863 //output.println(src+"->"+field+"="+temp+";");
2864 //output.println("}");
2865 //output.println(dst+"=temp;");
2866 //output.println("}");
2868 output.println(dst+"="+ src +"->"+field+ ";");
2869 //output.println("if ("+dst+"&0x1) {");
2870 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
2871 //output.println(src+"->"+field+"="+src+"->"+field+";");
2872 //output.println("}");
2875 output.println(dst+"="+ src+"->"+field+";");
2877 } else if (status==LocalityAnalysis.LOCAL) {
2878 if (ffn.getField().getType().isPtr()&&
2879 ffn.getField().isGlobal()) {
2880 String field=ffn.getField().getSafeSymbol();
2881 String src=generateTemp(fm, ffn.getSrc(),lb);
2882 String dst=generateTemp(fm, ffn.getDst(),lb);
2883 output.println(dst+"="+ src +"->"+field+ ";");
2884 if (locality.getAtomic(lb).get(ffn).intValue()>0)
2885 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
2887 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
2888 } else if (status==LocalityAnalysis.EITHER) {
2889 //Code is reading from a null pointer
2890 output.println("if ("+generateTemp(fm, ffn.getSrc(),lb)+") {");
2891 output.println("#ifndef RAW");
2892 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
2893 output.println("#endif");
2894 //This should throw a suitable null pointer error
2895 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
2897 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
2899 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
2903 private void generateFlatSetFieldNode(FlatMethod fm, LocalityBinding lb, FlatSetFieldNode fsfn, PrintWriter output) {
2904 if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
2905 throw new Error("Can't set array length");
2906 if (state.SINGLETM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
2907 //Single Machine Transaction Case
2908 boolean srcptr=fsfn.getSrc().getType().isPtr();
2909 String src=generateTemp(fm,fsfn.getSrc(),lb);
2910 String dst=generateTemp(fm,fsfn.getDst(),lb);
2911 if (srcptr&&!fsfn.getSrc().getType().isNull()) {
2912 output.println("{");
2913 if ((dc==null)||dc.getNeedSrcTrans(lb, fsfn)&&
2914 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) {
2915 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
2917 output.println("INTPTR srcoid=(INTPTR)"+src+";");
2920 if (wb.needBarrier(fsfn)&&
2921 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getDst())!=LocalityAnalysis.SCRATCH) {
2922 output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;");
2924 if (srcptr&!fsfn.getSrc().getType().isNull()) {
2925 output.println("*((unsigned INTPTR *)&("+dst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
2926 output.println("}");
2928 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
2930 } else if (state.DSM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
2931 Integer statussrc=locality.getNodePreTempInfo(lb,fsfn).get(fsfn.getSrc());
2932 Integer statusdst=locality.getNodeTempInfo(lb).get(fsfn).get(fsfn.getDst());
2933 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
2935 String src=generateTemp(fm,fsfn.getSrc(),lb);
2936 String dst=generateTemp(fm,fsfn.getDst(),lb);
2938 output.println("{");
2939 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
2941 if (statusdst.equals(LocalityAnalysis.GLOBAL)) {
2944 if (wb.needBarrier(fsfn))
2945 output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;");
2947 output.println("*((unsigned INTPTR *)&("+glbdst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
2949 output.println(glbdst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
2950 } else if (statusdst.equals(LocalityAnalysis.LOCAL)) {
2951 /** Check if we need to copy */
2952 output.println("if(!"+dst+"->"+localcopystr+") {");
2953 /* Link object into list */
2954 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
2955 output.println(revertptr+"=revertlist;");
2956 if (GENERATEPRECISEGC)
2957 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
2959 output.println("COPY_OBJ("+dst+");");
2960 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
2961 output.println("revertlist=(struct ___Object___ *)"+dst+";");
2962 output.println("}");
2964 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
2966 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
2967 } else if (statusdst.equals(LocalityAnalysis.EITHER)) {
2968 //writing to a null...bad
2969 output.println("if ("+dst+") {");
2970 output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}");
2972 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
2974 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
2977 output.println("}");
2980 if (state.FASTCHECK) {
2981 String dst=generateTemp(fm, fsfn.getDst(),lb);
2982 output.println("if(!"+dst+"->"+localcopystr+") {");
2983 /* Link object into list */
2984 if (GENERATEPRECISEGC)
2985 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
2987 output.println("COPY_OBJ("+dst+");");
2988 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
2989 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
2990 output.println("}");
2992 output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
2996 private void generateFlatElementNode(FlatMethod fm, LocalityBinding lb, FlatElementNode fen, PrintWriter output) {
2997 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
3000 if (elementtype.isArray()||elementtype.isClass())
3003 type=elementtype.getSafeSymbol()+" ";
3005 if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
3006 output.println("if ("+generateTemp(fm, fen.getIndex(),lb)+"< 0 | "+generateTemp(fm, fen.getIndex(),lb)+" >= "+generateTemp(fm,fen.getSrc(),lb) + "->___length___)");
3007 output.println("failedboundschk();");
3009 if (state.SINGLETM) {
3010 //Single machine transaction case
3011 String dst=generateTemp(fm, fen.getDst(),lb);
3012 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3014 if (elementtype.isPtr()&&locality.getAtomic(lb).get(fen).intValue()>0&&
3015 locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())!=LocalityAnalysis.SCRATCH) {
3016 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fen)||state.READSET&&dc.getNeedWriteTrans(lb, fen)) {
3017 output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));");
3018 } else if (state.READSET&&dc.getNeedTrans(lb, fen)) {
3019 output.println("TRANSREADRD("+dst+", "+dst+");");
3022 } else if (state.DSM) {
3023 Integer status=locality.getNodePreTempInfo(lb,fen).get(fen.getSrc());
3024 if (status==LocalityAnalysis.GLOBAL) {
3025 String dst=generateTemp(fm, fen.getDst(),lb);
3027 if (elementtype.isPtr()) {
3028 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3029 output.println("TRANSREAD("+dst+", "+dst+");");
3031 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3033 } else if (status==LocalityAnalysis.LOCAL) {
3034 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3035 } else if (status==LocalityAnalysis.EITHER) {
3036 //Code is reading from a null pointer
3037 output.println("if ("+generateTemp(fm, fen.getSrc(),lb)+") {");
3038 output.println("#ifndef RAW");
3039 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
3040 output.println("#endif");
3041 //This should throw a suitable null pointer error
3042 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3044 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
3046 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3050 private void generateFlatSetElementNode(FlatMethod fm, LocalityBinding lb, FlatSetElementNode fsen, PrintWriter output) {
3051 //TODO: need dynamic check to make sure this assignment is actually legal
3052 //Because Object[] could actually be something more specific...ie. Integer[]
3054 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
3057 if (elementtype.isArray()||elementtype.isClass())
3060 type=elementtype.getSafeSymbol()+" ";
3062 if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
3063 output.println("if ("+generateTemp(fm, fsen.getIndex(),lb)+"< 0 | "+generateTemp(fm, fsen.getIndex(),lb)+" >= "+generateTemp(fm,fsen.getDst(),lb) + "->___length___)");
3064 output.println("failedboundschk();");
3067 if (state.SINGLETM && locality.getAtomic(lb).get(fsen).intValue()>0) {
3068 //Transaction set element case
3069 if (wb.needBarrier(fsen)&&
3070 locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH) {
3071 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___objstatus___))|=DIRTY;");
3073 if (fsen.getSrc().getType().isPtr()&&!fsen.getSrc().getType().isNull()) {
3074 output.println("{");
3075 String src=generateTemp(fm, fsen.getSrc(), lb);
3076 if ((dc==null)||dc.getNeedSrcTrans(lb, fsen)&&
3077 locality.getNodePreTempInfo(lb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) {
3078 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3080 output.println("INTPTR srcoid=(INTPTR)"+src+";");
3082 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
3083 output.println("}");
3085 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
3087 } else if (state.DSM && locality.getAtomic(lb).get(fsen).intValue()>0) {
3088 Integer statussrc=locality.getNodePreTempInfo(lb,fsen).get(fsen.getSrc());
3089 Integer statusdst=locality.getNodePreTempInfo(lb,fsen).get(fsen.getDst());
3090 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
3091 boolean dstglobal=statusdst==LocalityAnalysis.GLOBAL;
3092 boolean dstlocal=statusdst==LocalityAnalysis.LOCAL;
3095 if (wb.needBarrier(fsen))
3096 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___localcopy___))|=DIRTY;");
3097 } else if (dstlocal) {
3098 /** Check if we need to copy */
3099 String dst=generateTemp(fm, fsen.getDst(),lb);
3100 output.println("if(!"+dst+"->"+localcopystr+") {");
3101 /* Link object into list */
3102 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3103 output.println(revertptr+"=revertlist;");
3104 if (GENERATEPRECISEGC)
3105 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3107 output.println("COPY_OBJ("+dst+");");
3108 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
3109 output.println("revertlist=(struct ___Object___ *)"+dst+";");
3110 output.println("}");
3111 } else throw new Error("Unknown array type");
3113 output.println("{");
3114 String src=generateTemp(fm, fsen.getSrc(), lb);
3115 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3116 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
3117 output.println("}");
3119 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
3122 if (state.FASTCHECK) {
3123 String dst=generateTemp(fm, fsen.getDst(),lb);
3124 output.println("if(!"+dst+"->"+localcopystr+") {");
3125 /* Link object into list */
3126 if (GENERATEPRECISEGC)
3127 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3129 output.println("COPY_OBJ("+dst+");");
3130 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
3131 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
3132 output.println("}");
3134 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
3138 protected void generateFlatNew(FlatMethod fm, LocalityBinding lb, FlatNew fn, PrintWriter output) {
3139 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
3140 //Stash pointer in case of GC
3141 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3142 output.println(revertptr+"=revertlist;");
3144 if (state.SINGLETM) {
3145 if (fn.getType().isArray()) {
3146 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
3147 if (locality.getAtomic(lb).get(fn).intValue()>0) {
3148 //inside transaction
3149 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3151 //outside transaction
3152 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3155 if (locality.getAtomic(lb).get(fn).intValue()>0) {
3156 //inside transaction
3157 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
3159 //outside transaction
3160 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
3163 } else if (fn.getType().isArray()) {
3164 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
3165 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
3166 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3167 } else if (GENERATEPRECISEGC) {
3168 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3170 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3173 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
3174 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");");
3175 } else if (GENERATEPRECISEGC) {
3176 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
3178 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
3181 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
3182 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3183 String dst=generateTemp(fm,fn.getDst(),lb);
3184 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
3185 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
3186 output.println("revertlist=(struct ___Object___ *)"+dst+";");
3188 if (state.FASTCHECK) {
3189 String dst=generateTemp(fm,fn.getDst(),lb);
3190 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
3191 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
3192 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
3196 private void generateFlatTagDeclaration(FlatMethod fm, LocalityBinding lb, FlatTagDeclaration fn, PrintWriter output) {
3197 if (GENERATEPRECISEGC) {
3198 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
3200 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+state.getTagId(fn.getType())+");");
3204 private void generateFlatOpNode(FlatMethod fm, LocalityBinding lb, FlatOpNode fon, PrintWriter output) {
3205 if (fon.getRight()!=null) {
3206 if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
3207 if (fon.getLeft().getType().isLong())
3208 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
3210 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned int)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
3212 } else if (dc!=null) {
3213 output.print(generateTemp(fm, fon.getDest(),lb)+" = ");
3214 if (dc.getNeedLeftSrcTrans(lb, fon))
3215 output.print("("+generateTemp(fm, fon.getLeft(),lb)+"!=NULL?"+generateTemp(fm, fon.getLeft(),lb)+"->"+oidstr+":NULL)");
3217 output.print(generateTemp(fm, fon.getLeft(),lb));
3218 output.print(fon.getOp().toString());
3219 if (dc.getNeedRightSrcTrans(lb, fon))
3220 output.println("("+generateTemp(fm, fon.getRight(),lb)+"!=NULL?"+generateTemp(fm, fon.getRight(),lb)+"->"+oidstr+":NULL);");
3222 output.println(generateTemp(fm,fon.getRight(),lb)+";");
3224 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+fon.getOp().toString()+generateTemp(fm,fon.getRight(),lb)+";");
3225 } else if (fon.getOp().getOp()==Operation.ASSIGN)
3226 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
3227 else if (fon.getOp().getOp()==Operation.UNARYPLUS)
3228 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
3229 else if (fon.getOp().getOp()==Operation.UNARYMINUS)
3230 output.println(generateTemp(fm, fon.getDest(),lb)+" = -"+generateTemp(fm, fon.getLeft(),lb)+";");
3231 else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
3232 output.println(generateTemp(fm, fon.getDest(),lb)+" = !"+generateTemp(fm, fon.getLeft(),lb)+";");
3233 else if (fon.getOp().getOp()==Operation.COMP)
3234 output.println(generateTemp(fm, fon.getDest(),lb)+" = ~"+generateTemp(fm, fon.getLeft(),lb)+";");
3235 else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
3236 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+"->fses==NULL;");
3238 output.println(generateTemp(fm, fon.getDest(),lb)+fon.getOp().toString()+generateTemp(fm, fon.getLeft(),lb)+";");
3241 private void generateFlatCastNode(FlatMethod fm, LocalityBinding lb, FlatCastNode fcn, PrintWriter output) {
3242 /* TODO: Do type check here */
3243 if (fcn.getType().isArray()) {
3244 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
3245 } else if (fcn.getType().isClass())
3246 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
3248 output.println(generateTemp(fm,fcn.getDst(),lb)+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc(),lb)+";");
3251 private void generateFlatLiteralNode(FlatMethod fm, LocalityBinding lb, FlatLiteralNode fln, PrintWriter output) {
3252 if (fln.getValue()==null)
3253 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
3254 else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
3255 if (GENERATEPRECISEGC) {
3256 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
3257 //Stash pointer in case of GC
3258 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3259 output.println(revertptr+"=revertlist;");
3261 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
3262 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
3263 //Stash pointer in case of GC
3264 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3265 output.println("revertlist="+revertptr+";");
3268 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
3270 } else if (fln.getType().isBoolean()) {
3271 if (((Boolean)fln.getValue()).booleanValue())
3272 output.println(generateTemp(fm, fln.getDst(),lb)+"=1;");
3274 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
3275 } else if (fln.getType().isChar()) {
3276 String st=FlatLiteralNode.escapeString(fln.getValue().toString());
3277 output.println(generateTemp(fm, fln.getDst(),lb)+"='"+st+"';");
3278 } else if (fln.getType().isLong()) {
3279 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+"LL;");
3281 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+";");
3284 protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) {
3285 if (frn.getReturnTemp()!=null) {
3286 if (frn.getReturnTemp().getType().isPtr())
3287 output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";");
3289 output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";");
3291 output.println("return;");
3295 protected void generateStoreFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
3296 output.println("STOREANDBRANCH(!"+generateTemp(fm, fcb.getTest(),lb)+", "+label+");");
3299 protected void generateFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
3300 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") goto "+label+";");
3303 /** This method generates header information for the method or
3304 * task referenced by the Descriptor des. */
3305 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) {
3306 generateHeader(fm, lb, des, output, false);
3309 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output, boolean addSESErecord) {
3311 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : des);
3312 MethodDescriptor md=null;
3313 TaskDescriptor task=null;
3314 if (des instanceof MethodDescriptor)
3315 md=(MethodDescriptor) des;
3317 task=(TaskDescriptor) des;
3319 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
3321 if (md!=null&&md.getReturnType()!=null) {
3322 if (md.getReturnType().isClass()||md.getReturnType().isArray())
3323 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
3325 output.print(md.getReturnType().getSafeSymbol()+" ");
3327 //catch the constructor case
3328 output.print("void ");
3330 if (state.DSM||state.SINGLETM) {
3331 output.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
3333 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
3335 output.print(task.getSafeSymbol()+"(");
3337 if (addSESErecord) {
3338 output.print("SESErecord* currentSESE, ");
3341 boolean printcomma=false;
3342 if (GENERATEPRECISEGC) {
3344 if (state.DSM||state.SINGLETM) {
3345 output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
3347 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
3349 output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
3355 for(int i=0; i<objectparams.numPrimitives(); i++) {
3356 TempDescriptor temp=objectparams.getPrimitive(i);
3360 if (temp.getType().isClass()||temp.getType().isArray())
3361 output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
3363 output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
3365 output.println(") {");
3366 } else if (!GENERATEPRECISEGC) {
3367 /* Imprecise Task */
3368 output.println("void * parameterarray[]) {");
3369 /* Unpack variables */
3370 for(int i=0; i<objectparams.numPrimitives(); i++) {
3371 TempDescriptor temp=objectparams.getPrimitive(i);
3372 output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
3374 for(int i=0; i<fm.numTags(); i++) {
3375 TempDescriptor temp=fm.getTag(i);
3376 int offset=i+objectparams.numPrimitives();
3377 output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
3380 if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
3381 maxtaskparams=objectparams.numPrimitives()+fm.numTags();
3382 } else output.println(") {");
3385 public void generateFlatFlagActionNode(FlatMethod fm, LocalityBinding lb, FlatFlagActionNode ffan, PrintWriter output) {
3386 output.println("/* FlatFlagActionNode */");
3389 /* Process tag changes */
3390 Relation tagsettable=new Relation();
3391 Relation tagcleartable=new Relation();
3393 Iterator tagsit=ffan.getTempTagPairs();
3394 while (tagsit.hasNext()) {
3395 TempTagPair ttp=(TempTagPair) tagsit.next();
3396 TempDescriptor objtmp=ttp.getTemp();
3397 TagDescriptor tag=ttp.getTag();
3398 TempDescriptor tagtmp=ttp.getTagTemp();
3399 boolean tagstatus=ffan.getTagChange(ttp);
3401 tagsettable.put(objtmp, tagtmp);
3403 tagcleartable.put(objtmp, tagtmp);
3408 Hashtable flagandtable=new Hashtable();
3409 Hashtable flagortable=new Hashtable();
3411 /* Process flag changes */
3412 Iterator flagsit=ffan.getTempFlagPairs();
3413 while(flagsit.hasNext()) {
3414 TempFlagPair tfp=(TempFlagPair)flagsit.next();
3415 TempDescriptor temp=tfp.getTemp();
3416 Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
3417 FlagDescriptor flag=tfp.getFlag();
3419 //Newly allocate objects that don't set any flags case
3420 if (flagortable.containsKey(temp)) {
3424 flagortable.put(temp,new Integer(mask));
3426 int flagid=1<<((Integer)flagtable.get(flag)).intValue();
3427 boolean flagstatus=ffan.getFlagChange(tfp);
3430 if (flagortable.containsKey(temp)) {
3431 mask=((Integer)flagortable.get(temp)).intValue();
3434 flagortable.put(temp,new Integer(mask));
3436 int mask=0xFFFFFFFF;
3437 if (flagandtable.containsKey(temp)) {
3438 mask=((Integer)flagandtable.get(temp)).intValue();
3440 mask&=(0xFFFFFFFF^flagid);
3441 flagandtable.put(temp,new Integer(mask));
3447 HashSet flagtagset=new HashSet();
3448 flagtagset.addAll(flagortable.keySet());
3449 flagtagset.addAll(flagandtable.keySet());
3450 flagtagset.addAll(tagsettable.keySet());
3451 flagtagset.addAll(tagcleartable.keySet());
3453 Iterator ftit=flagtagset.iterator();
3454 while(ftit.hasNext()) {
3455 TempDescriptor temp=(TempDescriptor)ftit.next();
3458 Set tagtmps=tagcleartable.get(temp);
3459 if (tagtmps!=null) {
3460 Iterator tagit=tagtmps.iterator();
3461 while(tagit.hasNext()) {
3462 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
3463 if (GENERATEPRECISEGC)
3464 output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
3466 output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
3470 tagtmps=tagsettable.get(temp);
3471 if (tagtmps!=null) {
3472 Iterator tagit=tagtmps.iterator();
3473 while(tagit.hasNext()) {
3474 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
3475 if (GENERATEPRECISEGC)
3476 output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
3478 output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp, lb)+", "+generateTemp(fm,tagtmp, lb)+");");
3483 int andmask=0xFFFFFFF;
3485 if (flagortable.containsKey(temp))
3486 ormask=((Integer)flagortable.get(temp)).intValue();
3487 if (flagandtable.containsKey(temp))
3488 andmask=((Integer)flagandtable.get(temp)).intValue();
3489 generateFlagOrAnd(ffan, fm, lb, temp, output, ormask, andmask);
3490 generateObjectDistribute(ffan, fm, lb, temp, output);
3494 protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp,
3495 PrintWriter output, int ormask, int andmask) {
3496 if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
3497 output.println("flagorandinit("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
3499 output.println("flagorand("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
3503 protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, PrintWriter output) {
3504 output.println("enqueueObject("+generateTemp(fm, temp, lb)+");");
3507 void generateOptionalHeader(PrintWriter headers) {
3510 headers.println("#include \"task.h\"\n\n");
3511 headers.println("#ifndef _OPTIONAL_STRUCT_");
3512 headers.println("#define _OPTIONAL_STRUCT_");
3514 //STRUCT PREDICATEMEMBER
3515 headers.println("struct predicatemember{");
3516 headers.println("int type;");
3517 headers.println("int numdnfterms;");
3518 headers.println("int * flags;");
3519 headers.println("int numtags;");
3520 headers.println("int * tags;\n};\n\n");
3522 //STRUCT OPTIONALTASKDESCRIPTOR
3523 headers.println("struct optionaltaskdescriptor{");
3524 headers.println("struct taskdescriptor * task;");
3525 headers.println("int index;");
3526 headers.println("int numenterflags;");
3527 headers.println("int * enterflags;");
3528 headers.println("int numpredicatemembers;");
3529 headers.println("struct predicatemember ** predicatememberarray;");
3530 headers.println("};\n\n");
3532 //STRUCT TASKFAILURE
3533 headers.println("struct taskfailure {");
3534 headers.println("struct taskdescriptor * task;");
3535 headers.println("int index;");
3536 headers.println("int numoptionaltaskdescriptors;");
3537 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
3539 //STRUCT FSANALYSISWRAPPER
3540 headers.println("struct fsanalysiswrapper{");
3541 headers.println("int flags;");
3542 headers.println("int numtags;");
3543 headers.println("int * tags;");
3544 headers.println("int numtaskfailures;");
3545 headers.println("struct taskfailure ** taskfailurearray;");
3546 headers.println("int numoptionaltaskdescriptors;");
3547 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
3549 //STRUCT CLASSANALYSISWRAPPER
3550 headers.println("struct classanalysiswrapper{");
3551 headers.println("int type;");
3552 headers.println("int numotd;");
3553 headers.println("struct optionaltaskdescriptor ** otdarray;");
3554 headers.println("int numfsanalysiswrappers;");
3555 headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
3557 headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
3559 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
3560 while(taskit.hasNext()) {
3561 TaskDescriptor td=(TaskDescriptor)taskit.next();
3562 headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
3567 //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
3568 int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
3569 int predicateindex = 0;
3570 //iterate through the classes concerned by the predicate
3571 Set c_vard = predicate.vardescriptors;
3572 Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
3575 for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext();) {
3576 VarDescriptor vard = (VarDescriptor)vard_it.next();
3577 TypeDescriptor typed = vard.getType();
3579 //generate for flags
3580 HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
3581 output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
3583 if (fen_hashset!=null) {
3584 for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext();) {
3585 FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
3587 DNFFlag dflag=fen.getDNF();
3588 numberterms+=dflag.size();
3590 Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
3592 for(int j=0; j<dflag.size(); j++) {
3594 output.println(",");
3595 Vector term=dflag.get(j);
3598 for(int k=0; k<term.size(); k++) {
3599 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
3600 FlagDescriptor fd=dfa.getFlag();
3601 boolean negated=dfa.getNegated();
3602 int flagid=1<<((Integer)flags.get(fd)).intValue();
3607 output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
3612 output.println("};\n");
3615 TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
3616 output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
3619 for(int j=0; j<tagel.numTags(); j++) {
3621 output.println(",");
3622 TempDescriptor tmp=tagel.getTemp(j);
3623 if (!slotnumber.containsKey(tmp)) {
3624 Integer slotint=new Integer(current_slot++);
3625 slotnumber.put(tmp,slotint);
3627 int slot=slotnumber.get(tmp).intValue();
3628 output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
3630 numtags = tagel.numTags();
3632 output.println("};");
3634 //store the result into a predicatemember struct
3635 output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
3636 output.println("/*type*/"+typed.getClassDesc().getId()+",");
3637 output.println("/* number of dnf terms */"+numberterms+",");
3638 output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
3639 output.println("/* number of tag */"+numtags+",");
3640 output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
3641 output.println("};\n");
3646 //generate an array that stores the entire predicate
3647 output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
3648 for( int j = 0; j<predicateindex; j++) {
3649 if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
3650 else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
3652 output.println("};\n");
3653 return predicateindex;
3657 void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
3658 generateOptionalHeader(headers);
3660 output.println("#include \"optionalstruct.h\"\n\n");
3661 output.println("#include \"stdlib.h\"\n");
3663 HashSet processedcd = new HashSet();
3665 Enumeration e = safeexecution.keys();
3666 while (e.hasMoreElements()) {
3669 ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
3670 Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp); //will be used several times
3672 //Generate the struct of optionals
3673 Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
3674 numotd = c_otd.size();
3675 if(maxotd<numotd) maxotd = numotd;
3676 if( !c_otd.isEmpty() ) {
3677 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
3678 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
3680 //generate the int arrays for the predicate
3681 Predicate predicate = otd.predicate;
3682 int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
3683 TreeSet<Integer> fsset=new TreeSet<Integer>();
3684 //iterate through possible FSes corresponding to
3685 //the state when entering
3687 for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext();) {
3688 FlagState fs = (FlagState)fses.next();
3690 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
3691 FlagDescriptor flagd = (FlagDescriptor)flags.next();
3692 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
3695 fsset.add(new Integer(flagid));
3696 //tag information not needed because tag
3697 //changes are not tolerated.
3700 output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
3701 boolean needcomma=false;
3702 for(Iterator<Integer> it=fsset.iterator(); it.hasNext();) {
3705 output.println(it.next());
3708 output.println("};\n");
3711 //generate optionaltaskdescriptor that actually
3712 //includes exit fses, predicate and the task
3714 output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
3715 output.println("&task_"+otd.td.getSafeSymbol()+",");
3716 output.println("/*index*/"+otd.getIndex()+",");
3717 output.println("/*number of enter flags*/"+fsset.size()+",");
3718 output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
3719 output.println("/*number of members */"+predicateindex+",");
3720 output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
3721 output.println("};\n");
3725 // if there are no optionals, there is no need to build the rest of the struct
3727 output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
3728 c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
3729 if( !c_otd.isEmpty() ) {
3730 boolean needcomma=false;
3731 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
3732 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
3734 output.println(",");
3736 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
3739 output.println("};\n");
3741 //get all the possible flagstates reachable by an object
3742 Hashtable hashtbtemp = safeexecution.get(cdtemp);
3744 TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
3745 fsts.addAll(hashtbtemp.keySet());
3746 for(Iterator fsit=fsts.iterator(); fsit.hasNext();) {
3747 FlagState fs = (FlagState)fsit.next();
3750 //get the set of OptionalTaskDescriptors corresponding
3751 HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
3752 //iterate through the OptionalTaskDescriptors and
3753 //store the pointers to the optionals struct (see on
3754 //top) into an array
3756 output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
3757 for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext();) {
3758 OptionalTaskDescriptor mm = mos.next();
3760 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
3762 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
3765 output.println("};\n");
3767 //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
3770 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
3771 FlagDescriptor flagd = (FlagDescriptor)flags.next();
3772 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
3776 //process tag information
3779 boolean first = true;
3780 Enumeration tag_enum = fs.getTags();
3781 output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
3782 while(tag_enum.hasMoreElements()) {
3784 TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
3788 output.println(", ");
3789 output.println("/*tagid*/"+state.getTagId(tagd));
3791 output.println("};");
3793 Set<TaskIndex> tiset=sa.getTaskIndex(fs);
3794 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
3795 TaskIndex ti=itti.next();
3799 Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
3801 output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
3802 boolean needcomma=false;
3803 for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext();) {
3804 OptionalTaskDescriptor otd=otdit.next();
3808 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
3810 output.println("};");
3812 output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
3813 output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
3814 output.print(ti.getIndex()+", ");
3815 output.print(otdset.size()+", ");
3816 output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
3817 output.println("};");
3820 tiset=sa.getTaskIndex(fs);
3821 boolean needcomma=false;
3823 output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
3824 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
3825 TaskIndex ti=itti.next();
3826 if (ti.isRuntime()) {
3833 output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
3835 output.println("};\n");
3837 //Store the result in fsanalysiswrapper
3839 output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
3840 output.println("/*flag*/"+flagid+",");
3841 output.println("/* number of tags*/"+tagcounter+",");
3842 output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
3843 output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
3844 output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
3845 output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
3846 output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
3847 output.println("};\n");
3851 //Build the array of fsanalysiswrappers
3852 output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
3853 boolean needcomma=false;
3854 for(int i = 0; i<fscounter; i++) {
3855 if (needcomma) output.print(",");
3856 output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
3859 output.println("};");
3861 //Build the classanalysiswrapper referring to the previous array
3862 output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
3863 output.println("/*type*/"+cdtemp.getId()+",");
3864 output.println("/*numotd*/"+numotd+",");
3865 output.println("otdarray"+cdtemp.getSafeSymbol()+",");
3866 output.println("/* number of fsanalysiswrappers */"+fscounter+",");
3867 output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
3868 processedcd.add(cdtemp);
3871 //build an array containing every classes for which code has been build
3872 output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
3873 for(int i=0; i<state.numClasses(); i++) {
3874 ClassDescriptor cn=cdarray[i];
3877 if (processedcd.contains(cn))
3878 output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
3880 output.print("NULL");
3882 output.println("};");
3884 output.println("#define MAXOTD "+maxotd);
3885 headers.println("#endif");
3888 public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
3889 Relation r=new Relation();
3890 for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext();) {
3891 OptionalTaskDescriptor otd=otdit.next();
3892 TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
3896 LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
3897 for(Iterator it=r.keySet().iterator(); it.hasNext();) {
3898 Set s=r.get(it.next());
3899 for(Iterator it2=s.iterator(); it2.hasNext();) {
3900 OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
3908 protected void outputTransCode(PrintWriter output) {