2 import IR.Tree.Modifiers;
3 import IR.Tree.FlagExpressionNode;
4 import IR.Tree.DNFFlag;
5 import IR.Tree.DNFFlagAtom;
6 import IR.Tree.TagExpressionList;
7 import IR.Tree.OffsetNode;
14 import Analysis.TaskStateAnalysis.FlagState;
15 import Analysis.TaskStateAnalysis.FlagComparator;
16 import Analysis.TaskStateAnalysis.OptionalTaskDescriptor;
17 import Analysis.TaskStateAnalysis.Predicate;
18 import Analysis.TaskStateAnalysis.SafetyAnalysis;
19 import Analysis.TaskStateAnalysis.TaskIndex;
20 import Analysis.CallGraph.CallGraph;
21 import Analysis.Loops.GlobalFieldType;
22 import Util.CodePrinter;
24 public class BuildCode {
27 Hashtable paramstable;
32 String localsprefix="___locals___";
33 String localsprefixaddr="&"+localsprefix;
34 String localsprefixderef=localsprefix+".";
35 String fcrevert="___fcrevert___";
36 String paramsprefix="___params___";
37 String nextobjstr="___nextobject___";
38 String localcopystr="___localcopy___";
39 public static boolean GENERATEPRECISEGC=false;
40 public static String PREFIX="";
41 public static String arraytype="ArrayObject";
42 public static int flagcount = 0;
45 protected int maxtaskparams=0;
46 protected int maxcount=0;
47 ClassDescriptor[] cdarray;
48 ClassDescriptor[] ifarray;
49 TypeDescriptor[] arraytable;
52 Hashtable<String, ClassDescriptor> printedfieldstbl;
53 int globaldefscount=0;
54 boolean mgcstaticinit = false;
56 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil) {
57 this(st, temptovar, typeutil, null);
60 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa) {
63 callgraph=new CallGraph(state);
64 this.temptovar=temptovar;
65 paramstable=new Hashtable();
66 tempstable=new Hashtable();
67 fieldorder=new Hashtable();
68 flagorder=new Hashtable();
69 this.typeutil=typeutil;
71 virtualcalls=new Virtual(state, null);
72 printedfieldstbl = new Hashtable<String, ClassDescriptor>();
75 /** The buildCode method outputs C code for all the methods. The Flat
76 * versions of the methods must already be generated and stored in
77 * the State object. */
80 public void buildCode() {
81 /* Create output streams to write to */
82 PrintWriter outclassdefs=null;
83 PrintWriter outstructs=null;
84 PrintWriter outrepairstructs=null;
85 PrintWriter outmethodheader=null;
86 PrintWriter outmethod=null;
87 PrintWriter outvirtual=null;
88 PrintWriter outtask=null;
89 PrintWriter outtaskdefs=null;
90 PrintWriter outoptionalarrays=null;
91 PrintWriter optionalheaders=null;
92 PrintWriter outglobaldefs=null;
93 PrintWriter outglobaldefsprim=null;
96 buildCodeSetup(); //EXTENSION POINT
97 outstructs=new CodePrinter(new FileOutputStream(PREFIX+"structdefs.h"), true);
98 outmethodheader=new CodePrinter(new FileOutputStream(PREFIX+"methodheaders.h"), true);
99 outclassdefs=new CodePrinter(new FileOutputStream(PREFIX+"classdefs.h"), true);
100 outglobaldefs=new CodePrinter(new FileOutputStream(PREFIX+"globaldefs.h"), true);
101 outglobaldefsprim=new CodePrinter(new FileOutputStream(PREFIX+"globaldefsprim.h"), true);
102 outmethod=new CodePrinter(new FileOutputStream(PREFIX+"methods.c"), true);
103 outvirtual=new CodePrinter(new FileOutputStream(PREFIX+"virtualtable.h"), true);
105 outtask=new CodePrinter(new FileOutputStream(PREFIX+"task.h"), true);
106 outtaskdefs=new CodePrinter(new FileOutputStream(PREFIX+"taskdefs.c"), true);
107 if (state.OPTIONAL) {
108 outoptionalarrays=new CodePrinter(new FileOutputStream(PREFIX+"optionalarrays.c"), true);
109 optionalheaders=new CodePrinter(new FileOutputStream(PREFIX+"optionalstruct.h"), true);
112 if (state.structfile!=null) {
113 outrepairstructs=new CodePrinter(new FileOutputStream(PREFIX+state.structfile+".struct"), true);
115 } catch (Exception e) {
120 /* Fix field safe symbols due to shadowing */
121 FieldShadow.handleFieldShadow(state);
123 /* Build the virtual dispatch tables */
124 buildVirtualTables(outvirtual);
126 /* Tag the methods that are invoked by static blocks */
127 tagMethodInvokedByStaticBlock();
129 /* Output includes */
130 outmethodheader.println("#ifndef METHODHEADERS_H");
131 outmethodheader.println("#define METHODHEADERS_H");
132 outmethodheader.println("#include \"structdefs.h\"");
134 if (state.EVENTMONITOR) {
135 outmethodheader.println("#include \"monitor.h\"");
138 additionalIncludesMethodsHeader(outmethodheader);
140 /* Output Structures */
141 outputStructs(outstructs);
143 // Output the C class declarations
144 // These could mutually reference each other
146 outglobaldefs.println("#ifndef __GLOBALDEF_H_");
147 outglobaldefs.println("#define __GLOBALDEF_H_");
148 outglobaldefs.println("");
149 outglobaldefs.println("struct global_defs_t {");
150 outglobaldefs.println(" int size;");
151 outglobaldefs.println(" void * next;");
152 outglobaldefsprim.println("#ifndef __GLOBALDEFPRIM_H_");
153 outglobaldefsprim.println("#define __GLOBALDEFPRIM_H_");
154 outglobaldefsprim.println("");
155 outglobaldefsprim.println("struct global_defsprim_t {");
157 outclassdefs.println("#ifndef __CLASSDEF_H_");
158 outclassdefs.println("#define __CLASSDEF_H_");
159 outputClassDeclarations(outclassdefs, outglobaldefs, outglobaldefsprim);
161 // Output function prototypes and structures for parameters
162 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
163 while(it.hasNext()) {
164 ClassDescriptor cn=(ClassDescriptor)it.next();
165 generateCallStructs(cn, outclassdefs, outstructs, outmethodheader, outglobaldefs, outglobaldefsprim);
167 outclassdefs.println("#include \"globaldefs.h\"");
168 outclassdefs.println("#include \"globaldefsprim.h\"");
169 outclassdefs.println("#endif");
170 outclassdefs.close();
172 outglobaldefs.println("};");
173 outglobaldefs.println("");
174 outglobaldefs.println("extern struct global_defs_t * global_defs_p;");
175 outglobaldefs.println("#endif");
176 outglobaldefs.flush();
177 outglobaldefs.close();
179 outglobaldefsprim.println("};");
180 outglobaldefsprim.println("");
181 outglobaldefsprim.println("extern struct global_defsprim_t * global_defsprim_p;");
182 outglobaldefsprim.println("#endif");
183 outglobaldefsprim.flush();
184 outglobaldefsprim.close();
187 /* Map flags to integers */
188 /* The runtime keeps track of flags using these integers */
189 it=state.getClassSymbolTable().getDescriptorsIterator();
190 while(it.hasNext()) {
191 ClassDescriptor cn=(ClassDescriptor)it.next();
195 generateTaskStructs(outstructs, outmethodheader);
197 /* Outputs generic task structures if this is a task
199 outputTaskTypes(outtask);
203 // an opportunity for subclasses to do extra
205 preCodeGenInitialization();
208 /* Build the actual methods */
209 outputMethods(outmethod);
212 // opportunity for subclasses to gen extra code
213 additionalCodeGen(outmethodheader,
219 /* Output code for tasks */
220 outputTaskCode(outtaskdefs, outmethod);
222 /* Record maximum number of task parameters */
223 outstructs.println("#define MAXTASKPARAMS "+maxtaskparams);
224 } else if (state.main!=null) {
225 /* Generate main method */
226 outputMainMethod(outmethod);
229 /* Generate information for task with optional parameters */
230 if (state.TASK&&state.OPTIONAL) {
231 generateOptionalArrays(outoptionalarrays, optionalheaders, state.getAnalysisResult(), state.getOptionalTaskDescriptors());
232 outoptionalarrays.close();
235 /* Output structure definitions for repair tool */
236 if (state.structfile!=null) {
237 buildRepairStructs(outrepairstructs);
238 outrepairstructs.close();
242 outmethodheader.println("#endif");
243 outmethodheader.close();
245 outstructs.println("#endif");
250 postCodeGenCleanUp();
253 /* This method goes though the call graph and check which methods are really
254 * invoked and should be generated
256 protected void checkMethods2Gen() {
257 MethodDescriptor md=(state.main==null)?null:typeutil.getMain();
260 // check the methods to be generated
261 state.setGenAllMethods(false);
263 // generate all methods
266 this.state.addMethod2gen(md);
268 Iterator it_classes = this.state.getClassSymbolTable().getDescriptorsIterator();
269 while(it_classes.hasNext()) {
270 ClassDescriptor cd = (ClassDescriptor)it_classes.next();
271 Iterator it_methods = cd.getMethodTable().getDescriptorsIterator();
272 while(it_methods.hasNext()) {
273 md = (MethodDescriptor)it_methods.next();
274 if(md.isStaticBlock() || md.getModifiers().isNative() || this.callgraph.getCallerSet(md).size() > 0
275 || (cd.getSymbol().equals("Thread") && md.getSymbol().equals("staticStart"))) {
276 this.state.addMethod2gen(md);
283 /* This method goes though the call graph and tag those methods that are
284 * invoked inside static blocks
286 protected void tagMethodInvokedByStaticBlock() {
287 Iterator it_sclasses = this.state.getSClassSymbolTable().getDescriptorsIterator();
288 MethodDescriptor current_md=null;
289 HashSet tovisit=new HashSet();
290 HashSet visited=new HashSet();
292 while(it_sclasses.hasNext()) {
293 ClassDescriptor cd = (ClassDescriptor)it_sclasses.next();
294 MethodDescriptor md = (MethodDescriptor)cd.getMethodTable().get("staticblocks");
300 while(!tovisit.isEmpty()) {
301 current_md=(MethodDescriptor)tovisit.iterator().next();
302 tovisit.remove(current_md);
303 visited.add(current_md);
304 Iterator it_callee = this.callgraph.getCalleeSet(current_md).iterator();
305 while(it_callee.hasNext()) {
306 Descriptor d = (Descriptor)it_callee.next();
307 if(d instanceof MethodDescriptor) {
308 if(!visited.contains(d)) {
309 ((MethodDescriptor)d).setIsInvokedByStatic(true);
317 /* This code generates code for each static block and static field
319 protected void outputStaticBlocks(PrintWriter outmethod) {
320 // execute all the static blocks and all the static field initializations
321 // execute all the static blocks and all the static field initializations
322 SymbolTable sctbl = this.state.getSClassSymbolTable();
323 Iterator it_sclasses = sctbl.getDescriptorsIterator();
324 if(it_sclasses.hasNext()) {
325 while(it_sclasses.hasNext()) {
326 ClassDescriptor t_cd = (ClassDescriptor)it_sclasses.next();
327 MethodDescriptor t_md = (MethodDescriptor)t_cd.getMethodTable().get("staticblocks");
329 outmethod.println(" {");
330 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
331 outmethod.print(" struct "+t_cd.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"_params __parameterlist__={");
332 outmethod.println("0, NULL};");
333 outmethod.println(" "+t_cd.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"(& __parameterlist__);");
335 outmethod.println(" "+t_cd.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();");
337 outmethod.println(" }");
343 /* This code generates code to create a Class object for each class for
346 protected void outputClassObjects(PrintWriter outmethod) {
347 // for each class, initialize its Class object
348 SymbolTable ctbl = this.state.getClassSymbolTable();
349 for(Iterator it_classes = ctbl.getDescriptorsIterator();it_classes.hasNext();) {
350 ClassDescriptor t_cd = (ClassDescriptor)it_classes.next();
351 outmethod.println(" {");
352 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
353 outmethod.println(" struct garbagelist dummy={0,NULL};");
354 outmethod.println(" global_defs_p->"+t_cd.getSafeSymbol()+"classobj = allocate_new(&dummy, " + typeutil.getClass(TypeUtil.ObjectClass).getId() + ");");
356 outmethod.println(" global_defs_p->"+t_cd.getSafeSymbol()+"classobj = allocate_new("+typeutil.getClass(TypeUtil.ObjectClass).getId() + ");");
357 outmethod.println(" }");
361 /* This code just generates the main C method for java programs.
362 * The main C method packs up the arguments into a string array
363 * and passes it to the java main method. */
365 protected void outputMainMethod(PrintWriter outmethod) {
366 outmethod.println("int main(int argc, const char *argv[]) {");
367 outmethod.println(" int i;");
368 outmethod.println(" global_defs_p=calloc(1, sizeof(struct global_defs_t));");
369 outmethod.println(" global_defsprim_p=calloc(1, sizeof(struct global_defsprim_t));");
370 if (GENERATEPRECISEGC) {
371 outmethod.println(" global_defs_p->size="+globaldefscount+";");
372 outmethod.println(" for(i=0;i<"+globaldefscount+";i++) {");
373 outmethod.println(" ((struct garbagelist *)global_defs_p)->array[i]=NULL;");
374 outmethod.println(" }");
376 outputStaticBlocks(outmethod);
377 outputClassObjects(outmethod);
380 additionalCodeAtTopOfMain(outmethod);
383 outmethod.println("initializethreads();");
386 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
387 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1);");
389 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1);");
391 outmethod.println(" for(i=1;i<argc;i++) {");
392 outmethod.println(" int length=strlen(argv[i]);");
394 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
395 outmethod.println(" struct ___String___ *newstring=NewString(NULL, argv[i], length);");
397 outmethod.println(" struct ___String___ *newstring=NewString(argv[i], length);");
399 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-1]=newstring;");
400 outmethod.println(" }");
402 MethodDescriptor md=typeutil.getMain();
403 ClassDescriptor cd=typeutil.getMainClass();
405 outmethod.println(" {");
406 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
407 outmethod.print(" struct "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
408 outmethod.println("1, NULL,"+"stringarray};");
409 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
411 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
413 outmethod.println(" }");
416 outmethod.println("pthread_mutex_lock(&gclistlock);");
417 outmethod.println("threadcount--;");
418 outmethod.println("pthread_cond_signal(&gccond);");
419 outmethod.println("pthread_mutex_unlock(&gclistlock);");
422 if (state.EVENTMONITOR) {
423 outmethod.println("dumpdata();");
427 outmethod.println("pthread_exit(NULL);");
430 additionalCodeAtBottomOfMain(outmethod);
432 outmethod.println("}");
435 /* This method outputs code for each task. */
437 protected void outputTaskCode(PrintWriter outtaskdefs, PrintWriter outmethod) {
438 /* Compile task based program */
439 outtaskdefs.println("#include \"task.h\"");
440 outtaskdefs.println("#include \"methodheaders.h\"");
441 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
442 while(taskit.hasNext()) {
443 TaskDescriptor td=(TaskDescriptor)taskit.next();
444 FlatMethod fm=state.getMethodFlat(td);
445 generateFlatMethod(fm, outmethod);
446 generateTaskDescriptor(outtaskdefs, fm, td);
449 //Output task descriptors
450 taskit=state.getTaskSymbolTable().getDescriptorsIterator();
451 outtaskdefs.println("struct taskdescriptor * taskarray[]= {");
453 while(taskit.hasNext()) {
454 TaskDescriptor td=(TaskDescriptor)taskit.next();
458 outtaskdefs.println(",");
459 outtaskdefs.print("&task_"+td.getSafeSymbol());
461 outtaskdefs.println("};");
463 outtaskdefs.println("int numtasks="+state.getTaskSymbolTable().getValueSet().size()+";");
467 /* This method outputs most of the methods.c file. This includes
468 * some standard includes and then an array with the sizes of
469 * objets and array that stores supertype and then the code for
470 * the Java methods.. */
471 protected void outputMethods(PrintWriter outmethod) {
472 outmethod.println("#include \"methodheaders.h\"");
473 outmethod.println("#include \"virtualtable.h\"");
474 outmethod.println("#include \"runtime.h\"");
476 // always include: compiler directives will leave out
477 // instrumentation when option is not set
478 outmethod.println("#include \"coreprof/coreprof.h\"");
480 if (state.FASTCHECK) {
481 outmethod.println("#include \"localobjects.h\"");
483 if(state.MULTICORE) {
485 outmethod.println("#include \"task.h\"");
487 outmethod.println("#include \"multicoreruntime.h\"");
488 outmethod.println("#include \"runtime_arch.h\"");
490 if (state.THREAD||state.DSM||state.SINGLETM) {
491 outmethod.println("#include <thread.h>");
494 outmethod.println("#include \"thread.h\"");
496 if (state.main!=null) {
497 outmethod.println("#include <string.h>");
499 if (state.CONSCHECK) {
500 outmethod.println("#include \"checkers.h\"");
504 additionalIncludesMethodsImplementation(outmethod);
506 outmethod.println("struct global_defs_t * global_defs_p;");
507 outmethod.println("struct global_defsprim_t * global_defsprim_p;");
508 //Store the sizes of classes & array elements
509 generateSizeArray(outmethod);
511 //Store table of supertypes
512 generateSuperTypeTable(outmethod);
514 //Store the layout of classes
515 generateLayoutStructs(outmethod);
518 additionalCodeAtTopMethodsImplementation(outmethod);
520 generateMethods(outmethod);
523 protected void generateMethods(PrintWriter outmethod) {
524 /* Generate code for methods */
525 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
526 while(classit.hasNext()) {
527 ClassDescriptor cn=(ClassDescriptor)classit.next();
528 Iterator methodit=cn.getMethods();
529 while(methodit.hasNext()) {
530 /* Classify parameters */
531 MethodDescriptor md=(MethodDescriptor)methodit.next();
532 if(!this.state.genAllMethods) {
533 boolean foundmatch = false;
534 Set vec_md = this.state.getMethod2gen().getSet(md.getSymbol());
535 for(Iterator matchit=vec_md.iterator(); matchit.hasNext();) {
536 MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
537 if (md.matches(matchmd)) {
546 FlatMethod fm=state.getMethodFlat(md);
547 if (!md.getModifiers().isNative()) {
548 generateFlatMethod(fm, outmethod);
554 protected void outputStructs(PrintWriter outstructs) {
555 outstructs.println("#ifndef STRUCTDEFS_H");
556 outstructs.println("#define STRUCTDEFS_H");
557 outstructs.println("#include \"classdefs.h\"");
558 outstructs.println("#ifndef INTPTR");
559 outstructs.println("#ifdef BIT64");
560 outstructs.println("#define INTPTR long");
561 outstructs.println("#else");
562 outstructs.println("#define INTPTR int");
563 outstructs.println("#endif");
564 outstructs.println("#endif");
567 additionalIncludesStructsHeader(outstructs);
570 /* Output #defines that the runtime uses to determine type
571 * numbers for various objects it needs */
572 outstructs.println("#define MAXCOUNT "+maxcount);
574 outstructs.println("#define STRINGARRAYTYPE "+
575 (state.getArrayNumber(
576 (new TypeDescriptor(typeutil.getClass(TypeUtil.StringClass))).makeArray(state))+state.numClasses()));
578 outstructs.println("#define OBJECTARRAYTYPE "+
579 (state.getArrayNumber(
580 (new TypeDescriptor(typeutil.getClass(TypeUtil.ObjectClass))).makeArray(state))+state.numClasses()));
583 outstructs.println("#define STRINGTYPE "+typeutil.getClass(TypeUtil.StringClass).getId());
584 outstructs.println("#define CHARARRAYTYPE "+
585 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.CHAR)).makeArray(state))+state.numClasses()));
587 outstructs.println("#define BYTEARRAYTYPE "+
588 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state))+state.numClasses()));
590 outstructs.println("#define BYTEARRAYARRAYTYPE "+
591 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state).makeArray(state))+state.numClasses()));
593 outstructs.println("#define NUMCLASSES "+state.numClasses());
594 int totalClassSize = state.numClasses() + state.numArrays() + state.numInterfaces();
595 outstructs.println("#define TOTALNUMCLASSANDARRAY "+ totalClassSize);
597 outstructs.println("#define STARTUPTYPE "+typeutil.getClass(TypeUtil.StartupClass).getId());
598 outstructs.println("#define TAGTYPE "+typeutil.getClass(TypeUtil.TagClass).getId());
599 outstructs.println("#define TAGARRAYTYPE "+
600 (state.getArrayNumber(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)).makeArray(state))+state.numClasses()));
604 protected void outputClassDeclarations(PrintWriter outclassdefs, PrintWriter outglobaldefs, PrintWriter outglobaldefsprim) {
605 if (state.THREAD||state.DSM||state.SINGLETM)
606 outclassdefs.println("#include <pthread.h>");
607 outclassdefs.println("#ifndef INTPTR");
608 outclassdefs.println("#ifdef BIT64");
609 outclassdefs.println("#define INTPTR long");
610 outclassdefs.println("#else");
611 outclassdefs.println("#define INTPTR int");
612 outclassdefs.println("#endif");
613 outclassdefs.println("#endif");
615 outclassdefs.println("#include \"optionalstruct.h\"");
616 outclassdefs.println("struct "+arraytype+";");
617 /* Start by declaring all structs */
618 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
619 while(it.hasNext()) {
620 ClassDescriptor cn=(ClassDescriptor)it.next();
621 outclassdefs.println("struct "+cn.getSafeSymbol()+";");
623 if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) {
624 // this class has static fields/blocks, need to add a global flag to
625 // indicate if its static fields have been initialized and/or if its
626 // static blocks have been executed
627 outglobaldefsprim.println(" int "+cn.getSafeSymbol()+"static_block_exe_flag;");
630 // for each class, create a global object
631 outglobaldefs.println(" struct ___Object___ *"+cn.getSafeSymbol()+"classobj;");
634 outclassdefs.println("");
635 //Print out definition for array type
636 outclassdefs.println("struct "+arraytype+" {");
637 outclassdefs.println(" int type;");
640 additionalClassObjectFields(outclassdefs);
643 if (state.EVENTMONITOR) {
644 outclassdefs.println(" int objuid;");
647 outclassdefs.println(" pthread_t tid;");
648 outclassdefs.println(" void * lockentry;");
649 outclassdefs.println(" int lockcount;");
652 outclassdefs.println(" int mutex;");
653 outclassdefs.println(" volatile int notifycount;");
654 outclassdefs.println(" volatile int objlock;");
655 if(state.MULTICOREGC) {
656 outclassdefs.println(" int marked;");
660 outclassdefs.println(" int flag;");
661 if(!state.MULTICORE) {
662 outclassdefs.println(" void * flagptr;");
664 outclassdefs.println(" int version;");
665 outclassdefs.println(" int * lock;"); // lock entry for this obj
666 outclassdefs.println(" int mutex;");
667 outclassdefs.println(" int lockcount;");
668 if(state.MULTICOREGC) {
669 outclassdefs.println(" int marked;");
673 outclassdefs.println(" int numfses;");
674 outclassdefs.println(" int * fses;");
678 printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs, outglobaldefs, outglobaldefsprim);
679 printedfieldstbl.clear();
680 printExtraArrayFields(outclassdefs);
681 if (state.ARRAYPAD) {
682 outclassdefs.println(" int paddingforarray;");
685 outclassdefs.println(" int ___length___;");
686 outclassdefs.println("};\n");
689 // TODO add version for normal Java later
690 outclassdefs.println("");
691 //Print out definition for Class type
692 outclassdefs.println("struct Class {");
693 outclassdefs.println(" int type;");
696 additionalClassObjectFields(outclassdefs);
699 if (state.EVENTMONITOR) {
700 outclassdefs.println(" int objuid;");
703 outclassdefs.println(" pthread_t tid;");
704 outclassdefs.println(" void * lockentry;");
705 outclassdefs.println(" int lockcount;");
708 outclassdefs.println(" int mutex;");
709 outclassdefs.println(" volatile int notifycount;");
710 outclassdefs.println(" volatile int objlock;");
711 if(state.MULTICOREGC) {
712 outclassdefs.println(" int marked;");
716 outclassdefs.println(" int flag;");
717 if(!state.MULTICORE) {
718 outclassdefs.println(" void * flagptr;");
720 outclassdefs.println(" int version;");
721 outclassdefs.println(" int * lock;"); // lock entry for this obj
722 outclassdefs.println(" int mutex;");
723 outclassdefs.println(" int lockcount;");
724 if(state.MULTICOREGC) {
725 outclassdefs.println(" int marked;");
729 outclassdefs.println(" int numfses;");
730 outclassdefs.println(" int * fses;");
733 printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs, outglobaldefs, outglobaldefsprim);
734 printedfieldstbl.clear();
735 outclassdefs.println("};\n");
738 outclassdefs.println("");
739 outclassdefs.println("extern int classsize[];");
740 outclassdefs.println("extern int hasflags[];");
741 outclassdefs.println("extern unsigned INTPTR * pointerarray[];");
742 outclassdefs.println("extern int* supertypes[];");
743 outclassdefs.println("");
746 /** Prints out definitions for generic task structures */
748 protected void outputTaskTypes(PrintWriter outtask) {
749 outtask.println("#ifndef _TASK_H");
750 outtask.println("#define _TASK_H");
751 outtask.println("struct parameterdescriptor {");
752 outtask.println("int type;");
753 outtask.println("int numberterms;");
754 outtask.println("int *intarray;");
755 outtask.println("void * queue;");
756 outtask.println("int numbertags;");
757 outtask.println("int *tagarray;");
758 outtask.println("};");
760 outtask.println("struct taskdescriptor {");
761 outtask.println("void * taskptr;");
762 outtask.println("int numParameters;");
763 outtask.println(" int numTotal;");
764 outtask.println("struct parameterdescriptor **descriptorarray;");
765 outtask.println("char * name;");
766 outtask.println("};");
767 outtask.println("extern struct taskdescriptor * taskarray[];");
768 outtask.println("extern numtasks;");
769 outtask.println("#endif");
773 protected void buildRepairStructs(PrintWriter outrepairstructs) {
774 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
775 while(classit.hasNext()) {
776 ClassDescriptor cn=(ClassDescriptor)classit.next();
777 outrepairstructs.println("structure "+cn.getSymbol()+" {");
778 outrepairstructs.println(" int __type__;");
780 outrepairstructs.println(" int __flag__;");
781 if(!state.MULTICORE) {
782 outrepairstructs.println(" int __flagptr__;");
785 printRepairStruct(cn, outrepairstructs);
786 outrepairstructs.println("}\n");
789 for(int i=0; i<state.numArrays(); i++) {
790 TypeDescriptor tdarray=arraytable[i];
791 TypeDescriptor tdelement=tdarray.dereference();
792 outrepairstructs.println("structure "+arraytype+"_"+state.getArrayNumber(tdarray)+" {");
793 outrepairstructs.println(" int __type__;");
794 printRepairStruct(typeutil.getClass(TypeUtil.ObjectClass), outrepairstructs);
795 outrepairstructs.println(" int length;");
796 outrepairstructs.println("}\n");
800 protected void printRepairStruct(ClassDescriptor cn, PrintWriter output) {
801 ClassDescriptor sp=cn.getSuperDesc();
803 printRepairStruct(sp, output);
805 Vector fields=(Vector)fieldorder.get(cn);
807 for(int i=0; i<fields.size(); i++) {
808 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
809 if (fd.getType().isArray()) {
810 output.println(" "+arraytype+"_"+ state.getArrayNumber(fd.getType()) +" * "+fd.getSymbol()+";");
811 } else if (fd.getType().isClass())
812 output.println(" "+fd.getType().getRepairSymbol()+" * "+fd.getSymbol()+";");
813 else if (fd.getType().isFloat())
814 output.println(" int "+fd.getSymbol()+"; /* really float */");
816 output.println(" "+fd.getType().getRepairSymbol()+" "+fd.getSymbol()+";");
820 /** This method outputs TaskDescriptor information */
821 protected void generateTaskDescriptor(PrintWriter output, FlatMethod fm, TaskDescriptor task) {
822 for (int i=0; i<task.numParameters(); i++) {
823 VarDescriptor param_var=task.getParameter(i);
824 TypeDescriptor param_type=task.getParamType(i);
825 FlagExpressionNode param_flag=task.getFlag(param_var);
826 TagExpressionList param_tag=task.getTag(param_var);
829 if (param_flag==null) {
830 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
831 output.println("0x0, 0x0 };");
834 DNFFlag dflag=param_flag.getDNF();
835 dnfterms=dflag.size();
837 Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
838 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
839 for(int j=0; j<dflag.size(); j++) {
842 Vector term=dflag.get(j);
845 for(int k=0; k<term.size(); k++) {
846 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
847 FlagDescriptor fd=dfa.getFlag();
848 boolean negated=dfa.getNegated();
849 int flagid=1<<((Integer)flags.get(fd)).intValue();
854 output.print("0x"+Integer.toHexString(andmask)+", 0x"+Integer.toHexString(checkmask));
856 output.println("};");
859 output.println("int parametertag_"+i+"_"+task.getSafeSymbol()+"[]={");
861 for(int j=0; j<param_tag.numTags(); j++) {
864 /* for each tag we need */
865 /* which slot it is */
866 /* what type it is */
867 TagVarDescriptor tvd=(TagVarDescriptor)task.getParameterTable().get(param_tag.getName(j));
868 TempDescriptor tmp=param_tag.getTemp(j);
869 int slot=fm.getTagInt(tmp);
870 output.println(slot+", "+state.getTagId(tvd.getTag()));
872 output.println("};");
874 output.println("struct parameterdescriptor parameter_"+i+"_"+task.getSafeSymbol()+"={");
875 output.println("/* type */"+param_type.getClassDesc().getId()+",");
876 output.println("/* number of DNF terms */"+dnfterms+",");
877 output.println("parameterdnf_"+i+"_"+task.getSafeSymbol()+",");
878 output.println("0,");
880 output.println("/* number of tags */"+param_tag.numTags()+",");
882 output.println("/* number of tags */ 0,");
883 output.println("parametertag_"+i+"_"+task.getSafeSymbol());
884 output.println("};");
888 output.println("struct parameterdescriptor * parameterdescriptors_"+task.getSafeSymbol()+"[] = {");
889 for (int i=0; i<task.numParameters(); i++) {
892 output.print("¶meter_"+i+"_"+task.getSafeSymbol());
894 output.println("};");
896 output.println("struct taskdescriptor task_"+task.getSafeSymbol()+"={");
897 output.println("&"+task.getSafeSymbol()+",");
898 output.println("/* number of parameters */" +task.numParameters() + ",");
899 int numtotal=task.numParameters()+fm.numTags();
900 output.println("/* number total parameters */" +numtotal + ",");
901 output.println("parameterdescriptors_"+task.getSafeSymbol()+",");
902 output.println("\""+task.getSymbol()+"\"");
903 output.println("};");
907 /** The buildVirtualTables method outputs the virtual dispatch
908 * tables for methods. */
910 protected void buildVirtualTables(PrintWriter outvirtual) {
911 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
912 while(classit.hasNext()) {
913 ClassDescriptor cd=(ClassDescriptor)classit.next();
914 if (virtualcalls.getMethodCount(cd)>maxcount)
915 maxcount=virtualcalls.getMethodCount(cd);
917 MethodDescriptor[][] virtualtable=null;
918 virtualtable=new MethodDescriptor[state.numClasses()+state.numArrays()][maxcount];
920 /* Fill in virtual table */
921 classit=state.getClassSymbolTable().getDescriptorsIterator();
922 while(classit.hasNext()) {
923 ClassDescriptor cd=(ClassDescriptor)classit.next();
924 if(cd.isInterface()) {
927 fillinRow(cd, virtualtable, cd.getId());
930 ClassDescriptor objectcd=typeutil.getClass(TypeUtil.ObjectClass);
931 Iterator arrayit=state.getArrayIterator();
932 while(arrayit.hasNext()) {
933 TypeDescriptor td=(TypeDescriptor)arrayit.next();
934 int id=state.getArrayNumber(td);
935 fillinRow(objectcd, virtualtable, id+state.numClasses());
938 outvirtual.print("void * virtualtable[]={");
939 boolean needcomma=false;
940 for(int i=0; i<state.numClasses()+state.numArrays(); i++) {
941 for(int j=0; j<maxcount; j++) {
943 outvirtual.print(", ");
944 if (virtualtable[i][j]!=null) {
945 MethodDescriptor md=virtualtable[i][j];
946 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
948 outvirtual.print("0");
952 outvirtual.println("");
954 outvirtual.println("};");
958 protected void fillinRow(ClassDescriptor cd, MethodDescriptor[][] virtualtable, int rownum) {
959 /* Get inherited methods */
960 Iterator it_sifs = cd.getSuperInterfaces();
961 while(it_sifs.hasNext()) {
962 ClassDescriptor superif = (ClassDescriptor)it_sifs.next();
963 fillinRow(superif, virtualtable, rownum);
965 if (cd.getSuperDesc()!=null)
966 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
967 /* Override them with our methods */
968 for(Iterator it=cd.getMethods(); it.hasNext(); ) {
969 MethodDescriptor md=(MethodDescriptor)it.next();
970 if (md.isStatic()||md.getReturnType()==null)
972 boolean foundmatch = false;
973 if(this.state.genAllMethods) {
976 Set vec_md = this.state.getMethod2gen().getSet(md.getSymbol());
977 for(Iterator matchit=vec_md.iterator(); matchit.hasNext();) {
978 MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
979 if (md.matches(matchmd)) {
988 int methodnum = virtualcalls.getMethodNumber(md);
989 virtualtable[rownum][methodnum]=md;
993 /** Generate array that contains the sizes of class objects. The
994 * object allocation functions in the runtime use this
997 protected void generateSizeArray(PrintWriter outclassdefs) {
998 outclassdefs.print("extern struct prefetchCountStats * evalPrefetch;\n");
999 generateSizeArrayExtensions(outclassdefs);
1001 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1002 cdarray=new ClassDescriptor[state.numClasses()];
1003 ifarray = new ClassDescriptor[state.numInterfaces()];
1005 int interfaceid = 0;
1006 while(it.hasNext()) {
1007 ClassDescriptor cd=(ClassDescriptor)it.next();
1008 if(cd.isInterface()) {
1009 ifarray[cd.getId()] = cd;
1011 cdarray[cd.getId()] = cd;
1015 arraytable=new TypeDescriptor[state.numArrays()];
1017 Iterator arrayit=state.getArrayIterator();
1018 while(arrayit.hasNext()) {
1019 TypeDescriptor td=(TypeDescriptor)arrayit.next();
1020 int id=state.getArrayNumber(td);
1024 /* Print out types */
1025 outclassdefs.println("/* ");
1026 for(int i=0; i<state.numClasses(); i++) {
1027 ClassDescriptor cd=cdarray[i];
1029 outclassdefs.println("NULL " + i);
1031 outclassdefs.println(cd +" "+i);
1035 for(int i=0; i<state.numArrays(); i++) {
1036 TypeDescriptor arraytd=arraytable[i];
1037 outclassdefs.println(arraytd.toPrettyString() +" "+(i+state.numClasses()));
1040 for(int i=0; i<state.numInterfaces(); i++) {
1041 ClassDescriptor ifcd = ifarray[i];
1042 outclassdefs.println(ifcd +" "+(i+state.numClasses()+state.numArrays()));
1045 outclassdefs.println("*/");
1048 outclassdefs.print("int classsize[]={");
1050 boolean needcomma=false;
1051 for(int i=0; i<state.numClasses(); i++) {
1053 outclassdefs.print(", ");
1055 outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")");
1057 outclassdefs.print("0");
1063 for(int i=0; i<state.numArrays(); i++) {
1065 outclassdefs.print(", ");
1066 TypeDescriptor tdelement=arraytable[i].dereference();
1067 if (tdelement.isArray()||tdelement.isClass()||tdelement.isNull())
1068 outclassdefs.print("sizeof(void *)");
1070 outclassdefs.print("sizeof("+tdelement.getSafeSymbol()+")");
1074 for(int i=0; i<state.numInterfaces(); i++) {
1076 outclassdefs.print(", ");
1077 outclassdefs.print("sizeof(struct "+ifarray[i].getSafeSymbol()+")");
1081 outclassdefs.println("};");
1083 ClassDescriptor objectclass=typeutil.getClass(TypeUtil.ObjectClass);
1085 outclassdefs.print("int typearray[]={");
1086 for(int i=0; i<state.numClasses(); i++) {
1087 ClassDescriptor cd=cdarray[i];
1088 ClassDescriptor supercd=i>0 ? cd.getSuperDesc() : null;
1089 if(supercd != null && supercd.isInterface()) {
1090 throw new Error("Super class can not be interfaces");
1093 outclassdefs.print(", ");
1095 outclassdefs.print("-1");
1097 outclassdefs.print(supercd.getId());
1101 for(int i=0; i<state.numArrays(); i++) {
1102 TypeDescriptor arraytd=arraytable[i];
1103 ClassDescriptor arraycd=arraytd.getClassDesc();
1104 if (arraycd==null) {
1106 outclassdefs.print(", ");
1107 outclassdefs.print(objectclass.getId());
1111 ClassDescriptor cd=arraycd.getSuperDesc();
1114 TypeDescriptor supertd=new TypeDescriptor(cd);
1115 supertd.setArrayCount(arraytd.getArrayCount());
1116 type=state.getArrayNumber(supertd);
1118 type+=state.numClasses();
1121 cd=cd.getSuperDesc();
1124 outclassdefs.print(", ");
1125 outclassdefs.print(type);
1129 for(int i=0; i<state.numInterfaces(); i++) {
1130 ClassDescriptor cd=ifarray[i];
1131 ClassDescriptor supercd=cd.getSuperDesc();
1132 if(supercd != null && supercd.isInterface()) {
1133 throw new Error("Super class can not be interfaces");
1136 outclassdefs.print(", ");
1138 outclassdefs.print("-1");
1140 outclassdefs.print(supercd.getId());
1144 outclassdefs.println("};");
1149 outclassdefs.print("int typearray2[]={");
1150 for(int i=0; i<state.numArrays(); i++) {
1151 TypeDescriptor arraytd=arraytable[i];
1152 ClassDescriptor arraycd=arraytd.getClassDesc();
1153 if (arraycd==null) {
1155 outclassdefs.print(", ");
1156 outclassdefs.print("-1");
1160 ClassDescriptor cd=arraycd.getSuperDesc();
1161 int level=arraytd.getArrayCount()-1;
1163 for(; level>0; level--) {
1164 TypeDescriptor supertd=new TypeDescriptor(objectclass);
1165 supertd.setArrayCount(level);
1166 type=state.getArrayNumber(supertd);
1168 type+=state.numClasses();
1173 outclassdefs.print(", ");
1174 outclassdefs.print(type);
1178 outclassdefs.println("};");
1181 /** Constructs params and temp objects for each method or task.
1182 * These objects tell the compiler which temps need to be
1185 protected void generateTempStructs(FlatMethod fm) {
1186 MethodDescriptor md=fm.getMethod();
1187 TaskDescriptor task=fm.getTask();
1188 ParamsObject objectparams=md!=null ? new ParamsObject(md,tag++) : new ParamsObject(task, tag++);
1190 paramstable.put(md, objectparams);
1192 paramstable.put(task, objectparams);
1194 for(int i=0; i<fm.numParameters(); i++) {
1195 TempDescriptor temp=fm.getParameter(i);
1196 TypeDescriptor type=temp.getType();
1197 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1198 objectparams.addPtr(temp);
1200 objectparams.addPrim(temp);
1203 for(int i=0; i<fm.numTags(); i++) {
1204 TempDescriptor temp=fm.getTag(i);
1205 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1206 objectparams.addPtr(temp);
1208 objectparams.addPrim(temp);
1211 TempObject objecttemps=md!=null ? new TempObject(objectparams,md,tag++) : new TempObject(objectparams, task, tag++);
1213 tempstable.put(md, objecttemps);
1215 tempstable.put(task, objecttemps);
1217 for(Iterator nodeit=fm.getNodeSet().iterator(); nodeit.hasNext(); ) {
1218 FlatNode fn=(FlatNode)nodeit.next();
1219 TempDescriptor[] writes=fn.writesTemps();
1220 for(int i=0; i<writes.length; i++) {
1221 TempDescriptor temp=writes[i];
1222 TypeDescriptor type=temp.getType();
1223 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1224 objecttemps.addPtr(temp);
1226 objecttemps.addPrim(temp);
1231 /** This method outputs the following information about classes
1233 * (1) For classes, what are the locations of pointers.
1234 * (2) For arrays, does the array contain pointers or primitives.
1235 * (3) For classes, does the class contain flags.
1238 protected void generateLayoutStructs(PrintWriter output) {
1239 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1240 while(it.hasNext()) {
1241 ClassDescriptor cn=(ClassDescriptor)it.next();
1242 output.println("unsigned INTPTR "+cn.getSafeSymbol()+"_pointers[]={");
1243 Iterator allit=cn.getFieldTable().getAllDescriptorsIterator();
1245 while(allit.hasNext()) {
1246 FieldDescriptor fd=(FieldDescriptor)allit.next();
1250 TypeDescriptor type=fd.getType();
1254 output.print(count);
1255 allit=cn.getFieldTable().getAllDescriptorsIterator();
1256 while(allit.hasNext()) {
1257 FieldDescriptor fd=(FieldDescriptor)allit.next();
1261 TypeDescriptor type=fd.getType();
1263 output.println(",");
1264 output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+
1265 fd.getSafeSymbol()+"))");
1268 output.println("};");
1270 output.println("unsigned INTPTR * pointerarray[]={");
1271 boolean needcomma=false;
1272 for(int i=0; i<state.numClasses(); i++) {
1273 ClassDescriptor cn=cdarray[i];
1275 output.println(",");
1278 output.print(cn.getSafeSymbol()+"_pointers");
1280 output.print("NULL");
1284 for(int i=0; i<state.numArrays(); i++) {
1286 output.println(", ");
1287 TypeDescriptor tdelement=arraytable[i].dereference();
1288 if (tdelement.isArray()||tdelement.isClass())
1289 output.print("((unsigned INTPTR *)1)");
1295 output.println("};");
1297 output.println("int hasflags[]={");
1298 for(int i=0; i<state.numClasses(); i++) {
1299 ClassDescriptor cn=cdarray[i];
1301 output.println(", ");
1303 if ((cn != null) && (cn.hasFlags()))
1308 output.println("};");
1311 private int checkarraysupertype(ClassDescriptor arraycd, TypeDescriptor arraytd) {
1314 TypeDescriptor supertd=new TypeDescriptor(arraycd);
1315 supertd.setArrayCount(arraytd.getArrayCount());
1316 type=state.getArrayNumber(supertd);
1321 ClassDescriptor cd = arraycd.getSuperDesc();
1323 type = checkarraysupertype(cd, arraytd);
1329 Iterator it_sifs = arraycd.getSuperInterfaces();
1330 while(it_sifs.hasNext()) {
1331 ClassDescriptor ifcd = (ClassDescriptor)it_sifs.next();
1332 type = checkarraysupertype(ifcd, arraytd);
1342 /** Print out table to give us supertypes */
1343 protected void generateSuperTypeTable(PrintWriter output) {
1344 ClassDescriptor objectclass=typeutil.getClass(TypeUtil.ObjectClass);
1345 for(int i=0; i<state.numClasses(); i++) {
1346 ClassDescriptor cn=cdarray[i];
1350 output.print("int supertypes" + cn.getSafeSymbol() + "[] = {");
1351 boolean ncomma = false;
1353 if((cn != null) && (cn.getSuperDesc() != null)) {
1356 Iterator it_sifs = cn != null? cn.getSuperInterfaces() : null;
1357 while(it_sifs != null && it_sifs.hasNext()) {
1363 if ((cn != null) && (cn.getSuperDesc()!=null)) {
1367 ClassDescriptor cdsuper=cn.getSuperDesc();
1368 output.print(cdsuper.getId());
1370 it_sifs = cn != null? cn.getSuperInterfaces() : null;
1371 while(it_sifs != null && it_sifs.hasNext()) {
1375 output.print(((ClassDescriptor)it_sifs.next()).getId()+state.numClasses()+state.numArrays());
1378 output.println("};");
1381 for(int i=0; i<state.numArrays(); i++) {
1382 TypeDescriptor arraytd=arraytable[i];
1383 ClassDescriptor arraycd=arraytd.getClassDesc();
1384 output.print("int supertypes___arraytype___" + (i+state.numClasses()) + "[] = {");
1385 boolean ncomma = false;
1387 if (arraycd==null) {
1391 output.print(objectclass.getId());
1392 output.println("};");
1395 if((arraycd != null) && (arraycd.getSuperDesc() != null)) {
1398 Iterator it_sifs = arraycd != null? arraycd.getSuperInterfaces() : null;
1399 while(it_sifs != null && it_sifs.hasNext()) {
1405 if ((arraycd != null) && (arraycd.getSuperDesc()!=null)) {
1406 ClassDescriptor cd=arraycd.getSuperDesc();
1409 type = checkarraysupertype(cd, arraytd);
1411 type += state.numClasses();
1418 it_sifs = arraycd != null? arraycd.getSuperInterfaces() : null;
1419 while(it_sifs != null && it_sifs.hasNext()) {
1420 ClassDescriptor ifcd = (ClassDescriptor)it_sifs.next();
1421 int type = checkarraysupertype(ifcd , arraytd);
1423 type += state.numClasses();
1429 output.println("};");
1432 for(int i=0; i<state.numInterfaces(); i++) {
1433 ClassDescriptor cn=ifarray[i];
1437 output.print("int supertypes" + cn.getSafeSymbol() + "[] = {");
1438 boolean ncomma = false;
1440 if((cn != null) && (cn.getSuperDesc() != null)) {
1443 Iterator it_sifs = cn != null? cn.getSuperInterfaces() : null;
1444 while(it_sifs != null && it_sifs.hasNext()) {
1450 if ((cn != null) && (cn.getSuperDesc()!=null)) {
1454 ClassDescriptor cdsuper=cn.getSuperDesc();
1455 output.print(cdsuper.getId());
1457 it_sifs = cn != null? cn.getSuperInterfaces() : null;
1458 while(it_sifs != null && it_sifs.hasNext()) {
1462 output.print(((ClassDescriptor)it_sifs.next()).getId()+state.numClasses()+state.numArrays());
1465 output.println("};");
1468 output.println("int* supertypes[]={");
1469 boolean needcomma=false;
1470 for(int i=0; i<state.numClasses(); i++) {
1471 ClassDescriptor cn=cdarray[i];
1473 output.println(",");
1476 output.print("supertypes" + cn.getSafeSymbol());
1482 for(int i=0; i<state.numArrays(); i++) {
1484 output.println(",");
1486 output.print("supertypes___arraytype___" + (i+state.numClasses()));
1489 for(int i=0; i<state.numInterfaces(); i++) {
1490 ClassDescriptor cn=ifarray[i];
1492 output.println(",");
1494 output.print("supertypes" + cn.getSafeSymbol());
1496 output.println("};");
1499 /** Force consistent field ordering between inherited classes. */
1501 protected void printClassStruct(ClassDescriptor cn, PrintWriter classdefout, PrintWriter globaldefout, PrintWriter globaldefprimout) {
1503 ClassDescriptor sp=cn.getSuperDesc();
1505 printClassStruct(sp, classdefout, /*globaldefout*/ null, null);
1507 SymbolTable sitbl = cn.getSuperInterfaceTable();
1508 Iterator it_sifs = sitbl.getDescriptorsIterator();
1509 while(it_sifs.hasNext()) {
1510 ClassDescriptor si = (ClassDescriptor)it_sifs.next();
1511 printClassStruct(si, classdefout, /*globaldefout*/ null, null);
1514 if (!fieldorder.containsKey(cn)) {
1515 Vector fields=new Vector();
1516 fieldorder.put(cn,fields);
1518 Vector fieldvec=cn.getFieldVec();
1519 for(int i=0; i<fieldvec.size(); i++) {
1520 FieldDescriptor fd=(FieldDescriptor)fieldvec.get(i);
1521 if((sp != null) && sp.getFieldTable().contains(fd.getSymbol())) {
1524 it_sifs = sitbl.getDescriptorsIterator();
1525 boolean hasprinted = false;
1526 while(it_sifs.hasNext()) {
1527 ClassDescriptor si = (ClassDescriptor)it_sifs.next();
1528 if(si.getFieldTable().contains(fd.getSymbol())) {
1534 // this field has been defined in the super class
1541 //Vector fields=(Vector)fieldorder.get(cn);
1543 Vector fields = cn.getFieldVec();
1545 for(int i=0; i<fields.size(); i++) {
1546 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
1547 String fstring = fd.getSafeSymbol();
1548 if(printedfieldstbl.containsKey(fstring)) {
1549 printedfieldstbl.put(fstring, cn);
1552 printedfieldstbl.put(fstring, cn);
1554 if (fd.getType().isClass()
1555 && fd.getType().getClassDesc().isEnum()) {
1556 classdefout.println(" int " + fd.getSafeSymbol() + ";");
1557 } else if (fd.getType().isClass()||fd.getType().isArray()) {
1558 if (fd.isStatic()) {
1559 // TODO add version for normal Java later
1561 if(globaldefout != null) {
1562 if(fd.isVolatile()) {
1563 globaldefout.println(" volatile struct "+fd.getType().getSafeSymbol()+ " * "+fd.getSafeSymbol()+";");
1565 globaldefout.println(" struct "+fd.getType().getSafeSymbol()+ " * "+fd.getSafeSymbol()+";");
1569 } else if (fd.isVolatile()) {
1571 classdefout.println(" volatile struct "+fd.getType().getSafeSymbol()+ " * "+fd.getSafeSymbol()+";");
1573 classdefout.println(" struct "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1575 } else if (fd.isStatic()) {
1576 // TODO add version for normal Java later
1578 if(globaldefout != null) {
1579 if(fd.isVolatile()) {
1580 globaldefprimout.println(" volatile "+fd.getType().getSafeSymbol()+ " "+fd.getSafeSymbol()+";");
1582 globaldefprimout.println(" "+fd.getType().getSafeSymbol()+ " "+fd.getSafeSymbol()+";");
1586 } else if (fd.isVolatile()) {
1588 classdefout.println(" volatile "+fd.getType().getSafeSymbol()+ " "+fd.getSafeSymbol()+";");
1590 classdefout.println(" "+fd.getType().getSafeSymbol()+" "+fd.getSafeSymbol()+";");
1595 /* Map flags to integers consistently between inherited
1598 protected void mapFlags(ClassDescriptor cn) {
1599 ClassDescriptor sp=cn.getSuperDesc();
1603 if (!flagorder.containsKey(cn)) {
1604 Hashtable flags=new Hashtable();
1605 flagorder.put(cn,flags);
1607 Hashtable superflags=(Hashtable)flagorder.get(sp);
1608 Iterator superflagit=superflags.keySet().iterator();
1609 while(superflagit.hasNext()) {
1610 FlagDescriptor fd=(FlagDescriptor)superflagit.next();
1611 Integer number=(Integer)superflags.get(fd);
1612 flags.put(fd, number);
1613 if ((number.intValue()+1)>max)
1614 max=number.intValue()+1;
1618 Iterator flagit=cn.getFlags();
1619 while(flagit.hasNext()) {
1620 FlagDescriptor fd=(FlagDescriptor)flagit.next();
1621 if (sp==null||!sp.getFlagTable().contains(fd.getSymbol()))
1622 flags.put(fd, new Integer(max++));
1628 /** This function outputs (1) structures that parameters are
1629 * passed in (when PRECISE GC is enabled) and (2) function
1630 * prototypes for the methods */
1632 protected void generateCallStructs(ClassDescriptor cn, PrintWriter classdefout, PrintWriter output, PrintWriter headersout, PrintWriter globaldefout, PrintWriter globaldefprimout) {
1633 /* Output class structure */
1634 classdefout.println("struct "+cn.getSafeSymbol()+" {");
1635 classdefout.println(" int type;");
1638 additionalClassObjectFields(classdefout);
1641 if (state.EVENTMONITOR) {
1642 classdefout.println(" int objuid;");
1645 classdefout.println(" pthread_t tid;");
1646 classdefout.println(" void * lockentry;");
1647 classdefout.println(" int lockcount;");
1650 classdefout.println(" int mutex;");
1651 classdefout.println(" volatile int notifycount;");
1652 classdefout.println(" volatile int objlock;");
1653 if(state.MULTICOREGC) {
1654 classdefout.println(" int marked;");
1658 classdefout.println(" int flag;");
1659 if((!state.MULTICORE) || (cn.getSymbol().equals("TagDescriptor"))) {
1660 classdefout.println(" void * flagptr;");
1661 } else if (state.MULTICORE) {
1662 classdefout.println(" int version;");
1663 classdefout.println(" int * lock;"); // lock entry for this obj
1664 classdefout.println(" int mutex;");
1665 classdefout.println(" int lockcount;");
1666 if(state.MULTICOREGC) {
1667 classdefout.println(" int marked;");
1670 if (state.OPTIONAL) {
1671 classdefout.println(" int numfses;");
1672 classdefout.println(" int * fses;");
1675 printClassStruct(cn, classdefout, globaldefout, globaldefprimout);
1676 printedfieldstbl.clear(); // = new Hashtable<String, ClassDescriptor>();
1677 classdefout.println("};\n");
1678 generateCallStructsMethods(cn, output, headersout);
1682 protected void generateCallStructsMethods(ClassDescriptor cn, PrintWriter output, PrintWriter headersout) {
1683 for(Iterator methodit=cn.getMethods(); methodit.hasNext(); ) {
1684 MethodDescriptor md=(MethodDescriptor)methodit.next();
1685 boolean foundmatch = false;
1686 if(this.state.genAllMethods) {
1689 Set vec_md = this.state.getMethod2gen().getSet(md.getSymbol());
1690 for(Iterator matchit=vec_md.iterator(); matchit.hasNext();) {
1691 MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
1692 if (md.matches(matchmd)) {
1699 generateMethod(cn, md, headersout, output);
1704 protected void generateMethodParam(ClassDescriptor cn, MethodDescriptor md, PrintWriter output) {
1705 /* Output parameter structure */
1706 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1707 if(md.isInvokedByStatic() && !md.isStaticBlock() && !md.getModifiers().isNative()) {
1708 // generate the staticinit version
1709 String mdstring = md.getSafeMethodDescriptor() + "staticinit";
1711 ParamsObject objectparams=(ParamsObject) paramstable.get(md);
1712 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_params {");
1713 output.println(" int size;");
1714 output.println(" void * next;");
1715 for(int i=0; i<objectparams.numPointers(); i++) {
1716 TempDescriptor temp=objectparams.getPointer(i);
1717 if(temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
1718 output.println(" int " + temp.getSafeSymbol() + ";");
1720 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1723 output.println("};\n");
1726 ParamsObject objectparams=(ParamsObject) paramstable.get(md);
1727 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1728 output.println(" int size;");
1729 output.println(" void * next;");
1730 for(int i=0; i<objectparams.numPointers(); i++) {
1731 TempDescriptor temp=objectparams.getPointer(i);
1732 if(temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
1733 output.println(" int " + temp.getSafeSymbol() + ";");
1735 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1738 output.println("};\n");
1742 protected void generateMethod(ClassDescriptor cn, MethodDescriptor md, PrintWriter headersout, PrintWriter output) {
1743 FlatMethod fm=state.getMethodFlat(md);
1744 generateTempStructs(fm);
1746 ParamsObject objectparams=(ParamsObject) paramstable.get(md);
1747 TempObject objecttemps=(TempObject) tempstable.get(md);
1749 boolean printcomma = false;
1751 generateMethodParam(cn, md, output);
1753 if(md.isInvokedByStatic() && !md.isStaticBlock() && !md.getModifiers().isNative()) {
1754 // generate the staticinit version
1755 String mdstring = md.getSafeMethodDescriptor() + "staticinit";
1757 /* Output temp structure */
1758 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1759 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_locals {");
1760 output.println(" int size;");
1761 output.println(" void * next;");
1762 for(int i=0; i<objecttemps.numPointers(); i++) {
1763 TempDescriptor temp=objecttemps.getPointer(i);
1764 if (!temp.getType().isArray() && temp.getType().isNull())
1765 output.println(" void * "+temp.getSafeSymbol()+";");
1767 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1769 output.println("};\n");
1772 headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+" 1");
1773 /* First the return type */
1774 if (md.getReturnType()!=null) {
1775 if(md.getReturnType().isClass() && md.getReturnType().getClassDesc().isEnum()) {
1776 headersout.println(" int ");
1777 } else if (md.getReturnType().isClass()||md.getReturnType().isArray())
1778 headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1780 headersout.print(md.getReturnType().getSafeSymbol()+" ");
1782 //catch the constructor case
1783 headersout.print("void ");
1785 /* Next the method name */
1786 headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"(");
1788 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1789 headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_params * "+paramsprefix);
1793 /* Output parameter list*/
1794 for(int i=0; i<objectparams.numPrimitives(); i++) {
1795 TempDescriptor temp=objectparams.getPrimitive(i);
1797 headersout.print(", ");
1799 if(temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
1800 headersout.print("int " + temp.getSafeSymbol());
1801 } else if (temp.getType().isClass()||temp.getType().isArray())
1802 headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1804 headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1806 headersout.println(");\n");
1809 /* Output temp structure */
1810 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1811 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1812 output.println(" int size;");
1813 output.println(" void * next;");
1814 for(int i=0; i<objecttemps.numPointers(); i++) {
1815 TempDescriptor temp=objecttemps.getPointer(i);
1816 if (!temp.getType().isArray() && temp.getType().isNull())
1817 output.println(" void * "+temp.getSafeSymbol()+";");
1819 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1821 output.println("};\n");
1824 /********* Output method declaration ***********/
1825 headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1826 /* First the return type */
1827 if (md.getReturnType()!=null) {
1828 if(md.getReturnType().isClass() && md.getReturnType().getClassDesc().isEnum()) {
1829 headersout.println(" int ");
1830 } else if (md.getReturnType().isClass()||md.getReturnType().isArray())
1831 headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1833 headersout.print(md.getReturnType().getSafeSymbol()+" ");
1835 //catch the constructor case
1836 headersout.print("void ");
1838 /* Next the method name */
1839 headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1841 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1842 headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1846 /* Output parameter list*/
1847 for(int i=0; i<objectparams.numPrimitives(); i++) {
1848 TempDescriptor temp=objectparams.getPrimitive(i);
1850 headersout.print(", ");
1852 if(temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
1853 headersout.print("int " + temp.getSafeSymbol());
1854 } else if (temp.getType().isClass()||temp.getType().isArray())
1855 headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1857 headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1859 headersout.println(");\n");
1863 /** This function outputs (1) structures that parameters are
1864 * passed in (when PRECISE GC is enabled) and (2) function
1865 * prototypes for the tasks */
1867 protected void generateTaskStructs(PrintWriter output, PrintWriter headersout) {
1868 /* Cycle through tasks */
1869 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
1871 while(taskit.hasNext()) {
1872 /* Classify parameters */
1873 TaskDescriptor task=(TaskDescriptor)taskit.next();
1874 FlatMethod fm=state.getMethodFlat(task);
1875 generateTempStructs(fm);
1877 ParamsObject objectparams=(ParamsObject) paramstable.get(task);
1878 TempObject objecttemps=(TempObject) tempstable.get(task);
1880 /* Output parameter structure */
1881 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1882 output.println("struct "+task.getSafeSymbol()+"_params {");
1883 output.println(" int size;");
1884 output.println(" void * next;");
1885 for(int i=0; i<objectparams.numPointers(); i++) {
1886 TempDescriptor temp=objectparams.getPointer(i);
1887 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1890 output.println("};\n");
1891 if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
1892 maxtaskparams=objectparams.numPointers()+fm.numTags();
1896 /* Output temp structure */
1897 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1898 output.println("struct "+task.getSafeSymbol()+"_locals {");
1899 output.println(" int size;");
1900 output.println(" void * next;");
1901 for(int i=0; i<objecttemps.numPointers(); i++) {
1902 TempDescriptor temp=objecttemps.getPointer(i);
1903 if (!temp.getType().isArray() && temp.getType().isNull())
1904 output.println(" void * "+temp.getSafeSymbol()+";");
1905 else if(temp.getType().isTag())
1906 output.println(" struct "+
1907 (new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1909 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1911 output.println("};\n");
1914 /* Output task declaration */
1915 headersout.print("void " + task.getSafeSymbol()+"(");
1917 boolean printcomma=false;
1918 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1919 headersout.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
1921 headersout.print("void * parameterarray[]");
1922 headersout.println(");\n");
1926 protected void generateFlatMethod(FlatMethod fm, PrintWriter output) {
1927 if (State.PRINTFLAT)
1928 System.out.println(fm.printMethod());
1929 MethodDescriptor md=fm.getMethod();
1930 TaskDescriptor task=fm.getTask();
1931 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
1932 ParamsObject objectparams=(ParamsObject)paramstable.get(md!=null ? md : task);
1934 if((md != null) && md.isInvokedByStatic() && !md.isStaticBlock() && !md.getModifiers().isNative()) {
1935 // generate a special static init version
1936 mgcstaticinit = true;
1937 String mdstring = md.getSafeMethodDescriptor() + "staticinit";
1939 generateHeader(fm, md!=null ? md : task,output);
1940 TempObject objecttemp=(TempObject) tempstable.get(md!=null ? md : task);
1942 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1943 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_locals "+localsprefix+"={");
1944 output.print(objecttemp.numPointers()+",");
1945 output.print(paramsprefix);
1946 for(int j=0; j<objecttemp.numPointers(); j++)
1947 output.print(", NULL");
1948 output.println("};");
1951 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1952 TempDescriptor td=objecttemp.getPrimitive(i);
1953 TypeDescriptor type=td.getType();
1954 if (type.isNull() && !type.isArray())
1955 output.println(" void * "+td.getSafeSymbol()+";");
1956 else if (type.isClass() && type.getClassDesc().isEnum()) {
1957 output.println(" int " + td.getSafeSymbol() + ";");
1958 } else if (type.isClass()||type.isArray())
1959 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1961 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1964 additionalCodeAtTopFlatMethodBody(output, fm);
1966 /* Check to see if we need to do a GC if this is a
1967 * multi-threaded program...*/
1969 if (((state.OOOJAVA||state.THREAD)&&GENERATEPRECISEGC)
1970 || this.state.MULTICOREGC) {
1971 //Don't bother if we aren't in recursive methods...The loops case will catch it
1972 if (callgraph.getAllMethods(md).contains(md)) {
1973 if (this.state.MULTICOREGC) {
1974 output.println("if(gcflag) gc("+localsprefixaddr+");");
1976 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
1981 generateCode(fm.getNext(0), fm, null, output);
1983 output.println("}\n\n");
1985 mgcstaticinit = false;
1988 generateHeader(fm, md!=null ? md : task,output);
1989 TempObject objecttemp=(TempObject) tempstable.get(md!=null ? md : task);
1991 if((md != null) && (md.isStaticBlock())) {
1992 mgcstaticinit = true;
1995 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1997 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1999 output.print(" struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={");
2000 output.print(objecttemp.numPointers()+",");
2001 output.print(paramsprefix);
2002 for(int j=0; j<objecttemp.numPointers(); j++)
2003 output.print(", NULL");
2004 output.println("};");
2007 for(int i=0; i<objecttemp.numPrimitives(); i++) {
2008 TempDescriptor td=objecttemp.getPrimitive(i);
2009 TypeDescriptor type=td.getType();
2010 if (type.isNull() && !type.isArray())
2011 output.println(" void * "+td.getSafeSymbol()+";");
2012 else if (type.isClass() && type.getClassDesc().isEnum()) {
2013 output.println(" int " + td.getSafeSymbol() + ";");
2014 } else if (type.isClass()||type.isArray())
2015 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
2017 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
2020 additionalCodeAtTopFlatMethodBody(output, fm);
2022 /* Check to see if we need to do a GC if this is a
2023 * multi-threaded program...*/
2025 if (((state.OOOJAVA||state.THREAD)&&GENERATEPRECISEGC)
2026 || this.state.MULTICOREGC) {
2027 //Don't bother if we aren't in recursive methods...The loops case will catch it
2028 if (callgraph.getAllMethods(md).contains(md)) {
2029 if (this.state.MULTICOREGC) {
2030 output.println("if(gcflag) gc("+localsprefixaddr+");");
2032 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2037 if(fm.getMethod().isStaticBlock()) {
2038 // a static block, check if it has been executed
2039 output.println(" if(global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag != 0) {");
2040 output.println(" return;");
2041 output.println(" }");
2045 generateCode(fm.getNext(0), fm, null, output);
2047 output.println("}\n\n");
2049 mgcstaticinit = false;
2052 protected void generateCode(FlatNode first,
2054 Set<FlatNode> stopset,
2055 PrintWriter output) {
2057 /* Assign labels to FlatNode's if necessary.*/
2059 Hashtable<FlatNode, Integer> nodetolabel;
2061 nodetolabel=assignLabels(first, stopset);
2063 Set<FlatNode> storeset=null;
2064 HashSet<FlatNode> genset=null;
2065 HashSet<FlatNode> refset=null;
2066 Set<FlatNode> unionset=null;
2068 /* Do the actual code generation */
2069 FlatNode current_node=null;
2070 HashSet tovisit=new HashSet();
2071 HashSet visited=new HashSet();
2073 while(current_node!=null||!tovisit.isEmpty()) {
2074 if (current_node==null) {
2075 current_node=(FlatNode)tovisit.iterator().next();
2076 tovisit.remove(current_node);
2077 } else if (tovisit.contains(current_node)) {
2078 tovisit.remove(current_node);
2080 visited.add(current_node);
2081 if (nodetolabel.containsKey(current_node)) {
2082 output.println("L"+nodetolabel.get(current_node)+":");
2084 if (state.INSTRUCTIONFAILURE) {
2086 output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
2088 output.println("if ((--instructioncount)==0) injectinstructionfailure();");
2090 if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
2092 generateFlatNode(fm, current_node, output);
2094 if (state.OOOJAVA && stopset!=null) {
2095 assert first.getPrev(0) instanceof FlatSESEEnterNode;
2096 assert current_node instanceof FlatSESEExitNode;
2097 FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev(0);
2098 FlatSESEExitNode fsxn = (FlatSESEExitNode) current_node;
2099 assert fsen.getFlatExit().equals(fsxn);
2100 assert fsxn.getFlatEnter().equals(fsen);
2102 if (current_node.kind()!=FKind.FlatReturnNode) {
2103 if((fm.getMethod() != null) && (fm.getMethod().isStaticBlock())) {
2104 // a static block, check if it has been executed
2105 output.println(" global_defsprim_p->" + fm.getMethod().getClassDesc().getSafeSymbol()+"static_block_exe_flag = 1;");
2108 output.println(" return;");
2111 } else if(current_node.numNext()==1) {
2113 if (state.OOOJAVA &&
2114 current_node.kind()==FKind.FlatSESEEnterNode) {
2115 FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
2116 generateFlatNode(fm, current_node, output);
2117 nextnode=fsen.getFlatExit().getNext(0);
2120 generateFlatNode(fm, current_node, output);
2121 nextnode=current_node.getNext(0);
2123 if (visited.contains(nextnode)) {
2124 output.println("goto L"+nodetolabel.get(nextnode)+";");
2127 current_node=nextnode;
2128 } else if (current_node.numNext()==2) {
2131 generateFlatCondBranch(fm, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2132 if (!visited.contains(current_node.getNext(1)))
2133 tovisit.add(current_node.getNext(1));
2134 if (visited.contains(current_node.getNext(0))) {
2135 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2138 current_node=current_node.getNext(0);
2139 } else throw new Error();
2143 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
2144 HashSet tovisit=new HashSet();
2145 HashSet visited=new HashSet();
2147 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2150 /*Assign labels first. A node needs a label if the previous
2151 * node has two exits or this node is a join point. */
2153 while(!tovisit.isEmpty()) {
2154 FlatNode fn=(FlatNode)tovisit.iterator().next();
2159 if(lastset!=null&&lastset.contains(fn)) {
2160 // if last is not null and matches, don't go
2161 // any further for assigning labels
2165 for(int i=0; i<fn.numNext(); i++) {
2166 FlatNode nn=fn.getNext(i);
2169 //1) Edge >1 of node
2170 nodetolabel.put(nn,new Integer(labelindex++));
2172 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2176 nodetolabel.put(nn,new Integer(labelindex++));
2183 /** Generate text string that corresponds to the TempDescriptor td. */
2184 protected String generateTemp(FlatMethod fm, TempDescriptor td) {
2185 MethodDescriptor md=fm.getMethod();
2186 TaskDescriptor task=fm.getTask();
2187 TempObject objecttemps=(TempObject) tempstable.get(md!=null ? md : task);
2189 if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
2190 return td.getSafeSymbol();
2193 if (objecttemps.isLocalPtr(td)) {
2194 return localsprefixderef+td.getSafeSymbol();
2197 if (objecttemps.isParamPtr(td)) {
2198 return paramsprefix+"->"+td.getSafeSymbol();
2206 protected void generateFlatNode(FlatMethod fm, FlatNode fn, PrintWriter output) {
2207 if(state.LINENUM) printSourceLineNumber(fm,fn,output);
2208 additionalCodePreNode(fm, fn, output);
2211 case FKind.FlatAtomicEnterNode:
2212 generateFlatAtomicEnterNode(fm, (FlatAtomicEnterNode) fn, output);
2215 case FKind.FlatAtomicExitNode:
2216 generateFlatAtomicExitNode(fm, (FlatAtomicExitNode) fn, output);
2219 case FKind.FlatInstanceOfNode:
2220 generateFlatInstanceOfNode(fm, (FlatInstanceOfNode)fn, output);
2223 case FKind.FlatSESEEnterNode:
2224 generateFlatSESEEnterNode(fm, (FlatSESEEnterNode)fn, output);
2227 case FKind.FlatSESEExitNode:
2228 generateFlatSESEExitNode(fm, (FlatSESEExitNode)fn, output);
2231 case FKind.FlatWriteDynamicVarNode:
2232 generateFlatWriteDynamicVarNode(fm, (FlatWriteDynamicVarNode)fn, output);
2235 case FKind.FlatGlobalConvNode:
2236 generateFlatGlobalConvNode(fm, (FlatGlobalConvNode) fn, output);
2239 case FKind.FlatTagDeclaration:
2240 generateFlatTagDeclaration(fm, (FlatTagDeclaration) fn,output);
2243 case FKind.FlatCall:
2244 generateFlatCall(fm, (FlatCall) fn,output);
2247 case FKind.FlatFieldNode:
2248 generateFlatFieldNode(fm, (FlatFieldNode) fn,output);
2251 case FKind.FlatElementNode:
2252 generateFlatElementNode(fm, (FlatElementNode) fn,output);
2255 case FKind.FlatSetElementNode:
2256 generateFlatSetElementNode(fm, (FlatSetElementNode) fn,output);
2259 case FKind.FlatSetFieldNode:
2260 generateFlatSetFieldNode(fm, (FlatSetFieldNode) fn,output);
2264 generateFlatNew(fm, (FlatNew) fn,output);
2267 case FKind.FlatOpNode:
2268 generateFlatOpNode(fm, (FlatOpNode) fn,output);
2271 case FKind.FlatCastNode:
2272 generateFlatCastNode(fm, (FlatCastNode) fn,output);
2275 case FKind.FlatLiteralNode:
2276 generateFlatLiteralNode(fm, (FlatLiteralNode) fn,output);
2279 case FKind.FlatReturnNode:
2280 generateFlatReturnNode(fm, (FlatReturnNode) fn,output);
2284 output.println("/* nop */");
2287 case FKind.FlatGenReachNode:
2288 // this node is just for generating a reach graph
2289 // in disjointness analysis at a particular program point
2292 case FKind.FlatExit:
2293 output.println("/* exit */");
2296 case FKind.FlatBackEdge:
2297 generateFlatBackEdge(fm, (FlatBackEdge)fn, output);
2300 case FKind.FlatCheckNode:
2301 generateFlatCheckNode(fm, (FlatCheckNode) fn, output);
2304 case FKind.FlatFlagActionNode:
2305 generateFlatFlagActionNode(fm, (FlatFlagActionNode) fn, output);
2308 case FKind.FlatPrefetchNode:
2309 generateFlatPrefetchNode(fm, (FlatPrefetchNode) fn, output);
2312 case FKind.FlatOffsetNode:
2313 generateFlatOffsetNode(fm, (FlatOffsetNode)fn, output);
2320 additionalCodePostNode(fm, fn, output);
2323 public void generateFlatBackEdge(FlatMethod fm, FlatBackEdge fn, PrintWriter output) {
2324 if (((state.OOOJAVA||state.THREAD)&&GENERATEPRECISEGC)
2325 || (this.state.MULTICOREGC)) {
2326 if(this.state.MULTICOREGC) {
2327 output.println("if (gcflag) gc("+localsprefixaddr+");");
2329 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2332 output.println("/* nop */");
2335 public void generateFlatOffsetNode(FlatMethod fm, FlatOffsetNode fofn, PrintWriter output) {
2336 output.println("/* FlatOffsetNode */");
2337 FieldDescriptor fd=fofn.getField();
2338 if(!fd.isStatic()) {
2339 output.println(generateTemp(fm, fofn.getDst())+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+
2340 fd.getSafeSymbol()+");");
2342 output.println("/* offset */");
2345 public void generateFlatPrefetchNode(FlatMethod fm, FlatPrefetchNode fpn, PrintWriter output) {
2348 public void generateFlatGlobalConvNode(FlatMethod fm, FlatGlobalConvNode fgcn, PrintWriter output) {
2351 public void generateFlatInstanceOfNode(FlatMethod fm, FlatInstanceOfNode fion, PrintWriter output) {
2354 if (fion.getType().isArray()) {
2355 type=state.getArrayNumber(fion.getType())+state.numClasses();
2356 } else if (fion.getType().getClassDesc().isInterface()) {
2357 type=fion.getType().getClassDesc().getId()+state.numClasses()+state.numArrays();
2359 type=fion.getType().getClassDesc().getId();
2361 if (fion.getSrc().getType().isArray()) {
2362 otype=state.getArrayNumber(fion.getSrc().getType())+state.numClasses();
2363 } else if (fion.getSrc().getType().getClassDesc().isInterface()) {
2364 otype=fion.getSrc().getType().getClassDesc().getId()+state.numClasses()+state.numArrays();
2366 otype=fion.getSrc().getType().getClassDesc().getId();
2369 if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
2370 output.println(generateTemp(fm, fion.getDst())+"=(" + generateTemp(fm,fion.getSrc()) + "!= NULL);");
2372 output.println(generateTemp(fm, fion.getDst())+"=instanceof("+generateTemp(fm,fion.getSrc())+","+type+");");
2376 public void generateFlatAtomicEnterNode(FlatMethod fm, FlatAtomicEnterNode faen, PrintWriter output) {
2379 public void generateFlatAtomicExitNode(FlatMethod fm, FlatAtomicExitNode faen, PrintWriter output) {
2382 public void generateFlatSESEEnterNode(FlatMethod fm,
2383 FlatSESEEnterNode fsen,
2384 PrintWriter output) {
2385 // if OOOJAVA flag is off, okay that SESE nodes are in IR graph,
2386 // just skip over them and code generates exactly the same
2389 public void generateFlatSESEExitNode(FlatMethod fm,
2390 FlatSESEExitNode fsexn,
2391 PrintWriter output) {
2392 // if OOOJAVA flag is off, okay that SESE nodes are in IR graph,
2393 // just skip over them and code generates exactly the same
2396 public void generateFlatWriteDynamicVarNode(FlatMethod fm,
2397 FlatWriteDynamicVarNode fwdvn,
2398 PrintWriter output) {
2402 protected void generateFlatCheckNode(FlatMethod fm, FlatCheckNode fcn, PrintWriter output) {
2403 if (state.CONSCHECK) {
2404 String specname=fcn.getSpec();
2405 String varname="repairstate___";
2406 output.println("{");
2407 output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
2409 TempDescriptor[] temps=fcn.getTemps();
2410 String[] vars=fcn.getVars();
2411 for(int i=0; i<temps.length; i++) {
2412 output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i])+";");
2415 output.println("if (doanalysis"+specname+"("+varname+")) {");
2416 output.println("free"+specname+"_state("+varname+");");
2417 output.println("} else {");
2418 output.println("/* Bad invariant */");
2419 output.println("free"+specname+"_state("+varname+");");
2420 output.println("abort_task();");
2421 output.println("}");
2422 output.println("}");
2426 protected void generateFlatCall(FlatMethod fm, FlatCall fc, PrintWriter output) {
2427 MethodDescriptor md=fc.getMethod();
2428 ParamsObject objectparams=(ParamsObject)paramstable.get(md);
2429 ClassDescriptor cn=md.getClassDesc();
2430 String mdstring = md.getSafeMethodDescriptor();
2431 if(mgcstaticinit && !md.isStaticBlock() && !md.getModifiers().isNative()) {
2432 mdstring += "staticinit";
2435 // if the called method is a static block or a static method or a constructor
2436 // need to check if it can be invoked inside some static block
2437 if((md.isStatic() || md.isStaticBlock() || md.isConstructor()) &&
2438 ((fm.getMethod() != null) && ((fm.getMethod().isStaticBlock()) || (fm.getMethod().isInvokedByStatic())))) {
2439 if(!md.isInvokedByStatic()) {
2440 System.err.println("Error: a method that is invoked inside a static block is not tagged!");
2442 // is a static block or is invoked in some static block
2443 ClassDescriptor cd = fm.getMethod().getClassDesc();
2445 // the same class, do nothing
2446 } else if(mgcstaticinit) {
2447 // generate static init check code if it has not done static init in main()
2448 if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) {
2449 // need to check if the class' static fields have been initialized and/or
2450 // its static blocks have been executed
2451 output.println("if(global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag == 0) {");
2452 if(cn.getNumStaticBlocks() != 0) {
2453 MethodDescriptor t_md = (MethodDescriptor)cn.getMethodTable().get("staticblocks");
2454 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2455 output.print(" struct "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"_params __parameterlist__={");
2456 output.println("0, NULL};");
2457 output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"(& __parameterlist__);");
2459 output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();");
2462 output.println(" global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag = 1;");
2464 output.println("}");
2468 if((md.getSymbol().equals("MonitorEnter") || md.getSymbol().equals("MonitorExit")) && fc.getThis().getSymbol().equals("classobj")) {
2469 output.println("{");
2470 // call MonitorEnter/MonitorExit on a class obj
2471 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2472 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
2473 output.println("1," + localsprefixaddr + ", global_defs_p->"+ fc.getThis().getType().getClassDesc().getSafeSymbol() +"classobj};");
2474 output.println(" "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
2476 output.println(" " + cn.getSafeSymbol()+md.getSafeSymbol()+"_"
2477 + md.getSafeMethodDescriptor() + "((struct ___Object___*)(global_defs_p->"
2478 + fc.getThis().getType().getClassDesc().getSafeSymbol() +"classobj));");
2480 output.println("}");
2484 output.println("{");
2485 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2486 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_params __parameterlist__={");
2487 output.print(objectparams.numPointers());
2488 output.print(", "+localsprefixaddr);
2489 if (md.getThis()!=null) {
2491 output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis()));
2493 if (fc.getThis()!=null&&md.getThis()==null) {
2494 System.out.println("WARNING!!!!!!!!!!!!");
2495 System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
2499 for(int i=0; i<fc.numArgs(); i++) {
2500 Descriptor var=md.getParameter(i);
2501 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
2502 if (objectparams.isParamPtr(paramtemp)) {
2503 TempDescriptor targ=fc.getArg(i);
2505 TypeDescriptor td=md.getParamType(i);
2507 output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol() +" *)"+generateTemp(fm, targ));
2509 output.print("(struct "+md.getParamType(i).getSafeSymbol() +" *)"+generateTemp(fm, targ));
2512 output.println("};");
2517 if (fc.getReturnTemp()!=null)
2518 output.print(generateTemp(fm,fc.getReturnTemp())+"=");
2520 /* Do we need to do virtual dispatch? */
2521 if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
2523 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring);
2527 if (md.getReturnType().isClass() && md.getReturnType().getClassDesc().isEnum()) {
2528 output.print("int ");
2529 } else if (md.getReturnType().isClass()||md.getReturnType().isArray())
2530 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
2532 output.print(md.getReturnType().getSafeSymbol()+" ");
2533 output.print("(*)(");
2535 boolean printcomma=false;
2536 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2537 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_params * ");
2541 for(int i=0; i<objectparams.numPrimitives(); i++) {
2542 TempDescriptor temp=objectparams.getPrimitive(i);
2546 if (temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
2547 output.print("int ");
2548 } else if (temp.getType().isClass()||temp.getType().isArray())
2549 output.print("struct " + temp.getType().getSafeSymbol()+" * ");
2551 output.print(temp.getType().getSafeSymbol());
2555 output.print("))virtualtable["+generateTemp(fm,fc.getThis())+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
2559 boolean needcomma=false;
2560 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2561 output.print("&__parameterlist__");
2565 if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
2566 if (fc.getThis()!=null) {
2567 TypeDescriptor ptd=null;
2568 if(md.getThis() != null) {
2569 ptd = md.getThis().getType();
2571 ptd = fc.getThis().getType();
2575 if(ptd.isClass() && ptd.getClassDesc().isEnum()) {
2577 } else if (ptd.isClass()&&!ptd.isArray())
2578 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
2579 output.print(generateTemp(fm,fc.getThis()));
2584 for(int i=0; i<fc.numArgs(); i++) {
2585 Descriptor var=md.getParameter(i);
2586 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
2587 if (objectparams.isParamPrim(paramtemp)) {
2588 TempDescriptor targ=fc.getArg(i);
2592 TypeDescriptor ptd=md.getParamType(i);
2593 if (ptd.isClass() && ptd.getClassDesc().isEnum()) {
2595 } else if (ptd.isClass()&&!ptd.isArray())
2596 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
2597 output.print(generateTemp(fm, targ));
2601 output.println(");");
2602 output.println(" }");
2605 protected boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
2606 if(thiscd.isInterface()) {
2607 // for interfaces, always need virtual dispatch
2610 Set subclasses=typeutil.getSubClasses(thiscd);
2611 if (subclasses==null)
2613 for(Iterator classit=subclasses.iterator(); classit.hasNext(); ) {
2614 ClassDescriptor cd=(ClassDescriptor)classit.next();
2615 Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol());
2616 for(Iterator matchit=possiblematches.iterator(); matchit.hasNext(); ) {
2617 MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
2618 if (md.matches(matchmd))
2626 protected void generateFlatFieldNode(FlatMethod fm, FlatFieldNode ffn, PrintWriter output) {
2628 if(ffn.getField().isStatic()) {
2630 if((fm.getMethod().isStaticBlock()) || (fm.getMethod().isInvokedByStatic())) {
2631 // is a static block or is invoked in some static block
2632 ClassDescriptor cd = fm.getMethod().getClassDesc();
2633 ClassDescriptor cn = ffn.getSrc().getType().getClassDesc();
2635 // the same class, do nothing
2636 } else if(mgcstaticinit) {
2637 // generate the static init check code if has not done the static init in main()
2638 if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) {
2639 // need to check if the class' static fields have been initialized and/or
2640 // its static blocks have been executed
2641 output.println("if(global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag == 0) {");
2642 if(cn.getNumStaticBlocks() != 0) {
2643 MethodDescriptor t_md = (MethodDescriptor)cn.getMethodTable().get("staticblocks");
2644 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2645 output.print(" struct "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"_params __parameterlist__={");
2646 output.println("0, NULL};");
2647 output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"(& __parameterlist__);");
2649 output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();");
2652 output.println(" global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag = 1;");
2654 output.println("}");
2658 // redirect to the global_defs_p structure
2659 if((ffn.getField().isStatic()) || (ffn.getSrc().getType().isClassNameRef())) {
2660 // reference to the static field with Class name
2661 if (ffn.getField().getType().isPtr())
2662 output.println(generateTemp(fm, ffn.getDst())+"=global_defs_p->"+ffn.getField().getSafeSymbol()+";");
2664 output.println(generateTemp(fm, ffn.getDst())+"=global_defsprim_p->"+ffn.getField().getSafeSymbol()+";");
2666 output.println(generateTemp(fm, ffn.getDst())+"=*"+ generateTemp(fm,ffn.getSrc())+"->"+ ffn.getField().getSafeSymbol()+";");
2668 } else if (ffn.getField().isEnum()) {
2669 // an Enum value, directly replace the field access as int
2670 output.println(generateTemp(fm, ffn.getDst()) + "=" + ffn.getField().enumValue() + ";");
2672 output.println(generateTemp(fm, ffn.getDst())+"="+ generateTemp(fm,ffn.getSrc())+"->"+ ffn.getField().getSafeSymbol()+";");
2677 protected void generateFlatSetFieldNode(FlatMethod fm, FlatSetFieldNode fsfn, PrintWriter output) {
2678 if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
2679 throw new Error("Can't set array length");
2680 if (state.FASTCHECK) {
2681 String dst=generateTemp(fm, fsfn.getDst());
2682 output.println("if(!"+dst+"->"+localcopystr+") {");
2683 /* Link object into list */
2684 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
2685 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
2687 output.println("COPY_OBJ("+dst+");");
2688 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
2689 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
2690 output.println("}");
2693 if(fsfn.getField().isStatic()) {
2695 if((fm.getMethod().isStaticBlock()) || (fm.getMethod().isInvokedByStatic())) {
2696 // is a static block or is invoked in some static block
2697 ClassDescriptor cd = fm.getMethod().getClassDesc();
2698 ClassDescriptor cn = fsfn.getDst().getType().getClassDesc();
2700 // the same class, do nothing
2701 } else if(mgcstaticinit){
2702 // generate static init check code if has not done the static init in main()
2703 if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) {
2704 // need to check if the class' static fields have been initialized and/or
2705 // its static blocks have been executed
2706 output.println("if(global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag == 0) {");
2707 if(cn.getNumStaticBlocks() != 0) {
2708 MethodDescriptor t_md = (MethodDescriptor)cn.getMethodTable().get("staticblocks");
2709 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2710 output.print(" struct "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"_params __parameterlist__={");
2711 output.println("0, NULL};");
2712 output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"(& __parameterlist__);");
2714 output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();");
2717 output.println(" global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag = 1;");
2719 output.println("}");
2723 // redirect to the global_defs_p structure
2724 if((fsfn.getDst().getType().isClassNameRef()) || (fsfn.getField().isStatic())) {
2725 // reference to the static field with Class name
2726 if (fsfn.getField().getType().isPtr())
2727 output.println("global_defs_p->" +
2728 fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc())+";");
2730 output.println("global_defsprim_p->" +
2731 fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc())+";");
2733 output.println("*"+generateTemp(fm, fsfn.getDst())+"->"+
2734 fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc())+";");
2737 output.println(generateTemp(fm, fsfn.getDst())+"->"+
2738 fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc())+";");
2743 protected void generateFlatElementNode(FlatMethod fm, FlatElementNode fen, PrintWriter output) {
2744 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
2747 if (elementtype.isClass() && elementtype.getClassDesc().isEnum()) {
2749 } else if (elementtype.isArray()||elementtype.isClass())
2752 type=elementtype.getSafeSymbol()+" ";
2754 if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
2755 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fen.getIndex())+") >= "+generateTemp(fm,fen.getSrc()) + "->___length___))");
2756 output.println("failedboundschk();");
2758 output.println(generateTemp(fm, fen.getDst())+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc())+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex())+"];");
2761 protected void generateFlatSetElementNode(FlatMethod fm, FlatSetElementNode fsen, PrintWriter output) {
2762 //TODO: need dynamic check to make sure this assignment is actually legal
2763 //Because Object[] could actually be something more specific...ie. Integer[]
2765 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
2768 if (elementtype.isClass() && elementtype.getClassDesc().isEnum()) {
2770 } else if (elementtype.isArray()||elementtype.isClass() || (elementtype.isNull()))
2773 type=elementtype.getSafeSymbol()+" ";
2775 if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
2776 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fsen.getIndex())+") >= "+generateTemp(fm,fsen.getDst()) + "->___length___))");
2777 output.println("failedboundschk();");
2779 if (state.FASTCHECK) {
2780 String dst=generateTemp(fm, fsen.getDst());
2781 output.println("if(!"+dst+"->"+localcopystr+") {");
2782 /* Link object into list */
2783 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
2784 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
2786 output.println("COPY_OBJ("+dst+");");
2787 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
2788 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
2789 output.println("}");
2791 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst())+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex())+"]="+generateTemp(fm,fsen.getSrc())+";");
2795 protected void generateFlatNew(FlatMethod fm, FlatNew fn, PrintWriter output) {
2796 if (fn.getType().isArray()) {
2797 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
2798 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2799 output.println(generateTemp(fm,fn.getDst())+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize())+");");
2801 output.println(generateTemp(fm,fn.getDst())+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize())+");");
2804 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2805 output.println(generateTemp(fm,fn.getDst())+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
2807 output.println(generateTemp(fm,fn.getDst())+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
2810 if (state.FASTCHECK) {
2811 String dst=generateTemp(fm,fn.getDst());
2812 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
2813 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
2814 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
2818 protected void generateFlatTagDeclaration(FlatMethod fm, FlatTagDeclaration fn, PrintWriter output) {
2819 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2820 output.println(generateTemp(fm,fn.getDst())+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
2822 output.println(generateTemp(fm,fn.getDst())+"=allocate_tag("+state.getTagId(fn.getType())+");");
2826 protected void generateFlatOpNode(FlatMethod fm, FlatOpNode fon, PrintWriter output) {
2827 if (fon.getRight()!=null) {
2828 if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
2829 if (fon.getLeft().getType().isLong())
2830 output.println(generateTemp(fm, fon.getDest())+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft())+")>>"+generateTemp(fm,fon.getRight())+";");
2832 output.println(generateTemp(fm, fon.getDest())+" = ((unsigned int)"+generateTemp(fm, fon.getLeft())+")>>"+generateTemp(fm,fon.getRight())+";");
2835 output.println(generateTemp(fm, fon.getDest())+" = "+generateTemp(fm, fon.getLeft())+fon.getOp().toString()+generateTemp(fm,fon.getRight())+";");
2836 } else if (fon.getOp().getOp()==Operation.ASSIGN)
2837 output.println(generateTemp(fm, fon.getDest())+" = "+generateTemp(fm, fon.getLeft())+";");
2838 else if (fon.getOp().getOp()==Operation.UNARYPLUS)
2839 output.println(generateTemp(fm, fon.getDest())+" = "+generateTemp(fm, fon.getLeft())+";");
2840 else if (fon.getOp().getOp()==Operation.UNARYMINUS)
2841 output.println(generateTemp(fm, fon.getDest())+" = -"+generateTemp(fm, fon.getLeft())+";");
2842 else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
2843 output.println(generateTemp(fm, fon.getDest())+" = !"+generateTemp(fm, fon.getLeft())+";");
2844 else if (fon.getOp().getOp()==Operation.COMP)
2845 output.println(generateTemp(fm, fon.getDest())+" = ~"+generateTemp(fm, fon.getLeft())+";");
2846 else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
2847 output.println(generateTemp(fm, fon.getDest())+" = "+generateTemp(fm, fon.getLeft())+"->fses==NULL;");
2849 output.println(generateTemp(fm, fon.getDest())+fon.getOp().toString()+generateTemp(fm, fon.getLeft())+";");
2852 protected void generateFlatCastNode(FlatMethod fm, FlatCastNode fcn, PrintWriter output) {
2853 /* TODO: Do type check here */
2854 if (fcn.getType().isArray()) {
2855 output.println(generateTemp(fm,fcn.getDst())+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc())+";");
2856 } else if (fcn.getType().isClass() && fcn.getType().getClassDesc().isEnum()) {
2857 output.println(generateTemp(fm,fcn.getDst())+"=(int)"+generateTemp(fm,fcn.getSrc())+";");
2858 } else if (fcn.getType().isClass())
2859 output.println(generateTemp(fm,fcn.getDst())+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc())+";");
2861 output.println(generateTemp(fm,fcn.getDst())+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc())+";");
2864 protected void generateFlatLiteralNode(FlatMethod fm, FlatLiteralNode fln, PrintWriter output) {
2865 if (fln.getValue()==null)
2866 output.println(generateTemp(fm, fln.getDst())+"=0;");
2867 else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
2868 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2869 output.println(generateTemp(fm, fln.getDst())+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
2871 output.println(generateTemp(fm, fln.getDst())+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
2873 } else if (fln.getType().isBoolean()) {
2874 if (((Boolean)fln.getValue()).booleanValue())
2875 output.println(generateTemp(fm, fln.getDst())+"=1;");
2877 output.println(generateTemp(fm, fln.getDst())+"=0;");
2878 } else if (fln.getType().isChar()) {
2879 String st=FlatLiteralNode.escapeString(fln.getValue().toString());
2880 output.println(generateTemp(fm, fln.getDst())+"='"+st+"';");
2881 } else if (fln.getType().isLong()) {
2882 output.println(generateTemp(fm, fln.getDst())+"="+fln.getValue()+"LL;");
2884 output.println(generateTemp(fm, fln.getDst())+"="+fln.getValue()+";");
2887 protected void generateFlatReturnNode(FlatMethod fm, FlatReturnNode frn, PrintWriter output) {
2888 if((fm.getMethod() != null) && (fm.getMethod().isStaticBlock())) {
2889 // a static block, check if it has been executed
2890 output.println(" global_defsprim_p->" + fm.getMethod().getClassDesc().getSafeSymbol()+"static_block_exe_flag = 1;");
2894 if (frn.getReturnTemp()!=null) {
2895 if (frn.getReturnTemp().getType().isPtr())
2896 output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp())+";");
2898 output.println("return "+generateTemp(fm, frn.getReturnTemp())+";");
2900 output.println("return;");
2904 protected void generateFlatCondBranch(FlatMethod fm, FlatCondBranch fcb, String label, PrintWriter output) {
2905 output.println("if (!"+generateTemp(fm, fcb.getTest())+") goto "+label+";");
2908 /** This method generates header information for the method or
2909 * task referenced by the Descriptor des. */
2910 protected void generateHeader(FlatMethod fm, Descriptor des, PrintWriter output) {
2911 generateHeader(fm, des, output, false);
2914 protected void generateHeader(FlatMethod fm, Descriptor des, PrintWriter output, boolean addSESErecord) {
2916 ParamsObject objectparams=(ParamsObject)paramstable.get(des);
2917 MethodDescriptor md=null;
2918 TaskDescriptor task=null;
2919 if (des instanceof MethodDescriptor)
2920 md=(MethodDescriptor) des;
2922 task=(TaskDescriptor) des;
2923 String mdstring = md != null ? md.getSafeMethodDescriptor() : null;
2925 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
2927 if (md!=null&&md.getReturnType()!=null) {
2928 if (md.getReturnType().isClass() && md.getReturnType().getClassDesc().isEnum()) {
2929 output.print("int ");
2930 } else if (md.getReturnType().isClass()||md.getReturnType().isArray())
2931 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
2933 output.print(md.getReturnType().getSafeSymbol()+" ");
2935 //catch the constructor case
2936 output.print("void ");
2938 if(mgcstaticinit && !md.isStaticBlock() && !md.getModifiers().isNative()) {
2939 mdstring += "staticinit";
2941 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"(");
2943 output.print(task.getSafeSymbol()+"(");
2945 boolean printcomma=false;
2946 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2948 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_params * "+paramsprefix);
2950 output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
2956 for(int i=0; i<objectparams.numPrimitives(); i++) {
2957 TempDescriptor temp=objectparams.getPrimitive(i);
2961 if(temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
2962 output.print("int " + temp.getSafeSymbol());
2963 } else if (temp.getType().isClass()||temp.getType().isArray())
2964 output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
2966 output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
2968 output.println(") {");
2969 } else if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
2970 /* Imprecise Task */
2971 output.println("void * parameterarray[]) {");
2972 /* Unpack variables */
2973 for(int i=0; i<objectparams.numPrimitives(); i++) {
2974 TempDescriptor temp=objectparams.getPrimitive(i);
2975 if(temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
2976 output.print("int " + temp.getSafeSymbol() + "=parameterarray["+i+"];");
2978 output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
2981 for(int i=0; i<fm.numTags(); i++) {
2982 TempDescriptor temp=fm.getTag(i);
2983 int offset=i+objectparams.numPrimitives();
2984 output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
2987 if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
2988 maxtaskparams=objectparams.numPrimitives()+fm.numTags();
2989 } else output.println(") {");
2992 public void generateFlatFlagActionNode(FlatMethod fm, FlatFlagActionNode ffan, PrintWriter output) {
2993 output.println("/* FlatFlagActionNode */");
2996 /* Process tag changes */
2997 Relation tagsettable=new Relation();
2998 Relation tagcleartable=new Relation();
3000 Iterator tagsit=ffan.getTempTagPairs();
3001 while (tagsit.hasNext()) {
3002 TempTagPair ttp=(TempTagPair) tagsit.next();
3003 TempDescriptor objtmp=ttp.getTemp();
3004 TagDescriptor tag=ttp.getTag();
3005 TempDescriptor tagtmp=ttp.getTagTemp();
3006 boolean tagstatus=ffan.getTagChange(ttp);
3008 tagsettable.put(objtmp, tagtmp);
3010 tagcleartable.put(objtmp, tagtmp);
3015 Hashtable flagandtable=new Hashtable();
3016 Hashtable flagortable=new Hashtable();
3018 /* Process flag changes */
3019 Iterator flagsit=ffan.getTempFlagPairs();
3020 while(flagsit.hasNext()) {
3021 TempFlagPair tfp=(TempFlagPair)flagsit.next();
3022 TempDescriptor temp=tfp.getTemp();
3023 Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
3024 FlagDescriptor flag=tfp.getFlag();
3026 //Newly allocate objects that don't set any flags case
3027 if (flagortable.containsKey(temp)) {
3031 flagortable.put(temp,new Integer(mask));
3033 int flagid=1<<((Integer)flagtable.get(flag)).intValue();
3034 boolean flagstatus=ffan.getFlagChange(tfp);
3037 if (flagortable.containsKey(temp)) {
3038 mask=((Integer)flagortable.get(temp)).intValue();
3041 flagortable.put(temp,new Integer(mask));
3043 int mask=0xFFFFFFFF;
3044 if (flagandtable.containsKey(temp)) {
3045 mask=((Integer)flagandtable.get(temp)).intValue();
3047 mask&=(0xFFFFFFFF^flagid);
3048 flagandtable.put(temp,new Integer(mask));
3054 HashSet flagtagset=new HashSet();
3055 flagtagset.addAll(flagortable.keySet());
3056 flagtagset.addAll(flagandtable.keySet());
3057 flagtagset.addAll(tagsettable.keySet());
3058 flagtagset.addAll(tagcleartable.keySet());
3060 Iterator ftit=flagtagset.iterator();
3061 while(ftit.hasNext()) {
3062 TempDescriptor temp=(TempDescriptor)ftit.next();
3065 Set tagtmps=tagcleartable.get(temp);
3066 if (tagtmps!=null) {
3067 Iterator tagit=tagtmps.iterator();
3068 while(tagit.hasNext()) {
3069 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
3070 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
3071 output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp)+", "+generateTemp(fm,tagtmp)+");");
3073 output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp)+", "+generateTemp(fm,tagtmp)+");");
3077 tagtmps=tagsettable.get(temp);
3078 if (tagtmps!=null) {
3079 Iterator tagit=tagtmps.iterator();
3080 while(tagit.hasNext()) {
3081 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
3082 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
3083 output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp)+", "+generateTemp(fm,tagtmp)+");");
3085 output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp)+", "+generateTemp(fm,tagtmp)+");");
3090 int andmask=0xFFFFFFF;
3092 if (flagortable.containsKey(temp))
3093 ormask=((Integer)flagortable.get(temp)).intValue();
3094 if (flagandtable.containsKey(temp))
3095 andmask=((Integer)flagandtable.get(temp)).intValue();
3096 generateFlagOrAnd(ffan, fm, temp, output, ormask, andmask);
3097 generateObjectDistribute(ffan, fm, temp, output);
3101 protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, TempDescriptor temp,
3102 PrintWriter output, int ormask, int andmask) {
3103 if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
3104 output.println("flagorandinit("+generateTemp(fm, temp)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
3106 output.println("flagorand("+generateTemp(fm, temp)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
3110 protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, TempDescriptor temp, PrintWriter output) {
3111 output.println("enqueueObject("+generateTemp(fm, temp)+");");
3114 void generateOptionalHeader(PrintWriter headers) {
3117 headers.println("#include \"task.h\"\n\n");
3118 headers.println("#ifndef _OPTIONAL_STRUCT_");
3119 headers.println("#define _OPTIONAL_STRUCT_");
3121 //STRUCT PREDICATEMEMBER
3122 headers.println("struct predicatemember{");
3123 headers.println("int type;");
3124 headers.println("int numdnfterms;");
3125 headers.println("int * flags;");
3126 headers.println("int numtags;");
3127 headers.println("int * tags;\n};\n\n");
3129 //STRUCT OPTIONALTASKDESCRIPTOR
3130 headers.println("struct optionaltaskdescriptor{");
3131 headers.println("struct taskdescriptor * task;");
3132 headers.println("int index;");
3133 headers.println("int numenterflags;");
3134 headers.println("int * enterflags;");
3135 headers.println("int numpredicatemembers;");
3136 headers.println("struct predicatemember ** predicatememberarray;");
3137 headers.println("};\n\n");
3139 //STRUCT TASKFAILURE
3140 headers.println("struct taskfailure {");
3141 headers.println("struct taskdescriptor * task;");
3142 headers.println("int index;");
3143 headers.println("int numoptionaltaskdescriptors;");
3144 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
3146 //STRUCT FSANALYSISWRAPPER
3147 headers.println("struct fsanalysiswrapper{");
3148 headers.println("int flags;");
3149 headers.println("int numtags;");
3150 headers.println("int * tags;");
3151 headers.println("int numtaskfailures;");
3152 headers.println("struct taskfailure ** taskfailurearray;");
3153 headers.println("int numoptionaltaskdescriptors;");
3154 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
3156 //STRUCT CLASSANALYSISWRAPPER
3157 headers.println("struct classanalysiswrapper{");
3158 headers.println("int type;");
3159 headers.println("int numotd;");
3160 headers.println("struct optionaltaskdescriptor ** otdarray;");
3161 headers.println("int numfsanalysiswrappers;");
3162 headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
3164 headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
3166 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
3167 while(taskit.hasNext()) {
3168 TaskDescriptor td=(TaskDescriptor)taskit.next();
3169 headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
3174 //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
3175 int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
3176 int predicateindex = 0;
3177 //iterate through the classes concerned by the predicate
3178 Set c_vard = predicate.vardescriptors;
3179 Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
3182 for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext(); ) {
3183 VarDescriptor vard = (VarDescriptor)vard_it.next();
3184 TypeDescriptor typed = vard.getType();
3186 //generate for flags
3187 HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
3188 output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
3190 if (fen_hashset!=null) {
3191 for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext(); ) {
3192 FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
3194 DNFFlag dflag=fen.getDNF();
3195 numberterms+=dflag.size();
3197 Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
3199 for(int j=0; j<dflag.size(); j++) {
3201 output.println(",");
3202 Vector term=dflag.get(j);
3205 for(int k=0; k<term.size(); k++) {
3206 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
3207 FlagDescriptor fd=dfa.getFlag();
3208 boolean negated=dfa.getNegated();
3209 int flagid=1<<((Integer)flags.get(fd)).intValue();
3214 output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
3219 output.println("};\n");
3222 TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
3223 output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
3226 for(int j=0; j<tagel.numTags(); j++) {
3228 output.println(",");
3229 TempDescriptor tmp=tagel.getTemp(j);
3230 if (!slotnumber.containsKey(tmp)) {
3231 Integer slotint=new Integer(current_slot++);
3232 slotnumber.put(tmp,slotint);
3234 int slot=slotnumber.get(tmp).intValue();
3235 output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
3237 numtags = tagel.numTags();
3239 output.println("};");
3241 //store the result into a predicatemember struct
3242 output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
3243 output.println("/*type*/"+typed.getClassDesc().getId()+",");
3244 output.println("/* number of dnf terms */"+numberterms+",");
3245 output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
3246 output.println("/* number of tag */"+numtags+",");
3247 output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
3248 output.println("};\n");
3253 //generate an array that stores the entire predicate
3254 output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
3255 for( int j = 0; j<predicateindex; j++) {
3256 if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
3257 else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
3259 output.println("};\n");
3260 return predicateindex;
3264 void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
3265 generateOptionalHeader(headers);
3267 output.println("#include \"optionalstruct.h\"\n\n");
3268 output.println("#include \"stdlib.h\"\n");
3270 HashSet processedcd = new HashSet();
3272 Enumeration e = safeexecution.keys();
3273 while (e.hasMoreElements()) {
3276 ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
3277 Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp); //will be used several times
3279 //Generate the struct of optionals
3280 Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
3281 numotd = c_otd.size();
3282 if(maxotd<numotd) maxotd = numotd;
3283 if( !c_otd.isEmpty() ) {
3284 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext(); ) {
3285 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
3287 //generate the int arrays for the predicate
3288 Predicate predicate = otd.predicate;
3289 int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
3290 TreeSet<Integer> fsset=new TreeSet<Integer>();
3291 //iterate through possible FSes corresponding to
3292 //the state when entering
3294 for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext(); ) {
3295 FlagState fs = (FlagState)fses.next();
3297 for(Iterator flags = fs.getFlags(); flags.hasNext(); ) {
3298 FlagDescriptor flagd = (FlagDescriptor)flags.next();
3299 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
3302 fsset.add(new Integer(flagid));
3303 //tag information not needed because tag
3304 //changes are not tolerated.
3307 output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
3308 boolean needcomma=false;
3309 for(Iterator<Integer> it=fsset.iterator(); it.hasNext(); ) {
3312 output.println(it.next());
3315 output.println("};\n");
3318 //generate optionaltaskdescriptor that actually
3319 //includes exit fses, predicate and the task
3321 output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
3322 output.println("&task_"+otd.td.getSafeSymbol()+",");
3323 output.println("/*index*/"+otd.getIndex()+",");
3324 output.println("/*number of enter flags*/"+fsset.size()+",");
3325 output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
3326 output.println("/*number of members */"+predicateindex+",");
3327 output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
3328 output.println("};\n");
3332 // if there are no optionals, there is no need to build the rest of the struct
3334 output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
3335 c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
3336 if( !c_otd.isEmpty() ) {
3337 boolean needcomma=false;
3338 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext(); ) {
3339 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
3341 output.println(",");
3343 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
3346 output.println("};\n");
3348 //get all the possible flagstates reachable by an object
3349 Hashtable hashtbtemp = safeexecution.get(cdtemp);
3351 TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
3352 fsts.addAll(hashtbtemp.keySet());
3353 for(Iterator fsit=fsts.iterator(); fsit.hasNext(); ) {
3354 FlagState fs = (FlagState)fsit.next();
3357 //get the set of OptionalTaskDescriptors corresponding
3358 HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
3359 //iterate through the OptionalTaskDescriptors and
3360 //store the pointers to the optionals struct (see on
3361 //top) into an array
3363 output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
3364 for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext(); ) {
3365 OptionalTaskDescriptor mm = mos.next();
3367 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
3369 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
3372 output.println("};\n");
3374 //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
3377 for(Iterator flags = fs.getFlags(); flags.hasNext(); ) {
3378 FlagDescriptor flagd = (FlagDescriptor)flags.next();
3379 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
3383 //process tag information
3386 boolean first = true;
3387 Enumeration tag_enum = fs.getTags();
3388 output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
3389 while(tag_enum.hasMoreElements()) {
3391 TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
3395 output.println(", ");
3396 output.println("/*tagid*/"+state.getTagId(tagd));
3398 output.println("};");
3400 Set<TaskIndex> tiset=sa.getTaskIndex(fs);
3401 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext(); ) {
3402 TaskIndex ti=itti.next();
3406 Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
3408 output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
3409 boolean needcomma=false;
3410 for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext(); ) {
3411 OptionalTaskDescriptor otd=otdit.next();
3415 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
3417 output.println("};");
3419 output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
3420 output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
3421 output.print(ti.getIndex()+", ");
3422 output.print(otdset.size()+", ");
3423 output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
3424 output.println("};");
3427 tiset=sa.getTaskIndex(fs);
3428 boolean needcomma=false;
3430 output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
3431 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext(); ) {
3432 TaskIndex ti=itti.next();
3433 if (ti.isRuntime()) {
3440 output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
3442 output.println("};\n");
3444 //Store the result in fsanalysiswrapper
3446 output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
3447 output.println("/*flag*/"+flagid+",");
3448 output.println("/* number of tags*/"+tagcounter+",");
3449 output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
3450 output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
3451 output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
3452 output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
3453 output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
3454 output.println("};\n");
3458 //Build the array of fsanalysiswrappers
3459 output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
3460 boolean needcomma=false;
3461 for(int i = 0; i<fscounter; i++) {
3462 if (needcomma) output.print(",");
3463 output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
3466 output.println("};");
3468 //Build the classanalysiswrapper referring to the previous array
3469 output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
3470 output.println("/*type*/"+cdtemp.getId()+",");
3471 output.println("/*numotd*/"+numotd+",");
3472 output.println("otdarray"+cdtemp.getSafeSymbol()+",");
3473 output.println("/* number of fsanalysiswrappers */"+fscounter+",");
3474 output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
3475 processedcd.add(cdtemp);
3478 //build an array containing every classes for which code has been build
3479 output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
3480 for(int i=0; i<state.numClasses(); i++) {
3481 ClassDescriptor cn=cdarray[i];
3484 if ((cn != null) && (processedcd.contains(cn)))
3485 output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
3487 output.print("NULL");
3489 output.println("};");
3491 output.println("#define MAXOTD "+maxotd);
3492 headers.println("#endif");
3495 public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
3496 Relation r=new Relation();
3497 for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext(); ) {
3498 OptionalTaskDescriptor otd=otdit.next();
3499 TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
3503 LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
3504 for(Iterator it=r.keySet().iterator(); it.hasNext(); ) {
3505 Set s=r.get(it.next());
3506 for(Iterator it2=s.iterator(); it2.hasNext(); ) {
3507 OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
3515 // override these methods in a subclass of BuildCode
3516 // to generate code for additional systems
3517 protected void printExtraArrayFields(PrintWriter outclassdefs) {
3519 protected void outputTransCode(PrintWriter output) {
3521 protected void buildCodeSetup() {
3523 protected void generateSizeArrayExtensions(PrintWriter outclassdefs) {
3525 protected void additionalIncludesMethodsHeader(PrintWriter outmethodheader) {
3527 protected void preCodeGenInitialization() {
3529 protected void postCodeGenCleanUp() {
3531 protected void additionalCodeGen(PrintWriter outmethodheader,
3532 PrintWriter outstructs,
3533 PrintWriter outmethod) {
3535 protected void additionalCodeAtTopOfMain(PrintWriter outmethod) {
3537 protected void additionalCodeAtBottomOfMain(PrintWriter outmethod) {
3539 protected void additionalIncludesMethodsImplementation(PrintWriter outmethod) {
3541 protected void additionalIncludesStructsHeader(PrintWriter outstructs) {
3543 protected void additionalClassObjectFields(PrintWriter outclassdefs) {
3545 protected void additionalCodeAtTopMethodsImplementation(PrintWriter outmethod) {
3547 protected void additionalCodeAtTopFlatMethodBody(PrintWriter output, FlatMethod fm) {
3549 protected void additionalCodePreNode(FlatMethod fm, FlatNode fn, PrintWriter output) {
3551 protected void additionalCodePostNode(FlatMethod fm, FlatNode fn, PrintWriter output) {
3554 private void printSourceLineNumber(FlatMethod fm, FlatNode fn, PrintWriter output) {
3555 // we do not print out line number if no one explicitly set the number
3556 if(fn.getNumLine()!=-1){
3558 int lineNum=fn.getNumLine();
3560 // do not generate the line number if it is same as the previous one
3561 boolean needtoprint;
3562 if(fn.prev.size()==0){
3568 for(int i=0;i<fn.prev.size();i++){
3569 int prevLineNum=((FlatNode)fn.prev.get(i)).getNumLine();
3570 if(prevLineNum!=lineNum){
3576 output.println("// "+fm.getMethod().getClassDesc().getSourceFileName()+":"+fn.getNumLine());